Unified Embeddings Across Five Modalities: Engineering Practices for On-Device Search and RAG
This article explores the engineering practices behind a unified embedding model that maps text, code, images, video, and audio into a single 768-dimensional vector space. It addresses the limitations of traditional multi-modal retrieval systems, details the model's modular architecture and parameter trade-offs, and provides practical guidance on leveraging fixed-dimension vectors, Matryoshka representation learning for cost reduction, on-device deployment considerations, integration within Retrieval-Augmented Generation (RAG) pipelines, and comprehensive evaluation strategies.
Moving from Single-Modality Retrieval to a Unified Semantic Space
Traditional search systems typically build separate indexes for different data types: text uses text vectors, images use visual vectors, audio uses acoustic features, and video requires processing keyframes, subtitles, or audio tracks separately. While this architecture is relatively easy to implement, it presents three significant challenges.
First, there is no direct basis for comparison across different modalities. For instance, when a user inputs a natural language description, the system struggles to directly retrieve relevant screenshots, recordings, or video clips. It often requires modality conversion before entering a separate retrieval pipeline.
Second, the system must maintain multiple sets of models, indexes, and service chains. As data scales, the complexity of vector generation, storage, updates, and version management increases rapidly.
Third, ranking results across different modalities is difficult. Text retrieval results and image or audio retrieval results come from different distance spaces, and mixing them directly can lead to unstable relevance.
The core idea behind a unified embedding model is to use different encoders for different modalities and map them into a shared vector space via a common projection layer. Ultimately, text, code, images, video, and audio can all be represented as vectors of the same dimension, compared using cosine similarity or dot product.
It’s important to note that “same dimension” does not automatically imply “fully aligned semantics.” True cross-modal capability relies on large-scale paired data, contrastive learning objectives, hard negative mining, and continuous task evaluation. A unified space is the engineering foundation, but the quality of semantic alignment is the decisive factor for system performance.
Model Architecture and Parameter Trade-offs
This type of model typically employs a modular design, where different modalities are handled by relatively independent encoders:
- Text encoder handles natural language sentences, documents, and queries.
- Code encoder handles source code, comments, function signatures, and technical documentation.
- Vision encoder handles images and screenshots.
- Video encoder handles temporal information, keyframes, and video semantics.
- Audio encoder handles speech content, environmental sounds, and recording segments.
After encoding, features from each modality are passed into a shared projection space, outputting fixed-length embedding vectors. For applications requiring only text and code search, only the corresponding encoding components need to be loaded. Support for full cross-modal retrieval requires loading more encoders, which increases parameter count, memory footprint, and computational cost.
This on-demand loading design is particularly important for mobile devices and laptops. An application doesn’t need to load the full multi-modal model for simple image search functionality, nor keep all encoders resident in memory. From an engineering perspective, deployments can be split into several modes:
- Text-Code Mode: Suitable for local codebase search, technical document retrieval, and intelligent Q&A.
- Text-Image Mode: Suitable for screen content search, album retrieval, and image-text knowledge bases.
- Full Multi-Modal Mode: Suitable for unified search across text, images, video, and audio, but requires more device computational power.
Engineering Value of a Unified 768-Dimensional Space
Fixed-dimension vector representations facilitate building a unified data pipeline. Regardless of whether the original object is a document, code file, screenshot, or recording, it can be processed through a similar workflow:
- Clean and chunk the data.
- Generate vectors using the corresponding encoder.
- Record metadata such as object type, source, timestamp, and permissions.
- Write the vector into the vector index.
- Encode the user query during search and perform similarity retrieval.
- Re-rank results based on modality type, permissions, and business rules.
In cross-modal search, the query and target object need not be of the same data type. For example, a user typing “find screenshots showing login failure prompts” allows the system to directly compare the text query with screenshot vectors. Similarly, a query for “retrieve recordings about database connection pool configuration” can find semantically relevant segments in the audio index.
However, a unified vector space doesn’t mean metadata can be ignored. Real-world systems still need to retain fields like object type, tenant identifier, permission tags, time range, and data version. Vector similarity only answers whether items are semantically close; it doesn’t determine user access rights or whether results meet recency requirements.
Therefore, a recommended retrieval flow is:
User Query↓Query Encoding↓Vector Recall↓Permission & Metadata Filtering↓Cross-Modal Result Fusion↓Re-ranking & Result Explanation
Matryoshka Representation Learning: Leveraging Shorter Vectors for Cost Efficiency
This model supports a nested representation learning method. During training, the prefix portions of the full vector are also imbued with relatively stable semantic expressive power. This allows for truncation to the first 128, 256, or other shorter dimensions for retrieval without retraining the model.
Taking 1 million vectors as an example, if using 768 dimensions with 2 bytes per dimension, the raw vector storage is approximately:
1,000,000 × 768 × 2 ≈ 1.5 GB
If truncated to 128 dimensions, the storage requirement becomes approximately:
1,000,000 × 128 × 2 ≈ 256 MB
This not only reduces disk and memory overhead but also lowers the computational cost of vector distance calculations. This optimization is highly valuable for edge devices, embedded systems, and large-scale local indexes.
However, dimensionality reduction inevitably leads to quality loss. Based on the original material, the 128-dimension representation retains a high proportion of effectiveness for text tasks, while performance degradation is more noticeable for image, video, and speech tasks. This is because multi-modal semantics often involve more complex local and temporal information that is difficult to fully capture in shorter vectors.
Therefore, dimension selection should not be based solely on storage savings, but should also consider:
- Query volume;
- Acceptable recall rate;
- Device memory;
- Retrieval latency;
- Modality complexity;
- Whether a two-stage re-ranking process exists.
A more robust approach involves “two-stage retrieval”: the first stage uses 128-dimensional or 256-dimensional vectors for fast candidate recall; the second stage uses the full 768-dimensional vector or a more expensive re-ranking model to recalculate relevance. This balances speed, storage, and quality.
Key Considerations for On-Device Deployment
Deploying models locally on devices offers advantages like low latency, better privacy, and independence from continuous network connections. However, edge environments face constraints including limited computational power, memory pressure, and battery sensitivity.
First, control the scope of model loading. When only performing text search, video and audio encoders should not be loaded. Second, encoding can be batched, but batch sizes shouldn’t be increased blindly to avoid memory spikes. Third, implement caching mechanisms for documents or media objects that have already been vectorized to prevent redundant computation.
For local codebase search, content should be chunked hierarchically based on files, classes, functions, and comments. Overly large code blocks reduce retrieval precision, while overly small chunks lose context. It’s recommended to preserve parent paths, language types, symbol names, and version information to provide full context in search results.
For screenshots, video, and audio, it’s better to generate searchable segment-level objects rather than a single vector for the entire file. Videos can be segmented based on time windows or scenes; audio can be split according to speaker changes, pauses, or topics. This allows retrieval results to pinpoint specific moments or sections, rather than returning a single large file.
Usage in RAG Systems
In Retrieval-Augmented Generation systems, the multi-modal embedding model primarily handles the “recall” responsibility, rather than directly generating answers. A complete workflow typically includes:
- Preprocess enterprise documents, code, images, audio, and video.
- Generate unified vectors for different objects.
- Index vectors alongside permissions, sources, and time information.
- Encode the user question into a query vector.
- Recall candidate content from multiple modality indexes.
- Filter based on relevance, permissions, and recency.
- Provide structured context to the generation model.
- Annotate sources and content types in the final answer.
Permission isolation is critical for enterprise scenarios. Different users may have access to different knowledge bases, project directories, or meeting recordings. While filtering permissions after vector recall is simple to implement, it can lead to wasted retrieval effort and potential data leakage risks. A more robust approach is to design tenant isolation during the indexing phase and use permission conditions as joint filters during the query phase.
Furthermore, cross-modal results need to be explainable. The system should clearly indicate whether a result comes from a document, screenshot, code, video, or audio and, where possible, show file paths, timestamps, or excerpts. Only with source information can users judge the credibility of the results.
How to Evaluate Practical Effectiveness
Evaluation should not rely solely on a single similarity metric. At minimum, the following tasks should be tested separately:
- Text-to-text retrieval;
- Text-to-code retrieval;
- Text-to-image retrieval;
- Text-to-video retrieval;
- Text-to-audio retrieval;
- Ranking of fused cross-modal results;
- On-device inference latency;
- Memory and storage footprint.
For text and code tasks, focus on recall rate (Recall@K), Mean Reciprocal Rank (MRR), and hit rate within the top N results. For video and audio tasks, also assess temporal localization error—that is, whether the returned segment truly contains the content described by the user.
In practice, full 768-dimension vectors are generally better suited for quality-critical scenarios; shorter vectors are suitable for scenarios with large data volumes, limited device resources, or extremely low latency requirements. Don’t assume that shorter, faster vectors automatically mean better overall system performance. Ultimately, use real business query sets for offline evaluation, combined with continuous tuning based on user clicks, corrections, and re-search behavior.
Conclusion
Mapping five modalities into a unified vector space addresses the foundational problem of uniformly searching multi-media data. It reduces fragmentation between multiple indexes, allowing text, code, images, video, and audio to share a single semantic retrieval framework. Modular encoders and edge optimization make this capability better suited for local search, codebase indexing, and privacy-sensitive scenarios.
However, unified embeddings are not a silver bullet. Cross-modal alignment quality, long-content chunking, permission control, result explanation, and dimensionality reduction losses can all directly impact the final user experience. A robust engineering path is to first define business modalities and query types, then load encoders on demand; establish a quality baseline using full vectors; and progressively optimize cost using shorter vectors, caching, and two-stage re-ranking. For enterprise-level applications, vector retrieval must also be integrated with permission systems, metadata management, monitoring, alerting, and data update mechanisms to build a stable, maintainable multi-modal search and RAG system.
