Unit 5 of 9 · about 4 hours · implement
Modality tokens, attention masks and multimodal RoPE coordinates
The Deep Learning unit on causal and padding masks and the LLM Foundations unit on RoPE supply the mechanics. Multimodal assembly adds a second indexing system: image grids expand placeholders, while coordinate offsets need not equal the packed token count.
You'll be able to
- Expand image placeholders while keeping embeddings, labels, attention masks and position metadata synchronized.
- Implement temporal, height and width coordinates for mixed text and visual grids with explicit offsets.
- Test causal isolation, padding, image ownership and truncation after visual-token expansion.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Qwen2-VL, arXiv:2409.12191v1: M-RoPEQwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution (Wang et al., 2024)
Section 2.1, Multimodal Rotary Position Embedding, and Figure 3; Section 3.3.2 and Table 8 for the ablation
Implement the coordinate contract, not the full Qwen2-VL model. Its ablation results belong to its own training setup, not your small decoder.
- LLaVA input assembly at commit c121f04LLaVA - Visual Instruction Tuning
prepare_inputs_labels_for_multimodal: image-placeholder replacement,IGNORE_INDEXimage labels, expanded-sequence truncation and rebuilt padding, masks and positionsTrace the one-image path. LLaVA's rebuilt one-dimensional positions are not Qwen2-VL M-RoPE; treat them as separate designs.
Focus on
- Attention permission and prediction supervision are different. Visual features may condition answers while having ignored labels; user prompts may also be visible but unsupervised.
- M-RoPE allocates rotary channel groups to temporal, height and width axes. Text repeats the same position on all axes; an image holds time fixed and varies grid row and column. This changes rotary coordinates, not the causal order of the packed sequence.
- The exercise advances the next segment to one beyond the largest coordinate already used, not one beyond the token count. Record grid dimensions after merging, row-major ordering and the separator policy.
- Expand first, then validate lengths and truncation. A cut through visual features or an assistant answer needs a declared rejection or truncation policy, not silent misalignment.
Common mistakes · 3
- Using coordinate magnitude to decide causal visibility. Visual grid coordinates can repeat; causality follows sequence order and the chosen fusion policy.
- Sending a placeholder sentinel into the ordinary text embedding table. Replace it before lookup if it is not a real vocabulary id.
- Assuming the coordinate exercise validates rotary channel allocation, cached decoding or model masks. It returns coordinates only; those need separate integration tests.
Try it yourself
Closed-book, before checking anything
[0, 1, 2, 2, 2, 2, 4], height [0, 1, 2, 2, 3, 3, 4] and width [0, 1, 2, 3, 2, 3, 4]. Then assemble a visual prefix plus text and perturb a future text embedding: earlier valid outputs must stay within your stated tolerance in evaluation mode. Repeat with padding changed and with two examples batched separately and together.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why is the separator coordinate 4 after a 2 by 2 image starting at offset 2, although seven tokens are emitted in total?Answer
The image uses coordinates up to 3 and advances the offset by its largest grid dimension, two. Coordinate progression is not packed sequence length.
2.Does ignoring the visual labels prevent the decoder from attending to the image?Answer
No. Ignored labels remove prediction losses at those positions. Attention masks separately determine which visual features can condition text.
3.Why must the image placeholder expand before checking the context budget?Answer
One placeholder can become hundreds of positions. A text-only length check can pass while the expanded input truncates image evidence or answer targets.
Practice
- TensorTonic: Assign Multimodal RoPE Coordinates
multimodal_rope_coordinates(segments); public cases Text image and separator, Wide image grid and Strided video gridThe cases check coordinates for mixed segments, a rectangular image and a strided video. Add empty-segment and offset tests. The section mini-project covers expanded labels, padding, future-token isolation, serialization and cached-versus-full decoding; the exercise does not test those.
You're done when
The three public coordinate cases pass, and your expanded batch preserves valid outputs under padding and future-token interventions without confusing attention masks with loss masks.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 13 more in the section
- LLaVA - Visual Instruction TuningLLaVA Team · required
Read Section 3 (GPT-assisted instruction data built from captions and boxes) and Sections 4.1 and 4.2 (a linear projection, then two-stage training). LLaVA-1.5 (https://arxiv.org/abs/2310.03744) swaps in a two-layer MLP; see
build_vision_projectorin the code. Build only a tiny frozen-encoder plus projector path and compare it with text-only and shuffled-pair controls. - Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution (Wang et al., 2024)Alibaba Qwen · required
Read Section 2.1 and Figure 3 (dynamic resolution, 2x2 token merging, M-RoPE with temporal, height and width components) and Section 3.3.2 (the M-RoPE ablation). Variable resolution means variable tokens and memory.
Also in this section
- CS336 2026 - Alignment and MultimodalityStanford University · primary
Step through the Lecture 17 trace ("multimodal models": CLIP, SigLIP, LLaVA, LLaVA-OneVision, Qwen-VL, Qwen2-VL, Qwen3-VL, Chameleon). Reconstruct patching, projector, fusion, multimodal positions and the chosen objective before implementing the bounded image-text path.
- CLIP Paper and Official CodeOpenAI · required
Read Section 2.2 and the Figure 3 pseudocode (normalized embeddings, logits scaled by a learned temperature, the symmetric cross-entropy), then Section 2.3. Check preprocessing and tokenization in the official code (
clip/clip.py_transformandtokenize, https://github.com/openai/CLIP). The README says logits are "times 100", but the model learns the scale. - Sigmoid Loss for Language Image Pre-Training (Zhai et al., 2023)Google DeepMind · required
Read Sections 3.1 and 3.2 and Algorithm 1: a pairwise sigmoid loss with a learned temperature and bias instead of a softmax over the batch. Negatives still matter; keep the reduction convention explicit.
- POPE: Evaluating Object Hallucination in Large Vision-Language ModelsRenmin University · required
Read Sections 5.1 and 5.2 of the paper (https://aclanthology.org/2023.emnlp-main.20.pdf), then evaluate one negative-sampling slice (random, popular or adversarial) with accuracy, F1 and the yes ratio. Join answers by question id, not row order, and keep the original files apart from POPEv2.
- Modern LLM Notebook - Vision-Language ModelsWalking Labs · support
Complete
notebooks-en/part4-frontiers/29-vlm.ipynbthrough the minimal VLM. Add missing-image, conflicting-caption, resolution and serialization tests that the walkthrough does not supply. - smol-course Unit 3 - Vision Language ModelsHugging Face · support
Work through Unit 3 for a runnable VLM fine-tuning path on SmolVLM2. Check its memory notes against your GPU and shrink the model, image resolution or batch before running.
- COCO Captions SubsetCOCO Consortium · support
Select 50 to 200 image ids from one annotation split with all their captions, record each image's license, and keep every caption of an evaluation image out of training. The annotations are CC BY 4.0; the images keep their own terms.
- Flamingo: a Visual Language Model for Few-Shot Learning (Alayrac et al., 2022)DeepMind · support
Read Sections 2.1 to 2.3 (details in Appendix A.1.1 to A.1.3): the Perceiver Resampler, gated cross-attention with tanh gates starting at zero, and multi-image masking. It is the cross-attention contrast to LLaVA's token concatenation.
- TensorTonic - Alignment and Multimodality SetTensorTonic · support
Solve Patchify a Batch of Images (
cs336-l17-vision-transformer-patchify), Implement Symmetric CLIP Contrastive Loss (cs336-l17-symmetric-clip-loss), Implement the SigLIP Pairwise Loss (cs336-l17-siglip-pairwise-loss) and Assign Multimodal RoPE Coordinates (cs336-l17-multimodal-rope-coordinates). Its SigLIP loss averages over all B squared pairs while OpenCLIP divides the sum by B, so multiply by B before comparing. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - OpenCLIPML Foundations · reference
Use release 3.3.0 for one small comparison:
ClipLossandSigLipLossinsrc/open_clip/loss.pyas oracles for your losses, and the zero-shot classifier. OpenAI RN50 weights needforce_quick_gelu=True. The main branch has a refactored training stack; do not adopt the distributed trainer. - Chameleon: Mixed-Modal Early-Fusion Foundation Models (Chameleon Team, 2024)Meta FAIR · reference
Read Sections 2.1 to 2.3: images as 1024 discrete tokens from an 8192-entry codebook, interleaved data and the stability fixes. Early fusion still depends on the image tokenizer.
- LLM Post-Training Laboratory - Multimodal ModuleRoadmap-Final · support
Use the optional multimodal evidence module for versioned aligned data, projector or fusion tests, retrieval and generation evaluation, and modality-specific safety checks.
- High Fidelity Neural Audio Compression (EnCodec)Meta AI · reference
Sections 3.1 to 3.4 of arXiv:2210.13438v1: temporal downsampling, residual codebooks, code prediction and codec reconstruction objectives. Read for audio-token vocabulary and rate accounting, not a codec training run.