Lesson 1 of 7 · Math for AI: Linear Algebra & Calculus Essentials

Vectors: Embeddings, Dot Products & Measuring Similarity

A vector is a list of numbers that you can treat as a point, an arrow, or a meaning. Almost every retrieval system, embedding model, and attention layer is built on three operations on vectors: add them, measure them, and take their dot product.

When a RAG system answers a question, it does not read your documents. It turns the question into a list of numbers, turns every stored text chunk into a list of numbers, and finds the chunks whose numbers sit closest to the question's. Everything in that sentence is vector math. This lesson assumes only high-school algebra and builds the pieces in order: what a vector is, how to combine and measure vectors, the dot product, and the three ways retrieval systems score "closeness" (dot product, cosine similarity, Euclidean distance), which often disagree.

1. A vector is a list of numbers (and a point, and an arrow)

A vector is an ordered list of numbers. The count of numbers is its dimension. Order matters: (3, 1, 2) and (1, 3, 2) are different vectors. We write a vector in bold or with an arrow, and its entries in a column or row. Here we use parentheses: q = (3, 1, 2) is a 3-dimensional vector with entries 3, 1, and 2.

The same list can be read three ways, and AI work switches between them constantly:

A list of features

One row of a dataset: (age, tokens per request, errors per day) = (31, 420, 2). Each position has a meaning you chose.

A point in space

Three numbers locate a point in 3-D. Two vectors that are close together describe similar things, if the numbers were produced sensibly.

An arrow from the origin

The same point drawn as an arrow from (0, 0, 0). The arrow has a length and a direction, and both turn out to matter.

An embedding is a vector that a model produces to represent a word, sentence, image, or document, so that similar items get nearby vectors. Real text embeddings typically have hundreds to a few thousand dimensions (768 and 1,536 are common sizes). To keep every number checkable by hand, this lesson uses a toy 3-dimensional embedding. Nothing here depends on the dimension being 3; only the pictures do.

Key Insight No single entry of a real embedding has a clean human meaning like "royalty" or "food." The meaning lives in the pattern across all entries. What you can rely on is geometry: items the model treats as similar end up pointing in similar directions.

2. Adding vectors and scaling them

Two operations need no new ideas. To add vectors of the same dimension, add entry by entry. To scale a vector, multiply every entry by one ordinary number (a scalar).

a = (1, 2, 3) b = (4, 0, -1)
a + b = (1+4, 2+0, 3+(-1)) = (5, 2, 2)
2a = (2×1, 2×2, 2×3) = (2, 4, 6)
a - b = (1-4, 2-0, 3-(-1)) = (-3, 2, 4)

Geometrically, 2a is the same arrow stretched to twice the length, pointing the same way. A negative scalar flips the arrow. Adding two arrows means placing the second's tail at the first's tip; the sum goes from the start to the end. Subtracting a - b gives the arrow that gets you from b to a, which is why subtraction measures "difference."

These two operations are everywhere in model code. Averaging a vector across tokens (adding them up and scaling by 1 divided by the count) is the usual way to get one embedding for a whole sentence. A residual connection in a transformer adds a layer's output vector to its input vector. Updating weights in training is a scaled vector subtraction: new weights = old weights - (step size) × (gradient), which the calculus lessons develop.

Embedding arithmetic (illustrative)

Early word-embedding work popularized the observation that differences between embeddings can encode relationships: the vector from "man" to "king" roughly matches the vector from "woman" to "queen". Here is a deliberately tiny toy version, with two made-up dimensions (royalty, gender), constructed so the arithmetic works exactly:

king = (9, 1) man = (1, 1) woman = (1, -1) queen = (9, -1)
king - man + woman = (9-1+1, 1-1+(-1)) = (9, -1)
which equals queen
Pitfall This is a hand-built illustration. In a real trained embedding model the result lands near "queen," not exactly on it, and many analogies fail. Treat embedding arithmetic as evidence that direction carries meaning, not as a reliable operation to build a product on.

3. Length: the L2 and L1 norms

The length of a vector, also called its norm, is written with double bars, ‖v‖. The everyday one is the L2 norm: square every entry, add them, take the square root. It is the Pythagorean theorem extended to any number of dimensions.

v = (3, -4, 12)
‖v‖2 = √(3² + (-4)² + 12²) = √(9 + 16 + 144) = √169
‖v‖2 = 13

The L1 norm adds the absolute values of the entries instead: ‖v‖1 = |3| + |-4| + |12| = 19. It measures "total size" like city-block travel rather than a straight line. You will meet it in regularization, where an L1 penalty on weights pushes many of them to exactly zero, and an L2 penalty shrinks them smoothly (the statistics course, Lesson 8, covers why a penalty on weight size fights overfitting). If a norm is written without a subscript, assume L2.

The distance between two points is the length of their difference: distance(a, b) = ‖a - b‖. That is Euclidean distance, and it is why subtraction from section 2 matters.

