Unit 2 of 9 · about 4 hours · explain, implement
Projectors between representation spaces, and early, late and cross-attention fusion
Equal widths permit concatenation, but do not establish semantic alignment. Fusion placement also determines which representations can interact and what a text-only control must bypass.
You'll be able to
- Trace visual features through a linear or MLP projector into decoder-width embeddings.
- Compare joint token processing, separate-encoder scoring and inserted cross-attention using explicit interaction shapes.
- Test a gated fusion branch against the unfused residual path at initialization.
Covers
Read
In this order, only the parts listed
0 of 4 done
- CS336 Spring 2026 Lecture 17: multimodal modelsCS336 2026 - Alignment and Multimodality
The
llavaModel block andqwen_vlArchitecture block - LLaVA projector builder at commit c121f04LLaVA - Visual Instruction Tuning
build_vision_projector:linear,mlpNx_geluandidentitybranches - Flamingo, arXiv:2204.14198v1Flamingo: a Visual Language Model for Few-Shot Learning (Alayrac et al., 2022)
Sections 3.1.1 to 3.1.3, Figures 4 to 6: resampler, gated cross-attention and image-causal masking
These are the architecture sections in this edition; Sections 2.1 to 2.3 are related work. Do not implement the full model.
- Modern LLM Notebook 29: projector and fusionModern LLM Notebook - Vision-Language Models
Sections 5 and 6, then Exercise 2: Implement a Single-Layer Projector
The Section 6 demo adds LayerNorm after the gated residual, so its zero gate returns normalized input, not unchanged input. Use Flamingo Figure 5 for an identity-preserving insertion.
Focus on
- For visual features of shape , a biased linear projector has parameters and returns . It changes width, not token count.
- Use early fusion to mean joint processing of modality tokens; Chameleon uses it from pretraining. Separate CLIP towers combine only at scoring, a late interaction. LLaVA concatenates pretrained features before decoder processing. State the actual interaction rather than relying on labels alone.
- Cross-attention uses text queries and visual keys and values: per-head score shape . Its cost includes text self-attention, visual encoding, projections and any resampler, not just this matrix.
- For a finite branch output, equals at a zero gate. This is an initialization contract, not evidence that the model later uses vision.
Common mistakes · 3
- Treating equal embedding dimensions as aligned spaces. Only an objective and external evaluation can establish useful correspondence.
- Claiming a resampler removes all resolution cost. Its output length is fixed, but visual encoding and resampling still process the input grid.
- Treating the notebook's schematic attention-entry counts as total FLOPs or a speed measurement. They omit projections and the vision tower.
Try it yourself
Closed-book, before checking anything
(2, 6, 32) to (2, 6, 64). Implement the gated residual from Flamingo Figure 5 and test zero-gate identity on finite inputs. Contrast it with the notebook's post-residual normalization.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Does a tokenwise MLP projector reduce a 196-token grid to 32 tokens?Answer
No. It changes each token's features independently. Pooling, merging or a query-based resampler must explicitly change the token axis.
2.Why can Flamingo text depend on older images when direct cross-attention sees only the most recent image?Answer
Earlier text states can already contain information from those images. Causal text self-attention carries that information forward.
3.At a zero gate, must the added branch's own parameters receive nonzero gradients?Answer
No. Their gradient through the gated output is multiplied by zero. The gate can receive a gradient and open the branch on later updates.
Practice
- Modern LLM Notebook 29, Exercise 2: Implement a Single-Layer Projector
Exercise 2 under Exercises: construct the linear map and satisfy the
(2, 196, 4096)output assertionRun on CPU. Add the smaller linear-versus-MLP parameter test and zero-gate regression above. The section mini-project connects the projector to frozen features and a decoder; this exercise checks shapes, not grounding.
You're done when
The exercise and your parameter and gate tests pass, and you can draw the interaction shapes and cost omissions for all three fusion designs.
Only when you can do this without notes.
Leads to
Notes
Resources · 4 for this unit, 11 more in the 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.
- 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. - 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. - 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.
Also in this section
- 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.
- 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.
- 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.
- 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.
- 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.