Unified Embedding Spaces for Multimodal Retrieval: Technical Practices and Optimization

    This article explains how a unified embedding space can simplify multimodal retrieval by mapping text, code, images, video, and audio into one vector space. It covers design principles, deployment trade-offs, on-demand encoder loading, Matryoshka representation learning for storage savings, typical retrieval pipelines, and a practical workflow for implementation and evaluation.

    Multimodal retrieval systems have long faced a structural problem. Text, code, images, video, and audio are often encoded by different models into vector spaces with different dimensions and distributions. As a result, cross-media retrieval requires multiple indexes, multiple similarity logics, and multiple fusion strategies. A unified embedding space offers a simpler engineering path. It maps multiple modalities into the same dimensional space, so semantic similarity can be compared in one coordinate system. This reduces the complexity of cross-modal retrieval systems. This article discusses the design principles, deployment trade-offs, and implementation practices of this approach from a general technical perspective.

    1. Why a Unified Embedding Space Is Needed

    Traditional multimodal retrieval usually builds indexes per modality and routes queries at search time. For example, a text query goes through a text encoder, image retrieval goes through an image encoder, and cross-modal queries depend on extra mapping layers or fusion models. This approach works when only a few modalities are involved. However, when a system must cover documents, screenshots, audio recordings, video, and source code at the same time, three problems appear:

    1. Index fragmentation: Each modality needs its own index, so storage and operational costs grow with the number of modalities.
    2. Incomparable similarity scores: Vector distances in different spaces lack a shared meaning, so cross-modal ranking needs extra calibration.
    3. Complex pipelines: Query understanding, modality routing, result fusion, and reranking are tightly coupled, which makes troubleshooting difficult.

    The core value of a unified embedding space is that embeddings from different modalities share the same dimensional space and can be compared directly by semantic similarity. Developers can build cross-media retrieval systems without maintaining separate, incompatible embedding spaces for each media type. For applications such as retrieval-augmented generation (RAG), on-device search, classification, and clustering, this consistency can significantly simplify service orchestration.

    However, a unified space does not mean that one model solves every problem. Data distributions differ greatly across modalities. The semantic granularity of images, audio, and video differs from that of text, and code has strict syntax and symbolic structure. Therefore, designing a unified space requires systematic consideration of shared dimensions, modality markers, normalization methods, negative sampling, and evaluation.

    2. Architectural Benefits and Challenges of a Unified Dimension

    In compact multimodal embedding models, a typical design represents text, code, images, video, and audio as vectors of a fixed dimension, for example 768. A unified dimension brings three direct benefits:

    • One index: A single vector index can hold embeddings from multiple modalities, which reduces the number of indexes and the complexity of metadata management.
    • One similarity calculation: Cross-modal and single-modal retrieval share the same distance metric, which makes unified ranking and threshold strategies easier.
    • One service interface: Upper-layer applications only submit content and a modality type, and the backend returns vectors in a uniform format. This lowers integration costs.

    The challenges are equally clear. First, the effective information density differs across modalities. Audio and video also involve a time dimension, so simple pooling may lose key segments. Second, building cross-modal training samples is difficult. If negative samples are poorly selected, the model may learn modality shortcuts rather than true semantics. Third, retrieval quality within a modality and across modalities must be evaluated separately. Average metrics alone are not enough.

    In engineering practice, it is recommended to include an explicit modality marker in each request. When content is indexed, record metadata such as modality, timestamp, source, version, and dimension. Normalize vectors before similarity calculation to avoid scale inconsistencies between encoders. For video and audio, generate embeddings at the segment level. Then, depending on business needs, aggregate them or keep multiple segment vectors instead of storing only one global vector.

    3. Compact Models and On-Demand Encoder Loading

    When targeting consumer hardware such as mobile devices and laptops, model size, startup speed, and memory usage matter more than peak accuracy. A common approach is to offer tiered capabilities. Text and code use smaller encoders, while full multimodal capability uses a larger encoder. Based on typical scales in public references, text and code encoders may have parameter counts in the hundreds of millions, and the full multimodal capability can reach around 700 million parameters. This tiered design lets applications load only the encoders they need, rather than keeping all modality capabilities resident.

    On-demand loading provides engineering value in three ways:

    1. Lower memory usage: Only the encoders required by the current business are enabled, which reduces resident memory.
    2. Shorter cold-start time: Device-side applications can lazy-load features by module, so the first launch does not wait for every model to initialize.
    3. Easier degradation: When resources are tight, video or audio encoding can be turned off, leaving only text and image retrieval.

    In practice, a capability declaration and routing layer should be designed. When the service starts, it registers the available modalities, dimensions, whether truncation is supported, and the maximum batch size. When a request arrives, the router selects an encoder based on the modality and resource budget. For low-latency scenarios, batching and warm-up strategies matter. Small requests can be merged for encoding, but a maximum wait time must be set. On mobile, frequent loading and unloading should be avoided, and models can be cached based on usage frequency.

    4. Matryoshka Representation Learning and Storage Trade-offs

    Matryoshka representation learning allows embeddings to be truncated into shorter vectors, which reduces storage requirements. For example, storing one million 768-dimensional vectors in bfloat16 precision requires about 1.5 GB of memory. Truncating them to 128 dimensions reduces this to about 250 MB, which is one-sixth of the original storage. For large-scale indexes, this saving is substantial.

    However, truncation is not free. Lower dimensions reduce representational capacity, and the loss differs across modalities. A typical reference from public sources suggests that at 128 dimensions, text tasks can retain about 90% of their quality, while image, video, and speech retrieval may drop to about 75%. Therefore, truncation should be treated as an explicit trade-off between capacity and quality, not enabled by default.

    A tiered strategy is recommended:

    • High dimensions for hot data, low dimensions for cold data: Keep higher dimensions for frequently accessed content and use lower-dimensional vectors for historical archives.
    • Recall first, then rerank: Use low-dimensional vectors for large-scale coarse recall, then rerank the candidate set with high-dimensional vectors or more detailed features.
    • Set thresholds by modality: Text can be truncated more aggressively, while image, video, and audio should be truncated more conservatively.
    • Truncate only when storage or search speed requires it: If quality is the priority, keep the original dimension.

    Note that truncation depends on how the model was trained. If a model was not trained for Matryoshka representation learning, directly truncating its vectors may cause a noticeable drop in quality. Before deployment, use a business evaluation set to test recall, ranking quality, and cross-modal stability at each dimension.

    5. Typical Application Scenarios and Retrieval Pipelines

    A unified embedding space suits many retrieval tasks. These include finding related documents, screenshots, and audio recordings from a query, searching source code with natural language, retrieving video content from text descriptions, and supporting on-device search, RAG, classification, and clustering. Each scenario has a different pipeline focus:

    • Document and screenshot retrieval: Encode the query and compare it against the unified index. Filter results by modality and source. Screenshots can combine OCR text with visual embeddings, but duplicate indexing must be avoided.
    • Audio recording retrieval: Split audio into time segments, index segment-level embeddings, and return segments with timestamps so users can locate the relevant part.
    • Code retrieval: Code has symbolic structure, so metadata such as file path, function name, and programming language should be preserved. Natural language queries and code embeddings are compared in the same space, which suits local codebase indexing and code search for AI agents.
    • Video retrieval: Encode keyframes and audio tracks separately, then aggregate them over time. At query time, coarse-recall video segments first and then rerank them by temporal order.

    Code retrieval especially requires dedicated testing. A unified space simplifies cross-modal comparison, but there is still a gap between code semantics and natural language. Index granularity, comment quality, and language distribution all affect results. It is recommended to build an evaluation set that covers natural language to code, code to code, and cross-language code retrieval.

    6. Implementation Workflow and Pseudocode

    Implementation can follow five steps: data governance, embedding generation, index construction, query serving, and evaluation and monitoring. Data governance unifies modality markers and metadata. Embedding generation loads encoders on demand and applies normalization. Index construction determines dimensions, sharding, and hot-cold tiering. Query serving handles routing, filtering, and reranking. Evaluation and monitoring cover both single-modal and cross-modal metrics.

    The following pseudocode only illustrates unified embedding and truncation logic. It does not depend on any specific interface:

    1. def embed(inputs, modality, target_dim=None):
    2. assert modality in {"text", "code", "image", "video", "audio"}
    3. vector = encoder_for(modality).encode(inputs)
    4. vector = normalize(vector)
    5. if target_dim is not None:
    6. vector = vector[:target_dim]
    7. vector = normalize(vector)
    8. return vector
    9. def search(query, modality, top_k, dim):
    10. q = embed(query, modality, dim)
    11. candidates = index.search(q, top_k * 4, filter={"dim": dim})
    12. return rerank(candidates, query, top_k)

    There are other engineering points to consider. The index version must be bound to the model version. After a model upgrade, rebuild the index or write to both old and new indexes during the transition. Logs should record modality, dimension, latency, and truncation strategy, which helps locate quality fluctuations. Monitor recall, empty-result rate, cross-modal click-through rate, and latency percentiles. When building a general-purpose retrieval service on Baidu AI Cloud, embedding computation, object storage, container platforms, log services, and monitoring and alerting can be combined into an end-to-end pipeline. The specific architecture should still be designed around business evaluation results.

    7. Limitations and Conclusion

    A unified embedding space is an important direction for simplifying retrieval architecture, but it is not a universal solution. Its main value is reducing the system complexity of cross-modal retrieval. The gains for pure text tasks should be carefully evaluated against business data. Views common in community discussions are also worth noting. Unified multimodal representations are impressive, but using the model correctly is equally important. This includes modality markers, normalization, truncation strategy, and evaluation methods.

    Overall, compact multimodal embedding models provide adjustable deployment flexibility for on-device and cloud retrieval through unified dimensions, on-demand encoder loading, and Matryoshka representation learning. Developers should let evaluation sets guide decisions and make explicit trade-offs among storage, latency, and quality. When cross-media retrieval is required, prioritize consistency within the unified space. When resources are limited, use low-dimensional coarse recall with high-dimensional reranking. For images, video, and audio, keep truncation strategies more conservative. Only then can a unified vector space become a maintainable and scalable retrieval capability.