# Embedding is not about turning words into numbers; it's about drawing a map of meaning

Date: 2026-11-15
Category: Technology
Tags: Embedding, Multimodal, Vector Retrieval
Summary: A review of \"The Necklace\" mixed into the related articles recommendations—it's not that the model is incapable, but that it hasn't thought clearly about what Embedding is doing. From words, sentences, and documents to images and videos, this breaks down the trade-offs of vectorization in each case and the pitfalls that are easy to stumble into.

When adding "related articles" to the blog, the first version was very plain: throw each article's body into a model, take a vector, compute cosine, and pick the top few. After launch, I clicked around a bit and immediately saw something was off. One article about the Agent closed loop had a book review of "The Necklace" sitting in its related recommendations, presumably because the word "system" appeared on both sides.

My first reaction was that the model was no good, so I switched to one with more parameters, and the result was just more expensive mistakes. There were really three problems: the entire article was averaged into a single vector, diluting the topics in long texts; normalization was forgotten at indexing time, so cosine and inner product were mixed; and I was using my intuition about "sentence similarity" to demand "article similarity."

After fixing these three things, the top five finally looked reasonable. This made me realize that most confusion about Embeddings isn't about the formulas, but about not thinking clearly about what it actually does. It's more like a map: placing discrete things into a continuous space so that "distance" can be computed. Maps are useful, but they also distort, and different models draw different projections—coordinates can't be mixed.

## Three conventions of a map

First, clarify what it does. Words, images, and video frames are originally symbols or pixels, and distances can't be computed directly; after vectorization, each object becomes a string of floating-point numbers, and only then do addition, subtraction, multiplication, and division make sense. Discrete input, continuous output—this is the most basic layer.

More critically, this distance must approximate semantic similarity. Two objects are close in space not because they look alike literally, but because the model repeatedly saw them appear in similar contexts during training. There's a limitation here that's often overlooked: it only holds for semantics covered by the training distribution. Domains the model hasn't seen, internal code names, and newly coined words may end up with coordinates close to random.

Another point: dimensions are distributed representations, not nameable features. 1536 dimensions doesn't mean dimension 7 represents "emotion" and dimension 42 represents "animal"; individual dimensions are basically uninterpretable. This is also the biggest difference from sparse vectors like TF-IDF: one is a compressed dense representation, the other is a count over a vocabulary.

Higher dimensions aren't always better, and this is often overlooked. In high-dimensional spaces, distances concentrate toward the middle, the gap between the nearest and farthest neighbors gets flattened, and discriminability actually decreases. So in engineering, a few hundred to a thousand-plus dimensions is more common, paired with normalization and an appropriate metric, rather than blindly chasing size.

The metric itself also deserves separate mention. Cosine looks at the angle, Euclidean looks at absolute position, and inner product mixes angle and magnitude. After vectors are L2-normalized, the rankings of these three on the unit sphere are consistent, which is why most vector databases default to inner product. Conversely, if only the document side is normalized and the query side is forgotten, or if preprocessing was changed midway, similarity will shift overall, but the interface won't report any error. My habit is to write "normalization + inner product" into the index metadata, together with the model version.

## Text: words, sentences, and documents are three different compressions

### Words: first solve "any two words are equally far apart"

The earliest approach was one-hot: the vector is as long as the vocabulary, the current word's position is 1, and everything else is 0. It works, but has two hard flaws: a 50,000-word vocabulary means a 50,000-dimensional sparse vector; and the inner product of any two different words is 0—the distance between cat and dog is exactly the same as the distance between cat and calculus, and the vector contains no concept of "similarity" at all.

Word2Vec took a different approach: don't define words first, just have them predict neighbors. Skip-gram uses the center word to predict context, and CBOW does the reverse. After training, words that often appear in similar contexts naturally get pulled together. GloVe takes another path, starting from the global co-occurrence matrix and doing weighted factorization; FastText splits words into character n-grams, adds subword vectors, and incidentally alleviates the problems of out-of-vocabulary words and spelling variants.

Its most famous byproduct is analogy arithmetic: `king - man + woman` lands near `queen`. This isn't because the model truly understands gender, but because the co-occurrence structure leaves linear traces in space. And precisely because of this, it also faithfully learns the biases in the corpus, which was later discussed repeatedly.

