Dot Product

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

published · difficulty 2/5 · 12 min read

Reading map and next steps

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

The dot product answers the question: “How much does one vector point in the direction of another?” Its value depends on both vectors' lengths and their relative direction.

  • If two nonzero arrows point in the same direction, the dot product is positive and equals the product of their lengths.
  • If they’re perpendicular, it’s zero.
  • If they point in opposite directions, it’s negative.

In ML, dot products serve as similarity scores and compare queries with keys in attention. Cosine similarity instead divides the dot product by the product of the vectors' lengths; it is defined only when both vectors are nonzero.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let u,v∈Rnu,v \in \mathbb{R}^n, with coordinates

u=(u1,…,un),v=(v1,…,vn).u = (u_1,\ldots,u_n), \qquad v = (v_1,\ldots,v_n).

The dot product is the coordinate-wise multiply-and-sum operation

u⋅v=∑i=1nuivi.u \cdot v = \sum_{i=1}^n u_i v_i.

This definition is algebraic, but it is designed to preserve geometry. The squared length of a vector is

∥u∥2=u⋅u=∑i=1nui2,\|u\|^2 = u \cdot u = \sum_{i=1}^n u_i^2,

so ∥u∥=u⋅u\|u\| = \sqrt{u\cdot u}. If θ\theta is the angle between two nonzero vectors, the same operation satisfies

u⋅v=∥u∥ ∥v∥cos⁡θ.u \cdot v = \|u\|\,\|v\|\cos\theta.

You can read this as:

u⋅v∥u∥ ∥v∥=cos⁡θ.\frac{u \cdot v}{\|u\|\,\|v\|} = \cos\theta.

That ratio is cosine similarity. It removes the lengths and keeps only direction, which is why embeddings often use it as a normalized similarity score.

That immediately gives:

  • Orthogonality: u⊥v  ⟺  u⋅v=0u \perp v \iff u\cdot v = 0.
  • Alignment: u⋅v>0u\cdot v > 0 means the angle is acute, while u⋅v<0u\cdot v < 0 means the angle is obtuse.
  • Scaling: (au)⋅v=a(u⋅v)(au)\cdot v = a(u\cdot v), so making one vector twice as long doubles the score.
  • Projection: the component of uu along vv is
proj⁡v(u)=u⋅vv⋅v v(v≠0).\operatorname{proj}_v(u) = \frac{u\cdot v}{v\cdot v} \, v \quad (v \neq 0).

The scalar u⋅vv⋅v\frac{u\cdot v}{v\cdot v} says how many copies of vv fit inside the part of uu that points along vv. The leftover

u⊥=u−proj⁡v(u)u_\perp = u - \operatorname{proj}_v(u)

is perpendicular to vv, because

u⊥⋅v=(u−u⋅vv⋅vv)⋅v=u⋅v−u⋅vv⋅v(v⋅v)=0.u_\perp \cdot v = \left(u - \frac{u\cdot v}{v\cdot v}v\right)\cdot v = u\cdot v - \frac{u\cdot v}{v\cdot v}(v\cdot v) = 0.

In dot-product attention, this same operation appears as q⋅kq\cdot k: the score depends on both vector lengths and their relative direction. With nonzero lengths held fixed, a smaller angle gives a larger score; when key lengths differ, the most aligned key need not receive the largest score.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
import numpy as np

u = np.array([2.0, 1.0])
v = np.array([-1.0, 2.0])

dot = float(u @ v)
nu = float(np.linalg.norm(u))
nv = float(np.linalg.norm(v))
cos = dot / (nu * nv)

proj_u_on_v = (dot / float(v @ v)) * v

print("u·v =", dot)
print("cos(theta) =", cos)
print("proj_v(u) =", proj_u_on_v)
print("perp component =", u - proj_u_on_v)
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

StudyExplore the worked calculation, then choose optional practice when you are ready.Keep the same inputs while you inspect what changes and what stays fixed.

Row 0 (A) · unmasked projection.

One query · three sources · one continuous example

A dot product becomes attention

Change the query and follow the same A, B, and C into a mixture. Move at your own pace; no prediction gate is required.

Worked instrument, not a test. These given vectors illustrate one unmasked attention head; they are not learned word meanings.

Change the query · one unmasked row

