What you will build
blog-coding-tutorials/c07-vlmtinyvlm: a working vision-language model. A pretrained SigLIP encoder and a pretrained SmolLM2 are joined by a projector you write, with your own image processor, sequence builder, labels, masks, tiling, generation and save_pretrained.
- Theory first
- Time
- About 3 hours, plus the training run in step 13
- Hardware
- A CPU is enough. Every CPU timing came from an AMD EPYC 7R13 with 8 threads. One forward benchmark also ran once on an NVIDIA H100, and step 9 shows it. Training and every other number are CPU only.
- You need
- Python 3.10+, PyTorch 2.x, transformers 5.x, and about 1 GB for the two checkpoints
- Package
tinyvlm
Final repo tree c07-vlm/
c07-vlm/
├── README.md
├── conftest.py
├── tinyvlm/
│ ├── image_processing.py # steps 1, 9: picture to crops to tensor
│ ├── projector.py # step 3: Linear, MLP, pixel shuffle
│ ├── merge.py # step 4: naive loop and masked_scatter
│ ├── chat.py # step 5: ChatML, split into supervised pieces
│ ├── processing.py # steps 5, 6, 10: placeholders, labels, boundaries
│ ├── positions.py # step 7: 1D and 3D position ids
│ ├── masks.py # step 8: attention masks you can print
│ ├── generation.py # step 11: greedy decoding by hand
│ ├── configuration.py # step 12: VLMConfig
│ ├── modeling.py # TinyVLM: forward, generate, set_trainable
│ ├── build.py # joins the two pretrained models
│ ├── data.py # step 13: synthetic shape captions
│ ├── testing.py # a tiny random model for the tests
│ └── device.py
├── scripts/
│ ├── step01_image_processor.py ... step12_save_load.py
│ ├── break_it.py
│ ├── run_all.sh # every step, benchmark and alignment run
│ ├── train_alignment.py
│ └── evaluate_alignment.py
├── benchmarks/
│ ├── bench_processor.py
│ ├── bench_forward.py
│ └── bench_decode.py
├── results/ # saved outputs quoted in this post
└── tests/
├── test_image_processing.py
├── test_projector.py
├── test_merge.py
├── test_processor.py
├── test_masks_positions.py
├── test_model.py
└── test_real_models.py # network: checks against the real checkpoints
The plan
A vision encoder returns vectors. A language model reads token ids. What has to happen between them, tensor by tensor, before a language model can answer a question about a picture?
Less than you might expect. We will not write a new attention layer. We take two pretrained models that have never seen each other: SigLIP for vision and SmolLM2 for language. Then we write the small projector that joins them, plus the bookkeeping around it.
Most of this tutorial is that bookkeeping. It decides how many tokens a picture costs, which token the loss may look at, and which picture each token belongs to. Almost every bug in a VLM lives here, and many of them raise no error.
In the shapes below, B is the number of samples, N is the padded sequence length, and n is the number of crops in the whole batch.
| Tensor | Shape | Meaning |
|---|---|---|
| pixel_values | (n, 3, 224, 224) | Crops, normalised to about [-1, 1]. Not grouped by sample. |
| vision features | (n, 196, 768) | One vector per 16 px patch. |
| after pixel shuffle | (n, 49, 3072) | Each 2 × 2 block of patches, concatenated. |
| image features | (n, 49, 576) | Projected to the language model's size. |
| input_ids | (B, N) | Text ids, plus 49 placeholder ids per crop. |
| inputs_embeds | (B, N, 576) | Token embeddings, with placeholders overwritten by image features. |
| logits | (B, N, 49216) | One distribution over the vocabulary per position. |
Clone the repo once. Every command runs from its root. The first run downloads the two checkpoints.
$ 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]"
$ .venv/bin/python -m pytest c07-vlm -m "not slow and not gpu and not network" -qSaved outputs in this post come from c07-vlm/results/ and were captured on AMD EPYC 7R13, 8 threads unless a label says otherwise. Shapes and tensor values do not depend on the machine. Timings do.
Write the image processor
Goal Turn any picture into exactly the tensor SigLIP expects, and match Hugging Face's processor to the last bit.
SigLIP learned from pictures prepared in one exact way. If we prepare them differently it still returns numbers, and nothing raises. So the first thing we write is the part with no room for error.
The recipe has four parts: convert to RGB, resize to 224 × 224 with bicubic filtering, scale to [0, 1], then subtract the mean and divide by the standard deviation. For SigLIP both are 0.5, so pixels land in [-1, 1].
def to_rgb(image: Image.Image) -> Image.Image:
"""Palette, grayscale and RGBA images have 1, 2 or 4 channels; the encoder expects exactly 3."""
return image if image.mode == "RGB" else image.convert("RGB")
def resize(image: Image.Image, size: int, resample: int = Image.Resampling.BICUBIC) -> Image.Image:
"""Squash to size x size, ignoring the aspect ratio. This is how SigLIP saw images in training."""
return image.resize((size, size), resample=resample)
def normalize(image: Image.Image, mean=SIGLIP_MEAN, std=SIGLIP_STD) -> torch.Tensor:
"""uint8 H x W x 3 picture -> float32 tensor of shape 3 x H x W, (x / 255 - mean) / std."""
array = np.asarray(image, dtype=np.float32) / 255.0 # H x W x 3, values in [0, 1]
array = (array - np.asarray(mean, dtype=np.float32)) / np.asarray(std, dtype=np.float32)
return torch.from_numpy(array.transpose(2, 0, 1).copy()) # channels first, as conv layers expect
Look at the highlighted lines. np.asarray(..., dtype=np.float32) / 255.0 gives floats in shape H × W × 3. The next line applies the mean and standard deviation. The last line moves channels first, because the encoder's patch embedding is a convolution that expects 3 × H × W. The .copy() gives the tensor its own contiguous memory rather than a view with shuffled strides.
The class wraps these in a call that takes a list of pictures and returns one flat batch of crops. For now each picture is one crop. Step 9 changes that.
def __call__(self, images: list[Image.Image]) -> dict:
crops_per_image = [self.crops(image) for image in images]
pixels = [normalize(c, self.image_mean, self.image_std) for crops in crops_per_image for c in crops]
return {
"pixel_values": torch.stack(pixels) if pixels else torch.zeros(0, 3, self.size, self.size),
"num_crops": [len(crops) for crops in crops_per_image],
}
num_crops is the only record of which crop came from which picture.Now run it on a 480 × 360 picture of two red circles, and compare with Hugging Face's own SigLIP processor.
$ .venv/bin/python c07-vlm/scripts/step01_image_processor.pyinput picture (480, 360) RGB
ours pixel_values (1, 3, 224, 224) mean +0.892 std 0.259 min -0.788 max +1.000
hf pixel_values (1, 3, 224, 224) mean +0.892 std 0.259 min -0.788 max +1.000
max |ours - hf| 0.00e+00
first pixel, ours [0.9372549057006836, 0.9372549057006836, 0.9372549057006836]| Tensor | Shape | Meaning |
|---|---|---|
| PIL image | 480 × 360 | Width first in PIL. Mode RGB. |
| after resize | 224 × 224 | The aspect ratio is lost here. Step 9 deals with that. |
| pixel_values | (1, 3, 224, 224) | float32, channels first. |
The first pixel is 0.937. The canvas shade was 247, and (247 / 255 − 0.5) / 0.5 = 0.937, so the arithmetic checks out by hand.
Is this code fast enough? We start naive and measure before changing anything.
$ .venv/bin/python c07-vlm/benchmarks/bench_processor.pydevice AMD EPYC 7R13, 8 threads, best of 20
picture resize ms normalise ms ours ms hf ms
224 x 224 0.01 0.72 0.85 1.07
640 x 480 2.46 0.75 3.26 3.87
1920 x 1080 11.71 0.79 12.75 25.70
tile strategy, 1920 x 1080, 3 crops: 28.46 msAt 1920 × 1080 the resize takes 11.71 ms of the 12.75 ms total. Normalising takes 0.79 ms. So rewriting our NumPy lines would save almost nothing. The bottleneck is the resize, which belongs to Pillow, and our version already takes less time than the Hugging Face one, which needs 25.70 ms. We stop here.
Run the pretrained vision encoder
Goal See what the encoder returns: one 768-number vector for each of 196 patches.
We use the encoder as it comes. The theory post explains what is inside it. Here we only want to see what comes out.
Theory inInside a modern vision encoder # SigLIP's pooling head turns 196 patch tokens into one vector; a VLM wants all 196, so drop it.
vision_config = SiglipVisionConfig.from_pretrained(vision_id)
vision_config.vision_use_head = False
vision = SiglipVisionModel.from_pretrained(vision_id, config=vision_config, dtype=dtype)
SigLIP was trained for contrastive matching, so its last piece pools all patch tokens into a single vector. A VLM needs to read the picture, so we want every patch. Setting vision_use_head = False removes the pooling head and leaves the patch tokens alone.
images = [render(1, "red", "circle", random.Random(0)), render(3, "blue", "square", random.Random(1))]
pixels = TinyVLMImageProcessor()(images)["pixel_values"]
print(stats("pixel_values", pixels))
with torch.no_grad():
out = vision(pixel_values=pixels, output_hidden_states=True)
print(stats("last_hidden_state", out.last_hidden_state))
print(stats("hidden_states[-2]", out.hidden_states[-2]))
print("hidden_states ", len(out.hidden_states), "tensors (patch embeddings + 12 layers)")
$ .venv/bin/python c07-vlm/scripts/step02_vision_features.pyencoder parameters 85,797,120
image 224, patch 16 -> 196 tokens, d_v = 768
pixel_values (2, 3, 224, 224) mean +0.781 std 0.405 min -0.686 max +0.937
last_hidden_state (2, 196, 768) mean -0.005 std 2.025 min -43.102 max +27.042
hidden_states[-2] (2, 196, 768) mean -0.061 std 1.555 min -212.203 max +69.700
hidden_states 13 tensors (patch embeddings + 12 layers)
cosine(corner, other corner) +0.600
mean cosine of all pairs +0.349The count is easy to derive. A 224 px crop with 16 px patches gives a grid of 224 / 16 = 14 per side, so 14 × 14 = 196 tokens. SigLIP has no class token, so all 196 are patches. Each has 768 numbers. In the usual notation this is B × Nv × dv, and here it is (2, 196, 768).
The script also checks that these vectors mean something. Two background corners of a picture have cosine similarity 0.600, against 0.349 for an average pair. Similar patches give similar vectors, which is the property the language model will later rely on.
| Tensor | Shape | Meaning |
|---|---|---|
| pixel_values | (2, 3, 224, 224) | Two crops. |
| last_hidden_state | (2, 196, 768) | The final layer, after a closing LayerNorm. |
| hidden_states | 13 tensors of (2, 196, 768) | Patch embeddings, then one tensor per layer. No closing LayerNorm. |
| sim | (196, 196) | Cosine similarity between the patches of one picture. |
Write the projector
Goal Map vision features to the language model's size, starting with one linear layer, and fold tokens to spend fewer of them.
Vision features have 768 numbers. SmolLM2 expects 576. Something must map one to the other, and this is the only new neural network in the model. We start with the smallest option, then add to it.
class LinearProjector(nn.Module):
"""The smallest possible bridge: one affine map per patch token (LLaVA-1)."""
def __init__(self, d_in: int, d_lm: int):
super().__init__()
self.proj = nn.Linear(d_in, d_lm)
def forward(self, features: torch.Tensor) -> torch.Tensor: # n x N x d_in -> n x N x d_lm
return self.proj(features)
class MLPProjector(nn.Module):
"""Linear -> GELU -> Linear (LLaVA-1.5). The nonlinearity lets it bend the feature space."""
def __init__(self, d_in: int, d_lm: int):
super().__init__()
self.fc1 = nn.Linear(d_in, d_lm)
self.act = nn.GELU()
self.fc2 = nn.Linear(d_lm, d_lm)
def forward(self, features: torch.Tensor) -> torch.Tensor: # n x N x d_in -> n x N x d_lm
return self.fc2(self.act(self.fc1(features)))
Each layer works on the last axis only, so every patch token is mapped on its own. The token count does not change. Let us run both, and compare their output with real SmolLM2 token embeddings.
$ .venv/bin/python c07-vlm/scripts/step03_projector.pyvision features (1, 196, 768) mean -0.009 std 2.013 min -27.980 max +25.404
after pixel shuffle (1, 49, 3072) mean -0.009 std 2.013 min -27.980 max +25.404
Linear(768) (1, 196, 576) mean +0.005 std 1.162 min -5.160 max +5.402
MLP(768) (1, 196, 576) mean -0.011 std 0.452 min -2.022 max +1.884
MLP(3072), the model (1, 49, 576) mean -0.025 std 0.462 min -2.366 max +1.946
real token embeddings (1, 11, 576) mean -0.002 std 0.107 min -0.578 max +0.797
all embedding rows (49152, 576) mean -0.001 std 0.136 min -1.961 max +1.875
parameters
Linear 768 -> 576 442,944
MLP 768 -> 576 775,296
Linear 3072 -> 576 1,770,048
MLP 3072 -> 576 2,102,400
whole model {'vision': 85797120, 'projector': 2102400, 'lm': 134551872, 'trainable': 222451392}The parameter counts can be derived by hand. A linear layer has din × dout weights and dout biases, so 768 × 576 + 576 = 442,944. The MLP adds a second layer of 576 × 576 + 576 = 332,352, for a total of 775,296.
Spend fewer tokens with pixel shuffle
196 tokens per crop is a lot for a small language model. Every token costs attention time and cache memory. The SmolVLM family folds neighbouring patches together before projecting. It does not average them. It concatenates them, so no numbers are lost.
def pixel_shuffle(features: torch.Tensor, factor: int) -> torch.Tensor:
"""Fold each factor x factor block of neighbouring patches into one token (SmolVLM, Idefics3).
n x N x d -> n x (N / factor^2) x (d * factor^2). No information is dropped: the 4 patches of
a 2 x 2 block are concatenated along the channel axis, so the token count shrinks 4x.
"""
if factor == 1:
return features
n, num_tokens, dim = features.shape
side = math.isqrt(num_tokens)
if side * side != num_tokens or side % factor:
raise ValueError(f"{num_tokens} tokens do not form a square grid divisible by {factor}")
x = features.reshape(n, side, side // factor, dim * factor) # merge `factor` columns
x = x.permute(0, 2, 1, 3) # n x (side/f) x side x (d*f)
x = x.reshape(n, side // factor, side // factor, dim * factor * factor) # merge `factor` rows
x = x.permute(0, 2, 1, 3) # back to row-major order of the coarse grid
return x.reshape(n, (side // factor) ** 2, dim * factor * factor)
The output above confirms it: after pixel shuffle has shape (1, 49, 3072) with exactly the same mean, standard deviation and range as the input. The same numbers, in a different arrangement.
| Tensor | Shape | Meaning |
|---|---|---|
| features | (n, 196, 768) | From the encoder. |
| x, first reshape | (n, 14, 7, 1536) | Columns merged in pairs. |
| x, after permute | (n, 7, 14, 1536) | Rows and columns swapped. |
| x, second reshape | (n, 7, 7, 3072) | Rows merged in pairs. |
| x, after permute | (n, 7, 7, 3072) | Back to row-major order. |
| output | (n, 49, 3072) | A flat list of tokens, one per block. |
| projected | (n, 49, 576) | The MLP projector maps 3072 to 576. |
| Projector | Parameters | Image tokens | Sequence | KV cache | Fresh output std |
|---|---|---|---|---|---|
| Linear, no shuffle | 442,944 | 196 | 210 | 9.7 MB | 1.162 |
| MLP, no shuffle | 775,296 | 196 | 210 | 9.7 MB | 0.452 |
| Linear, shuffle 2 | 1,770,048 | 49 | 63 | 2.9 MB | not measured |
| MLP, shuffle 2 (ours) | 2,102,400 | 49 | 63 | 2.9 MB | 0.462 |
Read it as a trade. Shuffle makes the projector about 2.7 times bigger and cuts the language model's sequence and cache by more than 3 times. The projector is the only part we pay for in training, and even at 2.1 million parameters it is under 1% of the model. Cheap tokens are worth a slightly bigger bridge.
Assemble the model
Now we can join the parts. A language model needs one more thing first: a token for the picture.
tokenizer = AutoTokenizer.from_pretrained(lm_id)
tokenizer.add_tokens([IMAGE_TOKEN], special_tokens=True) # one new id for the placeholder
# SigLIP's pooling head turns 196 patch tokens into one vector; a VLM wants all 196, so drop it.
vision_config = SiglipVisionConfig.from_pretrained(vision_id)
vision_config.vision_use_head = False
vision = SiglipVisionModel.from_pretrained(vision_id, config=vision_config, dtype=dtype)
lm = LlamaForCausalLM.from_pretrained(lm_id, dtype=dtype)
# A multiple of 64 keeps the embedding matmul shapes friendly; the extra rows are never used.
lm.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=64)
config = VLMConfig(
vision_config=vision.config,
text_config=lm.config,
image_token_id=tokenizer.convert_tokens_to_ids(IMAGE_TOKEN),
projector_type=projector_type,
pixel_shuffle_factor=pixel_shuffle_factor,
vision_feature_layer=vision_feature_layer,
)
with torch.device("meta"): # a skeleton with no memory and no random-init cost ...
model = TinyVLM(config)
model.vision, model.lm = vision, lm # ... filled with the two pretrained halves
model.projector = build_projector(projector_type, config.projector_in_dim, config.text_config.hidden_size).to(dtype)
Three lines matter most:
add_tokensgives<image>its own id, 49152. It must be special, or the tokenizer could split it.resize_token_embeddings(..., pad_to_multiple_of=64)grows the embedding table from 49152 rows to 49216. That is why logits have 49216 columns. Only one new row is used.with torch.device("meta")builds a skeleton with no memory, so we do not spend time randomly initialising weights we are about to replace.
Put image features into the sequence
Goal Replace placeholder rows with image features, first with a loop and then with one call that gives the same result.
SmolLM2 does not need a new input path. Like most Hugging Face language models, it accepts inputs_embeds in place of input_ids. So the plan is short: embed the tokens as usual, then overwrite the placeholder rows with image features.
The reference version does this one position at a time, so nobody can misread it. It starts with a check, because a count mismatch is the most common VLM bug.
def check_counts(input_ids: torch.Tensor, image_features: torch.Tensor, image_token_id: int) -> torch.Tensor:
"""Return the placeholder mask (B x N, bool) after checking it matches the number of features."""
mask = input_ids == image_token_id
n_slots, n_features = int(mask.sum()), image_features.shape[0] * image_features.shape[1]
if n_slots != n_features:
raise ValueError(
f"{n_slots} <image> placeholders but {n_features} image feature vectors "
f"({image_features.shape[0]} crops x {image_features.shape[1]} tokens). "
"The processor and the model disagree about tokens per crop."
)
return mask
def merge_naive(
text_embeds: torch.Tensor, input_ids: torch.Tensor, image_features: torch.Tensor, image_token_id: int
) -> torch.Tensor:
"""Reference version: walk the sequence and copy one feature vector per placeholder."""
check_counts(input_ids, image_features, image_token_id)
out = text_embeds.clone()
flat = image_features.reshape(-1, image_features.shape[-1]) # (n * N_img) x d_lm, in order
k = 0
for b in range(input_ids.shape[0]):
for t in range(input_ids.shape[1]):
if input_ids[b, t] == image_token_id:
out[b, t] = flat[k]
k += 1
return out
k walks the flat features as t walks the sequence.Now the fast version. masked_scatter copies values from a source into the true positions of a mask, in reading order. That is the same order as our loop.
def merge_masked_scatter(
text_embeds: torch.Tensor, input_ids: torch.Tensor, image_features: torch.Tensor, image_token_id: int
) -> torch.Tensor:
"""Fast version, same result: one masked_scatter fills the masked rows in row-major order."""
mask = check_counts(input_ids, image_features, image_token_id)
mask = mask.unsqueeze(-1).expand_as(text_embeds) # B x N x d_lm
return text_embeds.masked_scatter(mask, image_features.to(text_embeds.dtype))
The model wraps this into two methods.
def get_image_features(self, pixel_values: torch.Tensor) -> torch.Tensor:
"""n x 3 x H x W -> n x N_img x d_lm."""
layer = self.config.vision_feature_layer
out = self.vision(pixel_values=pixel_values.to(self.vision.dtype), output_hidden_states=layer != -1)
features = out.last_hidden_state if layer == -1 else out.hidden_states[layer] # n x N_v x d_v
features = pixel_shuffle(features, self.config.pixel_shuffle_factor)
return self.projector(features)
def embed(self, input_ids: torch.Tensor, pixel_values: torch.Tensor | None = None) -> torch.Tensor:
"""B x N ids (+ crops) -> B x N x d_lm input embeddings with image features scattered in."""
embeds = self.get_input_embeddings()(input_ids)
if pixel_values is None or pixel_values.shape[0] == 0:
# Otherwise the model would read one meaningless embedding N_img times and never complain.
if (input_ids == self.config.image_token_id).any():
raise ValueError("input_ids contain <image> placeholders, but no pixel_values were given")
return embeds
features = self.get_image_features(pixel_values)
return merge_masked_scatter(embeds, input_ids, features, self.config.image_token_id)
$ .venv/bin/python c07-vlm/scripts/step04_scatter.pyprompt string '<|im_start|>user\n<image>What do you see?<|im_end|>\n<|im_start|>assistant\n'
input_ids (1, 63) placeholders: 49
placeholder slots 3 to 51
text_embeds (1, 63, 576)
image features (1, 49, 576)
merged (1, 63, 576)
slot 3 equals features[0, 0] True
slot 51 equals features[0, 48] True
text rows untouched True
merge_naive 3.764 ms per batch, best of 20 (AMD EPYC 7R13, 8 threads)
merge_masked_scatter 0.461 ms per batch, best of 20 (AMD EPYC 7R13, 8 threads)| Tensor | Shape | Meaning |
|---|---|---|
| input_ids | (1, 63) | 14 text ids and 49 placeholder ids. |
| mask | (1, 63) | True at positions 3 to 51. |
| text_embeds | (1, 63, 576) | Placeholder rows hold a meaningless vector for now. |
| features | (1, 49, 576) | From the projector. |
| merged | (1, 63, 576) | Row 3 equals features[0, 0]. Row 51 equals features[0, 48]. |
Build the multimodal sequence
Goal Turn a conversation and a picture into token ids, with one seat per image feature.
The placeholders have to come from somewhere. The sequence builder turns a conversation and a picture into token ids, with the right number of seats. The layout we want is:
[BOS] user image tokens question assistantSmolLM2-Instruct uses ChatML. Its tokenizer's BOS token is <|im_start|> itself, so every ChatML sequence already starts with BOS, and we add nothing in front of it. We render the conversation in pieces, and each piece knows if it will be supervised. Step 6 needs that.
def chat_segments(messages: list[dict], add_generation_prompt: bool = False) -> list[tuple[str, bool]]:
"""Return (text, supervised) pieces whose concatenation is the full ChatML string.
Only the assistant's reply and its closing <|im_end|> are supervised: the model must learn to
answer and to stop. Role headers, the user's words and the image are context, not targets.
"""
segments: list[tuple[str, bool]] = []
for message in messages:
segments.append((f"{IM_START}{message['role']}\n", False))
body = render_content(message["content"])
if message["role"] == "assistant":
segments.append((body + IM_END, True))
segments.append(("\n", False))
else:
segments.append((body + IM_END + "\n", False))
if add_generation_prompt:
segments.append((f"{IM_START}assistant\n", False))
return segments
A <image> marker in the text then has to become one placeholder per feature vector. This is the rule that joins the processor to the model.
def tokens_for_image(self, num_crops: int) -> int:
return num_crops * self.image_seq_len
def _expand(self, text: str, crops: Iterator[int]) -> str:
"""Replace each <image> marker by the right number of placeholders (consumes `crops`)."""
pieces = text.split(self.image_token)
out = [pieces[0]]
for piece in pieces[1:]:
num_crops = next(crops, None)
if num_crops is None:
raise ValueError("more <image> markers than pictures in the messages")
out.append(self.image_token * self.tokens_for_image(num_crops))
out.append(piece)
return "".join(out)
def _ids(self, text: str) -> list[int]:
return self.tokenizer(text, add_special_tokens=False)["input_ids"]
tokens_for_image is num_crops × image_seq_len. add_special_tokens=False stops the tokenizer adding anything we did not ask for.$ .venv/bin/python c07-vlm/scripts/step05_sequence.py'<|im_start|>user\n<image>What do you see?<|im_end|>\n<|im_start|>assistant\nTwo red circles.<|im_end|>\n'
pos id label token
0 1 -100 '<|im_start|>'
1 4093 -100 'user'
2 198 -100 'Ċ'
3 49152 -100 <image> x 49
52 1780 -100 'What'
53 536 -100 'Ġdo'
54 346 -100 'Ġyou'
55 963 -100 'Ġsee'
56 47 -100 '?'
57 2 -100 '<|im_end|>'
58 198 -100 'Ċ'
59 1 -100 '<|im_start|>'
60 520 -100 'ass'
61 9531 -100 'istant'
62 198 -100 'Ċ'
63 10345 10345 'Two'
64 2382 2382 'Ġred'
65 11144 11144 'Ġcircles'
66 30 30 '.'
67 2 2 '<|im_end|>'
68 198 -100 'Ċ'
sequence length 69 | supervised 5 | ignored 64The text costs 20 tokens. The picture costs 49. Note how the model's tokenizer really behaves: assistant is two tokens, ass and istant, and Ġ marks a leading space. You would not guess this, so we print it.
Choose what the loss sees
Goal Supervise only the reply and its stop token, and see what happens otherwise.
Language models learn by predicting the next token. In a VLM we do not want a loss on every position. The model should not be asked to predict <image>, or the question. It should be asked to write the answer, and to stop.
The rule fits in one line. Any position outside a supervised piece gets label −100, the value cross-entropy ignores.
def build_example(self, messages: list[dict], images: list[Image.Image] | None = None) -> dict:
"""One training example. Labels copy the ids of supervised pieces and are -100 elsewhere."""
vision = self.image_processor(images or [])
crops = iter(vision["num_crops"])
input_ids: list[int] = []
labels: list[int] = []
for piece, supervised in chat_segments(messages):
ids = self._ids(self._expand(piece, crops))
input_ids += ids
labels += [i if supervised and i != self.image_token_id else IGNORE_INDEX for i in ids]
if next(crops, None) is not None:
raise ValueError("more pictures than <image> markers in the messages")
return {"input_ids": input_ids, "labels": labels, **vision}
The table in step 5 shows the result: 69 positions, of which 5 are supervised and 64 are ignored. Try other choices in the figure.
The readout on the right shows a detail that catches people out. The label at position t is scored against the logits at position t − 1. The first target, Two at position 63, is predicted from position 62, the newline after assistant. Hugging Face shifts the labels inside the model, so you pass them unshifted.
| Tensor | Shape | Meaning |
|---|---|---|
| input_ids | (B, N) | Padded with the pad id. |
| attention_mask | (B, N) | 1 for real tokens, 0 for padding. |
| labels | (B, N) | −100 everywhere except the reply and its stop token, and always on padding. |
| image_index | (B, N) | −1 for text, k for tokens of picture k. Used in step 10. |
Give every token a position
Goal Number a sequence that mixes pictures, text and padding, and see why a picture pushes text away.
Every token needs a position for RoPE. The simplest answer treats an image token like any other token: it takes the next integer. SmolLM2, LLaVA and SmolVLM all work this way.
Theory inPosition bookkeeping in VLM pipelinesdef position_ids_1d(attention_mask: torch.Tensor) -> torch.Tensor:
"""B x N mask -> B x N positions that count only real tokens.
With left padding the first real token must still be position 0; padding slots get 1 (any value
works, they are masked out) to match Hugging Face's convention.
"""
positions = attention_mask.long().cumsum(-1) - 1
return positions.masked_fill(attention_mask == 0, 1)
Why not just use 0, 1, 2 up to N? Because of left padding, which generation needs. A left-padded sample starts with a pad, and its first real token must still get position 0. cumsum handles this. We print it on a tiny model, with 4 image tokens per crop and one token per character, so the whole tensor fits on screen.
$ .venv/bin/python c07-vlm/scripts/step07_positions_masks.pyinput_ids
tensor([[ 3, 3, 3, 3, 21, 22],
[ 0, 3, 3, 3, 3, 14]])
attention_mask
tensor([[1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1]])
image_index
tensor([[ 0, 0, 0, 0, -1, -1],
[-1, 0, 0, 0, 0, -1]])
position_ids (1D)
tensor([[0, 1, 2, 3, 4, 5],
[1, 0, 1, 2, 3, 4]])Look at sample 1. Its attention mask starts with a 0, and its positions read 1, 0, 1, 2, 3, 4. The first value belongs to the pad slot. The real tokens start from 0.
There is a cost to 1D positions. A 49-token picture pushes the following text 49 places further away. Qwen2-VL takes a different route, M-RoPE, where each token gets three coordinates and a picture only advances the text by its longest side.
def position_ids_3d(image_index: torch.Tensor, grid: tuple[int, int]) -> torch.Tensor:
"""N image-index row (-1 = text) -> 3 x N (t, h, w) positions for crops laid out on a `grid` (rows, cols).
Single sample, no padding: this is a teaching version of Qwen2-VL's get_rope_index.
"""
rows, cols = grid
pos = torch.zeros(3, image_index.shape[0], dtype=torch.long)
next_pos, t = 0, 0
while t < image_index.shape[0]:
if image_index[t] < 0:
pos[:, t] = next_pos
next_pos += 1
t += 1
continue
cells = torch.arange(rows * cols)
span = slice(t, t + rows * cols)
pos[0, span] = next_pos # one temporal index for the whole picture
pos[1, span] = next_pos + cells // cols # row
pos[2, span] = next_pos + cells % cols # column
next_pos += max(rows, cols) # text resumes after the largest spatial extent
t += rows * cols
return pos
3D positions for sample 0 (t, h, w), image grid 2 x 2
tensor([[0, 0, 0, 0, 2, 3],
[0, 0, 1, 1, 2, 3],
[0, 1, 0, 1, 2, 3]])Rows are t, h and w. The four image tokens share t = 0 and spread over a 2 × 2 grid. The text then resumes at 2, not 4. At our real size, 7 × 7, text would resume after 7 positions in place of 49.
Build the attention mask
Goal Build the causal and padding mask as a tensor, then prove it equals the one inside Hugging Face.
Two questions decide whether query position i may read key position j. Is j in the past? Is j a real token? We build that as a tensor, so we can print it and test it.
def build_attention_mask(
attention_mask: torch.Tensor, image_index: torch.Tensor | None = None, bidirectional_images: bool = False
) -> torch.Tensor:
n = attention_mask.shape[-1]
causal = torch.ones(n, n, dtype=torch.bool, device=attention_mask.device).tril()
allowed = causal[None] & attention_mask.bool()[:, None, :] # B x N x N: key must be real
if bidirectional_images and image_index is not None:
same_image = (image_index[:, :, None] == image_index[:, None, :]) & (image_index[:, :, None] >= 0)
allowed = allowed | same_image
return allowed[:, None] # B x 1 x N x N
The broadcasting is worth reading slowly. causal[None] is 1 × N × N. attention_mask.bool()[:, None, :] is B × 1 × N, so it masks out padded keys in every query row. The final [:, None] adds a head axis, so the mask broadcasts over all heads.
sample 1, causal + padding (rows are queries, columns are keys)
pad ......
img .#....
img .##...
img .###..
img .####.
txt .#####
sample 1, with the image block bidirectional
pad ......
img .####.
img .####.
img .####.
img .####.
txt .###### means may attend. The default is an ordinary triangle. Image tokens are causal just like text. The first image token sees nothing of the picture but itself, and only the last one sees all of it. The second block opens up the picture, so every image token can see every other one. PaliGemma goes further, with full attention over the picture and the question together. Change the sizes and see how the tensor reacts.
In practice TinyVLM.forward passes the 2D attention_mask straight to the language model, which builds this same mask internally. So why build it ourselves? So we can see it, and so a test can tie the two together.
def test_explicit_4d_mask_matches_hf_default():
model, _ = tiny_vlm()
ids = torch.randint(4, 100, (2, 6))
attn = torch.tensor([[1] * 6, [0, 0, 1, 1, 1, 1]])
pos = position_ids_1d(attn)
ref = model.lm(input_ids=ids, attention_mask=attn, position_ids=pos).logits
ours = model.lm(input_ids=ids, attention_mask=to_additive(build_attention_mask(attn)), position_ids=pos).logits
real = attn.bool()
assert torch.allclose(ref[real], ours[real], atol=1e-5)
Handle pictures of any size
Goal Support fixed resize, aspect-ratio padding and tiling, with token counts that change per picture.
So far every picture becomes one 224 × 224 crop. Real pictures are not square. There are three common answers, and each gives a different trade. We write all three behind one method, so the rest of the code does not care.
def crops(self, image: Image.Image) -> list[Image.Image]:
"""The resolution strategy: one picture in, a list of size x size crops out."""
image = to_rgb(image)
if self.strategy == "pad":
image = pad_to_square(image, self.image_mean)
if self.strategy == "tile":
return tile(image, self.size, self.max_tiles, self.use_thumbnail)
return [resize(image, self.size, self.resample)]
A fixed resize squashes the picture. Padding keeps the shape by centring it on a square filled with the mean colour.
def pad_to_square(image: Image.Image, mean=SIGLIP_MEAN) -> Image.Image:
"""Centre the picture on a square canvas filled with the mean colour.
After normalisation the padding is close to 0, so it carries almost no signal. It is not exactly 0:
a mean of 0.5 is 127.5 in 8 bits, which rounds to 128 and normalises to 0.0039.
"""
width, height = image.size
side = max(width, height)
fill = tuple(round(m * 255) for m in mean)
canvas = Image.new("RGB", (side, side), fill)
canvas.paste(image, ((side - width) // 2, (side - height) // 2))
return canvas
Tiling keeps local detail. It picks a grid close to the picture's shape, cuts the picture into crops, then adds a thumbnail so the whole scene is still visible in one view. The grid rule is the one in the InternVL model card.
def select_grid(width: int, height: int, tile_size: int = 224, max_tiles: int = 6) -> tuple[int, int]:
"""Pick the tile grid whose aspect ratio is closest to the picture's (InternVL's rule).
On a tie (2:1 and 4:2 are the same ratio) take the bigger grid, but only if the picture has
enough pixels to fill more than half of it. Small pictures should not be blown up into many tiles.
"""
aspect = width / height
best, best_diff = (1, 1), math.inf
for cols, rows in candidate_grids(max_tiles):
diff = abs(aspect - cols / rows)
if diff < best_diff:
best, best_diff = (cols, rows), diff
elif diff == best_diff and width * height > 0.5 * tile_size * tile_size * cols * rows:
best = (cols, rows)
return best
def tile(image: Image.Image, tile_size: int = 224, max_tiles: int = 6, thumbnail: bool = True) -> list[Image.Image]:
"""Resize to the chosen grid, cut it into tile_size squares (row-major), add a global thumbnail.
The tiles keep local detail; the thumbnail keeps the whole scene in one view.
"""
cols, rows = select_grid(*image.size, tile_size=tile_size, max_tiles=max_tiles)
grid = image.resize((cols * tile_size, rows * tile_size), resample=Image.Resampling.BICUBIC)
tiles = [
grid.crop((c * tile_size, r * tile_size, (c + 1) * tile_size, (r + 1) * tile_size))
for r in range(rows)
for c in range(cols)
]
if thumbnail and len(tiles) > 1:
tiles.append(resize(image, tile_size))
return tiles
Each crop then becomes image_seq_len tokens. That is the dynamic token length: _expand from step 5 writes num_crops × 49 placeholders, so every picture can have a different count. Try it.
select_grid. KV cache is the prefill size for 14 text tokens plus the image tokens, at 46,080 bytes per position.The script prints the same thing for seven sizes, using real crops and no model.
$ .venv/bin/python c07-vlm/scripts/step09_variable_resolution.py picture | resize | pad | tile grid crops s=1 s=2
224 x 224 | 49 | 49 | 1 x 1 1 196 49
640 x 480 | 49 | 49 | 3 x 2 7 1372 343
1000 x 300 | 49 | 49 | 3 x 1 4 784 196
300 x 1000 | 49 | 49 | 1 x 3 4 784 196
1344 x 896 | 49 | 49 | 3 x 2 7 1372 343
2048 x 1536 | 49 | 49 | 3 x 2 7 1372 343
100 x 50 | 49 | 49 | 2 x 1 3 588 147
resize and pad columns use pixel shuffle s = 2 (49 tokens per crop); s = 1 gives 196.
resize (224, 224) aspect ratio changes by 3.33 x
pad (224, 224) content fills 30 % of the crop height| Strategy | Crops | Image tokens | What it costs in quality | When to use it |
|---|---|---|---|---|
| Fixed resize | 1 | 49 | Shapes stretch by 3.33 times. | Near-square pictures, and whenever the encoder was trained this way. |
| Aspect-ratio padding | 1 | 49 | Shape is kept. Content fills only 30% of the crop height. | When shape matters and the budget is tight. |
| Tiling with a thumbnail | 4 | 196 | Keeps detail. Objects can be cut across a tile edge. | Documents and long pictures, where small detail carries the answer. |
Now we can ask what a picture really costs. The benchmark times one forward pass and measures the KV cache that the language model keeps.
$ .venv/bin/python c07-vlm/benchmarks/bench_forward.py --device cpudevice AMD EPYC 7R13, 8 threads, float32, one sample, 14 text tokens, best of 5
crops s img tok seq encode ms lm ms total ms KV cache MB GPU peak MB
1 2 49 63 86 86 172 2.9 -
7 2 343 357 438 267 705 16.5 -
1 1 196 210 97 190 288 9.7 -
7 1 1372 1386 414 955 1369 63.9 -The cache column follows a formula. SmolLM2-135M has 30 layers, keys and values, 3 KV heads of 64 dimensions, and 4 bytes per float32: 30 × 2 × 3 × 64 × 4 = 46,080 bytes per position. Times 63 gives 2.90 MB. Times 1386 gives 63.87 MB. Both match the measured column exactly.
The same benchmark ran once on a GPU. It is a single run, so read it as one measurement.
$ .venv/bin/python c07-vlm/benchmarks/bench_forward.py --device cudadevice NVIDIA H100 80GB HBM3, torch 2.15.0+cu132, CUDA 13.2, float32, one sample, 14 text tokens, best of 5
crops s img tok seq encode ms lm ms total ms KV cache MB GPU peak MB
1 2 49 63 6 26 33 2.9 980
7 2 343 357 8 27 35 16.5 1131
1 1 196 210 6 27 33 9.7 1083
7 1 1372 1386 8 28 36 63.9 1636On the H100 every row takes 33 to 36 ms, whatever the token count. That suggests one sample leaves the GPU mostly idle, so the extra tokens cost almost nothing in time. We did not profile it. They still cost memory: peak memory grows from 980 MB to 1636 MB, and the cache column is the same as on the CPU. So on a GPU at batch size 1, token count shows up in memory first. Larger batches have not been measured.
Theory inWhat one picture costsAccept several pictures
Goal Pass two pictures in one prompt and record which token belongs to which picture.
Nothing new is needed for two pictures. The processor already writes placeholders per marker, and masked_scatter already fills them in order. What we add is a record of which token belongs to which picture.
messages = [{"role": "user", "content": [
{"type": "text", "text": "Image 1: "}, {"type": "image"},
{"type": "text", "text": "\nImage 2: "}, {"type": "image"},
{"type": "text", "text": "\nWhich one has more shapes?"},
]}]
def _image_index(self, ids: list[int], num_crops: list[int]) -> list[int]:
"""Boundary tracking: label each placeholder with the picture it belongs to."""
owners = [k for k, c in enumerate(num_crops) for _ in range(self.tokens_for_image(c))]
slots = [t for t, i in enumerate(ids) if i == self.image_token_id]
if len(slots) != len(owners):
raise ValueError(f"{len(slots)} <image> placeholders, but the pictures need {len(owners)}")
index = [-1] * len(ids)
for t, k in zip(slots, owners):
index[t] = k
return index
owners says which picture owns each seat, in order. slots says where the seats are.$ .venv/bin/python c07-vlm/scripts/step10_multi_image.pyinput_ids (1, 125) | pixel_values (2, 3, 224, 224) | num_crops [1, 1]
image 0: tokens 8 to 56 (49 tokens)
image 1: tokens 63 to 111 (49 tokens)
text between images: '\nImage 2: '
features (2, 49, 576) | embeds (1, 125, 576)
image 1 slot holds features[1, 0]: True| Tensor | Shape | Meaning |
|---|---|---|
| pixel_values | (2, 3, 224, 224) | Two crops, picture 0 first. |
| num_crops | [1, 1] | Crops per picture, in marker order. |
| input_ids | (1, 125) | 98 placeholder ids and 27 text ids. |
| image_index | (1, 125) | −1 for text, 0 for positions 8 to 56, 1 for positions 63 to 111. |
| features | (2, 49, 576) | Crop by crop. |
| inputs_embeds | (1, 125, 576) | Position 63 holds features[1, 0]. |
Generate text
Goal Reuse the language model's decoder, and write it by hand once to see what it does.
We do not need a new decoder. The language model already has one, so we build the multimodal embeddings once and hand them over.
@torch.no_grad()
def generate(
self,
input_ids: torch.Tensor,
pixel_values: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
**generate_kwargs,
) -> torch.Tensor:
"""Build the multimodal embeddings once, then reuse the language model's own decoding loop.
Returns only the new tokens, B x T_new (Hugging Face does this when given inputs_embeds).
"""
inputs_embeds = self.embed(input_ids, pixel_values)
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
return self.lm.generate(inputs_embeds=inputs_embeds, attention_mask=attention_mask, **generate_kwargs)
lm.generate does the rest.One line is easy to trust and hard to see inside, so we write the same thing by hand as a reference.
def greedy_generate(
model: TinyVLM,
input_ids: torch.Tensor,
pixel_values: torch.Tensor | None,
attention_mask: torch.Tensor,
max_new_tokens: int = 20,
eos_token_id: int | None = None,
use_cache: bool = True,
) -> torch.Tensor:
"""Returns B x T_new new token ids. use_cache=False recomputes the full sequence every step (slow reference)."""
embeds = model.embed(input_ids, pixel_values) # B x N x d_lm, image features already inside
mask = attention_mask.clone()
cache = DynamicCache(config=model.lm.config) if use_cache else None
new_tokens = []
step_input, positions = embeds, position_ids_1d(mask)
finished = torch.zeros(input_ids.shape[0], dtype=torch.bool, device=input_ids.device)
for _ in range(max_new_tokens):
out = model.lm(
inputs_embeds=step_input, attention_mask=mask, position_ids=positions, past_key_values=cache, use_cache=use_cache
)
next_token = out.logits[:, -1].argmax(-1) # B
if eos_token_id is not None:
next_token = next_token.masked_fill(finished, eos_token_id)
finished |= next_token == eos_token_id
new_tokens.append(next_token)
next_embed = model.get_input_embeddings()(next_token)[:, None] # B x 1 x d_lm
mask = torch.cat([mask, mask.new_ones(mask.shape[0], 1)], dim=1)
if use_cache:
step_input, positions = next_embed, position_ids_1d(mask)[:, -1:]
else:
embeds = torch.cat([embeds, next_embed], dim=1)
step_input, positions = embeds, position_ids_1d(mask)
if eos_token_id is not None and finished.all():
break
return torch.stack(new_tokens, dim=1)
Follow step_input. On the first pass it holds all the embeddings, images included, and the language model stores keys and values for each position. After that it holds a single row. pixel_values is never used again. The encoder runs once per generated answer.
$ .venv/bin/python c07-vlm/scripts/step11_generate.pyprompt tokens 63 (untrained projector)
output: 'I see that you have a question about the "What is the difference between a "variable" and'
manual == lm.generate: True | cached == recomputed: True
20 new tokens, best of 5, AMD EPYC 7R13, 8 threads
lm.generate 1.17 s 17.1 tokens/s
manual with cache 1.24 s 16.1 tokens/s
manual no cache 2.42 s 8.2 tokens/s| Tensor | Shape | Meaning |
|---|---|---|
| embeds | (1, 63, 576) | First pass. Image features already inside. |
| out.logits | (1, 63, 49216) then (1, 1, 49216) | We only ever read [:, -1]. |
| next_token | (1,) | Argmax of the last row. |
| next_embed | (1, 1, 576) | The new token's embedding. |
| positions | (1, 1) | The next integer, from the last of position_ids_1d. |
| result | (1, 20) | New tokens only. |
The answer is confident and useless: I see that you have a question about the "What is the difference between a "variable" and. That is correct behaviour. The projector is random, so the language model gets noise where the picture should be, and it falls back on what it knows. The pipeline works. It has not learned anything yet. Step 13 fixes that.
Dropping the cache on this short prompt makes 20 tokens 2.0 times slower: 2.42 s against 1.24 s. Does that factor stay the same for bigger pictures? We ran the same comparison across the prompt lengths from step 9. Its first row is also a 63-token prompt, timed with the same function, yet it gives a factor of 1.4 where the script above gives 2.0. The benchmark takes the best of 3 runs, the script the best of 5, and the machine had other work on it. So read the factors as rough, and look at how they grow down the table.
$ .venv/bin/python c07-vlm/benchmarks/bench_decode.pydevice AMD EPYC 7R13, 8 threads, float32, 20 new tokens, best of 3
crops s prompt cached s recomputed s ratio
1 2 63 1.49 2.13 1.4
7 2 357 2.07 6.58 3.2
1 1 210 1.41 4.01 2.8
7 1 1386 2.79 21.90 7.9Save and load it like any Hugging Face model
Goal Add a config, a model class and a processor that survive a round trip with identical logits.
The next tutorial trains this model, and it expects the usual Hugging Face calls. Three pieces make that work: a config, a PreTrainedModel subclass, and a registration.
class VLMConfig(PretrainedConfig):
"""Everything needed to rebuild a TinyVLM with random weights; saved as config.json.
Fields beyond the two sub-configs:
image_token_id id of the <image> placeholder in the tokenizer
projector_type "linear" or "mlp"
pixel_shuffle_factor 1 keeps all N_v patch tokens; 2 folds 2 x 2 blocks, N_v / 4 tokens
vision_feature_layer which encoder layer to read: -1 is the last, -2 the one before it
"""
model_type = "tinyvlm"
sub_configs = {"vision_config": SiglipVisionConfig, "text_config": LlamaConfig}
def __init__(
self,
vision_config: SiglipVisionConfig | dict | None = None,
text_config: LlamaConfig | dict | None = None,
image_token_id: int = 0,
projector_type: str = "mlp",
pixel_shuffle_factor: int = 1,
vision_feature_layer: int = -1,
**kwargs,
):
# from_pretrained hands us plain dicts read from config.json; rebuild the typed configs.
if isinstance(vision_config, dict):
vision_config = SiglipVisionConfig(**vision_config)
if isinstance(text_config, dict):
text_config = LlamaConfig(**text_config)
self.vision_config = vision_config if vision_config is not None else SiglipVisionConfig()
self.text_config = text_config if text_config is not None else LlamaConfig()
self.image_token_id = image_token_id
self.projector_type = projector_type
self.pixel_shuffle_factor = pixel_shuffle_factor
self.vision_feature_layer = vision_feature_layer
kwargs.setdefault("tie_word_embeddings", self.text_config.tie_word_embeddings)
super().__init__(**kwargs)
from_pretrained hands us plain dicts, so we rebuild the typed configs.The properties below it derive the token counts from the config, so the processor and the model cannot disagree unless someone overrides one by hand. That is the bug we caused in step 4.
def patches_per_crop(self) -> int:
"""N_v: patch tokens the encoder emits for one crop, e.g. (224 / 16)^2 = 196."""
return (self.vision_config.image_size // self.vision_config.patch_size) ** 2
@property
def image_seq_len(self) -> int:
"""N_img: image tokens the language model sees per crop, after pixel shuffle."""
return self.patches_per_crop // (self.pixel_shuffle_factor**2)
@property
def projector_in_dim(self) -> int:
return self.vision_config.hidden_size * self.pixel_shuffle_factor**2
class TinyVLM(PreTrainedModel):
config_class = VLMConfig
config: VLMConfig
base_model_prefix = "tinyvlm"
main_input_name = "input_ids"
input_modalities = ("image", "text")
# SmolLM2 ties the output head to the input embeddings; tell save/load about it.
_tied_weights_keys = {"lm.lm_head.weight": "lm.model.embed_tokens.weight"}
_supports_sdpa = True
def __init__(self, config: VLMConfig):
super().__init__(config)
self.vision = SiglipVisionModel(config.vision_config)
self.projector = build_projector(config.projector_type, config.projector_in_dim, config.text_config.hidden_size)
self.lm = LlamaForCausalLM(config.text_config)
self.post_init()
_tied_weights_keys tells save and load that the output head shares weights with the embeddings.# Registering lets AutoConfig / AutoModel load a saved TinyVLM directory like any Hub model.
AutoConfig.register("tinyvlm", VLMConfig, exist_ok=True)
AutoModel.register(VLMConfig, TinyVLM, exist_ok=True)
AutoModelForImageTextToText.register(VLMConfig, TinyVLM, exist_ok=True)
$ .venv/bin/python c07-vlm/scripts/step12_save_load.py chat_template.jinja 0.00 MB
config.json 0.00 MB
model.safetensors 889.86 MB
preprocessor_config.json 0.00 MB
processor_config.json 0.00 MB
tokenizer.json 3.52 MB
tokenizer_config.json 0.00 MB
AutoConfig -> VLMConfig | image_token_id 49152 | image_seq_len 49
AutoModel -> TinyVLM | tied: True
logits identical: True (1, 63, 49216)The checkpoint is 889.86 MB. That matches the arithmetic: 222,451,392 parameters at 4 bytes each is 889.8 MB, so the tied head is stored once. After reloading, the logits are identical to the last bit, and tied: True confirms the head and embeddings still share memory.
Train the projector and see if the model can see
Goal Train only the projector on captions we can score exactly, and measure if the model uses the picture.
All the parts run. We still have not shown that the model can see. The cheapest proof is to train only the projector on a task where the answer is exact.
We draw pictures of one to three coloured shapes and ask for a caption such as Two red circles. Because we drew them, we can score a generated caption by parsing it. The encoder and language model stay frozen. Gradients still flow through the frozen language model into the projector, because the loss sits on caption tokens and the image features sit in their context.
model.set_trainable(vision=False, projector=True, lm=False)
model.to(device)
batch = processor.collate([processor.build_example(e["messages"], e["images"]) for e in examples])
if args.bad_labels: # every real token becomes a target, image placeholders included
batch["labels"] = batch["input_ids"].masked_fill(batch["attention_mask"] == 0, -100)
loss = model(
input_ids=batch["input_ids"].to(device),
pixel_values=batch["pixel_values"].to(device),
attention_mask=batch["attention_mask"].to(device),
labels=batch["labels"].to(device),
).loss
for group in optimizer.param_groups:
group["lr"] = lr_at(step, args.steps, args.lr, args.warmup)
optimizer.zero_grad(set_to_none=True)
loss.backward()
grad_norm = torch.nn.utils.clip_grad_norm_(model.projector.parameters(), 1.0)
optimizer.step()
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --steps 300 --eval-every 25
$ .venv/bin/python c07-vlm/scripts/evaluate_alignment.py --run align-mlp-s2The run took 869 s for 300 steps on AMD EPYC 7R13, 8 threads, on a machine with other work running. The loss starts at 4.768 and averages 0.004 over the last 20 steps. On 96 held-out pictures, the share of captions with count, colour and shape all correct goes from 0% to 100%.
Before training the model writes The image is a photograph of a woman wearing a white dress. After training it writes Three orange squares. That is what the picture shows. Only the 2.1 million projector parameters changed.
Is the picture really being used?
A caption can be right for the wrong reason. evaluate_alignment.py reruns the same 96 pictures with one thing broken at a time. Nothing in this list raises an error.
conditions = {
"correct": {},
"blind (all pixels zero)": {"transform": torch.zeros_like},
"wrong normalisation ([0, 1], not [-1, 1])": {"transform": lambda x: x * 0.5 + 0.5},
"right padding at generation": {"padding_side": "right"},
| Condition | Count | Colour | Shape | All three | Sample caption |
|---|---|---|---|---|---|
| Correct | 100% | 100% | 100% | 100% | Three orange squares. |
| Blind: all pixels zero | 19% | 9% | 42% | 0% | One red square. |
| Wrong normalisation: [0, 1] | 99% | 83% | 100% | 82% | Three yellow squares. |
| Right padding at generation | 73% | 74% | 71% | 70% | What is the same as this question? What |
| Crops reversed, own targets (16 pictures) | 25% | 0% | 38% | 0% | Each caption describes another sample |
| Crops reversed, reversed targets (16 pictures) | 100% | 100% | 100% | 100% | The same captions, scored in reversed order |
The sample captions all describe one picture, and the first row shows its true caption. Four results stand out.
- Blind. With the pixels zeroed, 0% of captions are right. The captions keep the trained format, but count and colour are worse than random guessing, which would give 33% for count and 17% for colour. So the right answers above come from the picture.
- Wrong normalisation. This is the mistake promised in step 1. Colour falls to 83%, count holds at 99% and shape at 100%. Pixels in [0, 1] are brighter than the encoder expects, and orange and red both become yellow in the samples. Shape survives it. An overall score of 82% could pass a quick check, and it comes entirely from one wrong line in a processor.
- Right padding. 29 of 96 captions fail, and the question lengths differ by only one token.
Describe the image.has 4 tokens and the other two questions have 5, so a third of the prompts, 32 of 96, get one pad token on the right.evaluate_alignment.pyalso splits the score by group. Of the 64 unpadded samples, 64 give the exact caption. Of the 32 padded samples, 3 parse as right and only 1 is the exact caption. With left padding, all 32 of the 32 padded samples are exact, as theconditions.correct.paddedfield of the same results file records. The next token is read from the last position, and under right padding that position is a pad slot, not the end of the prompt. The parser is also generous here: it scoresWhat is something you saw? Two purple circlesas correct, so the real damage is worse than the table shows. - Reversed crops. This is the last frame of Figure 3, now measured. Against each sample's own target the score is 0%. Against the reversed targets it is 100%. So every caption is perfect, for the wrong sample.
Where it stops working
Now for pictures the generator could never draw. These are the honest test of what the projector learned.
| Picture | Caption | What happened |
|---|---|---|
| A red circle and a blue square | Two red circles. | It only knows one colour and one shape per picture, so it drops one object and invents another. |
| Four green squares | Three green squares. | Colour and shape are right. It has never written "Four", so it says the nearest count it knows. |
| Two yellow triangles, colours inverted, dark canvas | Two blue triangles. | Inverted yellow really is blue, so this reading is right, on a canvas it never saw. |
| A grey gradient, no shapes | "A" is a valid punctuation mark. | It leaves the caption format and writes confident nonsense. It has no way to say "no shapes". |
The model reads colour and shape from real pixels, and that survives a dark canvas. But it can only say what it was trained to say, and it never admits doubt. That is the job of real data, which is where the next tutorial starts.
Does the choice of projector matter?
Here is the same task with the other bridges from step 3. The MLP with shuffle 2 is the run above. The final-loss column is the mean of the last 20 steps. The run with pixel shuffle 1 has four times the tokens, so it gets fewer steps.
| Run | Image tokens | Trainable | Steps | Time per step | Final loss | All three, step 50 | Step 100 | Final |
|---|---|---|---|---|---|---|---|---|
| MLP, shuffle 2 | 49 | 2,102,400 | 300 | 2.9 s | 0.004 | 59% | 97% | 100% |
| Linear, shuffle 2 | 49 | 1,770,048 | 300 | 2.8 s | 0.004 | 94% | 97% | 100% |
| MLP, shuffle 1 | 196 | 775,296 | 200 | 6.3 s | 0.004 | 91% | 100% | 100% |
| MLP, shuffle 2, labels on every token | 49 | 2,102,400 | 300 | 3.5 s | 8.469 | 9% | 28% | 95% |
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector linear --steps 300 --eval-every 50
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --pixel-shuffle 1 --steps 200 --eval-every 50
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --bad-labels --steps 300 --eval-every 50Every bridge gets there. The differences are in how fast. At step 50 the linear projector is already at 94% and the MLP without shuffle at 91%, while our MLP with shuffle 2 is at 59%. This is one run per setting with one seed, so read it as one observation, not a ranking. What it does show is that on an easy task a single linear layer is enough, and that shuffle earns its place through cost: a step with 196 image tokens took 6.3 s against 2.9 s with 49.
Checks against trusted code
A from-scratch build earns trust by agreeing with something you did not write. Each row below is a test or a run you can repeat.
| Our code | Trusted side | Check | Where |
|---|---|---|---|
| Image processor | SiglipImageProcessorPil | Max difference under 1e-5. The script printed 0. | test_matches_hf_siglip_processor |
| Headless encoder | Full SiglipModel | Patch tokens within 1e-5 | test_vision_tower_matches_full_siglip |
| Pixel shuffle | Idefics3Connector.pixel_shuffle | torch.equal | test_pixel_shuffle_equals_idefics3 |
| Text-only forward | Plain SmolLM2 | Logits within 1e-4 on the original 49152 columns | test_text_only_logits_match_smollm2 |
| Chat rendering | The SmolLM2 tokenizer's template | Identical strings when a system message is given. With none, SmolLM2 adds a default one and we do not. | test_chat_template_matches_smollm2, test_we_leave_out_smollm2s_default_system_message |
| Loss | F.cross_entropy by hand | Within 1e-6 | test_forward_shapes_and_loss_matches_manual_cross_entropy |
| Attention mask | Hugging Face's internal mask | Logits within 1e-5 | test_explicit_4d_mask_matches_hf_default |
| Greedy decoding | lm.generate | Identical tokens | test_manual_greedy_equals_hf_generate_and_no_cache |
The last two stand out for one reason. Both prove a reference we wrote for reading is the same as the code that runs. The text-only row matters too: it shows that attaching a vision tower left the language model's behaviour on text alone unchanged.
TinyVLM next to real VLMs
Our choices are not the only ones. Rows are models. Columns are the aspects we built, one per step. Values come from each model's published config or its Hugging Face modelling code.
| Model | Encoder input | Patch tokens per crop | Folding | Image tokens per crop | Connector | Positions |
|---|---|---|---|---|---|---|
| TinyVLM (this post) | 224 px, patch 16, SigLIP-base | 196 | Pixel shuffle, factor 2 | 49 | Linear, GELU, Linear | 1D |
| SmolVLM-256M | 512 px, patch 16 | 1024 | Pixel shuffle, factor 4 | 64 | One linear layer, no bias | 1D |
| LLaVA-1.5 | 336 px, patch 14, CLIP | 576 | None | 576 | Linear, GELU, Linear | 1D |
| Qwen2.5-VL | Variable size, patch 14 | Depends on the picture | Patch merger over 2 × 2 | Depends on the picture | RMSNorm, then Linear, GELU, Linear | M-RoPE, 3D |
The pattern to notice is in the folding column. SmolVLM-256M uses the same language model shape as ours: hidden size 576, 30 layers, 9 heads and 3 KV heads. It sees a picture at more than twice our crop size, and it still costs only 64 tokens, because it folds harder. Its connector is simpler too: one linear layer over a concatenation of 16 patches. LLaVA-1.5 sits at the other end: no folding, 576 tokens, and a language model with a 4096-number hidden size to carry them.
Many more inThe VLM architecture galleryRun everything
The final folder, and every command that produced a number in this post. scripts/run_all.sh runs the step scripts, benchmarks and all four alignment runs in one go. The few one-line checks are shown where they are used.
c07-vlm/ final tree
c07-vlm/
├── README.md
├── conftest.py
├── tinyvlm/
│ ├── image_processing.py # steps 1, 9: picture to crops to tensor
│ ├── projector.py # step 3: Linear, MLP, pixel shuffle
│ ├── merge.py # step 4: naive loop and masked_scatter
│ ├── chat.py # step 5: ChatML, split into supervised pieces
│ ├── processing.py # steps 5, 6, 10: placeholders, labels, boundaries
│ ├── positions.py # step 7: 1D and 3D position ids
│ ├── masks.py # step 8: attention masks you can print
│ ├── generation.py # step 11: greedy decoding by hand
│ ├── configuration.py # step 12: VLMConfig
│ ├── modeling.py # TinyVLM: forward, generate, set_trainable
│ ├── build.py # joins the two pretrained models
│ ├── data.py # step 13: synthetic shape captions
│ ├── testing.py # a tiny random model for the tests
│ └── device.py
├── scripts/
│ ├── step01_image_processor.py ... step12_save_load.py
│ ├── break_it.py
│ ├── run_all.sh # every step, benchmark and alignment run
│ ├── train_alignment.py
│ └── evaluate_alignment.py
├── benchmarks/
│ ├── bench_processor.py
│ ├── bench_forward.py
│ └── bench_decode.py
├── results/ # saved outputs quoted in this post
└── tests/
├── test_image_processing.py
├── test_projector.py
├── test_merge.py
├── test_processor.py
├── test_masks_positions.py
├── test_model.py
└── test_real_models.py # network: checks against the real checkpoints
$ .venv/bin/python -m pytest c07-vlm -m "not slow and not gpu and not network" -q
$ .venv/bin/python -m pytest c07-vlm -m "network and not slow" -q
$ for s in 01_image_processor 02_vision_features 03_projector 04_scatter 05_sequence \
07_positions_masks 09_variable_resolution 10_multi_image 11_generate 12_save_load; do \
.venv/bin/python c07-vlm/scripts/step$s.py; done
$ .venv/bin/python c07-vlm/scripts/break_it.py
$ .venv/bin/python c07-vlm/benchmarks/bench_processor.py
$ .venv/bin/python c07-vlm/benchmarks/bench_forward.py --device cpu
$ .venv/bin/python c07-vlm/benchmarks/bench_decode.py
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --steps 300 --eval-every 25
$ .venv/bin/python c07-vlm/scripts/evaluate_alignment.py --run align-mlp-s2
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector linear --steps 300 --eval-every 50
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --bad-labels --steps 300 --eval-every 50
$ .venv/bin/python c07-vlm/scripts/train_alignment.py --projector mlp --pixel-shuffle 1 --steps 200 --eval-every 50
$ PY=.venv/bin/python bash c07-vlm/scripts/run_all.sh # or all of the runs above in one goKey insights and nuances
- The resize filter is part of the encoder's input. Bicubic overshoot moves the darkest value from −0.686 to −0.788. A processor that swaps the filter does not match the training recipe. Step 1
- Choosing a vision layer also chooses a normalisation.
hidden_statesskips the closing LayerNorm, so layer −2 ranges down to −212 where the last layer stops at −43. Step 2 - A fresh projector is loud, not quiet. A new
Linear(768)outputs about 11 times the standard deviation of real token embeddings. Step 3 - PyTorch's own check on
masked_scatteronly works one way. Too few features raise an error. Too many are silently dropped, and reversed crops are not detectable from counts at all. Step 4 - A loss above ln(V) points at your labels. Labels on every token give 11.458 against a uniform score of 10.8, and nothing raises. Step 6
- 3D positions are a change to the language model. A processor can compute them, but the attention layers must be able to use them. Step 7
- With a tile cap, cost follows the aspect ratio, not the resolution. 640 × 480 and 2048 × 1536 both cost 343 tokens. A 100 × 50 icon costs 147. Step 9
- The KV cache matters more as pictures grow. Its saving over 20 tokens goes from a factor of 1.4 at 63 tokens to 7.9 at 1386 tokens, while its memory grows 22 times. Step 11
- Token compression cannot speed up the encoder. Pixel shuffle runs after it. All the saving is in the language model and its cache. Step 9
- Silent bugs show a pattern in the scores. Wrong normalisation lowers colour and leaves shape alone. Reversed crops score 0% against their own targets and 100% against the reversed ones. One pad token on the wrong side breaks almost every padded sample. Step 13
- Training does not match the scales. The trained projector's output is about 36 times larger than token embeddings, and captions on this task are still all correct. Step 13
- A perfect score here is a narrow claim. It shows that the picture reaches the language model. A red circle next to a blue square still comes back as
Two red circles.Step 13
Exercises
- Add a marker around each pictureEasy Add a
<fake_token_around_image>special token on both sides of every picture, as Idefics3 does. Update_expandandimage_index, then show with a test that the placeholder count is unchanged.Hint
Remember to resize the token embeddings again. Then check that the labels on the new tokens are −100.
- Stop the icon problemEasy Add a
min_size_for_tilingargument so the 100 × 50 picture in step 9 gets one crop. Makenum_crops_for_sizeagree with it, and extendtest_tile_count_matches_prediction. - Build the prefix-LM maskMedium Extend
build_attention_maskso image and question tokens see each other in both directions and the reply stays causal, as in PaliGemma. Pass it withto_additiveand show that logits change only on prompt positions.Hint
The training path knows which segments are supervised. That is your boundary.
- Try a real connectorHard Replace the MLP with learned queries and cross-attention from C3, so that 196 patches become 16 tokens. Compare the parameter count, KV cache and alignment accuracy against pixel shuffle.
- Match SmolVLM's shapeHard Configure a 512 px crop with pixel shuffle 4, and confirm you get 64 tokens per crop. SiglipVisionConfig needs
image_size=512, and the positional table needs interpolating. Measure the encode time per crop against ours.
Continue reading
- Train a Real VLM: the next tutorial trains this model on real data, with mixtures and stages.
- Post-Train a VLM: preferences and RL on a pretrained model, and why a tiny one is not enough.
- Teaching language models to see: the theory behind projector-first training and data mixtures.
- The cost of a picture: token compression and serving, beyond pixel shuffle.
- How VLMs read documents: where tiling and small detail matter most.
References
Grouped by topic. Every entry links to its primary source.
Encoders and language models
- An Image is Worth 16x16 Words · Dosovitskiy et al., 2020. Patch tokens.
- Sigmoid Loss for Language Image Pre-Training · Zhai et al., 2023. SigLIP.
- google/siglip-base-patch16-224 · the encoder checkpoint we use.
- HuggingFaceTB/SmolLM2-135M-Instruct · the language model checkpoint we use.
Connectors and token folding
- Visual Instruction Tuning · Liu et al., 2023. LLaVA and the one-layer projector.
- Improved Baselines with Visual Instruction Tuning · Liu et al., 2023. LLaVA-1.5 and the MLP projector.
- Building and better understanding vision-language models · Marafioti et al., 2024. Idefics3 and pixel shuffle.
- SmolVLM: Redefining small and efficient multimodal models · Marafioti et al., 2025.
Resolution, positions and masks
- How Far Are We to GPT-4V? · Chen et al., 2024. InternVL 1.5 and dynamic high resolution.
- OpenGVLab/InternVL-Chat-V1-5 · the model card holds the grid rule we follow, in
find_closest_aspect_ratio. - Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution · Wang et al., 2024. M-RoPE.
- PaliGemma: A versatile 3B VLM for transfer · Beyer et al., 2024. Prefix-LM attention.
Code
- blog-coding-tutorials: c07-vlm · the code for this tutorial.
- transformers: idefics3 · the trusted pixel shuffle and merge.