Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Worked example · 20 min · revision 2

Similarity by Hand and in NumPy

Compute dot product, cosine similarity and distance by hand, see how normalisation changes which document wins, rank real embeddings with one NumPy matrix product, and measure what cutting dimensions does to storage and results.

Contentsand lesson path

What you will learn

  • Compute cosine similarity and explain how normalization and dimensionality affect results.

Prerequisites: Data Handling

01. The problem

You have a matrix of document vectors and a question vector, and you need the documents most similar to the question. A vector database will do this for you in the next skill, but you should be able to compute the answer yourself, for three reasons:

  • to check that an index returns what it should;
  • to debug the classic failures: long documents that win every query, scores that suddenly shrink, recall that drops after someone "saved memory";
  • to judge the trade-off between vector size and quality with numbers instead of guesses.

We start with three-number vectors you can work out on paper, then apply exactly the same NumPy code to real 384-number embeddings. Use the environment from the previous lesson; NumPy comes with sentence-transformers.

02. Step 1: Dot product, length and cosine by hand

Four formulas cover everything in this lesson. For vectors a and b with the same number of values:

  • dot product: multiply the values position by position and add them up, a·b = a1×b1 + a2×b2 + …
  • length (L2 norm): ‖a‖ = √(a1² + a2² + …)
  • cosine similarity: a·b / (‖a‖ × ‖b‖), the dot product with both lengths divided out, so only the angle between the vectors counts
  • Euclidean distance: ‖a − b‖, the length of the difference

Take a query q = (1, 2, 2) and two documents, A = (0, 3, 4) and B = (6, 0, 6). Work it out before reading on:

  1. Dot products: q·A = 0 + 6 + 8 = 14 and q·B = 6 + 0 + 12 = 18. The dot product prefers B.
  2. Lengths: ‖q‖ = √9 = 3, ‖A‖ = √25 = 5, ‖B‖ = √72 ≈ 8.485.
  3. Cosines: 14 / (3 × 5) ≈ 0.933 for A and 18 / (3 × 8.485) ≈ 0.707 for B. Cosine prefers A.
  4. Distances: q − A = (1, −1, −2), length √6 ≈ 2.449; q − B = (−5, 2, −4), length √45 ≈ 6.708. A is closer.

B wins the dot product only because it is long. Its direction matches the query less well than A's does. With text embeddings that are not normalised, the length of a vector varies with things other than meaning, such as the length and wording of the text, so an unnormalised dot product can reward a document for the wrong reason. Now check the arithmetic with NumPy:

Python · by_hand.py
import numpy as np

q = np.array([1.0, 2.0, 2.0])
docs = np.array([
    [0.0, 3.0, 4.0],  # A
    [6.0, 0.0, 6.0],  # B
])

dot = docs @ q
cosine = dot / (np.linalg.norm(docs, axis=1) * np.linalg.norm(q))
distance = np.linalg.norm(docs - q, axis=1)
print('dot     ', dot)
print('cosine  ', cosine.round(3))
print('distance', distance.round(3))
Expected output
dot      [14. 18.]
cosine   [0.933 0.707]
distance [2.449 6.708]

docs @ q multiplies a (2, 3) matrix by a vector of 3 values and returns one dot product per row. np.linalg.norm(docs, axis=1) returns one length per row; without axis=1 it would return a single number for the whole matrix.

03. Step 2: Normalise once, then the dot product is enough

L2 normalisation divides a vector by its length, so it keeps its direction and gets length 1. For two unit vectors the denominator of the cosine is 1 × 1, so the dot product is the cosine. Distance lines up too: for unit vectors ‖a − b‖² = 2 − 2 × cos(a, b), so a higher cosine always means a smaller distance. Add this to the end of by_hand.py:

Python · by_hand.py (append)
def normalise(x: np.ndarray) -> np.ndarray:
    """Scale a vector, or each row of a matrix, to length 1."""
    return x / np.linalg.norm(x, axis=-1, keepdims=True)


q_unit, docs_unit = normalise(q), normalise(docs)
print('lengths ', np.linalg.norm(docs_unit, axis=1))
print('dot     ', (docs_unit @ q_unit).round(3))
print('distance', np.linalg.norm(docs_unit - q_unit, axis=1).round(3))
Expected output (after the three lines from step 1)
lengths  [1. 1.]
dot      [0.933 0.707]
distance [0.365 0.765]