Shared normalization: m = 1.414; Z = 1.736.

  1. Source Aindex 0
    Dot
    0
    Scaled
    0
    Share
    0.14
    Carry w_Av_A
    [0.28, 0]
  2. Source Bindex 1
    Dot
    2
    Scaled
    1.414
    Share
    0.576
    Carry w_Bv_B
    [0, 1.152]
  3. Source Cindex 2
    Dot
    1
    Scaled
    0.707
    Share
    0.284
    Carry w_Cv_C
    [-0.284, -0.284]

Output o = [-0.004, 0.868]

Compared with q = [2, 1]:

Scores same; shares same; output same.

Worked example, not a test or model run. Given vectors, not learned meanings. Match the query with keys; mix values, not keys. All three sources are allowed in this view.

1 · Match and scaleq · kᵢ → sᵢ = (q · kᵢ) / √2sum(qj * kj for qj, kj in zip(q, k)) / sqrt(2)
2 · Share one denominatorwᵢ = exp(sᵢ − m) / Zexps = [exp(s - max(scores)) for s in scores]weights = [e / sum(exps) for e in exps]
3 · Carry the valuescᵢ = wᵢvᵢ; o = Σᵢ cᵢsum(w * v[j] for w, v in zip(weights, values))

m is the shared maximum scaled score; Z = exp(s_A − m) + exp(s_B − m) + exp(s_C − m). Subtracting the same maximum avoids large exponentials without changing the shares. Each carry is a weighted source value; sum the three contributions coordinate by coordinate for output o.

The reference uses the same current keys and values, with q = [2, 1]. Not every query edit changes the mixture. Solid amber borders mark numerical changes; dashed teal borders mark values unchanged within 1e-12. Labels round to three decimals, not the calculation.

Source A · index 0
k_A = [-1, 2]; v_A = [2, 0]
Source B · index 1
k_B = [1, 0]; v_B = [0, 2]
Source C · index 2
k_C = [0, 1]; v_C = [-1, -1]
Inspect precise numbers and input coordinates

Finite JavaScript numbers before display rounding; −0 is retained where supplied. Tiny allowed shares can underflow to zero; that is not a mask.

q = [2, 1]
A: key=[-1, 2]; value=[2, 0]; dot=0; score=0; share=0.14002924504337802; contribution=[0.28005849008675604, 0]
B: key=[1, 0]; value=[0, 2]; dot=2; score=1.414213562373095; share=0.575975345215362; contribution=[0, 1.151950690430724]
C: key=[0, 1]; value=[-1, -1]; dot=1; score=0.7071067811865475; share=0.28399540974126003; contribution=[-0.28399540974126003, -0.28399540974126003]
m=1.414213562373095; stable denominator=1.736185425829454
output=[-0.00393691965450399, 0.8679552806894639]
Read the full Python witness

This runnable Python witness uses the current controls and the same labels. No NumPy or random inputs are needed.

from math import exp, sqrt

labels = ["A","B","C"]
q = [2,1]
keys = [[-1,2],[1,0],[0,1]]
values = [[2,0],[0,2],[-1,-1]]

d_k = len(q)  # key dimension, NOT number of sources or value width
raw_scores = [sum(qj * kj for qj, kj in zip(q, k)) for k in keys]
scores = [s / sqrt(d_k) for s in raw_scores]
exps = [exp(s - max(scores)) for s in scores]
weights = [e / sum(exps) for e in exps]
output = [sum(w * v[j] for w, v in zip(weights, values))
          for j in range(len(values[0]))]

for label, raw, score, weight in zip(labels, raw_scores, scores, weights):
    print(label, round(raw, 3), round(score, 3), round(weight, 3))
print("output", [round(x, 3) for x in output])

Expected output: [-0.004, 0.868] (rounded to three decimals).

Inspect key and value geometry
Key space: query and source keysQuery q is [2, 1]. Source coordinates and calculations are available in the labelled numeric readouts.xy0k_Ak_Bk_Cq
Key space only. Each grid interval is 1 coordinate unit on both axes. Amber marks the query q you control; ink marks the three fixed keys.
Value space: weighted output and source valuesOutput o is [-0.004, 0.868]. Source coordinates and calculations are available in the labelled numeric readouts.xy0v_Av_Bv_Co
Value space only. Each grid interval is 1 coordinate unit on both axes. Teal marks the mixed output o; the triangle bounds its possible positions.

