llm.guideChapter 12Multimodal

Multimodal

Images as tokens, OCR versus VLMs, vision hallucination and production pipelines.

Part 3: Building with LLMs. 10 sections, about 15 minutes.

8 × 8: 98%64 pixels4 × 4: 91%16 pixels2 × 2: 62%4 pixels
8 × 8: 98%64 pixels4 × 4: 91%16 pixels2 × 2: 62%4 pixels
One handwritten digit at three resolutions, with the test accuracy of a small vision model trained at each. What is lost in downscaling is lost before the model looks.

Models that take images, audio and video are not a different kind of system. The input is turned into tokens and enters the same transformer, and everything you know about context, cost and hallucination carries over. What is new is how lossy that conversion is, how many tokens it produces, and how hard it is to see what the model could not see.

The experiments here train a small vision transformer on 1,797 handwritten digits, each 8 by 8 pixels, using the engine from Chapter 7. Token rules quoted from provider documentation were checked in November 2026.

12.1Images as tokens

Patches in, vectors out, then the same transformer.

A transformer takes a sequence of vectors. Text becomes one through a tokenizer and an embedding table. An image becomes one by being cut into a grid of small squares, called patches. Each patch’s pixel values are multiplied by one learned matrix to produce a vector, and a position embedding says where in the grid it came from. From there on, the model is the one you already know.

image, cut into2 × 2 patches16 patches in reading orderone linear layer16 token vectors, plus positionthe transformer of Chapter 7
Figure 12.1 A real digit from the dataset becoming sixteen tokens. The only new component is the linear layer.

That is the whole of a vision transformer, or ViT. To check that nothing else is needed, I built one from Chapter 7’s code: the same attention, the same blocks, with the token embedding replaced by a patch projection and the output read from the last position as one of ten digit classes. Trained on 1,400 digits for 700 steps, about nine seconds, it classifies 97.7% of 397 unseen digits correctly.

0%50%100%0200400600test accuracytraining steps16 tokens per image: 97.7%64 tokens per image: 90.9%
0%50%100%0200400600test accuracytraining steps16 tokens: 98%64 tokens: 91%
  • 16 tokens per image (2 × 2 patches)
  • 64 tokens per image (single pixels)
Figure 12.2 Real training runs. The same model with the image cut two ways. More tokens per image did not help here; section 12.2 says why.

Common take“The model sees the image.”

Sharper take“The model attends over a grid of patch vectors. It sees at the resolution the patches kept, and the gap between that and the original is where my bugs will be.”

12.2From CNNs to CLIP

How vision encoders learned to line up with language.

Three steps led from the convolutional networks of section 4.6 to the vision side of a current model.

  • The vision transformer (2020) showed that patches and plain attention can replace convolutions. It came with a condition: it beat convolutional networks only after pretraining on hundreds of millions of images. Convolutions build in the assumption that nearby pixels belong together; a transformer has to learn it.
  • CLIP (2021) connected images to language. Two encoders, one for images and one for text, were trained on 400 million image–caption pairs so that each image’s vector lands close to its own caption’s vector and far from the others. This is contrastive training. The result is an image encoder whose outputs already mean something in language terms, and a shared space in which you can search images with text (Chapter 14).
  • The projector. To give a language model sight, take a pretrained vision encoder, pass its patch vectors through a small trained network that maps them into the language model’s embedding space, and place them in the sequence beside the text tokens.
ImageVision encoderProjectorimage tokenstext tokensLanguage model
Figure 12.3 A vision-language model. There is no separate component that answers questions about pictures: image tokens sit in the same context as text and are attended to by the same layers.

How finely should an image be cut? I ran the digit model at four patch sizes.

Patch sizeTokens per imageTest accuracyTraining time
Single pixels6490.9%55 seconds
2 × 2 pixels1697.7%9 seconds
4 × 4 pixels498%3 seconds
8 × 8, the whole image199.5%1 second

On this small dataset, larger patches won, and the 64-token model was both the slowest and the least accurate. That is the vision transformer’s condition seen in miniature: finer patches preserve more detail, but they need far more data and compute before that detail pays off. Production models use patches of around 14 to 28 pixels and many of them per image, backed by training sets large enough to justify it.

Common take“More image tokens means the model sees better.”