The limitations are also clear: one word has only one vector. Whether "apple" is a fruit or a company, whether "bank" is a riverbank or a financial institution, the model can only give a compromise position. After ELMo and BERT, word vectors became context-dependent, and the same word gets different representations in different sentences, which finally handled polysemy.

### Sentences: the ceiling of mean pooling

The easiest way to turn a sentence into a vector is to average the word vectors. It's cheap, stable, and the default in many early systems. But averaging is essentially a bag of words, and word order and negation get erased:

- "Dog bites man" and "man bites dog" become the same vector after averaging.
- "I like this proposal" and "I don't like this proposal" differ only by a "not," yet the cosine is still high.

CNN and RNN were once the mainstream solutions: the former captures local n-grams, the latter reads in order. After Transformer, self-attention can look at the whole sentence at once, and positional encoding restores order information. But there's a widespread misunderstanding here: BERT's `[CLS]` vector is not naturally suitable for computing sentence similarity. For BERT without contrastive learning fine-tuning, the sentence vector distribution is anisotropic—all sentences are squeezed into a narrow cone-shaped region, and the cosine between any two random sentences is around 0.8. Sentence-BERT uses siamese networks and contrastive learning to repress sentences into a comparable space, and only then does "just compute cosine" become valid.

Current retrieval models basically all take this path: BGE, E5, GTE and the like, trained with large-scale weak supervision pairs plus hard negatives. There are two details that can't be skipped when using them: queries and documents need their respective prefixes (e.g., `query: ` / `passage: `), and the instructions must match those used during training. Missing a prefix won't cause an error; it will just quietly drop recall by a few points.

```python
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("BAAI/bge-small-zh-v1.5")
sentences = [
    "猫在追老鼠",
    "小猫在捕猎啮齿动物",
    "我喜欢火腿三明治",
]
# 归一化之后，内积等价于余弦
vecs = model.encode(sentences, normalize_embeddings=True)
sim = vecs @ vecs.T

for i in range(len(sentences)):
    print([round(float(x), 3) for x in sim[i]])
```

Every time I run this example, the similarity of the first two sentences is roughly around 0.7, and the third is only a little over 0.1. The numbers fluctuate with the model version, but the magnitude is very stable. Many people use it to prove that "the model understands semantics," but I think it also exposes a weakness: change the first two sentences to "cats don't chase mice" and "kittens don't hunt rodents," and the similarity is still high—what it captures is the topic, not the fact.

### Documents: a long text is not a "longer sentence"

The most common pitfall with document vectors is directly averaging the full text. A 3,000-word article may cover five subtopics, and averaging yields a center point that is "nothing." A more reliable approach is hierarchical:

1. Chunk by semantic boundaries (headings, paragraphs, code blocks), and encode each chunk separately;
2. At retrieval time, hit chunks, then aggregate upward to the article;
3. Use the title plus abstract for the article-level vector, or a weighted average of chunk vectors, rather than averaging the full text.

Among statistical methods, TF-IDF is still strong: representing documents as weight vectors over the vocabulary—sparse, interpretable, strong at literal matching, and more reliable than dense vectors for rare tokens such as error codes, person names, and internal code names. Its weaknesses are equally obvious: all word-order information is lost, and "dog bites man" and "man bites dog" have exactly the same weights. N-grams fill this gap by treating two or three consecutive words as one feature; order comes back, at the cost of a combinatorial explosion in the feature space, usually requiring minimum-frequency pruning or hashing.

Topic models are another path. LDA assumes each document is a mixture of several topics, and each topic is a distribution over words; after training, the document-topic distribution is used as the vector. It is interpretable—you can directly see "what this piece is about"—but the number of topics must be set manually, it is unstable on short texts, and for fine-grained similarity it usually underperforms neural methods.

Doc2Vec is the document version of Word2Vec: it learns an extra paragraph vector for each document, updated together with word vectors during training. The idea is intuitive and it does fine on long texts, but nowadays it is mostly used as a baseline or as a fallback in settings without GPUs.

