# LLaVA: Text-Only GPT-4 Writes 158K Visual Instructions and a Language Model Learns to See

> LLaVA connects a frozen CLIP ViT-L/14, one linear projection and Vicuna: stage 1 trains only the projection, stage 2 tunes it with the language model on 158K visual instructions written by text-only GPT-4. This post covers the method, rechecks the tables and re-runs stage 1 at small scale.

- URL: https://dmxsf.com/en/blog/llava-visual-instruction-tuning/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2023-04-28
- Updated: 2026-11-13
- Paper notes
- Paper: [Visual Instruction Tuning](https://arxiv.org/abs/2304.08485) (Haotian Liu, Chunyuan Li, Qingyang Wu, Yong Jae Lee · NeurIPS 2023, 2023)

"Visual Instruction Tuning" (Liu, Li, Wu and Lee, NeurIPS 2023; this post calls it the LLaVA paper) asks a narrow question: given a strong text-only language model and a strong vision encoder, what is the smallest change that lets the language model chat about an image? Its answer has two parts. **Data**: there was no ready-made set of (image, instruction, response) triples, so it had the text-only GPT-4 write them. An image is first turned into five captions plus a set of bounding boxes with coordinates, and GPT-4 generates three kinds of samples from that, conversations, detailed descriptions and complex reasoning, 158K in all. **Model**: a frozen CLIP ViT-L/14 turns the image into a grid of features, one linear projection maps them into "visual tokens" in the language model's word-embedding space, and these go into Vicuna together with the text instruction. Training has two steps: first only the projection is trained (595K image-caption pairs, feature alignment), then the projection and the language model together (158K visual instructions). The paper reports a relative score of 85.1% against text-only GPT-4 reference answers on LLaVA-Bench (COCO), a 30-image, 90-question benchmark, and on ScienceQA 90.92% for LLaVA alone and 92.53% when GPT-4 acts as a judge between two models' answers.

This post does two things. **Check**: it copies the paper's tables into a script and recomputes them, then counts parameters and cost from the public configs. The paper's numbers are largely self-consistent: stage 1 updates only 5,248,000 parameters, 0.0394% of the total. But 4 of the 16 brackets in Table 4 do not match the table's own numbers (largest gap 0.8 points), "+29%" and "+48%" are really percentage points, and the ablation text on "answer first or reasoning first" contradicts Table 8. **Small-scale reproduction**: on a laptop it freezes both CLIP ViT-B/32 and Qwen2.5-0.5B and trains only a 768-to-896 linear projection, so that the language model names the class of a CIFAR-10 image. After 200 steps the test accuracy is 93.4% with before-last-layer features and 93.4% with last-layer features (three-seed means), on par with a linear probe trained directly on the same features (93.2% and 93.1%); yet the projected visual tokens look like no word vector, so the language model is not reading "an image translated into words".

## Why this paper is worth reading

- **It reduces the recipe for a seeing assistant to the minimum.** A frozen vision tower, one linear layer and a language model, joined end to end. The linear projection has 5,248,000 parameters, less than four ten-thousandths of the whole model, and it is all that connects CLIP's features to a 13-billion-parameter language model. LLaVA-1.5 later swapped the linear layer for a two-layer MLP, raised the resolution to 336 pixels and added academic VQA data, while calling the original fully-connected connector "surprisingly powerful and data-efficient".
- **A text model builds training data for a vision model.** As the paper's introduction frames it, Alpaca, Vicuna and GPT-4-LLM improved the alignment of open language models with machine-generated instruction data, and LLaVA moves the same road onto images. The GPT-4 of spring 2023 could not see images, so the paper "translates" each image into captions plus boxes and lets GPT-4 write the questions. That detour is the most instructive part of the paper, and it also sets the ceiling and the blind spots of the data.
- **It is cheap.** The appendix reports 4 hours plus 10 hours on 8 A100 GPUs; the check below turns that into 112 A100-hours.
- **Its evaluation style became influential, and deserves caution.** LLaVA-Bench has a text-only GPT-4 score answers against ground-truth descriptions. That "relative score against a judge's reference" was reused by many later multimodal papers, so the sample sizes, judge bias and question sources are worth going through one by one.
- **Neighbors on this site.** For how multimodal models attach images to language models in general, see [Multimodal LLMs](https://dmxsf.com/en/wiki/multimodal/multimodal-llms/). The vision tower's origin is in the [CLIP walkthrough](https://dmxsf.com/en/blog/clip-learning-transferable-visual-models/) and the [ViT walkthrough](https://dmxsf.com/en/blog/vit-an-image-is-worth-16x16-words/); how instruction tuning shapes assistant behavior is in the [InstructGPT walkthrough](https://dmxsf.com/en/blog/instructgpt-rlhf/); and judge bias is covered in [LLM as a judge](https://dmxsf.com/en/wiki/evaluation/llm-as-judge/).

## Background: language models learned to follow instructions, vision models had not

By spring 2023 the text-only recipe was clear: an open base model (LLaMA) plus machine-generated instruction data (the paper's introduction cites Alpaca, Vicuna and GPT-4-LLM) turns a base model into an assistant that does what it is told. The vision side was different. The paper points out that large vision models were mostly "one task, one model", with language used only to describe image content, so the interface was fixed and interaction limited. Flamingo, BLIP-2, OpenFlamingo and LLaMA-Adapter had already connected images to language models, but according to the related-work section they were not explicitly tuned on vision-language instruction data, and their performance on multimodal tasks often lagged behind their performance on language-only tasks.

What was missing was data. Text instruction data can be generated by a strong model, but there was no ready source for image instructions; the paper says that crowd-sourcing them is time-consuming and that it is hard to define the tasks well (Section 3). LLaVA's two contributions target these two gaps: a pipeline for producing the data, and a model trained on it.

## Method

### Data: a text-only GPT-4 writes questions about images it cannot see

The cheapest option is to turn existing image-text pairs into instruction format: pick a random "describe this image" sentence as the instruction and use the original caption as the answer. The paper calls this naive expansion; it is cheap, but both instructions and answers lack diversity and deeper reasoning.

The paper's approach is to ask the text-only GPT-4 (or ChatGPT) to be the teacher. To let a text model "see" an image it uses two symbolic representations: **captions** describe the same scene from different angles, and **bounding boxes** give each object's class and normalized coordinates (Table 1 of the paper has an example, `person: [0.681, 0.242, 0.774, 0.694]`). Images come only from COCO. For each type of data a few seed examples are written by hand and used as in-context examples for GPT-4; they are the only human annotation in the whole data pipeline. GPT-4 then generates three kinds of responses:

| Type | Count | Form | Notes |
| --- | --- | --- | --- |
| Conversation | 58K | multi-turn Q&A | asks about object type, count, action, location and relative position; only questions with definite answers |
| Detailed description | 23K | single turn | one random sentence from a question list (first generated by GPT-4, then curated) asks GPT-4 for a rich, comprehensive description |
| Complex reasoning | 77K | single turn | on top of what the first two kinds look at, asks questions that need step-by-step reasoning with rigorous logic |

The three add up to 158K samples from about 80K distinct images (the note under Table 3 of the paper). The paper says it compared ChatGPT and GPT-4 in early experiments and found GPT-4 consistently gave higher-quality data, for example in spatial reasoning; it gives no numbers for that comparison.

*Figure: Figure 1: How LLaVA-Instruct-158K is generated (Section 3 and Table 1 of the paper). GPT-4 reads text only, so the image is written down as captions and boxes; the hand-written seed examples are the only human annotation in the whole pipeline.*

### Architecture: a frozen vision tower, one linear layer, one language model

The model has only three blocks. For an input image $\mathbf X_v$, a pretrained CLIP ViT-L/14 gives visual features $\mathbf Z_v=g(\mathbf X_v)$; a trainable projection matrix $\mathbf W$ turns them into visual tokens with the same dimension as the language model's word embeddings:

$$
\mathbf H_v=\mathbf W\cdot\mathbf Z_v,\qquad \mathbf Z_v=g(\mathbf X_v)
$$

The paper takes the grid features from before and after the last Transformer layer and compares them in the ablation below. It picks Vicuna as the language model because it had the best instruction-following ability among the publicly available checkpoints at the time. The paper does not say how many visual tokens one image becomes; ViT-L/14 at 224 pixels has $16\times16=256$ patches, which is computed here from the public configuration (see "Checking the paper's numbers") and is not a figure from the paper.

The paper calls the linear projection "lightweight" and says it allows fast, data-centric iteration; more elaborate connectors, such as Flamingo's gated cross-attention and BLIP-2's Q-Former, are left for future exploration.

*Figure: Figure 2: LLaVA's structure and two-stage training (Section 4 and Appendix C of the paper). The parameter counts, trainable fractions and step counts are computed here from public configs and the paper's hyperparameters (see the check section); 256 is the number of patches of ViT-L/14 at 224 pixels, which the paper does not state.*

### Training: loss on the answers only, in two stages

For each image, a multi-turn conversation $(\mathbf X_q^1,\mathbf X_a^1,\dots,\mathbf X_q^T,\mathbf X_a^T)$ is laid out as one sequence (Table 2 of the paper): after a system message come alternating Human and Assistant turns separated by the stop token `###`; in the first turn the image is placed randomly before or after the question. Training keeps the language model's usual autoregressive objective, and **only the assistant's answers and the stop token after them** count toward the loss. For an answer of length $L$:

$$
p(\mathbf X_a\mid\mathbf X_v,\mathbf X_{\text{instruct}})=\prod_{i=1}^{L}p_\theta\bigl(x_i\mid\mathbf X_v,\mathbf X_{\text{instruct},<i},\mathbf X_{a,<i}\bigr)
$$

The two stages differ only in the trainable parameters $\theta$ and the data:

| | Stage 1: feature alignment | Stage 2: end-to-end fine-tuning |
| --- | --- | --- |
| Trainable | only the projection $\mathbf W$ | $\mathbf W$ and the language model; the vision encoder stays frozen |
| Data | 595K image-caption pairs filtered from CC3M | LLaVA-Instruct-158K (chatbot) or the ScienceQA training set |
| Instruction | a random "describe the image briefly" sentence; the answer is the original caption | conversation, detailed description and complex reasoning sampled uniformly; conversation is multi-turn, the other two single-turn |
| LR, batch, epochs | 2e-3, 128, 1 | 2e-5, 32, 3 (the 158K setting; ScienceQA trains for 12 epochs) |
| Wall-clock in the paper (8 A100) | about 4 h | about 10 h (ScienceQA: about 4 h) |

The paper reads stage 1 as "training a compatible visual tokenizer for the frozen language model". The optimizer follows Vicuna: Adam without weight decay, a cosine learning-rate schedule and 3% warmup; fine-tuning uses FSDP and gradient checkpointing to save memory, with BF16 and TF32 enabled.

The 595K pairs of stage 1 come from filtering CC3M, which the paper's Appendix E describes. A noun phrase is extracted from every caption with Spacy and its frequency counted; phrases with a frequency below 3 are skipped (the paper says they are mostly rare combinations of concepts and attributes already covered by other captions); starting from the least frequent remaining phrase, captions that contain it are added to the pool, and when a phrase's frequency exceeds 100, only 100 random captions are kept. The count of distinct noun phrases drops from 108,182 to 31,423 (appendix Fig. 7), and the sample count to about 595K. It is a compromise between concept coverage and training efficiency.

For ScienceQA, the question and context are treated as the instruction and the reasoning plus answer as the response, trained as a single-turn conversation; LLaVA is asked to write the reasoning first and then the answer.

## Experiments and conclusions

The paper has three main groups of results: chat ability (qualitative examples and LLaVA-Bench), ScienceQA, and ablations.

**Qualitative.** The paper compares LLaVA with GPT-4, BLIP-2 and OpenFlamingo on a few examples from the GPT-4 technical report (such as the image of someone ironing clothes on the back of a taxi). Asked what is unusual about the image, BLIP-2 and OpenFlamingo just describe the picture, while LLaVA follows the instruction and points out the oddity. The paper stresses that this comes from a dataset of only about 80K images.

**How LLaVA-Bench is scored.** The paper borrows from Vicuna and uses GPT-4 as the judge. For each (image, ground-truth description, question) triple, the candidate model answers while looking at the image; the reference answer is written by the text-only GPT-4 from the ground-truth description (captions and boxes), approximating a theoretical upper bound; the judge, also a text-only GPT-4, sees the question, the visual information as text and the two answers, and gives each a score from 1 to 10 on helpfulness, relevance, accuracy and level of detail. The benchmark reports the candidate's score relative to the reference's score.

**LLaVA-Bench (COCO): ablating the training data.** The paper randomly picks 30 images from COCO-Val-2014 and, following its Section 3 pipeline, generates the three question types for each, 90 questions in all. Table 4 compares different training data (relative score in %; the brackets are the gaps to Full data as printed in the paper):

| Training data | Conv | Detail | Complex | All |
| --- | --- | --- | --- | --- |
| Full data (all three types) | 83.1 | 75.3 | 96.5 | 85.1 |
| Detail + Complex | 81.5 (−1.6) | 73.3 (−2.0) | 90.8 (−5.7) | 81.9 (−3.2) |
| Conv + 5% Detail + 10% Complex | 81.0 (−2.1) | 68.4 (−7.1) | 91.5 (−5.0) | 80.5 (−4.4) |
| Conversation only | 76.5 (−6.6) | 59.8 (−16.2) | 84.9 (−12.4) | 73.8 (−11.3) |
| No instruction tuning | 22.0 (−61.1) | 24.0 (−51.3) | 18.5 (−78.0) | 21.5 (−63.6) |

The paper draws three readings: instruction tuning raises the score by over 50 points; adding just a little detailed-description and complex-reasoning data (5% and 10%) raises the total by about 7 points more and improves the conversation questions too, which suggests that reasoning ability and conversation ability reinforce each other; and using all three types gives the best score, 85.1%.

**LLaVA-Bench (In-the-Wild): harder, unseen domains.** 24 images and 60 questions; the images include indoor and outdoor scenes, memes, paintings and sketches, and each comes with a highly detailed human-written description. Table 5 (mean ± standard deviation; the first three rows are three inference runs, and † is one set of LLaVA outputs judged three times):

| Model | Conv | Detail | Complex | All |
| --- | --- | --- | --- | --- |
| OpenFlamingo | 19.3 ± 0.5 | 19.0 ± 0.5 | 19.1 ± 0.7 | 19.1 ± 0.4 |
| BLIP-2 | 54.6 ± 1.4 | 29.1 ± 1.2 | 32.9 ± 0.7 | 38.1 ± 1.0 |
| LLaVA | 57.3 ± 1.9 | 52.5 ± 6.3 | 81.7 ± 1.8 | 67.3 ± 2.0 |
| LLaVA† (judged 3 times) | 58.8 ± 0.6 | 49.2 ± 0.8 | 81.4 ± 0.3 | 66.7 ± 0.3 |

The paper concludes that LLaVA clearly beats BLIP-2 (+29%) and OpenFlamingo (+48%), reaching 81.7% of the text-only GPT-4 reference on complex-reasoning questions.

**ScienceQA.** The dataset has 21K multimodal multiple-choice questions over 3 subjects, 26 topics, 127 categories and 379 skills, with 12,726, 4,241 and 4,241 questions in the train, validation and test splits. For LLaVA the paper uses the visual features from before the last layer, has the model write the reasoning before choosing an answer, and trains for 12 epochs, reaching 90.92%, close to the best score of the time, 91.68% (MM-CoT Large). It also prompts the text-only GPT-4 with two examples for 82.69%, and tries two ways of combining GPT-4 and LLaVA. **Complement** uses LLaVA's prediction only when GPT-4 cannot answer, and is nearly the same as LLaVA alone. **Judge** gives GPT-4 the question and both answers when the two models disagree and lets it produce the final answer; it improves every category and reaches 92.53%. The paper says this is the first time GPT-4 has been used for model ensembling. Table 7, abridged to four columns (average, social science, questions with an image context, questions with no context; the full table has 9 columns, and the check script uses all of them):

| Method | Avg | SOC | IMG | NO |
| --- | --- | --- | --- | --- |
| Human | 88.40 | 84.97 | 87.50 | 88.10 |
| GPT-3.5 w/ CoT | 75.17 | 70.87 | 67.43 | 79.93 |
| LLaMA-Adapter | 85.19 | 88.30 | 80.32 | 86.90 |
| MM-CoT Base | 84.91 | 77.17 | 82.90 | 86.83 |
| MM-CoT Large | 91.68 | 82.00 | 88.80 | 92.89 |
| GPT-4 (text-only, 2-shot) | 82.69 | 73.45 | 70.75 | 90.73 |
| LLaVA | 90.92 | 95.95 | 88.00 | 90.66 |
| LLaVA + GPT-4 (complement) | 90.97 | 95.50 | 87.80 | 91.08 |
| LLaVA + GPT-4 (judge) | 92.53 | 96.74 | 88.99 | 93.52 |

**Ablations (Table 8, ScienceQA).**

| Variant | Accuracy |
| --- | --- |
| The paper's best setting | 90.92 |
| Visual features from the last layer | 89.96 (−0.96) |
| Answer first, reasoning after | 89.77 (−1.15) |
| No pretraining, train on ScienceQA directly | 85.81 (−5.11) |
| 7B model | 89.84 (−1.08) |

The paper explains the weaker last-layer features by suggesting that the last layer may focus more on global, abstract properties, while the layer before it keeps more local properties that help with specific details; this is a hypothesis it does not test. It also reports that removing "pretraining" (stage 1, by the naming of its Section 4.2) loses 5.11 points, which shows the alignment stage matters.

**Limitations in the paper's own words.** The paper uses two images from LLaVA-Bench (In-the-Wild), a bowl of ramen and a fridge full of food, to show the benchmark is deliberately hard: naming the ramen restaurant needs broad knowledge and multilingual understanding, and recognizing a yogurt brand needs high-resolution input. It also observes an interesting failure: asked whether the fridge contains strawberry-flavored yogurt, LLaVA answers yes, although the fridge holds only yogurt and strawberries. The paper's judgment is that LLaVA sometimes sees an image as a "bag of patches" and fails to grasp its complex semantics.

### Reading the tables with care

- **These scores are not accuracies.** LLaVA-Bench numbers are "scores relative to a text-only GPT-4 reference answer"; both the judge and the reference are GPT-4, and the judge sees ground-truth descriptions rather than the image. It measures how much an answer resembles what a GPT-4 holding the full description would say, not whether the answer is right.
- **The COCO benchmark shares its origin with the training data.** Its 90 questions were generated for COCO validation images with the Section 3 pipeline, so they have the same procedure, the same image source (COCO) and the same generator (GPT-4) as the training data. It is closer to measuring how well LLaVA imitates the data generator; for unseen domains look at In-the-Wild.
- **The samples are small and the noise is not.** The COCO benchmark has 30 images and 90 questions, In-the-Wild has 24 images and 60 questions. In Table 5 the standard deviation of LLaVA's All score over three inference runs is 2.0 points, and 6.3 for the detailed-description column; the judge's own fluctuation is much smaller (0.3 for All when one set of outputs is judged three times). Table 4 gives single-run numbers only, so differences of a point or two should not be interpreted. Judge biases such as preferring longer answers are covered in [LLM as a judge](https://dmxsf.com/en/wiki/evaluation/llm-as-judge/); the paper reports the stability of the scores, and its Appendix A concedes that how robust this evaluation is in other situations, and whether it can assess hallucination and fine-grained understanding, is left for future work; I found no test of the judge's preferences in it.
- **The ScienceQA "new best" comes from an ensemble.** The 92.53% is LLaVA plus one GPT-4 call, not LLaVA alone; LLaVA alone gets 90.92%, below MM-CoT Large's 91.68%.
- **Places where the paper disagrees with itself** are listed one by one in the next section: four brackets in Table 4 do not add up, "+29%" is in percentage points, and the ablation text about answer-first versus reasoning-first contradicts Table 8.

## Checking the paper's numbers

The script below downloads no dataset and loads no weights. It does two things: it copies the paper's tables into the script and recomputes them, and it builds the models from the public `config.json` files on the meta device to count parameters and cost. Environment: Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0, NumPy 2.4.2, run on CPU. The configurations are `openai/clip-vit-large-patch14` and `lmsys/vicuna-13b-v1.5` (the paper uses Vicuna v0, based on LLaMA-1; the publicly available v1.5 configuration stands in for it here, and its layer count and hidden size match a 13B LLaMA, but details such as the vocabulary may differ, so the parameter counts are estimates).

<details>
<summary>Full code (about 179 lines)</summary>

```python
"""Checking LLaVA: recompute the claims from its tables and public configs"""
import numpy as np
import torch
from transformers import (AutoConfig, CLIPVisionConfig, CLIPVisionModel,
                          LlamaForCausalLM)
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()

# --- Numbers from arXiv 2304.08485, copied table by table ---
COLS = ("Conv", "Detail", "Complex", "All")
T4 = {  # Table 4: relative score (%) and the bracketed differences
    "Full data": ((83.1, 75.3, 96.5, 85.1), None),
    "Detail + Complex": ((81.5, 73.3, 90.8, 81.9), (-1.6, -2.0, -5.7, -3.2)),
    "Conv + 5% Detail + 10% Complex": ((81.0, 68.4, 91.5, 80.5),
                                       (-2.1, -7.1, -5.0, -4.4)),
    "Conversation": ((76.5, 59.8, 84.9, 73.8), (-6.6, -16.2, -12.4, -11.3)),
    "No instruction tuning": ((22.0, 24.0, 18.5, 21.5),
                              (-61.1, -51.3, -78.0, -63.6))}
T5 = {  # Table 5: LLaVA-Bench (In-the-Wild), mean and std
    "OpenFlamingo": ((19.3, 19.0, 19.1, 19.1), (0.5, 0.5, 0.7, 0.4)),
    "BLIP-2": ((54.6, 29.1, 32.9, 38.1), (1.4, 1.2, 0.7, 1.0)),
    "LLaVA": ((57.3, 52.5, 81.7, 67.3), (1.9, 6.3, 1.8, 2.0)),
    "LLaVA (judge x3)": ((58.8, 49.2, 81.4, 66.7), (0.6, 0.8, 0.3, 0.3))}
G7 = ("NAT", "SOC", "LAN", "TXT", "IMG", "NO", "G1-6", "G7-12")
T7 = {  # Table 7: ScienceQA accuracy; the last number is the average
    "Human": (90.23, 84.97, 87.48, 89.60, 87.50, 88.10, 91.59, 82.42, 88.40),
    "GPT-3.5": (74.64, 69.74, 76.00, 74.44, 67.28, 77.42, 76.80, 68.89, 73.97),
    "GPT-3.5 CoT": (75.44, 70.87, 78.09, 74.68, 67.43, 79.93, 78.23, 69.68,
                    75.17),
    "LLaMA-Adapter": (84.37, 88.30, 84.36, 83.72, 80.32, 86.90, 85.83, 84.05,
                      85.19),
    "MM-CoT Base": (87.52, 77.17, 85.82, 87.88, 82.90, 86.83, 84.65, 85.37,
                    84.91),
    "MM-CoT Large": (95.91, 82.00, 90.82, 95.26, 88.80, 92.89, 92.44, 90.31,
                     91.68),
    "GPT-4": (84.06, 73.45, 87.36, 81.87, 70.75, 90.73, 84.69, 79.10, 82.69),
    "LLaVA": (90.36, 95.95, 88.00, 89.49, 88.00, 90.66, 90.93, 90.90, 90.92),
    "LLaVA + GPT-4 complement": (90.36, 95.50, 88.55, 89.05, 87.80, 91.08,
                                 92.22, 88.73, 90.97),
    "LLaVA + GPT-4 judge": (91.56, 96.74, 91.09, 90.62, 88.99, 93.52, 92.73,
                            92.16, 92.53)}
T8 = {"best": 90.92, "last-layer features": (89.96, -0.96),
      "answer first": (89.77, -1.15), "no pre-training": (85.81, -5.11),
      "7B model": (89.84, -1.08)}

# --- 0. The paper's headline numbers ---
print("0. The paper's headline numbers (from Tables 4, 5 and 7)")
print(f"   LLaVA-Bench COCO: {T4['Full data'][0][3]}; "
      f"In-the-Wild: {T5['LLaVA'][0][3]} (BLIP-2 {T5['BLIP-2'][0][3]})")
print("   ScienceQA: " f"LLaVA {T7['LLaVA'][8]}, "
      f"MM-CoT Large {T7['MM-CoT Large'][8]}, "
      f"LLaVA + GPT-4 judge {T7['LLaVA + GPT-4 judge'][8]}")

# --- 1. Data and training budget ---
print("\n1. Data and training budget")
mix = {"conversation": 58, "detail": 23, "reasoning": 77}
print(f"   LLaVA-Instruct-158K: {sum(mix.values())}K = 58K + 23K + 77K")
s1, s2 = 595_000 / 128, 158_000 * 3 / 32
print(f"   Stage 1: 595K pairs, batch 128, 1 epoch: about {s1:,.0f} steps")
print(f"   Stage 2: 158K samples, batch 32, 3 epochs: about {s2:,.0f} steps")
for name, n, h in (("stage 1", 595_000, 4),
                   ("stage 2", 158_000 * 3, 10)):
    print(f"   {name}: {h} h on 8 A100 = {8 * h} GPU-hours, "
          f"{n / (h * 3600):.1f} samples/s")
print(f"   ScienceQA splits: 12726 + 4241 + 4241 = {12726 + 4241 + 4241:,}")

# --- 2. Table 4: the bracketed differences and "All" ---
print("\n2. Table 4 (LLaVA-Bench COCO): is each bracket the gap to Full data?")
full = np.array(T4["Full data"][0])
bad, n_cells = [], 0
for row, (v, d) in T4.items():
    if d is None:
        continue
    gap = np.round(np.array(v) - full, 1)
    for c, g, r in zip(COLS, gap, d):
        n_cells += 1
        if abs(g - r) > 0.15:
            bad.append(f"{row} / {c}: {g:+.1f} vs {r:+.1f}")
print(f"   Cells beyond rounding error (0.15): {len(bad)} / {n_cells}")
for b in bad:
    print("   " + b)
print("   \"All\" minus the mean of the three columns: "
      + " ".join(f"{v[3] - np.mean(v[:3]):+.2f}" for v, _ in T4.values()))
conv = T4["Conversation"][0][3]
mixed = T4["Conv + 5% Detail + 10% Complex"][0][3]
none = T4["No instruction tuning"][0][3]
print(f"   Text, \"over 50 points\": {conv} - {none} = {conv - none:.1f}; "
      f"\"about 7 points\": {mixed} - {conv} = {mixed - conv:.1f}")

# --- 3. Table 5: "+29%", "+48%" and the judge's stability ---
print("\n3. Table 5 (LLaVA-Bench In-the-Wild)")
allc = {k: v[0][3] for k, v in T5.items()}
print(f"   Text \"+29%\": {allc['LLaVA']} - {allc['BLIP-2']} = "
      f"{allc['LLaVA'] - allc['BLIP-2']:.1f}" + "; \"+48%\": "
      f"{allc['LLaVA'] - allc['OpenFlamingo']:.1f}")
m3 = np.array([v[0][:3] for v in T5.values()])
y5 = np.array([v[0][3] for v in T5.values()])
w, *_ = np.linalg.lstsq(m3, y5, rcond=None)
res = m3 @ w - y5
print("   Implied weights of the three question types (sum not forced): "
      + " ".join(f"{x:.3f}" for x in w) + f"  (sum {w.sum():.3f})")
print("   Residual per row: " + " ".join(f"{x:+.2f}" for x in res))
print(f"   As ratios: LLaVA is {allc['LLaVA'] / allc['BLIP-2']:.2f}x BLIP-2, "
      f"{allc['LLaVA'] / allc['OpenFlamingo']:.2f}x OpenFlamingo")
sd = {k: v[1][3] for k, v in T5.items()}
print(f"   Std of \"All\": three inference runs {sd['LLaVA']}, "
      f"one set of outputs judged three times {sd['LLaVA (judge x3)']}")

# --- 4. Table 7: recover the group sizes from the table ---
print("\n4. Table 7 (4,241 ScienceQA test questions): group sizes")
M = np.array(list(T7.values()))
parts = {"subject": [0, 1, 2], "context": [3, 4, 5], "grade": [6, 7]}
for name, cols in parts.items():
    wts, *_ = np.linalg.lstsq(M[:, cols], M[:, 8], rcond=None)
    err = M[:, cols] @ wts - M[:, 8]
    sizes = wts * 4241
    print(f"   {name:<8}" + "implied sizes "
          + " ".join(f"{s:7.1f}" for s in sizes) + f" (sum {sizes.sum():.1f})")
    print("            max residual " + f"{abs(err).max():.3f}")
    worst = list(T7)[int(abs(err).argmax())]
    print(f"            row with the largest residual: {worst}")
print("   Claims in the text:")
g = lambda k, i=8: T7[k][i]
print(f"   GPT-4 - GPT-3.5 CoT = {g('GPT-4') - g('GPT-3.5 CoT'):.2f}"
      + " (paper: 7.52)")
print(f"   MM-CoT Large - LLaVA = {g('MM-CoT Large') - g('LLaVA'):.2f}"
      + "; judge - MM-CoT Large = "
      f"{g('LLaVA + GPT-4 judge') - g('MM-CoT Large'):.2f}"
      + "; complement - LLaVA = "
      f"{g('LLaVA + GPT-4 complement') - g('LLaVA'):.2f}")
up = [G7[i] for i in range(8)
      if T7["LLaVA + GPT-4 judge"][i] > T7["LLaVA"][i]]
print(f"   Columns where judge beats LLaVA alone: {len(up)} / 8")
up = [G7[i] for i in range(8)
      if T7["LLaVA + GPT-4 complement"][i] > T7["LLaVA"][i]]
print(f"   Columns where complement beats LLaVA alone: {len(up)} / 8")
print("   Gap to LLaVA alone, by column:")
print("   " + " " * 10 + "".join(f"{c:>7}" for c in G7))
for k in ("LLaVA + GPT-4 judge", "LLaVA + GPT-4 complement"):
    d = [b - a for a, b in zip(T7["LLaVA"], T7[k])]
    cells = "".join(f"{x:>+7.2f}" for x in d[:8])
    print("   " + k.split()[-1].ljust(10) + cells)
pj = g('LLaVA + GPT-4 judge') / 100
se = (pj * (1 - pj) / 4241) ** 0.5 * 100
print(f"   One question = {100 / 4241:.3f} points; "
      f"binomial standard error of 92.53% = {se:.2f}")
print("   Table 8: is each bracket the gap to 90.92? "
      + " ".join(f"{round(v[0] - T8['best'], 2):+.2f}/{v[1]:+.2f}"
                 for k, v in T8.items() if k != "best"))

# --- 5. Parameters, visual tokens and compute (public configs) ---
print("\n5. Architecture bookkeeping (public configs, counted on meta)")
vc = CLIPVisionConfig.from_pretrained("openai/clip-vit-large-patch14")
lc = AutoConfig.from_pretrained("lmsys/vicuna-13b-v1.5")
with torch.device("meta"):
    vit = CLIPVisionModel(vc)
    llm = LlamaForCausalLM(lc)
n_vit = sum(p.numel() for p in vit.parameters())
n_llm = sum(p.numel() for p in llm.parameters())
n_emb = lc.vocab_size * lc.hidden_size
proj = vc.hidden_size * lc.hidden_size + lc.hidden_size
tokens = (vc.image_size // vc.patch_size) ** 2
total = n_vit + n_llm + proj
print(f"   Vision encoder {n_vit / 1e6:.1f}M (frozen), "
      f"language model {n_llm / 1e9:.2f}B")
print(f"   Projection: {vc.hidden_size} x {lc.hidden_size} + bias = "
      f"{proj:,} parameters")
print(f"   Stage 1 trainable: {proj / total:.4%}; "
      f"stage 2: {(n_llm + proj) / total:.2%}")
print(f"   Visual tokens: ({vc.image_size} / {vc.patch_size})^2 = {tokens}, "
      f"{tokens / 2048:.1%} of a 2048-token context")
kv = tokens * 2 * lc.num_hidden_layers * lc.hidden_size * 2
print(f"   KV cache of those tokens (fp16): {kv / 2**20:.0f} MiB")
f_vit = 2 * n_vit * (tokens + 1)
f_llm = 2 * (n_llm - n_emb) * tokens
print(f"   Forward FLOPs: encoder {f_vit / 1e9:.0f} GFLOPs, "
      f"language model over the {tokens} tokens {f_llm / 1e12:.2f} TFLOPs, "
      f"encoder share {f_vit / f_llm:.1%}")
```

</details>

Output:

```text
0. The paper's headline numbers (from Tables 4, 5 and 7)
   LLaVA-Bench COCO: 85.1; In-the-Wild: 67.3 (BLIP-2 38.1)
   ScienceQA: LLaVA 90.92, MM-CoT Large 91.68, LLaVA + GPT-4 judge 92.53

1. Data and training budget
   LLaVA-Instruct-158K: 158K = 58K + 23K + 77K
   Stage 1: 595K pairs, batch 128, 1 epoch: about 4,648 steps
   Stage 2: 158K samples, batch 32, 3 epochs: about 14,812 steps
   stage 1: 4 h on 8 A100 = 32 GPU-hours, 41.3 samples/s
   stage 2: 10 h on 8 A100 = 80 GPU-hours, 13.2 samples/s
   ScienceQA splits: 12726 + 4241 + 4241 = 21,208

2. Table 4 (LLaVA-Bench COCO): is each bracket the gap to Full data?
   Cells beyond rounding error (0.15): 4 / 16
   Conv + 5% Detail + 10% Complex / Detail: -6.9 vs -7.1
   Conv + 5% Detail + 10% Complex / All: -4.6 vs -4.4
   Conversation / Detail: -15.5 vs -16.2
   Conversation / Complex: -11.6 vs -12.4
   "All" minus the mean of the three columns: +0.13 +0.03 +0.20 +0.07 +0.00
   Text, "over 50 points": 73.8 - 21.5 = 52.3; "about 7 points": 80.5 - 73.8 = 6.7

3. Table 5 (LLaVA-Bench In-the-Wild)
   Text "+29%": 67.3 - 38.1 = 29.2; "+48%": 48.2
   Implied weights of the three question types (sum not forced): 0.285 0.254 0.460  (sum 0.999)
   Residual per row: +0.02 -0.00 -0.03 +0.03
   As ratios: LLaVA is 1.77x BLIP-2, 3.52x OpenFlamingo
   Std of "All": three inference runs 2.0, one set of outputs judged three times 0.3

4. Table 7 (4,241 ScienceQA test questions): group sizes
   subject implied sizes  2251.5   889.2  1100.3 (sum 4241.0)
            max residual 0.014
            row with the largest residual: Human
   context implied sizes  -842.8  2281.9  2854.2 (sum 4293.3)
            max residual 0.667
            row with the largest residual: MM-CoT Base
   grade   implied sizes  2737.9  1503.0 (sum 4240.9)
            max residual 0.063
            row with the largest residual: Human
   Claims in the text:
   GPT-4 - GPT-3.5 CoT = 7.52 (paper: 7.52)
   MM-CoT Large - LLaVA = 0.76; judge - MM-CoT Large = 0.85; complement - LLaVA = 0.05
   Columns where judge beats LLaVA alone: 8 / 8
   Columns where complement beats LLaVA alone: 3 / 8
   Gap to LLaVA alone, by column:
                 NAT    SOC    LAN    TXT    IMG     NO   G1-6  G7-12
   judge       +1.20  +0.79  +3.09  +1.13  +0.99  +2.86  +1.80  +1.26
   complement  +0.00  -0.45  +0.55  -0.44  -0.20  +0.42  +1.29  -2.17
   One question = 0.024 points; binomial standard error of 92.53% = 0.40
   Table 8: is each bracket the gap to 90.92? -0.96/-0.96 -1.15/-1.15 -5.11/-5.11 -1.08/-1.08

5. Architecture bookkeeping (public configs, counted on meta)
   Vision encoder 303.2M (frozen), language model 13.02B
   Projection: 1024 x 5120 + bias = 5,248,000 parameters
   Stage 1 trainable: 0.0394%; stage 2: 97.72%
   Visual tokens: (224 / 14)^2 = 256, 12.5% of a 2048-token context
   KV cache of those tokens (fp16): 200 MiB
   Forward FLOPs: encoder 156 GFLOPs, language model over the 256 tokens 6.58 TFLOPs, encoder share 2.4%
```

Going through it item by item:

- **Training budget.** The three data types, 58K + 23K + 77K, add up to exactly 158K. Stage 1 with 595K pairs, batch size 128 and one epoch is about 4,648 steps; stage 2 with 158K samples, batch size 32 and three epochs is about 14,812 steps. The appendix wall-clock is 4 and 10 hours on 8 A100 GPUs, that is 32 and 80 GPU-hours, with throughputs of 41.3 and 13.2 samples per second; stage 2 is much slower, and the paper does not say why (stage-2 samples are longer and the trainable parameters grow from a few million to 13 billion, which is my inference). The two stages add up to 112 A100-hours, a total I computed; the paper does not give it. Fine-tuning on ScienceQA needs about 4 more hours. The three ScienceQA splits add up to 21,208, consistent with the paper's "21K".
- **The brackets in Table 4.** Of the 16 brackets, 4 disagree with "this cell minus the Full-data cell" by more than rounding error (0.15): in the conversation-only row, Detail and Complex (printed −16.2 and −12.4, the subtraction gives −15.5 and −11.6), and in the mixed-ratio row, Detail and All (printed −7.1 and −4.4, the subtraction gives −6.9 and −4.6); the largest discrepancy is 0.8 points. This does not change the paper's conclusion (those rows are far below Full data anyway), but the brackets cannot be used as reproducible numbers; compute from the raw scores yourself. The All column is also not the plain average of the three columns, differing by 0.0 to 0.2 points; the paper does not say how All is computed, and it may be a ratio of totals over all 90 questions.
- **The claims in the text.** "Instruction tuning adds over 50 points" is 73.8 − 21.5 = 52.3 and "a further 7 points" is 80.5 − 73.8 = 6.7; both check out.
- **"+29%" and "+48%" are percentage points.** In Table 5 LLaVA's 67.3 is 29.2 points above BLIP-2's 38.1 and 48.2 points above OpenFlamingo's 19.1; the "+29%" and "+48%" in the paper are these differences, not relative improvements. As ratios, LLaVA is 1.77 times BLIP-2 and 3.52 times OpenFlamingo. Solving the four rows for the implicit weights of the three question types gives 0.285, 0.254 and 0.460 (summing to 0.999, with row residuals below 0.03), so the All column is consistent with the first three; the paper does not give the number of questions of each type.
- **The judge is stable, generation is not.** The standard deviation of LLaVA's All score is 2.0 points over three inference runs and only 0.3 points when one set of outputs is judged three times: the judge's own randomness is much smaller than the generation randomness, in line with the paper's statement that GPT-4 gives consistent evaluations. It is also a reminder that differences of the Table 4 kind, one or two points (80.5 against 81.9, say), probably fall inside generation noise (Table 5 is a different benchmark, so this is only an order of magnitude).
- **The subset sizes in Table 7 can be solved for.** "Average" is the accuracy of each subset weighted by its number of questions, so the ten rows determine the subset sizes. The three subject columns (NAT, SOC, LAN) give 2251.5, 889.2 and 1100.3, which add up to exactly 4,241.0, with a maximum residual of only 0.014 points; the two grade columns give 2737.9 and 1503.0, summing to 4,240.9, with a residual of 0.063. The three context columns (TXT, IMG, NO) cannot be solved: the implied size for TXT is negative (−842.8) and the three sum to 4,293.3, with a residual of 0.667. A possible reason is that these three subsets are not a partition, since one question can have both text and image context and be counted in two groups; I did not check this against the dataset. At least for the subject and grade partitions, the numbers in the table are mutually consistent.
- **Statements about ScienceQA.** GPT-4 beats GPT-3.5 (with chain of thought) by 82.69 − 75.17 = 7.52 points, matching the 7.52 in the paper. MM-CoT Large is 0.76 points above LLaVA, and the judge scheme is 0.85 points above MM-CoT Large. One question is worth 0.024 points, so 0.85 points is about 36 questions; the binomial standard error of a single accuracy (92.53%) is 0.40 points, so a gap of 0.85 is only one or two standard errors and cannot be called a significant lead (both models answer the same questions, so a paired comparison would have a smaller error, but there is no per-question data to compute it). The complement scheme is only 0.05 points, 2 questions, above LLaVA alone, and by column it is higher in only 3 of 8, with G7-12 2.17 points lower, so "nearly identical" describes the average only; column by column it goes up and down. The judge scheme is higher in all 8 columns, by +0.79 to +3.09, and also 0.99 points higher in the IMG column with image context; the paper's explanation is that some questions that come with an image do not need it, so a text model can correct LLaVA's mistakes.
- **Table 8.** All four brackets equal "this row minus 90.92", so they are consistent. But the paper's ablation paragraph is inconsistent with it on answer-first versus reasoning-first: the paragraph says that answer-first gets its best 89.77% after 12 epochs, while reasoning-first reaches 89.77% in 6 epochs and then stops improving with more training; Section 5.2 and Table 8 say that reasoning-first with 12 epochs gets 90.92% and answer-first gets 89.77%. The two cannot both hold, and I cannot tell from the paper which one is the typo.
- **Bookkeeping of the architecture.** The vision tower has 303.2M parameters (frozen) and the language model 13.02B. The projection is a $1024\times5120$ weight plus 5120 biases, 5,248,000 parameters in all: stage 1 trains only 0.0394% of all parameters, and stage 2 trains 97.72% (language model and projection; the vision tower stays frozen). The 256 visual tokens take 12.5% of the 2048-token context; their KV cache (fp16) is 200 MiB, with the algorithm in [KV Cache](https://dmxsf.com/en/wiki/inference/kv-cache/). The forward cost, roughly "2 × parameters × tokens": the vision encoder takes about 156 GFLOPs per image and the language model about 6.58 TFLOPs more for the 256 tokens, so the vision tower is only 2.4%. The cost sits on the language-model side, not in encoding the image.

## Hands-on: stage 1 at small scale

The check can only show whether the paper's numbers are self-consistent. It cannot answer a more basic question: **can a frozen language model really read visual features after only a linear layer has been trained?** Below is a scaled-down stage 1 on a laptop: freeze CLIP and Qwen2.5-0.5B, train only the projection, and have the language model name the CIFAR-10 class after it has seen 49 patch tokens and a question. This is a "small-scale reproduction": it shows how the route behaves and can neither confirm nor refute the paper's conclusions, and it differs from the paper a lot:

| | The paper's stage 1 | This experiment |
| --- | --- | --- |
| Vision tower | CLIP ViT-L/14, frozen, 256 patch features | CLIP ViT-B/32, frozen, 49 patch features |
| Language model | Vicuna 13B, frozen | Qwen2.5-0.5B, frozen, fp32 |
| Connection | one linear layer | one linear layer (768 to 896, with bias) |
| Training data | 595K image-caption pairs; the answer is a whole caption | 6,400 CIFAR-10 images; the answer is the class name |
| Loss | cross-entropy over every answer token | softmax over the first tokens of the 10 class names only |
| Optimization | Adam, lr 2e-3, batch 128, cosine decay, 3% warm-up | same optimizer and learning rate, batch 32, 200 steps, each image seen once |
| Evaluation | LLaVA-Bench and others | 1,000 CIFAR-10 test images; the class with the highest first-token probability |

Environment: Apple M2 Max (64 GB, MPS backend), Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0. Qwen2.5-0.5B is Apache-2.0 licensed; the CLIP weights are `openai/clip-vit-base-patch32` from Hugging Face (OpenAI's CLIP repository is MIT-licensed; the model card itself declares no license), and CIFAR-10 comes from `uoft-cs/cifar10` (the dataset card lists the license as unknown).

**Audit the gradients before trusting a curve.** The first version of this experiment did not learn at all on MPS: accuracy stayed at chance while the loss looked normal. That version used cross-entropy over the whole vocabulary, with multi-token answers and padding inside the batch. Comparing with the CPU located the problem in MPS: when backpropagating through a 151,936-row vocabulary matrix, at batch sizes of 16 and above the gradient disagrees with the one computed on the CPU, while the forward values agree, so the loss values look reasonable and the training is wrong. The final version makes two changes. The loss is a softmax over the first tokens of the 10 class names only (just 10 rows of the vocabulary matrix), and the script opens with a gradient audit: it computes the gradient once on MPS and once on the CPU for the same images and the same initial projection and compares them by cosine (section 0 of the output). On this machine, with this configuration, the whole-vocabulary version scores a cosine of 0.9253 instead of 1, and the ten-class version scores 1.0000. I have not tried other machines or versions, so for any experiment that trains on MPS I recommend running such an audit first.

<details>
<summary>Full code (about 212 lines)</summary>

```python
"""A scaled-down LLaVA stage 1: freeze CLIP and the language
model, train one linear projection so the model names CIFAR-10 images"""
import copy
import io
import math
import random
import sys

import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import snapshot_download
from PIL import Image
from transformers import (AutoModelForCausalLM, AutoTokenizer, CLIPModel,
                          CLIPProcessor)
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
DEV = sys.argv[1] if len(sys.argv) > 1 else "mps"
STEPS = int(sys.argv[2]) if len(sys.argv) > 2 else 200
BATCH, LR, N_TRAIN, N_TEST, SEEDS = 32, 2e-3, 10_000, 1_000, (0, 1, 2)
LM, VIS = "Qwen/Qwen2.5-0.5B", "openai/clip-vit-base-patch32"
CLASSES = "airplane automobile bird cat deer dog frog horse ship truck".split()
PROMPT = "Question: what is in the picture?\nAnswer:"
SPACE = " "  # English class names follow a space
EVALS = (0, 10, 25, 50, 100, STEPS)

tok = AutoTokenizer.from_pretrained(LM)
lm = AutoModelForCausalLM.from_pretrained(
    LM, dtype=torch.float32, attn_implementation="eager").to(DEV).eval()
lm.requires_grad_(False)
clip = CLIPModel.from_pretrained(VIS).to(DEV).eval()
proc = CLIPProcessor.from_pretrained(VIS)
embed = lm.get_input_embeddings()
FIRST = [tok(SPACE + c).input_ids[0] for c in CLASSES]
assert len(set(FIRST)) == len(CLASSES), "first tokens must be distinct"
Q = tok(PROMPT, return_tensors="pt").input_ids

root = snapshot_download("uoft-cs/cifar10", repo_type="dataset",
                         local_files_only=True)

def load(split, n):
    t = pq.read_table(f"{root}/plain_text/{split}-00000-of-00001.parquet")
    t = t.slice(0, n).to_pydict()
    imgs = [Image.open(io.BytesIO(d["bytes"])).convert("RGB")
            for d in t["img"]]
    return imgs, torch.tensor(t["label"])

def grid(imgs, bs=250):
    """49 patch tokens from the layer before the last and from the last"""
    before, last = [], []
    for i in range(0, len(imgs), bs):
        px = proc(images=imgs[i:i + bs], return_tensors="pt").pixel_values
        with torch.no_grad():
            hs = clip.vision_model(pixel_values=px.to(DEV),
                                   output_hidden_states=True).hidden_states
        before.append(hs[-2][:, 1:].half().cpu())
        last.append(hs[-1][:, 1:].half().cpu())
    return {"before": torch.cat(before), "last": torch.cat(last)}

train_x, train_y = load("train", N_TRAIN)
test_x, test_y = load("test", N_TEST)
G_train, G_test = grid(train_x), grid(test_x)
del clip

def free():
    if DEV == "mps":
        torch.mps.empty_cache()

def last_state(model, proj, z):
    """[visual tokens][question] in; hidden state of the last position"""
    dev = proj.weight.device
    q = model.get_input_embeddings()(Q.to(dev)).expand(len(z), -1, -1)
    x = torch.cat([proj(z.to(dev).float()), q], dim=1)
    return model.model(inputs_embeds=x).last_hidden_state[:, -1]

def loss_of(model, proj, z, y, full):
    h = last_state(model, proj, z)
    dev = h.device
    cls = torch.tensor(FIRST, device=dev)
    if full:  # cross-entropy over the whole vocabulary
        return F.cross_entropy(model.lm_head(h), cls[y.to(dev)])
    # softmax over the ten class tokens only
    return F.cross_entropy(h @ model.lm_head.weight[cls].T, y.to(dev))

def accuracy(proj, z, y):
    hit = 0
    for i in range(0, len(z), 100):
        with torch.no_grad():
            h = last_state(lm, proj, z[i:i + 100])
            lg = lm.lm_head(h)
        hit += (lg[:, FIRST].argmax(1).cpu() == y[i:i + 100]).sum().item()
    free()
    return hit / len(z)

def train(kind, seed):
    torch.manual_seed(seed)
    proj = torch.nn.Linear(768, lm.config.hidden_size).to(DEV)
    opt = torch.optim.Adam(proj.parameters(), lr=LR)
    order = list(range(N_TRAIN))
    random.Random(100 + seed).shuffle(order)
    zs, curve, losses = G_train[kind], [], []
    for s in range(STEPS + 1):
        if s == STEPS or (seed == 0 and s in EVALS):
            curve.append((s, accuracy(proj, G_test[kind], test_y)))
        if s == STEPS:
            break
        lr = LR * min(1, (s + 1) / (0.03 * STEPS)) * (
            0.5 * (1 + math.cos(math.pi * s / STEPS)))
        for g in opt.param_groups:
            g["lr"] = lr
        idx = order[s * BATCH:(s + 1) * BATCH]
        loss = loss_of(lm, proj, zs[idx], train_y[idx], full=False)
        opt.zero_grad()
        loss.backward()
        opt.step()
        losses.append(loss.item())
        if s % 50 == 49:
            free()
    return proj, curve, sum(losses[-10:]) / 10

def probe(kind):
    """Reference: a linear classifier on the mean feature, no language model"""
    torch.manual_seed(0)
    a = G_train[kind].float().mean(1)
    b = G_test[kind].float().mean(1)
    mu, sd = a.mean(0), a.std(0) + 1e-6
    a, b = (a - mu) / sd, (b - mu) / sd
    clf = torch.nn.Linear(768, 10)
    opt = torch.optim.Adam(clf.parameters(), lr=1e-2)
    for _ in range(300):
        opt.zero_grad()
        F.cross_entropy(clf(a), train_y).backward()
        opt.step()
    return (clf(b).argmax(1) == test_y).float().mean().item()

# --- 0. Audit gradients first: one batch, one projection, MPS and CPU ---
print(f"{LM} frozen; CLIP ViT-B/32 frozen; {STEPS * BATCH:,} of "
      f"{N_TRAIN:,} training images (no repeats)")
print(f"test {N_TEST:,}; {BATCH} images per step, {STEPS} steps, lr {LR}")
print("first tokens of the class names are distinct: "
      + " ".join(f"{c}={t}" for c, t in zip(CLASSES, FIRST)))
lm_cpu = AutoModelForCausalLM.from_pretrained(
    LM, dtype=torch.float32, attn_implementation="eager").eval()
lm_cpu.requires_grad_(False)
print(f"\n0. Gradient audit ({BATCH} images, projection gradient, MPS vs CPU)")
for full, name in ((True, "cross-entropy over the vocabulary"),
                   (False, "softmax over ten class tokens")):
    torch.manual_seed(0)
    p_cpu = torch.nn.Linear(768, lm.config.hidden_size)
    p_dev = copy.deepcopy(p_cpu).to(DEV)
    z, y = G_train["before"][:BATCH], train_y[:BATCH]
    grads = []
    for model, p in ((lm_cpu, p_cpu), (lm, p_dev)):
        loss_of(model, p, z, y, full).backward()
        grads.append(p.weight.grad.cpu().flatten())
    cos = F.cosine_similarity(grads[0], grads[1], dim=0).item()
    cos = min(cos, 1.0)
    print(f"   {name:<30} {cos:+.4f}")
del lm_cpu, p_cpu, p_dev, grads
free()

# --- 1. Two kinds of visual features, one linear projection each ---
runs = {(k, s): train(k, s) for k in ("before", "last") for s in SEEDS}
print("\n1. Test accuracy over training steps (seed 0; guessing is 10%)")
print(f"   {'step':>5}" + "   before-last        last")
for i, (s, a) in enumerate(runs["before", 0][1]):
    print(f"   {s:>5}   {a:>9.1%}   {runs['last', 0][1][i][1]:>9.1%}")

print(f"\n2. After {STEPS} steps, three seeds (init and sample order differ)")
for k, name in (("before", "before-last"), ("last", "last")):
    acc = [runs[k, s][1][-1][1] for s in SEEDS]
    loss = [runs[k, s][2] for s in SEEDS]
    print(f"   {name:<12}" + " ".join(f"{a:.1%}" for a in acc)
          + f"   {sum(acc) / 3:.1%}"
          + f"   train loss, last 10 steps {sum(loss) / 3:.3f}")
print("   Linear probe on mean features (no language model): "
      + "before-last " + f"{probe('before'):.1%}"
      + ", last " + f"{probe('last'):.1%}")

# --- 3. What the projected visual tokens look like ---
print("\n3. Projected tokens against word embeddings (before-last, seed 0)")
proj = runs["before", 0][0]
W = F.normalize(embed.weight.float(), dim=-1)
n_img, hit_nn, top = 200, 0, []
for i in range(n_img):
    with torch.no_grad():
        v = proj(G_test["before"][i].to(DEV).float())
        cos = F.normalize(v, dim=-1) @ W.T
    top.append(cos.max(1).values.mean().item())
    hit_nn += int((cos.argmax(1) == FIRST[test_y[i]]).any())
gen = torch.Generator().manual_seed(5)
rnd = torch.randn(49, W.shape[1], generator=gen).to(DEV)
base = (F.normalize(rnd, dim=-1) @ W.T).max(1).values.mean().item()
v_norm = proj(G_test["before"][:200].to(DEV).float()).norm(dim=-1).mean().item()
print(f"   Mean norm of projected tokens {v_norm:.2f}; of word embeddings "
      f"{embed.weight.norm(dim=-1).mean().item():.2f}")
print(f"   Cosine to the nearest word: {sum(top) / n_img:.3f} "
      f"(random directions {base:.3f})")
print(f"   Images (of {n_img}) with a token whose nearest word "
      f"is the class name's first token: " f"{hit_nn}")
```

</details>

Output (`python exp_llava_align.py mps 200`, one complete run):

```text
Qwen/Qwen2.5-0.5B frozen; CLIP ViT-B/32 frozen; 6,400 of 10,000 training images (no repeats)
test 1,000; 32 images per step, 200 steps, lr 0.002
first tokens of the class names are distinct: airplane=42924 automobile=34428 bird=11958 cat=8251 deer=38049 dog=5562 frog=59881 horse=15223 ship=8284 truck=10855

0. Gradient audit (32 images, projection gradient, MPS vs CPU)
   cross-entropy over the vocabulary +0.9253
   softmax over ten class tokens  +1.0000

1. Test accuracy over training steps (seed 0; guessing is 10%)
    step   before-last        last
       0        8.9%       10.6%
      10       58.1%       47.0%
      25       87.2%       85.3%
      50       91.8%       90.0%
     100       92.6%       91.6%
     200       94.2%       94.4%

2. After 200 steps, three seeds (init and sample order differ)
   before-last 94.2% 91.0% 94.9%   93.4%   train loss, last 10 steps 0.277
   last        94.4% 93.3% 92.5%   93.4%   train loss, last 10 steps 0.238
   Linear probe on mean features (no language model): before-last 93.2%, last 93.1%

3. Projected tokens against word embeddings (before-last, seed 0)
   Mean norm of projected tokens 17.46; of word embeddings 0.46
   Cosine to the nearest word: 0.121 (random directions 0.139)
   Images (of 200) with a token whose nearest word is the class name's first token: 0
```

*Figure: Figure 3: Results of the scaled-down stage 1 on CIFAR-10 (Qwen2.5-0.5B frozen, CLIP ViT-B/32 frozen, only a 768-to-896 linear projection trained; 1,000 test images). Numbers come from one complete run of this page's script.*

**How to read the numbers.**

- **It learns quickly.** On the seed-0 curve, the before-last-layer features start at 8.9% at step 0 (a randomly initialized projection, close to the 10% of guessing), reach 58.1% after 10 steps, 87.2% after 25, 92.6% after 100 and 94.2% after 200. Features from the last layer start more slowly (47.0% at step 10, 85.3% at step 25) and reach 94.4% at step 200. There is only one curve (seed 0); the early gap (58.1% against 47.0% at step 10) is much larger than the differences at step 200, but it comes from a single run, so treat it as suggestive.
- **The two layers end up the same within noise.** Over three seeds the before-last layer reaches 94.2%, 91.0% and 94.9% (mean 93.4%) and the last layer 94.4%, 93.3% and 92.5% (mean 93.4%). The two means are the same, and the before-last layer's own three seeds range from 91.0% to 94.9%, far wider than any gap between the means; on 1,000 test images an accuracy near 94% also has a binomial standard error under 1 point. In the paper's ablation the last layer is 0.96 points lower than the before-last layer (Table 8, ScienceQA). No difference can be resolved here, so this small experiment cannot be said to reproduce that ablation; it only shows the before-last layer starting faster.
- **The language model neither drags nor adds.** A linear probe trained directly on the mean of the same layer's features, with no language model, scores 93.2% and 93.1%. Passing through the frozen language model with one linear projection gives 93.4% and 93.4%, slightly higher but within the noise. The ceiling for this task is set mostly by CLIP's features, and the language model's role is to read them out.
- **The projected visual tokens look like no word.** Their mean norm is 17.46 against 0.46 for word vectors, and the cosine to the nearest word vector is 0.121 against 0.139 for random directions. Among the 200 test images checked, none has a visual token whose nearest word is the first token of its class name. The paper describes the projection as putting visual features into the language model's word-embedding space; here what goes in lies outside the word vectors, closer to a soft prompt the language model can read than to a translation into words. This says something only about a 0.5B language model with a 768-to-896 linear layer, so do not extrapolate it to LLaVA.

**What this experiment does not show.** It trains no stage 2 and has no instruction following or multi-turn dialogue; the answer is a class name chosen from ten, not a free-form sentence. CIFAR-10 images are only 32 by 32 pixels and are upscaled before they go into CLIP, and the sample is 6,400 training images and 1,000 test images with just three seeds. What it does show is only that the core idea of stage 1 holds at small scale: between a frozen vision tower and a frozen language model, one linear layer is enough for the latter to read the former.

## Limitations and follow-ups

The shortcomings the paper admits are still common in multimodal models today:

- **Detail and high resolution.** Failing to read the ramen shop's name or to recognize the yogurt brand calls for higher-resolution input and broader knowledge. The paper uses a 224-pixel vision tower; LLaVA-1.5 moved to a 336-pixel ViT-L/14, and later work went on to dynamic resolution, where the number of tokens follows the image size (see [Multimodal LLMs](https://dmxsf.com/en/wiki/multimodal/multimodal-llms/)).
- **The "bag of patches".** Answering yes about strawberry-flavored yogurt shows that the model sometimes just strings together the scattered objects it sees without understanding how they relate. This is tied to where the data comes from: the training data is generated from captions and bounding boxes, so its information comes only from those two symbolic representations.
- **Evaluation.** LLaVA-Bench is small, noisy and judged by GPT-4 (see above); later multimodal papers moved more toward academic benchmarks and larger human-evaluated sets.

Follow-up work went in several directions. **A stronger recipe**: LLaVA-1.5 (Liu et al., October 2023) made only two simple changes, a two-layer MLP projection and a 336-pixel CLIP ViT-L/14, and added academic VQA data with response-format prompts; its final 13B model uses 1.2M public data samples, trains in about a day on one 8-A100 node, and reached the best results of its time on 11 benchmarks. **More elaborate connectors**: Flamingo's gated cross-attention and BLIP-2's Q-Former are comparisons the paper mentions itself; InstructBLIP adds instruction tuning along BLIP-2's Q-Former route. **Toward actions**: [OpenVLA](https://dmxsf.com/en/blog/openvla-an-open-source-vision-language-action-model/) and similar work continue to train the same "vision encoder, projection, language model" three-part design into a model that outputs robot actions.

## What to take away from this paper

1. **Data matters more than architecture.** The architecture is three off-the-shelf parts and a linear layer; the real novelty is how to produce instruction data for images: use a symbolic representation so that a strong text-only model can annotate for you. It is also the blind spot: all the information in the data comes from captions and boxes.
2. **Each of the two stages solves one problem.** Stage 1 trains a small projection that places visual features in a space the language model can read; only stage 2 teaches the model how to answer about a picture. Shrinking the trainable parameters to a minimum is what lets stage 1 work with the simplest data, image-caption pairs.
3. **Know which score you are reading.** LLaVA-Bench is a relative score against a GPT-4 reference over a few dozen questions, and the COCO benchmark shares its origin with the training data; the ScienceQA "new best" is an ensemble with GPT-4, and LLaVA alone did not beat MM-CoT Large.
4. **The paper's numbers are largely trustworthy, but check the brackets and the prose yourself.** Four brackets in Table 4 do not add up, "+29%" is in percentage points, and the ablation paragraph contradicts Table 8; none of these changes the main conclusion, but they are a reminder to go back to the raw tables when using the paper's numbers.

## Further reading

- Paper: [Visual Instruction Tuning](https://arxiv.org/abs/2304.08485); project page: [llava-vl.github.io](https://llava-vl.github.io).
- Follow-up: [Improved Baselines with Visual Instruction Tuning](https://arxiv.org/abs/2310.03744) (LLaVA-1.5); comparisons the paper mentions: [Flamingo](https://arxiv.org/abs/2204.14198), [BLIP-2](https://arxiv.org/abs/2301.12597), [InstructBLIP](https://arxiv.org/abs/2305.06500).
- The ScienceQA line: [Learn to Explain: Multimodal Reasoning via Thought Chains for Science Question Answering](https://arxiv.org/abs/2209.09513); [Multimodal Chain-of-Thought Reasoning in Language Models](https://arxiv.org/abs/2302.00923) (MM-CoT).
- On this site: [Multimodal LLMs](https://dmxsf.com/en/wiki/multimodal/multimodal-llms/); [CLIP walkthrough](https://dmxsf.com/en/blog/clip-learning-transferable-visual-models/); [ViT walkthrough](https://dmxsf.com/en/blog/vit-an-image-is-worth-16x16-words/); [InstructGPT walkthrough](https://dmxsf.com/en/blog/instructgpt-rlhf/); [LLaMA walkthrough](https://dmxsf.com/en/blog/llama-open-and-efficient-foundation-language-models/); [SFT data](https://dmxsf.com/en/wiki/post-training/sft-data/); [Evaluation statistics](https://dmxsf.com/en/wiki/evaluation/eval-statistics/).

## FAQ

### What is LLaVA and what is it made of?

LLaVA (Large Language and Vision Assistant) is an open multimodal model introduced in April 2023. It has three parts: a frozen CLIP ViT-L/14 vision encoder that turns an image into a grid of features, a trainable linear projection that maps those features into the language model's word-embedding space as visual tokens, and a Vicuna language model (13B in the paper's main model). The visual tokens are concatenated with the text instruction and the language model writes the answer autoregressively, as usual. Counted from the public configs, the vision tower has about 303 million parameters, the language model about 13.02 billion, and the projection only 5,248,000.

### What do the two training stages of LLaVA train?

Stage 1, feature alignment, freezes the vision encoder and the language model and trains only the linear projection on 595K image-caption pairs filtered from CC3M. Each sample is a random "describe the image briefly" instruction plus the original caption, with learning rate 2e-3, batch size 128 and one epoch. Stage 2 is end-to-end fine-tuning: the vision encoder stays frozen while the projection and the language model are trained together on 158K visual instructions (conversation, detailed description, complex reasoning), with learning rate 2e-5, batch size 32 and three epochs. The appendix reports about 4 and 10 hours on 8 A100 GPUs; counted from the configs, stage 1 trains only 0.039% of all parameters.

### How was LLaVA's visual instruction data made, and did GPT-4 see the images?

It did not see them. The paper used the text-only GPT-4. Each COCO image was first written down in two symbolic forms, its five captions and a set of boxes with class names and normalized coordinates, and GPT-4, prompted with a few hand-written seed examples, generated three kinds of data: 58K conversations, 23K detailed descriptions and 77K complex-reasoning samples, 158K in all. The seed examples are the only human annotation in the pipeline. In its own discussion of limitations the paper notes that LLaVA sometimes treats an image as a "bag of patches" and misses its overall semantics.

### Is LLaVA-Bench's 85.1% an accuracy?

No. LLaVA-Bench has a text-only GPT-4 act as the judge: it scores the candidate's answer and a reference answer from 1 to 10 each, and the benchmark reports the candidate's score relative to the reference, which is written by another text-only GPT-4 given the true captions and boxes. The COCO subset has 30 images and 90 questions generated by the same pipeline that produced the training data. On the In-the-Wild subset (24 images, 60 questions) the standard deviation of LLaVA's overall score across three inference runs is 2.0 points, against 0.3 points for judging one set of outputs three times, so a gap of a point or two should not be read as significant.

### How does LLaVA differ from LLaVA-1.5?

LLaVA-1.5 (Liu et al., October 2023) makes two simple changes to the original framework: the linear projection becomes a two-layer MLP and the vision encoder becomes a CLIP ViT-L/14 with 336-pixel input; it also adds academic VQA data with a response-format prompt. Its abstract states that the final 13B model uses only 1.2M public data samples, trains in about one day on a single 8-A100 node and reaches state-of-the-art results on 11 benchmarks, and it calls the original fully-connected connector "surprisingly powerful and data-efficient".
