Forward Deployed EngineeringAI EngineeringEmbeddings and Attention

Why is the dot product the similarity score in attention and embeddings, and when should you normalize to cosine?

Question 42 of 73 · Updated

On this page

Interview-ready answer#

The dot product is a natural compatibility score because it measures how strongly two vectors align while also accounting for their magnitudes. Algebraically, q · k = Σ qᵢkᵢ; geometrically, q · k = ||q|| ||k|| cos θ. It is differentiable, inexpensive to compute using matrix multiplication, and lets a learned representation assign positive or negative contributions through its coordinates.

In Transformer attention, queries and keys are learned projections. Their dot product expresses how compatible a query is with a key in the learned attention space. Standard scaled dot-product attention divides the score by the square root of the key dimension, applies the attention mask, and then applies softmax. The scaling controls the typical variance of logits as dimension grows; it does not normalize vectors to unit length.

For embeddings, I would choose the similarity metric that matches the embedding model's training and documented retrieval contract. Cosine similarity removes the effect of vector magnitude, so it is appropriate when direction is the intended signal and length is an unwanted source of variation. But if norms carry information that the model was trained to use, normalization can hurt retrieval quality. On unit-normalized embeddings, cosine and dot product are identical, and Euclidean distance gives the same nearest-neighbor ranking.

I would not replace dot-product attention inside a pretrained model with cosine attention without retraining or appropriate calibration and evaluation. That changes the learned logits and their softmax distribution.

1. Mathematical intuition: what the score measures#

For two real, nonzero vectors a and b of dimension d:

  • Dot product: a · b = Σ(aᵢbᵢ), for i from 1 to d.

The geometric identity a · b = ||a||₂ ||b||₂ cos θ separates the dot product into direction and magnitude. Cosine is defined for nonzero vectors; the dot product is also defined for zero vectors.

Geometric relationshipCosineInterpretation
Same direction1Maximum angular alignment
Acute angleBetween 0 and 1Positive angular alignment
Orthogonal0No signed linear alignment
Obtuse angleBetween -1 and 0Negative angular alignment
Opposite direction-1Maximum angular opposition

These are geometric statements, not guarantees about language meaning. Orthogonal embeddings are not necessarily semantically unrelated, and negative cosine does not necessarily mean two sentences contradict each other. Training determines how semantic relationships are represented.

One useful intuition is projection: a · b equals the length of a multiplied by the signed scalar projection of b onto the direction of a. In a learned feature space, dimensions need not correspond to individually interpretable concepts; the aggregate compatibility score can be useful even when the individual coordinates are not human-readable.

2. A numerical example where rankings change#

Let the query be q = (1,0), and consider candidates A = (1,0) and B = (3,4).

CandidateNormDot product with qCosine with q
A111
B530.6

Raw dot product ranks B first because its projection onto the query direction is larger. Cosine ranks A first because its direction matches the query exactly.

Neither ranking is inherently correct without a task definition and model contract. If the model was trained so document norms contribute useful relevance information, B might deserve the higher score. If only angular similarity is intended, A is the more aligned result.

Multiplying a candidate vector by a positive scalar multiplies its dot product with the query by that scalar but leaves its cosine unchanged. Multiplication by a negative scalar reverses its direction and therefore changes the cosine sign. A zero scaling factor makes cosine undefined.

For a fixed nonzero query, normalizing only the query multiplies every raw dot-product score by the same positive constant and does not change the ranking. Normalizing document vectors can change the ranking because their magnitudes differ. To obtain actual cosine scores by inner product, normalize both query and documents.

3. Why dot product is a useful learned compatibility function#

A dot product is bilinear: it is linear in either input when the other is fixed. Its gradients are simple: the gradient with respect to a is b, and the gradient with respect to b is a. This is useful in optimization because the encoder can learn representations whose dot products favor desired pairs.

Dot products can also be evaluated for many queries and candidates at once with optimized matrix multiplication. For a query matrix Q of shape n by d and key matrix K of shape m by d, QKᵀ is an n by m matrix of pairwise scores. That fits GPU and accelerator execution well.

A dot product does not imply that the embedding space was learned using an angular objective. Models may use different contrastive losses, temperatures, normalization schemes, asymmetric query/document encoders and training distributions. The score must match that design.

