Multimodal Embedding Models: Unified Representations and Cross-Modal Retrieval in Practice
This article explains how multimodal embedding models map text, images, video, and other modalities into a shared semantic vector space for cross-modal retrieval. It covers the role of multimodal large language models as backbone encoders, the use of final-token hidden states for dense representation, and retrieval-oriented fine-tuning with contrastive learning and instruction tuning. It also describes offline indexing, online similarity search, approximate nearest neighbor optimization, evaluation metrics such as Recall@K, nDCG, and MRR, and practical best practices for building accurate and scalable multimodal retrieval systems.
1. Why Multimodal Embeddings Are Needed
With the rapid growth of multimedia applications, user-generated content is increasingly diverse. Data is no longer limited to text; it also includes images, audio, and video. Traditional information retrieval systems often model only a single modality. Text search matches text against a text collection, and image search matches images against an image collection. In real applications, however, users often need cross-modal retrieval, such as searching images with text, searching text with images, or combining text and images as input.
The key challenge is that if text, images, and videos are encoded into independent vector spaces, their similarities cannot be compared directly. Even when two vectors are semantically related, their numeric distance may not be meaningful. The core goal of multimodal embeddings is to map data from different modalities into the same semantic vector space. This ensures that semantically similar content, regardless of modality, is close in vector space and enables cross-modal semantic retrieval.
2. Core Idea of a Unified Representation Space
Multimodal embedding is essentially a representation alignment technique. The model learns to place the text description of a cat near an image of a cat in the vector space, while pushing unrelated content farther apart. During retrieval, both queries and candidates can be converted into vectors, and semantic relevance can be measured by vector distance or similarity.
The difficulty is that raw data structures vary greatly across modalities. Text is a sequence of discrete tokens, while images are pixel tensors. Aligning these inputs into the same space requires a backbone model with cross-modal understanding capability.
3. Model Architecture: Multimodal Large Language Models as Backbone
A mainstream approach is to use a multimodal large language model, or MLLM, as the backbone encoder. An MLLM can accept text, images, and even image-text pairs as inputs and model them jointly.
For representation extraction, a common strategy is to take the final hidden state corresponding to the last token in the model output sequence as the dense vector representation of the entire input sequence. This practice is inspired by established experience in text embedding: tokens at the end of a sentence or at specific positions often aggregate sentence-level semantic information, and their hidden states can effectively represent global meaning.
However, it is important to note that pretrained multimodal large language models have strong multimodal understanding ability, but their original training objectives are generation and dialogue rather than representation learning. Using such models directly to compute similarity often produces poor results. Therefore, retrieval-oriented fine-tuning, also known as alignment, is required so that the output vectors are suitable for similarity matching.
4. Training Paradigm: Instruction Tuning and Contrastive Learning
4.1 Contrastive Learning
Contrastive learning is the core method for training multimodal embeddings. A training instance usually contains three parts:
- A query, q.
- A relevant candidate, c+, as a positive sample.
- A set of irrelevant candidates, {c^-_1, c^-_2, …, c^-_K}, as negative samples.
The training objective is to minimize the cosine distance between relevant pairs while maximizing the cosine distance between irrelevant pairs. In other words, the model should bring a query closer to its truly relevant candidates and push it away from randomly sampled irrelevant candidates. When constructing training samples, positive and negative samples should cover multiple types, including text, images, and combined image-text content, so that the model learns effective discrimination across different modality combinations.
A typical contrastive loss, such as an InfoNCE variant, can be illustrated with the following code:
import torchimport torch.nn.functional as Fdef contrastive_loss(q_emb, pos_emb, neg_embs, temperature=0.05):"""q_emb: [B, D] Query vectorspos_emb: [B, D] Positive sample vectorsneg_embs: [B, K, D] K negative samples for each query"""pos_score = (q_emb * pos_emb).sum(dim=-1, keepdim=True) / temperature # [B, 1]neg_score = torch.bmm(neg_embs, q_emb.unsqueeze(-1)).squeeze(-1) / temperature # [B, K]logits = torch.cat([pos_score, neg_score], dim=-1) # [B, 1+K]labels = torch.zeros(logits.size(0), dtype=torch.long, device=logits.device)return F.cross_entropy(logits, labels)
4.2 Instruction Tuning
To adapt to diverse downstream retrieval tasks, such as visual question answering, image-text retrieval, and video retrieval, a general and effective approach is instruction tuning: attach a customized instruction text i to each retrieval task. For example, for a text-to-image retrieval task, a query can be prefixed with an instruction such as “Retrieve the image that best matches the following description:”. With different instruction prefixes, the same model can flexibly adapt to different tasks, improving the generality and task awareness of the learned representations.
5. Similarity Computation and Retrieval Workflow
After training, an online retrieval workflow usually consists of two steps:
- Offline vectorization: Encode all content in the candidate collection, such as text and images, into vectors and build an index.
- Online retrieval: Encode the user query into a vector, compute similarity against candidate vectors, and return the top-K most relevant results.
Similarity is usually measured by cosine similarity or inner product:
def cosine_similarity(query_vec, candidate_matrix):"""query_vec: [D]; candidate_matrix: [N, D]"""query_norm = F.normalize(query_vec, dim=-1)cand_norm = F.normalize(candidate_matrix, dim=-1)scores = cand_norm @ query_norm # [N]return scores# Retrieve the top K results with the highest similaritytopk_idx = torch.topk(scores, k=10).indices
When the candidate collection is large, exhaustive pairwise comparison can be costly. In this case, approximate nearest neighbor, or ANN, indexing can be introduced to accelerate retrieval. Common engineering practices include storing vectors in a vector search service or vector database and leveraging its built-in indexing and search capabilities, applying vector quantization to reduce storage and computation costs, and using batch processing to improve throughput.
6. Evaluation and Best Practices
To measure multimodal retrieval effectiveness, common industry metrics include Recall@K, nDCG, and MRR. Recall@K measures whether relevant items are retrieved within the top K results. nDCG accounts for ranking quality. MRR focuses on the rank of the first correct result.
Several practical recommendations are worth noting:
- Quality of positive and negative samples determines the upper bound. Negative samples should have a certain level of difficulty, such as hard negatives that are semantically close but irrelevant. The sampling strategy directly affects the model’s discriminative power.
- Instruction design should match the task. Using clear and stable instruction prefixes for different tasks helps the model form task-aware representations.
- Pay attention to modality balance. Avoid having one modality dominate the training data, which can bias the representation toward a single modality.
- Evaluate quantization and retrieval together. After vector compression, retrieval performance should be revalidated to avoid excessive precision loss.
By aligning heterogeneous data into a unified semantic space, multimodal embeddings provide a general and scalable solution for cross-modal retrieval. Mastering the combination of backbone architecture, contrastive learning, and instruction tuning, together with vector retrieval engineering practices, enables the construction of efficient and accurate multimodal information retrieval systems.
