Lab: Embed a Corpus in Batches
Embed a small help-centre corpus in checked batches, store the vectors with their chunk IDs and a manifest naming the exact model revision, reuse unchanged vectors, refuse to mix models, and run the same batches through a hosted embeddings API.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the corpus
- Step 2: Pin the model and its prefixes
- Step 3: A batching function you can reuse
- Step 4: Embed, store and record the manifest
- Step 5: Search, but only with the matching model
- Step 6: Change a chunk, then change the model
- Step 7: The same batches through a hosted API
- Troubleshooting
- Check your understanding
- Apply it (stretch)
- Review prompt
Lessons of Embeddings
- From Text to Vectors, and What Vectors Are For Concept · 15 min
- Similarity by Hand and in NumPy Worked example · 20 min
- Lab: Embed a Corpus in Batches Lab · 25 min
- Comparing Two Embedding Models Lab · 25 min
- Check: Similarity and Model Choice Knowledge check · 6 questions
What you will learn
- Generate embeddings for a corpus in batches and store them with their source IDs and model version.
Prerequisites: Data Handling
01. Goal and setup
Embedding one sentence is a function call. Embedding a corpus that a search service relies on for months is a small data pipeline, and it must answer questions the function call never asks:
- Which chunk does row 7 of the vector file belong to?
- Which model, and which exact version of it, produced these vectors?
- One article changed. Do we pay to re-embed everything?
- Someone switched the model in the config. What stops queries being compared with vectors from the old one?
You will build that pipeline for a 14-chunk help centre. It writes an index/ folder with vectors.npy (one float32 row per chunk), chunks.parquet (chunk ID, document ID, text, text hash and token count, in the same row order) and manifest.json (model, pinned revision, prefixes, dimension, library version).
You need Python 3.12 or later; the outputs come from sentence-transformers 6.3, pandas 3.1 and pyarrow 26. Only the hosted step at the end needs an API key.
mkdir embed-lab && cd embed-lab
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "sentence-transformers>=6,<7" pandas pyarrow openaiembed-lab/
make_corpus.py writes corpus.jsonl
config.py the models you allow, pinned
check_model.py a quick look at the loaded model
batching.py provider-neutral batch loop
embed_corpus.py corpus.jsonl -> index/
search.py queries against index/
hosted.py the same batches through an API
corpus.jsonl
index/
vectors.npy
chunks.parquet
manifest.json02. Step 1: Create the corpus
Real chunks come from the chunking step of a RAG pipeline. Here a script writes 14 short chunks from five articles to JSON Lines, one record per line, each with a stable chunk_id built from the document ID and the chunk number.
import json
# (doc_id, chunk number, text): a tiny help centre split into chunks
CHUNKS = [
('login', 0, 'Reset your password from the sign-in page with "Forgot password".'),
('login', 1, 'Accounts lock for 15 minutes after five failed sign-in attempts.'),
('login', 2, 'Two-factor codes expire after 30 seconds; check your phone clock.'),
('billing', 0, 'Invoices are emailed on the first working day of each month.'),
('billing', 1, 'Edit your billing profile to change the VAT number on invoices.'),
('billing', 2, 'Refunds for annual plans are prorated and take 5 to 10 days.'),
('export', 0, 'Export any report to CSV or Parquet from the Reports menu.'),
('export', 1, 'Scheduled exports run nightly at 02:00 UTC and are kept 30 days.'),
('api', 0, 'Create API keys under Settings > API; each key is shown only once.'),
('api', 1, 'Each key may send 100 requests per minute; extra calls get 429.'),
('api', 2, 'Rotate a key by creating a new one, then deleting the old key.'),
('privacy', 0, 'Delete your account under Settings > Privacy.'),
('privacy', 1, 'Deleted accounts are erased after 30 days and cannot be restored.'),
('privacy', 2, 'Customer data is stored in the EU (Frankfurt) region.'),
]
with open('corpus.jsonl', 'w', encoding='utf-8') as f:
for doc_id, n, text in CHUNKS:
record = {'chunk_id': f'{doc_id}-{n}', 'doc_id': doc_id, 'text': text}
print(json.dumps(record, ensure_ascii=False), file=f)
print(f'wrote {len(CHUNKS)} chunks from {len({c[0] for c in CHUNKS})} documents')wrote 14 chunks from 5 documents03. Step 2: Pin the model and its prefixes
A model name such as sentence-transformers/all-MiniLM-L6-v2 points at a Git repository on the Hugging Face Hub, and its main branch can change; this one was last updated in June 2026. Passing revision= with a commit hash loads exactly the same weights, tokenizer and settings on every machine, for as long as that repository and commit stay available. An owner can delete a repository or restrict access to it, so keep a copy of the model files if you must reproduce vectors years later. Copy the hash from the model page under Files and versions, or from the folder name under ~/.cache/huggingface/hub/models--…/snapshots/.
config.py lists every model the project may use, each with its revision and the prefixes its model card asks for. Some models are trained asymmetrically: questions and passages get different prefixes, because a short question and the passage that answers it look different. multilingual-e5-small expects query: before questions and passage: before documents, and its card warns that quality drops without them. encode_query and encode_document add a prefix only if the model's configuration defines one, and this model's configuration does not, so you pass them as prompts.
import os
from sentence_transformers import SentenceTransformer
# Models you may index with: a pinned revision and the prefixes the model card asks for.
MODELS = {
'sentence-transformers/all-MiniLM-L6-v2': {
'revision': '1110a243fdf4706b3f48f1d95db1a4f5529b4d41',
'prompts': {'query': '', 'document': ''},
},
'intfloat/multilingual-e5-small': {
'revision': '614241f622f53c4eeff9890bdc4f31cfecc418b3',
'prompts': {'query': 'query: ', 'document': 'passage: '},
},
}
MODEL_NAME = os.environ.get('EMBED_MODEL', 'sentence-transformers/all-MiniLM-L6-v2')
def load_model() -> tuple[SentenceTransformer, dict]:
spec = MODELS[MODEL_NAME] # KeyError: add the model and its revision first
model = SentenceTransformer(
MODEL_NAME, revision=spec['revision'], prompts=spec['prompts']
)
return model, specfrom config import MODEL_NAME, load_model
model, spec = load_model()
vectors = model.encode_document(['hello', 'a slightly longer text'])
print(MODEL_NAME, spec['revision'][:7])
print('dimension', vectors.shape[1], '| max tokens', model.max_seq_length)sentence-transformers/all-MiniLM-L6-v2 1110a24
dimension 384 | max tokens 25604. Step 3: A batching function you can reuse
Sending texts in batches cuts per-call overhead, and with a hosted API it keeps you well inside request limits and rate limits. embed_in_batches knows nothing about any model: you pass it a function that embeds one batch. It checks every batch before keeping it (one vector per input, no nan or infinite values), because a silent mismatch here would shift every later vector onto the wrong chunk.
import numpy as np
def embed_in_batches(texts: list[str], embed_batch, batch_size: int) -> np.ndarray:
"""Call embed_batch on slices of texts and check every result before keeping it."""
parts = []
for start in range(0, len(texts), batch_size):
batch = texts[start : start + batch_size]
vectors = np.asarray(embed_batch(batch), dtype=np.float32)
if vectors.shape[0] != len(batch) or not np.isfinite(vectors).all():
raise ValueError(f'batch at row {start} returned {vectors.shape}')
parts.append(vectors)
print(f' batch {start // batch_size + 1}: size {len(batch)}')
return np.vstack(parts)For a local model alone, model.encode(texts, batch_size=64) already batches internally. The explicit loop earns its place when the same pipeline must also drive an API (step 7), report progress, or be extended to save each batch so a crashed run can resume.
05. Step 4: Embed, store and record the manifest
embed_corpus.py comes in three parts; put them in one file. The first part fingerprints each chunk's text with SHA-256 and looks for an existing index. If that index was built with the same model, revision and prefixes, its vectors can be reused for every chunk whose text hash is unchanged. Otherwise nothing can be reused: vectors from two models live in different spaces, and a new prefix counts as a new model.
import hashlib
import json
import shutil
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import pandas as pd
import sentence_transformers
from batching import embed_in_batches
from config import MODEL_NAME, load_model
INDEX = Path('index')
BATCH_SIZE = 4 # tiny so you can see the batches; 32 to 256 is usual
def sha256(text: str) -> str:
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def previous_vectors(spec: dict) -> dict[str, np.ndarray]:
"""Vectors by text hash, if the index used this model, revision and prefixes."""
try:
manifest = json.loads((INDEX / 'manifest.json').read_text(encoding='utf-8'))
except FileNotFoundError:
return {}
built = (manifest['model'], manifest['revision'], manifest['prompts'])
if built != (MODEL_NAME, spec['revision'], spec['prompts']):
same_model = built[:2] == (MODEL_NAME, spec['revision'])
what = 'other prefixes' if same_model else built[0]
print(f'index was built with {what}: re-embedding everything')
return {}
old = pd.read_parquet(INDEX / 'chunks.parquet')
vectors = np.load(INDEX / 'vectors.npy')
return dict(zip(old['text_sha256'], vectors))The second part loads the chunks, counts tokens with the model's own tokenizer (prefix included, since the model reads it too), and warns about chunks longer than the model reads (the excess would be cut off silently). It then embeds only the chunks it cannot reuse. normalize_embeddings=True stores unit vectors whatever the model does, so search can use the plain dot product.
def main() -> None:
model, spec = load_model()
with open('corpus.jsonl', encoding='utf-8') as f:
chunks = pd.DataFrame([json.loads(line) for line in f if line.strip()])
chunks['text_sha256'] = chunks['text'].map(sha256)
prefix = spec['prompts']['document'] # encode_document adds it: count it too
token_ids = model.tokenizer([prefix + t for t in chunks['text']])['input_ids']
chunks['n_tokens'] = [len(ids) for ids in token_ids]
over = int((chunks['n_tokens'] > model.max_seq_length).sum())
print(f'{len(chunks)} chunks; longest {chunks["n_tokens"].max()} tokens; '
f'{over} over the {model.max_seq_length}-token limit')
known = previous_vectors(spec)
vectors = [known.get(h) for h in chunks['text_sha256']]
todo = [i for i, v in enumerate(vectors) if v is None]
print(f'reusing {len(chunks) - len(todo)}, embedding {len(todo)}')
if todo:
fresh = embed_in_batches(
chunks['text'].iloc[todo].tolist(),
lambda batch: model.encode_document(batch, normalize_embeddings=True),
BATCH_SIZE,
)
for i, vector in zip(todo, fresh):
vectors[i] = vectorThe third part writes the three files into index.tmp/ and swaps that folder into place only when all of them exist, so a crash while writing never leaves a vector file that disagrees with its metadata. The swap itself, deleting index/ and then renaming index.tmp/, is two steps and not atomic: a crash between them leaves no index/ at all, and re-running the script rebuilds it. A live service should instead write each build to a new folder and switch a pointer to it, such as a symbolic link. Row i of vectors.npy belongs to row i of chunks.parquet, and the manifest records everything needed to reproduce the vectors or to detect that they no longer match the configuration.
matrix = np.vstack(vectors).astype(np.float32)
tmp = Path('index.tmp') # build next to the old index, then swap
shutil.rmtree(tmp, ignore_errors=True)
tmp.mkdir()
np.save(tmp / 'vectors.npy', matrix) # row i belongs to row i of chunks.parquet
chunks.to_parquet(tmp / 'chunks.parquet', index=False)
manifest = {
'model': MODEL_NAME,
'revision': spec['revision'],
'prompts': spec['prompts'],
'library': f'sentence-transformers {sentence_transformers.__version__}',
'dimension': matrix.shape[1],
'normalized': True,
'max_seq_length': model.max_seq_length,
'count': matrix.shape[0],
'created_at': datetime.now(timezone.utc).isoformat(timespec='seconds'),
}
(tmp / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
shutil.rmtree(INDEX, ignore_errors=True)
tmp.rename(INDEX)
print(f'saved {matrix.shape[0]} x {matrix.shape[1]} vectors to {INDEX}/')
if __name__ == '__main__':
main()python make_corpus.py
python embed_corpus.py14 chunks; longest 19 tokens; 0 over the 256-token limit
reusing 0, embedding 14
batch 1: size 4
batch 2: size 4
batch 3: size 4
batch 4: size 2
saved 14 x 384 vectors to index/{
"model": "sentence-transformers/all-MiniLM-L6-v2",
"revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
"prompts": {
"query": "",
"document": ""
},
"library": "sentence-transformers 6.3.0",
"dimension": 384,
"normalized": true,
"max_seq_length": 256,
"count": 14,
"created_at": "2026-10-18T09:26:52+00:00"
}The vectors take 14 × 384 × 4 bytes, about 21 KB. A .npy file stores shape and dtype, loads in one call and can be memory-mapped, so a large file is read from disk only as needed; Parquet keeps the per-chunk metadata typed and compact. A vector column in Parquet, or a vector database (the next skill), works as well, as long as the ID, the vector and the model version always travel together.
06. Step 5: Search, but only with the matching model
Before search.py embeds a single query, it compares the manifest with the configured model, revision and prefixes and stops if they differ. It also checks that the three files agree on the number of rows. Then it uses encode_query, which applies the query prefix when the model has one.
import json
import sys
from pathlib import Path
import numpy as np
import pandas as pd
from config import MODEL_NAME, MODELS, load_model
INDEX = Path('index')
def load_index() -> tuple[pd.DataFrame, np.ndarray]:
manifest = json.loads((INDEX / 'manifest.json').read_text(encoding='utf-8'))
built = (manifest['model'], manifest['revision'], manifest['prompts'])
spec = MODELS[MODEL_NAME]
wanted = (MODEL_NAME, spec['revision'], spec['prompts'])
if built[:2] != wanted[:2]:
sys.exit(f'index was built with {built[0]}@{built[1][:7]}\n'
f'queries would use {wanted[0]}@{wanted[1][:7]}; '
'run embed_corpus.py first')
if built[2] != wanted[2]:
sys.exit(f'index was built with prefixes {built[2]}\n'
f'config.py now says {wanted[2]}; run embed_corpus.py first')
chunks = pd.read_parquet(INDEX / 'chunks.parquet')
vectors = np.load(INDEX / 'vectors.npy', mmap_mode='r')
if not len(chunks) == vectors.shape[0] == manifest['count']:
sys.exit('index files disagree; rebuild the index')
return chunks, vectors
def main() -> None:
chunks, vectors = load_index()
model, _ = load_model()
for query in sys.argv[1:]:
q = model.encode_query([query], normalize_embeddings=True)[0]
scores = vectors @ q # unit vectors, so this is cosine similarity
print(query)
for i in np.argsort(-scores)[:3]:
print(f' {scores[i]:.3f} {chunks.chunk_id[i]:<10} {chunks.text[i]}')
if __name__ == '__main__':
main()python search.py "I can't sign in" "how long until I get my money back"I can't sign in
0.595 login-0 Reset your password from the sign-in page with "Forgot password".
0.419 login-1 Accounts lock for 15 minutes after five failed sign-in attempts.
0.386 privacy-0 Delete your account under Settings > Privacy.
how long until I get my money back
0.563 billing-2 Refunds for annual plans are prorated and take 5 to 10 days.
0.296 privacy-1 Deleted accounts are erased after 30 days and cannot be restored.
0.287 login-1 Accounts lock for 15 minutes after five failed sign-in attempts.07. Step 6: Change a chunk, then change the model
Support shortens the refund time. In make_corpus.py, change the billing-2 text to 'Refunds for annual plans are prorated and take 3 to 5 days.', then rebuild and search again.
python make_corpus.py
python embed_corpus.py
python search.py "how long until I get my money back"wrote 14 chunks from 5 documents
14 chunks; longest 19 tokens; 0 over the 256-token limit
reusing 13, embedding 1
batch 1: size 1
saved 14 x 384 vectors to index/
how long until I get my money back
0.561 billing-2 Refunds for annual plans are prorated and take 3 to 5 days.
0.296 privacy-1 Deleted accounts are erased after 30 days and cannot be restored.
0.287 login-1 Accounts lock for 15 minutes after five failed sign-in attempts.Only the edited chunk was embedded; with a hosted model that is the difference between paying for one chunk and paying for the whole corpus. Now point the configuration at the multilingual model and search before rebuilding. In PowerShell, set the variable with $env:EMBED_MODEL = 'intfloat/multilingual-e5-small' instead of the prefix shown here.
export EMBED_MODEL=intfloat/multilingual-e5-small
python search.py "Tôi quên mật khẩu"index was built with sentence-transformers/all-MiniLM-L6-v2@1110a24
queries would use intfloat/multilingual-e5-small@614241f; run embed_corpus.py firstWithout that guard, the search would have run and returned confident-looking scores computed between two unrelated vector spaces. Both models produce 384 numbers, so nothing in NumPy would have complained. Rebuild, and search in English and in Vietnamese (the query means "I forgot my password"):
python embed_corpus.py
python search.py "I can't sign in" "Tôi quên mật khẩu"
unset EMBED_MODEL # PowerShell: Remove-Item Env:EMBED_MODEL14 chunks; longest 21 tokens; 0 over the 512-token limit
index was built with sentence-transformers/all-MiniLM-L6-v2: re-embedding everything
reusing 0, embedding 14
batch 1: size 4
batch 2: size 4
batch 3: size 4
batch 4: size 2
saved 14 x 384 vectors to index/
I can't sign in
0.836 login-0 Reset your password from the sign-in page with "Forgot password".
0.832 login-1 Accounts lock for 15 minutes after five failed sign-in attempts.
0.813 privacy-0 Delete your account under Settings > Privacy.
Tôi quên mật khẩu
0.830 login-0 Reset your password from the sign-in page with "Forgot password".
0.823 privacy-0 Delete your account under Settings > Privacy.
0.778 api-2 Rotate a key by creating a new one, then deleting the old key.All 14 chunks were re-embedded although no text changed, and the Vietnamese question now finds the English password article. The scores sit around 0.8, the range this model typically produces, so compare their order, not their size, with the MiniLM run. The rule behind this step: a new model or a new revision means re-embedding everything, with the query side switched at the same moment. In production you build the new index next to the old one, compare them, and then move the service over.
08. Step 7: The same batches through a hosted API
A hosted model plugs into the same embed_in_batches. The OpenAI Python SDK reads OPENAI_API_KEY from the environment, retries rate-limit and server errors twice by default, and takes up to 2,048 inputs per request (and at most 300,000 tokens across them). Read the model name from an environment variable too, for example OPENAI_EMBED_MODEL=text-embedding-3-small. Each returned item carries the index of its input, so the code sorts by it instead of trusting the order, and it adds up the tokens you are billed for.
import json
import os
import numpy as np
from openai import OpenAI
from batching import embed_in_batches
client = OpenAI() # reads OPENAI_API_KEY (and OPENAI_BASE_URL, if set)
MODEL = os.environ['OPENAI_EMBED_MODEL'] # for example text-embedding-3-small
usage = {'tokens': 0}
def embed_batch_hosted(batch: list[str]) -> list[list[float]]:
response = client.embeddings.create(model=MODEL, input=batch)
usage['tokens'] += response.usage.total_tokens
# each item carries the position of its input: sort by it rather than assume
items = sorted(response.data, key=lambda item: item.index)
return [item.embedding for item in items]
if __name__ == '__main__':
with open('corpus.jsonl', encoding='utf-8') as f:
texts = [json.loads(line)['text'] for line in f if line.strip()]
vectors = embed_in_batches(texts, embed_batch_hosted, batch_size=8)
norms = np.linalg.norm(vectors, axis=1)
print(f"{MODEL}: {vectors.shape}, {usage['tokens']} tokens, "
f'norms {norms.min():.3f} to {norms.max():.3f}') batch 1: size 8
batch 2: size 6
text-embedding-3-small: (14, 1536), 193 tokens, norms 1.000 to 1.000This output was not captured from the live API, because the lab assumes no key. It shows what to expect: OpenAI documents 1,536 dimensions for text-embedding-3-small and vectors normalised to length 1, and 193 is the token count of the 14 chunks with tiktoken's cl100k_base encoding, which OpenAI names for its third-generation embedding models. You can check that number offline with tiktoken.get_encoding("cl100k_base") after pip install tiktoken; a real call should report the same shape and about the same token count. A hosted model has no commit hash to pin: record the model name returned in response.model, the dimension and the date in the manifest, and treat a provider's model update or retirement exactly like a model switch.
09. Troubleshooting
10. Check your understanding
11. Apply it (stretch)
Move the lab towards the practice project:
- Run
embed_corpus.pyon your own 500-documentdocs.jsonlwithBATCH_SIZE = 64and note how long it takes. - Keep one index per model, in
index/<model-slug>/, so the local and hosted indexes can sit side by side for the comparison in the next lab. - Write a hosted variant of
embed_corpus.pythat usesembed_batch_hostedand writes the same three files, withresponse.model, the dimension and the token total in its manifest. - Make the batch loop resumable: save each finished batch to
index.tmp/part-NNNN.npyand skip parts that already exist, then kill a run halfway with Ctrl+C and restart it.
12. Review prompt
Without looking back, list the three files of the index and what each one holds, and the fields of the manifest you would refuse to drop. Then explain when the pipeline may reuse a stored vector, when it must re-embed everything, and why search.py checks the manifest before it embeds a query.
References
- Sentence Transformers documentation
- Sentence Transformers: Computing embeddings (prompts and batching)
- Sentence Transformers: SentenceTransformer API reference
- Hugging Face Hub: Downloading models
- Model card: intfloat/multilingual-e5-small
- OpenAI docs: Embeddings
- OpenAI API reference: Create embeddings
- NumPy: numpy.load
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.