Sub topic 5
Generating embeddings with a pretrained model
This chapter assumes you know basic Python, can read NumPy arrays, and understand dot products and vector length. You should also know roughly what an embedding is and how cosine similarity compares two vectors. Here you will turn real text into vectors with a pretrained model. You will also learn what happens inside the encode call and which settings change the output.
Why use a pretrained model
Training an embedding model takes large datasets and a lot of compute. For most projects you download a model that someone else trained and call it as a function. Text goes in. A fixed-size array of floats comes out.
The sentence-transformers library wraps this workflow. It downloads a model from the Hugging Face Hub on first use and caches it locally. After that it runs the model on CPU or GPU.
pip install sentence-transformers numpyWhat `encode` does
The model never sees raw characters. Several steps run between your string and the vector:
- A tokenizer splits the text into subword tokens and maps each token to an integer id.
- A transformer encoder turns the token ids into one vector per token.
- A pooling step combines those token vectors into one vector for the whole text. Mean pooling is the most common choice.
- Optionally, the result is scaled to unit length (normalization).
Pooling is why texts of any length produce vectors of the same size. A three-word query and a two-paragraph passage both come out with the same number of dimensions.
Your first embeddings
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)all-MiniLM-L6-v2 is a small general-purpose English model. It maps each input to 384 floats. The result is a NumPy array with one row per input.
Because normalize_embeddings=True gives every row unit length, a dot product equals cosine similarity. A single matrix product then compares every pair:
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)
sims = emb @ emb.T
np.set_printoptions(precision=2, suppress=True)
print(sims)The diagonal is 1.0, because each text matches itself. The password and account-recovery sentences share almost no words, yet their score is clearly higher than the score of either one against the weather sentence. That gap is what makes semantic search work.
Inspecting a model before you rely on it
Check two properties of any model before you build on it: its output dimension and its input limit.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
print(model.get_sentence_embedding_dimension()) # 384
print(model.max_seq_length) # 256max_seq_length is measured in tokens, not words. Anything past the limit is cut off silently. No error appears, and the extra text does not influence the vector at all. This is the main reason long documents need chunking, which a later chapter covers.
To see how close a text is to the limit, count its tokens with the model's own tokenizer:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
def token_count(text):
return len(model.tokenizer(text)["input_ids"])
short = "Reset your password in settings."
long_text = "word " * 1000
for t in (short, long_text):
n = token_count(t)
status = "truncated" if n > model.max_seq_length else "fits"
print(n, status)The count includes special tokens that the model adds at the start and end, so it is the number the limit applies to. The 1,000-word string is well over 256 tokens, so only its beginning contributes to the embedding.
Encoding many texts
Calling encode once on a list is much faster than calling it in a loop. The library sorts texts by length, groups them into batches, and runs each batch through the model together. Padding is then kept to a minimum.
Embedding a corpus is also the slow, one-time part of building a search system, so save the result instead of recomputing it:
import numpy as np
from sentence_transformers import SentenceTransformer
MODEL_NAME = "all-MiniLM-L6-v2"
def embed_corpus(texts, path, batch_size=64):
model = SentenceTransformer(MODEL_NAME)
emb = model.encode(
texts,
batch_size=batch_size,
normalize_embeddings=True,
show_progress_bar=True,
)
np.save(path, emb.astype("float32"))
return emb
docs = [
"Steps to recover access to your account",
"Our office is open from 9 to 5 on weekdays",
"Change your login credentials in the security settings",
"The cafeteria serves lunch at noon",
]
emb = embed_corpus(docs, "doc_embeddings.npy")
loaded = np.load("doc_embeddings.npy")
print(loaded.shape, loaded.dtype) # (4, 384) float32Larger batches are faster up to a point, then run out of memory. On a GPU, start at 64 and raise the batch size until memory runs short. On a CPU the batch size matters less.
Storage cost
Storage is straightforward arithmetic: documents × dimensions × bytes per number. With 32-bit floats, a million 384-dimensional vectors take 1,000,000 × 384 × 4 bytes, about 1.5 GB. A model with 1,536 dimensions would need four times that. This cost is one reason dimension count matters when you choose a model.
Settings that change the output
| Setting | Effect | Typical choice |
|---|---|---|
| `normalize_embeddings` | Scales each vector to length 1 | `True` for cosine or dot-product search |
| `batch_size` | Speed and memory use. Does not change the vectors meaningfully | 32 to 128 |
| `device` | CPU, `"cuda"`, or `"mps"` | GPU when available |
| `max_seq_length` | Truncation point in tokens | Model default, or lower to save time |
| `convert_to_numpy` | Return NumPy arrays instead of tensors | Default `True` |
You can lower max_seq_length after loading (model.max_seq_length = 128). Raising it above what the model was trained for is usually unwise. The model's position information was learned up to a fixed length, and some models cannot accept longer input at all.
Choosing a model
Most of the decision comes down to a few questions:
- Language. An English-only model performs poorly on other languages. Choose a multilingual model if your data is mixed.
- Dimension. Higher dimensions can capture more detail but cost more to store and search.
- Input limit. Some models accept 512 or more tokens, others only 256 or fewer. Match it to your chunk size.
- Speed. Smaller models such as 6-layer ones run well on a CPU. Larger models need a GPU for large corpora.
- Task fit. Some models are trained for retrieval and others for general similarity. Retrieval benchmarks such as MTEB can help you compare candidates, but test on your own data too.
Rules to follow in practice
- Embed queries and documents with the same model. Vectors from different models live in different spaces, and comparing them is meaningless even when the dimensions match.
- Record the model name and version next to the saved vectors. If you change models, re-embed the whole corpus.
- Keep the same normalization setting at index time and query time.
- The same text always produces the same vector from the same model on the same hardware. Tiny floating-point differences can appear across devices, so do not compare vectors for exact equality. Use
np.allclose.
Exercise
You plan to embed 200,000 passages with a model that outputs 768-dimensional vectors, stored as float32. Roughly how much memory do the vectors need? Also, your passages average 400 tokens and the model has a 256-token limit. What happens to the extra tokens, and what would you do about it?
Show answer
Memory is 200,000 × 768 × 4 bytes = 614,400,000 bytes, about 614 MB. The tokens past 256 are silently dropped, so each embedding represents only the first part of its passage and later content cannot be found. Split the passages into chunks under the limit (for example with overlapping windows) and embed each chunk, or choose a model with a longer input limit.
Exercise
You embedded a corpus last month with one model and now want to embed new queries with a different model that also outputs 384 dimensions. Why is this a bug even though the array shapes match, and what is the fix?
Show answer
Each model learns its own vector space, so coordinates mean different things in different models. Cosine scores between vectors from two models are essentially random. The fix is to use one model for both queries and documents, which means re-embedding the whole corpus with the new model.