On-Device Multimodal Embeddings: Engineering a Unified Vector Space
This article examines compact multimodal embedding models that map text, code, images, video, and audio into a shared vector space for on-device semantic search, retrieval-augmented generation, classification, and clustering. It covers model architectures, cross-modal alignment through contrastive learning, storage and retrieval tradeoffs with Matryoshka representation learning, common on-device scenarios, and practical engineering pitfalls. The goal is to show how a unified multimodal embedding system can be designed, evaluated, and deployed under the constraints of mobile and laptop environments.
Why One Vector Space for Five Modalities
1. The fragmentation of traditional multimodal retrieval
In the past, cross-modal retrieval often followed a “one modality, one model” approach: text was handled by text embeddings, images relied on image-text matching models, and audio or video was usually transcribed into text before processing. This approach introduces three problems:
- Index fragmentation: Each modality maintains a separate index. Data updates, deletions, and version management differ across modalities, and operational cost grows linearly with the number of modalities.
- Missing capabilities: A request such as “find the slide screenshot that shows this proposal” or “locate a specific discussion in a meeting recording with one sentence” is difficult to handle. Traditional systems either cannot complete the task or must first transcribe content and then rely on approximate matching, allowing errors to accumulate across stages.
- Inconsistent performance: Vectors from different models differ in dimensionality, normalization method, and similarity score distribution. A single set of thresholds and ranking rules rarely works well across all modalities.
2. What a unified embedding space solves
The goal of a unified embedding space is straightforward: whether the query comes from text, an image, or another modality, and whether the document is a paragraph, a code snippet, a screenshot, a video segment, or an audio clip, both vectors can be placed in the same space and compared with the same similarity metric.
This makes it possible to build a knowledge base that mixes text passages, code snippets, screenshots, video segments, and audio recordings, and to support four major query types:
- Cross-modal retrieval: Search for screenshots with text, find documents with images, or locate video segments with a text description.
- Natural-language code search: Enter a description such as “the function that handles payment callbacks” to find the relevant implementation without needing to remember the function name.
- On-device local indexing: Build local indexes for photo albums, recordings, documents, and code repositories, and complete search entirely on the device.
- Content understanding and clustering: Classify, deduplicate, and cluster multimodal content, such as organizing images by topic or grouping support tickets by content.
3. The unique value of on-device deployment
Running embedding computation on-device is about more than speed:
- Privacy: Search content, recordings, and screenshots do not need to be uploaded to the cloud.
- Offline availability: Local content can still be searched under weak network or no network conditions.
- Cost: It avoids paying for each cloud inference request and also reduces network bandwidth consumption.
On-device deployment also introduces hard constraints: limited memory, compute restricted by power and thermal limits, and sensitivity to application size. A practical on-device embedding model should therefore meet at least four requirements:
- The parameter count must be small enough that runtime memory remains manageable.
- The model should support loading only the encoders needed for a given scenario, avoiding memory overhead for unused capabilities.
- The embedding dimension should be adjustable so storage budgets can be controlled.
- Inference latency must be low enough to return results in real time while the user is still typing a search query.
Technical Foundations of a Unified Embedding Space
1. Model design: shared backbone and projection alignment
There are two common routes to building a unified embedding space:
- Multiple encoders with shared projection: Text, vision, and audio each use dedicated encoders to extract features, and projection layers map those features into the same vector space. This gives fine-grained modeling per modality, but the architecture is more complex and parameter-heavy.
- Unified backbone with modality adaptation: A single Transformer backbone processes all modalities, and modality tags or lightweight adapters distinguish different inputs. This approach shares more parameters and is better suited to parameter-constrained on-device scenarios.
Regardless of the route, the key requirement is that output embeddings fall into the same space, use the same dimensionality, and are L2-normalized so that the inner product is equivalent to cosine similarity.
A useful engineering design is tiered loading: the encoder can be split into a lightweight “text plus code” tier and a full-modal tier, and applications can load only the part they need. For example, a text-only semantic search service can load only the lightweight tier to reduce memory usage and cold-start time, while the full-modal tier can be enabled when screenshots or recordings need to be processed. For compact multimodal embedding models, the lightweight tier may be on the order of a few hundred million parameters, while the full-modal tier is usually below one billion. The exact details depend on the model documentation.
From an engineering perspective, tiered loading means the retrieval code and index format do not need to change. The encoder is simply replaced, so the application-side adaptation cost is low.
2. Cross-modal alignment: contrastive learning is key
The essence of a unified embedding space is to make “semantic similarity” more important than “modality difference.” The mainstream approach is contrastive learning:
- Build positive pairs: Different modality representations of the same content are treated as positive labels, such as an image and its description, a video segment and its speech transcript, or code and its documentation.
- Introduce hard negatives: Relying only on other samples in the same batch as negatives often leads the model to learn coarse distinctions. Adding hard negatives that look similar but have different semantics can significantly improve fine-grained discrimination, such as two UI screenshots that look alike but serve different functions.
- Instruction-style training: Add a task instruction prefix on the query side, such as “Find relevant documents for this search query:”. This helps the model understand that the input is a search query rather than a document, reducing the asymmetry in length and phrasing between queries and documents.
Instruction-style training also explains why prefix conventions are so important. During training, the model learns to depend on the position and format of the prefix. At inference time, if the prefix is missing or inconsistent, the input deviates from the training distribution, and retrieval quality degrades.
3. Training process: from alignment to retrieval optimization
A typical training pipeline includes three progressive stages:
- Alignment pretraining: Train cross-modal alignment on large-scale weakly labeled or synthetic data so that different modalities can be roughly mapped into the same space.
- Contrastive fine-tuning: Fine-tune with high-quality query-document pairs, introducing hard negatives and instruction prefixes so that the model is optimized for real retrieval tasks.
- Targeted optimization: Optimize separately for technical content such as code retrieval. Code differs significantly from natural language: identifiers are highly specific, and commenting style is inconsistent. Fine-tuning with training pairs built from code and documentation, or code and queries, can usually improve code retrieval performance.
This also explains why many multimodal embedding models have improved significantly on code search and technical-content retrieval, making them suitable for local code repository indexing, code retrieval for AI agents, and similar scenarios.
4. Do not ignore the “modality gap”
Even after thorough alignment, vectors from different modalities often form relatively concentrated cone-shaped regions in the embedding space. This is known as the modality gap. It does not invalidate the unified space, but it has two practical consequences:
- The same similarity threshold does not have the same meaning for within-modality retrieval and cross-modal retrieval. Thresholds should be calibrated separately for each scenario.
- If a modality has too little training data or weak encoding quality, it can become a weak point and drag down overall performance.
From an engineering perspective, retrieval metrics should be evaluated separately for each modality. Once a weak modality is identified, targeted data supplementation or separate tuning can be performed.
Matryoshka Representation Learning: Storage and Retrieval Tradeoffs
1. Principle: one vector, multiple precision levels
A unified space places all modalities into the same index, and the number of vectors grows quickly. Storage becomes one of the main bottlenecks on-device. Matryoshka Representation Learning (MRL) provides a practical solution.
During training, the model is required to ensure that the leading dimensions of a vector can independently support retrieval. For example, the first 64 dimensions should be usable for retrieval, the first 128 dimensions should also be usable, and so on up to the full dimension. Like a Russian nesting doll, each layer can be used independently.
At inference time, the vector can be truncated to the first k dimensions and re-normalized to obtain a lower-dimensional embedding. No retraining or additional compression is required. The index can store only the truncated vectors, and query vectors can be truncated in the same way, allowing both sides to be compared in the same lower-dimensional space.
2. A storage calculation
Assume 1 million embeddings, each with 768 dimensions, stored in bfloat16 with 2 bytes per value:
- Full dimension: 1,000,000 × 768 × 2 B ≈ 1.5 GB.
- Truncated to 128 dimensions: 1,000,000 × 128 × 2 B = 0.25 GB, about one-sixth of the original size.
This matters a lot on-device. A mobile application may need to manage tens of thousands of images and thousands of audio recordings. A full-dimensional index can easily occupy hundreds of megabytes. After truncation to 128 dimensions, the same content may fit into tens of megabytes, which is friendlier to both the application package and runtime memory. Distance computation is also reduced proportionally, helping lower latency.
3. Quality tradeoffs: there is no free lunch
Shorter dimensions reduce expressive capacity, and retrieval quality will be affected. Different modalities are not affected equally:
| Retained dimensions | Relative storage | Text retrieval quality (reference) | Image/video/audio retrieval quality (reference) |
|---|---|---|---|
| 768 | 100% | 100% | 100% |
| 256 | About 1/3 | Close to full quality | Moderate decline |
| 128 | About 1/6 | About 90% | About 75% |
These values are typical ranges summarized from public practice and vary by model, dataset, and task difficulty. They should be validated on your own business data before making decisions.
The general pattern is that text has a relatively simple semantic structure, so short vectors retain a higher proportion of useful information. Images, video, and audio contain richer detail, so truncation causes more noticeable loss. Therefore, the following recommendations apply:
- Enable truncation only when storage space or search speed is a clear bottleneck.
- Text-heavy scenarios can more aggressively use around 128 dimensions.
- Image-, video-, or audio-heavy scenarios should retain higher dimensions, or use truncation only for cold data or low-precision recall layers.
- If the retrieval framework supports multi-stage search, use low-dimensional vectors for coarse filtering first, then rerank the top candidates with full-dimensional vectors. This balances storage and accuracy.
Typical Deployment Scenarios
1. Cross-modal semantic search
A single index can store embeddings for documents, screenshots, and recordings. Users can ask a natural-language question and match content across modalities. For example, the query “reimbursement process” can match a policy document passage, a screenshot of the related system interface, and a fragment of a training recording.
Two implementation points are important:
- Each content type should be chunked at an appropriate granularity: text by paragraphs or semantic blocks, images by individual images or slides, and audio/video by fixed duration or topic segment.
- Each vector should carry metadata, such as source, time, file path, and segment start and end times, to support result display and traceability.
2. Natural-language code search and agent tools
A typical local code repository indexing flow is: split code by functions, classes, or logical blocks, add context such as file paths, function signatures, and brief comments to each snippet, compute embeddings, and store them in a local vector index.
Developers can describe requirements in natural language and find candidate implementations. Agents can also use this capability as a tool to quickly locate relevant functions and call sites before modifying code. Because these models often perform well on code retrieval, they are well suited for local indexing and agent code search. Practical recommendations include:
- Keep symbol names, owning modules, and similar information in the index to make results easier to locate.
- Combine with keyword retrieval, such as exact identifier matching, to use hybrid retrieval. This balances semantic generalization with exact matching.
3. On-device RAG and classification or clustering
- On-device RAG: A personal assistant on a phone or laptop can answer questions based on local emails, notes, and documents without sending content off the device. The retrieval pipeline can first use low-dimensional truncated vectors for fast coarse filtering, then perform higher-precision reranking on a small number of candidates.
- Classification and clustering: Unified embeddings are naturally suited to scenarios without labels. After computing embeddings for notes, tickets, or images, clustering can automatically group similar content. Classification can also be implemented by computing centroid vectors from a small number of samples and assigning the nearest class, without retraining the model.
Engineering Practices and Common Pitfalls
1. Query and document prefixes must match the model convention
This is one of the most easily overlooked issues, yet it can be costly. Many instruction-enabled embedding models require different task prefixes for queries and documents. If a query-side prefix is mistakenly used when indexing documents, or a required title field is left empty, recall may drop significantly.
The root cause lies in the training distribution. The model sees different input formats for queries and documents. If the formats are mixed during inference, the vector moves away from the region where it should belong. The correct approach includes three steps:
- Read the model documentation carefully and confirm the prefix formats for queries and documents.
- Encapsulate a unified embedding interface and hard-code the prefix logic so business code does not manually concatenate strings.
- Add unit tests for prefix conventions to prevent accidental input-format changes during refactoring.
The following code is illustrative. API names and prefix contents are placeholders and should be replaced according to the documentation of the model you use:
# Example code: API names and prefix content are placeholders. Replace them with the actual model interface.import numpy as npclass UnifiedEmbedder:"""Wrapper for unified multimodal embeddings that centralizes prefix handling and normalization."""QUERY_PREFIX = "Find relevant documents for this search query: " # query side onlyDOC_TEMPLATE = "title: {title} | text: {text}" # document template; pass "none" if no titledef __init__(self, encoder, dim=128):self.encoder = encoder # created by the concrete implementationself.dim = dim # truncation dimension: 128 for tighter storage, None for higher precisiondef embed_query(self, query: str) -> np.ndarray:vec = np.asarray(self.encoder.encode(self.QUERY_PREFIX + query), dtype=np.float32)return self._finalize(vec)def embed_documents(self, docs: list[tuple[str, str]]) -> np.ndarray:texts = [self.DOC_TEMPLATE.format(title=t or "none", text=b) for t, b in docs]vecs = np.asarray(self.encoder.encode(texts), dtype=np.float32)return np.stack([self._finalize(v) for v in vecs])def _finalize(self, vec: np.ndarray) -> np.ndarray:if self.dim is not None:vec = vec[: self.dim]return vec / np.linalg.norm(vec) # re-normalize after truncation so dot product equals cosine similarity# Multimodal content is represented as (title, body/description) tuples.# A screenshot can be written as "title: screenshot | text: text description of the image content".embedder = UnifiedEmbedder(encoder=load_encoder(), dim=128)docs = [("Travel reimbursement", "Employee travel expenses must be submitted within 30 days after the trip."),("Payment callback", "def handle_payment_callback(request): ..."),]doc_matrix = embedder.embed_documents(docs)# Mixed-modality index: each item stores a vector and metadata; results are ranked uniformly.items = list(zip(doc_matrix, docs))for query in ["reimbursement deadline", "function that handles payment callbacks"]:q = embedder.embed_query(query)scores = np.array([float(np.dot(v, q)) for v, _ in items])best = int(np.argmax(scores))print(query, "->", items[best][1][0], f"score={scores[best]:.3f}")
2. Similarity computation and similarity thresholds
Once the model output is normalized, the dot product of two vectors is the cosine similarity. During storage, you can keep only the normalized vectors and compute the dot product directly during retrieval, avoiding repeated length calculations.
Be cautious with similarity thresholds. Different models, different modalities, and different truncation settings all change score distributions. Thresholds from other systems cannot be copied directly. It is better to use a batch of manually labeled query-result pairs to plot the score distribution and then determine thresholds.
3. Chunking granularity determines the retrieval ceiling
For both text and audio/video, chunking granularity directly affects retrieval quality. If chunks are too large, semantics are diluted and multiple topics are mixed together. If chunks are too small, there may not be enough context, leading to mismatches. Common strategies include:
- Split text along semantic boundaries and retain a certain amount of overlap.
- Organize images by individual image or slide.
- Split audio and video by fixed duration or topic, and record timestamps.
The original granularity should be determined through small-scale evaluation rather than intuition alone.
4. On-device inference optimization
- Quantization: Converting weights to lower-precision formats such as int8 can significantly reduce model size and memory usage. After conversion, retrieval quality must be re-tested for each modality because different modalities have different sensitivity to quantization.
- Batch encoding: When building the first index for large amounts of content, such as photo albums and recordings, use small-batch encoding to reduce the overhead of repeatedly loading the model.
- Cache query vectors: Vectors for high-frequency queries can be cached to avoid repeated encoding.
- Incremental indexing: For new content, compute embeddings only for the new portion and write them to a vector index that supports dynamic insertion and deletion, avoiding full rebuilds.
- Latency budget: Set a latency budget for each search, such as under 100 ms. If the search times out, return keyword-based results to keep the interaction smooth.
5. Evaluation should be per modality and per scenario
The biggest risk with a unified space is that overall metrics look good while a specific scenario performs poorly. Recommendations include:
- Evaluate retrieval quality separately for text, code, images, video, and audio to identify the weakest modality.
- Evaluate cross-modal retrieval separately; do not rely only on within-modality retrieval.
- Use metrics such as Recall@k, normalized discounted cumulative gain (nDCG), and mean reciprocal rank (MRR). Recall measures whether relevant results are found, nDCG focuses on ranking quality, and MRR focuses on the position of the first correct result.
- After each change, such as changing the truncation dimension, quantization, or chunking strategy, compare performance on the same evaluation set to avoid local optimization causing overall regression.
Conclusion
The value of a unified multimodal embedding space is that it combines originally fragmented text, code, image, video, and audio retrieval into one index and one query method. Compact parameter design also makes it possible to run this capability on phones and laptops for the first time.
To avoid many common pitfalls during deployment, follow these principles:
- Choose tiers by scenario: Use the lightweight tier for text-only scenarios, and enable the full-modal tier when cross-modal capabilities are needed.
- Truncate dimensions only when necessary: Apply truncation when storage and latency are tight, and validate the quality loss on business data.
- Strictly follow prefix conventions: Mismatches between query-side and document-side formats are a common cause of recall degradation.
- Evaluate per modality: Continuously monitor performance with a multi-metric, per-modality evaluation system.
Going further, adding keyword retrieval on top of vector retrieval for hybrid recall, followed by a reranking stage, can balance semantic generalization and exact matching. With continuous evaluation, on-device multimodal semantic search can be both lightweight and accurate.