Sharper take“More tokens carry more detail and cost more to process. Whether the detail helps depends on the task and on how the model was trained. I test at the resolution I plan to pay for.”

12.3Image token math

An image is billed as input tokens, by its size.

Each provider converts image size to tokens by its own rule. Two documented examples:

  • Claude: about width × height ÷ 750 tokens. Images are first scaled down to fit a ceiling: 1,568 pixels on the long edge and about 1,568 tokens on most models, or 2,576 pixels and about 4,784 tokens on the recent models with high-resolution support.
  • Gemini: 258 tokens for an image up to 384 pixels on each side. Larger images are cut into 768-pixel tiles at 258 tokens per tile.

Under the first rule:

ImagePixelsTokens on most modelsTokens on high-resolution models
Thumbnail400 × 300160160
Resized photo800 × 600640640
Square image1,024 × 1,0241,3981,398
Full-HD screenshot1,920 × 1,0801,5682,765
Phone photo, 12 megapixels4,032 × 3,0241,5684,784

The bottom rows are the ones to notice. A phone photo is scaled down on the provider’s side before the model sees it, so you upload twelve megapixels and are billed, and answered, for about one. Three production facts follow.

  • Images are input tokens. They lengthen the wait before the first output token, like any long prompt, and a few images per request add up quickly.
  • Resize before you upload, to the smallest size that keeps the detail the task needs. A support product receiving 20,000 images a day at $3 per million input tokens spends about $2,820 a month on full-size photos and about $1,150 if it resizes them to 800 × 600 first.
  • Images in history are re-sent. A conversation carrying five screenshots pays for all five again on every turn (section 11.1). Once an image has been discussed, replace it with a sentence describing it.
01,5684,7840.10.5212tokens per imagemegapixels, log scalecap ≈ 4,784cap ≈ 1,56812 MP photo
01,5684,7840.10.5212tokens per imagemegapixels, log scale
  • most models
  • high-resolution models
Figure 12.4 Computed from the documented rule, width × height ÷ 750 up to a ceiling. Past the ceiling the provider scales the image down, so more pixels stop costing more and stop adding detail.

Common take“Sending the full-resolution photo gives the best results.”

Sharper take“The provider scales it down before the model sees it. I resize on my side to the size the task needs, so I control what is kept and I don’t pay to upload pixels that get thrown away.”

12.4Resolution

Detail lost before the model looks cannot be recovered.

Resizing saves money until it removes something the task depends on. The figure at the top of the chapter measures that. I shrank every digit to 4 × 4 and to 2 × 2 pixels and trained the same model on each version.

Image resolutionTest accuracy
8 × 8 pixels97.7%
4 × 4 pixels90.9%
2 × 2 pixels62.5%

No prompt and no larger model would win those points back, because the information is no longer in the input. The same thing happens in production with small text. A page of dense print, scaled down to fit a token ceiling, can leave each character only a few pixels tall, smaller than one patch. The model then answers from blurred shapes and from what such a page would usually say.

The remedy is a resolution check on the detail that matters. Work out how many pixels tall the smallest important text will be after scaling. If it is under about twenty pixels, crop the region of interest and send the crop at full size, or split the page into tiles. The high-resolution support in recent models moves the limit up, at about three times the token cost per image.

Common take“The model is bad at reading invoices.”

Sharper take“After scaling, the digits on these invoices are eight pixels tall. I crop the totals box and send it at full size before I conclude anything about the model.”

12.5Capability map

What vision models do well and badly.

Before designing around a vision model, place the task on a map like this one. The ratings are working judgments, not benchmarks, and they shift with each model generation; the reasons change more slowly.

TaskReliabilityWhy
Reading clean printed textHighHeavily represented in training; in effect, built-in text recognition
Describing scenes, objects and charts in wordsHighWhat image–caption training teaches directly
Layout: which label belongs to which boxGoodAttention over patch positions handles it, roughly
HandwritingMixedLegible writing is fine; dense scrawl fails without warning
Small text or fine digits at low resolutionPoorDetail smaller than a patch is gone before attention runs
Counting many objectsPoorAttention blends; counting needs exact enumeration
Exact positions and measurementsPoor, improving in models trained to operate interfacesThe model reasons in grid cells, not pixels
Identifying real peopleDeclinedA policy set in post-training, not a limit of ability

