Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 05  /  EMBEDDINGS

The Meaning Map.

Turn every word into a point in space, arranged so that closeness means similar meaning. Click a word to find its neighbours, then do the impossible-sounding math: king − man + woman lands right on top of queen.

THE GIST · 20 SECONDS

An embedding is a word as a vector. Trained on context, words used alike end up pointing the same way. Similarity is the cosine of the angle between two vectors — 1 = same direction, 0 = unrelated. Because concepts become consistent directions, you can add and subtract meaning: king − man + woman ≈ queen. Geometry becomes semantics.

  • Embeddinga word as a vector
  • Cosineangle = similarity
  • Neighbourclosest by cosine
  • Analogyadd & subtract meaning

Click any word to see its nearest neighbours — or hit an analogy button on the right and watch the arithmetic land.

UNDER THE HOOD

What you just played, written down

Meaning becomes direction. Once every word is a vector, similarity is an angle and analogies are arithmetic — the two ideas that power semantic search and RAG.

How embeddings work — four ideas

  1. A word is a vector. Each word maps to a list of numbers, learned so words in similar contexts get similar vectors.
  2. Similarity is cosine. Compare two words by the angle between their vectors, not their distance — direction carries the meaning.
  3. Neighbours are meaning. The nearest vectors to a word are its closest relatives: cat → kitten, dog; tokyo → japan.
  4. Analogies are arithmetic. Concepts become consistent directions, so king − man + woman shifts along the gender axis and lands on queen.
WHY COSINE, NOT DISTANCE?

A word's vector can be long or short for reasons unrelated to meaning (frequency, magnitude). Cosine ignores length and compares only direction, so "cat" and "kitten" score high even if their raw magnitudes differ.

The whole thing in code

import numpy as np

def cosine(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))

def nearest(word, embeds, k=3):
    v = embeds[word]
    scored = [(w, cosine(v, u)) for w, u in embeds.items()
              if w != word]
    return sorted(scored, key=lambda t: -t[1])[:k]

def analogy(a, b, c, embeds):        # a - b + c
    target = embeds[a] - embeds[b] + embeds[c]
    scored = [(w, cosine(target, u)) for w, u in embeds.items()
              if w not in (a, b, c)]
    return max(scored, key=lambda t: t[1])   # → queen
COSINE−1 … 11 = identical direction
REAL DIMS100s–1000s2D here is a projection
THE 2D MAP IS A SHADOW

Real embeddings live in hundreds of dimensions. Tools like PCA or t-SNE flatten them to 2D so you can see the clusters — but the neighbours and analogies here are computed on the full vectors, not the flattened dots.

⚠ They inherit bias

Because embeddings learn from human text, they absorb its biases — analogies can surface stereotypes. Auditing and debiasing embeddings is an active area of fairness research.

↔ Static vs contextual

word2vec/GloVe give each word one fixed vector. Modern contextual embeddings (from Transformers) give a word a different vector per sentence, so "bank" differs by context.

★ Where it's used

Semantic search & RAG, recommendations, clustering, classification — and the very first layer of every Transformer, which embeds its input tokens.

STEP BY STEP

Word embeddings, step by step

How word2vec builds the space, the formula behind every similarity score, and this page's own vectors worked by hand: the numbers the map shows when you click.

How the space is learned, then searched

  1. Collect context pairs. Slide a window over the text (5 words on each side is a common default) and record every (word, neighbor) pair as a positive example.
  2. Add negatives. For each positive pair, draw k random words (k = 5 is typical), sampled in proportion to frequency0.75 so the most common words do not swamp the sample.
  3. Score with a dot product and train. Word2vec's skip-gram loss pushes σ(u·v) toward 1 for real pairs and toward 0 for the negatives. Words that share contexts get the same pushes, so their vectors end up pointing the same way.
  4. Search by cosine. Embed the query and rank stored vectors by cos(a, b). Once every vector has length 1, cosine is just the dot product, and ||a − b||² = 2 − 2·cos(a, b), so Euclidean distance gives the same ranking.
