Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 7: Embeddings and RAG

Week 07 / Lesson 1

Embeddings and searchable document chunks

Build a small local index and explain what similarity does and does not measure.

Section 1.1 1 of 7

Overview

Focus

Build a small local index and explain what similarity does and does not measure.

Your route through the lesson

  • 1.2 Embedding models and compatible vector spaces
  • 1.3 Dot products, norms, and cosine similarity
  • 1.4 Chunk boundaries, metadata, and a local vector index
  • 1.5 Put it into practice
  • 1.6 Guided comparison
  • 1.7 An exact product-code query

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 1.2 2 of 7

Embedding models and compatible vector spaces

Focus

Explain why a query and a document need compatible numerical representations.

An embedding is a list of numbers representing an item. An embedding model is the mapping that produces that list. A learned text encoder can put paraphrases near one another because its training rewarded useful relationships. The numbers are coordinates, not named facts or proof that a passage is true. Retrieval selects candidates; reading the selected evidence still matters.

Consider a deliberately small teaching encoder with two coordinates: access problems and payment problems. It maps “password reset” to [2, 0], “cannot sign in” to [1, 0], and “invoice overdue” to [0, 2]. The first two point in the same direction despite different wording. This encoder is handcrafted, so its success demonstrates representation mechanics, not the quality of a trained language model.

An index stores document vectors together with the encoder name, revision, dimension, and preprocessing rule. A query must use that same representation. Another encoder might reverse the coordinate meanings while still returning two numbers. Equal length therefore does not establish compatibility. Changing the encoder requires rebuilding document vectors before comparing new queries.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Encoder A means [access, payment]; encoder B means [payment, access]. Both return two numbers. Can their vectors be mixed?
2. A handcrafted encoder maps “password reset” and “cannot sign in” to parallel vectors. What has this demonstrated?
3. A knowledge index uses encoder revision 1. The application switches queries to revision 2 with different coordinates. What should change?

Section 1.3 3 of 7

Dot products, norms, and cosine similarity

Focus

Calculate similarity and handle a vector with no usable direction.

A dot product multiplies matching coordinates and adds the products. For [3, 4] and [4, 3], it is 3 × 4 + 4 × 3 = 24. The norm is the vector’s length: square each coordinate, add, then take the square root. Both vectors have norm 5. Cosine similarity divides the dot product by the product of the norms, giving 24 / 25 = 0.96. It measures direction while removing length.

This distinction matters when one passage repeats the same words. Vectors [1, 0] and [10, 0] have different dot products with [1, 0], but both have cosine similarity 1. Repetition has increased magnitude without changing direction. Neither score is a probability that a document answers the question.

The vector [0, 0] has norm zero, so the cosine denominator would be zero. An implementation must define a policy, such as returning similarity zero and recording an empty-representation warning. It must not divide first and hope that ranking handles the resulting error. Negative similarities are possible with encoders that produce negative coordinates.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Vectors [3, 4] and [4, 3] each have norm 5 and dot product 24. What is their cosine similarity?
2. A query [1, 0] is compared with [1, 0] and [10, 0] using cosine. Which ranks higher?
3. An unknown-word query encodes as [0, 0]. Which policy prevents invalid cosine arithmetic?

Section 1.4 4 of 7

Chunk boundaries, metadata, and a local vector index

Focus

Preserve context and traceability while indexing document chunks.

A chunk is the unit retrieved from a longer document. Splitting every forty words is easy, but can detach “except contractors” from the policy it qualifies. A boundary should preserve the smallest useful answer and its conditions. Modest overlap can repeat a sentence across neighboring chunks when a paragraph exceeds the chosen size. Overlap consumes storage and can produce duplicate results, so more overlap is not automatically better.

Suppose a source reads “Employees reset passwords online. Contractors contact support.” A chunk containing only “reset passwords online” loses who may do so. Store the full first sentence, its source identifier, and start and end character positions. Python slicing uses an inclusive start and an exclusive end: source[start:end] should reproduce the stored text exactly. A source revision or content hash makes this check meaningful after edits.

A local vector index can simply be a list of records searched exhaustively. A vector database adds storage and search machinery, often including faster approximate search for larger collections. Whichever storage is chosen, keep permissions, source location, and revision beside the vector. Fast nearest-neighbor search cannot reconstruct metadata that was never stored.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A policy says “Staff may reset online. Contractors must call support.” Which chunk best preserves the staff rule?
2. Python stores text = source[10:25]. Which invariant checks the chunk location?
3. An approximate vector search is very fast but drops source identifiers. What has been lost?