The poor rows matter most, because they do not fail visibly. Ask how many items are in a photo and you will get a number. The rule that follows: where reliability is good or better, a vision model alone may do; where it is poor, pair the model with a deterministic tool, such as text recognition, an object detector or ordinary code, that does the exact part.

PoorMixedGoodHighReading clean printed textDescribing scenes and chartsLayout: which label goes whereHandwritingSmall text at low resolutionCounting many objectsExact positions and measurementsWorking judgments, not benchmarks. Identifying real people is declined by policy, not by ability.
Figure 12.5 The table as a heat map. The orange column is where to design around the model, since those failures look like confident answers.

Common take“It described the photo perfectly, so it can count the parts in it.”

Sharper take“Describing and counting are different skills with different reliability. I check which row of the map my task is on before I choose an architecture.”

12.6Documents

Text recognition, a vision model, or both.

For documents there is an older tool, optical character recognition (OCR), which turns an image of text into characters with their positions. The claim that vision models have replaced it is half true.

NeedOCRVision model on the page imageBoth: page image plus OCR text
Exact charactersStrong: deterministic, character for characterA transcription that can silently “correct” a typo or a digitOCR anchors the exact strings
Positions of wordsStrong: a box for every wordWeakOCR supplies the boxes
Meaning: which amount is the total?Weak: a bag of positioned wordsStrong: reads layout as a person wouldThe model supplies the meaning
Handwriting, stamps, checkboxes, photos of documentsOften failsUsableThe model handles them
Same input, same outputYesNot guaranteedExact strings are stable; interpretation is the model’s
Cost per pageLow, or free when run locallyHigher, plus latencyBoth, justified on fields that must be right

The decision rule: high volume, exact strings and audit trails point to OCR; messy inputs and questions of meaning point to a vision model; regulated extraction, such as invoices, claims and identity documents, points to both. In the combined approach you send the page image and the OCR text in one prompt and require the model to quote the OCR string it used for each field. That quotation gives your code something to verify.

The failure this prevents is common. A pipeline that uses only a vision model demonstrates beautifully, and months later someone finds amounts where one digit was misread on a low-resolution scan: no error, no warning, a plausible number. A check that the extracted amount appears verbatim in the OCR text catches most such cases for a fraction of a cent per page.

OCR onlyPage imageOCRcharacters andboxesRulesfixed layoutsexact, cheap,blind to meaningVision model onlyPage imageVision modelreads the layoutJSONunderstands, may“correct” a digitBothPage imageand OCR textVision modelmeaning from theimageCheckstrings against OCRfor fields thatmust be right
Figure 12.6 The decision rule as three pipelines. Combining them costs both bills, so reserve the third lane for fields where a wrong digit is expensive.

Common take“OCR is obsolete. Just send the PDF pages as images.”

Sharper take“OCR gives exact strings and positions; the model gives meaning. For fields that must be right I use both and make the model cite the OCR text.”

12.7Vision hallucination

Confident descriptions of what was never legible.

Three facts from earlier chapters combine into the characteristic failure of vision models. The patch grid discards fine detail (section 12.4). The decoding loop must produce a plausible continuation and has no built-in way to say “illegible” (section 2.9). And post-training rewards fluent, detailed answers (Chapter 9). Together they produce a confident description of something that was not readable, or not there.

Typical forms: a blurred serial number read out as a specific, wrong serial number; a chart with unlabeled axes given invented values; a nearly blank page described as a form. The danger is greater than with text. When a text answer is wrong, a person can reread the source. With an image, the evidence was degraded before the model saw it, and nobody downstream can tell that the digits were eight pixels tall.

Fix, weakest firstHow much it does
An instruction: “describe only what you can clearly see”A mild nudge. Do not rely on it
A legibility field in the schema: clear, partial or illegible, per extracted valueUseful: it gives the model an allowed way to say it cannot read something
A resolution check, with crop-and-zoom for small detailFixes the cause for fine-detail failures
Grounding in deterministic extraction: OCR, barcode or detector output in the prompt, with verbatim citation requiredThe largest single improvement
Verification: format, range and checksum rules, with human review of low-confidence fieldsCatches what remains; standard at scale

Common take“I told it to say ‘unclear’ when it can’t read something.”

Sharper take“An instruction is the weakest fix. I give it a legibility field to fill, make sure the detail survives scaling, ground exact values in OCR, and verify them in code.”

