Unified Audio-Visual-Language Modeling
Learn how audio, video, and text encoders feed a shared language model, how fusion strategies compare, and where cross-modal generation breaks down.
Language AI HandbookAll chapters Unified Audio-Visual-Language Modeling
A short video can contain a sound that arrives just before the event it describes. If a user asks what happened at that moment, an audio encoder and a video encoder may each provide part of the evidence. The model has to keep those pieces tied to the same interval so it can answer from the clip instead of guessing from the question.
This chapter follows the input from modality-specific encoders into a shared language-model width, then compares where the streams can meet and how generation heads consume the result. In the worked example, a text query selects a time window in synthetic audio and video features. The same clips let us measure when a second stream helps, when it hurts, and what happens when it is missing.
Modality Encoders
A model cannot use a waveform or a frame until it has a representation for it. A text tokenizer produces integer IDs, each associated with an embedding row. Audio and video encoders instead often produce real-valued feature vectors. In both cases the transformer receives vectors, but the audio and video positions do not need an ID in the text vocabulary.
Why not feed raw audio or pixels directly
At 16,000 samples per second, 30 seconds of audio gives 480,000 samples. A 30-second video at 30 frames per second gives 900 frames. If each RGB frame contributes one sequence position per color value, the video has 135,475,200 positions. This is a deliberately inefficient raw encoding for comparison. An ordinary dense attention head computes pairwise scores for up to query-key positions before considering a mask. One head on the raw audio would therefore have about position pairs in one layer. A causal mask has fewer allowed pairs, with the same quadratic growth. An optimized kernel can avoid storing a dense score matrix while doing the underlying pairwise computation.
PythonIn [3]Expand
# For a 30-second clip, compute raw sizes from the stated sampling and frame
# rates. Use one pooled video feature per frame. The 1,500 audio positions
# come from the Whisper large model configuration.
SAMPLE_RATE = 16_000 # Hz, speech
AUDIO_SECONDS = 30.0
VIDEO_FPS = 30
VIDEO_SECONDS = 30.0
FRAME_PIXELS = 224 * 224 * 3
raw_audio_samples = int(SAMPLE_RATE * AUDIO_SECONDS)
raw_video_values = int(VIDEO_FPS * VIDEO_SECONDS) * FRAME_PIXELS
# Compressed representations: Whisper-large (1500 vectors / 30s) and a
# per-frame ViT at 1 token per frame.
compressed_audio = 1500
compressed_video = int(VIDEO_FPS * VIDEO_SECONDS) # 1 token per frame
compressed_total = compressed_audio + compressed_video
seq_lengths = {
"Raw audio samples": raw_audio_samples,
"Raw video values": raw_video_values,
"Audio feature vectors": compressed_audio,
"Video feature vectors": compressed_video,
}
print({k: f"{v:,}" for k, v in seq_lengths.items()})
print(f"Combined compressed length: {compressed_total:,}")ConsoleOut [3]Expand
{'Raw audio samples': '480,000', 'Raw video values': '135,475,200', 'Audio feature vectors': '1,500', 'Video feature vectors': '900'}
Combined compressed length: 2,400VisualizationOut [4]Expand