Other compatibility functions exist, including additive attention, learned bilinear scores, distances and neural cross-encoders. Dot product is a practical and expressive choice when the surrounding model learns useful projections; it is not the only mathematically valid similarity function.

4. Scaled dot-product attention#

For one attention head, suppose Q and K have key/query dimension and V has value dimension . The usual operation is:

LaTeX

Here M represents an additive attention mask: disallowed positions receive negative infinity in the idealized formulation, and allowed positions receive zero. Architectures may also incorporate positional biases or other transformations. Softmax operates over key positions for each query.

Loading diagram…

This diagram depicts self-attention for one head. Cross-attention obtains its queries and keys/values from different representations. Multi-head attention applies the relevant operations for each head and combines their outputs according to the architecture.

The query asks which information is useful for the current position, the key provides a learned compatibility representation for a candidate position, and the value provides the information to be combined. The score is not directly a statement of document relevance or token importance in an interpretability sense.

Why divide by the square root of dimension?#

Under the simplifying assumption that the query and key components are independent, zero-mean random variables with unit variance, each product qᵢkᵢ has mean zero and variance one. Summing independent products gives a dot product with variance and standard deviation √d_k.

Dividing by √d_k yields variance one under these assumptions. Without scaling, increasing the dimension tends to increase the typical magnitude of the logits. Very large differences in softmax logits can produce nearly saturated distributions and small gradients for many alternatives.

Real learned activations are not necessarily independent or unit variance. The derivation explains the design intuition, not an exact guarantee about the distribution of every attention layer.

Worked attention example#

Use q = (2,0), k₁ = (1,0), k₂ = (0,1), v₁ = (10,0), v₂ = (0,10), with = 2 and both keys permitted.

The dot products are 2 and 0. Scaled logits are √2 and 0. Softmax weights are approximately 0.8044 and 0.1956. The weighted output is approximately (8.044,1.956).

Using unscaled logits instead produces weights approximately 0.8808 and 0.1192. Using cosine alone gives logits 1 and 0, producing approximately 0.7311 and 0.2689. These are different operations and different outputs even though all three score choices prefer the first key.

5. Dimension scaling is not L2 normalization#