12.8Screenshots and interfaces

Reading a screen is easy, acting on it is hard.

Screenshots show up in two places: support, where a user sends a picture of an error, and agents that operate software by looking at it. The capability map explains what to expect. Reading a screen, the error text, which page it is, what has been filled in, is reliable. Acting on it needs exact positions, the weakest row of the map.

The failure compounds. An agent told to press a button may choose a point some distance from it. The click lands elsewhere, the screen changes, and the next decision is made from a state nobody intended. Systems that work in production reduce the need for coordinates:

  • Use structure where it exists. A browser exposes its page structure and accessibility tree. “Click the element with this identifier” replaces a guess at a position, which is why browser agents are more reliable than agents working from raw screenshots.
  • Set-of-marks prompting. Draw numbered boxes on the clickable elements before sending the screenshot. The model answers “click 7”, turning a coordinate problem into a choice among labels.
  • Check after acting. Take a new screenshot after every action and confirm the expected change before continuing.

The cost follows from section 12.3: one screenshot per step, re-sent as history, for as many steps as the task takes. Part 5 returns to this.

CheckoutEmailCard numberExpiryCVCSave this cardBackPay now1234567Asked: “pay for the order”the screenshot goes in witha number on every controlThe model answers “click 7”a choice among labelsYour code maps 7 to the element and clicksits center, then takes a new screenshotto confirm the page changed as expected.
Figure 12.7 Set-of-marks prompting on a mock form. The coordinate problem, the weakest row of the capability map, becomes a multiple-choice question.

Common take“It read the screen correctly, so it can use the application.”

Sharper take“Reading is the strong skill and pointing is the weak one. I give the agent identifiers or numbered marks to choose from, and I verify the screen after each action.”

12.9Audio and video

More tokens per second than you expect.

Sound and moving pictures follow the same pattern: an encoder turns the signal into a sequence of vectors, and the sequence goes into the model. The token counts are the thing to know. Google’s documentation for Gemini gives fixed rates: 32 tokens per second of audio and 263 tokens per second of video, which is sampled at one frame per second.

LengthAs audioAs video
1 minute1,920 tokens15,780 tokens
10 minutes19,200 tokens157,800 tokens
1 hour115,200 tokens946,800 tokens

An hour of video is close to a million tokens, enough to fill the largest context windows on its own. Three practices follow.

  • Transcribe when the words are what matter. An hour of speech is about 115,000 audio tokens but only around 12,000 tokens as a transcript. Speech-to-text first, then a text model, is far cheaper.
  • Use native audio when the sound matters. A transcript drops tone, emphasis, hesitation and who is speaking over whom. Models that take audio directly keep them. Chapter 22 covers the trade for voice agents.
  • Sample video deliberately. One frame per second misses fast action and wastes tokens on a static slide. Pick frames at scene changes, or lower the per-frame resolution when detail is not needed.

Common take“The model can watch the whole recording.”

Sharper take“At about 263 tokens a second, an hour of video is nearly a million tokens. I transcribe when I need the words, sample frames when I need the pictures, and send raw audio only when tone carries the meaning.”

12.10The production pipeline

Where the model call sits, and what surrounds it.

StageWhat happensWhy
IntakeCheck file type and size; strip metadata such as locationSafety, and privacy the user did not think about
NormalizeResize to a chosen resolution; log the final dimensionsCost control, and a record for when accuracy shifts
TriageA small model or simple rules: blank? duplicate? document, photo or screenshot?Rejecting junk before the expensive call saves more than any prompt change
RouteDocuments to OCR plus model; photos to the model; screenshots with page structureEach type has a different weak point
Model callSchema-enforced output with legibility fieldsSections 11.4 and 12.7
ValidateFormat, range and cross-checks against OCR; a review queue for low confidenceThe model’s output is a claim, not a fact

Two further topics belong in any multimodal product plan.

Privacy. Images carry more than their subject: faces of bystanders, documents on a desk, a screen in the background, location in the file’s metadata. Decide what is redacted before the call, what is stored and for how long, and what your provider retains. A photo of an identity document deserves the same handling as the data printed on it.

Image generation. Producing images is a separate capability with its own models, usually priced per image and taking seconds per result. As a product feature it brings its own checklist: moderation of prompts and outputs, the policy on real people and brands, text inside images, which is still unreliable, and labeling generated content as such.