4. The dot product

The dot product of two vectors of the same dimension multiplies matching entries and adds the results. The answer is a single number, not a vector.

a = (1, 2, 3) b = (4, 0, -1)
a · b = (1×4) + (2×0) + (3×(-1))
= 4 + 0 - 3
= 1

That is the by-components recipe. The second description is geometric:

a · b = ‖a‖ × ‖b‖ × cos(θ)
where θ is the angle between the two arrows

Both recipes give the same number for the same pair of vectors. The second explains what the number means. Take two vectors in 2-D, a = (4, 1) and b = (2, 3):

By components: a · b = (4×2) + (1×3) = 8 + 3 = 11
Lengths: ‖a‖ = √17 ≈ 4.123 ‖b‖ = √13 ≈ 3.606
Solve for cos: cos(θ) = 11 / (4.123 × 3.606) ≈ 0.740
θ ≈ 42.3°
θ ≈ 42.3° a = (4, 1) b = (2, 3) drop straight down onto a green: length of b along a = (a·b)/‖a‖ ≈ 2.67 a · b = 4×2 + 1×3 = 11 ‖a‖ × ‖b‖ × cos θ = 4.123 × 3.606 × 0.740 ≈ 11 small θ → cos near 1 → large dot product θ = 90° → cos = 0 → dot product 0 θ > 90° → cos < 0 → negative dot product
The dot product is the length of one vector times how far the other reaches along it. The angle θ controls how much of the second vector counts.

Read the dot product as "how much do these two arrows point the same way, scaled by how long they are." Three cases cover everything: if the arrows point roughly the same way, cos is near 1 and the dot product is large and positive; at a right angle, cos is 0 and the dot product is 0; pointing opposite ways, it is negative.

Orthogonality

Two vectors are orthogonal (perpendicular) exactly when their dot product is 0. Check: (2, -3, 0) · (3, 2, 5) = 6 - 6 + 0 = 0, so these two are orthogonal even though you could not draw them easily. Orthogonal means "carries no shared information in the dot-product sense." You will see this again in the later linear algebra lessons, and in attention, where a query orthogonal to a key contributes a score of zero.

5. Unit vectors and normalization

A unit vector has length 1. To normalize any nonzero vector, divide it by its own length: u = v / ‖v‖. The direction is unchanged and only the length is removed.

v = (3, 4) ‖v‖ = √(9 + 16) = 5
u = v / 5 = (0.6, 0.8)
‖u‖ = √(0.36 + 0.64) = 1

Normalization matters because of the geometric formula. If both ‖a‖ and ‖b‖ equal 1, then a · b = cos(θ): the dot product of two unit vectors is purely an angle measurement. Many embedding models output unit-length vectors for exactly this reason, and many vector databases offer a "normalize on insert" option.

6. Three ways to score "close": dot product, cosine, distance

Retrieval needs one number saying how well a stored chunk matches a query. Three standard choices:

ScoreFormulaBest match is theSees length?
Dot productq · clargest valueYes: longer vectors score higher
Cosine similarity(q · c) / (‖q‖ ‖c‖)largest value (max 1)No: only the angle counts
Euclidean distance‖q - c‖smallest valueYes: length differences add distance

Cosine similarity is just the dot product with both lengths divided out, so it is the cos(θ) from section 4. It ranges from -1 (opposite) through 0 (orthogonal) to 1 (same direction). A related fact from the statistics course, Lesson 6: if you first subtract each vector's own mean from its entries, cosine similarity becomes the Pearson correlation.

Worked example: one query, three chunks

A team's retrieval system embeds a query and three document chunks into a toy 3-dimensional space. The numbers are invented for the example:

query q = (3, 1, 2)
chunk A = (6, 2, 4) (a long, detailed passage on the topic)
chunk B = (2, 1, 2) (a short passage, similar content)
chunk C = (10, 0, 0) (a long passage heavy on one unrelated feature)

First the lengths. ‖q‖ = √(9 + 1 + 4) = √14 ≈ 3.742. ‖A‖ = √(36 + 4 + 16) = √56 ≈ 7.483. ‖B‖ = √(4 + 1 + 4) = 3. ‖C‖ = √100 = 10.

Dot products:

q · A = 3×6 + 1×2 + 2×4 = 18 + 2 + 8 = 28
q · B = 3×2 + 1×1 + 2×2 = 6 + 1 + 4 = 11
q · C = 3×10 + 1×0 + 2×0 = 30

Cosine similarities (dot product divided by ‖q‖ × ‖chunk‖):

cos(q, A) = 28 / (3.742 × 7.483) = 28 / 28 = 1.000
cos(q, B) = 11 / (3.742 × 3) = 11 / 11.225 ≈ 0.980
cos(q, C) = 30 / (3.742 × 10) = 30 / 37.417 ≈ 0.802

Euclidean distances (length of q - chunk):

