Try it first
Before you read, pick what you think is right. It's fine to be wrong.
What can embeddings do that keyword search cannot?
What does the cosine similarity of two embedding vectors measure?
Text is made of separate symbols; math is a continuous space. Every time you look for "similar" documents, compare meanings, or make a search work even when the words differ, you cross a bridge between these two worlds. That bridge is the embedding. If you don't understand embeddings, you can use today's AI, but you can't understand it.
Type: Build Language: Python (standard library only) Prerequisites: Stage 1 Prompt Engineering, Python list and dictionary basics Time: about 75 minutes Next: Stage 4 Context Engineering — windows, budgets, memory, retrieval Run: Right in the browser (no install). The vectors in the code are built by counting words (TF-IDF), not by a trained model, and no real API is called.
What You Will Learn
- Explain how embeddings solve the "same meaning, different words" problem that keyword search cannot.
- Build, from scratch, a search engine that splits documents into pieces (chunks), turns them into vectors, and ranks them against a question.
- See for yourself when cosine similarity, dot product, and Euclidean distance give the same ranking and when they differ.
- Measure search quality with hit@1, recall@3, and MRR, and use those numbers to choose a tokenization method, a chunk size, a number of dimensions, and binary codes.
- Learn to use real embeddings and reranking through the OpenAI, Google, and Cohere APIs and open models (BGE-M3, Qwen3-Embedding).
The Problem
You have 10,000 customer inquiries from an online shop. A new customer writes "my payment didn't go through." You need to find similar past inquiries. Keyword search finds inquiries that contain "payment" and "didn't go through." It misses "the card approval was declined," "transaction failed," and "billing error." All of them describe the same problem in completely different words.
This is called the vocabulary mismatch problem. People have dozens of ways to say the same thing. Keyword search treats every word as a meaningless symbol. It has no way of knowing that "was declined" and "didn't go through" point to the same event.
Korean adds one more trap. Particles and endings attach to words. If you split on spaces, "환불은" and "환불을" (the word for "refund" with two different particles) become two different words, and documents with the same meaning are not found.
What you need is a representation of text in which closeness is decided by meaning, not by spelling. It is a way to place "my payment didn't go through" and "the card approval was declined" close together in some mathematical space, and to keep "I downloaded my payment history" far away even though it shares the word "payment."
That representation is the embedding.
The Concept
What an embedding is
An embedding is a list of real numbers that represents the meaning of a text, in other words a dense vector. "Dense" matters. Sparse representations such as bag-of-words or TF-IDF have zeros in most slots, while a dense vector carries information in every slot.
"The cat sat on the mat" becomes a list of numbers like [0.023, -0.041, 0.087, ..., 0.012]. The length differs by model. It runs from hundreds to thousands; for example, OpenAI text-embedding-3-small has 1536 and Gemini embeddings default to 3072. You almost never look at the individual numbers. You just compare vectors with each other.
Word2Vec — geometry carries meaning
In 2013, Tomas Mikolov and his Google colleagues published Word2Vec. The key idea is this. If you train a neural network to guess the middle word from its neighbors (or the neighbors from the middle word), the hidden-layer weights become meaningful vectors.
This is the famous result.
king - man + woman ≈ queen
Adding and subtracting word vectors captures relationships of meaning. The direction from "man" to "woman" is almost the same as the direction from "king" to "queen." This was the moment the field realized that geometry can carry meaning.
Word2Vec made a 300-dimensional vector for each word. One word gets one vector, regardless of context. The "bank" of a river bank and the "bank" of a bank account had the same vector. This limitation drove the next ten years of research.
From words to sentences
A word vector represents one word. Real services need to turn whole sentences, paragraphs, and documents into vectors. Four approaches emerged.
Averaging: Average the word vectors of a sentence. It is cheap, it loses information, and it is more useful than you might expect for short text. Word order disappears entirely. "The dog bit the man" and "The man bit the dog" become the same vector.
CLS token: Transformer models (BERT, 2018) output the vector of a special [CLS] token that stands for the whole input. It beats averaging, but the [CLS] token was trained for "next sentence prediction," not for similarity.
Contrastive learning: Train the model directly to pull similar pairs close and push different pairs apart. Sentence-BERT (Reimers & Gurevych, 2019) used this method, and it became the basis of today's embedding models. The model learns to give "How do I change my password?" and "I need to change my password" nearly the same vector.
XenLook note The Sentence-BERT paper shows in numbers why this approach matte…
The Sentence-BERT paper shows in numbers why this approach matters. To find the most similar pair among 10,000 sentences, feeding two sentences into BERT together and comparing every pair takes about 65 hours, but making one vector per sentence once and then comparing them takes about 5 seconds. You will meet this difference again below in "Bi-encoders and cross-encoders."
Embeddings with instructions: A method where you tell one model what job to do with a prefix such as "this is a search question" or "this is a document to be searched." Each model defines its own prefixes. E5 uses query: and passage: , Nomic uses search_query: and search_document: , and Qwen3-Embedding puts Instruct: {task}\nQuery: in front of the question. Gemini Embedding 2 uses task: search result | query: {content} for questions and title: {title} | text: {content} for documents. This lets a single model do several jobs. If you leave out the prefix or use another model's prefix, quality drops, so attach it exactly as written in the documentation of the model you use.
- king
- [0.2, -0.1, ...
- queen
- [0.3, -0.2, ...
- How do I change my password?
- [0.04, 0.12, ...
- I need to change my password
- [0.05, 0.11, ...
- query: change password
- [0.08, 0.09, ...
- passage: To change your password...
- [0.07, 0.10, ...
Today's embedding models
The models used most in production have narrowed to a handful. This follows each company's official documentation as of November 2026.
| Model | Maker | Dimensions | Input length per call | Features |
|---|---|---|---|---|
gemini-embedding-2 | 128–3072 (default 3072; 768, 1536, 3072 recommended) | 8,192 tokens | Text, images, audio, and video in one space. The task is given by a prefix. Passing several inputs in one call returns a single combined vector, so to get several separately, call one at a time or use the Batch API | |
gemini-embedding-001 | 128–3072 (default 3072) | 2,048 tokens | Text only. The task is given by the task_type parameter | |
text-embedding-3-small / -large | OpenAI | 1536 / 3072, reducible with dimensions | 8,192 tokens | Vectors normalized to length 1 |
embed-v5.0-pro / -fast | Cohere | 256–2048 (default 2048) | 128K tokens | Text and images. pro and fast share the same space, so you can index with pro and query with fast. Also returned as int8 or binary |
| BGE-M3 | BAAI | 1024 (dense + sparse + multi-vector) | 8,192 tokens | Open weights (MIT), more than 100 languages |
| Qwen3-Embedding 0.6B / 4B / 8B | Qwen | up to 1024 / 2560 / 4096 (can be reduced) | 32K tokens | Open weights (Apache-2.0), instruction prefixes, more than 100 languages |
XenLook note Leaderboard scores and prices are left out on purpose. Scores ch…
Leaderboard scores and prices are left out on purpose. Scores change every few months, and which model is better depends on the kind of task and the language. The MTEB paper itself concluded that "no method wins on every task." When choosing, look at the MTEB leaderboard for the entries that match your task (retrieval, classification, clustering) and your language (Korean), pick two or three candidates, and then measure them yourself on a few dozen questions from your own data. You will build the way to measure in "Build" 5) below. Check prices on each company's pricing page on the day you decide.
Measuring similarity
There are three ways to measure how similar two embedding vectors are.
Cosine similarity: The cosine of the angle between two vectors. It runs from -1 (opposite) to 1 (same direction). It ignores length. A ten-word sentence and a five-hundred-word document score 1 if they point the same way.
cos(a, b) = dot(a, b) / (|a| × |b|)
Dot product: Multiply the vectors slot by slot and add up. For vectors of length 1 (unit vectors) it equals the cosine. It is a little cheaper to compute. OpenAI embeddings come normalized to length 1, so dot product and cosine give the same ranking.
dot(a, b) = a₁b₁ + a₂b₂ + ... + aₙbₙ
Euclidean (L2) distance: The straight-line distance in space. Smaller means more similar. It is sensitive to differences in length.
L2(a, b) = √((a₁-b₁)² + (a₂-b₂)² + ... + (aₙ-bₙ)²)
For unit vectors, all three are tied together. The dot product equals the cosine, and the squared distance is 2 - 2 × cosine. So if you have normalized the vectors, any of the three gives the same ranking. Only the dot product of unnormalized vectors gives a different answer. A document made by pasting the same text three times has the same meaning, yet its dot product triples and it climbs to first place. You will see this yourself in "Build" STEP 3.
| Method | Use when | Avoid when |
|---|---|---|
| Cosine similarity | Comparing texts of different lengths, most search | The vector length carries meaning |
| Dot product | The vectors are already normalized, or speed matters | Unnormalized vectors |
| Euclidean distance | Clustering, finding nearby neighbors in space | Comparing documents of very different lengths without normalizing |
Vector databases and HNSW
A search that compares against every vector one by one (exhaustive search) takes about 1.5 billion multiplications and additions per query for 1 million vectors of 1536 dimensions. It gets slower in proportion to the data.
Vector databases solve this with approximate nearest neighbor (ANN) algorithms. The most widely used is HNSW (Hierarchical Navigable Small World graph).
- Build a graph with several layers from the vectors.
- The upper layers are sparse, with long links between clusters that are far apart.
- The lower layers are dense, linking vectors that are close.
- A search starts at the top layer and narrows down by walking toward the nearest vectors.
- Instead of the exact answer, it returns the top k that are nearly right. The paper showed that search time grows logarithmically with data size (exhaustive search grows in proportion to data size).
How accurate it will be depends on the settings (M, efConstruction, and ef at search time) and on your data. Raising the values makes it more accurate and slower. Decide by treating the exhaustive search result as the ground truth and measuring, on your own data, how much the top k overlap (recall@k).
- Layer 2 (sparse)
- Layer 1 (medium)
- Layer 0 (dense, all vectors)
- Query vector
- Top k
Common choices:
| Name | Type | Good for |
|---|---|---|
| Pinecone | Managed service | When you want to use it without operating it yourself |
| Weaviate | Open source | Self-hosting, hybrid search that mixes in keyword search |
| Qdrant | Open source | Self-hosting, filtering by conditions |
| Chroma | Embedded | Prototypes, development on your own computer |
| pgvector | Postgres extension | When you already use Postgres |
| FAISS | Library | Direct use inside your program, research |
XenLook note How far each can scale depends heavily on hardware, dimensions, …
How far each can scale depends heavily on hardware, dimensions, and settings, so no numbers are given in the table. If scale worries you, look at each product's official performance material together with results measured on your own data. If you have only tens of thousands of items, exhaustive search is often fast enough.
Chunking
A document is too long to turn into a single vector. A 50-page PDF covers dozens of topics. That one vector becomes an average of everything and resembles none of it in particular. So you split the document into pieces (chunks) and make a vector for each piece.
Fixed length: Cut every N tokens, with M tokens of overlap. It is simple and predictable. It suits text with no structure. With 512 tokens and 50 tokens of overlap, the first chunk is tokens 0–511 and the second is tokens 462–973.
By sentence: Cut at sentence boundaries and gather sentences up to the length limit. It never cuts a thought in half.
Recursive: Cut first at the largest boundary (headings). If a piece is still too big, cut at paragraphs, then sentences, and finally by character count. LangChain's RecursiveCharacterTextSplitter works this way and suits documents of mixed formats.
Semantic: Make a vector for each sentence and group neighboring sentences into one chunk while they are similar. When the similarity drops below a threshold, start a new chunk. It is expensive because every sentence needs an embedding.
| Method | Effort to build | Strengths | Weaknesses | Good for |
|---|---|---|---|---|
| Fixed length | Easy | Even sizes, predictable | Cuts mid-sentence | Text with no structure, logs |
| By sentence | Easy | Thoughts stay whole | Sizes vary with sentence length | Articles, emails, notices |
| Recursive | Medium | Follows document structure | Boundary rules must be set for each format | Markdown, HTML |
| Semantic | Hard | Cuts where the topic changes | Embedding cost per sentence, threshold tuning | When search quality matters a great deal |
XenLook note Two traps you often step in with Korean documents. First, if you…
Two traps you often step in with Korean documents. First, if you cut at every period, 99.95%, TLS 1.3, and web addresses get broken into pieces. Cut only when a period is followed by a space (STEP 1). Second, if you split words on spaces, particles stay attached, so "환불은" and "환불을" (both "refund" plus a particle) become different words. Real embedding models handle this with their own tokenizers, but when you also use word search (BM25), use a morphological analyzer or character-level pieces (STEP 2). There is no single right answer to "how many tokens is best." Choose the chunk size by measuring with your own documents and questions (STEP 8).
Bi-encoders and cross-encoders
A bi-encoder makes vectors for the question and the document separately and compares them. Document vectors are made ahead of time, and the question is turned into a vector only once. It is fast. This is what you use for search.
A cross-encoder feeds the question and the document together as one input and outputs a single relevance score. It runs the whole model for every question-document pair, so it is slow. In exchange, the question's tokens and the document's tokens look at each other directly, so it is much more accurate.
A common setup in production: use a bi-encoder to fetch a generous set of candidates (say the top 100), then rerank them with a cross-encoder and keep the top 10. This is "fetch, then rerank."
- Question
- Bi-encoder:question to vector
- Vector search:100 candidates
- Cross-encoder:rerank
- Top 10
Examples of reranking models (rerankers): Cohere rerank-v5.0-pro and rerank-v5.0-fast (paid API, many languages), BAAI/bge-reranker-v2-m3 (open weights, Apache-2.0), and jinaai/jina-reranker-v2-base-multilingual (open weights but CC-BY-NC-4.0, no commercial use). Always check the license of an open model before you use it.
Matryoshka embeddings
A normal embedding is all or nothing. If you take only the first 256 slots of a 1536-dimension vector, quality collapses badly in a model that was not trained to be used that way.
Matryoshka representation learning (MRL, Kusupati et al. 2022) solves this. Like a Russian doll, the model is trained so that the first N slots alone are usable. The earlier slots carry the more important information. If you cut the vector, quality drops a little but it still does its job.
OpenAI text-embedding-3 models use this through dimensions, Gemini embeddings through output_dimensionality, and Cohere Embed 5 through its choice of output dimension. If you ask for 256 slots instead of 1536, storage shrinks to one sixth. How much quality falls differs by model and data, so measure with your own evaluation questions. If you cut the first slots yourself after receiving the vector, you must re-normalize to length 1 so that cosine and dot product give the same answer.
XenLook note Truncating works only on models trained for it. You will see thi…
Truncating works only on models trained for it. You will see this yourself in STEP 6. If you cut the leading slots in an arbitrary order (alphabetical or otherwise), search collapses, and if you first re-sort the axes "most important first" (SVD) and then cut, it collapses far less. MRL builds this "most important first" order in during model training.
Binary quantization
Storing a 1536-dimension vector as float32 takes 6,144 bytes. For 10 million documents, the vectors alone come to about 61 GB.
Binary quantization turns each slot's number into one bit: 1 if greater than 0, otherwise 0. 6,144 bytes becomes 192 bytes, a 32-fold reduction. Similarity is measured by Hamming distance (the number of differing bits). One XOR and a count of the 1s (popcount) finish the job, so it is very fast.
Quality drops. A common setup is this. Scan everything quickly with the binary codes to pick a generous set of candidates, then re-score only those candidates with the original real-valued vectors. Re-scoring can save only what is inside the candidate set, so how many candidates you pick decides the quality. How much is preserved differs by model and data, so measure with your own evaluation questions.
XenLook note The sign bit keeps information only in vectors whose values spre…
The sign bit keeps information only in vectors whose values spread to both sides of 0. The vectors of trained embedding models are like that. If you binarize a vector whose values are all 0 or above, like TF-IDF, only "is this word present or not" remains, and it is almost useless. You compare the two in STEP 7.
Build It
XenLook note The Python names and output text are in English because real pro…
The Python names and output text are in English because real production code usually is too. It uses only the standard library (math, re), so it runs as is, with no install, in "Run the code" further down this page. Instead of a trained embedding model, it builds vectors by counting words (TF-IDF). So the framework of split into chunks → vector → similarity → ranking → measurement is the same as the real thing, and you also see where word counting hits its limits. The example texts are notices from a fictional online shop, "MoaShop."
1) Data and chunking
Six notices, plus an evaluation set of 8 questions a customer might type, each paired with its correct document. The last two questions were made on purpose to share almost no words with their correct document.
import math
import re
SAMPLE_DOCUMENTS = [
{"id": "refund", "title": "환불 정책", # Refund policy
"text": "모아샵 환불 정책입니다. 상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다. " # MoaShop refund policy. You can request a refund within 7 days of receiving the item.
"포장을 뜯지 않은 상품은 전액 환불됩니다. 환불 금액은 결제한 수단으로 3영업일 안에 돌아갑니다."}, # Unopened items are refunded in full. The money returns to the payment method within 3 business days.
{"id": "shipping", "title": "배송 안내", # Shipping
"text": "오후 2시 전에 주문하면 당일 출고합니다. 제주와 도서 지역은 1~2일 더 걸립니다. " # Orders placed before 2 pm ship the same day. Jeju and island areas take 1-2 more days.
"배송 조회는 주문 내역 화면에서 할 수 있습니다."}, # You can track a delivery on the order history screen.
{"id": "payment", "title": "결제 오류", # Payment errors
"text": "카드 승인이 거절되면 카드사 한도와 해외 결제 차단 설정을 확인하세요. " # If a card approval is declined, check your card limit and the foreign-payment block setting.
"같은 주문에 승인이 두 번 났다면 하나는 자동으로 취소됩니다."}, # If the same order was approved twice, one is cancelled automatically.
{"id": "security", "title": "계정 보안", # Account security
"text": "로그인할 때 2단계 인증을 켤 수 있습니다. 비밀번호는 10자 이상이어야 합니다. " # You can turn on 2-step verification at login. Passwords must be at least 10 characters.
"모든 통신은 TLS 1.3으로 암호화됩니다."}, # All traffic is encrypted with TLS 1.3.
{"id": "api", "title": "판매자 API", # Seller API
"text": "판매자 API 요청은 분당 600회까지 허용됩니다. 문서는 https://dev.moashop.example/v2 에 있습니다. " # Seller API requests are allowed up to 600 per minute. The docs are at https://dev.moashop.example/v2 .
"응답 형식은 JSON입니다."}, # The response format is JSON.
{"id": "uptime", "title": "서비스 가동률", # Service uptime
"text": "지난 분기 서비스 가동률은 99.95%였습니다. 정기 점검은 매주 화요일 새벽 3시에 합니다."}, # Last quarter's uptime was 99.95%. Regular maintenance is every Tuesday at 3 am.
]
LABELED_QUERIES = [
("환불은 며칠 안에 신청해야 하나요", "refund"), # Within how many days must I apply for a refund?
("오늘 주문하면 언제 출고되나요", "shipping"), # If I order today, when does it ship?
("카드 승인이 거절됐어요", "payment"), # My card approval was declined
("2단계 인증은 어떻게 켜나요", "security"), # How do I turn on 2-step verification?
("API 호출 한도가 얼마인가요", "api"), # What is the API call limit?
("점검은 언제 하나요", "uptime"), # When is maintenance?
("결제가 안 됐어요", "payment"), # My payment didn't go through
("돈을 돌려받고 싶어요", "refund"), # I want my money back
]Three ways to cut: fixed-length pieces, cutting at every period, and cutting only when a period is followed by a space.
def chunk_words(text, size=8, overlap=2):
"""Fixed-size chunks of `size` words; each chunk repeats the last `overlap` words of the one before."""
if overlap >= size:
raise ValueError("overlap must be smaller than size")
words = text.split()
chunks = []
step = size - overlap
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
def split_sentences_naive(text):
"""Splits on every period. Breaks decimals (99.95), versions (TLS 1.3) and URLs."""
return [p.strip() for p in text.split(".") if p.strip()]
def split_sentences(text):
"""Splits only where . ! or ? is followed by whitespace, so 99.95%, 1.3 and dev.moashop.example stay whole."""
return [p.strip() for p in re.split(r"(?<=[.!?])\s+", text) if p.strip()]2) Tokens and TF-IDF vectors
Two ways to cut text into tokens: space-separated words, and pieces made by cutting each word into overlapping two-character slices (bigrams). A bigram pulls "환불" (refund) out of "환불은", so the pieces overlap even when the particle differs.
def tokenize_words(text):
"""Lowercased runs of letters/digits. Punctuation is dropped, so "정책입니다." and "정책입니다" ("it is the policy") match."""
return re.findall(r"[0-9a-z가-힣]+", text.lower())
def char_bigrams(text):
"""Two-character pieces of each word. "환불은" -> 환불, 불은, so it shares "환불" (refund) with "환불을"."""
grams = []
for word in tokenize_words(text):
if len(word) <= 2:
grams.append(word)
else:
grams.extend(word[i:i + 2] for i in range(len(word) - 1))
return gramsTF-IDF gives each token a weight. The more often it appears in this chunk and the more rarely in other chunks, the heavier it is. The result is a sparse vector with zeros in most slots, so it is stored as a dictionary.
class TfidfEmbedder:
"""Sparse TF-IDF vectors: a weight per token, larger when the token is frequent here and rare elsewhere."""
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.idf = {}
def fit(self, texts):
n = len(texts)
df = {}
for text in texts:
for tok in set(self.tokenizer(text)):
df[tok] = df.get(tok, 0) + 1
# Smoothed idf: a token in every text still gets a small positive weight.
self.idf = {tok: math.log((1 + n) / (1 + c)) + 1 for tok, c in df.items()}
return self
def counts(self, text):
out = {}
for tok in self.tokenizer(text):
if tok in self.idf:
out[tok] = out.get(tok, 0) + 1
return out
def embed(self, text, normalize=True):
vec = {tok: c * self.idf[tok] for tok, c in self.counts(text).items()}
return unit(vec) if normalize else vec3) Similarity
Vector length, unit vectors, dot product, cosine, and Euclidean distance.
def norm(vec):
return math.sqrt(sum(v * v for v in vec.values()))
def unit(vec):
n = norm(vec)
return {k: v / n for k, v in vec.items()} if n else {}
def dot(a, b):
if len(a) > len(b):
a, b = b, a
return sum(v * b.get(k, 0.0) for k, v in a.items())
def cosine(a, b):
na, nb = norm(a), norm(b)
return dot(a, b) / (na * nb) if na and nb else 0.0
def euclidean(a, b):
keys = set(a) | set(b)
return math.sqrt(sum((a.get(k, 0.0) - b.get(k, 0.0)) ** 2 for k in keys))4) Where word counting stops
"결제가 안 됐어요" ("my payment didn't go through") and "카드 승인이 거절됐습니다" ("the card approval was declined") mean the same thing but share no words. By word counting, their similarity is 0. We build a toy that imitates by hand what a trained model does. We set up three named axes (payment, failure, records) and place a few words on those axes by hand. A real model learns hundreds or thousands of unnamed axes by itself from data.
CONCEPT_AXES = ("payment", "failure", "records")
CONCEPT_LEXICON = {
"결제": (1.0, 0.0, 0.0),
"카드": (0.8, 0.0, 0.0),
"승인": (0.8, 0.0, 0.0),
"거절": (0.0, 1.0, 0.0),
"안 됐": (0.0, 1.0, 0.0),
"실패": (0.0, 1.0, 0.0),
"내역": (0.0, 0.0, 1.0),
"다운로드": (0.0, 0.0, 0.8),
}def toy_concept_vector(text):
vec = {axis: 0.0 for axis in CONCEPT_AXES}
for phrase, weights in CONCEPT_LEXICON.items():
if phrase in text:
for axis, w in zip(CONCEPT_AXES, weights):
vec[axis] += w
return vec5) Search engine and measurement
Bundle chunking, vector making, and cosine ranking into one. And then measure. You must not finish a search by glancing at a few results and saying "looks fine." Measure three things with questions whose answers you know.
- hit@1: the share of questions where the correct document came out first
- recall@3: the share where the correct document is in the top 3
- MRR: the average of the reciprocal of the correct document's rank (1 if first, 0.5 if second, 0 if not found)
The size of a similarity score itself (for example 0.85) means something different for each model, so it is hard to use as a yardstick. What matters is whether the correct answer rises to the top.
class SemanticSearchEngine:
"""Chunks documents, embeds the chunks, and ranks them against a query by cosine similarity."""
def __init__(self, tokenizer, chunker=split_sentences):
self.tokenizer = tokenizer
self.chunker = chunker
self.chunks = []
self.embedder = None
self.vectors = []
def index(self, documents):
self.chunks = [(doc["id"], chunk) for doc in documents for chunk in self.chunker(doc["text"])]
self.embedder = TfidfEmbedder(self.tokenizer).fit([c for _, c in self.chunks])
self.vectors = [self.embedder.embed(c) for _, c in self.chunks]
return self
def search(self, query, k=3):
q = self.embedder.embed(query)
scored = [(cosine(q, v), i) for i, v in enumerate(self.vectors)]
scored.sort(key=lambda s: (-s[0], s[1]))
return [(score, self.chunks[i][0], self.chunks[i][1]) for score, i in scored[:k]]
def ranked_docs(self, query):
"""Document ids in order of their best chunk; documents with no shared token are left out."""
seen = []
for score, doc_id, _ in self.search(query, k=len(self.chunks)):
if score > 0 and doc_id not in seen:
seen.append(doc_id)
return seen
def evaluate(ranker, labeled_queries, k=3):
"""hit@1: right document first. recall@k: right document in the top k. MRR: average of 1/rank (0 if missing)."""
hits = recall = rr = 0.0
misses = []
for query, answer in labeled_queries:
docs = ranker(query)
if docs[:1] == [answer]:
hits += 1
if answer in docs[:k]:
recall += 1
if answer in docs:
rr += 1 / (docs.index(answer) + 1)
if docs[0] != answer:
misses.append(f"{query} -> right document at rank {docs.index(answer) + 1}")
else:
misses.append(f"{query} -> right document not found")
n = len(labeled_queries)
return {"hit@1": hits / n, f"recall@{k}": recall / n, "MRR": rr / n, "misses": misses}
def show_metrics(label, m):
keys = [k for k in m if k != "misses"]
print(f" {label:<32}" + " ".join(f"{k} {m[k]:.2f}" for k in keys))6) Cutting dimensions
Cut the leading slots of the 187-slot TF-IDF vector. First cut in the original alphabetical order, and then re-sort the axes with SVD (singular value decomposition), starting with "the axis that best explains the chunks," and cut after that. SVD imitates by computation the "most important axis first" order that Matryoshka models acquire through training. There are only 17 chunks, so there are at most 17 SVD axes. The matrix calculation finds the eigenvalues of a small symmetric matrix with Jacobi rotations, using only the standard library.
def dense_matrix(vectors, features):
return [[v.get(f, 0.0) for f in features] for v in vectors]
def dense_cosine(a, b):
num = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return num / (na * nb) if na and nb else 0.0
def jacobi_eigen(a, sweeps=60):
"""Eigenvalues and eigenvectors of a small symmetric matrix (Jacobi rotations), largest first."""
n = len(a)
a = [row[:] for row in a]
v = [[float(i == j) for j in range(n)] for i in range(n)]
for _ in range(sweeps):
if sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j) < 1e-18:
break
for p in range(n):
for q in range(p + 1, n):
if abs(a[p][q]) < 1e-15:
continue
theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
t = (1 if theta >= 0 else -1) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(t * t + 1)
s = t * c
for k in range(n):
a[k][p], a[k][q] = c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]
for k in range(n):
a[p][k], a[q][k] = c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]
for k in range(n):
v[k][p], v[k][q] = c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]
order = sorted(range(n), key=lambda i: -a[i][i])
return [a[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
def svd_directions(matrix):
"""New axes for the chunk vectors, ordered so the first axis carries the most of them (SVD via the small Gram matrix)."""
n = len(matrix)
gram = [[sum(x * y for x, y in zip(matrix[i], matrix[j])) for j in range(n)] for i in range(n)]
values, vectors = jacobi_eigen(gram)
directions = []
for lam, u in zip(values, vectors):
if lam > 1e-9:
s = math.sqrt(lam)
directions.append([sum(u[i] * matrix[i][j] for i in range(n)) / s for j in range(len(matrix[0]))])
share = [lam / sum(values) for lam in values if lam > 1e-9]
return directions, share
def project(row, directions):
return [sum(x * y for x, y in zip(row, d)) for d in directions]
def doc_ranker(engine, rows, to_row):
"""Ranks documents by their best chunk, comparing to_row(query vector) with the given chunk rows."""
def rank(query):
qrow = to_row(engine.embedder.embed(query))
scored = sorted(((dense_cosine(qrow, r), i) for i, r in enumerate(rows)), key=lambda s: (-s[0], s[1]))
seen = []
for score, i in scored:
doc_id = engine.chunks[i][0]
if score > 0 and doc_id not in seen:
seen.append(doc_id)
return seen
return rank7) Binary codes and rescoring
Make bit codes that keep only "is it greater than 0?" for each slot, pick candidates by Hamming distance, and then rescore only the candidates with the real-valued vectors. Take the top 3 of the real-valued vectors as the ground truth and measure how much they overlap.
def binarize(row):
"""1 bit per dimension: is the value above zero?"""
return [1 if x > 0 else 0 for x in row]
def hamming(a, b):
return sum(x != y for x, y in zip(a, b))
def top_chunks_float(qrow, rows, k):
"""The reference answer: the k best chunks by full-precision cosine. Chunks scoring 0 share nothing with the query, so they are left out."""
scored = sorted(((dense_cosine(qrow, r), i) for i, r in enumerate(rows)), key=lambda s: (-s[0], s[1]))
return [i for score, i in scored[:k] if score > 0]
def top_chunks_binary(qbits, codes, k):
scored = sorted(((hamming(qbits, c), i) for i, c in enumerate(codes)), key=lambda s: (s[0], s[1]))
return [i for _, i in scored[:k]]
def rescore(qrow, rows, candidates, k):
scored = sorted(((dense_cosine(qrow, rows[i]), i) for i in candidates), key=lambda s: (-s[0], s[1]))
return [i for _, i in scored[:k]]8) Run everything
Run the eight experiments in order. The last one, STEP 8, changes the chunk size and measures with the same evaluation questions.
def step_chunking():
print("=" * 64)
print("STEP 1: Chunking")
print("=" * 64)
text = SAMPLE_DOCUMENTS[5]["text"] + " " + SAMPLE_DOCUMENTS[4]["text"]
print(" naive split on '.':")
for s in split_sentences_naive(text):
print(" |", s)
print(" split only before whitespace:")
for s in split_sentences(text):
print(" |", s)
print(" 8-word chunks, 2 words of overlap:")
for c in chunk_words(SAMPLE_DOCUMENTS[0]["text"], size=8, overlap=2):
print(" |", c)
print()
def step_tokens():
print("=" * 64)
print("STEP 2: Word tokens vs character bigrams")
print("=" * 64)
q = "환불은 며칠 안에 신청해야 하나요"
d = "상품을 받은 날부터 7일 안에 환불을 요청할 수 있습니다."
for name, tok in (("words", tokenize_words), ("bigrams", char_bigrams)):
shared = sorted(set(tok(q)) & set(tok(d)))
print(f" {name:<8} query {tok(q)}")
print(f" {name:<8} shared with the refund sentence: {shared}")
print()
def step_similarity():
print("=" * 64)
print("STEP 3: Cosine, dot product, Euclidean distance")
print("=" * 64)
docs = SAMPLE_DOCUMENTS[:3] + [{"id": "payment x3", "text": " ".join([SAMPLE_DOCUMENTS[2]["text"]] * 3)}]
emb = TfidfEmbedder(char_bigrams).fit([d["text"] for d in SAMPLE_DOCUMENTS])
query = "주문 결제 승인"
print(f' query: "{query}" ("payment x3" is the payment text pasted three times)')
q_raw, q_unit = emb.embed(query, normalize=False), emb.embed(query)
rows = []
for d in docs:
raw, u = emb.embed(d["text"], normalize=False), emb.embed(d["text"])
rows.append((d["id"], cosine(q_raw, raw), dot(q_raw, raw), dot(q_unit, u), euclidean(q_unit, u)))
print(f" {'doc':<12}{'cosine':>8}{'dot(raw)':>10}{'dot(unit)':>11}{'L2(unit)':>10}{'sqrt(2-2cos)':>14}")
for doc_id, c, d_raw, d_unit, l2 in rows:
print(f" {doc_id:<12}{c:>8.3f}{d_raw:>10.2f}{d_unit:>11.3f}{l2:>10.3f}{math.sqrt(max(0.0, 2 - 2 * c)):>14.3f}")
order = lambda col, rev: [r[0] for r in sorted(rows, key=lambda r: (-round(r[col], 9) if rev else round(r[col], 9)))]
print(" rank by cosine :", order(1, True))
print(" rank by dot(unit):", order(3, True))
print(" rank by L2(unit) :", order(4, False))
print(" rank by dot(raw) :", order(2, True))
print()
def step_mismatch():
print("=" * 64)
print("STEP 4: Same meaning, different words")
print("=" * 64)
a = "결제가 안 됐어요"
b = "카드 승인이 거절됐습니다"
c = "결제 내역을 다운로드했어요"
emb = TfidfEmbedder(char_bigrams).fit([a, b, c])
va, vb, vc = emb.embed(a), emb.embed(b), emb.embed(c)
print(f' A "{a}" B "{b}" C "{c}"')
print(f" TF-IDF bigrams A~B {cosine(va, vb):.3f} A~C {cosine(va, vc):.3f}")
ta, tb, tc = toy_concept_vector(a), toy_concept_vector(b), toy_concept_vector(c)
print(f" toy concept axes A~B {cosine(ta, tb):.3f} A~C {cosine(ta, tc):.3f}")
for name, t in (("A", ta), ("B", tb), ("C", tc)):
print(f" {name} {CONCEPT_AXES} = {tuple(round(t[x], 1) for x in CONCEPT_AXES)}")
print()
def step_search_eval():
print("=" * 64)
print("STEP 5: Search, then measure it")
print("=" * 64)
engine = SemanticSearchEngine(char_bigrams).index(SAMPLE_DOCUMENTS)
for score, doc_id, chunk in engine.search("카드 승인이 거절됐어요", k=3):
if score > 0:
print(f" {score:.3f} [{doc_id}] {chunk}")
print(f" {len(LABELED_QUERIES)} labeled queries, {len(engine.chunks)} sentence chunks:")
for name, tok in (("word tokens", tokenize_words), ("character bigrams", char_bigrams)):
eng = SemanticSearchEngine(tok).index(SAMPLE_DOCUMENTS)
m = evaluate(eng.ranked_docs, LABELED_QUERIES)
show_metrics(name, m)
for miss in m["misses"]:
print(f" {miss}")
print()
return engine
def step_truncation(engine):
print("=" * 64)
print("STEP 6: Cutting dimensions")
print("=" * 64)
features = sorted(engine.embedder.idf)
matrix = dense_matrix(engine.vectors, features)
to_full = lambda q: [q.get(f, 0.0) for f in features]
print(f" full vector: {len(features)} dimensions")
show_metrics("all dimensions", evaluate(doc_ranker(engine, matrix, to_full), LABELED_QUERIES))
for n in (8, 16, 64):
rows = [r[:n] for r in matrix]
show_metrics(f"first {n} (a-z order)", evaluate(doc_ranker(engine, rows, lambda q, n=n: to_full(q)[:n]), LABELED_QUERIES))
directions, share = svd_directions(matrix)
print(f" after SVD: {len(directions)} axes (one per chunk at most), largest first")
for n in (2, 4, 8, 16):
d = directions[:n]
rows = [project(r, d) for r in matrix]
label = f"first {n} SVD axes ({sum(share[:n]):.0%})"
show_metrics(label, evaluate(doc_ranker(engine, rows, lambda q, d=d: project(to_full(q), d)), LABELED_QUERIES))
print()
return features, matrix, directions
def step_binary(engine, features, matrix, directions):
print("=" * 64)
print("STEP 7: Binary codes")
print("=" * 64)
k = 3
presence = [binarize(r) for r in matrix]
dense = [project(r, directions) for r in matrix]
signs = [binarize(r) for r in dense]
totals = {f"presence bits ({len(features)})": 0, f"SVD sign bits ({len(directions)})": 0,
"sign bits top 6 -> rescore": 0, "sign bits top 10 -> rescore": 0}
names = list(totals)
n = 0
for query, _ in LABELED_QUERIES:
q = engine.embedder.embed(query)
qrow = [q.get(f, 0.0) for f in features]
truth = set(top_chunks_float(qrow, matrix, k))
n += len(truth)
totals[names[0]] += len(truth & set(top_chunks_binary(binarize(qrow), presence, k)))
cand = top_chunks_binary(binarize(project(qrow, directions)), signs, 10)
totals[names[1]] += len(truth & set(cand[:k]))
totals[names[2]] += len(truth & set(rescore(qrow, matrix, cand[:6], k)))
totals[names[3]] += len(truth & set(rescore(qrow, matrix, cand, k)))
print(f" overlap with the float top {k} (chunks scoring above 0: {n} over {len(LABELED_QUERIES)} queries):")
for name, hit in totals.items():
print(f" {name:<30}{hit}/{n} ({hit / n:.0%})")
d = 1536
print(f" storage for one {d}-dimension vector: float32 {d * 4} bytes, 1 bit each {d // 8} bytes ({d * 4 // (d // 8)}x smaller)")
print()
def step_chunk_size():
print("=" * 64)
print("STEP 8: Chunk size")
print("=" * 64)
for size in (4, 8, 16, 64):
overlap = size // 4
eng = SemanticSearchEngine(char_bigrams, chunker=lambda t, s=size, o=overlap: chunk_words(t, s, o)).index(SAMPLE_DOCUMENTS)
show_metrics(f"{size} words, overlap {overlap} ({len(eng.chunks)} chunks)", evaluate(eng.ranked_docs, LABELED_QUERIES))
eng = SemanticSearchEngine(char_bigrams).index(SAMPLE_DOCUMENTS)
show_metrics(f"sentences ({len(eng.chunks)} chunks)", evaluate(eng.ranked_docs, LABELED_QUERIES))
print()if __name__ == "__main__":
step_chunking()
step_tokens()
step_similarity()
step_mismatch()
engine = step_search_eval()
features, matrix, directions = step_truncation(engine)
step_binary(engine, features, matrix, directions)
step_chunk_size()How to read the results
XenLook note This section is guidance added by XenLook.
This section is guidance added by XenLook.
STEP 2 shows the particle problem.
words query ['환불은', '며칠', '안에', '신청해야', '하나요']
words shared with the refund sentence: ['안에']
bigrams query ['환불', '불은', '며칠', '안에', '신청', '청해', '해야', '하나', '나요']
bigrams shared with the refund sentence: ['안에', '환불']With space-separated words, the question and the refund notice share only one word, "안에" ("within"). That is because "환불은" and "환불을" are different words. When cut into two-character pieces, "환불" overlaps.
STEP 3 compares the three similarity measures. payment x3 is a fake document made by pasting the payment notice three times.
query: "주문 결제 승인" ("payment x3" is the payment text pasted three times)
doc cosine dot(raw) dot(unit) L2(unit) sqrt(2-2cos)
refund 0.057 3.41 0.057 1.374 1.374
shipping 0.156 6.83 0.156 1.299 1.299
payment 0.344 16.97 0.344 1.146 1.146
payment x3 0.344 50.92 0.344 1.146 1.146
rank by cosine : ['payment', 'payment x3', 'shipping', 'refund']
rank by dot(unit): ['payment', 'payment x3', 'shipping', 'refund']
rank by L2(unit) : ['payment', 'payment x3', 'shipping', 'refund']
rank by dot(raw) : ['payment x3', 'payment', 'shipping', 'refund']Cosine, the dot product of unit vectors, and the distance between unit vectors give the same ranking. The last column, sqrt(2-2cos), matching the distance column exactly confirms "squared distance of unit vectors = 2 - 2 × cosine." Only the unnormalized dot product (dot(raw)) lifts payment x3, which has the same content, to first place. The longer document wins regardless of meaning.
STEP 4 is the limit of word counting.
A "결제가 안 됐어요" B "카드 승인이 거절됐습니다" C "결제 내역을 다운로드했어요"
TF-IDF bigrams A~B 0.000 A~C 0.199
toy concept axes A~B 0.974 A~C 0.343
A ('payment', 'failure', 'records') = (1.0, 1.0, 0.0)
B ('payment', 'failure', 'records') = (1.6, 1.0, 0.0)
C ('payment', 'failure', 'records') = (1.0, 0.0, 1.8)By word counting, A and B, which mean the same thing, score 0, and A and C, which share only the word "결제" (payment), come out closer. It is the reverse of human judgment. On the toy concept axes, A and B are close at 0.974 and C is far. This is the job a trained embedding model does for you.
STEP 5 measures the search.
8 labeled queries, 17 sentence chunks:
word tokens hit@1 0.75 recall@3 0.75 MRR 0.75
결제가 안 됐어요 -> right document not found
돈을 돌려받고 싶어요 -> right document not found
character bigrams hit@1 0.75 recall@3 0.88 MRR 0.81
결제가 안 됐어요 -> right document at rank 2
돈을 돌려받고 싶어요 -> right document not foundTwo-character pieces do better than space-separated words (recall@3 0.75 → 0.88). Even so, "돈을 돌려받고 싶어요" ("I want my money back") is never found, because no characters overlap with the refund notice. This is as far as word counting goes. To find this question you need a trained embedding model. And once you have this evaluation set, you can confirm with numbers whether switching to another model really improves things.
STEP 6 is cutting dimensions.
full vector: 187 dimensions
all dimensions hit@1 0.75 recall@3 0.88 MRR 0.81
first 8 (a-z order) hit@1 0.12 recall@3 0.12 MRR 0.12
first 16 (a-z order) hit@1 0.12 recall@3 0.12 MRR 0.12
first 64 (a-z order) hit@1 0.62 recall@3 0.62 MRR 0.62
after SVD: 17 axes (one per chunk at most), largest first
first 2 SVD axes (16%) hit@1 0.25 recall@3 0.62 MRR 0.47
first 4 SVD axes (29%) hit@1 0.38 recall@3 0.75 MRR 0.59
first 8 SVD axes (53%) hit@1 0.75 recall@3 0.88 MRR 0.81
first 16 SVD axes (96%) hit@1 0.75 recall@3 0.88 MRR 0.81If you keep only the first 8 or 16 slots in alphabetical order, hit@1 collapses to 0.12 (1 out of 8). That is because only the tokens that happen to sit in those slots remain. If you line up the axes with SVD, most important first, just 8 slots give the same score as the full vector. The number in parentheses is the share of the sum of squares of all chunk vectors that those axes hold. Even though 8 axes hold only 53%, the ranking is the same as with the full vector. Truncating works only on vectors built so that "the important part comes first."
STEP 7 is binary codes.
overlap with the float top 3 (chunks scoring above 0: 15 over 8 queries):
presence bits (187) 4/15 (27%)
SVD sign bits (17) 13/15 (87%)
sign bits top 6 -> rescore 13/15 (87%)
sign bits top 10 -> rescore 14/15 (93%)
storage for one 1536-dimension vector: float32 6144 bytes, 1 bit each 192 bytes (32x smaller)presence bits, which turn the TF-IDF slots directly into bits, overlap with the top 3 of the real-valued vectors by only 27%. That is because every value is 0 or above, so only "present/absent" is left. The values on the SVD axes spread to both sides of 0, so their 17 sign bits keep 87%. Rescoring saves only what is inside the candidate set. With 6 candidates it stays at 87%, and when you raise the candidates to 10 it becomes 93%. This means the missed chunk was sitting in 7th–10th place.
STEP 8 is chunk size.
4 words, overlap 1 (34 chunks) hit@1 0.88 recall@3 0.88 MRR 0.88
8 words, overlap 2 (17 chunks) hit@1 0.88 recall@3 0.88 MRR 0.88
16 words, overlap 4 (9 chunks) hit@1 0.75 recall@3 0.88 MRR 0.81
64 words, overlap 16 (6 chunks) hit@1 0.88 recall@3 0.88 MRR 0.88
sentences (17 chunks) hit@1 0.75 recall@3 0.88 MRR 0.81On this small data, chunks of 4, 8, and 64 words scored a higher hit@1 than sentence-level chunks. Even so, you can't say "this many words is the right answer." The fact that 4 words and 64 words score the same already means there aren't enough questions to tell the difference. With only 8 questions, a single question going right or wrong moves the score by 0.12. In real documents, chunks that are too small lose the surrounding context and may not leave enough material to build an answer. Choose the chunk size by measuring with your own documents and plenty of evaluation questions.
| Part of the output | Meaning |
|---|---|
| STEP 1 | Cutting at every period breaks 99.95% and the web address; cutting only at a space after a period keeps them whole. The 8-word chunks overlap by 2 words |
| STEP 2 | Space-separated words miss "환불" (refund) because of the particle, and two-character pieces catch it |
| STEP 3 | With normalized vectors, cosine, dot product, and distance give the same ranking. Only the unnormalized dot product lifts the long document to first place |
| STEP 4 | Same meaning, different words: word counting gives 0, the concept axes give 0.974 |
| STEP 5 | hit@1, recall@3, and MRR measured with 8 evaluation questions, plus the questions that were not found |
| STEP 6 | Cutting in an arbitrary order collapses; cutting from the most important axis holds up |
| STEP 7 | How much of the real-valued top 3 the binary codes preserve, and how much rescoring saves |
| STEP 8 | Scores by chunk size — with few questions, differences can be chance |
Use It
XenLook note All the code below is blocked with comments (#) and does not r…
All the code below is blocked with comments (#) and does not run. To actually run it you need each company's API key or a model download. The model IDs and function names come from each company's official documentation as of November 2026, so check that day's documentation once more when you run them yourself.
OpenAI embeddings
# from openai import OpenAI
#
# client = OpenAI()
#
# response = client.embeddings.create(
# model="text-embedding-3-small",
# input=["결제가 안 됐어요", "카드 승인이 거절됐습니다"], # "my payment didn't go through", "the card approval was declined"
# dimensions=256, # get only the first 256 slots instead of 1536 (Matryoshka)
# )
# vectors = [item.embedding for item in response.data]OpenAI vectors come normalized to length 1, so dot product and cosine give the same ranking. If you pass a list to input, you get one vector back for each text.
Google Gemini embeddings
# from google import genai
# from google.genai import types
#
# client = genai.Client()
#
# def as_query(text):
# return f"task: search result | query: {text}"
#
# def as_document(title, text):
# return f"title: {title} | text: {text}"
#
# result = client.models.embed_content(
# model="gemini-embedding-2",
# contents=as_query("결제가 안 됐어요"), # "my payment didn't go through"
# config=types.EmbedContentConfig(output_dimensionality=768),
# )
# query_vector = result.embeddings[0].valuesgemini-embedding-2 tells the model the task not through a parameter but through a prefix on the text. Questions and documents get different prefixes. If you pass several texts to this model at once, you get one combined vector. If you need a vector per document, call it one at a time or use the Batch API. The text-only gemini-embedding-001 returns one vector per text when you pass a list, and you give the task with task_type.
Open models: BGE-M3 and Qwen3-Embedding
# pip install sentence-transformers
# from sentence_transformers import SentenceTransformer
#
# bge = SentenceTransformer("BAAI/bge-m3")
# doc_vectors = bge.encode(["환불은 7일 안에 요청하세요.", "오후 2시 전 주문은 당일 출고합니다."], # "Request a refund within 7 days.", "Orders before 2 pm ship the same day."
# normalize_embeddings=True)
#
# qwen = SentenceTransformer("Qwen/Qwen3-Embedding-0.6B")
# query_vectors = qwen.encode(["돈을 돌려받고 싶어요"], prompt_name="query") # "I want my money back"; instruction prefix on the question only
# doc_vectors = qwen.encode(["환불은 7일 안에 요청하세요."]) # "Request a refund within 7 days."
# print(qwen.similarity(query_vectors, doc_vectors))Open models run on your own computer or server, so your data does not leave. For Qwen3-Embedding, putting the prefix only on the question and not on the documents is the way the model's documentation recommends. You must use the one model you chose for both indexing and questions. With a different model the vector spaces differ and the vectors cannot be compared.
Reranking
# import cohere
#
# co = cohere.ClientV2()
# response = co.rerank(
# model="rerank-v5.0-fast",
# query="돈을 돌려받고 싶어요", # "I want my money back"
# documents=["환불은 7일 안에 요청하세요.", "오후 2시 전 주문은 당일 출고합니다."], # "Request a refund within 7 days.", "Orders before 2 pm ship the same day."
# top_n=1,
# )
# for r in response.results:
# print(r.index, r.relevance_score)
#
# # with an open model
# from sentence_transformers import CrossEncoder
#
# reranker = CrossEncoder("BAAI/bge-reranker-v2-m3")
# ranked = reranker.rank("돈을 돌려받고 싶어요", # "I want my money back"
# ["환불은 7일 안에 요청하세요.", "오후 2시 전 주문은 당일 출고합니다."], # "Request a refund within 7 days.", "Orders before 2 pm ship the same day."
# top_k=1)Use a reranker only on the candidates that vector search fetched. If you run it on the whole document set, you take on the full slowness of a cross-encoder.
Ship It
This lesson produces two deliverables.
An embedding-selection advice prompt — a prompt template that asks about the data type, scale, query style, response time, and operating environment, then recommends the model, dimensions, chunking, storage, and reranking with reasons, and also tells you what to measure to confirm.
An embedding patterns skill — a decision framework covering when to use embeddings and when not to, chunking, similarity, reducing storage, reranking, common mistakes, and the order to fix them in.
The Python code (code/embeddings.py) is a self-contained practice tool. If you replace TfidfEmbedder.embed with a call to a real embedding API, the search engine and the evaluation (hit@1, recall@3, MRR) keep working without any changes.
XenLook note You can unfold the two deliverables in Korean under "Deliverable…
You can unfold the two deliverables in Korean under "Deliverables" further down this page. Just copy them and paste them into an AI chat window or a coding agent.
Exercises
- Build a similarity comparer. For the same question, rank by cosine, dot product, and Euclidean distance and compare. Do it once with normalized vectors and once with unnormalized vectors, and write down when the rankings agree and when they split. Make one more document that differs only in length, like
payment x3in STEP 3. - Grow the chunk-size experiment. Put in a few documents you know (a company notice, a product manual), write 30 or more evaluation questions, and then change the chunk size and overlap while measuring hit@1 and MRR. See whether the conclusion matches the one you got with 8 questions.
- Imitate Matryoshka further. Compare alphabetical truncation and SVD truncation as in STEP 6, but raise the number of slots one at a time from 1 to 17 and plot MRR as a graph. Find where it reaches the full score.
- Change the number of candidates for the binary codes. In STEP 7, change the number of candidates to rescore to 3, 6, 10, and 15 and measure the overlap ratio. Decide where to stop between the cost of adding candidates (the number of real-valued vectors to rescore) and quality.
- Try to find "돈을 돌려받고 싶어요" ("I want my money back"). Add a hybrid score that mixes the space-separated word score and the two-character piece score, or a synonym list (돌려받다 "get back" → 환불 "refund"). Then make 10 more questions with the same meaning in different words and measure how far your hand-made rules hold up. It shows in numbers why a trained embedding model is needed.
Key Terms
| Term | What people say | What it actually means |
|---|---|---|
| Embedding | "Text as numbers" | A real-valued vector that carries the meaning of a text. Texts with similar meaning sit close together in vector space |
| Cosine similarity | "How similar is it" | The cosine of the angle between two vectors. It ignores length and looks only at direction. Between -1 and 1 |
| Dot product | "Multiply and add" | The sum of the slot-by-slot products. For unit vectors it equals the cosine |
| Normalization | "Evening out the length" | Dividing a vector by its length to make it length 1. Once normalized, cosine, dot product, and distance give the same ranking |
| HNSW | "Fast vector search" | An algorithm that finds nearby neighbors approximately with a multi-layer graph. It does not compare against every vector |
| Chunk | "Splitting documents" | A unit that a document is cut into at a size good for making vectors. Size and overlap are decided by measuring on your own data |
| Bi-encoder | "Embedding model" | A model that makes vectors for the question and the document separately and compares them. Fast, and document vectors can be made ahead of time |
| Cross-encoder | "Reranker" | A model that takes the question and the document together and outputs a relevance score. Slow but accurate, so it is used to rerank candidates |
| Matryoshka embedding | "A vector you can shrink" | A vector trained so that the first N slots alone are usable. It works only on models trained that way |
| Binary quantization | "1-bit vector" | Keeps only the sign of each slot, cutting storage by 32 times. Pick candidates, then rescore with the real-valued vectors |
| MTEB | "The embedding leaderboard" | A large-scale text embedding benchmark. The 2022 paper measured 33 models on 8 tasks, 58 datasets, and 112 languages. Its successor, MMTEB, expanded to more than 500 tasks and more than 250 languages |
| Vocabulary mismatch | "Same meaning, different words" | The problem where the same meaning is written in different words so keyword search can't find it |
| hit@1 | "First-place hit rate" | The share of questions where the correct answer came out first (a term added by the XenLook course) |
| recall@k | "Is it in the top k" | The share of questions where the correct answer is in the top k (a term added by the XenLook course) |
| MRR | "Mean reciprocal rank" | The average of the reciprocal of the correct answer's rank (1 if first, 0.5 if second, 0 if not found) (a term added by the XenLook course) |
| Rescoring | "Re-scoring" | Re-scoring with an accurate method only the candidates picked by a fast, rough method (a term added by the XenLook course) |
Further Reading
- Mikolov et al., 2013 — "Efficient Estimation of Word Representations in Vector Space" — The Word2Vec paper. The starting point of word vectors and vector addition and subtraction
- Reimers & Gurevych, 2019 — "Sentence-BERT" — The paper that built sentence embeddings with contrastive learning. The basis of today's embedding models
- Kusupati et al., 2022 — "Matryoshka Representation Learning" — How to train embeddings that stay usable when you cut off the trailing slots
- Malkov & Yashunin — "Efficient and robust approximate nearest neighbor search using HNSW graphs" — The HNSW paper, used by most vector databases
- Muennighoff et al., 2022 — "MTEB: Massive Text Embedding Benchmark" — A benchmark that compares embedding models across many tasks and languages
- Enevoldsen et al., 2025 — "MMTEB: Massive Multilingual Text Embedding Benchmark" — A follow-up to MTEB that greatly widens languages and tasks
- MTEB leaderboard — Where you can see model scores by task and language. When choosing, look at the entries for your own task and language
- OpenAI embeddings guide — The
text-embedding-3models, thedimensionsparameter, usage examples - Gemini embeddings guide —
gemini-embedding-2task prefixes, output dimensions, multi-format input - Cohere Embed guide and Rerank guide — The Embed 5 and Rerank 5 models
- BGE-M3 model card — An open embedding model that produces dense, sparse, and multi-vector output in one model
- Qwen3-Embedding model card — An open embedding model that supports instruction prefixes and truncation
- Sentence Transformers documentation — A library for using open embedding models and cross-encoders in Python
This lesson is XenLook's translation and revision of AI Engineering from Scratch by Rohit Ghumare (MIT License).
Run it yourself
embeddings.py
This is the code of this lesson. Press the button and Python runs only inside this browser. Your code and results are never sent to XenLook servers.
Not run yet.
Check your understanding
When you've read it all, try these. You see the answer and the explanation as soon as you choose.
About how long (how many dimensions) are the vectors that today's text embedding models produce?
Why should you measure embedding quality with retrieval metrics instead of eyeballing similarity scores?
When is it better to run an open model yourself instead of using an API embedding?
What you take away
These are the things you build in this lesson and keep. Tap to open.
PromptEmbedding selection advice promptA prompt that listens to your use case and recommends the embedding model, dimensions, chunking, storage, and reranking with reasons, and tells you what to measure to confirm it
You are an embedding design advisor. When the user describes a use case, you recommend the whole embedding setup as concrete choices with reasons.
Before recommending, ask the following. Do not ask again about anything already answered.
- Data type: What are you embedding? (documents, code, product descriptions, chat messages, images and text, PDFs)
- Language: Which language is it? Are several languages mixed?
- Scale: How many items are there? How often do they grow or change?
- Query style: Is it finding by meaning, clustering, classification, recommendation, or finding duplicates?
- Response time: Do you need real time, interactive, or batch processing?
- Operating environment: Is it OK to call an external API, or must the data not leave your side? Do you have a GPU?
- Budget: Is there a monthly limit you can spend?
Pick each item and give the reasons.
Embedding model (candidates as of the November 2026 official documentation. Before recommending, tell the user to check that day's documentation and the entry for their language and task on the MTEB leaderboard):
- OpenAI
text-embedding-3-small(1536 dimensions) /text-embedding-3-large(3072 dimensions): API, can be shortened withdimensions, comes normalized to length 1 - Google
gemini-embedding-2(3072 dimensions by default, 128–3072): API, text, images, audio, video, and PDFs, tells the model the task through a text prefix. If you pass several inputs at once you get one combined vector, so if you need a vector per item, call it one at a time or use the Batch API - Google
gemini-embedding-001(3072 dimensions by default): API, text only, the task goes intask_type - Cohere
embed-v5.0-pro/embed-v5.0-fast(256–2048 dimensions): API, text and images, the same space, so you can index with pro and query with fast,int8andbinaryoutput - BGE-M3 (1024 dimensions, MIT): open weights, multiple languages, dense, sparse, and multi-vector, you run it yourself
- Qwen3-Embedding 0.6B / 4B / 8B (up to 1024 / 2560 / 4096 dimensions, Apache-2.0): open weights, multiple languages, instruction prefix on the query, can be shortened
Dimensions:
- The model's default dimensions: accuracy first
- Reduced dimensions (Matryoshka): only on models trained for it (OpenAI
dimensions, Geminioutput_dimensionality, Cohere output dimension, Qwen3). Storage shrinks in proportion to the dimensions. Measure how much quality falls with evaluation questions - If you cut the leading slots yourself, re-normalize to length 1
- Binary quantization: storage shrinks to one 32nd. Pick a generous set of candidates, then rescore with the real-valued vectors. Decide how many to rescore with evaluation questions
Chunking:
- Fixed length + overlap: unstructured text, logs
- Sentence level: well-written prose (articles, notices)
- Recursive (heading → paragraph → sentence): markdown, HTML, structured documents
- Semantic units: when search quality matters a great deal and you can afford to embed every sentence
- Code units (function and class boundaries): source code
- Korean: cut sentences only when a period is followed by a space (this protects numbers and web addresses). When you also use word search, use a morphological analyzer that handles particles, or character-level pieces
- Chunk size and overlap have no fixed right answer. Measure two or three candidates with evaluation questions and choose
Similarity:
- Cosine: the default. For comparing texts of different lengths
- Dot product: when the vectors are already normalized (OpenAI and others). On normalized vectors the ranking is the same as cosine
- Euclidean distance: clustering
- Avoid the dot product of unnormalized vectors, because it lifts long documents up regardless of meaning
Vector storage:
- An in-memory array + exhaustive search: prototypes, when there are few items
- FAISS: directly inside your program (exhaustive or HNSW)
- pgvector: when you already use Postgres
- Chroma: development on your own computer
- Qdrant: self-hosted, filtering by conditions
- Weaviate: self-hosted, hybrid with word search
- Pinecone: managed service
- Scale limits depend on hardware and settings, so do not state them as numbers. Tell the user to look at each product's official performance material
Reranking:
- None: when the data is small and first-stage search is enough
- Cohere
rerank-v5.0-pro/rerank-v5.0-fast: API, multiple languages BAAI/bge-reranker-v2-m3: open weights, Apache-2.0, you run it yourselfjinaai/jina-reranker-v2-base-multilingual: open weights, but it is CC-BY-NC-4.0, so commercial use is not allowed. Do not recommend it for a commercial service
Cost calculation (do not make up unit prices. Take the unit prices from that day's price list of each company from the user and plug them in, or leave them blank and show only the formula):
- Indexing cost = total number of tokens ÷ 1 million × the price per 1 million tokens
- Storage size = number of vectors × dimensions × bytes per slot (float32 4, int8 1, binary 1/8)
- Query cost = monthly number of queries × (query embedding price + reranking price)
- For open models, calculate with server (GPU) cost instead of an API price
For every recommendation, give the following:
- The reasons for the choice (tied to the conditions the user stated)
- Storage size (calculated with the formula above, in GB)
- The cost formula (the monthly amount if you received unit prices, otherwise a formula with blanks)
- The parts that make up the response time (query embedding + search + reranking). Write that the numbers must be measured directly
- What to measure to confirm: with 30 or more evaluation questions whose answers are known, measure hit@1, recall@k, and MRR, and compare two or three candidate models and two or three chunk sizes
- The three biggest risks for this use case
- The path to move to when the scale grows 10 times
What you must follow:
- Use the same model for indexing and queries. If the model changes, re-embed everything
- Never leave out the prefixes (for queries and for documents) that the model documentation requires
- Do not make up accuracy numbers or leaderboard scores you have not verified. If you do not know, write "must be measured directly"
SkillEmbedding patternsA decision framework for using embeddings, vector search, and similarity in a real service — when to use them, chunking, similarity, reducing storage, reranking, common mistakes, and the order to fix them in
Every embedding task follows this contract.
text -> embed(text) -> vector (a list of real numbers)
similarity(vector_a, vector_b) -> score (a real number)There are two big decisions: which embedding model to use, and what to measure the results with. The rest is plumbing.
When to use embeddings
- Finding by meaning in documents (matching by meaning, not by words)
- Grouping similar things (customer inquiries, product reviews, bug reports)
- Classifying by nearest neighbors (labeling a new item by how similar it is to labeled examples)
- Recommendation (finding items similar to what the user liked)
- Finding duplicates (finding nearly identical texts. Set the threshold with your own data)
When not to use embeddings
- When looking for exact words, codes, or numbers (use full-text search, or use it alongside)
- Queries with clear conditions (SQL, filters)
- Very small data that is faster to classify by hand
- When explaining why a result came out matters more than accuracy (embeddings are hard to look inside)
Choosing a model
Choose by your conditions. These are candidates as of the November 2026 official documentation. Before choosing, check the entry for your language and task on the MTEB leaderboard, and that day's price list.
- API, text-focused: OpenAI
text-embedding-3-small(1536 dimensions) or-large(3072 dimensions), Googlegemini-embedding-001 - API, text and images/PDFs in one space: Google
gemini-embedding-2, Cohereembed-v5.0-pro/-fast - Data must not leave your side: run BGE-M3 (MIT) or Qwen3-Embedding (Apache-2.0) yourself
- Multiple languages: all the models above support multiple languages. Check Korean performance by measuring with your own evaluation questions
Rule: do not mix different embedding models between indexing and queries. With different models the vector spaces differ and the vectors cannot be compared.
Rule: attach the prefixes exactly as the model documentation specifies. E5 uses query: /passage: , Nomic uses search_query: /search_document: , Qwen3-Embedding puts Instruct: ...\nQuery: on the query, and gemini-embedding-2 puts task: search result | query: ... on the query and title: ... | text: ... on the document.
Caution: if you pass several inputs to gemini-embedding-2 at once, you get one combined vector. If you need a vector per item, call it one at a time or use the Batch API.
Chunking rules
- Chunk size and overlap have no fixed right answer. Measure two or three candidates with evaluation questions and choose
- If you can, do not cut in the middle of a sentence
- Store metadata with every chunk (source file, section heading, position)
- For structured documents (markdown, HTML), cut at heading boundaries first
- For Korean, cut sentences only when a period is followed by a space. This keeps
99.95%,1.3, and web addresses from being broken apart - If you also use word search, handle the particles (a morphological analyzer or character-level pieces). Make "환불은" and "환불을" (both "refund" plus a particle) point to the same thing
- Search with questions whose answers you know, and check that the correct chunk comes out
Choosing similarity
- Cosine similarity: the default. For comparing texts of different lengths
- Dot product: when the vectors are already normalized to length 1 (OpenAI models are). A little faster
- Euclidean distance: clustering, when position in the space matters
If you normalized the vectors, all three give the same ranking. The choice matters only with unnormalized vectors, and then the dot product lifts long documents up regardless of meaning.
Reducing storage
You can stack three techniques.
- Reducing dimensions (Matryoshka): receive 1536 dimensions as 256 and storage is one sixth. Works only on models trained for it. If you cut yourself, re-normalize
- float16 / int8: from 4 bytes per slot to 2 bytes / 1 byte. Cohere Embed 5 can give you
int8directly - Binary quantization: 1 bit per slot, storage one 32nd. Pick candidates by Hamming distance, then rescore with the real-valued vectors
How much quality is preserved differs by model and data. Decide by measuring before and after with the same evaluation questions. When you pick with binary codes and then rescore, remember that rescoring saves only what is inside the candidate set, and decide the number of candidates by measuring.
Reranking after retrieval
A two-stage structure that raises accuracy.
- A bi-encoder fetches a generous set of candidates (fast, uses pre-made vectors)
- A cross-encoder reranks only the candidates (slow, runs the model on every question-document pair)
Use it when accuracy matters more than response time. Confirm how much it helps by measuring with evaluation questions. Reranker candidates: Cohere rerank-v5.0-pro/-fast (API), BAAI/bge-reranker-v2-m3 (Apache-2.0). jinaai/jina-reranker-v2-base-multilingual is CC-BY-NC-4.0, so it cannot be used in a commercial service.
Common mistakes
- Using different embedding models for indexing and queries
- Leaving out the query and document prefixes that the model documentation specifies
- Embedding whole documents without chunking (it becomes the average of everything)
- Using cosine without checking whether the vectors are normalized (most models give them normalized, but check)
- Ignoring chunk overlap (a sentence cut at a boundary loses its context)
- Storing only the vectors and throwing away the original text (you need text to show after finding)
- Changing the model and not re-embedding (old vectors cannot be compared)
- Treating the size of a similarity score (for example, 0.7 or above means related) as a threshold regardless of the model. The meaning of a score differs by model
- Looking at a few results by eye and ending with "looks fine." Leave numbers behind with evaluation questions
The order to fix bad search results
- Check that the query vector is not zero (an empty text or whitespace gives a zero vector or a stray vector)
- Directly compute the similarity of a document you know is the answer
- Check that you attached the model documentation's prefixes correctly
- Rewrite the query in the document's words and see whether the result changes (to tell whether it is a vocabulary mismatch)
- Open the chunk boundaries and check that the needed content was not split across two chunks
- Compare the top k by cosine, dot product, and distance to find a normalization problem
- Feed one sentence of a document in as the query as it is, and check that it comes out first (whether the pipeline itself works)
Starting values and values to decide by measuring
- Chunk size and overlap: pick two or three candidates and measure with evaluation questions
- Number to fetch: a few when using the results directly, more generous when reranking. Decide by recall@k before and after reranking
- Similarity threshold: do not use a fixed value. If you use one, look at the score distribution of correct and incorrect answers in your own evaluation questions and set it separately for each model
- Number of texts per request: batch within each API documentation's per-call limit (for
gemini-embedding-2, see the caution above) - Re-embedding: when the model changes or the documents change a lot
- Evaluation questions: 30 or more questions whose answers are known. Record hit@1, recall@k, and MRR, and measure again whenever you change something
This course is XenLook's English translation and revision of Rohit Ghumare's AI Engineering from Scratch (MIT License), based on the Korean edition we corrected against the original. Source commit: 8fec9cc19e.
Full MIT License text
MIT License
Copyright (c) 2026 Rohit Ghumare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.Source lesson: phases/11-llm-engineering/04-embeddings