# skip-gram, negative sampling
loss = −log σ(u_c · v_w)
       − Σ_n log σ(−u_n · v_w)
# similarity of two vectors
cos(a, b) = a · b / (|a| · |b|)

Worked example: this page's vectors

  1. The axes. Each word here is a 0/1 vector over 11 readable dimensions: royal, male, female, animal, cat, dog, young, city, country, Europe, Asia. cat is animal + cat; kitten is animal + cat + young.
  2. cat vs kitten. Dot product 2, lengths √2 and √3, so cos = 2/√6 ≈ 0.82, cat's top neighbor.
  3. kitten vs puppy, cat vs dog. Sharing animal + young gives 2/3 ≈ 0.67; sharing only animal gives 1/2 = 0.50.
  4. king's neighbors. Click king and the nearest word is man (0.71), not queen (0.50). Each shares one axis with king, but man has no second axis to dilute the match.
  5. The analogies. king − man + woman = royal + female, which is exactly queen: cosine 1.00. paris − france + japan = city + Asia, exactly tokyo: also 1.00.
  6. Why the inputs are excluded. Against that same king − man + woman target, woman scores 0.71 and king 0.50. In real word2vec vectors an input word often scores highest, so analogy tests skip a, b and c, as the code above does.

⚠ Scores are relative

A cosine of 0.8 means different things in different models, and in many models even unrelated texts score well above 0. Rank by similarity, and calibrate any cut-off on labeled pairs from your own data. Vectors from two models are not comparable: switching models means re-embedding the corpus.

↔ Size and storage

One million vectors of 1,536 float32 values take 6.14 GB. int8 quantization cuts that to 1.54 GB and 1-bit codes to 192 MB, usually with a rescoring pass over the top hits. Some models, such as OpenAI's text-embedding-3 family, can be truncated to fewer dimensions.

★ In production

Normalize at write time and use the dot product. Embed queries and documents with the same model, including any query/passage prefixes it expects. Chunk long documents, since one vector averaged over many pages blurs every topic in it, and serve the search from an approximate nearest-neighbor index such as HNSW.

THE PICTURE

The picture: king − man + woman, axis by axis

royalmalefemale king110 − man0−10 + woman001 = target101 other 8 axes (animal, cat, dog, young,city, country, Europe, Asia): all 0 rank every word by cos(target, w) queen · 2/(√2·√2) = 1.00 woman · 1/√2 = 0.71 · input, skip king · 1/2 = 0.50 · input, skip man · 0 = 0.00 · input, skip 8 others · 0.00 · no shared axis answer: queen, once the three inputs are skipped cos(a, b) = a·b / (|a|·|b|)
The same arithmetic the lab runs when you press the analogy button, shown on the three axes that change. Subtracting man cancels male, adding woman switches on female, and the target lands exactly on queen. The right-hand ranking shows why analogy code skips its inputs: woman would come second and king third. Real models do the same sum over hundreds of unlabelled axes, and the target rarely lands exactly on any word, so “nearest” is all you get.
TRADE-OFFS

Cost and trade-offs: comparing, storing and searching vectors

Here Time is work per query (or per training pair) and Space is memory, for one million vectors of 1,536 dimensions unless the row says otherwise.

CaseTimeSpaceWhy
One cosine, raw vectorsdot + two norms: 4,608 multiply-addsnone extraNormalise once at write time and it drops to the dot product alone: 1,536.
Exact scan, float321.536 billion multiply-adds per query6.14 GBPerfect recall, cost grows linearly with the corpus.
Exact scan, int8same count, on 1-byte values1.54 GBA quarter of the memory traffic, for a small loss of precision.
1-bit codes, then rescoreone Hamming distance over 192 bytes per vector, then exact cosine on the top hits192 MB in RAM, full vectors kept elsewhere32 times smaller. The rescoring pass recovers most of the lost ordering.
HNSW graph indexvisits a small fraction of the vectors; grows roughly with log nvectors + about 128 MB of links at M = 16Approximate: recall under 100%, traded against speed by the search-width setting.
Training one pair, full softmaxV · d = 30,000,000 at V = 100,000, d = 300V · d output weightsNormalising over the whole vocabulary for every pair is what made early models slow.
Training one pair, negative sampling(k + 1) · d = 1,800 at k = 5same weightsAbout 16,667 times less work per pair, which is why word2vec offers it.