Step 1 of 4 · Vectors

What does this query have in common with each key?

A, B, and C name the same three sources throughout. Compare q with their keys in key space. Their values are payloads in a different space, not arrows to compare with q.

These are optional inspection controls. The connected scores, shares and mixture stay visible above.

Read the current numbers

Shapes: q and each k have d_k = 2 coordinates. Each v and the output have d_v = 2 coordinates. Equal widths here do not make the spaces identical.

q = [q₁, q₂]; k_A = [−1, 2]; k_B = [1, 0]; k_C = [0, 1]

i names a source; j runs over A, B, C. s is a scaled score, w its share, and o the output. Displayed decimals are rounded; calculations are not.

Keys in key space
SourceKey kq
A[-1, 2][2, 1]
B[1, 0][2, 1]
C[0, 1][2, 1]

Reset example restores the query and first value’s x coordinate only. All other held inputs stay unchanged.

All sources are allowed here; this is not a masked sequence output. Query edits return to row 0; value edits are shared. Other rows and the held mask stay unchanged.

Keep the same Q/K/V; inspect every supplied query row.

Practice, help and export

A study detour counts as consultation for the attempt you leave. Clearing a response or resetting values keeps its help history.

Held example · 3 queries · 3 sources. Started from the A/B/C sequence.

Study history for this visit

These are help exposures, not completion or learning scores. Individual attempts retain their own feedback and help. Reloading the page clears this local history; it does not establish a fresh unaided assessment.

  • Guided attention notebook · worked study · sequence-abc-v1

Start with Guided notebook, the default worked example: use the query qq sliders to follow the same three sources through Vectors → Scores → Weights → Mixture, without a prediction gate. Keys stay fixed; in Mixture, you can also change a value. For the original projection task, open Advanced demonstrations: drag uu and vv, then predict whether the signed projection of uu along vv points with vv, nearly vanishes, or points against vv. Reveal after committing to connect that signed projection with the signs of u⋅vu\cdot v and cos⁡θ\cos\theta.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Dot Product

What is the smallest example that makes Dot Product click without losing the math?

BeforeVector SpacesNow4/4 sections readyTryManipulate one control and predict the visible change.NextScaled Dot-Product Attention & Transformer Layers
Object contextLinear Algebra
ConceptLearner lens

Dot Product

What is the smallest example that makes Dot Product click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inVector Spaces

Bring the mental model from Vector Spaces; this page will reuse it instead of restarting from zero.

Work hereDot Product

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

Carry outScaled Dot-Product Attention & Transformer Layers

The next edge should feel earned: use the demo prediction here before following Scaled Dot-Product Attention & Transformer Layers.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptDot ProductLinear Algebra

Mechanism Storyboard

See the idea move before the page explains it

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

Demo notes open01 / Intuition
Editorial mathematical illustration of two vectors, their angle, and a projection shadow.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Dot Product should make visible.

Visual Inquiry

Make the image answer a mathematical question

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Dot Product easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptDot ProductQuestion

What is the smallest example that makes Dot Product click without losing the math?

concept:linear-algebra/dot-product
Boundary

sources: deisenroth-2020-mml

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · book · 2020Mathematics for Machine LearningDeisenroth, Faisal, and Ong
Located CF editorial boundary

Grounds inner products, vector geometry, and the linear algebra notation reused across attention and optimization.

Used here as

MML introduces inner products as algebraic operations with induced norms, angles, orthogonality, and projections; the page's formulas and demo instantiate those relationships in 2D and co...

Caveat

Applies to finite-dimensional real vectors with v != 0, and to angle/cosine only when both vectors are nonzero. Dot-product magnitude still includes vector lengths; cosine normalizes dire...

Open source

Claim Review

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

Object - ConceptDot ProductQuestion

What is the smallest example that makes Dot Product click without losing the math?

concept:linear-algebra/dot-product
Boundary

sources: deisenroth-2020-mml

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

For vectors u,v in R^n, the dot product sum_i u_i v_i is a coordinate multiply-sum that also encodes geometry: u dot v = ||u||||v||cos(theta), so sign and size track alignment, cosine similarity removes lengths, and proj_v(u) scales v by (u dot v)/(v dot v).
Used here as

