Sub topic 5
Generating embeddings with a pretrained model
This chapter assumes you know basic Python, what a vector and a dot product are, and roughly what a neural network does. You do not need to train anything. You will load a pretrained embedding model, encode sentences, and check that the output behaves as expected.
The working model
A pretrained embedding model is a function from text to a fixed-size vector. Every input, whether it is a word, a sentence, or a short paragraph, produces a vector with the same number of dimensions. The model's weights are fixed, so the same text always gives the same vector. Texts with similar meaning land close together.
The sentence-transformers library wraps this in a few lines. The model all-MiniLM-L6-v2 is small, runs on a CPU, and outputs 384 dimensions.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
sentences = [
"How do I reset my password?",
"Steps to recover access to your account",
"The weather is sunny today",
]
embeddings = model.encode(sentences, normalize_embeddings=True)
print(embeddings.shape) # (3, 384)The first run downloads the model weights and caches them. The result is a NumPy array with one row per sentence.
What happens inside encode
- The tokenizer splits the text into tokens and truncates it if it is too long.
- The encoder produces one vector per token.
- Pooling averages those token vectors into one vector for the whole text.
- Normalization, if you ask for it, scales the vector to length 1.
Check the result
Because the vectors are normalized, a dot product equals cosine similarity. Compare the sentences from above.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
sentences = [
"How do I reset my password?",
"Steps to recover access to your account",
"The weather is sunny today",
]
emb = model.encode(sentences, normalize_embeddings=True)
print(np.linalg.norm(emb, axis=1)) # each value is about 1.0
print(round(float(emb[0] @ emb[1]), 2)) # relatively high
print(round(float(emb[0] @ emb[2]), 2)) # relatively lowThe first pair shares almost no words, yet it should score clearly higher than the second pair. Exact numbers depend on the model version, so compare the order of the scores, not the values.
Practical settings
| Setting | What it does | Typical advice |
|---|---|---|
| `normalize_embeddings` | Scales each vector to length 1 | Turn on, so dot product equals cosine |
| `batch_size` | Texts processed at once | Raise it on a GPU, lower it if memory runs out |
| `show_progress_bar` | Prints progress | Useful for large corpora |
| `model.max_seq_length` | Token limit before truncation | Check it for your model |
Pass a list instead of looping over single strings. Batching is much faster, especially on a GPU.
Common errors
- Silent truncation.
all-MiniLM-L6-v2keeps only the first 256 tokens by default. Text beyond that is ignored without a warning, so long documents need chunking (covered in a later chapter). - Mixing models. Vectors from different models are not comparable, even when the dimensions match. Use one model for both queries and documents.
- Forgetting normalization. If you skip it, dot product is no longer cosine similarity, and longer vectors can win unfairly.
- Encoding one text at a time. A loop of single calls is slow. Encode a list.
- Wrong input shape.
encode("text")returns shape(384,).encode(["text"])returns(1, 384).
Exercise
You encode 1,000 documents with a model whose limit is 256 tokens. Some documents are 2,000 tokens long. The encode call raises no error. What happened to the long documents, and why is this a problem for search?
Show answer
Each was truncated to its first 256 tokens, so only that part is embedded. Content later in the document cannot be found by search, because the vector never represented it. Splitting the documents into chunks that fit the limit fixes this.