This figure compares counts of positions, not bytes or measured latency. Restricting video to one vector per frame is an illustrative pooling choice. A vision encoder can also preserve a patch sequence per frame, or keep multiple spatial regions. Pooling saves positions while making it harder to recover within-frame detail. Speech recognition features can also retain information about the speaker. Whisper-PMFA used features from Whisper encoder blocks for speaker verification.
Audio encoders
A common front end divides the waveform into overlapping windows, computes a spectrum for each window, and aggregates spectral energy into mel-filterbank bins. The resulting mel spectrogram has one axis for time and one for frequency bins. For an actual model, check the exact window, hop, padding and feature stride before converting a time span into a number of output positions.
If denotes a spectrogram with frequency bins and frames, the audio encoder produces time-indexed vectors
Here counts output positions, and counts components per position. A stride-two convolution can reduce the time resolution without changing the duration of the underlying clip. The Whisper paper uses 30-second input segments and a convolutional stem with stride two. The released large model configuration lists hidden width 1,280 and up to 1,500 source positions. Padding and trimming affect which positions represent the actual clip near its boundaries.
Video encoders
One option runs a vision encoder on each frame and preserves the time ordering of the frame features. A frame encoder can describe the frame at its own timestamp without encoding motion between frames. A later model can still infer motion by comparing the ordered outputs. Another option projects spatiotemporal patches across consecutive frames. For frames of height and width , with nonoverlapping patches of temporal extent and spatial extent , exactly divisible dimensions yield
This is a count before pooling or adding markers. At 300 frames of , with and , it is . Real encoders may sample fewer frames or merge patches after encoding. Those are separate choices with separate effects on what timing or spatial detail reaches the language model.
Text tokenizer
A tokenizer such as byte-pair encoding maps input text to a sequence of vocabulary IDs. The embedding lookup maps each ID to a fixed-width vector. Token counts depend on the vocabulary and normalization rules. An encoder can retain continuous features at input positions while a generation head selects discrete IDs at its output.
A position filled by an audio or video encoder is sometimes called a token. This usage describes its place in the sequence. It does not mean the encoder emitted an ID from the text vocabulary.
Shared Token Spaces
The projection layer
The language model expects a vector of width at each input position. Let and have widths and . Separate linear maps can make both streams fit the language model:
where and . Projection changes feature width while preserving the number of input positions in this example. It does not by itself map a musical note, a frame and a word to interchangeable meanings. The training examples and objectives determine which relationships are useful to the readout.
ImageBind illustrates a distinct goal for a shared representation. It aligns six modalities in a joint embedding space using image-paired data, which supports cross-modal comparisons even for some modalities not paired together in training. That comparison space serves a different purpose from assembling continuous input rows for an autoregressive decoder.
Interleaved sequences
An input sequence can contain text embeddings, audio embeddings, video embeddings and learned markers for boundaries. Some systems group each stream in its own block, while others insert audio and video along a common time axis. With causal self-attention, a position can attend only to permitted preceding and current positions. If a downstream text answer needs both streams, make their relevant input features available before the answer positions. A common embedding width is necessary for concatenating these vectors into a sequence, but does not remove the causal mask.
A modality marker tells the model where a stream starts. It does not supply absolute time, align two clocks, or reveal how many raw samples went into one feature. Relative or absolute time information can come from timestamps, an explicit resampling rule, or the position encoding. The Qwen2.5-Omni report uses time-aligned multimodal rotary positions for its audio and video inputs. This is an architectural choice, not a requirement of sharing the language model width.
What "shared token space" really buys you
Consider a text-only output head. Its logits still index the text vocabulary even when audio and visual embeddings are present in the context. The decoder uses the sensory inputs to predict text tokens. The projections used for reading sensory inputs do not provide a waveform or image decoder. Generating a second modality needs its own output representation and conversion to a usable signal.
Fusion Strategies
Late fusion
Late fusion combines modality-specific predictions or summaries after much of the separate processing has taken place. For a classifier, fit a score from audio and another from video, then combine the scores by averaging or by fitting a second model. Check the output units or calibration before averaging across independently trained systems. An uncalibrated high-amplitude score can dominate this combination without being more reliable. The worked example uses two signed regressions with the same target scale.
Pooling can remove local detail before a fusion stage sees it. If each encoder gives only a clip-level vector, the fusion stage has no explicit row for one particular frame or audio interval. This limitation follows from what the interface retains. A scoring pipeline can instead align or select the relevant window in each stream before combining two late scores, as the example does.
Early fusion
Early fusion lets a shared stage operate on features from multiple modalities before producing separate predictions. At the level of a transformer with a joint input sequence, layers can learn interactions between audio, video, and text positions that the mask allows. Those interactions can use local cues if the model can resolve which rows correspond in time. The arrangement enables this computation within the transformer. Its presence does not establish that the trained model uses it correctly.
A model-side budget example helps separate sequence length from architecture. Suppose both layouts use 200 text positions. One layout places two pooled feature rows in front of the text. The other retains 1,500 audio and 120 video rows. Here 120 stands for a minute sampled at two frames per second, with one vector per frame. We omit markers in both layouts to keep the comparison focused on sensory positions. This is a comparison of attention in the shared language backbone, not two measurements of total system compute.
PythonIn [5]Expand
text_positions = 200
pooled_positions = 2
full_audio_positions = 1500
full_video_positions = 60 * 2
backbone_lengths = {
"Two pooled rows": text_positions + pooled_positions,
"Full feature rows": text_positions
+ full_audio_positions
+ full_video_positions,
}
backbone_pairs = {name: length**2 for name, length in backbone_lengths.items()}ConsoleOut [6]Expand
Two pooled rows: 202 positions, 40,804 full score positions Full feature rows: 1,820 positions, 3,312,400 full score positions
VisualizationOut [7]Expand

