Skip to content
ImagineWorld

Multimodal Systems, Tools, and Agents

node_idnode-book_building-frontier-llm-from-scratch_chapter-31-multimodal-systems-tools-and-agents
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num31
chapter_titleMultimodal Systems, Tools, and Agents
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 31 — Multimodal Systems, Tools, and Agents

Section titled “Chapter 31 — Multimodal Systems, Tools, and Agents”

The model built in this book reads and writes text. The assistants people actually use also see images, call tools, browse the web, and take multi-step actions — and Chapter 1 made the key claim that almost none of this lives in the language model itself. This chapter makes that concrete. It shows how perception is attached at the input, how tools and actions are attached at the output, and how a reasoning loop turns a text predictor into an agent. The engine is unchanged; what changes is what connects to it.

A vision-language model lets the transformer “see” by turning images into tokens it can attend to alongside text. An image encoder (usually a vision transformer) converts an image into a sequence of feature vectors; a small projector maps those into the model’s embedding space; and the resulting image tokens are simply concatenated with the text tokens and fed through the same transformer. From the language model’s perspective, an image is just more tokens. Figure 31.1 shows the wiring.

To the language model, an image is simply more tokens in the sequence.

Figure 31.1. A vision-language model. An image encoder and a projector turn an image into tokens in the model’s embedding space; these are concatenated with text tokens and processed by the same transformer. Perception is attached at the input — the core model is the one you already built.

amilies differ in how tightly this is integrated. An adapter approach (LLaVA-style, and broadly Qwen-VL and DeepSeek-VL) bolts a vision encoder onto a pretrained language model and trains mostly the projector — cheap and modular. Native early fusion (Llama 4) trains the model on mixed image-and-text tokens from the start, for tighter integration at higher cost. Either way, the attention, blocks, and objective are exactly those of Parts III and IV.

The same pattern extends. Audio is tokenized by a speech encoder and fed in as tokens; speech output is produced by a separate vocoder or audio model. As Chapter 1 stressed, generating images, video, and music is done not by the language model but by separate diffusion or flow models the assistant invokes — DALL·E, Sora, Suno, and the rest. The language model’s role in those cases is to understand the request and write a good prompt for the generative model; the pixels and audio come from elsewhere. Understanding new modalities is attached at the input; generating them is delegated to other models at the output.

Tools are attached at the output. The model is trained (during SFT and alignment) to emit a structured function call — typically JSON naming a tool and its arguments — whenever a task needs a capability it lacks. A surrounding harness detects the call, executes the real function, and feeds the result back into the context for the model to continue. The flow is simple:

user: What is 847 * 1293?
model: {"tool": "calculator", "args": {"expr": "847 * 1293"}} # emitted call
harness: runs the calculator -> 1095171 # real execution
model: 847 x 1293 = 1,095,171. # continues with the result

Interaction — a tool call: the model proposes, the harness executes

This single mechanism explains the whole capability list from Chapter 1. “Browsing the web” is a search tool; “running a Monte Carlo simulation from an HTML form” is a code tool that writes and executes JavaScript; “zip a file” is a shell tool. The model never gains these abilities internally — it learns when and how to ask for them, and a harness provides them. Reliable tool use is largely a matter of training the model to produce well-formed calls and to use their results sensibly.

An agent is what you get when tool use becomes a loop. Instead one call, the model alternates between thinking, acting (a tool call) and observing (the result), repeating until the task is done — reading a file, running code on it, seeing an error, fixing it, and trying again, autonomously. Table 31.1 shows the loop. The reasoning models of Chapter 25 are especially strong agents, because the same deliberation that solves a math problem — planning, checking, backtracking — is exactly what multi-step tasks require. Agents are the current frontier of applying language models, and they are built almost entirely from pieces in this book: a capable model, tool calling, and a reasoning loop around them.

StepWhat happens
Thinkthe model reasons about the goal and the next action
Actit emits a tool call (run code, search, read a file)
Observethe harness executes the tool and returns the result
Repeatloop until the task is complete or a budget is reached

Table 31.1 — The agent loop

Code reference — haotian-liu/LLaVA · Qwen-VL, DeepSeek-VL (modeling) · the ReAct / tool-use literature

LLaVA is the canonical adapter-style vision-language model; the Qwen-VL and DeepSeek-VL reports detail production multimodal training; and the ReAct line of work formalized the think-act-observe agent loop. All sit on top of the text model this book builds.

Perception, tools, and agency are all attachments to the engine you now understand from the inside. That leaves one final question — not how today’s models work, but where they are going. The closing chapter looks at the research frontier and what it means for the models that come after these.

31.5 Worked Example: Training the Vision Projector

Section titled “31.5 Worked Example: Training the Vision Projector”

The bolt-on pattern (Chapter 31) trains mainly the small projector that maps vision features into the language model’s embedding space, on image-caption pairs, with the language model frozen. Only the projector’s gradients matter:

for image, caption_ids in loader:
vis = projector(vision_encoder(patchify(image))) # -> hidden_size
tokens = concat(vis, embed(caption_ids))
logits = language_model(tokens) # LM weights are frozen
loss = F.cross_entropy(shift(logits), caption_ids)
loss.backward() # gradient reaches projector only
optimizer.step() # updates just the projector
# later stages unfreeze the LM for deeper multimodal grounding (Chapter 40)