Intaketype, size,strip metadataNormalizeresize, logsizeTriageblank,duplicate,which kind?OCR + modelmodelpage structurerouteModel callschemaValidatereview queue
Figure 12.8 The table as a pipeline. The model call is one stage of six; the cheap stages before it save more than any prompt change, and the stage after it treats the output as a claim.

Common take“We send the upload to the vision model and return the answer.”

Sharper take“The model call is one stage of six. Intake, resizing, triage and routing come before it; validation and review come after; and the resize log is the first place I look when accuracy moves.”

Key takeaways

  • An image becomes tokens by being cut into patches, each mapped to a vector by one linear layer. After that it is the same transformer.
  • Built from Chapter 7’s code, that design classified 97.7% of unseen handwritten digits correctly.
  • A vision-language model is a vision encoder, a projector, and a language model reading image tokens beside text tokens.
  • Images are billed as input tokens by size, and large ones are scaled down first: a phone photo is billed at about 1,568 tokens on most Claude models.
  • Detail lost to downscaling cannot be recovered: accuracy fell from 97.7% to 90.9% to 62.5% as the digits were shrunk.
  • Vision models read and describe well, and count and point poorly. Pair them with deterministic tools for the exact parts.
  • For documents that must be right, send the page image and the OCR text together and require verbatim citation.
  • Vision hallucination is a confident answer about detail that did not survive the encoder. Give the model a way to say “illegible” and verify in code.
  • Audio is about 32 tokens a second and video about 263 on Gemini: an hour of video is nearly a million tokens.

Check your understanding

  1. Your receipt-scanning feature works well in testing. In production, totals are wrong on about 6% of receipts, always by one digit, and mostly on long receipts. Explain the likely cause from sections 12.3 and 12.4, and design a fix that does not depend on a better model.

    Answer outline

    Long receipts are tall images. Scaling them to fit the provider’s size limit shrinks each character, and on the longest ones the digits fall below the size a patch can represent, so the model fills in a plausible digit. Fix: compute the text height after scaling; for tall receipts, crop the region containing the total, or split the image into tiles, and send those at full size. Add OCR and require that the extracted total appears in the OCR text, check that line items sum to the total, and route failures to review. Log dimensions after resizing so that the relationship between size and error stays visible.

  2. A teammate proposes an agent that operates a desktop application by looking at screenshots and clicking at coordinates the model outputs. Using the capability map, predict how it will fail and propose two changes.

    Answer outline

    Reading the screen will work. Producing exact coordinates is the weak skill, so some clicks will miss, and each miss changes the screen in a way the plan did not expect, so errors compound over a multi-step task. Changes: avoid coordinates by using the application’s structure or accessibility interface where one exists, or draw numbered marks on the interactive elements so the model chooses a label; and verify after every action with a fresh screenshot, retrying or stopping when the expected change did not happen. Also budget for the tokens: one screenshot per step, re-sent as history.

  3. You are asked to build search over 2,000 hours of recorded meetings so that people can ask what was decided. Estimate the cost of sending the recordings to a model as audio and as video using the rates in section 12.9, and propose a design.

    Answer outline

    As audio: 2,000 hours × 115,200 tokens is about 230 million tokens for one pass. As video: 2,000 × 946,800 is about 1.9 billion. Neither can be sent per question. Design: transcribe every recording once with a speech-to-text model, keeping speaker labels and timestamps; that is roughly 24 million tokens of text in total. Index the transcripts for retrieval (Chapters 14 and 15) and answer questions from the retrieved passages, citing the meeting and time. Use the video only for the few cases that need what was on screen, by sampling frames around the cited timestamp.

Further reading

  • Jay Alammar and Maarten Grootendorst, Hands-On Large Language Models, chapter 9: vision transformers, CLIP, and connecting a vision encoder to a language model, with code.
  • Simon Prince, Understanding Deep Learning, section 12.10: transformers for images.
  • Dosovitskiy et al. (2020), “An Image is Worth 16x16 Words”, and Radford et al. (2021), “Learning Transferable Visual Models From Natural Language Supervision”: the ViT and CLIP papers.
  • Your provider’s vision documentation: the current token formula, size limits and supported formats.

↑↓ to move↵ to openesc to close