Hybrid fusion
Independent audio and video encoders can feed a shared language backbone. The sensory encoders process streams separately, and fusion happens early relative to the language model. Other designs can introduce cross-stream attention during encoding or allow selected language layers to consult a separate memory. Where fusion occurs and how many feature rows survive are separate design decisions. If you want to explain a difference in latency, count the encoder operations and active positions where the paths differ, then measure the actual system.
For an audio-visual speech example, AV-HuBERT jointly learns from audio and visual speech with masked multimodal cluster prediction. A speech representation learner such as this one does not imply that every model needs an audio-visual encoder. The data and target task determine how useful an aligned representation is.
Counts, masks, and measurements
Dense self-attention with the same number of key and query positions counts their Cartesian product. For the two layouts above, the number of candidate positions is 202 squared or 1,820 squared. A standard causal mask retains the diagonal and the positions to its left. With length 202 it permits 20,503 pairs per head in this construction, and with length 1,820 it permits 1,657,110. This triangular count describes the mask. It does not tell us whether the kernel computes or stores a complete dense array. A full-score count and a count of allowed pairs make different assumptions and should not be compared as if they were timing measurements.
Cross-attention uses a different count if its queries and keys come from different streams. For 200 language positions attending to 1,620 sensory positions, a full cross-attention operation has 324,000 candidate pairs per head before masking. If the sensory stream is compressed first, use the resulting length in the calculation. Report the calculation separately from latency. For example, the added encoder may dominate short prompts even where the backbone's attention count is smaller.
A common comparison error is to count only the decoder for one model and the encoder plus decoder for another. Choose which layers, heads and sequence positions are within the analysis before comparing. Report the length of the longest examples or give a distribution of lengths when the inputs vary, because the mean of squared lengths will generally differ from the square of mean length. In the mathematical example here the lengths are fixed, so no aggregation over differing lengths is needed.
Compare designs with a controlled input change
A lower cost at a chosen interface is only useful if the features it passes are sufficient for the target task. If a user asks about a single event near the end of a clip, decide whether an encoder that pools all frames can preserve the distinction between a late event and an earlier one. You can make a paired check by moving the same synthetic event from the queried window into a neighboring one. The change tests sensitivity to event time. Keeping the event in the queried window while increasing unrelated noise tests a different property and should be reported separately.
For a generative system, fix the decoding settings before comparing its answers across such controlled inputs. A changed response cannot be attributed to the modality perturbation alone if sampling settings or the prompt also changed. The fixture below avoids those confounders by using fixed linear readouts and a deterministic class decision. Its measured comparisons are about that evaluation; they do not provide evidence for a specific production model.
Cross-Modal Generation
Generating text
A decoder can produce text autoregressively from prior text and sensory features. For a question about a clip, arrange the input so the relevant audio and video rows are visible under the attention mask before generation begins. Evaluate whether the answer changes appropriately when the relevant event is removed or when one modality supplies contradictory evidence.
Generating audio
A neural codec can represent audio with discrete codes. A generative head predicts codes at one or more levels, and the learned codec decoder converts those codes to waveform samples. The code rate and number of codebooks depend on the codec and configuration. A language-model stream need not use the same vocabulary for speech and text. Another design conditions an acoustic generator on the language model's states to predict continuous features or flow trajectories. The waveform synthesis step depends on what that generator produces.
The Qwen2.5-Omni report gives a concrete example. Its Thinker produces text, while its Talker consumes hidden representations from the Thinker and produces audio codes. Subsequent processing converts those codes to speech. The report describes streaming text and speech output from text, images, audio, and video inputs. The set of inputs is broader than the set of generated output modalities in that model.
Generating video
A multimodal model that accepts video may return a text answer or timestamps for matching evidence. Synthesizing video frames is a different output objective and needs an output model that can represent a video sequence. The next chapter deals with understanding events across time. Here the important architectural distinction is between the features used to read a modality and the output mechanism used to generate one.
Worked Example: Aligning Audio and Video with a Shared Time Axis
A user asks about an event at a particular moment in a clip. The text gives the location in time, while audio and video supply evidence about the event. To combine them, map the audio and video timestamps to the same interval before pooling either stream. A marker for the audio stream identifies the modality. It does not tell the model when any particular element occurred.
Use six quarter-second windows. The audio feature encoder in this example emits sixteen rows per second and the video feature encoder emits four. Each window gets four audio rows and one video row. A command such as window_3 selects the fourth window, from 0.75 s up to 1.00 s. Clip-level pooling would mix that window with events elsewhere in the clip.
Code Implementation
Generate paired synthetic features
Generate an independent positive or negative event at each time bin. The query token selects a bin independently of the event labels. It gives the evaluator a time index with no class information. Each audio or video row is a scalar feature containing the event signal plus independent Gaussian noise. The streams stand in for encoder outputs. The notebook never loads an audio clip, video, or pretrained model.
PythonIn [8]Expand
from dataclasses import dataclass
import numpy as np
SEED = 2026
WINDOWS = 6
SECONDS_PER_WINDOW = 0.25
AUDIO_PER_WINDOW = 4
QUERY_TOKENS = tuple(f"window_{i}" for i in range(WINDOWS))
@dataclass(frozen=True)
class Clips:
events: np.ndarray
audio: np.ndarray
video_noise: np.ndarray
query_ids: np.ndarray
def video(self, noise_scale: float) -> np.ndarray:
return self.events + noise_scale * self.video_noise
def targets(self) -> np.ndarray:
return self.events[np.arange(len(self.events)), self.query_ids]
def make_clips(size: int, rng: np.random.Generator) -> Clips:
events = rng.choice([-1.0, 1.0], size=(size, WINDOWS))
audio = np.repeat(events[..., None], AUDIO_PER_WINDOW, axis=2)
audio += 2.2 * rng.standard_normal(audio.shape)
video_noise = rng.standard_normal(events.shape)
query_ids = rng.integers(WINDOWS, size=size)
return Clips(events, audio, video_noise, query_ids)
train = make_clips(2400, np.random.default_rng(SEED))
test = make_clips(1200, np.random.default_rng(SEED + 1))
train_video = train.video(0.55)Put the feature rows on the same clock
In the first evaluation clip, use its query token to highlight one window. Timestamps are the centers of the feature rows. The half-open interval includes its left endpoint and excludes its right, so neighboring windows do not share rows. The shape assertions track the number of samples assigned to this query.
PythonIn [9]Expand
probe_clip = 0
probe_query = int(test.query_ids[probe_clip])
probe_token = QUERY_TOKENS[probe_query]
probe_start = probe_query * SECONDS_PER_WINDOW
probe_stop = probe_start + SECONDS_PER_WINDOW
audio_step = SECONDS_PER_WINDOW / AUDIO_PER_WINDOW
audio_time = (np.arange(WINDOWS * AUDIO_PER_WINDOW) + 0.5) * audio_step
video_time = (np.arange(WINDOWS) + 0.5) * SECONDS_PER_WINDOW
probe_audio = test.audio[probe_clip].ravel()
probe_video = test.video(0.25)[probe_clip]
assert (
np.count_nonzero((probe_start <= audio_time) & (audio_time < probe_stop))
== 4
)
assert (
np.count_nonzero((probe_start <= video_time) & (video_time < probe_stop))
== 1
)VisualizationOut [10]Expand

