Unit 1 of 9 · about 4 hours · derive, implement

Image patches, vision encoders and visual-token counts, and resolution, context and compute cost

Patch extraction is already familiar from the Deep Learning unit on patch embeddings and positional information. The research problem is tracking what survives preprocessing and compression, and which component pays for each token.

You'll be able to

  • Derive separate token counts for the vision encoder and the language decoder after merging and delimiters.
  • Implement rectangular patch extraction with an explicit flattening order and grid coordinates.
  • Budget resolution changes across vision attention, decoder context and cached state.

Covers

Image patching, vision encoders and visual-token sequencesResolution, patch count, context length, memory and compute
1

Read

In this order, only the parts listed

0 of 2 done

  1. CS336 Spring 2026 Lecture 17: multimodal modelsCS336 2026 - Alignment and Multimodality

    The clip data-processing and vision-encoder blocks, then llava_onevision Data processing and qwen2_vl Visual encoder

    Read for preprocessing and token budgets, not the reported large-model speed comparisons. The Qwen2-VL count of 66 includes two delimiters, not 66 visual features.

  2. Qwen2-VL, arXiv:2409.12191v1Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution (Wang et al., 2024)

    Section 2.1, Model Architecture: the Naive Dynamic Resolution paragraph (2D positions, adjacent 2 by 2 token compression and vision delimiters)

2

Focus on

  • Count the processed image, not its original dimensions. Resizing, cropping and tiling change both evidence and token count.
  • For divisible dimensions and square patch width , the vision grid has patches. A 2 by 2 merger gives visual decoder tokens when both grid dimensions are even.
  • Doubling both image dimensions quadruples patch count. Dense vision attention score entries grow sixteenfold; projections grow fourfold. Decoder attention instead depends on the total visual plus text length.
  • Attention score counts are not measured latency or peak memory. Fused attention can avoid storing the full score matrix; decoder KV state grows linearly with its sequence length.
Common mistakes · 3
  • Counting a pooled CLIP embedding as a sequence of patch features. A pooled vector discards the explicit grid the projector may need.
  • Changing a frozen encoder's input resolution without checking its positional encoding and preprocessing contract. A valid tensor shape is not proof of compatible features.
  • Calling a sixteenfold attention-score increase a sixteenfold runtime increase. Other operations, kernels and memory traffic still matter.
3

Try it yourself

Closed-book, before checking anything

Closed-book, count a 224 by 224 image with patch width 14: 256 vision patches, 64 visual tokens after 2 by 2 merging, and 66 positions including two delimiters. For a 448 by 448 input, get 1024, 256 and 258 respectively. With 32 text tokens and no other special tokens, the decoder lengths are 98 and 290. Implement the TensorTonic rectangular patch contract and check its channel ordering against a nested-loop oracle on CPU with PyTorch 2.14.1.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Why does Qwen2-VL describe 66 tokens for a 224 by 224 image?Answer

    Patch width 14 gives 256 patches. Merging each 2 by 2 group gives 64 visual tokens; the start and end delimiters add two positions.

  2. 2.Does doubling image resolution quadruple the whole decoder's attention cost?Answer

    No. Visual token count quadruples under the stated grid rule, but dense decoder attention uses the square of text plus visual length, including delimiters.

  3. 3.Can a center crop improve efficiency without changing the task?Answer

    Only if it preserves the evidence the task needs. Cropping away a small object or text changes what can be answered from the input.

5

Practice

  • TensorTonic: Patchify a Batch of Images

    Implement vision_transformer_patchify(images, patch_height, patch_width); public cases Four horizontal patches, Two-channel patches and Whole-image patch

    The public cases cover rectangular extraction, channel-first flattening and a whole-image patch. Add noncontiguous-input, dtype and reconstruction tests; reuse the result for the mini-project's resolution budget rather than repeating the earlier square-patch exercise.

You're done when

Your rectangular patch outputs match the public cases and your loop oracle, and your budget distinguishes vision patches, merged decoder tokens and delimiters at both resolutions.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 13 more in the section

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 _transform and tokenize, 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.

  • 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_projector in the code. Build only a tiny frozen-encoder plus projector path and compare it with text-only and shuffled-pair controls.

  • 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.ipynb through 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: ClipLoss and SigLipLoss in src/open_clip/loss.py as oracles for your losses, and the zero-shot classifier. OpenAI RN50 weights need force_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.