Unified Audio-Visual-Language Modeling › Code Implementation
Language AI HandbookAll chapters 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.
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!