Embeddings
What an embedding is
Say this
An embedding is a vector of numbers that represents a text's meaning. Texts with similar meaning get vectors pointing in similar directions, even with no shared words. We compare them with cosine similarity.
Example project
qwen3-embedding:4b gives 2560-dimensional vectors, normalized to length 1, so cosine equals the dot product. In pgvector I search with the cosine distance operator <=>, and .
If they push
- Embeddings miss exact identifiers: names, codes, numbers. That's why I added keyword search (story 2).
- The query and the documents must use the same model. Change the model and you re-embed everything and re-measure the threshold.
How an embedding is made
Say this
The model can't read text, so a tokenizer first splits it into subword pieces and gives each an ID. An ID is only a row number with no meaning. Each ID looks up a learned vector, 2560 numbers in my qwen3-embedding:4b. Those vectors go through 36 transformer layers, where self-attention lets every token take context from the others, so the same word gets a different vector in a different sentence. Pooling (in Qwen, the last token, because it has seen the whole text) gives one vector for the whole text, and we normalize it. Similar meanings land close because the model was trained contrastively. Full detail: chapter 2, step 4.
Example project
Queries get Qwen's instruction prefix: Instruct: Given a question, retrieve passages from the document collection that answer it / Query: …. Documents get no prefix. Leaving the prefix off measurably lowers retrieval quality, so I added it.
If they push
- Why the last token: decoder attention is causal, so only the last token has seen the whole text.
- Input limit: 8192 tokens for my embedder. That's why my chunks can be fairly large.
How Qwen trains its embedding model
Say this
Qwen3-Embedding starts from a pretrained Qwen3 LLM. Stage one: contrastive training on a huge set of synthetic query–passage pairs (about 150 million) that a larger Qwen model generated across tasks and languages. Stage two: supervised fine-tuning on smaller high-quality labelled data plus the best synthetic pairs. Stage three: merging several checkpoints for robustness. The loss is InfoNCE: pull each query to its correct passage, push it from negatives.
If they push
- Negatives: the other passages in the batch, plus hard negatives that look relevant but aren't.
- Queries carry a task instruction, so one model serves search, classification and clustering. That's why I use the prefix.
- Sizes: 0.6B, 4B, 8B. Last-token pooling. Matryoshka training lets you cut dimensions.
- The Qwen3 reranker is trained separately as a yes/no relevance judge.
Be honest
"I haven't trained an embedding model myself. I use Qwen's, and I know their training recipe from the technical report. I have trained models end to end: a CRNN OCR from scratch and a LoRA fine-tune of Qwen3.5-4B."
First: three different Qwen models, three different jobs
Say this clearly in the interview. Mixing them up sounds like you don't know your own system.
| Model | Type | Where | Did I train it? | Its job |
|---|---|---|---|---|
qwen3-embedding:4b | Embedding model (encoder use) | RAG | No. Used as released. | Text → one vector of 2560 numbers |
qwen3:8b | Chat LLM (generator) | RAG | No. Used as released. | Reads the evidence, writes the cited answer |
| Qwen3.5-4B + my LoRA | Chat LLM, fine-tuned | Tez | Yes. LoRA fine-tune. | Turns an Excel request into a JSON plan for DuckDB |
The one-liner: "In RAG I use Qwen3-Embedding as is, served by Ollama. The model I fine-tuned is a different one, Qwen3.5-4B in Tez, trained with LoRA to output JSON plans."
How the pieces connect
- Chrome extensionPOST /api/ingest/page {url, title, text}
- FastAPI app (app.py)settings come from .env through pydantic-settingsDATABASE_URL, OLLAMA_URL, model names
- Talks to two servicesOllama · 127.0.0.1:11434HTTP through httpx, 20 s timeout/api/embed → qwen3-embedding:4b /api/generate → qwen3:8bPostgreSQL 17 + pgvectorSQL through psycopg, database ragdb7 tables, vectors in a vector column
Ollama runs the model on my machine and exposes it over HTTP, so the app never loads model weights itself. The app talks to two services, Ollama for vectors and text, Postgres for storage and search, and connects them.
The database structure
- documentsone row per page; children are deleted with it (CASCADE)id, canonical_url UNIQUE, title, page_type
- Raw copy and versions1..n, CASCADEraw_documentscontent_hash, raw_contentdocument_versionsversion_number, content_hash, cleaned_content
- chunks1..n per version; GIN index: to_tsvector('simple', chunk_text)chunk_index, chunk_text, token_count, start_char, end_char, overlap_with_previous
- embeddingsUNIQUE (chunk_id, embedding_model_id)chunk_id, embedding_model_id, embedding vector
- embedding_modelsevery embedding points here; a model in use cannot be deleted (RESTRICT)id, model_name UNIQUE, dimension, max_input_tokens, normalized, backend
- retrieval_tracesone row per questionquestion, intent, embedding_model_id, selected_chunk_ids[], latency_ms
- Why vectors live in their own table: one chunk can have vectors from several models (
UNIQUE(chunk_id, embedding_model_id)). To switch models I re-embed into new rows while the old ones keep serving, then switch. No downtime, no mixing. - Why
embedding_modelsexists: every vector knows which model and dimension made it. Search filters by model id, so vectors from two models are never compared. - Why versions: a changed page becomes a new version, search reads only the newest, and the history stays.
- CASCADE / RESTRICT: deleting a document removes its versions, chunks and vectors. A model that still has vectors can't be deleted by accident.
Indexing path, in code order
- Find the model's dimension at runtime.
ensure_model()embeds the text "embedding dimension probe", reads the vector length (2560), and upserts the model intoembedding_models. Nothing is hardcoded: swap the model in.envand the dimension follows. - One transaction per page. Lock the document row (
SELECT … FOR UPDATE), compare the cleaned text with the latest version, return "unchanged" if equal, otherwise insert a new version with its SHA-256 hash. - Chunk and insert the chunk rows, refusing any chunk over the model's 8192-token input limit.
- Embed all chunks of the page in one batch:
matn3 lines
POST http://127.0.0.1:11434/api/embed {"model": "qwen3-embedding:4b", "input": [chunk1, chunk2, ...], "truncate": false} → {"embeddings": [[0.021, -0.113, ...], [...]]}truncate: falsemeans an over-long text raises an error instead of being cut silently. The code checks it got one vector per chunk and that every number is finite. - Check and store. Each vector must have the probed dimension. It's written as a pgvector literal:
INSERT INTO embeddings(chunk_id, embedding_model_id, embedding) VALUES (…, '[0.021,-0.113,…]'::vector). - Commit. If anything fails, the whole page rolls back, so there are never chunks without vectors.
Query path, in code order
- Look up the model id and dimension (same
ensure_model()). - Embed
instruct prefix + questionthrough the same/api/embedcall, and check the length is 2560. - Search with one SQL query:
In the real query this is one CTE, fused with the keyword search by RRF in the same statement.sql10 lines
SELECT c.chunk_text, d.canonical_url, 1 - (e.embedding <=> $question_vector) AS similarity FROM embeddings e JOIN chunks c ON c.id = e.chunk_id JOIN document_versions v ON v.id = c.document_version_id JOIN documents d ON d.id = v.document_id WHERE e.embedding_model_id = $model_id -- never mix models AND v.version_number is the newest -- latest version only ORDER BY e.embedding <=> $question_vector -- cosine distance LIMIT 12;
The 60-second answer
Say this
"In my RAG I don't train the embedding model; I use Qwen3-Embedding 4B as released, served locally by Ollama over HTTP. My FastAPI app sends all chunks of a page in one batch to Ollama's embed endpoint and gets back one 2560-number vector per chunk. The dimension isn't hardcoded: at startup I embed a probe text, read the length, and register the model in an embedding_models table. In PostgreSQL with pgvector the schema is documents, versions, chunks, and a separate embeddings table keyed by chunk and model, so I can re-embed with a new model side by side. Each page is stored in one transaction. At question time I embed the question with Qwen's instruction prefix and search with pgvector's cosine operator, filtered to the same model and the newest versions. The model I did fine-tune is a different one: Qwen3.5-4B in Tez, with LoRA."
Gaps I would fix (say these if asked "what would you improve?")
- No ANN index yet. The vector column has no fixed dimension, so search is an exact scan. That's fine at my size. To scale I'd make it
halfvec(2560)with an HNSW index, because pgvector's HNSW supports up to 2,000 dimensions forvectorand 4,000 forhalfvec. The other option is using Qwen's Matryoshka support to cut vectors to 1024. - One connection per request. I'd add a connection pool.
- The embedding call happens inside the database transaction, so the row lock is held while the model runs. I'd embed first, then open a short transaction to write.
Questions about this chapter?
The course, homework review and the other five books are in Uzbek. Questions in English are welcome on Telegram.