Sub topic 1
From data to vectors: what embeddings are
Prerequisites
This chapter assumes you have the following:
- Basic Python or SQL. The code examples use NumPy.
- Vectors and dot products at an introductory level. You should know that a vector is an ordered list of numbers and that a dot product multiplies two vectors element by element and sums the results.
- A general idea of what machine learning embeddings are. You do not need to have trained a model.
- Familiarity with how a database index speeds up queries, for example a B-tree on a column.
What an embedding is
An embedding is a list of floating-point numbers, a vector, that represents a piece of data such as a sentence, an image, an audio clip, or a product. A trained model produces it. The model is trained so that items with similar meaning end up close together in the vector space, and items with different meaning end up far apart.
A vector database stores these vectors and answers one main question: given a query vector, which stored vectors are closest to it? Everything later in this tutorial builds on that question. This chapter covers how the vectors come to exist and what properties they have.
Here is a small, made-up example. Suppose a model maps words to 3 numbers:
| Item | Vector |
|---|---|
| cat | [0.9, 0.1, 0.0] |
| kitten | [0.85, 0.2, 0.05] |
| car | [0.0, 0.1, 0.95] |
"cat" and "kitten" have nearly the same numbers, so they are close. "car" is far from both. Real models use hundreds or thousands of dimensions, and no single dimension has a clean human meaning like "is an animal". The meaning is spread across all of the dimensions together.
How a model produces embeddings
Most text embedding models are neural networks, usually transformers. The pipeline looks like this:
- The input is split into tokens, which are small pieces of text such as words or word fragments.
- The network turns each token into a context-aware vector.
- A pooling step, often a mean over the token vectors, combines them into one vector for the whole input.
- Many models then scale the result to unit length, which means a vector length (norm) of 1.
The training objective is what gives the space its structure. A common method is contrastive learning. The model sees pairs that should match, such as a question and its answer, or two captions of one image. It also sees pairs that should not match. It is rewarded when matching pairs land close together and non-matching pairs land far apart. After enough training, distance in the space tracks the kind of similarity the training pairs encoded.
This has a practical consequence: "similar" means whatever the model was trained to treat as similar. A model trained on question-and-answer pairs finds answers to questions. A model trained to match paraphrases finds near-duplicates. Pick a model whose training matches your task.
Dimensions, size, and cost
Each embedding model has a fixed output size called its dimensionality. Typical values range from 384 to 3072. Some models let you truncate the vector to a smaller size with limited quality loss. Models that support this are usually described as trained with Matryoshka representation learning.
Dimensionality directly sets your storage and compute cost. A float32 value takes 4 bytes, so the raw size of a vector is dimensions × 4 bytes.
| Dimensions | Bytes per vector | 1 million vectors | 100 million vectors |
|---|---|---|---|
| 384 | 1,536 | about 1.5 GB | about 154 GB |
| 768 | 3,072 | about 3.1 GB | about 307 GB |
| 1536 | 6,144 | about 6.1 GB | about 614 GB |
These figures count only the raw vectors. Index structures, metadata, and replicas add to them. This is why later chapters spend time on compression and on index memory use.
A runnable example
The code below builds a toy embedding by hashing words into a fixed-size vector. This is not a learned model, and it captures only word overlap, not meaning. It is useful here because it runs with only NumPy and shows the mechanics: text goes in, a fixed-length unit vector comes out, and similar texts get higher scores.
import hashlib
import numpy as np
DIM = 64
def toy_embed(text: str) -> np.ndarray:
"""Hash each word into a bucket and count it. Not a learned model."""
vec = np.zeros(DIM, dtype="float32")
for word in text.lower().split():
digest = hashlib.md5(word.encode("utf-8")).digest()
bucket = int.from_bytes(digest[:4], "little") % DIM
vec[bucket] += 1.0
norm = np.linalg.norm(vec)
return vec / norm if norm > 0 else vec
docs = [
"the cat sat on the mat",
"a cat sat on a rug",
"stock prices fell sharply today",
]
query = "cat on a mat"
doc_vecs = np.stack([toy_embed(d) for d in docs])
q_vec = toy_embed(query)
print("shape:", doc_vecs.shape)
print("norms:", np.linalg.norm(doc_vecs, axis=1))
scores = doc_vecs @ q_vec
for doc, score in sorted(zip(docs, scores), key=lambda p: -p[1]):
print(f"{score:.3f} {doc}")The output shows three things. The matrix has shape (3, 64), one row per document. Every norm is 1.0 because of the normalization step. The two cat sentences score higher than the finance sentence, because they share words with the query.
A real model replaces toy_embed. With a real model, "feline resting on a carpet" would also score high against the query, because the model learned that those phrases mean similar things. The hash version cannot do that. This gap between word overlap and meaning is the reason embeddings exist.
What embeddings can and cannot do
Embeddings work for any data type that a model can process. Common cases:
- Text: sentences, paragraphs, documents, code.
- Images: photos, product pictures, diagrams.
- Audio: speech, music, sound effects.
- Multimodal: text and images in one shared space, so a text query can retrieve images.
- Structured entities: users, products, or items, using embeddings learned from behavior such as clicks or purchases.
Some properties and limits matter in practice:
- Embeddings from different models are not compatible. Dimension 1 in one model has no relation to dimension 1 in another. You cannot compare a vector from model A with a vector from model B, even if both have 768 dimensions. If you switch models, you must re-embed all your data.
- Version changes count as model changes. A new version of the same model usually produces a different space. Store the model name and version alongside each vector.
- Queries and documents must use the same model. Some models use special prefixes or separate modes for queries and documents. Read the model card.
- Long inputs get compressed or cut. Models have a maximum input length. Text beyond it is truncated, and long inputs can blur into one vector that represents no part of the text well. This is why documents are usually split into chunks before embedding.
- Embeddings are lossy. They capture general meaning but can lose exact details such as a specific number, an ID, or a rare name. Searching for "error code 4031" may return documents about errors in general. Hybrid search, covered later, addresses this.
- Domain shift reduces quality. A general-purpose model may handle medical, legal, or code content poorly. Evaluate on your own data.
- Vectors can leak information. Embeddings can sometimes be inverted to recover approximate source text. Treat them with the same access controls as the source data.
Common mistakes
- Mixing models in one index. The search runs without error and returns meaningless results. Check dimensions at insert time and store a model identifier.
- Forgetting to normalize. If you rely on dot product as a stand-in for cosine similarity, unnormalized vectors with different lengths skew the ranking.
- Embedding whole documents. A 20-page document reduced to one vector is a poor match for most specific questions. Chunk the text first.
- Assuming a higher dimension is always better. More dimensions cost more memory and time. Quality gains often level off. Benchmark a smaller model or a truncated vector on your data.
- Treating similarity scores as probabilities. A score of 0.8 from one model may mean a strong match, and from another model may mean a weak one. Scores are only comparable within one model and one task.
Checking your understanding
Exercise
You embed 5 million product descriptions with a 768-dimension model that stores values as float32. About how much memory do the raw vectors need? Then, six months later, the provider releases a new version of the model with the same 768 dimensions. Can you embed new products with the new version and add them to the same index?
Show answer
Each vector takes 768 × 4 = 3,072 bytes, so 5 million vectors take about 15.4 GB (5,000,000 × 3,072 bytes = 15.36 GB). No, you should not mix them. Even with the same dimension count, the new version produces a different vector space, so distances between old and new vectors are meaningless. You need to re-embed all products with the new version, or keep the old model for queries against the old index.
Exercise
In the toy example, why does "feline resting on a carpet" score near zero against the query "cat on a mat" with the hash-based embedding, and what property of a learned model fixes this?
Show answer
The hash embedding only counts shared words, and these two texts share almost none (only "a" and "on" can overlap by chance, and "on" is absent), so their vectors have little overlap. A learned model is trained with contrastive pairs so that texts with similar meaning map to nearby vectors, even when they use different words.