q - A = (-3, -1, -2) → √(9 + 1 + 4) = √14 ≈ 3.742
q - B = ( 1, 0, 0) → √1 = 1.000
q - C = (-7, 1, 2) → √(49 + 1 + 4) = √54 ≈ 7.348
ChunkDot productCosineDistance
A281.000 (best)3.742
B110.9801.000 (best)
C30 (best)0.8027.348

Three metrics, three different winners. Chunk A points in exactly the same direction as the query (it is 2× the query, since 2 × (3, 1, 2) = (6, 2, 4)), so cosine rates it a perfect match. Chunk B is the closest point in space, so distance picks it. Chunk C has a huge length and a big component that overlaps with the query's biggest entry, so it wins on raw dot product, even though its direction is the worst of the three. The dot product mixed "does it match" with "how big is this vector."

What happens after normalizing

Divide every vector by its length first, and the disagreement disappears. For unit vectors, dot product = cosine, and Euclidean distance is a function of cosine: ‖u - v‖2 = 2 - 2cos(θ). Using B as a check: 2 - 2(0.980) = 0.040, which matches the squared distance between the normalized q and normalized B (about 0.0401). Chunk C: 2 - 2(0.802) = 0.396. A: 2 - 2(1) = 0. So after normalization all three metrics rank A, then B, then C.

Key Insight Pick the metric your embedding model was trained for, and normalize if it says to. Cosine similarity is the usual default for text because a chunk's vector length mostly reflects incidental things (such as passage length or word frequency), not relevance. Raw dot product is right when length is meaningful, as in some recommendation models where a larger vector means a more popular item. Mixing a model trained for one metric with an index configured for another silently changes which chunks come back.

7. High dimensions: why the scores bunch up

Real embeddings have hundreds to thousands of dimensions, and geometry behaves differently there. Take two directions chosen at random in d dimensions. Their cosine is centered on 0, with a typical spread of about 1/√d:

d = 3: 1 / √3 ≈ 0.577 (random pairs vary a lot)
d = 768: 1 / √768 ≈ 0.036
d = 1,536: 1 / √1536 ≈ 0.026

In high dimensions, two unrelated directions are almost always nearly orthogonal, because there are so many ways to differ. That is useful: it leaves lots of room to store distinct meanings. It also means real similarity scores sit in a narrow band. A cosine of 0.78 versus 0.74 can be the difference between "relevant" and "not," and there is no universal cutoff, because the typical background level depends on the model. Calibrate a threshold against your own labeled queries rather than copying one from a blog post.

Pitfall Real embeddings are not random directions. Many models place all their outputs in a narrow cone, so unrelated texts can still show a cosine of 0.5 or more. Compare scores within one model and one corpus. A score of 0.8 from one model is not comparable with 0.8 from another.

8. Why this matters for building AI systems

Why This Matters Dot products are the single most repeated operation in modern AI. Retrieval, attention, and every neural-network layer reduce to them.

Retrieval and RAG

A vector database stores one embedding per chunk and, for each query, returns the chunks with the best score under one of the three metrics above. When retrieval returns odd results, check the metric and normalization before changing the chunking or the prompt. A longest-chunk-wins pattern is the signature of raw dot product on unnormalized vectors.

Attention

In a transformer, each token produces a query vector and a key vector, and the attention score between two tokens is a dot product of query and key. High score means "pay attention here." Because dot products grow with dimension, implementations divide the scores by √(key dimension), which is a normalization of the same kind as section 5. M2 shows how these query, key, and value vectors are produced from a token's embedding by matrices.

Neural-network layers

One neuron computes a dot product between its weight vector and its input vector, adds a bias, and applies a nonlinearity. A layer is many such dot products at once. That bundling is what a matrix is, and it is where this lesson hands off.

Leads into M2

You now have vectors as data and the dot product as the basic measuring tool. M2 (Matrices & Transformations) stacks many vectors into a matrix, uses a matrix to turn one vector into another, and shows that a whole layer of a neural network, and the query, key, and value projections in attention, are just matrix-vector multiplication: lots of dot products done together.

Recap

✅ Check Yourself

1. What is the dot product of a = (2, 0, 5) and b = (1, 4, -1)?

The vector (2, 0, -5)
7
-3

2. Two embeddings have a dot product of exactly 0. What does that tell you about the angle between them?

They are at 90° (orthogonal)
They point in the same direction
They point in opposite directions

3. A retrieval system keeps returning the longest chunks, whose vectors have the largest lengths, even when shorter chunks are clearly more on-topic. The index scores with raw dot product on unnormalized vectors. What is the most direct fix?

Increase the embedding dimension
Normalize the vectors to unit length (or score with cosine similarity)
Switch to the L1 norm for the lengths of the query

4. What is the L2 norm of v = (6, -8)?

14
2
10

5. For two unit vectors u and v, which statement is true?

Their dot product is always 1
Their dot product equals the cosine of the angle between them
Their dot product equals their Euclidean distance