The storage rows and the search rows are separate decisions. Quantization shrinks every vector; an index cuts how many you look at. Large systems usually do both, then rescore a short list with full-precision vectors so the final order is exact even if the candidate list was not.

WATCH FOR

Common mistakes with embeddings

  • Ranking by raw dot product on unnormalised vectors

    Dot product rewards length as well as direction. Query kitten on this page’s vectors: cat and puppy both score a dot product of 2, a tie. Cosine separates them, 0.82 for cat and 0.67 for puppy, because puppy’s match is spread over a longer vector. Either normalise every vector at write time, or use cosine. Never mix normalised documents with raw queries.

  • Averaging word vectors to embed a sentence

    An average ignores order. “dog bites man” and “man bites dog” contain the same three words, so their averaged vectors are identical, and a search built on them cannot tell the stories apart. Averages also let frequent filler words dominate. Use a model trained to embed whole sentences or passages, which sees order and context.

  • Reading distances off the 2D plot

    The map is a projection. t-SNE in particular keeps local neighbourhoods and throws away global geometry, so the gap between two clusters and the size of a cluster carry little meaning, and a different random seed can move clusters around. Judge similarity on the full vectors, as the lab does, and use the plot only to spot structure worth checking.

  • Treating approximate search as exact

    An HNSW or IVF index returns most of the true nearest neighbours, not all of them, and the miss rate changes with its settings and with how the data grows. Measure recall@k: run a sample of real queries through both the index and an exact scan, and compare the top-k lists. Re-check after large inserts or a settings change.

  • Letting near-duplicates fill the top results

    Five copies of the same paragraph, from five versions of one document, are each other’s nearest neighbours and will take all five slots of a top-5 retrieval. The reader gets one fact five times. Deduplicate at ingest, or re-rank for diversity with maximal marginal relevance, which penalises a candidate for being too close to ones already picked.

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In an embedding space, what does it mean for two words to be close?

    Answer: They have similar meaning / appear in similar contexts — Embeddings are trained so words used in similar contexts get similar vectors. Geometric closeness (high cosine similarity) therefore corresponds to semantic closeness, which is why cat sits near kitten.

  2. Why use cosine similarity instead of straight-line distance?

    Answer: It compares direction and ignores vector length, which carries no meaning — A vector’s magnitude can vary for reasons unrelated to meaning. Cosine measures only the angle (direction) between vectors, so similarity reflects meaning rather than length.

  3. Why does king − man + woman land on queen?

    Answer: Because the man→woman gender direction, added to king, shifts it to the female-royalty region — Concepts become consistent directions in embedding space. Subtracting man and adding woman applies a gender shift; applied to king, the nearest word to the result is queen.

FAQ

Embeddings, answered

What is a word embedding?

A word represented as a vector of numbers, learned so words used in similar contexts get similar vectors. Closeness in the space means closeness in meaning.

What is cosine similarity?

The angle between two vectors — dot product over the product of magnitudes. It runs from 1 (same direction) through 0 (unrelated) to −1 (opposite), and ignores vector length.

How does king − man + woman ≈ queen work?

Concepts become consistent directions. The man→woman direction is a gender shift; adding it to king lands nearest to queen. The analogy is literal vector arithmetic.

Why show them in 2D?

Real embeddings have hundreds of dimensions. PCA/t-SNE project them to 2D so clusters are visible; the math here still uses the full vectors.

Where are embeddings used?

Semantic search and RAG, recommendations, clustering, classification, and as the first layer of every Transformer.

RESULT

—

Next → rank a whole document store by cosine to a query embedding and you've built the retrieval half of RAG.

Finished this one? 0 / 61 Labs done
NextThe Skip-List of Space: HNSW Next on the “Structure, and making new things” ladder · rung 4 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs