The neural notebook
← All chapters

IV-17 / Part III · Embeddings

Embedding Geometry and Similarity

Drag two actual feature vectors and distinguish dot product, distance and robust direction cosine, including the zero-vector boundary.

Review the ideas this chapter uses

Two embedding rows are collections of numbers. Before calling them “similar,” we need to say which comparison we mean. Two arrows can point in the same direction yet end far apart; another pair can have a large dot product partly because one arrow is long. A numerical score answers a particular geometric question, not every possible question about the represented objects.

The lookup mechanism comes from IV-16 — Token IDs and Embedding Lookup Tables. Review the dot product in II.4 — Dot product, angle, and orthogonality and the geometric viewpoint in III-18 — Distance Metrics and Curse of Dimensionality when useful. Here two dimensions let us draw every coordinate instead of hiding the calculation inside a large vector.

Move the actual inputs

Compute it yourself

Drag real vectors and compare three scores

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
a0
1
a1
0
b0
1
b1
1
dot1
distance1
normA1
normB1.4142135623730951

dot 1. distance 1. normA 1. normB 1.4142135623730951. Actual editable feature coordinates. These are the model coordinates used by every geometric quantity and by the draggable plane.. a0 1. a1 0. b0 1. b1 1

Actual editable feature coordinates

A=[a0,a1]; B=[b0,b1]

These are the model coordinates used by every geometric quantity and by the draggable plane.

Inputs

a0
1
a1
0
b0
1
b1
1

Outputs

a0
1
a1
0
b0
1
b1
1

Drag the labelled A or B endpoint. The four labelled numeric inputs above are equivalent keyboard controls, including when endpoints overlap. Dragging bounds both coordinates to the visible square [−4,4]; both enter the model in one edit.

Editable vectors A and B in a two dimensional planeHorizontal axis is feature zero; vertical axis is feature one. Solid A and dashed B start at zero. Coordinate values and similarities are also supplied as text.-4-4-2-22244feature 0feature 1AB
Actual endpoint coordinates and projections onto the fixed axes
VectorFeature 0Feature 1
A10
B11

Dot = 1; distance = 1; lengths = 1, 1.4142135623730951.

Cosine = 0.7071067811865475

Inspect tensor shapes and full precision

All computed outputs

dot
1
distance
1
normA
1
normB
1.4142135623730951
a0
1
a1
0
b0
1
b1
1
product0
1
product1
0
difference0
0
difference1
-1
cosineAvailable
1
cosine
0.7071067811865475

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

A

D=2 · float64 · display precision 8 · Actual first editable vector; components are projections onto these fixed axes.

Storage indexValue
01
10

B

D=2 · float64 · display precision 8 · Actual second editable vector; toy coordinates are not learned semantic evidence.

Storage indexValue
01
11

Try B=[0,1] (orthogonal), B=[−1,0] (opposite), and A=[0,0] (cosine unavailable). Reset restores the original vectors and clears exercise grading.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. What does cosine compare for nonzero vectors?
2. For current A=[1,0], B=[1,1], what is their dot product?
3. Reset to A=[1,0], B=[1,1]. What is their Euclidean distance?
4. Reset, then change A from [1,0] to [2,0]. Which prediction is correct?
5. Set A=[0,0]. How should its cosine with B be reported?

A vector is an ordered set of coordinates. A is the first vector, with coordinates [a0,a1]; B is the second, [b0,b1]. Coordinate 0 is horizontal and coordinate 1 is vertical. Each arrow starts at the origin, [0,0], so its endpoint identifies its coordinates. The dotted component lines show projections onto the fixed coordinate axes.

Drag an endpoint, or use the four labelled number inputs with a keyboard. Both methods edit the same four model fields. A drag changes its two coordinates together in one input patch, recomputes every score and starts a fresh trace. Editing also clears exercise grading. Dragging beyond the visible square bounds the pointer’s requested coordinates to [−4,4]; numeric inputs report invalid out-of-range values instead of quietly changing them.

