#What embeddings are
AddedAn embedding is a list of numbers that places a piece of text at a point in space, so that texts with similar meanings land close together. An embedding model is a neural network trained for exactly that: it reads a sentence and outputs a fixed-length vector (384 numbers for all-MiniLM-L6-v2, 1,024 by default for Voyage AI's current models, 1,536 or 3,072 for OpenAI's), whatever the length of the input. Once text is a vector, "is this document relevant to this question?" becomes geometry: measure the angle or distance between two points.
The mental model is a map of meaning. On a street map, two cafés on the same corner have nearby coordinates even if their names share no letters. On the embedding map, "How do I reset my password?" and "I forgot my login details" sit close together although they share no words, while "The parcel arrived damaged" is far away. The map has hundreds of dimensions instead of two, so it can keep many kinds of closeness apart at once (topic, intent, tone), but the idea is the same: close means similar.
How the model learns the map matters for using it well. Sentence-embedding models such as all-MiniLM-L6-v2 start from a transformer like the ones in How LLMs Work and are then trained on pairs of texts that should match (a question and its answer, a title and its article: over 1 billion pairs for this model, according to its model card) with a loss that pulls matching pairs together and pushes others apart. So "similar" means similar in the way the training pairs were similar: mostly "would answer the same question" or "is about the same thing". That's why embeddings are superb for search and clustering, and also why they have blind spots you'll see below.
Two details of how a vector is produced show up in every example. The model outputs one vector per token; mean pooling averages them into one vector for the whole text. Then normalising scales the vector to length 1, so only its direction carries meaning; that makes comparisons simpler and faster (next topic).
The example embeds six support messages, three pairs that mean the same thing in different words, and prints how similar each is to every other.
import { pipeline } from "@huggingface/transformers";
// A real sentence-embedding model (all-MiniLM-L6-v2, 8-bit weights), running locally.
const embed = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", { dtype: "q8" });
const sentences = [
"How do I reset my password?",
"I forgot my login details",
"Can I get a refund for my order?",
"I want my money back",
"The parcel arrived damaged",
"My package was broken when it came",
];
// Mean-pool the token vectors into one vector per sentence, then scale it to length 1.
const output = await embed(sentences, { pooling: "mean", normalize: true });
const vectors = output.tolist();
console.log(`tensor shape [${output.dims}]: ${vectors.length} sentences x ${vectors[0].length} numbers`);
console.log(`"${sentences[0]}" starts [${vectors[0].slice(0, 6).map((x) => x.toFixed(3)).join(", ")}, …]`);
console.log(`its length: ${Math.hypot(...vectors[0]).toFixed(3)}`);
// With length-1 vectors, the dot product is the cosine similarity.
const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
console.log("\ncosine similarity " + sentences.map((_, j) => ` s${j + 1}`).join(""));
sentences.forEach((s, i) => {
const row = vectors.map((v) => dot(vectors[i], v).toFixed(2).padStart(5)).join("");
console.log(`s${i + 1} ${s.slice(0, 18).padEnd(18)}${row}`);
});tensor shape [6,384]: 6 sentences x 384 numbers
"How do I reset my password?" starts [0.004, -0.055, -0.071, -0.038, -0.043, 0.069, …]
its length: 1.000
cosine similarity s1 s2 s3 s4 s5 s6
s1 How do I reset my 1.00 0.60 0.21 0.29 0.08 0.20
s2 I forgot my login 0.60 1.00 0.24 0.29 0.16 0.23
s3 Can I get a refund 0.21 0.24 1.00 0.54 0.34 0.37
s4 I want my money ba 0.29 0.29 0.54 1.00 0.16 0.24
s5 The parcel arrived 0.08 0.16 0.34 0.16 1.00 0.59
s6 My package was bro 0.20 0.23 0.37 0.24 0.59 1.00pipeline("feature-extraction", …)loads the tokenizer and the 8-bit model from the local cache. Called with an array, it embeds the whole batch in one forward pass;pooling: "mean"averages the per-token vectors into one per sentence, andnormalize: truescales each to length 1.- The result is a tensor of shape
[6, 384]: six sentences, 384 numbers each. The numbers themselves (0.004, -0.055, -0.071…) mean nothing on their own; no single dimension is "the password dimension". Only positions relative to other vectors carry meaning. The length printed is1.000, as normalising promised. - Because every vector has length 1, the dot product of two vectors is their cosine similarity: 1 for identical direction, around 0 for unrelated. The diagonal is 1.00 (each sentence with itself).
- The paraphrase pairs score highest in their rows: password/login 0.60, refund/money back 0.54, damaged parcel/broken package 0.59, with no shared content words in any pair. Unrelated pairs are much lower: the password question against the damaged parcel is 0.08.
- The middle values are informative too: "Can I get a refund for my order?" scores 0.34 and 0.37 against the delivery complaints, because damaged deliveries and refunds really do co-occur. Scores are graded, not yes/no, which is why search ranks by score and why the right threshold depends on your data.
"Close means similar" hides a question: similar in what way? These pairs show the answer for this model.
import { pipeline } from "@huggingface/transformers";
const embed = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", { dtype: "q8" });
async function similarity(a, b) {
const [x, y] = (await embed([a, b], { pooling: "mean", normalize: true })).tolist();
return x.reduce((s, v, i) => s + v * y[i], 0);
}
const pairs = [
["same meaning, different words", "The battery lasts all day", "Battery life is excellent"],
["opposite meaning, same words", "The battery lasts all day", "The battery does not last all day"],
["opposite sentiment", "I love this phone", "I hate this phone"],
["different error codes", "Error E1042 when printing", "Error E2210 when printing"],
["same question in Spanish", "How do I reset my password?", "¿Cómo restablezco mi contraseña?"],
["same question in Hindi", "How do I reset my password?", "मैं अपना पासवर्ड कैसे रीसेट करूं?"],
];
for (const [label, a, b] of pairs) console.log(`${(await similarity(a, b)).toFixed(3)} ${label.padEnd(30)} "${a}" / "${b}"`);0.572 same meaning, different words "The battery lasts all day" / "Battery life is excellent"
0.888 opposite meaning, same words "The battery lasts all day" / "The battery does not last all day"
0.822 opposite sentiment "I love this phone" / "I hate this phone"
0.902 different error codes "Error E1042 when printing" / "Error E2210 when printing"
0.028 same question in Spanish "How do I reset my password?" / "¿Cómo restablezco mi contraseña?"
0.094 same question in Hindi "How do I reset my password?" / "मैं अपना पासवर्ड कैसे रीसेट करूं?"- Paraphrase ("lasts all day" / "battery life is excellent") scores 0.572: clearly related, as you'd want.
- Negation scores 0.888, far higher than the paraphrase. "Does not last" shares almost every word and the topic, and mean pooling averages one extra "not" into twelve other tokens. For search ("find reviews about battery life") that's fine; for anything that depends on polarity it's wrong.
- Opposite sentiment ("love" / "hate" this phone) scores 0.822 for the same reason: same topic, same structure. Don't use raw embedding similarity as a sentiment or contradiction detector.
- Different error codes score 0.902. To this model
E1042andE2210are both "some error code", and the rest of the sentence is identical. Identifiers, part numbers, names and versions are exactly where embeddings are weakest and keyword search is strongest (Keyword search still matters). - Other languages: the same password question in Spanish scores 0.028 and in Hindi 0.094, no better than unrelated text. all-MiniLM-L6-v2 was trained on English pairs; multilingual models place translations close together, and that's a model choice you make up front (Choosing an embedding model).
- The pattern: embeddings capture topic and intent well and exact details, negation and polarity poorly. Good retrieval systems combine them with keyword search and a reranker (chapter 6) rather than trusting one similarity score.
The diagram at the top of this topic is real: it's a principal component analysis (PCA) of ten embeddings, computed by the program below. PCA finds the directions along which the points spread out most; projecting onto the top two gives the most faithful flat picture, though a lossy one.
import { pipeline } from "@huggingface/transformers";
const embed = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", { dtype: "q8" });
const sentences = [
"How do I reset my password?", "I forgot my login details", "My account is locked",
"Can I get a refund for my order?", "I want my money back", "How do returns work?",
"The parcel arrived damaged", "My package was broken when it came", "The box was crushed in delivery",
"Do you sell gift cards?",
];
const vectors = (await embed(sentences, { pooling: "mean", normalize: true })).tolist();
const dims = vectors[0].length;
// PCA: centre the vectors, then find the two directions along which they spread out most (power iteration).
const mean = Array.from({ length: dims }, (_, j) => vectors.reduce((s, v) => s + v[j], 0) / vectors.length);
const centred = vectors.map((v) => v.map((x, j) => x - mean[j]));
const project = (v, dir) => v.reduce((s, x, j) => s + x * dir[j], 0);
function direction(previous = []) {
let w = Array.from({ length: dims }, (_, j) => Math.sin(j + 1)); // any fixed starting vector
for (let iteration = 0; iteration < 200; iteration++) {
const scores = centred.map((v) => project(v, w));
let next = Array.from({ length: dims }, (_, j) => centred.reduce((s, v, i) => s + v[j] * scores[i], 0));
for (const p of previous) { const overlap = project(next, p); next = next.map((x, j) => x - overlap * p[j]); }
const length = Math.hypot(...next);
w = next.map((x) => x / length);
}
return w;
}
const first = direction();
const second = direction([first]);
const total = centred.reduce((s, v) => s + project(v, v), 0);
const share = (dir) => centred.reduce((s, v) => s + project(v, dir) ** 2, 0) / total;
console.log(`the two directions keep ${(share(first) * 100).toFixed(0)}% + ${(share(second) * 100).toFixed(0)}% of the spread`);
for (const [i, v] of centred.entries())
console.log(`${project(v, first).toFixed(2).padStart(6)} ${project(v, second).toFixed(2).padStart(6)} ${sentences[i]}`);the two directions keep 27% + 19% of the spread
0.62 -0.19 How do I reset my password?
0.51 -0.25 I forgot my login details
0.64 -0.21 My account is locked
-0.14 0.37 Can I get a refund for my order?
0.18 0.35 I want my money back
-0.10 0.60 How do returns work?
-0.55 -0.33 The parcel arrived damaged
-0.36 -0.38 My package was broken when it came
-0.54 -0.40 The box was crushed in delivery
-0.26 0.42 Do you sell gift cards?- The ten vectors are centred by subtracting their mean, so PCA measures spread around the middle of the cloud rather than distance from the origin.
directionfinds the direction of greatest spread by power iteration: repeatedly multiply a starting vector by the data and renormalise, and it settles on the top principal direction. The second call removes the first direction at every step, so it finds the best direction at right angles to it.- The two directions keep 27% and 19% of the total spread: the flat picture shows less than half of what the 384 dimensions hold. Points that look close in 2-D may be far apart in the full space, so never measure similarity on a projection.
- The coordinates still separate the three intents cleanly: account questions at about (0.6, −0.2), money questions near (−0.1, 0.4), damaged deliveries near (−0.5, −0.35). "Do you sell gift cards?" lands with the money questions, which is a reasonable reading.
- PCA is a sanity check worth knowing for production too: plot a sample of your corpus and your real queries, and if the queries sit somewhere the documents don't, your retrieval will struggle.
A shop embeds its reviews and searches for "battery does not last all day" to find complaints. Using the numbers from the blind-spots example, what will the top results contain, and how would you fix it?
Show answer
Plenty of happy reviews saying the battery does last all day, mixed in with the complaints.
- "The battery lasts all day" and "The battery does not last all day" scored 0.888, higher than a true paraphrase (0.572). To this model the topic dominates and the negation barely moves the vector.
- So a similarity search returns everything about battery life, both polarities, ranked mostly by wording overlap.
- Fixes, from cheapest: use the embedding search only to find battery-related reviews, then classify polarity with a model call or a sentiment classifier; or rerank candidates with a cross-encoder that reads query and review together (chapter 6), which handles negation far better than comparing two independent vectors.
- The general lesson: vector search is a recall step ("find candidates about X"), not a judge of fine-grained meaning.