What I ended up using on the blog is a hybrid scheme: dense vectors handle semantics, BM25 handles literal matching, and the two result sets are fused (details are in [another post](/2026/08/03/hybrid-retrieval-bm25-plus-vector/)). Those proper nouns in related recommendations are exactly what BM25 fishes back.

## Images: from "do they look alike" to "are they the same thing"

Vectorizing images has to answer a vaguer question than text: what makes two images similar? Similar colors, similar composition, or content of the same category? Different goals call for completely different methods.

In the handcrafted-feature era, the representatives were SIFT, SURF, and HOG. They find keypoints in an image (corners, blobs, edge orientations), pair each keypoint with a local descriptor, then use bag-of-words, VLAD, or Fisher vectors to aggregate the variable number of descriptors into a fixed-length vector—without aggregation, they cannot go into an index. Such features are very robust to rotation, scaling, and illumination, and suit "finding different angles of the same building"; but they do not understand semantics—a photo of a cat and one of a dog are both "a pile of edges and corners" to them. So they are usually paired with geometric metrics such as Euclidean distance, not semantic similarity.

In the CNN era, the approach is to use a classification network as a feature extractor: drop the final fully connected layer, take the output of the second-to-last layer, apply global average pooling, and get a vector of around 2048 dimensions—ResNet or VGG both work. The resulting vectors carry semantics: cat images cluster together even if coat color and pose differ completely. The cost is that it inherits the tastes of the classification dataset: for categories absent from ImageNet, representation quality drops noticeably. Two things must not be forgotten in practice: preprocessing must strictly match the training-time settings, and L2 normalization must be applied uniformly before indexing.

Autoencoders are another line. They do not predict labels, only require reconstruction of the input, and the narrow bottleneck in the middle is the representation. Advantages: no annotation needed, natural dimensionality reduction, suitable for compression, denoising, and anomaly detection; drawback: they optimize "can the pixels be restored," not "are the semantics close," so for retrieval they often underperform classification-network features.

What truly connects images and text is CLIP. It uses contrastive learning to train an image encoder and a text encoder simultaneously, pulling paired image-text closer in the same position and pushing unpaired ones apart. After training, an image and a caption share the same coordinate system, so "searching images by text" becomes a nearest-neighbor problem in the same space, and zero-shot classification becomes "write the class names as sentences and see which one matches best." CLIP's weaknesses must also be known: fine-grained counting, spatial relations ("the cup on the left"), and text inside images are all things it is bad at. One more point: it is extremely sensitive to preprocessing—whatever resize, crop, and normalization were used in training must be reproduced exactly at inference; switch to a different preprocessing and the vectors drift globally, all thresholds become invalid, and the code will not report any error.

ViT deserves a mention: it cuts an image into fixed-size patches, flattens each patch, and passes it through a linear layer to become a sequence of tokens. This idea was originally for image classification, yet it happened to pave the way for video.

## Video: patches are tokens, not retrieval vectors

Video has an extra time axis compared with images, and the approaches split into two almost unrelated directions.

The retrieval direction aims to "find similar clips." A common approach is frame sampling: pass each frame through CLIP to get a vector, then aggregate along time—averaging, weighting, or a small temporal model. It works for short videos but struggles with long videos and action content: door opening and door closing, after averaging, are almost the same vector. Models like VideoMAE and VideoCLIP have seen temporal dynamics during pretraining and perform better, but the compute cost goes up too.

The generation direction has a completely different goal, with Sora as the representative. Its approach can be roughly broken into three steps: first, a VAE compresses the video into a low-dimensional latent space, compressing time and space together, keeping the main structure and discarding high-frequency details; then the latent representation is cut into spacetime patches, each flattened into a token; finally, a diffusion Transformer generates over this token sequence, with text and image conditions also encoded as part of the sequence.

```python
# 概念示意，不是 Sora 的实现
z = vae.encode(video)                  # (T', H', W', C)，压缩后的潜在表示
patches = spacetime_patchify(z, p=2)   # 时空块 -> 定长 token 序列
tokens = patch_embed(patches)
out = diffusion_transformer(tokens, cond=text_tokens)
```