After normalising, the dot product equals the cosine from step 1, A still wins, and the distances follow the same order: √(2 − 2 × 0.933) ≈ 0.365.

In normalise, axis=-1 measures along the last axis, so the same function handles one vector or a matrix of rows, and keepdims=True keeps the lengths as a (2, 1) column so that each row is divided by its own length.

This is why pipelines normalise every vector once, documents when they are stored and queries when they arrive, and then score with the plain dot product, the cheapest of the three. Vector indexes ask you to pick a metric (inner product, cosine or L2); on unit vectors all three rank alike. Normalising twice does no harm, so normalize_embeddings=True in model.encode is a cheap guarantee.

04. Step 3: Search real embeddings with one matrix product

The same arithmetic works for 384 values. Put the document vectors in a matrix D with one row per document and the query vectors in Q. Then Q @ D.T computes every query against every document in one call.

Python · search.py
import numpy as np
from sentence_transformers import SentenceTransformer

docs = [
    'Reset your password from the sign-in page with "Forgot password".',
    'Two-factor codes expire after 30 seconds; check your phone clock.',
    'Invoices are emailed on the first working day of each month.',
    'Edit your billing profile to change the VAT number on invoices.',
    'Export any report to CSV or Parquet from the Reports menu.',
    'Accounts lock for 15 minutes after five failed sign-in attempts.',
    'Single sign-on users sign in through their company identity provider.',
    'Webhooks retry failed deliveries for up to 24 hours.',
]
queries = [
    "I can't log in to my account",
    'wrong tax number on my bill',
    'download my data as a spreadsheet',
]

model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
D = model.encode(docs)  # shape (8, 384)
Q = model.encode(queries)  # shape (3, 384)
print('row lengths', np.linalg.norm(D, axis=1).round(3))

scores = Q @ D.T  # shape (3, 8): every query against every document
assert np.allclose(scores, model.similarity(Q, D).numpy(), atol=1e-5)
for query, row in zip(queries, scores):
    print(query)
    for i in np.argsort(-row)[:3]:  # indices of the three highest scores
        print(f'  {row[i]:.3f}  doc {i}  {docs[i]}')
Expected output
row lengths [1. 1. 1. 1. 1. 1. 1. 1.]
I can't log in to my account
  0.546  doc 0  Reset your password from the sign-in page with "Forgot password".
  0.454  doc 5  Accounts lock for 15 minutes after five failed sign-in attempts.
  0.319  doc 6  Single sign-on users sign in through their company identity provider.
wrong tax number on my bill
  0.560  doc 3  Edit your billing profile to change the VAT number on invoices.
  0.222  doc 2  Invoices are emailed on the first working day of each month.
  0.155  doc 1  Two-factor codes expire after 30 seconds; check your phone clock.
download my data as a spreadsheet
  0.411  doc 4  Export any report to CSV or Parquet from the Reports menu.
  0.097  doc 2  Invoices are emailed on the first working day of each month.
  0.063  doc 3  Edit your billing profile to change the VAT number on invoices.

Walk through it:

  • All row lengths are 1 because this model normalises its output, which is why the plain matrix product matches model.similarity (cosine). For a model that does not normalise, the assert would fail.
  • Q @ D.T multiplies (3, 384) by (384, 8) into a (3, 8) table of scores.
  • np.argsort(-row) sorts indices by descending score; without the minus the worst match comes first. For large corpora, np.argpartition(-row, k)[:k] finds the top k without a full sort, and beyond a few million vectors an approximate index takes over.

Each query found the right article without a shared keyword for tax or spreadsheet, even though the best spreadsheet score is only 0.411. What counts is the order of the scores from one model, not their size.

05. Step 4: Fewer dimensions: truncate, re-normalise, re-check

Dimensions cost money. Every vector is stored as dimensions × 4 bytes in float32, and a brute-force search does one multiplication per dimension per document, so memory and search time grow in step with the dimension count:

Python · storage.py
for dims in (3072, 1536, 384, 128):
    gigabytes = 1_000_000 * dims * 4 / 1e9  # float32 = 4 bytes per number
    print(f'{dims:>5} dimensions: {gigabytes:5.2f} GB per million vectors')
Expected output
 3072 dimensions: 12.29 GB per million vectors
 1536 dimensions:  6.14 GB per million vectors
  384 dimensions:  1.54 GB per million vectors
  128 dimensions:  0.51 GB per million vectors

