We are going to design a multimodal embedding index that unifies text, vision, and audio features. The goal is to have a system that can index and retrieve items (or generate embeddings) for multiple modalities and then perform retrieval (similarity search) across these modalities.
Steps:
Feature Extraction Models:
Text: Use a pre-trained language model (e.g., BERT, RoBERTa, or a sentence transformer) to extract text embeddings.
Vision: Use a pre-trained vision model (e.g., ResNet, ViT, CLIP's image encoder) to extract image embeddings.
Audio: Use a pre-trained audio model (e.g., VGGish, Wav2Vec2, or CLAP for audio) to extract audio embeddings.
We need to ensure that the embeddings from different modalities are in the same vector space (or at least comparable). One common approach is to use a model that is trained to align multiple modalities (like CLIP for text-image, or CLAP for text-audio). However, we might have to handle cases where we don't have a single model that covers all three.
Option 1: Use separate models and then project to a common space (e.g., via a learned projection or by using a model that already aligns them).
Option 2: Use a multimodal model that can process all three (like a variant of CLIP that also handles audio, or a custom model). But note that such a model might not be readily available.
Since the requirement is to unify text, vision, and audio, we might consider:
For text-image: CLIP (text and image)
For text-audio: CLAP (text and audio) or a model that aligns text and audio.
But then we have two different models and two different embedding spaces (CLIP and CLAP). We need a common space.
Alternatively, we can use a single model that handles all three, but such a model is less common. We might have to train or fine-tune one.
Given the complexity, a practical approach is:
Use CLIP for text and image (so text and image embeddings are in the same space).
Use CLAP for text and audio (so text and audio are in the same space, but note that CLAP's text space might not be the same as CLIP's text space).
So we have two different text embeddings? That's a problem.
Alternatively, we can use a single text model (like a sentence transformer) and then use separate projection heads for image and audio to align with the text space. This is similar to how CLIP is trained: it has a text encoder and an image encoder, and they are trained to align in a common space.
So, we can design:
Text encoder: a pre-trained sentence transformer (e.g., all-MiniLM-L6-v2) which gives a 384-dim vector.
Image encoder: a pre-trained vision transformer (e.g., ViT-B/32) and then a linear projection to 384-dim.
Audio encoder: a pre-trained audio model (e.g., Wav2Vec2) and then a linear projection to 384-dim.
But then we need to train the projection layers to align with the text space. We can do this by having a dataset of (text, image) and (text, audio) pairs and training the projections to minimize the contrastive loss (like CLIP) for each modality pair. However, note that we want a single space for all three, so we might need to train on (text, image, audio) triples? Or at least on pairs and then hope the text space is shared.
Actually, if we fix the text encoder, then we train the image and audio projections to align with the fixed text space. Then, for an image, we get an embedding that is in the same space as the text embeddings (from the fixed text encoder). Similarly for audio.
But note: the text encoder is fixed, so we are not changing it. We are only training the image and audio projection layers (and possibly fine-tuning the image and audio encoders?).
However, the problem says "architect", so we are designing the system. We can assume that we have a way to get embeddings for each modality in a common space.
Let's assume we have the following models:
text_encoder: a model that takes text and outputs a vector (e.g., 384-dim).
image_encoder: a model that takes an image and outputs a vector (e.g., 768-dim for ViT-B/32) and then a linear projection to 384-dim.
audio_encoder: a model that takes an audio waveform/spectrogram and outputs a vector (e.g., 768-dim for Wav2Vec2) and then a linear projection to 384-dim.
We train the image and audio projection layers (and optionally the encoders) on paired data (text-image and text-audio) to align with the text space.
Alternatively, we can use a pre-trained model that already does this alignment for all three? There are models like CLAP that do text and audio, and CLIP for text and image. But again, the text spaces might differ.
Given the time, let's assume we are going to build a system that uses a common text encoder and then separate projection for image and audio, and we train the projections on paired data.
But note: the text encoder is fixed, so the text embeddings are from that fixed model. Then we train the image and audio projections to map to the same space. Then, for retrieval, we can:
Index: for each item (which might be text, image, or audio) we compute its embedding (using the appropriate encoder and projection) and store it in the index.
Query: for a query of any modality, we compute its embedding (again using the appropriate encoder and projection) and then search in the index.
So the index contains vectors of the same dimension (384) and we use a similarity measure (like cosine similarity) to retrieve.
Indexing:
We need an efficient vector index for high-dimensional vectors. We can use:
FAISS (Facebook AI Similarity Search) for approximate nearest neighbor search.
Or Annoy, Hnswlib, etc.
We will choose FAISS because it's widely used and supports various index types (e.g., IndexFlatIP for inner product, which with normalized vectors is equivalent to cosine similarity).
Steps for indexing:
a. For each item in the dataset:
- Determine its modality (text, image, audio).
- Use the appropriate encoder and projection to get a 384-dim vector.
- Normalize the vector (so that we can use inner product as cosine similarity).
- Add the vector to the FAISS index.
b. We also need to store the metadata (like the original data, modality, etc.) so that we can return the actual item and its modality.
So we have:
A FAISS index (which stores the normalized vectors and allows search by vector).
A separate database (could be a simple list or a more structured database) that maps the index id (the position in the FAISS index) to the item's metadata and the original data (or a pointer to it).
Retrieval:
Given a query (of any modality):
- Convert the query to an embedding (using the appropriate encoder and projection) and normalize.
- Search the FAISS index for the top-k similar vectors (using inner product, which is cosine similarity for normalized vectors).
- Return the top-k items (with their metadata) from the database.
We can also support cross-modal retrieval: for example, a text query can retrieve images, and vice versa.
Metrics:
We need to define retrieval metrics to evaluate the system. Common metrics for retrieval:
Recall@k: The proportion of queries for which the true positive (or at least one true positive) is in the top-k results.
Precision@k: The proportion of the top-k results that are true positives.
Mean Average Precision (mAP): A more comprehensive metric that considers the ranking of all relevant items.
However, note that we are dealing with multiple modalities. We might have:
Within-modal retrieval: query and retrieved items are of the same modality.
Cross-modal retrieval: query and retrieved items are of different modalities.
We should evaluate both.
Also, we need a test set with ground truth: for each query, we know which items are relevant (regardless of modality? or only same modality?).
Let's define:
For a text query, an image or audio might be relevant if it matches the text (e.g., the image depicts the same scene as the text describes). So we need a dataset with cross-modal annotations.
Example datasets: COCO for text-image, AudioCaps for text-audio, etc.
We can evaluate:
Text-to-Image retrieval
Image-to-Text retrieval
Text-to-Audio retrieval
Audio-to-Text retrieval
Image-to-Audio and Audio-to-Image? (if we have such annotations)
But note: our index contains all three modalities. So for a text query, we might retrieve both images and audios. We should evaluate separately for each target modality? Or we can have a combined evaluation?
It depends on the use case. If the user wants to retrieve any modality, then we should evaluate the retrieval of all relevant items (regardless of modality) for a query.
However, the metrics above assume a binary relevance per item for a query. We can have:
For each query, we have a set of relevant items (which could be of any modality). Then we compute:
Recall@k: (number of relevant items in top-k) / (total relevant items for the query)
But note: the total relevant items might be of different modalities, and we are retrieving from a mixed index.
Alternatively, we might want to restrict the retrieval to a specific modality? The system should allow that? We can have a modality filter.
For evaluation, we might want to evaluate:
Cross-modal retrieval for each pair (text->image, text->audio, image->text, audio->text, image->audio, audio->image) if we have ground truth.
Implementation Plan:
We'll break down the system into components:
a. Embedding Models:
- Load pre-trained models (text, image, audio) and the projection layers (if any). We assume we have trained the projection layers or we are using a pre-aligned model.
b. Index Builder:
- Given a dataset (with items of different modalities), for each item:
- Load the item (text string, image file, audio file).
- Compute the embedding using the appropriate model and projection.
- Normalize the embedding.
- Add to FAISS index.
- Store the metadata (id, modality, original data path or data itself) in a list or a database.
c. Retriever:
- Given a query (and its modality), compute the normalized embedding.
- Search the FAISS index for top-k.
- Return the top-k items (with metadata) from the stored metadata list.
d. Evaluator:
- Given a test set (queries with ground truth for one or more target modalities), run the retriever for each query and compute metrics (Recall@k, mAP, etc.) for each (query_modality, target_modality) pair.
Challenges:
The alignment of the three modalities: we need a common space. If we use separate projection layers for image and audio, we must train them to align with the text space. We need a dataset that has (text, image) and (text, audio) pairs. We might not have a dataset with all three together. We can train on two separate datasets and hope the text space is shared (since the text encoder is fixed).
The text encoder is fixed, so the text space is fixed. Then we train the image and audio projections to map to that fixed text space. This should work if we have enough paired data.
Alternatively, we can use a model that already aligns text and image (like CLIP) and then for audio, we use CLAP and then align CLAP's text space with CLIP's text space? That would require an alignment between the two text spaces, which is non-trivial.
Given the complexity, let's stick to the plan of using a fixed text encoder and training image and audio projections.
We can use:
Text encoder: sentence-transformers/all-MiniLM-L6-v2 (384-dim)
Image encoder: openai/clip-vit-base-patch32 (512-dim) and then a linear projection to 384-dim.
Audio encoder: facebook/wav2vec2-base-960h (768-dim) and then a linear projection to 384-dim.
Then we train the image and audio projections on paired data (text-image and text-audio) with a contrastive loss (like CLIP) but with the text embeddings fixed.
However, note that the image encoder from CLIP is already trained to align with CLIP's text encoder (which is different from our sentence transformer). So if we fix our text encoder and train a projection on top of the CLIP image encoder, we are effectively trying to align the CLIP image space (which is already aligned with CLIP text) to our sentence transformer text space. That might be difficult.
Alternatively, we can use the CLIP image encoder and then a projection to our text space, and train that projection on (our text, CLIP image) pairs. Similarly for audio.
But then we are not using the CLIP text encoder at all? We are using our own text encoder for text.
So we have:
For text: use sentence transformer.
For image: use CLIP image encoder + projection (trained to align with sentence transformer text).
For audio: use Wav2Vec2 + projection (trained to align with sentence transformer text).
We need paired data: (sentence transformer text embedding, CLIP image embedding) and (sentence transformer text embedding, Wav2Vec2 audio embedding). We can get the CLIP image embeddings and Wav2Vec2 audio embeddings offline, and then train the projections with a contrastive loss (with the text embeddings fixed).
Code Structure:
We'll design:
models.py: defines the encoders and projections.
index_builder.py: builds the FAISS index and metadata.
retriever.py: retrieves given a query.
evaluator.py: evaluates on a test set.
We assume we have trained models saved (the projection layers) and the encoders are pre-trained.
Steps in code:
a. Load the models (text, image, audio) and the projection layers (which are just linear layers) from saved checkpoints.
b. For each item, compute embedding:
code
if modality == 'text':
embedding = text_encoder(text) # already 384-dim? or we need to project?
# If the text encoder outputs 384, then no projection needed for text.
elif modality == 'image':
image_features = image_encoder(image) # e.g., 512-dim from CLIP
embedding = image_projection(image_features) # to 384
elif modality == 'audio':
audio_features = audio_encoder(audio) # e.g., 768-dim from Wav2Vec2
embedding = audio_projection(audio_features) # to 384
Then normalize.
c. Add to FAISS index.
d. Store metadata in a list: metadata = [{id: 0, modality: 'text', data: ...}, ...]
e. For retrieval: given a query of modality M, compute the normalized embedding, then search in FAISS, get the indices, and then retrieve the metadata for those indices.
Evaluation:
We need a test set that for each query (with modality Q) has a set of ground truth items (with modality T). We'll assume the test set is given as:
code
test_queries = [
{
'query': ... , # the query data (text, image, or audio)
'modality': Q,
'ground_truth': [
{'id': id1, 'modality': T},
...
]
}
]
Then for each query:
code
- Compute the query embedding (using the appropriate model for Q).
- Search the index (which has all modalities) and get top-k indices.
- From the top-k, filter to only those with modality T (if we are evaluating for a specific T) and then check how many are in the ground_truth set (by id).
- Compute recall@k.
We might want to evaluate for multiple target modalities for the same query? For example, a text query might have both image and audio ground truth. Then we can compute two recalls: one for images and one for audios.
So we can define:
code
For each query, for each target modality T that appears in the ground_truth:
- Filter the top-k to modality T.
- Compute recall@k for that T.
Then average over queries and modalities.
Extensions:
We might want to support batch retrieval.
We might want to support filtering by modality (so that when we search, we only consider items of a certain modality). This can be done by post-processing the results (filter by modality) or by building separate indices per modality? But then cross-modal retrieval would require searching across indices. It's easier to have one index with all modalities and then filter by modality after retrieval.
However, note that if we want to retrieve only images for a text query, we can filter the results to only images. But the search is done over all vectors, so we are comparing the text query vector to all vectors (text, image, audio). That's fine because we want cross-modal.
But if the user only wants images, we can filter the results to only images. So we don't need separate indices.
Summary:
We have designed a multimodal embedding index that unifies text, image, and audio by projecting them into a common space (384-dim) using a fixed text encoder (sentence transformer) and trained projection layers for image and audio.
The system:
Uses FAISS for efficient similarity search.
Stores metadata separately.
Supports retrieval of any modality for a query of any modality.
Evaluation can be done for any (query_modality, target_modality) pair.
Now, we need to implement this.
However, note that the user asked to "architect", so we are providing the design. We can also provide a skeleton code.
Let's write a high-level code structure:
File: multimodal_index.py
Classes:
code
Final Design:
We have:
code
- Three encoders (text, image, audio) and two projection layers (image_proj, audio_proj). The text encoder does not need a projection because we are using its space as the common space.
- Three FAISS indices (one per modality).
- Metadata stored per modality.
Steps:
code
Training the projections:
We have:
text_encoder: fixed, outputs 384-dim.
image_encoder: pre-trained (e.g., CLIP ViT-B/32) -> 512-dim, then image_proj: Linear(512, 384)
audio_encoder: pre-trained (e.g., Wav2Vec2) -> 768-dim, then audio_proj: Linear(768, 384)
We train image_proj and audio_proj on paired data:
For text-image pairs:
text_emb = text_encoder(text) # (batch, 384)
image_emb = image_encoder(image) # (batch, 512)
proj_image_emb = image_proj(image_emb) # (batch, 384)
loss = contrastive_loss(text_emb, proj_image_emb)
Similarly for text-audio.
We don't train the text_encoder, image_encoder, or audio_encoder? We can optionally fine-tune them, but to keep the text space fixed, we only train the projections.
Then we save the projection layers.
Implementation:
code
We assume we have the models and projections saved.
In the index builder, we load:
text_encoder = SentenceTransformer('all-MiniLM-L6-v2')
image_encoder = CLIPVisionModel.from_pretrained('openai/clip-vit-base-patch32')
audio_encoder = Wav2Vec2Model.from_pretrained('facebook/wav2vec2-base-960h')
image_proj = torch.load('image_proj.pth')
audio_proj = torch.load('audio_proj.pth')
Then we build the index.
class ProjectionHead(nn.Module):
"""Learnable projection to unified space"""
def __init__(self, input_dims: Dict[str, int], unified_dim=512):
super().__init__()
self.projections = nn.ModuleDict({
modality: nn.Linear(dim, unified_dim)
for modality, dim in input_dims.items()
})
self.layer_norm = nn.LayerNorm(unified_dim)
def forward(self, x: torch.Tensor, modality: str) -> torch.Tensor:
x = self.projections[modality](x)
return self.layer_norm(x)
# Training strategy:
# 1. Use contrastive loss (NT-Xent) on paired modalities
# 2. Initialize with supervised alignment datasets:
# - COCO (text-image)
# - AudioCaps (text-audio)
# - HowTo100M (video with audio+text)
3. Vector Indexing Engine
Hybrid Index Configuration
python
class MultimodalIndex:
def __init__(self, unified_dim=512, index_type="hybrid"):
self.unified_dim = unified_dim
# Primary index for approximate search
self.primary_index = faiss.IndexHNSWFlat(
unified_dim, # M=32 for graph connectivity
faiss.METRIC_INNER_PRODUCT # Cosine similarity with normalized vectors
)
# Secondary metadata store
self.metadata = [] # List of dicts with modality, id, source, timestamp
# Modality-specific filters (for efficient filtering)
self.modality_index = defaultdict(list) # modality -> list of FAISS ids
# Optional: IVF for large-scale (>1M vectors)
if index_type == "ivf":
self.primary_index = faiss.IndexIVFPQ(
faiss.IndexHNSWFlat(unified_dim, 32),
unified_dim,
nlist=1024, # number of Voronoi cells
M=16, # number of sub-quantizers
nbits=8 # bits per sub-quantizer
)
def add_items(self, embeddings: np.ndarray, metadatas: List[dict]):
"""Add multimodal items to index"""
# embeddings shape: (n, unified_dim), normalized
self.primary_index.add(embeddings)
start_id = len(self.metadata)
for i, meta in enumerate(metadatas):
meta['faiss_id'] = start_id + i
self.metadata.append(meta)
self.modality_index[meta['modality']].append(start_id + i)
def search(
self,
query_embedding: np.ndarray,
top_k: int = 100,
modality_filter: Optional[str] = None,
score_threshold: float = 0.0
) -> List[dict]:
"""Search with optional modality filtering"""
# Search across all modalities first
distances, indices = self.primary_index.search(
query_embedding.reshape(1, -1),
top_k * 3 # Get extra for filtering
)
results = []
for dist, idx in zip(distances[0], indices[0]):
if idx == -1: # FAISS padding
break
if dist < score_threshold:
break
meta = self.metadata[idx]
if modality_filter and meta['modality'] != modality_filter:
continue
results.append({
**meta,
'score': float(dist),
'rank': len(results) + 1
})
if len(results) >= top_k:
break
return results
4. Retrieval Metrics Suite
Comprehensive Evaluation Framework
python
class RetrievalMetrics:
@staticmethod
def compute_metrics(
results: List[dict],
ground_truth: Set[int], # Set of relevant item IDs
k_values: List[int] = [1, 5, 10, 50, 100]
) -> Dict[str, float]:
"""Compute standard retrieval metrics"""
metrics = {}
# Relevance array (1 if relevant, 0 otherwise)
relevance = [1 if r['faiss_id'] in ground_truth else 0 for r in results]
for k in k_values:
if k > len(relevance):
continue
# Precision@K
top_k_relevant = sum(relevance[:k])
metrics[f'P@{k}'] = top_k_relevant / k
# Recall@K
total_relevant = len(ground_truth)
if total_relevant > 0:
metrics[f'R@{k}'] = top_k_relevant / total_relevant
else:
metrics[f'R@{k}'] = 0.0
# F1@K
p = metrics[f'P@{k}']
r = metrics[f'R@{k}']
if p + r > 0:
metrics[f'F1@{k}'] = 2 * p * r / (p + r)
else:
metrics[f'F1@{k}'] = 0.0
# MAP (Mean Average Precision)
ap = 0
num_relevant = 0
for i, rel in enumerate(relevance, 1):
if rel == 1:
num_relevant += 1
ap += num_relevant / i
if num_relevant > 0:
metrics['MAP'] = ap / num_relevant
else:
metrics['MAP'] = 0.0
# MRR (Mean Reciprocal Rank)
for i, rel in enumerate(relevance, 1):
if rel == 1:
metrics['MRR'] = 1.0 / i
break
else:
metrics['MRR'] = 0.0
return metrics
@staticmethod
def cross_modal_metrics(
queries: List[dict],
index: MultimodalIndex,
target_modality: str,
k_values: List[int] = [1, 5, 10]
) -> Dict[str, float]:
"""Evaluate cross-modal retrieval (e.g., text→image)"""
all_metrics = defaultdict(list)
for query in queries:
# Get query embedding based on query modality
query_emb = get_embedding(query['data'], query['modality'])
# Search in target modality
results = index.search(
query_emb,
top_k=max(k_values),
modality_filter=target_modality
)
# Get ground truth IDs for this query
gt_ids = set(query['ground_truth'][target_modality])
# Compute metrics
metrics = RetrievalMetrics.compute_metrics(results, gt_ids, k_values)
for metric, value in metrics.items():
all_metrics[metric].append(value)
# Average across queries
return {m: np.mean(vals) for m, vals in all_metrics.items()}
5. Advanced Features
a) Dynamic Weighted Fusion
python
class FusionStrategy:
@staticmethod
def late_fusion(embeddings: List[np.ndarray], weights: List[float]) -> np.ndarray:
"""Weighted combination of multiple modality embeddings"""
assert len(embeddings) == len(weights)
weighted_sum = sum(w * emb for w, emb in zip(weights, embeddings))
return normalize(weighted_sum)
@staticmethod
def attention_fusion(embeddings: List[np.ndarray]) -> np.ndarray:
"""Learnable attention over modality embeddings"""
# Implement cross-attention mechanism
# Requires training on multimodal tasks
pass
b) Hard Negative Mining
python
class HardNegativeMiner:
def __init__(self, index: MultimodalIndex):
self.index = index
def mine_hard_negatives(
self,
positive_pairs: List[Tuple[str, str, str]], # (query_modality, target_modality, id)
num_negatives: int = 5
) -> List[dict]:
"""Find hard negatives for training"""
hard_negatives = []
for q_mod, t_mod, pos_id in positive_pairs:
# Get positive embedding
pos_meta = next(m for m in self.index.metadata
if m['faiss_id'] == pos_id and m['modality'] == t_mod)
pos_emb = self.index.primary_index.reconstruct(pos_id)
# Search for nearest neighbors of different modality
results = self.index.search(
pos_emb.reshape(1, -1),
top_k=num_negatives * 3,
modality_filter=t_mod # Same target modality
)
# Filter out positives and select hard negatives
negatives = [r for r in results if r['faiss_id'] != pos_id][:num_negatives]
hard_negatives.extend(negatives)
return hard_negatives
c) Incremental Indexing
python
class IncrementalIndex(MultimodalIndex):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.buffer = [] # Buffer for batch additions
self.buffer_metadata = []
self.buffer_size = 10000
def add_buffer(self, embeddings: np.ndarray, metadatas: List[dict]):
"""Add to buffer instead of immediate indexing"""
self.buffer.append(embeddings)
self.buffer_metadata.extend(metadatas)
if len(self.buffer) * embeddings.shape[0] >= self.buffer_size:
self.flush_buffer()
def flush_buffer(self):
"""Commit buffer to main index"""
if not self.buffer:
return
all_embeddings = np.vstack(self.buffer)
super().add_items(all_embeddings, self.buffer_metadata)
self.buffer = []
self.buffer_metadata = []
6. Deployment Configuration
Scalability Considerations
yaml
# config.yaml
index:
type: "hnsw" # or "ivf", "flat" for small datasets
dimension: 512
hnsw:
M: 32
ef_construction: 200
ef_search: 50
storage:
metadata_backend: "postgresql" # or "mongodb", "redis"
vector_backend: "faiss" # or "milvus", "qdrant"
performance:
batch_size: 1024
num_threads: 8
use_gpu: true
monitoring:
track_latency: true
track_hit_rate: true
track_modality_distribution: true
But note: our index has all modalities, so for a text query we can retrieve text, image, and audio. We should evaluate:
For text queries: retrieve all modalities (and we have ground truth for each modality?).
It might be simpler to evaluate per modality pair, because the ground truth might only be available for certain pairs (like COCO only has text-image pairs).
So, for a given query modality and a target modality, we can compute the metrics.
We can design the evaluation to be flexible: for a set of queries, we have a ground truth mapping from query to relevant items (with modality specified). Then we can compute:
For each query, we retrieve the top-k (without modality restriction) and then check the relevant items (of the target modality) in the top-k.
But note: the ground truth for a query might have relevant items of multiple modalities. We can compute:
Recall@k (for a specific target modality) = (# of relevant items of that modality in top-k) / (total relevant items of that modality for the query)
And then average over queries.
Alternatively, we can compute:
Recall@k for each modality separately, and then also a combined recall (considering all modalities) if the ground truth has multiple modalities.
However, the ground truth datasets are often designed for a specific pair (like text-image). So we might only have ground truth for one target modality per query.
Therefore, we might evaluate:
For text queries (from COCO): we have ground truth images. We retrieve from the entire index (which has text, images, audio) but we only consider the images in the ground truth as relevant. Then we compute recall@k for images.
Similarly for other pairs.
But note: our index also contains text and audio for the same image? In COCO, each image has multiple captions. So if we index both the image and the captions (text) for the same image, then for a text query (caption) we might retrieve the same image (which is correct) or other images. But also we might retrieve the text captions of the same image? That would be within-modal (text) and cross-modal (text->text) but the ground truth is only for images.
So we have to be careful: the ground truth for a text query in COCO is a set of images. So we should only consider the images in the top-k as relevant, and ignore the text and audio.
Therefore, in the evaluation, we need to know the modality of the ground truth relevant items. And we only count those in the top-k.
So steps for evaluation:
For a given query (with modality Q) and a target modality T (for which we have ground truth):
code
- Compute the query embedding (using Q's encoder).
- Search the index and get top-k results (each result has an id and a modality).
- From the top-k, filter to only those with modality T.
- Check how many of these are in the ground truth set for this query (for modality T).
- Compute recall@k = (number of relevant items of modality T in top-k) / (total number of relevant items of modality T for the query).
We can do this for each query and then average.
We can also compute mAP for a given (Q, T) pair.
This is a feasible pipeline.
However, note that the CLIP image encoder is already aligned with CLIP text, but we are aligning it with a different text space. This might degrade the performance for image-text retrieval? But if the sentence transformer text space is also a good language space, then it might work.
Alternatively, we can use the CLIP text encoder as our text encoder? Then we have:
Audio: then we need to align audio to the same 512-dim CLIP text space.
But then we need a dataset of (CLIP text, audio) pairs to train the audio projection. We can use CLAP which already aligns text and audio, but CLAP uses a different text encoder (e.g., RoBERTa) and audio encoder. So we would have to use CLAP's audio encoder and then project to CLIP's text space? That's two steps.
Given the time, let's stick to the first plan (sentence transformer for text, and then project image and audio to that space) because it's simpler and the sentence transformer is a good general text encoder.
But note: the sentence transformer is not trained to align with images or audio. So we are relying on the projection training to do the alignment.
We'll assume we have the training data and we train the projections.
class MultimodalEmbeddingIndex:
def __init__(self, text_encoder, image_encoder, audio_encoder, image_projection, audio_projection, device='cuda'):
self.text_encoder = text_encoder
self.image_encoder = image_encoder
self.audio_encoder = audio_encoder
self.image_projection = image_projection
self.audio_projection = audio_projection
self.device = device
self.index = None # FAISS index
self.metadata = [] # list of dicts
def _get_embedding(self, data, modality):
# data: for text, a string; for image, a PIL image or tensor; for audio, a waveform or spectrogram.
# returns: normalized torch tensor of shape (1, embedding_dim)
if modality == 'text':
with torch.no_grad():
emb = self.text_encoder(data) # assume returns tensor of shape (1, 384) or (384,)
elif modality == 'image':
with torch.no_grad():
img_feat = self.image_encoder(data) # e.g., (1, 512)
emb = self.image_projection(img_feat) # (1, 384)
elif modality == 'audio':
with torch.no_grad():
aud_feat = self.audio_encoder(data) # e.g., (1, 768)
emb = self.audio_projection(aud_feat) # (1, 384)
# Normalize
emb = emb / emb.norm(dim=-1, keepdim=True)
return emb.cpu().numpy().astype('float32')
def build_index(self, dataset):
# dataset: a list of dicts, each with keys: 'modality', 'data', and maybe other metadata.
# We assume the dataset is given as a list of items.
embeddings = []
for i, item in enumerate(dataset):
emb = self._get_embedding(item['data'], item['modality'])
embeddings.append(emb)
self.metadata.append({
'id': i,
'modality': item['modality'],
'data': item['data'], # or store a path if data is large
# ... other metadata
})
embeddings = np.vstack(embeddings) # (n, 384)
# Build FAISS index
self.index = faiss.IndexFlatIP(embeddings.shape[1])
self.index.add(embeddings)
def search(self, query, query_modality, k=10, modality_filter=None):
# query: the query data (text, image, audio)
# query_modality: 'text', 'image', 'audio'
# k: number of results to return
# modality_filter: if not None, only return results of this modality.
query_emb = self._get_embedding(query, query_modality)
distances, indices = self.index.search(query_emb, k)
results = []
for idx, dist in zip(indices[0], distances[0]):
meta = self.metadata[idx]
if modality_filter is not None and meta['modality'] != modality_filter:
continue
results.append({
'id': meta['id'],
'modality': meta['modality'],
'data': meta['data'],
'score': dist.item()
})
return results
Then we can have an evaluator:
def evaluate(index, test_queries, k_values=[1,5,10], modality_pairs=None):
# test_queries: list of dicts as above.
# modality_pairs: list of (query_modality, target_modality) to evaluate. If None, evaluate all pairs that appear in the ground truth.
# We assume that each query has ground_truth for one or more target modalities.
# We'll compute recall@k for each pair and each k.
# Collect all unique (query_modality, target_modality) pairs from the test_queries if modality_pairs is None.
if modality_pairs is None:
modality_pairs = set()
for q in test_queries:
q_mod = q['modality']
for gt in q['ground_truth']:
t_mod = gt['modality']
modality_pairs.add((q_mod, t_mod))
modality_pairs = list(modality_pairs)
# Initialize results: dict of (q_mod, t_mod) -> dict of k -> list of recalls (one per query)
results = {pair: {k: [] for k in k_values} for pair in modality_pairs}
for query in test_queries:
q_mod = query['modality']
# For each target modality that we are evaluating and that is in the ground truth for this query?
# Actually, we want to evaluate for each (q_mod, t_mod) in modality_pairs, but only if the query has ground truth for t_mod?
# We'll check: for each pair in modality_pairs, if the query has at least one ground truth item of modality t_mod, then we evaluate.
for (q_mod_pair, t_mod) in modality_pairs:
if q_mod_pair != q_mod:
continue
# Check if the query has any ground truth of modality t_mod
gt_items = [gt for gt in query['ground_truth'] if gt['modality'] == t_mod]
if len(gt_items) == 0:
continue
gt_ids = set(gt['id'] for gt in gt_items)
# Search with modality filter set to t_mod? But note: we are evaluating for target modality t_mod, so we want to retrieve only items of that modality?
# Actually, the index has all modalities. We want to see if the relevant items of modality t_mod are in the top-k. So we can either:
# Option 1: search without filter and then count only the ones with modality t_mod that are in the ground truth.
# Option 2: search with modality_filter=t_mod so that we only consider items of that modality. But note: the ground truth is only for modality t_mod, so we don't care about other modalities.
# We'll do Option 2: because we are interested in retrieving items of the target modality. However, note that the user might want to retrieve any modality? But the ground truth is only for t_mod, so we should only consider t_mod.
# So we set modality_filter=t_mod.
results_list = index.search(query['query'], q_mod, k=max(k_values), modality_filter=t_mod)
# Now, we have a list of results (each with 'id') of modality t_mod.
retrieved_ids = [r['id'] for r in results_list]
for k in k_values:
top_k = set(retrieved_ids[:k])
num_retrieved_and_relevant = len(top_k & gt_ids)
recall = num_retrieved_and_relevant / len(gt_ids) if len(gt_ids) > 0 else 0
results[(q_mod, t_mod)][k].append(recall)
# Now average the recalls over queries for each pair and k.
final_metrics = {}
for pair, k_dict in results.items():
final_metrics[pair] = {}
for k, recalls in k_dict.items():
final_metrics[pair][k] = np.mean(recalls) if recalls else 0
return final_metrics
This is a basic structure.
Note: In the search function, we are using modality_filter. But note that the index.search returns results of the filtered modality, but the number of results might be less than k if there are not enough items of that modality? We are taking the top-k (which are the top-k of that modality because we filtered). But note: the FAISS search returns the top-k over all, then we filter. That's not correct because we are filtering after the search. We want the top-k of the filtered modality.
How to do modality filtering in FAISS? We cannot easily do that in FAISS because FAISS doesn't know about modality. So we have two options:
Option 1: Do the search without filter, get more than k (say 10*k) and then filter by modality and take the top-k of the filtered set? But note: the scores are inner products, and we want the highest scoring items of the target modality. However, the top-k overall might not include the top-k of the target modality because there could be many high-scoring items of other modalities.
Example: for a text query, there might be many text items that are very similar (because they are on the same topic) and they might have higher scores than the relevant images. So if we take the top-k overall and then filter to images, we might get low recall for images.
Therefore, we need to search specifically for the target modality. We cannot do that with a single index that has all modalities. We have two options:
a. Have separate indices for each modality. Then for a query of modality Q and target modality T, we use the index for T? But note: the query is of modality Q, and we want to find items of modality T. We need to compute the query embedding (using Q's encoder) and then search in the T index. But the T index contains embeddings of modality T (computed with T's encoder). And we have trained the projections so that the query embedding (from Q) is in the same space as the T embeddings. So we can do that.
But then we have to maintain multiple indices? Alternatively, we can have one index for each modality? That would be:
code
- text_index: contains text embeddings (from text encoder, no projection because text is already in the space).
- image_index: contains image embeddings (from image encoder + projection).
- audio_index: contains audio embeddings (from audio encoder + projection).
Then for a query of modality Q and target modality T, we use the index for T.
But wait: the text embeddings are from the sentence transformer, and the image embeddings are from CLIP image + projection to sentence transformer space. So they are in the same space. Therefore, we can put all in one index and then when searching for a target modality T, we only want to consider the vectors in the index that are of modality T. We can do:
code
- When building the index, we also store the modality for each vector.
- Then at search time, we get the top-k overall, but then we have to re-rank? Or we need to get the top-k of the target modality.
Since FAISS doesn't support filtering by metadata, we have to do:
code
Option A: Do a two-step retrieval:
Step 1: retrieve a large number (e.g., 1000) of nearest neighbors (without modality filter).
Step 2: filter by modality and then take the top-k by score.
But note: the scores are inner products, and we are using normalized vectors, so the score is cosine similarity. We want the highest scoring items of the target modality. However, the top-1000 might not include all the relevant items of the target modality if there are many items of other modalities with higher scores.
Option B: Maintain separate indices for each modality. Then for a query of modality Q and target modality T, we compute the query embedding (using Q's encoder) and then search in the T index. This way, we are only comparing with items of modality T.
This seems more correct. And it's efficient because each index is smaller.
But then we have to build three indices. And note that the text index is built from text embeddings (no projection), the image index from image embeddings (with projection), and audio index from audio embeddings (with projection). And they are all in the same 384-dim space.
So we can have:
self.indices = {
'text': faiss.IndexFlatIP(384),
'image': faiss.IndexFlatIP(384),
'audio': faiss.IndexFlatIP(384)
}
And then we also have three metadata lists for each modality.
Then when building, we add to the appropriate index.
Then in search, we specify the target modality and use that index.
But then what about within-modal retrieval? For example, text to text: we use the text index. Cross-modal: text to image: we use the image index (with the text query embedding).
This seems better.
So we change:
In build_index, for each item:
- compute embedding (as before)
- add to self.indices[modality] (and also to a metadata list for that modality? or we can have a global metadata list with id and modality, and then the indices are separate?).
We need to map from index id (in each modality index) to the global id? Or we can have:
For each modality, we have:
- index: FAISS index for that modality.
- metadata: list of metadata for that modality (in the same order as added to the index).
Then when we search in the image index, we get indices that are local to the image index. Then we can get the metadata from the image_metadata list.
But then we don't have a global id? We can assign a global id when building, but the indices are separate. Alternatively, we can have a global counter and assign an id to each item, and then store in each modality index the global id? But then the FAISS index stores vectors and we need to map the local index id to the global id.
Actually, FAISS returns the index id (the position in the index) for the modality we searched. So we can have:
self.metadata_by_modality = {
'text': [],
'image': [],
'audio': []
}
Then when building:
for item in dataset:
emb = ...
modality = item['modality']
self.indices[modality].add(emb)
self.metadata_by_modality[modality].append({
'global_id': global_id, # optional, if we want a global id
'modality': modality,
'data': item['data'],
...
})
global_id += 1
Then when searching for target modality T:
distances, indices = self.indices[T].search(query_emb, k)
results = []
for idx, dist in zip(indices[0], distances[0]):
meta = self.metadata_by_modality[T][idx]
results.append({...})
This way, we only search in the target modality index.
But note: the query embedding is computed from the query modality (which might be different from T). We are using the same embedding function (which maps to the common space) for the query, regardless of the target modality. And the target modality index contains vectors that are in the same common space. So it's valid.
So we change the design to have separate indices per modality.
Then the search function becomes:
def search(self, query, query_modality, target_modality, k=10):
# Compute query embedding using query_modality's encoder.
query_emb = self._get_embedding(query, query_modality)
# Search in the target_modality index.
distances, indices = self.indices[target_modality].search(query_emb, k)
results = []
for idx, dist in zip(indices[0], distances[0]):
meta = self.metadata_by_modality[target_modality][idx]
results.append({
'id': meta.get('global_id', idx), # if we stored global_id, use it, else use local index id?
'modality': target_modality,
'data': meta['data'],
'score': dist.item()
})
return results
But note: the same item might appear in multiple modalities? For example, an image and its caption (text) are two separate items. So we have two separate entries in the index (one in image index, one in text index). That's fine.
Then in the evaluator, for a query of modality Q and target modality T, we call search with target_modality=T.
This design is cleaner.
Let's adjust the code accordingly.
However, note: if we have separate indices, then we cannot do a single search that returns mixed modalities? But the requirement is to unify and allow cross-modal retrieval. We are doing cross-modal by searching in the target modality index with a query from another modality. That's exactly what we want.
So we are good.
Let's write the code accordingly.
Note: The image_encoder and audio_encoder are large models, so we might want to use a GPU.
We'll write the code in a way that it can run on GPU if available.
We assume the data loading for images and audio is done outside and passed as appropriate tensors.
This is a high-level design and code structure.
We can now write the code.
However, note: the user might not have the training code for the projections. We assume they are already trained.
Let's write the code for the index building and retrieval.
We'll create a class MultimodalIndex that can be initialized with the models and projections, and then build the index and search.
We'll also write a separate function for evaluation.
Due to the complexity, we'll write the code in a single file for simplicity.
Let's code accordingly.
I'll design a comprehensive multimodal embedding index system that unifies text, vision, and audio features with robust retrieval metrics. Here's the architectural blueprint: