3500: Multimodal Models¶
Overview¶
This module covers vision-language models (CLIP, BLIP, LLaVA) and audio models (Whisper, AudioLM). You'll learn how Transformers extend beyond text to process images, audio, and video, enabling applications like image captioning, visual question answering, and speech recognition.
Module Documents¶
| Document | Description | Time | Difficulty |
|---|---|---|---|
| 3501: Vision-Language Models | CLIP, BLIP, LLaVA, multimodal RAG | 5 hrs | βββ |
| 3502: Audio Models | Whisper, AudioLM, voice assistants | 5 hrs | βββ |
Learning Objectives¶
After completing this module, you will:
- Understand vision-language model architectures
- Implement CLIP-style contrastive learning
- Build multimodal RAG systems
- Understand audio Transformers (Whisper, AudioLM)
- Apply multimodal models to real-world tasks
Prerequisites¶
- Vision: Convolutional neural networks basics
- Audio: Signal processing basics (MFCC, spectrograms)
- Previous: 3100: Attention, 3400: Architectures
See PREREQUISITES.md for detailed requirements.
Key Concepts¶
What is Multimodal AI?¶
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Multimodal Models β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Input Modality Processing Output Modality β
β βββββββββββββ βββββββββ ββββββββββββββββ β
β β
β Text β β
β Image β Transformer β Text / Image / Audioβ
β Audio β β
β Video β β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Multimodal Architecture Families¶
| Architecture | Description | Examples | Use Case |
|---|---|---|---|
| Encoder-Encoder | Separate encoders, fusion layer | CLIP, BLIP | Image-text retrieval |
| Encoder-Decoder | Cross-modal attention | LLaVA, Flamingo | VQA, captioning |
| Unified | Single modality-agnostic encoder | GATO, Flamingo | General multimodal |
| Projection | Map to shared embedding space | CLIP | Zero-shot transfer |
Vision-Language Models¶
CLIP: Contrastive Language-Image Pre-training¶
Core Idea: Learn visual concepts from natural language supervision
Training: (Image, Text) pairs with contrastive loss
ββββββββββββββββββββ ββββββββββββββββββββ
β Image Encoder β β Text Encoder β
β (Vision β β (Text β
β Transformer) β β Transformer) β
ββββββββββ¬ββββββββββ ββββββββββ¬ββββββββββ
β β
β Shared Embedding Space (512D) β
β β
βββββββββββββββ¬ββββββββββββββββββββ
β
βΌ
Contrastive Loss
(Maximize similarity for
matching pairs, minimize
for non-matching)
Key Formula:
L = -log(exp(sim(z_i, z_j) / Ο) / Ξ£ exp(sim(z_i, z_k) / Ο))
Where:
- z_i: Image embedding
- z_j: Text embedding (positive pair)
- z_k: All text embeddings
- Ο: Temperature parameter
- sim: Cosine similarity
LLaVA: Large Language and Vision Assistant¶
Architecture: Connect vision encoder to LLM via projection layer
Image Input
β
CLIP ViT-L/14 (Vision Encoder)
β
Linear Projection (to LLM token space)
β
LLM (Vicuna, LLaMA)
β
Text Output
Example:
User: <image> What is in this image?
LLaMA: The image shows a cat sitting on a windowsill...
Multimodal RAG¶
Idea: Extend text RAG with visual documents
Query: "What did the Q4 earnings report say about revenue?"
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Multimodal RAG Pipeline β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β 1. PDF Pages β
β βββ Text chunks β Text embeddings β
β βββ Images β CLIP embeddings β
β β
β 2. Vector Store β
β βββ Text vectors (Qdrant) β
β βββ Image vectors (Qdrant) β
β β
β 3. Retrieval β
β βββ Relevant text chunks β
β βββ Relevant images/tables/charts β
β β
β 4. Generation (Vision-Language LLM) β
β βββ Text context β
β βββ Images (base64) β
β βββ Answer: "According to Q4 report, revenue..." β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Audio Models¶
Whisper: Automatic Speech Recognition¶
Architecture: Encoder-decoder Transformer
Audio Input (16kHz)
β
Log-Mel Spectrogram (80 channels)
β
Audio Transformer Encoder (bidirectional)
β
Transformer Decoder (autoregressive)
β
Text Output (with timestamps)
Key Features:
- 680k hours of weakly supervised training data
- Robust to accents, background noise, technical language
- Multilingual (99 languages)
- Timestamps for word-level alignment
AudioLM: Audio Generation¶
Approach: Language modeling approach to audio
Audio Input
β
Semantic Tokens (from w2v-BERT encoder)
β
Transformer (predicts next semantic token)
β
Coarse Acoustic Model (predicts acoustic tokens)
β
Fine Acoustic Model (predicts actual audio samples)
β
Generated Audio
Implementation Examples¶
CLIP-style Contrastive Learning¶
import torch.nn.functional as F
import torch.nn as nn
import torch
import numpy as np
class ContrastiveLearning(nn.Module):
"""
CLIP-style contrastive learning for image-text pairs.
"""
def __init__(self, image_encoder, text_encoder, embed_dim=512):
super().__init__()
self.image_encoder = image_encoder
self.text_encoder = text_encoder
self.embed_dim = embed_dim
# Projection layers
self.image_proj = nn.Linear(image_encoder.output_dim, embed_dim)
self.text_proj = nn.Linear(text_encoder.output_dim, embed_dim)
# Learnable temperature parameter
self.logit_scale = nn.Parameter(torch.ones(1) * np.log(1 / 0.07))
def forward(self, images, texts):
"""
Args:
images: (batch, 3, H, W)
texts: (batch, seq_len)
Returns:
loss: Contrastive loss
"""
# Encode images and texts
image_features = self.image_encoder(images)
text_features = self.text_encoder(texts)
# Project to shared space
image_embeds = self.image_proj(image_features)
text_embeds = self.text_proj(text_features)
# Normalize
image_embeds = F.normalize(image_embeds, dim=-1)
text_embeds = F.normalize(text_embeds, dim=-1)
# Cosine similarity
logits = (image_embeds @ text_embeds.T) * self.logit_scale.exp()
# Labels: diagonal elements (matching pairs)
batch_size = images.size(0)
labels = torch.arange(batch_size, device=images.device)
# Loss (symmetric)
loss_i = F.cross_entropy(logits, labels)
loss_t = F.cross_entropy(logits.T, labels)
loss = (loss_i + loss_t) / 2
return loss
Multimodal RAG Query¶
def multimodal_rag_query(query: str, vector_store, vision_llm):
"""
Perform multimodal RAG query.
"""
# 1. Retrieve relevant text chunks
text_results = vector_store.search(
query,
modality="text",
top_k=5
)
# 2. Retrieve relevant images
image_results = vector_store.search(
query,
modality="image",
top_k=3
)
# 3. Prepare multimodal context
context = {
"text": "\n\n".join([r.content for r in text_results]),
"images": [encode_base64(r.image) for r in image_results]
}
# 4. Generate response with vision-language LLM
prompt = f"""
Query: {query}
Context:
{context['text']}
Images: <image_tags_here>
Based on the text and images above, answer the query.
"""
response = vision_llm.generate(
prompt=prompt,
images=context["images"]
)
return response
Related Experiments¶
| Experiment | Description |
|---|---|
| EXP_3501: Multimodal RAG | Build multimodal RAG system |
| LAB-011: Multi-Modal AI | Vision + language hands-on |
| LAB-012: Audio AI | Speech recognition and synthesis |
Assessment¶
- Quiz: 3500: Multimodal Models - Quiz - Test your multimodal knowledge
- Practice: 3500: Multimodal AI - Practice - Build multimodal applications
See Also¶
- Previous Module: 3400: Model Architectures
- Related: 6200: Retrieval Strategies - For multimodal RAG
- Related: 7500: AI Security - Multimodal threats
- Phase Overview: Phase 3 README
Common Issues¶
| Issue | Solution |
|---|---|
| Vision encoder too slow | Use smaller ViT or ResNet backbone |
| Poor image-text alignment | Increase training data or use better loss weighting |
| Audio model hallucinations | Add language model decoding or ensemble voting |
Quick Reference¶
Model Selection by Task¶
| Task | Recommended Model | Reason |
|---|---|---|
| Zero-shot classification | CLIP | No training needed |
| Image captioning | BLIP-2, LLaVA | Good image understanding |
| Visual QA | LLaVA, Flamingo | Strong reasoning |
| Speech recognition | Whisper | Robust, multilingual |
| Voice cloning | Vall-E, AudioLM | High quality |
| Multimodal RAG | CLIP + LLaMA | Simple, effective |
Modalities and Their Representations¶
| Modality | Raw Input | Preprocessing | Encoder |
|---|---|---|---|
| Image | RGB pixels | Resize, normalize | ViT, CNN |
| Audio | Waveform | Mel-spectrogram | Audio Transformer |
| Video | Frame sequence | Per-frame encoding | Video ViT |
| 3D | Point cloud | Voxelization | Point Transformer |
Applications¶
Vision-Language Applications¶
- Image Search β Find images by description
- Visual QA β Answer questions about images
- Image Captioning β Generate descriptions
- OCR + Understanding β Read and understand documents
- Multimodal RAG β Query PDFs with images/charts
Audio Applications¶
- Speech Recognition β Transcribe audio
- Voice Assistants β Natural voice interaction
- Audio Search β Find similar audio
- Music Generation β Create music
- Voice Cloning β Synthesize specific voices
Module Difficulty: Advanced
Estimated Time: 10 hours total