ELLMEngineering Large
Language Models
Download PDF

Chapter 56

Multimodal Representations: Images, Video, and Speech

On this page

A multimodal model must turn signals with space and time into a representation that a language system can learn from and act on. The encoder, alignment objective, sequence layout, and output contract are as important as the language backbone.

From pixels to language-model inputs

A common conceptual arrangement maps visual, audio, and text representations into language-model context. Position and time metadata preserve meaning across the interfaces; the exact encoder, projection, and fusion arrangement is model-specific.
Open full diagram ↗

A common conceptual arrangement maps visual, audio, and text representations into language-model context. Position and time metadata preserve meaning across the interfaces; the exact encoder, projection, and fusion arrangement is model-specific.

Begin with an image of height H and width W. A simple patch encoder divides it into patches of side p, producing approximately (H/p) × (W/p) tokens when dimensions divide evenly. Each flattened patch is projected into a vector; a vision transformer mixes these vectors with position information. A projector then maps visual features to the language model's hidden width. Insert them into a declared multimodal sequence or expose them through cross-attention.

In sequence insertion, visual embeddings occupy positions alongside text and consume backbone context/attention work. In cross-attention, text queries read a separate visual representation; visual-token count still changes cross-attention and encoder cost, but it is not necessarily identical to text KV growth. Early joint training can learn richer integration across modalities; it does not remove modality-specific preprocessing or alignment requirements. Visual Instruction Tuning is a primary example of connecting a vision encoder and language model for instruction-following behavior.

An original geometry example: 448 × 448 pixels with 16 × 16 patches gives 784 patch tokens before any pooling or special tokens. Doubling both image dimensions gives 3,136, four times as many. A merge that combines each 2 × 2 patch group reduces those counts to 196 and 784 respectively, while discarding some spatial detail. These are illustrative dimensions, not a particular model's processor configuration. Always calculate tokens after the actual resize, crop, patch, and merge policy.

Small text in a document creates a real tradeoff: aggressive downsampling can erase a decimal point before the language model sees anything. Increasing language-model size cannot recover pixels that were removed. Evaluate encoder resolution, OCR/visual parsing, and language interpretation separately.

Alignment objectives teach different capabilities

Contrastive alignment teaches matching. In a batch of N image/text pairs, compute an N × N matrix of scaled similarities. For each image, use cross-entropy to favor its paired text over other batch texts; commonly apply the reverse direction too. CLIP establishes this form of image-language representation learning. A high matching score is not itself a caption generator or a proof of visual reasoning.

For an original two-pair example, logits [2,0] give the correct first text probability exp(2)/(exp(2)+1) ≈ 0.881, with loss about 0.127. If two captions are both valid descriptions of the image, treating one as a negative creates a data/objective mismatch. Pair quality, duplicated images, and near-identical captions affect the training signal.

Generative alignment instead predicts text conditioned on visual features—for example a caption or answer. Instruction tuning adds varied questions and response formats. Training a projector with a frozen backbone differs from updating the vision encoder and language model together: their memory, compute, forgetting risk, and data needs differ. Evaluate visual grounding using image changes that should alter the answer, not only questions that a text-only prior can answer.

Video requires time, not only more images

A straightforward video pipeline samples frames, encodes each, and attaches timestamps before combining them with text or audio. Frame order alone is insufficient if sampling rates vary. The model must distinguish “frame 20” from “twenty seconds elapsed.” Temporal pooling can lower cost while losing short actions; adaptive sampling can retain events while adding another learned or heuristic decision.

At two frames per second, a one-minute clip contains 120 sampled frames. With 196 visual tokens per frame, that is 23,520 tokens before text, audio, and temporal compression. A 100-millisecond event can occur entirely between the sampled frames. No downstream reasoning method can guarantee recovery of an unobserved event. Evaluate temporal localization, ordering, and evidence coverage separately from a general video summary.

Grounded outputs need a coordinate contract. If a detector reports normalized (x,y) coordinates, first map them to the pixel frame defined by its output schema, then invert the recorded preprocessing transforms in reverse order to locate the point in the original image. For example, remove model-input padding before undoing resize, then add the crop's original-image offset. Rotation requires its corresponding inverse transform. A correct label with the wrong coordinate frame can trigger the wrong UI action. For video, preserve the source time base and dropped-frame policy similarly.

Speech has acoustic and linguistic time scales

Audio may enter as waveform-derived features such as a log-mel spectrogram, then pass through an audio encoder. For generation, a neural codec can compress audio into discrete code sequences that a model predicts before a decoder reconstructs a waveform. EnCodec is a primary neural-compression reference. Codec tokens are not words: several codebooks may describe different residual details of one audio frame.

Imagine a codec producing 50 frames per second with eight codebooks. A naive flattening has 400 code symbols per second; a model that predicts codebooks partly in parallel has a different sequential-step count. Neither count should be called text tokens per second. Separate semantic content, acoustic detail, frame rate, codec bitrate, model steps, and audible latency.

A cascaded assistant uses speech recognition, a text model, then text-to-speech. It offers clear component boundaries but can lose prosody and compound errors. A speech-text model can integrate these representations more directly. Moshi studies real-time speech-text dialogue; the Qwen3-Omni report describes a Thinker/Talker organization for multimodal understanding and speech generation. These systems motivate separating language decisions from waveform production while coordinating their streams.

The April 2026 Qwen3.5-Omni report describes hybrid-attention MoE components and adaptive text/speech alignment, addressing differing production rates between text and speech tokens. The underlying problem is general: if text outruns audio, buffering grows; if audio commits too early, later reasoning cannot retract spoken words cleanly. The book does not adopt the report's broad benchmark leadership claims as a universal ranking.

The September frontier has multiple interaction contracts

