Lesson 23 Embeddings Deep Dive
Theme:
Lesson 23 · Slide 1

Embeddings Deep Dive

How machines represent meaning as numbers — from Word2Vec to production-grade vector search over millions of documents.

Learning Objectives

Lesson 23 · Slide 2

Word2Vec: Where It All Started

In 2013, Mikolov et al. showed that training a shallow neural network on a simple objective — predict a word from its neighbours — produces vectors where semantic relationships become arithmetic.

CBOW (Continuous Bag of Words)

Given surrounding context words, predict the centre word. Fast to train, works well on frequent words.

Input: ["the", "cat", "on", "mat"] → Predict: "sat"

Skip-gram

Given the centre word, predict each surrounding word. Better for rare words and small datasets.

Input: "sat" → Predict: ["the", "cat", "on", "mat"]

The Famous Analogy

vec("king") - vec("man") + vec("woman") ≈ vec("queen")

This showed the vectors encode relational structure, not just co-occurrence statistics.

Notes: Word2Vec vectors are static — the same word always gets the same vector regardless of context. This is a key limitation that contextual embeddings (BERT, etc.) solved.
Lesson 23 · Slide 3

From Words to Sentences & Documents

Word2Vec gives one vector per word, but most real tasks need to represent entire passages. Several approaches evolved:

Averaging Word Vectors

Simple mean of word vectors in a sentence. Cheap but loses word order. Surprisingly effective as a baseline.

Sentence-BERT (2019)

Fine-tuned BERT with a siamese/triplet network objective to produce fixed-size sentence vectors. Mean-pools the final-layer token embeddings. This is the foundation of the sentence-transformers library.

API Embedding Models

OpenAI text-embedding-3-large, Cohere embed-v4, Voyage voyage-3, and Google text-embedding-005 provide high-quality embeddings as a service — no GPU required.

Key Principle

Texts with similar meaning land close together in embedding space; dissimilar texts are far apart. The quality of "similar" depends on what the model was trained or fine-tuned to capture.

Lesson 23 · Slide 4

Cosine Similarity & Distance Metrics

Once you have two vectors, you need a way to measure how similar they are. The most common choice is cosine similarity.

import numpy as np

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
MetricRangeBest for
Cosine similarity-1 to 1Normalised embeddings (most common)
Dot product-∞ to +∞When magnitude encodes importance
Euclidean (L2)0 to +∞Clustering, when scale matters

Practical Rule

If embeddings are unit-normalised (most API models return normalised vectors), cosine similarity and dot product give identical rankings. Cosine is the safe default.

Notes: Cosine similarity of 1.0 = identical direction, 0.0 = orthogonal (unrelated), -1.0 = opposite. In practice, most text pairs land between 0.3 and 0.9.
Lesson 23 · Slide 5

Embedding Dimensions & Quality Trade-offs

Embedding models produce vectors of a fixed dimensionality. More dimensions can capture finer distinctions, but at a cost.

ModelDimensionsMTEB AvgSpeed
all-MiniLM-L6-v2384~56Very fast (local)
text-embedding-3-small (OpenAI)1536~62API latency
text-embedding-3-large (OpenAI)3072~64API latency
voyage-3 (Voyage AI)1024~67API latency
embed-v4 (Cohere)1024~66API latency

Trade-off Triangle

Notes: For most applications, 768–1536 dimensions is the sweet spot. Going from 384 to 1536 usually helps; going from 1536 to 3072 offers diminishing returns unless your task is very nuanced.
Lesson 23 · Slide 6

Vector Databases

Once you have embeddings, you need somewhere to store and search them efficiently. Vector databases use approximate nearest neighbour (ANN) algorithms to find similar vectors in milliseconds.

ChromaDB

Open-source, Python-native, embedded mode. Great for prototyping and small-to-medium datasets. Zero infrastructure needed.

Pinecone

Fully managed cloud service. Scales to billions of vectors. Serverless or pod-based tiers. No infrastructure to manage.

Weaviate

Open-source with cloud option. Hybrid search (vector + keyword). Built-in module system for embedding generation.

pgvector

PostgreSQL extension. Add vector search to your existing Postgres database. Perfect when you already use Postgres and want to avoid a second database.

Basic ChromaDB Example

import chromadb

client = chromadb.Client()
collection = client.create_collection("docs")

collection.add(
    documents=["AI is transforming healthcare", "The stock market rose today"],
    ids=["doc1", "doc2"]
)

results = collection.query(query_texts=["medical AI"], n_results=1)
print(results["documents"])  # [['AI is transforming healthcare']]
Lesson 23 · Slide 7

MTEB Benchmark & Fine-Tuning Embeddings

The Massive Text Embedding Benchmark (MTEB) evaluates embedding models across 8 task categories and 56+ datasets. It is the standard way to compare embedding quality.

MTEB Task Categories

When to Fine-Tune Embeddings

Off-the-shelf models work well for general text. Fine-tuning helps when:

  • Your domain has specialised vocabulary (legal, medical, scientific)
  • You need to align "similarity" with your specific definition (e.g., same customer intent, not just same topic)
  • You have labelled pairs or triplets (query, positive, negative)
from sentence_transformers import SentenceTransformer, InputExample, losses
from torch.utils.data import DataLoader

model = SentenceTransformer("all-MiniLM-L6-v2")
train_examples = [
    InputExample(texts=["anchor text", "positive match"], label=1.0),
    InputExample(texts=["anchor text", "negative example"], label=0.0),
]
train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16)
train_loss = losses.CosineSimilarityLoss(model)
model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=3)
Notes: Check MTEB leaderboard at huggingface.co/spaces/mteb/leaderboard before choosing an embedding model. Scores vary significantly across task types — a model that leads in retrieval may lag in classification.
Lesson 23 · Slide 8

Lab & Homework

Lab Exercises

  1. Generate Embeddings — use sentence-transformers to embed a set of sentences and inspect the resulting vectors
  2. Compute Similarities — build a cosine similarity matrix and identify the closest and farthest sentence pairs
  3. Semantic Search — load a small document corpus into ChromaDB and build a query interface that returns the top-k most relevant passages
  4. Compare Models — embed the same sentences with two different models and compare how similarity rankings change

Homework Tasks

  1. Build a domain-specific FAQ retrieval system using embeddings and measure its accuracy on 10 test queries.
  2. Compare cosine similarity vs. Euclidean distance on the same set of embeddings and explain when the rankings diverge.
  3. Research Matryoshka embeddings. Explain in 150 words how they work and why they are useful for production systems.
1 / ?