Train feature-level and score-level fusion
Average the four audio samples within each window. Use the query ID to index the aligned audio and video features at the same time. For early fusion, fit one readout using both features jointly. For late fusion, fit separate readouts and average their scores. Both readouts here are linear and share the same labeled training clips. This comparison illustrates where the streams meet, rather than testing whether a deep joint encoder beats an independent one.
The ridge solve penalizes large coefficients while fitting the signed target. We reuse the audio readout as a fallback when the video stream is absent. Passing None for missing video is different from receiving a present video feature equal to zero.
PythonIn [11]Expand
def select_window(bins: np.ndarray, query_ids: np.ndarray) -> np.ndarray:
return bins[np.arange(len(bins)), query_ids]
def audio_feature(clips: Clips) -> np.ndarray:
pooled = clips.audio.mean(axis=2)
return select_window(pooled, clips.query_ids)[:, None]
def video_feature(clips: Clips, video: np.ndarray) -> np.ndarray:
return select_window(video, clips.query_ids)[:, None]
def fit_readout(features: np.ndarray, targets: np.ndarray) -> np.ndarray:
gram = features.T @ features / len(targets)
cross = features.T @ targets / len(targets)
return np.linalg.solve(gram + 0.01 * np.eye(gram.shape[0]), cross)
train_a = audio_feature(train)
train_v = video_feature(train, train_video)
y_train = train.targets()
w_audio = fit_readout(train_a, y_train)
w_video = fit_readout(train_v, y_train)
w_joint = fit_readout(np.column_stack((train_a, train_v)), y_train)PythonIn [12]Expand
def scores(clips: Clips, video: np.ndarray | None) -> dict[str, np.ndarray]:
audio = audio_feature(clips)
audio_score = audio @ w_audio
if video is None:
return {
"Audio only": audio_score,
"Early fusion": audio_score,
"Late fusion": audio_score,
}
visual = video_feature(clips, video)
video_score = visual @ w_video
return {
"Audio only": audio_score,
"Early fusion": np.column_stack((audio, visual)) @ w_joint,
"Late fusion": (audio_score + video_score) / 2,
}
def accuracy(score: np.ndarray, targets: np.ndarray) -> float:
score = np.asarray(score)
targets = np.asarray(targets)
if score.ndim != 1 or score.shape != targets.shape or score.size == 0:
raise ValueError(
"Scores and targets must be aligned nonempty one-dimensional arrays."
)
if score.dtype.kind not in "iuf" or not np.isfinite(score).all():
raise ValueError("Scores must be finite real numbers.")
if targets.dtype.kind not in "iuf" or not np.isin(targets, (-1, 1)).all():
raise ValueError("Targets must contain only -1 or +1.")
labels = np.where(score >= 0.0, 1.0, -1.0)
return float(np.mean(labels == targets))
conditions = {
"Clean video": test.video(0.25),
"Noisy video": test.video(5.0),
"Missing video": None,
}
y_test = test.targets()
condition_scores = {
name: scores(test, video) for name, video in conditions.items()
}
condition_accuracy = {
name: {model: accuracy(s, y_test) for model, s in readings.items()}
for name, readings in condition_scores.items()
}
missing = condition_scores["Missing video"]
assert np.array_equal(missing["Audio only"], missing["Early fusion"])
assert np.array_equal(missing["Audio only"], missing["Late fusion"])
assert (
condition_accuracy["Clean video"]["Early fusion"]
> condition_accuracy["Clean video"]["Audio only"]
)
assert (
condition_accuracy["Noisy video"]["Early fusion"]
< condition_accuracy["Noisy video"]["Audio only"]
)ConsoleOut [13]Expand
Clean video: Audio only: 81.8%, Early fusion: 100.0%, Late fusion: 99.1% Noisy video: Audio only: 81.8%, Early fusion: 62.2%, Late fusion: 64.0% Missing video: Audio only: 81.8%, Early fusion: 81.8%, Late fusion: 81.8%
The two observed video conditions reuse exactly the same clips, targets, text query IDs, audio observations, and underlying video noise draws. Only the multiplier on video noise changes. Audio-only therefore has the same accuracy in every column of the comparison. Both kinds of fusion help on clean video and hurt on the noisier version in this seeded run. When the video is absent, the explicit fallback makes their scores equal the audio-only scores. No learned missing-modality behavior is being tested.
Sweep the same clips across video-noise levels
The horizontal axis is the standard deviation used to scale the same seeded Gaussian video noise array. A single line for each model shows how those fixed readouts respond. Equal nominal noise scales in audio and video would not imply equal reliability. The audio readout averages four rows whose noise draws are independent. That divides the audio noise standard deviation by two, from 2.2 per row to 1.1 for the average. The plotted comparison still depends on the chosen features and fitted readouts.
PythonIn [14]Expand
noise_levels = np.array([0.0, 0.25, 0.55, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0])
model_names = tuple(condition_scores["Clean video"])
accuracy_by_noise = np.array(
[
[
accuracy(value, y_test)
for value in scores(test, test.video(scale)).values()
]
for scale in noise_levels
]
)
assert np.all(accuracy_by_noise[:, 0] == accuracy_by_noise[0, 0])VisualizationOut [15]Expand

The crossover belongs to this generator, fixed readouts, and evaluation set. It does not establish a universal noise threshold or a preference for one fusion architecture. Real continuous streams also bring clock offsets, dropped frames, and encoder alignment errors. Check missing, noisy, and deliberately shifted streams separately so that a drop in a particular condition can be traced back to what changed.
Limitations and Impact
A model trained on aligned clips can encounter missing frames, microphone offsets, or transcripts that lag the sound. A correct answer on the clean split does not diagnose such failures. Keep a paired evaluation set and change one condition at a time. Check whether the same alignment tolerance applies when an event is brief, when an encoder compresses several events into one row, or when the prompt names a precise point in time.
There are two ways a system can fail even with technically compatible embeddings. The needed detail may have been lost during encoding, for example when pooled visual rows hide where in the frame an object appeared. Or it may still be present but the trained predictor gives more weight to an unreliable modality. The paired video-noise sweep illustrates the second mechanism. Video helps on clean clips and hurts on noisy clips under fixed coefficients. It does not show that adding a modality is harmful on all data or that the same noise threshold applies outside the toy.
Treat an absent stream as a distinct condition. A deployment can use a learned missing-stream token, a model trained with modality dropout, or a declared fallback such as the separate audio readout in this notebook. Decide what your system is allowed to answer from the remaining streams. If a query asks about a visual event and the video is absent, a well-configured system may have to ask for the clip rather than improvise.
A useful evaluation groups examples by the evidence they require. For questions solvable from audio alone, check the effect of adding video. For joint questions, verify that changing only one necessary piece of evidence changes the answer in the expected direction. Also measure workload-level accuracy and latency. A larger gain on common easy clips can hide a failure on rare clips that need both modalities.
Summary
- Audio and video encoders can provide continuous vectors. A text tokenizer provides discrete IDs, which become vectors after embedding lookup.
- Per-stream projections can put input vectors at the same width. Temporal alignment depends on timestamps, sampling, and position information.
- Fusion can happen before a shared readout or after separate predictions. Count attention at the stage that actually receives the joint sequence.
- A model that reads audio or video can still output text only. Additional output modalities require their own generation and decoding mechanism.
- Test fusion on paired clean, corrupted, and missing-stream conditions. In the synthetic experiment, an unchanged audio baseline distinguishes the benefit of useful video from the cost of an unreliable present stream.
Quiz
Unified Audio-Visual-Language Modeling
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!