Unified Multimodal Embeddings: A Practical Guide to On-Device Deployment
A practical, model-agnostic engineering walkthrough of unified multimodal embeddings for on-device retrieval. It explains how text, code, images, video, and audio can share a single vector space, how to deploy embedding models on phones and laptops, and how to compress vector storage through truncation—alongside encoding and normalization, cross-modal search code, per-modality evaluation, and common pitfalls.
Mobile apps now handle far more than text. The data waiting to be searched on a device already includes documents in chat threads, screenshots, meeting recordings, news videos, and code repositories—all scattered across different media types. The traditional approach runs a separate model and index for each modality, and as modalities multiply, so do storage, compute, and operational costs. A class of compact, open-weight multimodal embedding models has emerged in recent years that tries to place text, code, images, video, and audio in the same vector space, optimized for consumer hardware such as mobile devices and laptops.
This article stays model-agnostic. From an engineering perspective, it breaks down how a “unified embedding space” works and how to put it into practice, focusing on three questions:
- How do multiple modalities share one coordinate system?
- How do you deploy the embedding model on device?
- How do you compress vector storage overhead?
1. Why you need a unified embedding space
Modality-separated retrieval architectures have three main problems:
- Fragmented coordinate systems. Each modality’s model outputs vectors with different dimensions, directions, and score distributions, so similarity values can’t be compared directly. Cross-modal retrieval then relies either on intermediate bridges like pre-configured text descriptions between queries and documents, or on training an additional mapping network—both of which lose information.
- System redundancy. Every new modality means a new model, index, score-fusion logic, and evaluation pipeline, and the install size and memory footprint of on-device apps grow accordingly.
- Fragmented experience. Users want to “find that screenshot or that recording with a single sentence,” but a separated architecture can only query each modality individually and stitch results together by hand, with no unified basis for cross-modal ranking.
The core idea of a unified embedding space is to let different modalities pass through their own encoders and then land in the same vector space, with the same dimension and coordinate system. In four or more dimensions, a “point” no longer corresponds to a specific direction; it just represents where the vector sits. Text descriptions, like images and audio, become a point in this space, and any two points can be compared for “semantic distance” using cosine similarity, Euclidean distance, and so on.
This collapses the architecture from “M models × N indices” to “one encoder + one vector index”: whether the query is text, a screenshot, or an audio clip, once it’s encoded into a vector in the same space, the retrieval flow is identical. For on-device scenarios, this directly means fewer models, lower memory usage, and a simpler engineering pipeline.
2. How to build a unified embedding space
How good the unified space is depends on three things: whether the modality encoders are adequate, whether alignment training is done well, and whether the dimension configuration is reasonable.
Modular encoders: load what the application needs
A common approach is “modality-specific encoder + shared projection layer”:
- Modality encoders: text, code, image, video, and audio each have a dedicated encoding method responsible for extracting semantic features from raw input.
- Shared projection layer: maps features from each modality to the same dimension—for example, 768 dimensions.
These models typically offer tiered capability configurations. Parameter counts range from a text-and-code-only version of about 270 million to a full multimodal version of about 740 million. On-device apps can trim to actual needs, for example:
- A customer service assistant that only handles chat text can load the text version.
- A local assistant that needs to understand screenshots and recordings loads the full multimodal version.
Note that the embedding model’s size is only part of the story. Index memory is often proportional to the number of vectors, and while these prototype models are designed for consumer hardware, the on-device resource budget is therefore spent mainly on the index and retrieval—and that part needs dedicated optimization.
Alignment training: making “similar meaning” land “close in position”
A unified space doesn’t form on its own; it requires alignment through contrastive learning:
- Pull positive pairs together: for example, a piece of text and its corresponding image, video, or recording are paired in training.
- Push unrelated samples apart: the model needs to learn to distinguish irrelevant content.
For same-modality retrieval like text and code, the model must also distinguish samples that are “related but not identical” so it can produce meaningful rankings rather than just judging “is this the same thing.” These models usually also adopt an instruction-based calling convention—for example, requiring the query side and the document side to use different prompt prefixes. Whatever the training convention, usage must stay consistent with it.
The encoding essentials for each modality are shown in the table below:
| Modality | Encoding considerations | Typical retrieval |
|---|---|---|
| Text | Tokenization, positional encoding, pooling | Keyword and natural-language questions |
| Code | Preserve identifiers, indentation, and structure | Natural-language source search, cross-file implementation lookup |
| Image | Block or tile encoding, then aggregation | Image-to-image, text-to-screenshot |
| Video | Key-frame or uniform frame-sampling encoding, then temporal aggregation | Finding video segments from text descriptions |
| Audio | Frame segmentation and acoustic feature extraction | Audio clip retrieval, recording content search |
Dimension configuration: the first lever between accuracy and cost
Most mainstream compact embedding models output 768-dimensional vectors. Unlike 1024 or 1536 dimensions, 768 doesn’t consume excessive bandwidth and memory, yet still carries enough expressive space for multimodal alignment. Dimension isn’t a case of “bigger is better”—lower dimensions sacrifice discriminative power, while in on-device scenarios inference latency, memory, and storage cost are highly sensitive to dimension. So 768 dimensions is a common starting point for these models, and the specific dimension and truncation strategy should be decided together with the quality evaluation in Section 4.
3. On-device deployment: keeping retrieval local
On-device (local) inference is the most direct payoff of unified multimodal embeddings. Personal data can be retrieved without uploading, which fits the recent trend of on-device intelligence becoming an industry focus. To run an embedding model on phones and thin laptops, the key problems to solve are:
- Compute precision. Half-precision floating point (bfloat16/float16) usually reduces memory usage significantly and speeds up computation; in supported environments, int8 quantization can compress size further. On-device quantization should be validated against retrieval quality on an offline evaluation set rather than assumed lossless.
- Inference backend. Mobile neural-network acceleration frameworks, vector instruction sets on desktop CPUs, and the like can all serve as inference backends. When choosing, focus on first-load time, peak memory, and sustained query latency—not just peak compute.
- Model lifecycle. On-device models involve version upgrades and compatibility. Once an upgrade changes the vector space, old indices can no longer be compared directly with new query vectors, so you must design a process for rebuilding indices.
- Device-cloud collaboration. Not every task suits the device. On-device is good for fast recall of local private data and low-latency interaction; complex reranking and multi-turn reasoning can still happen in the cloud. Divide responsibilities based on privacy requirements and task complexity.
4. Vector storage optimization: truncated representations and their tradeoffs
Once embeddings land on device, the first bottleneck is often not encoding speed but storage. Embedding models commonly support nested representation learning, which concentrates the most important information in the earlier dimensions of a vector and allows the vector to be truncated into a shorter unit vector.
Quantifying storage overhead
Storing 1 million 768-dimensional vectors in bfloat16, for example:
- The raw vectors need about 1.5 GB of memory.
- Truncated to 128 dimensions, they need only about 250 MB—storage drops to one-sixth of the original.
For offline indices shipped with an app on a phone, this is an order-of-magnitude difference. It determines how much content can be indexed locally and directly affects memory-bandwidth pressure during retrieval.
Uneven quality loss
Truncation means discarding the tail dimensions of a vector. Truncated to 128 dimensions, this class of model retains about 90% of quality on pure-text tasks but drops to about 75% on image, video, and audio retrieval.
The root cause: text tokens map relatively compactly to semantic units, with information concentrated in a few dimensions; image, video, and audio information is spread across finer local features and temporal structure, and the tail dimensions carry more discriminative information. So truncation strategy must be evaluated per modality.
Practical recommendations
- Grade by modality. Text indices can be truncated aggressively; image, video, and audio indices should keep full dimensions, or use full vectors only for the reranking stage after recall.
- Re-normalize after truncation. Truncation changes the vector’s norm. If using cosine similarity, truncate first, then do L2 normalization; if normalization happens before truncation, the remaining dimensions’ norm will be less than 1 and the scoring scale changes.
- Build a quality curve. Measure recall and precision changes at different truncation dimensions on your own data rather than reusing generic rules of thumb.
- Truncate only when necessary. If storage or search speed isn’t a bottleneck, keeping full dimensions is the safest choice.
5. Typical use cases
The value of a unified space ultimately shows up at the application layer. These tasks are especially well-suited to combining multimodal embeddings on device:
- On-device cross-modal search: type “the flowchart mentioned in last week’s meeting” into your phone’s photo gallery and hit screenshots, recording transcripts, and video frames at once, instead of just matching filenames.
- Local code repository indexing: describe a feature in natural language and jump straight to the specific function or file—useful for local development assistance and agent code retrieval. The open-weight, offline-capable nature also lets enterprises build their own code retrieval in an intranet environment.
- RAG retrieval layer: enterprise knowledge bases typically mix documents, architecture diagrams, training videos, and customer service recordings. Unified embeddings let a RAG system recall all of these from a single vector store, cutting the cost of stitching together multiple retrieval pipelines.
- Classification and clustering: after encoding emails, images, and audio clips uniformly, you can cluster them in the same space for topic discovery, content archiving, or duplicate detection.
- Agent tool calling: when an agent needs to look up information in local data, embedding retrieval can serve as a low-cost, low-latency foundational tool within a large model’s tool-calling flow.
6. Engineering practices and code examples
Below is library-agnostic sample code that focuses on the flow. In real development, you can map it to the corresponding inference and vector-retrieval implementations.
Encoding and normalization
import hashlibimport jsondef encode(text: str) -> list[float]:"""Call the embedding model to encode (illustrative interface).In real engineering:- Handle the query side with the model's agreed instruction prefix;- Use the precision the model requires (e.g., bfloat16);- Split long text into paragraphs and encode each separately."""...def encode_cached(text: str, cache: dict, model) -> list[float]:"""Cache embeddings by content hash to avoid re-encoding"""key = hashlib.sha256(text.encode("utf-8")).hexdigest()if key not in cache:cache[key] = encode(text)return cache[key]
Vector truncation and similarity
def l2_normalize(vec: list[float]) -> list[float]:norm = sum(v * v for v in vec) ** 0.5return [v / norm for v in vec] if norm > 0 else vecdef truncate(vec: list[float], dim: int = 128) -> list[float]:"""Truncate to the first dim dimensions, then re-normalize"""return l2_normalize(vec[:dim])def cosine(a: list[float], b: list[float]) -> float:"""Cosine similarity; equivalent to dot product when vectors are normalized"""return sum(x * y for x, y in zip(a, b))
Cross-modal search
def search(query: str, corpus: list[dict], top_k: int = 5, dim: int | None = None):"""Each entry in corpus has a modality type and a text representation;images can use OCR or alt text, audio can use speech-transcribed text,video can use frame-sampled descriptions."""q = encode(query)if dim is not None:q = truncate(q, dim)results = []for item in corpus:vec = encode_cached(item["text"], {}, None)if dim is not None:vec = truncate(vec, dim)results.append((item, cosine(q, vec)))results.sort(key=lambda r: r[1], reverse=True)return results[:top_k]
Two easily overlooked details in the sample code:
- Text representations are only an “encodable stand-in” for images, audio, and video. For raw non-text material like screenshots and recordings, first convert them to encodable text via OCR, speech transcription, or frame-sampled descriptions, then call the multimodal encoder. Encoding raw binary data directly does not guarantee semantically searchable results.
- Embedding retrieval depends on annotation and transcription quality, so the ceiling on retrieval effectiveness is often determined by these preprocessing steps, not just the model itself.
7. Evaluation and tuning
The gap between a unified space being “usable” and “good” is a rigorous evaluation system.
- Build per-modality evaluation sets. Each modality should cover at least three query types: intra-modal retrieval (text to text), cross-modal retrieval (text to image/video/audio), and inter-modal retrieval (image to audio). Evaluating only on text tasks masks weaknesses in image, video, and audio.
- Metrics and definitions. Recall@K measures “did we find what should be found”; Mean Reciprocal Rank (MRR) measures “are relevant results ranked high enough”; nDCG suits scenarios with graded relevance. On device, also record P95 latency, peak memory, and index build time.
- Targeted tuning. To improve non-text modalities, start from the input side:
- Increase video frame-sampling density;
- Apply speaker diarization or chapter segmentation to recordings;
- Preserve complete interface text for screenshots;
- Only when there’s no obvious weakness on the input side should you consider using full-dimension vectors.
- Online monitoring. Combine logging services and monitoring alerts to establish baselines for metrics like query latency and empty-recall ratio, and observe them continuously.
8. Common pitfalls and misconceptions
- Mixing dimensions. Vector spaces from different models or different versions aren’t compatible; queries and documents must come from the same encoder and the same version.
- Ignoring the instruction-prefix convention. Inconsistent calling between the query side and the document side noticeably degrades results.
- One-size-fits-all truncation. Applying text truncation dimensions to image, video, and audio multiplies the loss.
- Encoding raw binary directly. Image, audio, and video need proper textualization or featurization preprocessing first.
- Treating embeddings as a panacea. Exact matching, structured filtering, and strong logical reasoning still need other means; a common approach is a layered architecture of “vector recall + structured filtering + large-model reranking.”
9. Summary
The essence of unified multimodal embeddings is to remove retrieval barriers between modalities with one shared coordinate system. Decisions during implementation can be summarized in four steps:
- Trim the modality encoder to fit the application;
- Choose inference precision reasonably on device;
- Evaluate the quality-versus-storage tradeoff of truncation per modality;
- Drive iteration with a rigorous evaluation system.
For developers, the direct payoff of this approach is that one model, one index, and one retrieval logic can cover content discovery needs from text to audio and video.
