TExcelTAD
Home › Generative AI & LLMs › Image, Audio & Multimodal Models

Image, Audio & Multimodal Models

Generative AI is not only text. Models now read and create images, audio and video, and many chat models are multimodal: you can send a photo of a whiteboard, a chart or a screenshot together with a question. This lesson explains, conceptually, how other kinds of data are turned into something a Transformer can process, and how image generators work. The code shows the core transformations on tiny arrays — real models do the same at much larger scale.

Everything becomes tokens

A Transformer processes a sequence of vectors. For text, those vectors come from token embeddings. For other modalities, we need a way to cut the input into pieces and embed each piece:

Modality Typical "tokens"
Text subword tokens
Images small square patches (e.g. 16×16 pixels), each flattened and projected to a vector
Audio short time slices, often of a spectrogram, or codes from a neural audio codec
Video patches across space and time

Once everything is a sequence of vectors, the same attention machinery can relate a word in your question to a region in your photo.

Images as patches

A Vision Transformer (ViT) splits an image into patches. Here an 8×8 "image" becomes four 4×4 patches, each flattened into a 16-number vector and then projected to an embedding:

python · try it yourself
import numpy as np

image = np.arange(64).reshape(8, 8)          # a tiny 8x8 grayscale "image"
P = 4                                        # patch size

patches = (image.reshape(8 // P, P, 8 // P, P)
                .transpose(0, 2, 1, 3)
                .reshape(-1, P * P))
print("image shape:", image.shape)
print("patches:", patches.shape, "-> 4 patches of 16 pixels")
print("first patch:", patches[0])

rng = np.random.default_rng(0)
W = rng.normal(size=(P * P, 6))              # learned projection in a real model
tokens = patches @ W
print("patch embeddings:", tokens.shape)
image shape: (8, 8)
patches: (4, 16) -> 4 patches of 16 pixels
first patch: [ 0  1  2  3  8  9 10 11 16 17 18 19 24 25 26 27]
patch embeddings: (4, 6)

A real image model might cut a photo into hundreds or thousands of patches, so images can use a significant part of the context window. Multimodal APIs therefore count images in tokens too.

Audio as a spectrogram

Raw audio is a long list of pressure samples (e.g. 16,000 per second). Speech models usually convert it into a spectrogram: how much energy each frequency has in each short time window. That is computed with a Fourier transform:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

sr = 8000                                    # samples per second
t = np.arange(0, 1.0, 1 / sr)
# A "melody": 440 Hz for the first half, then 880 Hz
signal = np.where(t < 0.5, np.sin(2 * np.pi * 440 * t), np.sin(2 * np.pi * 880 * t))

win = 256
frames = signal[: len(signal) // win * win].reshape(-1, win) * np.hanning(win)
spectrum = np.abs(np.fft.rfft(frames, axis=1))       # (time frames, frequencies)
freqs = np.fft.rfftfreq(win, 1 / sr)

fig, ax = plt.subplots(figsize=(6, 3))
ax.imshow(spectrum.T, origin="lower", aspect="auto",
          extent=[0, 1, 0, freqs[-1]], cmap="magma")
ax.set_xlabel("time (s)"); ax.set_ylabel("frequency (Hz)"); ax.set_title("Spectrogram")
fig.tight_layout()
plt.show()

peak_first = freqs[spectrum[2].argmax()]
peak_last = freqs[spectrum[-2].argmax()]
print("frames:", spectrum.shape[0], "| frequency bins:", spectrum.shape[1])
print(f"dominant frequency early: {peak_first:.0f} Hz, late: {peak_last:.0f} Hz")
frames: 31 | frequency bins: 129
dominant frequency early: 438 Hz, late: 875 Hz

The detected peaks (438 and 875 Hz) are the frequency bins closest to the true 440 and 880 Hz — with 256-sample windows each bin is about 31 Hz wide. Each column of the spectrogram can be treated like a token. Speech-to-text models map these to text tokens; text-to-speech models go the other way.

How image generators work: diffusion

Most current image generators are diffusion models. Training teaches a network to remove noise:

  1. Take a real image and add a random amount of Gaussian noise.
  2. Train the network to predict the noise that was added (given the noisy image, the noise level and the text prompt).
  3. To generate, start from pure noise and repeatedly subtract the predicted noise, step by step, steering with the text prompt.

The forward (noising) half is easy to show on a 1-D "image":

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
clean = np.array([0.0, 0.2, 0.8, 1.0, 0.8, 0.2, 0.0])     # a little bump
noise = rng.normal(size=clean.shape)

for alpha in [1.0, 0.9, 0.5, 0.1, 0.0]:                   # how much signal remains
    noisy = np.sqrt(alpha) * clean + np.sqrt(1 - alpha) * noise
    print(f"signal {alpha:.1f}: {np.round(noisy, 2)}")

# If a network predicted the noise perfectly, one step recovers the clean signal:
alpha = 0.5
noisy = np.sqrt(alpha) * clean + np.sqrt(1 - alpha) * noise
recovered = (noisy - np.sqrt(1 - alpha) * noise) / np.sqrt(alpha)
print("recovered:", np.round(recovered, 2))
signal 1.0: [0.  0.2 0.8 1.  0.8 0.2 0. ]
signal 0.9: [ 0.11  0.45  0.86  0.54  1.05  0.33 -0.17]
signal 0.5: [ 0.24  0.72  0.8  -0.21  1.21  0.46 -0.38]
signal 0.1: [ 0.33  0.84  0.57 -0.92  1.11  0.49 -0.51]
signal 0.0: [ 0.35  0.82  0.33 -1.3   0.91  0.45 -0.54]
recovered: [0.  0.2 0.8 1.  0.8 0.2 0. ]

A real denoiser only estimates the noise, so generation takes many small steps, and the text prompt (through embeddings and attention) decides what emerges from the noise. Some image and audio generators instead produce tokens autoregressively, like an LLM.

Using multimodal models

With the Anthropic API, an image is sent as a content block next to the text (reference code):

python
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=300,
    messages=[{"role": "user", "content": [
        {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": png_base64}},
        {"type": "text", "text": "What does this chart show? Answer in two sentences."},
    ]}],
)

Typical uses: describing images for accessibility, reading charts and documents, extracting data from receipts and forms, and answering questions about screenshots. The same cautions apply as for text — models can misread small text or numbers and can hallucinate details — plus extra ones for generated media: deepfakes, consent for images of real people, and labelling AI-generated content.

Go further: Vision Transformers (ViT) turns images into patch tokens in NumPy and trains a tiny ViT against a small CNN.

Test yourself

How does a Vision Transformer turn an image into tokens?

  1. It reads the file name
  2. It splits the image into patches and projects each patch to a vector
  3. It converts pixels to letters
  4. It uses the image's colour histogram only

What does a spectrogram show?

  1. Word frequencies in a text
  2. How much energy each frequency has over time
  3. The size of an image
  4. The model's attention weights

How does a diffusion model generate an image?

  1. It copies the most similar training image
  2. It starts from noise and removes predicted noise step by step, guided by the prompt
  3. It draws pixels from left to right with rules
  4. It searches the web