IV-16 / Part III · Embeddings
Token IDs and Embedding Lookup Tables
Follow discrete vocabulary IDs into actual editable embedding rows, with named batch, position and feature axes.
Review the ideas this chapter uses
A neural network needs numerical features, but a vocabulary entry is initially a label. Giving “sun” the number 2 identifies an entry; it does not explain what sunlight is, or make the word twice as large as another word. An embedding lookup solves a smaller, precise problem: use an integer address to retrieve a vector of adjustable numbers.
A vector is an ordered collection of coordinates. An embedding table is a matrix containing one such vector per vocabulary entry. For the shape language used below, revisit IV-04 — A Trainable MLP Forward Pass. For how a matrix organizes rows and columns, see I.8 — Indexed quantities and summation. You only need to follow which row is selected and which numbers are copied.
Start by changing one shared row
The fixed illustrative vocabulary is ['oak','river','sun'], with integer IDs 0, 1 and 2 respectively. A token ID here means one of those discrete addresses. This is a deliberately supplied mapping, not a tokenizer: the page does not split arbitrary text, call a service or claim these entries represent an actual model’s vocabulary.
Select actual embedding rows
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
- e00
- 1
- e01
- 0
- e10
- 0
- e11
- 1
- e20
- 1
- e21
- 1
- B
- 1
- T
- 3
- i00
- 2
- i01
- 0
- i02
- 2
- i10
- 1
- i11
- 2
- i12
- 0
B 1. T 3. D 2. lookupCount 3. Gather batch 0, position 0, feature 0. The integer ID selects one parameter row. Repeated IDs copy the same row values into detached output storage; the magnitude of the ID is not a multiplier.. x000 1
Gather batch 0, position 0, feature 0
X[b,t,d]=E[ID[b,t],d]
The integer ID selects one parameter row. Repeated IDs copy the same row values into detached output storage; the magnitude of the ID is not a multiplier.
Inputs
- b
- 0
- t
- 0
- ID
- 2
- row
- 2
- feature
- 0
- rowValue
- 1
Outputs
- x000
- 1
| ID | Vocabulary entry | Feature 0 | Feature 1 |
|---|---|---|---|
| 0 | oak | 1 | 0 |
| 1 | river | 0 | 1 |
| 2 | sun | 1 | 1 |
| Batch | Position | ID / entry | Retrieved feature 0 | Retrieved feature 1 |
|---|---|---|---|---|
| 0 | 0 | 2 / sun | 1 | 1 |
| 0 | 1 | 0 / oak | 1 | 0 |
| 0 | 2 | 2 / sun | 1 | 1 |
Each table cell is read from the same derived tensors as the trace. Output copies do not become additional trainable parameter rows.
Inspect tensor shapes and full precision
All computed outputs
- B
- 1
- T
- 3
- D
- 2
- lookupCount
- 3
- x000
- 1
- x001
- 1
- x010
- 1
- x011
- 0
- x020
- 1
- x021
- 1
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
ids
B=1 × T=3 · int32 · display precision 8 · Validated discrete IDs; vocabulary 0=oak, 1=river, 2=sun.
| Storage index | Value |
|---|---|
| 0 | 2 |
| 1 | 0 |
| 2 | 2 |
E
Vocab=3 × D=2 · float64 · display precision 8 · One parameter row per vocabulary entry; no semantic claim.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 0 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
X
B=1 × T=3 × D=2 · float64 · display precision 8 · Feature-last row-major gathered copies, not aliases of E.
| Storage index | Value |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
| 5 | 1 |
Reset to [sun,oak,sun]. Edit the sun row, then switch B to 2 to expose a second sequence. All six ID controls are validated even when their positions are inactive.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Reset gives the sequence [sun,oak,sun]. Find row 2, feature 0 and change its value from 1 to 2. Both sun positions now retrieve [2,1]; the oak position still retrieves [1,0]. Follow the trace to a gather step for each sun position. There are two uses of one parameter row, rather than two independent sun parameters.
Next set batch size B to 2. A second sequence becomes active without changing the vocabulary. Change its middle ID and watch just that position select a different row. These edits reveal the two separate kinds of choice: an ID chooses where to read, while an embedding coordinate chooses what value lives there. Reset restores every coordinate, shape choice and ID, and clears exercise answers.
Give every dimension a job
The letter names the embedding matrix. Its default value is
Here is the vocabulary size, the number of rows. is the feature dimension, the number of coordinates in a row. Thus has shape [Vocab=3,D=2]. Feature 0 and feature 1 are column labels. They are not names such as “brightness” or “tree-ness”; these hand-set numbers have no learned semantic interpretation.
A tensor is an array with a declared shape and axis meanings. The input IDs form a tensor with shape [B,T]: B counts batch members, and T counts positions in each sequence. A batch is a group of examples processed together. A position identifies an entry within one example. These examples all have the same selected T; this lesson has no padding or variable-length masking.
The result is called and has shape [B,T,D]. At each batch member and position, it stores a complete D-coordinate vector. “Feature-last” means D is the final axis. It does not mean the last feature alone is returned. With B=1 and T=3, there are three selected rows and six output coordinates.
Subscripts in name one batch index b, position t and feature index d. All indices start at zero. The default ID tensor is , where I denotes integer IDs, not the first book. The lookup rule is
First read the integer ; use it as E’s row index; keep the feature index d. This is indexing, so there is no multiplication by the ID. The ID tensor has dtype int32, meaning integer storage; E and X have dtype float64, meaning binary64 numerical coordinates. Declaring types helps prevent treating an address as a continuous feature.
Work through every default output
At batch 0, position 0, the ID is 2. The two reads are
At position 1, the ID is 0, giving
At position 2, ID 2 selects the same parameter row again:
Putting the six values into their named dimensions produces
The outer brackets contain the one batch member. Inside it are three position rows; inside each position row are two features. The summary’s lookup count is , the number of rows retrieved, not the number of scalar coordinates. The scalar count is . Inspect the tensors to distinguish those quantities.
Storage is row-major: the last index changes fastest. The flattened X buffer is [1,1,1,0,1,1], in the order position 0 feature 0, position 0 feature 1, then position 1, and so on. In general the flattened address is . This address describes result storage; it does not replace the vocabulary address used to read E.
Why indexing has the same result as selection
One way to describe lookup algebraically is with a one-hot row: a row containing one 1 and otherwise zeros. ID 2 corresponds to , shape [1,3]. Multiplying by the embedding matrix gives
The multiplication is legal because q’s three columns match E’s three rows. Only the selected row survives. An actual gather can retrieve that row directly, without allocating a large one-hot vector. This explanation establishes the selection rule; the live model uses the direct reads shown in its trace.
Earlier neuron calculations often wrote one feature vector as a column . Here a token’s features occupy a row . The same coordinates can be viewed as the column , where superscript T means transpose. A later output row can produce a scalar using , or equivalently . Always check orientation before multiplying; changing storage convention does not change a feature’s meaning or values.
Shared parameters, detached output copies
Suppose the two sun positions both appear in one sequence. They refer to row 2 in the parameter table, the collection of adjustable numbers. The result tensor nevertheless stores independent copies of the selected values. Changing a saved output buffer must not secretly rewrite E or another saved trace snapshot.
These statements are compatible: parameters are shared by identity, while forward output storage is detached. On a fresh computation, a row edit is read by every matching position. Later, during learning, contributions from all uses must be added back to that same parameter row. A copy is a record of a read, not a new trainable vocabulary entry.
Lookup alone performs no learning. Changing an ID in this interface changes the supplied input data. Editing E changes supplied parameter values. Neither edit is a gradient update inferred from examples. The next learning chapter will introduce a loss and show what actually changes E automatically through a specified update rule.
What can go wrong at this boundary?
There are only three legal IDs: integer 0, 1 and 2. ID 3 is not a fourth row; ID −1 is not an instruction to count backward; ID 1.5 is not halfway between two entries. Each is invalid. Rounding, wrapping or silently clipping would substitute different data for the data the learner entered.
All fourteen fields are required: six embedding coordinates, B, T and six ID slots. Coordinates must be finite numbers in [−4,4]; B is integer 1 or 2; T is integer 1, 2 or 3. Every ID slot is validated even when its batch or position is inactive. This prevents hiding invalid data until a shape change exposes it. Extra, missing, inherited-only and nonnumeric fields are rejected rather than guessed.
A valid entry can be a zero row, a negative row or identical to another row. Two different IDs may retrieve equal vectors. Equality of values does not merge their parameter identities: editing one row still affects only positions selecting that row. Renaming labels alone changes no coordinates. To renumber IDs while preserving each entry’s vector, permute both the mapping and E’s rows consistently. Changing the mapping alone can select a different vector.
Finally, integer IDs have no derivative in this model. Small real-valued changes to an ID are not a supported input operation. The learnable coordinates of E are different: they are continuous parameters, and later we can differentiate a loss with respect to them.
Read the actual Python and its helper
The program below validates the full state before gathering any active position. Its nested loops follow b, t and d in the same order as the worked example. embedding_rows creates NumPy float64 storage; float(E[...]) reads a coordinate into detached result storage. Tensor records then name the dimensions explicitly, rather than relying on an ambiguous nested list alone.
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.
"""IV16: exact discrete row selection into detached feature-last tensor storage."""
from embedding_reference import EMBEDDING_DEFAULTS, Trace, embedding_rows, fixed_state, guarded, run, tensor
DEFAULT_IV16 = {**EMBEDDING_DEFAULTS, "B": 1, "T": 3,
"i00": 2, "i01": 0, "i02": 2, "i10": 1, "i11": 2, "i12": 0}
@guarded
def derive_iv16(state):
"""Validate all 14 fields, then gather active IDs, never multiply by them."""
id_keys = ("i00", "i01", "i02", "i10", "i11", "i12")
bounds = {key: (-4, 4) for key in EMBEDDING_DEFAULTS}
bounds.update({key: (0, 2) for key in id_keys})
bounds.update(B=(1, 2), T=(1, 3))
s = fixed_state(state, DEFAULT_IV16, bounds, ("B", "T", *id_keys))
E, ids, X, trace = embedding_rows(s), [], [], Trace()
for b in range(s["B"]):
for t in range(s["T"]):
identifier = s[f"i{b}{t}"]
ids.append(identifier)
for d in range(2):
# Each appended scalar is copied; X never shares writable E storage.
value = float(E[2 * identifier + d])
X.append(value)
trace.add(f"gather_{b}_{t}_{d}", f"Gather batch {b}, position {t}, feature {d}",
"X[b,t,d]=E[ID[b,t],d]", "Select the row and feature; repeated IDs reuse parameters, not output storage.",
dict(b=b, t=t, ID=identifier, row=identifier, feature=d, rowValue=value), {f"x{b}{t}{d}": value})
return trace.result(dict(B=s["B"], T=s["T"], D=2, lookupCount=s["B"] * s["T"]), [
tensor("ids", [s["B"], s["T"]], ["B", "T"], ids, "0=oak, 1=river, 2=sun.", "int32"),
tensor("E", [3, 2], ["Vocab", "D"], E, "One parameter row per vocabulary entry."),
tensor("X", [s["B"], s["T"], 2], ["B", "T", "D"], X, "Detached feature-last row-major lookup outputs."),
])
if __name__ == "__main__":
run(derive_iv16, DEFAULT_IV16)
The imported helper supplies the actual state checks, tensor serialization and command-line interface. It is shown in full because the short chapter program depends on it.
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. With no state argument the CLI uses defaults; a complete JSON object replaces the entire state; - requests that complete object from standard input.
Carry the mechanism forward
An ID addresses a vocabulary row. A lookup copies that row into a feature-last tensor with separate batch and position axes. Repeated IDs read the same parameters, and different output positions retain separate stored values. None of those facts alone gives the coordinates linguistic meaning.
Use the five graded questions in the lab to check row selection, shape, a current coordinate, shared-row edits and invalid indices. Next, IV-17 — Embedding Geometry and Similarity asks how to compare two retrieved vectors geometrically before IV-18 — How Embeddings Learn From Gradients gives the table an actual learning rule.