Section 1.5 5 of 7

Put it into practice

Focus

Run the small index and interpret its checks without claiming model quality.

Save week07.py in your exercise folder. Run python week07.py --lesson 1. The script needs only Python’s standard library, no account, download, or graphics processor. Its tiny corpus and handcrafted feature encoder use negligible memory and should finish in seconds on a normal processor. This is a checked baseline for retrieval mechanics; an optional local embedding endpoint can replace the encoder in a separately requested run.

The script imports math for square roots. zip(a, b) pairs matching coordinates; sum(...) adds the generated products. A conditional checks zero length before division. The core computation is:

import math
def cosine(a, b):
    assert len(a) == len(b)
    dot = sum(x * y for x, y in zip(a, b))
    norm = math.sqrt(sum(x*x for x in a) * sum(y*y for y in b))
    return dot / norm if norm else 0.0
assert cosine([1, 0], [0, 1]) == 0.0

Read the printed query rankings and PASS lines. Matching dimensions, zero-vector handling, and source-slice equality should pass. The exact-code query deliberately exposes a dense-representation tie. A passing assertion verifies its stated invariant; it does not establish general semantic understanding.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A lab prints PASS for source slicing and dimension checks. Which conclusion is supported?
2. In sum(x * y for x, y in zip(a, b)), what does zip provide?
3. A learner sees a tie for two different product codes in the handcrafted dense index. What should they do?

Section 1.6 6 of 7

Guided comparison

Focus

Trace a complete ranking from query representation back to source evidence.

Consider a completed lookup for “cannot sign in.” The teaching encoder counts access-related terms and produces [1, 0]. The password-reset passage has [2, 0], the invoice passage [0, 2], and a mixed account-billing passage [1, 1]. Their cosine scores are 1, 0, and about 0.707. Sorting descending puts the password passage first, then the mixed passage. The result retains the password passage’s source identifier and character range.

Now compare “ZX-41 support.” The encoder intentionally lacks product-code coordinates. Two product passages may both become [1, 0] and tie. The index has executed its specified mathematics correctly while retrieving an ambiguous result. A retrieval failure is therefore not necessarily a software exception. It can be a mismatch between the representation and the information the task requires.

The lab checks both outcomes. A changed vector length should produce an assertion failure rather than a plausible-looking score. An unknown-word query should produce zeros rather than crash. These cases explain why a useful trace records the encoder revision, query representation, candidate identifiers, scores, and eventual source text together.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A query [1, 0] has cosine scores 1, 0, and 0.707 for passages A, B, and C. What is descending order?
2. Two product passages encode identically, so the wrong one is returned. The arithmetic is correct. What failed?
3. A trace records a score of 0.9 but no passage or source. Can it substantiate a warranty claim?

Section 1.7 7 of 7

An exact product-code query

Focus

Use exact identifiers alongside semantic representations in a product lookup.

A support engineer asks for the reset steps for device ZX-41. The corpus contains ZX-41, ZX-14, and ZY-41 manuals. Their prose is almost identical: press the reset button, wait, then reconnect. A semantic encoder can appropriately consider these passages similar while still being unsuitable for selecting the exact device. Similar procedural language and exact product identity answer different questions.

A completed solution first recognizes the literal identifier ZX-41, narrows to documents whose product_code metadata equals that value, and then ranks eligible passages for the reset topic. If the corpus contains no ZX-41 manual, the assistant states that this source is missing. It does not silently substitute ZX-14 because the procedure sounds plausible.

This transfer case shows why metadata is more than a display label. An exact field can enforce a condition before similarity ranking, while source revision distinguishes outdated instructions from current ones. A model may help extract a candidate identifier, but the executor checks that value against the user’s request and the actual index. The next lesson combines lexical evidence with dense ranking without confusing either score with truth.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. ZX-41 and ZX-14 manuals have similar wording. The user specifically requests ZX-41. Which selection rule is best?
2. A corpus contains only a ZX-14 manual, but the request is for ZX-41. What response is supported?
3. Two ZX-41 manuals disagree and carry different revisions. Which metadata helps investigate?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Combining retrieval methods →