On-Device Multimodal Retrieval with a Unified Embedding Space
Learn how to build on-device retrieval across text, code, images, audio, and video using a shared embedding space. This article covers encoder loading, metadata-aware indexing, dimensionality truncation, query and document instructions, hybrid retrieval, and modality-specific evaluation, with practical trade-offs for memory, latency, privacy, and retrieval quality.
On-Device Multimodal Retrieval with a Unified Embedding Space
1. Why Multimodal Retrieval Needs a Shared Space
Search systems increasingly need to retrieve more than text. A knowledge base may contain documents, source code, product screenshots, meeting recordings, and training videos. An AI agent may need to use a natural-language query to find a local code snippet, a screenshot from a support ticket, or a relevant passage in a recording.
A conventional approach maintains separate indexes for each media type: text embeddings for documents, visual embeddings for images, and audio embeddings for recordings. Results are then combined through multiple retrieval paths and ranking fusion. This works, but it adds engineering overhead: multiple indexes, models, and thresholds, difficult cross-modal comparisons, and growing storage and update costs.
A unified embedding space addresses this fragmentation. Modality-specific encoders project their inputs into a semantic space with the same dimensionality and distance metric. A text query can then be compared directly with images, video frames, audio segments, or code snippets. The retrieval system no longer needs to manage incompatible embedding spaces for every media type.
This shared representation can simplify on-device search, retrieval-augmented generation (RAG), classification, and clustering.
However, a shared space does not imply equal quality across modalities. Signal-to-noise ratios, encoder capacity, and training data distributions vary substantially. Image and audio retrieval often degrade more than text retrieval when embeddings are truncated to fewer dimensions. A unified space makes representations comparable and jointly indexable, but production systems still need modality labels, metadata filters, modality-aware thresholds, and reranking.
2. Architecture: Load Encoders on Demand
A multimodal embedding model does not need to run every encoder on every device. A more practical approach is selective loading: load a smaller text/code encoder when processing only text and code, and add vision or audio encoders when those capabilities are needed.
This helps control memory use, cold-start time, and power consumption on mobile devices, laptops, and edge nodes.
Key deployment considerations include:
- Memory budgets and model caching: Encoders may contain hundreds of millions to nearly a billion parameters. Avoid keeping all encoders resident at once. Preload them for expected workloads, unload idle models, and enforce cache capacity limits.
- Quantization and precision: Embeddings can be stored at half precision or lower, but normalization and distance calculations must remain consistent. Reevaluate retrieval quality after quantization rather than judging success only by the reduction in model size.
- Batching and asynchronous pipelines: Screenshots, recordings, and extracted video frames often arrive in bursts. Run indexing asynchronously to avoid blocking foreground interactions, while prioritizing low latency for queries.
- Privacy and permissions: Local indexes can reduce the need to transmit sensitive data. However, permission checks and any required redaction must still be applied before retrieval so that vector search cannot bypass access controls.
In a hybrid edge–cloud architecture, the device can handle initial candidate ranking and local incremental indexing, while the cloud maintains the full index and performs more detailed reranking.
For a deployment on Baidu AI Cloud, the architecture can use object storage for source media, vector retrieval services for the embedding index, and logging and monitoring to track retrieval quality, latency, and failure rates. Treat these as infrastructure components rather than tightly coupling them to business logic.
3. Index Design: Unified Vectors, Structured Metadata
A shared embedding space does not eliminate the need for metadata. Metadata is essential to making a unified index manageable.
Each vector should retain at least:
- Modality
- Source identifier
- Timestamp
- Permission labels
- Business category
- Location of the original chunk
At query time, metadata filtering can narrow the candidate set before vector similarity is evaluated, helping reduce irrelevant matches.
Chunking should also reflect the structure of each media type:
- Documents: Split by heading hierarchy and paragraph boundaries. Preserve titles, body text, and section paths, and avoid combining unrelated passages into one embedding.
- Code: Split by file, class, function, or symbol boundaries. Retain paths, dependencies, and programming language information. Code search relies heavily on structure, so fixed-length character splitting is often insufficient.
- Screenshots: Combine OCR text with visual features where appropriate, and retain interface regions, timestamps, and source information.
- Audio: Transcribe before embedding, while retaining timestamps and speaker labels. Segment long recordings and aggregate results as needed.
- Video: Align sampled frames, audio transcripts, and timestamps. Retrieve individual segments first, then aggregate them into video-level results.
A practical retrieval layer combines keyword retrieval, vector retrieval, metadata filtering, and reranking. Keyword search is more reliable for proper nouns, error codes, and function names. Vector search is more robust to semantic paraphrasing. A reranker can use modality and business features to compensate for biases in the shared space.
4. Matryoshka Representation Learning: Trading Dimensions for Storage
Matryoshka representation learning allows embeddings to be truncated to fewer dimensions, reducing storage and computation costs.
For example, one million 768-dimensional vectors stored in bfloat16 require roughly 1.5 GB of raw vector storage. Truncating them to 128 dimensions reduces that to approximately 250 MB, or about one-sixth of the original size. This is attractive for on-device indexes and large collections of infrequently accessed data.
Truncation is not lossless, however. Text tasks can often retain a relatively high proportion of their quality at lower dimensionality, while image, video, and audio retrieval may degrade more noticeably. Illustrative retention figures might be around 90% for text tasks and 75% for cross-modal tasks; these should not be treated as guarantees for a particular model or workload.
Recommended practices are:
- Enable truncation only when storage or search speed is a genuine constraint.
- Use tiered indexes: retain higher-dimensional vectors for frequently accessed data and lower-dimensional vectors for cold data.
- Run A/B evaluations at different dimensions, measuring retrieval changes separately for text, code, images, audio, and video.
- Renormalize vectors after truncation and keep query and indexed vectors at the same dimensionality.
5. Task Prefixes and Instruction Consistency
Multimodal embedding models often distinguish queries from documents through task instructions or prefixes.
A common implementation error is to use a query instruction when indexing documents. This can create a mismatch between document and query embedding distributions, substantially reducing recall. Although the mistake appears minor, it can be a major reason production performance falls short of expectations.
The following pseudocode illustrates the distinction:
def build_document_vector(title, body):payload = compose(title=title, body=body, kind="document")return embed(payload, instruction="document")def build_query_vector(query):return embed(query, instruction="query")# Incorrect: call build_query_vector during document indexing.# Correct: use the appropriate instruction for indexing and querying,# and record instruction versions.
Instruction templates should be versioned, with changes coordinated across index rebuilds. Offline evaluations should explicitly include cases where query and document prefixes are mixed up.
On the document side, preserve the distinction between title and body. Use a consistent placeholder for an empty title, and avoid concatenating unrelated fields.
6. Evaluation and Monitoring: Measure Each Modality Separately
A unified embedding space can make a single overall recall score seem sufficient. A safer approach evaluates each modality and task separately:
- Text retrieval: Recall@k, mean reciprocal rank (MRR), and normalized discounted cumulative gain (NDCG)
- Code search: Function-level and file-level hits
- Image and video retrieval: Segment-level recall
- Audio retrieval: Timestamp localization
Operational monitoring should also cover P95 latency, index size, cold-start time, failure rates, and permission-filter matches.
In production, clicks, result adoption, and manual spot checks can provide a feedback loop for refining chunking, thresholds, and reranking strategies.
7. Implementation Checklist
- Confirm that the application actually needs cross-modal retrieval; do not unify representations solely for architectural consistency.
- Load encoders according to the workload and control resident memory on the device.
- Standardize vector dimensionality while retaining modality, permission, timestamp, and other metadata.
- Use the appropriate task instructions for queries and documents; do not interchange them.
- Evaluate dimensionality truncation separately for each modality through A/B testing.
- Combine keyword search, vector search, filtering, and reranking.
- Maintain modality-specific evaluation sets and production monitoring to track quality, latency, and storage costs.
Unified multimodal embeddings are not a single-model solution to every retrieval problem. They provide a shared representation layer within an architecture shaped by engineering trade-offs.
Careful encoder loading, index design, truncation policies, instruction consistency, and continuous evaluation are what turn that representation into a low-latency, maintainable, and scalable foundation for on-device RAG and cross-media search.
