Skip to content
AI from Scratch
EN

Other modalities: image, audio, video

This project is about language. But the distance to the other modalities is far shorter than it looks, because almost everything ended up being transformers.

Here is the map, with the same criterion as the rest: the real mechanism, and where you would touch the code you already have.


1. Vision: the idea that unified everything

Before 2020: convolutional networks

A convolution slides a small filter (3×3) across the whole image and detects the same pattern at any position. You stack layers and the patterns become more abstract: edges → textures → parts → objects.

Two properties made it unbeatable on images:

  • Translation invariance: a cat is a cat wherever it is.
  • Weight sharing: the same filter for the whole image, so there are few parameters.

2020: Vision Transformer (ViT)

And then somebody asked: what if we treat an image as a sequence?

224×224 image
  → split into 16×16 patches  →  196 patches
  → flatten each patch (16·16·3 = 768 numbers)
  → a linear layer projects them into the model dimension
  → add a position embedding
  → FEED THEM INTO AN ORDINARY TRANSFORMER

That is all. An image patch plays exactly the role of a token.

Compare it with your etapas/06_transformer/gpt.py: the only thing that changes is where the input vectors come from. Instead of wte(ids) — a table lookup — you have patches @ W_projection. The rest of the file is identical.

The honest nuance: ViT needs vastly more data than a CNN to match it, because it does not come with translation invariance built in: it has to learn it. With little data, CNNs still win. With a lot, transformers do.

And that sentence sums up the whole field: inductive structure versus data. When there is data to spare, the generic architecture that learns the structure on its own wins.

Causal attention disappears

A detail worth understanding: in an image there is no future. All the patches exist at once. So ViT uses bidirectional attention: no mask.

In your code it would be literally deleting the line att = att.masked_fill(self.mascara[:T, :T], -1e9).


2. Image generation: diffusion

Here there really is a genuinely different idea, and it is lovely.

The mechanism

Training: you take a real image and add Gaussian noise to it little by little, over around 1,000 steps, until it is pure noise. You train a network so that, given a noisy image and the noise level, it predicts the noise that was added.

Generating: you start with pure noise and apply the network in reverse, removing a little noise each time. After the steps, an image appears.

train:     image → +noise → +noise → ... → pure noise
                   the network learns to undo ONE step

generate:  pure noise → −noise → −noise → ... → image

Why it works so well

Compare it with what you know:

language modeldiffusion
Generatesone token at a time, in orderthe whole image, refining
Passesone per token20-1,000 per image
Can correct itselfno (what is written stays written)yes, at every step
Parallelismnone when generatingtotal (the whole image at once)

That ability to correct is the key: if step 300 introduces an error, step 301 can fix it. An autoregressive model cannot go back.

Diffusion: from noise to image, undoing the pathDiffusion: from noise to image, undoing the pathimagepure noisetraining: add noise step by step →← generating: the network removes noise, step by stepand because it can correct itself at every step, it does not drag its errors along
Diffusion: from noise to image, undoing the path

Latent diffusion (Stable Diffusion)

Diffusing 512×512×3 = 786,432 numbers is enormously expensive. The trick:

  1. An autoencoder compresses the image into a 64×64×4 latent space (48 times smaller).
  2. The diffusion happens in there.
  3. The decoder reconstructs the final image.

That is why Stable Diffusion fits on a consumer GPU.

And here your project comes back

How is it conditioned on text ("an astronaut cat")?

  1. A text encoder — CLIP, which is a transformer — turns the prompt into vectors.
  2. The diffusion network uses cross-attention against those vectors.

Cross-attention is your own AtencionCausal, with one change: the queries (Q) come from the image and the keys and values (K, V) come from the text. The image "asks" the text what it should draw.

In your code: instead of qkv = self.c_attn(x), you would have q = Wq(x_image) and k, v = Wk(t_text), Wv(t_text). Ten lines.


3. Audio

Speech recognition (Whisper)

audio → spectrogram (a time × frequency image)
      → cut into windows
      → transformer encoder
      → transformer decoder → text

It is an encoder-decoder transformer, just like the original one from 2017. The "tokenizer" is the spectrogram.

Speech synthesis and music

A neural audio tokenizer (such as EnCodec) turns the waveform into discrete tokens — literally, a vocabulary of sounds. And then:

You generate audio with an autoregressive language model, exactly like your GPT. Same loop, same sampling, same KV cache. All that changes is what the tokens mean.

It is the result that surprises people most: your etapas/08_inferencia/02_kv_cache.py would work, without touching a line of the loop, for generating music.


4. Genuinely multimodal

How a model "sees" an image and talks about it:

    image ──► visual encoder (ViT) ──► linear projection ──┐
                                                            ├──► TRANSFORMER
    text  ──► tokenizer ──► embeddings ───────────────────┘

And that is it. The image vectors go into the same sequence as the text ones. The transformer does not tell the difference: to it they are vectors in a sequence.

Training has three phases:

  1. Freeze the language model and train only the projection (cheap).
  2. Unfreeze and fine-tune on image-text pairs.
  3. Multimodal instruction tuning.

If you wanted to do it with your code: you would add an nn.Linear(768, n_embd) projecting the patches, and concatenate them with self.wte(ids) before the first block. The rest of gpt.py stays untouched.


5. The table that sums it up

ModalityHow it becomes tokensArchitecture
TextBPE over bytesdecoder transformer
Image (understanding)16×16 patchesbidirectional transformer
Image (generating)latents from an autoencoderU-Net or diffusion transformer
Audio (understanding)spectrogram windowsencoder-decoder transformer
Audio (generating)tokens from a neural codecdecoder transformer
Videospatio-temporal patchestransformer (enormously expensive)

The lesson: the hard work in each modality is turning it into a sequence of vectors. From there on, it is the same transformer you have written.

That is why AI from 2017 onwards converges: not because language is special, but because "sequence of vectors" turned out to be a universal format.


If you want to explore on your own

With mininn and what you know, these are the next steps by difficulty:

ProjectDifficultyWhat you reuse
ViT on MNISTeasygpt.py with the causal mask removed
Cross-attentioneasyAtencionCausal, changing where K and V come from
Diffusion on MNISTmediumall of mininn; the network can be an MLP
A CLIP-style text encodermediumyour GPT, with pooling at the end
Audio tokenizerhardyou would need vector quantization

The first is a weekend and it teaches you more than ten papers.


Next: 12-entrenamiento-distribuido.md