Reset starts at A=[1,0], B=[1,1]. First move B vertically while keeping its horizontal coordinate 1. Watch dot, distance and cosine separately. Then reset and double A’s horizontal coordinate to 2. Predict which scores change before reading the result. The plane, coordinate table and score text all consume the same numerical result, so a picture is never substituted for a calculation.

Three quantities, three questions

The dot product adds products of matching coordinates:

s=A⋅B=a0b0+a1b1.s=A\cdot B=a_0b_0+a_1b_1.

Here s is a signed scalar score, a single number. At the default,

s=(1)(1)+(0)(1)=1+0=1.s=(1)(1)+(0)(1)=1+0=1.

The matching-feature products are the trace’s product0 and product1. If coordinates share units, the dot product has squared units; in this toy example the coordinates are dimensionless. A large positive dot product can reflect aligned directions, large lengths or both.

The Euclidean norm is a vector’s length from the origin. We write double bars for it:

∥A∥=a02+a12,∥B∥=b02+b12.\|A\|=\sqrt{a_0^2+a_1^2},\qquad \|B\|=\sqrt{b_0^2+b_1^2}.

The default lengths are 12+02=1\sqrt{1^2+0^2}=1 and 12+12=2\sqrt{1^2+1^2}=\sqrt2. Length cannot be negative. It is zero exactly for the zero vector in this two-coordinate finite input model.

The Euclidean distance asks how far apart the endpoints are. Subtract corresponding coordinates and take the length:

d(A,B)=∥A−B∥=(a0−b0)2+(a1−b1)2.d(A,B)=\|A-B\| =\sqrt{(a_0-b_0)^2+(a_1-b_1)^2}.

At the default, A−B=[0,−1], so distance is 02+(−1)2=1\sqrt{0^2+(-1)^2}=1. This is not B’s length 2\sqrt2: length compares an endpoint with the origin, while distance compares the two endpoints. The trace records both differences explicitly.

Remove length to compare directions

A unit vector has length 1. For a nonzero A, division by its length gives unit direction A^=A/∥A∥\widehat A=A/\|A\|. The hat means normalized direction. Likewise B^=B/∥B∥\widehat B=B/\|B\|. Their dot product is cosine similarity:

c=A^⋅B^=A⋅B∥A∥∥B∥.c=\widehat A\cdot\widehat B =\frac{A\cdot B}{\|A\|\|B\|}.

The second expression is an identity in real arithmetic for nonzero vectors. The implementation uses scaled component normalization, explained below, rather than literally dividing the stored dot by a product of stored raw lengths. Both represent the same ideal geometric quantity but can behave differently in floating-point arithmetic.

At the default, A^=[1,0]\widehat A=[1,0] and B^=[1/2,1/2]\widehat B=[1/\sqrt2,1/\sqrt2]. Therefore

c=(1)(1/2)+(0)(1/2)=1/2.c=(1)(1/\sqrt2)+(0)(1/\sqrt2)=1/\sqrt2.

In ideal real geometry, cosine is 1 for matching directions, 0 for orthogonal nonzero directions and −1 for opposite directions. Orthogonal means perpendicular: their direction dot product is zero. No angle-in-degrees calculation is needed to make these comparisons. The page neither calls an inverse cosine function nor hides rounding with clipping.

To compare examples by hand, keep A=[1,0]. With B=[2,0], dot is 2, distance is 1 and cosine is 1. With B=[0,1], dot is 0, distance is 2\sqrt2 and cosine is 0. With B=[−1,0], dot is −1, distance is 2 and cosine is −1. Each example answers all three questions rather than collapsing them into one “similarity” label.

Why scale matters to one score but not another

Let k be a positive real scale factor. Multiplying A by k gives

(kA)⋅B=k(A⋅B),∥kA∥=k∥A∥.(kA)\cdot B=k(A\cdot B),\qquad \|kA\|=k\|A\|.

