Build a Cross-Modal Embedding Store for Text, Image, and Video
databases data-engineering scalability
AI System Design Deep Dive
Cross-Modal Embedding Store
One shared space, three modalities, and a 68 degree gap that makes the index right and the ranking wrong.
Put every employee’s badge photo and every employee’s written job description into the same filing cabinet, sorted by height. Technically the cabinet is one system, technically every record has one coordinate, and technically the sort is correct. In practice the photos end up at one end and the descriptions at the other, because photographs and paragraphs differ from each other far more than two photographs differ from each other, and no amount of careful sorting repairs that. The cabinet is working. The axis you chose is the problem.
That is what happens when you put text, image, and video embeddings into one vector index. We have 400 million text chunks, 1.2 billion images, and 1.8 million videos cut into 432 million shot-level segments, 2.032 billion vectors total, all produced by the three towers of a single SigLIP-2 model and all projected into the same 1024-dimensional unit-normalised space. The model was trained contrastively so that a caption and its image land near each other. It works: the correct image for a caption is on average 0.31 cosine away from a random one. And yet when we send a text query into a single joint HNSW index over all 2.032 billion vectors, the top 100 comes back 98.6 percent text, even though text is only 19.7 percent of the corpus.
The reason is geometric and it is well documented. Mean cosine similarity between two vectors of the same modality is 0.68 with a standard deviation of 0.09. Mean cosine between two vectors of different modalities is 0.23 with a standard deviation of 0.07. Those two distributions overlap on 1.4 percent of their mass. The towers of a contrastive model do not learn to occupy one blob; they learn two narrow cones separated by roughly 68 degrees, and the contrastive objective only ever needed relative ordering within a batch, never an absolute scale shared across modalities. So the nearest-neighbour search is answering a question nobody asked: not “what is most relevant” but “what is most text-like”.
Every downstream problem in this system follows from that gap, plus one more fact: the three modalities are not symmetric in anything. A video is 0.11 percent of the asset count and 63 percent of the encoder GPU bill. A video produces 240 vectors that must collapse into one result slot while an image produces exactly one. Text tolerates aggressive quantisation far worse than images do. We need to solve for a shared space that is actually comparable across modalities, asset-level ranking from segment-level vectors, and an ingest plane where one asset type costs 42,000 times more than another, simultaneously, at 2,500 queries per second.
Requirements and Constraints
Functional Requirements
- Accept a query that is text, an image, or both, plus structured filters (
acl_mask,created_after,duration_msrange) and a requested modality set - Retrieve from a text lane, an image lane, and a video segment lane over one shared 1024-dimensional space
- Return a single ranked page that mixes modalities, with at most one slot per asset
- For a video hit, return the matching segment offset so the player can seek to it, not just the video id
- Fuse the lane results with weights that depend on the detected query intent, not a global constant
- Rescore the head exactly against uncompressed vectors before the page is cut
- Enforce
acl_maskinside the index scan, never as a post-filter - Expose per-lane diagnostics (
lane_depths,distinct_assets,starved_lanes,epoch_id) on every response - Support a full re-embedding of all three modalities under a new epoch without downtime
Non-Functional Requirements
- Latency: 112ms p99 and 34ms p50 end to end, with a 20ms hard deadline on the retrieval fan-out and 3.4ms p50 for fusion
- Throughput: 2,500 QPS peak, 900 QPS average, 77.8M queries per day
- Quality: cross-modal
nDCG@10above 0.61 on a 24,000-query golden set,recall@100above 0.93 per modality pair, and no modality pair regressing more than 1.5 points between epochs - Cost: under $9 per million queries all-in, and a full 2.032B-vector backfill under $12,000 of GPU
- Capacity: 572 GB resident across all three lanes with 40 percent headroom, 4.16 TB of
fp16originals on object storage - Freshness: a new image is queryable within 90 seconds, a new video within 20 minutes, a text chunk within 15 seconds
- Determinism: identical query, identical filters, identical
epoch_idreturns byte-identical ordering
Constraints
- Encoders are the
siglip2-so400m-patch14-384image tower and its paired text tower, with a linear projection to 1024 dimensions andL2normalisation. Both towers are pinned together for the life of an epoch. - Video has no native video tower. It is encoded frame-wise by the image tower and pooled temporally, which is the cheap option and has consequences we will quantify.
- Shot boundaries come from
TransNetV2on frames sampled at 2 fps. - Index is
HNSWwithM = 16,maxM0 = 32,efConstruction = 200,efSearch = 192, with per-lane product quantisation. - Out of scope: audio as a fourth modality, learned cross-modal rerankers, and multilingual text. All three are real and all three change the design rather than extend it.
High-Level Architecture
Six components, and the one that matters is 34 lines long.
The Asset Intake service consumes S3 object-created events at up to 42,000 assets per second during backfill and writes one assets row plus N asset_segments rows per asset. Text chunks and images get exactly one segment. Videos go to the Shot Segmenter, which decodes at 2 fps, runs TransNetV2 over the frame sequence, and emits a mean of 240 shots for a 9.6-minute video. The Encoder Pool runs the two SigLIP-2 towers on A10G GPUs and is where essentially the entire ingest budget lives.
Everything then passes through the Modality Calibrator, which is the 34-line component. It subtracts the modality centroid mu_m from each vector and renormalises to unit length. That single arithmetic step is what makes the rest of the system possible, and it is also where most implementations of this architecture quietly go wrong by skipping it. The Embedding Writer upserts into one of three lane indexes keyed by (asset_id, segment_no, epoch_id).
On the query side, the Query Encoder embeds the incoming text or image and applies the same centring, then the three lanes are searched concurrently under a shared 20ms deadline at per-lane depths of 300, 500, and 1,400. The Cross-Modal Fusion layer merges the three rank lists with weighted reciprocal rank fusion. The Asset Aggregator collapses up to 1,400 video segment hits into at most one slot per video. Finally the head of 400 is rescored exactly against fp16 originals, because the quantisation error we accepted to fit 2 billion vectors in RAM is large enough to reorder the top 10.
The critical path is 2.8ms of query encoding, 14.8ms in the image lane, 3.4ms of fusion, 1.9ms of rollup, 2.1ms of rescore, and 4.2ms of hydration, which is 29.2ms, and p50 lands at 34ms. The image lane’s 14.8ms swallows the text lane’s 6.1ms and the video lane’s 8.2ms entirely. The p99 of 112ms is not caused by any of these; it is caused by the 11 percent of rescore fetches that miss the hot fp16 cache and go to object storage, which costs 38ms when it happens.
A shared embedding space is not a shared ranking space. The model guarantees that a caption is closer to its own image than to a random image; it guarantees nothing about whether that distance is comparable to the distance between two captions. Treating one index over one space as one ranking problem is the mistake the whole architecture exists to avoid.
The Modality Calibrator
Its job is to make a cosine similarity computed across two modalities mean roughly the same thing as one computed within a modality.
The non-obvious part is how little work this takes. A smart engineer looks at a 68 degree cone separation and reaches for a learned adapter: a small MLP trained to project both modalities into a genuinely isotropic space, or a fine-tune of the towers with a gap-closing regulariser. Both work. Neither is necessary, because the gap is very nearly a constant offset. Compute the mean vector of 4 million sampled text embeddings and the mean of 4 million image embeddings, and the difference between those two centroids accounts for 0.45 of the 0.45 cosine shortfall between intra-modal and cross-modal similarity, to within measurement noise. The cones are not twisted relative to each other. They are translated.
So the fix is to subtract the per-modality mean and renormalise.
# Modality centring: the whole cross-modal calibration, computed at ingest time.
import numpy as np
class ModalityCalibrator:
"""Removes the per-modality offset that creates the modality gap.
mu is fitted once per epoch over a uniform sample of each modality and
frozen. It must be identical on the ingest path and the query path or
every distance in the system is computed in a different space.
"""
def __init__(self, mu: dict[str, np.ndarray], epoch_id: int):
for modality, vec in mu.items():
if vec.shape != (1024,):
raise ValueError(f"mu[{modality}] has shape {vec.shape}, want (1024,)")
self.mu = {m: v.astype(np.float32) for m, v in mu.items()}
self.epoch_id = epoch_id
def apply(self, vecs: np.ndarray, modality: str) -> np.ndarray:
if modality not in self.mu:
raise KeyError(f"no centroid for modality {modality} in epoch {self.epoch_id}")
centred = vecs.astype(np.float32) - self.mu[modality]
norms = np.linalg.norm(centred, axis=1, keepdims=True)
# A vector that sits exactly on the centroid has no direction left.
# It is a degenerate asset (a blank image, an empty chunk); drop it
# rather than emitting a NaN row into the index.
keep = norms[:, 0] > 1e-6
centred[keep] /= norms[keep]
return centred, keep
@staticmethod
def fit(vecs_by_modality: dict[str, np.ndarray], epoch_id: int) -> "ModalityCalibrator":
mu = {m: v.mean(axis=0) for m, v in vecs_by_modality.items()}
return ModalityCalibrator(mu, epoch_id)
Think of it as removing the “this is a photograph” signal from a photograph’s embedding. That signal is real, it is strong, and it is the loudest thing in the vector, so nearest-neighbour search finds it first. It is also useless for ranking, because the caller already told us which modalities they want. We strip it out and let the remaining 1023 effective dimensions carry semantics.
Measured on our golden set, centring moves the mean gap between intra-modal and cross-modal cosine from 0.45 to 0.07, and it does so without touching intra-modal recall: image-to-image recall@100 is 0.947 before and 0.946 after. Cross-modal nDCG@10 on a joint index goes from 0.221 to 0.544. That is 78 percent of the total gain the full lane architecture eventually delivers, bought with two lines of arithmetic.
What would break if we simplified further and skipped the renormalisation after subtracting mu? The vectors would no longer be unit length, so cosine similarity and inner product would stop agreeing, and HNSW built on inner product would start preferring long vectors. Vector length after centring correlates with how atypical the asset is for its modality, so the index would systematically rank weird assets first. We measured that: skipping renormalisation puts images whose centred norm is in the top decile into 29 percent of top-10 slots, against an expected 10 percent.
Premium Content
Unlock the full article along with everything else in the archive — all in one place.