Some models are trained so that you can keep only the first values of each vector and lose little quality. This is called Matryoshka representation learning, after the nesting dolls. OpenAI's text-embedding-3 models accept a dimensions parameter that shortens the vectors for you. In sentence-transformers, SentenceTransformer(name, truncate_dim=256) or encode(..., truncate_dim=256) keeps the first 256 values of any model, but only a model trained this way keeps most of its quality.

all-MiniLM-L6-v2 was not trained this way, which makes it a useful test of what truncation does. Add this to the end of search.py. It keeps the first dims values, re-normalises, and prints the top 3 for each query, together with the best score you would get without re-normalising:

Python · search.py (append)
def normalise(x: np.ndarray) -> np.ndarray:
    return x / np.linalg.norm(x, axis=-1, keepdims=True)


header = 'dims  top-3 per query' + ' ' * 20 + 'best score' + ' ' * 8
print(header + 'without re-normalising')
for dims in (384, 128, 64, 32):
    S = normalise(Q[:, :dims]) @ normalise(D[:, :dims]).T
    raw = Q[:, :dims] @ D[:, :dims].T
    tops = [np.argsort(-row)[:3].tolist() for row in S]
    print(f'{dims:>4}  {tops}  {S.max(axis=1).round(2)}  {raw.max(axis=1).round(2)}')
Expected output (after the search results)
dims  top-3 per query                    best score        without re-normalising
 384  [[0, 5, 6], [3, 2, 1], [4, 2, 3]]  [0.55 0.56 0.41]  [0.55 0.56 0.41]
 128  [[0, 5, 6], [3, 2, 1], [4, 2, 3]]  [0.47 0.6  0.53]  [0.16 0.24 0.21]
  64  [[0, 5, 6], [3, 7, 2], [4, 2, 3]]  [0.55 0.74 0.43]  [0.08 0.18 0.06]
  32  [[5, 0, 6], [3, 2, 1], [4, 7, 2]]  [0.49 0.78 0.45]  [0.03 0.09 0.03]

Three effects are visible:

  • At 128 values the top 3 is unchanged, at a third of the storage. At 64, the webhook article (doc 7) reaches second place for the tax query; at 32, the login query's best answer drops to second.
  • Scores shift even when the order holds. The best spreadsheet score rises from 0.41 to 0.53 at 128 values, so a cut-off tuned on full vectors does not carry over.
  • Without re-normalising, scores collapse to between 0.03 and 0.24, because part of a unit vector is shorter than 1. Each truncated document also gets its own length, so rankings can change for the wrong reason, as in step 1. Always re-normalise after truncating; OpenAI's guide says the same about shortening its vectors by hand.

Eight documents show the mechanics, not the quality loss. To decide whether 128 values are enough, rerun the labelled-query evaluation from the last lesson of this skill at each size. Lower precision is the other lever: float16 halves storage, and int8 or binary quantisation shrink it further, again at a cost you measure.

06. Common mistakes

07. Check your understanding

Practice check · 3 questions

Similarity arithmetic

Work these out with pen and paper or in a Python shell.

Q1. What is the cosine similarity of the vectors (3, 4) and (4, 3)?
Q2. D is a NumPy array of shape (1000, 384) with one document vector per row. Which expression scales every document vector to length 1?
Q3. You keep the first 128 of the 384 values of each unit-length vector and go on scoring with the dot product, without re-normalising. What goes wrong?
Practice only: not graded, not saved, not evidence.

08. Apply it

Use the docs.jsonl and the 20 labelled questions you collected for the practice project:

  1. Embed all documents and questions with all-MiniLM-L6-v2, then compute, with NumPy only, the rank of the labelled document for each question.
  2. Repeat at 192 and 96 dimensions, re-normalising after truncation, and count how many questions lose their labelled document from the top 5.
  3. Save the document matrix with np.save as float32 and as float16 (D.astype(np.float16)), compare the file sizes, and check whether the top 5 results change.

Keep the script: the next lab turns it into a proper batch job with a manifest.

09. Review prompt

Without looking back, compute the dot product, both lengths and the cosine for (1, 0) and (1, 1). Then explain in two sentences why a long vector can win on dot product but lose on cosine, what normalising changes, and the two things you must do after cutting a vector to fewer dimensions.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check