OperationFormulaPurpose
Scaled dot product(q · k)/√d_kAdjust typical logit scale based on dimension
Cosine(q · k)/(
Temperature scalingscore/τ for positive τAdjust softmax sharpness
Layer normalizationNormalize features using their mean and variance, with applicable affine parametersStabilize learned hidden representations

Standard Transformer attention uses learned query/key magnitudes as part of its compatibility function. Scaling by a fixed dimension-dependent constant preserves their effect. Unit normalization divides by per-vector norms and can remove learned magnitude information.

Some architectures deliberately normalize queries and keys or use cosine-style attention with a learned or fixed logit scale. They must be trained or evaluated for that operation. A cosine range of [-1,1] alone may give softmax too little contrast for certain workloads with many keys; suitable temperature or logit scaling depends on the architecture.

LayerNorm and RMSNorm applied elsewhere in a model do not imply that all projected query and key vectors are unit-normalized. Learned projections can change both direction and magnitude.

6. Dot product, cosine and Euclidean retrieval#

For unit vectors û and v̂:

  • û · v̂ = cos(u,v).

Consequently, maximizing cosine, maximizing inner product on normalized vectors, and minimizing squared Euclidean distance on normalized vectors produce the same exact ranking, apart from numerical effects and ties. With a fixed query and equal candidate norms, even raw dot-product and Euclidean rankings are equivalent. With varying norms they need not agree.

MetricAppropriate whenCaveat
Raw inner productThe model's training contract uses magnitude-sensitive scoresLarger candidate norms can influence ranking
CosineThe model specifies cosine or angular similarity is the intended signalRemoves potentially useful norm information; undefined for zero vectors
Euclidean distanceAbsolute positions and magnitudes in the trained space matterNot generally equivalent to cosine without suitable normalization

Vector databases may expose inner product as a similarity, negative inner product as a distance, or cosine distance such as 1 − cosine. A higher-is-better score is not interchangeable with a lower-is-better distance. Check the chosen database operator and index metric, score conventions and normalization behavior rather than assuming all engines use the same definitions.

Exact ranking equivalence is not a guarantee that approximate nearest-neighbor indexes return identical results. Quantization, floating-point representation, search parameters, index construction and approximate search can affect recall.

7. How to choose a retrieval metric#

Loading diagram…

Prefer the embedding model's documented similarity function and query/document encoding instructions. If the contract is ambiguous, use a controlled evaluation rather than automatically choosing cosine because it is familiar.

For a customer RAG deployment, compare recall@k, MRR or nDCG when labels support those measures, answer grounding and citation correctness on end-to-end tasks, latency and index resource use. Analyze cases where high-norm documents dominate inner-product retrieval and cases where cosine removes useful relevance signal. Do not assume that vector norm is confidence, popularity or relevance without evidence from training or evaluation.

Normalize indexed vectors at ingestion when appropriate, and apply the same intended preprocessing at query time. Do not mix embeddings generated by incompatible model versions or mismatched metrics. If changing the metric or normalization invalidates an existing index's assumptions, rebuild or migrate using a versioned index, compare against a reference, and retain a rollback path.

A cosine score is not a calibrated probability. A fixed threshold such as 0.8 may be inappropriate across models, languages, domains or embedding dimensions. Calibrate thresholds with representative labeled data and account for false positives, false negatives and abstention behavior.

8. Tested Python implementations#

The following dependency-free examples use finite real numeric components represented by ordinary Python sequences. They demonstrate exact score definitions for moderate values and stable normalization and softmax techniques. They are educational CPU implementations, not high-throughput vector-search or attention kernels.

PYTHON
from math import fsum, hypot, sqrt, exp, isfinite def dot(a, b): if not a or len(a) != len(b): raise ValueError('nonempty equal-length vectors required') if not all(isfinite(x) for x in (*a, *b)): raise ValueError('finite components required') return fsum(x*y for x, y in zip(a, b)) def unit(a): if not a or not all(isfinite(x) for x in a): raise ValueError('nonempty finite vector required') scale = max(abs(x) for x in a) if scale == 0: raise ValueError('zero vector has no direction') scaled = [x/scale for x in a] norm = hypot(*scaled) return [x/norm for x in scaled] def cosine(a, b): return dot(unit(a), unit(b))

The normalization first divides by the largest absolute component, which reduces overflow and underflow risk when computing the norm. The dot helper checks vector lengths and finite components. Finite inputs do not guarantee finite products or sums: extremely large raw dot products can still overflow. Floating-point results can deviate slightly from mathematical identities, including the [-1,1] cosine range; apply an appropriate tolerance or carefully justified clipping if a downstream operation requires it.

PYTHON
q = [1, 0] a, b = [1, 0], [3, 4] assert dot(q, b) > dot(q, a) assert cosine(q, a) > cosine(q, b)

One-query scaled dot-product attention#

PYTHON
def attend(q, keys, values, allowed): if not q or not keys or len(keys) != len(values) or len(keys) != len(allowed): raise ValueError('invalid attention shapes') width = len(values[0]) if not width or any(len(v) != width for v in values): raise ValueError('inconsistent value widths') if any(not isfinite(x) for v in values for x in v): raise ValueError('finite values required') scores = [dot(q, k)/sqrt(len(q)) for k in keys] active = [s for s, ok in zip(scores, allowed) if ok] if not active: raise ValueError('all keys masked') peak = max(active) terms = [exp(s-peak) if ok else 0.0 for s, ok in zip(scores, allowed)] total = fsum(terms) weights = [t/total for t in terms] out = [fsum(w*v[j] for w, v in zip(weights, values)) for j in range(width)] return weights, out

Use this with the imports and dot helper above. The allowed argument is a boolean sequence; True means the key is eligible. Subtracting the largest permitted score before exponentiation preserves softmax mathematically and avoids overflow in exponentiation when logits are finite. Tiny probabilities can underflow to zero in floating-point arithmetic. The helper rejects an entirely masked row rather than silently returning undefined weights; production runtimes may define a different explicit policy. It does not support arbitrary additive biases, dropout, batched heads or gradients.

For d-dimensional vectors, dot and cosine use O(d) arithmetic work; the educational code uses O(d) temporary memory for validation and normalization. For m keys of dimension and values of dimension , this single-query attention performs O(m( + )) arithmetic work, using O(m + + ) additional storage under the usual unit-cost arithmetic model, excluding the inputs. Full dense self-attention over n positions has quadratic pairwise scoring work in n and a naive score matrix of O(n²) elements per head. Optimized exact attention implementations can avoid materializing the entire matrix by tiling and using online softmax; this does not make ordinary dense attention's pairwise arithmetic linear.

Local verification#

Python 3.13.5 executed the exact implementations above.

  • 15,376 ordered vector-pair scenarios using every nonzero three-dimensional integer vector with components from -2 through 2. Each checked the dot product against integer arithmetic, cosine against a 50-digit Decimal reference and cosine invariance under positive rescaling.
  • 2,187 attention scenarios across every pair of two-dimensional keys and query from the nine vectors with coordinates in {-1,0,1}, and all three nonempty masks for two keys. Each checked weights, their sum and value outputs against an independent direct-exponentiation reference.
  • Nine invalid-input scenarios covering empty, mismatched or nonfinite vectors, zero norm, inconsistent attention shapes and all-masked keys.
  • Two numerical stability scenarios with large finite logits and vectors of very different magnitudes.
  • Two additional scenarios verifying the ranking reversal in the worked example and the normalized squared Euclidean distance identity.

All 17,576 test scenarios passed. These are synthetic local mathematical correctness tests, not GPU performance benchmarks or retrieval-quality evaluations on a customer's corpus.

9. Production engineering considerations#

For attention, preserve the architecture's trained scaling, bias, masking and precision contract. Use a compatible optimized attention implementation and test it against a trusted baseline, especially for long contexts, low precision, padding and masked positions. The query-key dot product is only one part of the operation; value combination and subsequent learned layers affect the output.

For retrieval, store the encoder version, dimension, metric, normalization policy and relevant metadata. Guard against malformed, nonfinite or zero-norm embeddings. Choose an explicit policy for zero vectors, such as rejecting or quarantining invalid embeddings rather than arbitrarily assigning a cosine score. Quantization can perturb norms and directions, so validate approximate index recall and threshold behavior after quantization.

Do not use similarity scoring as access control. Filter or constrain retrieval using authoritative permissions and tenant scope, and verify that returned documents are authorized before using them in model context. High similarity does not grant access to a source.

In a real FDE engagement, distinguish four questions: whether embeddings represent the customer task well, whether the chosen metric respects the model's training, whether the approximate index retrieves the intended neighbors, and whether those neighbors improve the final answer. Optimizing the score calculation without checking these other layers can make a system faster but not more useful.

Likely interviewer follow-ups#

Why is cosine always between -1 and 1? The Cauchy–Schwarz inequality bounds the magnitude of the dot product by the product of the two norms. Dividing by the positive norm product gives the stated bound for nonzero vectors.

Is dot product itself a normalized similarity? No. It is unbounded across unrestricted real vectors. Its magnitude reflects both alignment and vector lengths.

Why does a fixed positive scaling of all logits change attention? It preserves their rank but changes their relative softmax probabilities. Retrieval ranking and attention weighting are different operations.

Should you normalize embeddings before indexing? Do so when the model and metric require it or a validated comparison supports it. If both query and documents have unit norm, an inner-product index can implement cosine ranking.

Does softmax make vectors unit length? No. It produces nonnegative weights summing to one over the chosen dimension. L2 normalization produces a vector whose Euclidean norm is one.

Can cosine replace dot product in an existing Transformer? Not as a transparent drop-in change. It alters logits and their weighting. A model explicitly designed for normalized attention may use cosine or a related operation with appropriate scaling.

What if all keys are masked? Define the runtime's expected behavior explicitly. Avoid applying ordinary softmax to an all-negative-infinity row without special handling.

Interview takeaway#

Dot product combines angular alignment and magnitude, making it a useful learned compatibility function and an efficient matrix operation. Cosine removes magnitude; use it when that matches the embedding model and task. Standard attention's square-root dimension scaling controls logit scale rather than normalizing vectors. Preserve the trained contract and verify retrieval rankings, numerical stability and downstream quality before changing metrics.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models