The factor k cancels in the real cosine formula. It does not cancel in raw dot, and it does not generally cancel in distance. For A=[2,0] and the original B=[1,1], dot becomes 2, cosine stays 1/21/\sqrt2, and distance becomes 12+(−1)2=2\sqrt{1^2+(-1)^2}=\sqrt2.

A negative scale factor reverses direction, so the cosine sign reverses too. Scaling by zero destroys direction entirely. “Cosine ignores length” therefore requires the qualification nonzero positive scaling when claiming the direction is unchanged.

The related real identity

∥A−B∥2=∥A∥2+∥B∥2−2(A⋅B)\|A-B\|^2=\|A\|^2+\|B\|^2-2(A\cdot B)

follows by expanding both coordinate squares: (a0−b0)2(a_0-b_0)^2 and (a1−b1)2(a_1-b_1)^2. If both vectors are unit length, it becomes d2=2−2cd^2=2-2c. On unit vectors a larger cosine corresponds to a smaller distance. On arbitrary vectors their lengths also participate, so rankings by dot, cosine and distance need not agree. The page evaluates distance directly from differences; it does not subtract nearly equal norm squares to recover it.

Coordinates depend on the chosen axes

A coordinate is a projection onto a selected basis axis. Rotate both default vectors by a quarter turn: A=[1,0] becomes [0,1], while B=[1,1] becomes [−1,1]. Dot remains 1, lengths remain 1 and 2\sqrt2, and distance remains 1. The coordinate projections visibly change.

This is a common rotation of both vectors, not a rotation of just one. In real Euclidean geometry it preserves dot and distance because it preserves lengths and relative directions. Finite arithmetic can introduce rounding for more general rotations. We use this exact quarter-turn example so you can inspect the changed coordinates with ordinary integer arithmetic.

A particular embedding coordinate is consequently not an axis-independent meaning label. Even if a learned system used these vectors, an equivalent choice of basis could change individual coordinates while preserving these geometric relationships. A small two-dimensional drawing is useful for learning operations; it does not prove a linguistic explanation.

Zero and very small vectors deserve explicit treatment

Set A=[0,0]. Its dot with B is zero and its distance from B is B’s length. But its unit direction would require division by zero. Cosine is therefore unavailable, rather than a numerical zero that could be mistaken for a perpendicular direction. The result keeps cosineAvailable=0 and omits the cosine field. The trace and visible status state the reason while preserving the defined dot and distance.

All inputs are finite binary64 numbers between −4 and 4. Binary64 is the stored number format, with finite precision and a smallest positive subnormal value. Subnormal numbers are exceptionally small values with reduced relative precision. Squaring such coordinates can underflow to zero; underflow means a nonzero real result is too small for the stored representation. Thus raw dot can be zero for tiny aligned vectors even when their direction cosine is near 1.

The program uses hypot, a length operation that avoids naively squaring tiny or large inputs. Even so, a raw length in the subnormal range can round substantially. If both coordinates are the smallest positive representable number, the real length is that number times 2\sqrt2, but the stored length may round back to that same smallest number. Dividing directly by that rounded length would give direction components [1,1], whose squared length is 2.

Instead, for each nonzero vector choose m=max⁡(∣a0∣,∣a1∣)m=\max(|a_0|,|a_1|), where vertical bars mean absolute value. Form v=A/mv=A/m, compute q=hypot⁡(v0,v1)q=\operatorname{hypot}(v_0,v_1), then set A^=v/q\widehat A=v/q. The largest scaled coordinate has magnitude 1, so this normalization avoids the raw tiny-length problem. Apply the same procedure to B, then multiply unit components and add. The trace exposes each scale, scaled coordinate and scaled norm. Raw dot and raw lengths remain their actual binary64 values; they are not retroactively replaced to force an identity.

Read the implementation and check your interpretation