The Gemini 3.8 Audio card, listed as updated September 23 in the publisher's index, distinguishes Live and Live Extended Thinking from Flash TTS and Flash-Lite TTS. The Live variants accept audio, images, video, and text and return audio/text; the TTS variants take text and return audio. These are not interchangeable endpoints. The card also acknowledges hallucinations and occasional slowness or timeouts. A stronger reasoning mode must be evaluated against the interaction's silence and interruption budgets.

GPT-Live 1 documents full-duplex speech and delegation to a backend agent. Its own model card lists audio/text, not image/video input. The delegation guide separates managed Responses delegation from application-owned client delegation: the latter owns the context and decides which backend results to return. Thus a multimodal backend does not make the live voice model itself a vision model, and finishing a backend request does not establish that its answer was spoken.

Gemini Omni Flash's August card describes a different boundary: generating and editing video with audio from multimodal input. It notes remaining problems with edit consistency, complex motion, and accurate text rendering. Understanding a video, generating one, and maintaining a real-time conversation require different evaluations. Treat media-generation quality as an adjacent system concern; it cannot be reduced to text perplexity.

For a live assistant, model the conversation and the delegated task as two concurrent state machines. A correction can invalidate a pending task while audio continues. Attach a task generation number to each delegated result, check it before committing an action or speaking an answer, and record the last audio actually played. This is an application design principle, not a claim that any cited service supplies transactional cancellation automatically.

Worked concurrent interaction: correction during a tool call

Suppose a visual assistant is describing a diagram while looking up a cited specification. The following original timeline uses milliseconds from session start. Video timestamps identify evidence capture; audio times identify playback, not generation completion. The tool is read-only in this example.

Time Concurrent activity Host state and decision
0 User asks about the left connector; video frame V0 is captured Start task generation 41 and bind evidence V0
100 Specification lookup starts while the assistant begins a short acknowledgment Tool call carries generation 41; audio queue belongs to that response
200 New frame V200 shows the user pointing at the right connector Store capture time and provenance; do not silently replace V0 in the pending task
600 User interrupts: "I meant the right connector" Advance to generation 42; request old-tool cancellation and flush unplayed old audio
650 Playback stop is acknowledged; replacement lookup starts Record old audio actually heard through 650; bind generation 42 to V200 only if still relevant
900 Old lookup returns despite cancellation Reject generation-41 result for speaking or new actions
1200 Replacement lookup completes Validate generation 42 and evidence freshness, then queue its answer
1400 New answer begins playing Record delivery now; queued audio at 1200 was not yet heard

If a newer frame contradicts V200, refresh evidence or ask for clarification instead of pairing the correction with stale visual state. A playback device may continue briefly after a stop request; the 600-650 ms interval belongs in the interruption metric. Checks at enqueue time alone are insufficient: invalidate queued old-generation audio and check generation again at delivery.

For a write tool, generation validation must be coordinated with effect commitment through an authoritative gate, version precondition or fencing mechanism. A check followed by an unprotected network write leaves a race with the correction. If the external service already committed generation 41, mark that effect as committed and reconcile it; canceling speech cannot undo it. An endpoint without conditional execution requires an explicit ambiguous-outcome policy. This timeline describes an application contract, not a guarantee supplied by a particular live-model API.

Budget and evaluate the entire interaction

Time to first audio includes input buffering, encoder work, decision latency, codec generation, waveform decoding, and playback buffering. An illustrative budget assigns 80 milliseconds to input buffering, 60 to encoding, 140 to the first response decision, 40 to codec generation plus waveform decoding, and 80 to playback buffering. These five sequential stages total 400 milliseconds; overlap may reduce the total, while queueing can enlarge it. A first text token is not a first audible response.

For interruption, stop generation and playback coherently, release queued state, and record what the user actually heard. A tool action already committed cannot be canceled by muting its spoken confirmation. Define turn-taking, barge-in, maximum silence, and degradation on packet loss before optimizing throughput.

Evaluate recognition by language, accent, noise, and domain vocabulary; grounding by visible/audible evidence; generated speech by intelligibility and timing; interaction by successful tasks and appropriate interruption. Train/test splits should avoid speaker, video, or near-duplicate scene leakage. Obtain appropriate rights and consent for source material and voices; data availability is not equivalent to permission to clone a speaker.

Exercises and worked answers

  1. Why does doubling width and height quadruple patch count? Patches cover area; both axes double. Attention and encoder costs may then grow faster than the token count.
  2. Can a larger model fix text destroyed by downsampling? Not reliably. Preserve the signal or use a better crop/resolution policy before changing the backbone.
  3. Why is a contrastive model not automatically a generative assistant? Matching representations and generating conditional responses use different objectives and output mechanisms.
  4. Why can a correct video summary miss an important action? Sampling or compression can omit a brief event; evaluate coverage and temporal localization, not only summary fluency.
  5. What counts as completed speech output? Audio actually delivered under the interaction contract, with synchronized cancellation and tool state—not merely predicted text or queued codec tokens.
  6. Can a delegated task finish after the spoken request has changed? Yes. Track task generations and reject stale results before speaking or acting; cancellation of audio and cancellation of external work are separate operations.
  7. Does a multimodal backend make GPT-Live a native video model? No. Record the modalities supported by each component and the context actually transmitted across delegation.

Executable image-coordinate transform

examples/cross_layer.py maps boxes through centered letterboxing. Fitting 800×400 into 400×400 gives scale 0.5 and vertical padding 100; (100,100,500,300) becomes (50,150,250,250). The inverse subtracts padding before dividing by scale and recovers the continuous coordinates exactly. Real UI pipelines must also compose rounding, device pixel ratio, cropping and orientation in declared order. Test those round trips before dispatching a coordinate-based action.