The conceptual mismatch most easily produced here is to treat Sora's patches as "video embeddings" and then compute cosine similarity with them. They are not designed for measurement but for reconstruction and generation: a good generative representation must retain details and be decodable back to pixels; a good retrieval representation must discard details and keep only comparable semantics. The two have opposite optimization goals and cannot be mixed.

One widely circulated claim needs correcting: Sora's technical report covers only images and video; audio is not in its unified representation. Some later models also cut audio into tokens and put them into the same sequence—that is another line and cannot be attributed directly to Sora.

Patches and tokens in GPT are indeed alike: both cut continuous signals into discrete units and then map them to vectors. The difference is that tokens have an explicit vocabulary, whereas patches are cut from a continuous latent space and have no vocabulary—position itself carries spacetime information. Compressing video to a latent and then cutting it into blocks is largely to control sequence length: attention cost grows quadratically with length, and global modeling directly on pixels is unrealistic.

## Whether the map is drawn right must be checked with a compass

Embedding visualization usually reduces high-dimensional vectors to two dimensions and then draws a scatter plot: PCA preserves global structure, t-SNE preserves local neighbors, and UMAP sits in between. The plots look nice, but there are plenty of pitfalls: inter-cluster distances in t-SNE are almost meaningless, cluster size and shape change with perplexity, and the same model with different hyperparameters can produce completely different plots. So visualization is only good for seeing "whether there is obvious collapse," not for proving a model is good or bad. A common pipeline is to first reduce to a few dozen dimensions with PCA for denoising, then run t-SNE for the plot.

There is a very practical self-check: randomly sample a batch of vectors and compute pairwise cosines; if the median is above 0.9, you can basically be sure the model has collapsed, or one side forgot normalization. Under a normal distribution, unrelated sentences should be clearly lower than related ones; if the overall baseline is absurdly high, do not suspect the data first—check preprocessing and normalization first.

What really decides whether to ship is still retrieval metrics: take a batch of real queries, look at Recall@k, MRR, and nDCG, and then break them down by query type—semantic questions, proper nouns, numbers, negations—the weak spots of each group often differ. Visualization is responsible for finding hard defects, evaluation is responsible for making decisions, and the two cannot replace each other.

## "Brute force works miracles" is only half right

There's a popular saying: as long as the model is large enough and the data is plentiful enough, embeddings can represent everything, and anything can be generated. Scale does solve the capacity problem, but it doesn't solve representation quality. With the same parameter count, the training objective, data mix, and negative-sample construction have a far greater impact on retrieval performance than stacking on a few more layers.

In engineering practice, I prefer to remember these few points:

| Modality | Typical representation | Good for | Most common pitfall |
| --- | --- | --- | --- |
| Text | Sentence vectors / chunk vectors | Semantic retrieval, clustering, deduplication | Pooling method, query prefix, averaging over long documents |
| Image | CNN features / CLIP | Image-to-image search, text-to-image search, deduplication | Inconsistent preprocessing, wrong feature layer chosen |
| Video | Frame aggregation / spatiotemporal patches | Clip retrieval / generative modeling | Confusing retrieval representations with generative representations |

There are also two points that have nothing to do with the model.

The model version is the schema of the index. Change the embedding model and all old vectors are invalidated; a full rebuild is mandatory. The query side and the document side must use the same model, the same set of prefixes, and the same normalization. The most insidious bug I've seen was during a canary rollout, where two model versions shared one index and recall inexplicably dropped by half.

Evaluation must use your own query distribution. Public leaderboards measure general semantics, but your users may speak entirely in internal codenames. The last time I switched models, the leaderboard score went up, but the internal-codename group actually dropped—and it took a private evaluation set of two hundred examples to pin down the problem. I wrote a separate piece on the specific dimensions of model selection ([Embedding Selection: Don't Just Look at Leaderboard Scores](/2025/05/23/embedding-selection-and-vector-representation/)), so I won't expand on it here.

Back to the "related articles" feature from the beginning. In the final version, besides hybrid retrieval, I added a rather crude rule: recompute the vectors for the same article once a day, and do a full rebuild when the model is upgraded. Maps expire—the world changes, so the coordinates have to be redrawn. Embeddings are the same: they're not a one-off conversion but a representation that must be maintained alongside your data and models.