MML introduces inner products as algebraic operations with induced norms, angles, orthogonality, and projections; the page's formulas and demo instantiate those relationships in 2D and connect normalized dot...

Local witness
Equation 2
u⋅v=∑i=1nuivi.u \cdot v = \sum_{i=1}^n u_i v_i.
Caveat

Applies to finite-dimensional real vectors with v != 0, and to angle/cosine only when both vectors are nonzero. Dot-product magnitude still includes vector lengths; cosine normalizes direction only. Excludes...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

MML substantively supports the claim: it defines the R^n dot product as x^T y=sum_i x_i y_i, uses inner products to induce norms/angles/orthogonality, defines cos omega=<x,y>/(||x||||y||), and derives projection onto span(b) as (<x,b>/<b,b>)b. With the dot product this is proj_v(u)=(u dot v)/(v dot v)v; local math/code/demo match.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice · Dot Product

Try the idea in your own words

The dot product measures alignment: it connects angles, lengths, and projections, and underlies cosine similarity in ML.

Concept · Current object

Dot Product

Source boundary: sources: deisenroth-2020-mml

Object context and links

Linear Algebra

concept:linear-algebra/dot-product
Choose a task

Explain the mechanism

For Dot Product: What is the smallest example that makes Dot Product click without losing the math? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Local to this page session. Not saved after leaving or reloading.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer does not erase help history. Outside help cannot be verified here.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    This draft and any AI response do not establish mastery. Try a different case later without help; this page has not measured that learning.

    Grounded object roomClose
    Selected object routeAsk from this object; carry one invariant back.sources: deisenroth-2020-mml
    1. ObjectConceptDot Product
    2. PredictBefore revealDot Product prediction
    3. WitnessCompare codeDot Product code witness 1
    4. RoomAsk groundedChecking local snapshot
    ConceptDot ProductLinear Algebra
    Code witness comparisonDot Product code witness 1u = np.array([2.0, 1.0])Prediction before revealDot Product predictionManipulate one control and predict the visible change.
    Grounded room questionWhat is the smallest example that makes Dot Product click without losing the math?Checking local snapshot

    Research Room

    Attach the question to an exact object

    Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptLinear Algebra

    Dot Product

    Anchored question

    What is the smallest example that makes Dot Product click without losing the math?

    Source boundaryInspect source ids: deisenroth-2020-mmlStable content-object key attached
    Role lenses for this object

    These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

    Learner evidence requestAsk what would make "Dot Product" feel predictable rather than familiar.
    Assumption

    Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic.

    Source-checking summary

    Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

    Proposed experiment

    Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

    Next action

    The learner can state the mechanism in their own words

    Evidence4 checks
    PredictionChecking carried observation
    ActionReady for one action
    AILearner handoff ready
    Open source object
    01PredictionChecking browser-local route memory
    02EvidenceChecking for a carried observation
    03BoundaryInspect source ids: deisenroth-2020-mml
    04Next moveSave one next action
    Local action draftNo local draft saved yetExpand only when ready to capture one local next action
    Local action draft

    This draft stays locally in this browser for concept:linear-algebra/dot-product.

    No local draft saved.
    Evidence to inspect
    • Source ids to inspect: deisenroth-2020-mml
    • Definition, prerequisite, and contrast concept links
    • The equation or code witness that makes the concept operational
    • One demo state that shows the invariant instead of a slogan
    What would resolve this
    • The learner can state the mechanism in their own words
    • The learner can name the prerequisite that would repair confusion
    • The learner can predict how the mechanism changes under one perturbation
    Object-attached AI handoff

    I am working in Continuous Function's research reading room. Object: concept - Dot Product Object key: concept:linear-algebra/dot-product Context: Linear Algebra Anchor id: concept/concept-notebook/linear-algebra/dot-product Open question: What is the smallest example that makes Dot Product click without losing the math? Evidence to inspect: - Source ids to inspect: deisenroth-2020-mml - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Dot Product" feel predictable rather than familiar." | assumption: Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: deisenroth-2020-mml" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Dot Product" feel predictable rather than familiar. - Assumption to keep visible: Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

    concept/concept-notebook/linear-algebra/dot-product concept:linear-algebra/dot-product