The Python source uses the same explicit products, differences and scaled unit-direction order. It provides no semantic labels and no hidden angle calculation. The four required state fields reject missing, extra and nonfinite values.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV17: actual dot, lengths, distance and robust direction cosine."""
import math
from embedding_reference import Trace, finite, fixed_state, guarded, run, tensor

DEFAULT_IV17 = dict(a0=1, a1=0, b0=1, b1=1)


@guarded
def derive_iv17(state):
    """A zero vector leaves cosine absent while other quantities remain defined."""
    s = fixed_state(state, DEFAULT_IV17, {key: (-4, 4) for key in DEFAULT_IV17})
    trace = Trace()
    trace.add("coordinates", "Actual editable feature coordinates", "A=[a0,a1]; B=[b0,b1]", "These are the actual model coordinates.", s, s)
    product0, product1 = finite(s["a0"] * s["b0"], "product0"), finite(s["a1"] * s["b1"], "product1")
    dot = finite(product0 + product1, "dot")
    trace.add("dot", "Dot product", "dot=a0*b0+a1*b1", "Add signed matching-component products.", s, dict(product0=product0, product1=product1, dot=dot))
    normA, normB = finite(math.hypot(s["a0"], s["a1"]), "normA"), finite(math.hypot(s["b0"], s["b1"]), "normB")
    trace.add("norms", "Vector lengths", "norm=hypot(coordinates)", "Raw binary64 lengths can round in the subnormal range.", s, dict(normA=normA, normB=normB))
    difference0, difference1 = finite(s["a0"] - s["b0"], "difference0"), finite(s["a1"] - s["b1"], "difference1")
    distance = finite(math.hypot(difference0, difference1), "distance")
    trace.add("distance", "Euclidean distance between endpoints", "distance=hypot(a0-b0,a1-b1)", "Length of the actual difference vector.", s, dict(difference0=difference0, difference1=difference1, distance=distance))
    if normA == 0 or normB == 0:
        trace.add("cosine", "Cosine unavailable: a zero vector has no direction", "cosine unavailable when a norm is zero", "Unavailable is not orthogonal: omit the cosine value.", dict(normA=normA, normB=normB), dict(cosineAvailable=0))
    else:
        # Normalize the scaled direction, not a severely rounded raw tiny length.
        scaleA, scaleB = max(abs(s["a0"]), abs(s["a1"])), max(abs(s["b0"]), abs(s["b1"]))
        scaledA0, scaledA1 = finite(s["a0"] / scaleA, "scaledA0"), finite(s["a1"] / scaleA, "scaledA1")
        scaledB0, scaledB1 = finite(s["b0"] / scaleB, "scaledB0"), finite(s["b1"] / scaleB, "scaledB1")
        scaledNormA, scaledNormB = finite(math.hypot(scaledA0, scaledA1), "scaledNormA"), finite(math.hypot(scaledB0, scaledB1), "scaledNormB")
        unitA0, unitA1 = finite(scaledA0 / scaledNormA, "unitA0"), finite(scaledA1 / scaledNormA, "unitA1")
        unitB0, unitB1 = finite(scaledB0 / scaledNormB, "unitB0"), finite(scaledB1 / scaledNormB, "unitB1")
        cosine = finite(finite(unitA0 * unitB0, "normalized product0") + finite(unitA1 * unitB1, "normalized product1"), "cosine")
        trace.add("cosine", "Cosine of nonzero directions", "scale=max(abs(coords)); scaled=coords/scale; unit=scaled/hypot(scaled); cosine=unitA0*unitB0+unitA1*unitB1",
                  "Preserve actual raw lengths and dot; use scaled unit directions for cosine. No clipping or angle API.",
                  dict(normA=normA, normB=normB, scaleA=scaleA, scaleB=scaleB, scaledA0=scaledA0, scaledA1=scaledA1, scaledB0=scaledB0, scaledB1=scaledB1, scaledNormA=scaledNormA, scaledNormB=scaledNormB, unitA0=unitA0, unitA1=unitA1, unitB0=unitB0, unitB1=unitB1), dict(cosineAvailable=1, cosine=cosine))
    return trace.result(dict(dot=dot, distance=distance, normA=normA, normB=normB), [
        tensor("A", [2], ["D"], [s["a0"], s["a1"]], "First actual vector."),
        tensor("B", [2], ["D"], [s["b0"], s["b1"]], "Second actual vector; no semantic claim."),
    ])


if __name__ == "__main__":
    run(derive_iv17, DEFAULT_IV17)
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Shared source for IV16–18: strict scalar state, detached records and JSON CLI.

Keep this file beside the three lesson programs. NumPy holds real float64 tensor
storage; explicit scalar operations keep the lesson's order of arithmetic visible.
Authored during the runtime hold; no execution or validation is claimed.
"""
import argparse
from functools import wraps
import json
import math
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    if isinstance(value, (bool, np.bool_)) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = float(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not math.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def fixed_state(state, defaults, bounds, integers=()):
    # Full replacement, including inactive slots: no coercion, defaults or clipping.
    if type(state) is not dict or set(state) != set(defaults):
        raise NumericalFault("INVALID_INPUT", "Provide exactly every named scalar field, including inactive slots.")
    result = {}
    for key in defaults:
        value = finite(state[key], key)
        low, high = bounds[key]
        if value < low or value > high:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {low} and {high}.")
        if key in integers and not value.is_integer():
            raise NumericalFault("INVALID_INPUT", f"{key} must be an integer choice.")
        result[key] = int(value) if key in integers else value
    return result


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
    return call


def numbers(values):
    return {key: finite(value, key) for key, value in values.items()}


class Trace:
    def __init__(self):
        self.outputs = {}
        self.steps = []

    def add(self, identifier, label, equation, explanation, inputs, values):
        inputs, values = numbers(inputs), numbers(values)
        self.outputs.update(values)
        self.steps.append({"id": identifier, "label": label, "equation": equation,
                           "explanation": explanation, "inputs": inputs, "outputs": values})

    def result(self, summary, tensors):
        return {"status": "defined", "outputs": numbers({**summary, **self.outputs}),
                "steps": self.steps, "tensors": tensors}


def tensor(identifier, shape, axes, values, provenance, dtype="float64"):
    array = np.asarray(values, dtype=np.float64)
    if array.size != math.prod(shape) or len(shape) != len(axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage must match the named dimensions.")
    flat = [finite(v, identifier) for v in array.reshape(-1)]
    if dtype == "int32":
        if any(not v.is_integer() for v in flat):
            raise NumericalFault("INVALID_INPUT", "IDs must be integers.")
        flat = [int(v) for v in flat]
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": dtype,
            "values": flat, "provenance": provenance, "precision": 8}


EMBEDDING_DEFAULTS = dict(e00=1, e01=0, e10=0, e11=1, e20=1, e21=1)
VOCABULARY = ("oak", "river", "sun")


def embedding_rows(s):
    return np.array([s["e00"], s["e01"], s["e10"], s["e11"], s["e20"], s["e21"]], dtype=np.float64)


def sigmoid(z):
    # Stable sign branch, evaluated in stored binary64; positive tails may round to 1.
    z = finite(z, "sigmoid input")
    if z >= 0:
        return 1 / (1 + math.exp(-z))
    exponential = math.exp(z)
    return exponential / (1 + exponential)


def run(derive, defaults):
    """No state argument: defaults. Full JSON object: replacement. '-': stdin."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            result = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            result = derive(state)
    else:
        state = dict(defaults)
        result = derive(state)
    print(json.dumps(result, allow_nan=False, separators=(",", ":")))

Keep both files together. The CLI accepts defaults with no argument, a complete replacement JSON object, or - for standard input.

The five graded lab questions distinguish direction, a current dot product, default distance, scaling and zero-vector unavailability. Keep those distinctions when using a geometric score elsewhere: specify the comparison, inspect lengths when relevant, and treat coordinates as basis-dependent features. Next, IV-18 — How Embeddings Learn From Gradients introduces a task and a loss so embedding coordinates can actually learn rather than simply being moved by hand.