Python — train only the projector, language model frozen

31.6 Connecting a Vision Encoder: The Full Path

Section titled “31.6 Connecting a Vision Encoder: The Full Path”

Section 31.1 sketched vision-language models; here is the actual forward path, which is simpler than its reputation. An image is encoded by a vision transformer into patch features, a learned projector maps those features into the language model’s embedding space, and the resulting image tokens are spliced into the text-token stream wherever an image placeholder appeared:

img_feats = vision_encoder(pixels) # [N_patch, d_vit]
img_tokens = projector(img_feats) # [N_patch, d_model]
embeds = text_embed(input_ids) # [T, d_model]
embeds[image_positions] = img_tokens # splice at the placeholders
logits = language_model(inputs_embeds=embeds)

Python — vlm/forward.py: image tokens into the text stream

Everything downstream of the splice is the unchanged decoder of Part III: once the image is a sequence of vectors in the model’s embedding space, attention treats it exactly like text. This is why the dominant recipe (Section 31.1) freezes a pretrained vision encoder and a pretrained language model and trains only the small projector first — the projector’s sole job is to learn the coordinate change from vision space into language space, after which the language model’s existing competence does the rest.

31.7 Worked Example: How Many Tokens Is an Image?

Section titled “31.7 Worked Example: How Many Tokens Is an Image?”

Images are not free in the context budget; each becomes a block or tokens whose count follows directly from the patch grid. A vision transformer with a 14×14 patch size processing a 336×336 image produces a 24×24 grid — 576 patch tokens — before a single word of the prompt. High-resolution handling multiplies this: a model that tiles a large image into, say, four crops plus a thumbnail encodes five times as many, climbing toward three thousand tokens for one picture.

The consequence shapes both cost and design. At 576 tokens an image is comparable to a substantial paragraph of text; at 3,000 it rivals several pages, and it consumes KV cache (Section 27.7) on the same terms. This is why production VLMs invest in token-efficient connectors — pooling patch features, selecting salient regions, or compressing the grid — and why “how many images, at what resolution” is a real capacity-planning question for any multimodal deployment, not an afterthought.

An image is a paragraph (or a chapter) Patches become tokens one-for-one. A single high-resolution, tiled image can cost more context than the text prompt around it — budget vision tokens as deliberately as you budget words.

Multimodality reaches past vision to sound, and the recipe is the same one Section 31.6 used for images: turn the modality into tokens the transformer can process. For audio, a neural codec learns to compress a waveform into a sequence of discrete codes — effectively a tokenizer for sound — and those codes drop into the same stream as text:

# a neural codec turns a waveform into discrete audio codes
audio_tokens = codec.encode(waveform) # sequence of codes
# fold into one stream with text, exactly as with image tokens
seq = text_tokens(prompt) + audio_tokens

Python — audio/tokens.py: audio as discrete tokens (illustrative)

Once sound is a sequence of discrete tokens, the same transformer machinery handles it: a model can transcribe (audio tokens in, text out), synthesize speech (text in, audio tokens out, decoded back to a waveform by the codec), or hold a spoken conversation natively without ever converting to text in between. This is the unifying lesson of the whole multimodal frontier (Section 40.5): vision, audio, and text are not fundamentally different problems to the architecture — they are different tokenizations feeding one sequence model. The encoder or codec that turns each modality into tokens is the only modality-specific piece; everything after it is the decoder this book has built.

Every modality is a tokenization A neural codec makes audio a sequence of discrete codes, just as patches make an image a sequence. Transcription, speech synthesis, and spoken dialogue then run on the same transformer — the modality lives in the tokenizer, not the model.

Section 31.6 turned an image into tokens, but glossed a crucial difficulty: a vision encoder produces features in its own representation space, while the language model expects vectors in its embedding space, and the two do not naturally match. Bridging them is the central problem of building a multimodal model, and the bridge is a deliberately trained connector:

img_features = vision_encoder(image) # vision space
img_tokens = projector(img_features) # mapped to LLM space
seq = torch.cat([img_tokens, text_embeds]) # one sequence

Python — mm/connector.py: projecting vision features into the LLM space

The projector — typically a small multilayer perceptron — learns to map vision features into vectors the language model can consume as if they were ordinary token embeddings. Training this alignment is usually staged: both the vision encoder and the language model are first frozen, and only the projector is trained on image-text pairs, so it learns the translation between spaces without disturbing either pretrained component; an optional end-to-end fine-tune then lets the whole system co-adapt. This connector is small and unglamorous, but it is the crux of the entire multimodal model — it is what lets the language model “understand” image features as though they were words, and the quality of the alignment it learns largely determines whether the model genuinely reasons over the image or merely captions it. The same pattern — encoder, projector, shared sequence — recurs for audio (Section 31.8) and is the structural blueprint for the any-to-any models of Section 40.7.

A small projector bridges two spaces Vision and language live in different representation spaces; a trained projector maps image features into the LLM’s embedding space, usually with both pretrained models frozen. That modest connector is what makes a multimodal model actually multimodal.