Embedding layers: lookup, then accumulate
嵌入层
Execute a trainable lookup table with repeated indices and an explicit padding-loss mask; separate row operations from learned semantics.
embedding-layersAn integer selects a row; it does not measure meaning
A token ID of 12 is not twice as meaningful as ID 6. IDs are labels used to select rows from an embedding table. The selected row is a real-valued vector that downstream computation can use. Repeating an ID selects the same parameter row again, so gradients from its occurrences must accumulate.
Bengio and colleagues’ 2003 paper, Section 2 represents word features as a vocabulary-by-feature matrix learned jointly with a language model. The fixed PyTorch 2.8 Embedding documentation describes a lookup table whose input indices retrieve corresponding vectors. A lookup is the layer operation; a useful representation comes from the training task, data and surrounding model.
Lookup and one-hot multiplication select the same row
Let E have V rows and D columns. For an index i, let eᵢ be the V-dimensional one-hot vector with a one at i. For positions t with indices iₜ:
The multiplication selects one row because every other one-hot coefficient is zero. Implementing it as a direct lookup avoids constructing the long one-hot vector or doing a dense matrix multiplication. The table still stores VD parameters; indexing is not compression of the table itself.
The lookup is differentiable with respect to the selected row values. An integer index is not an ordinary continuously differentiable input. Algorithms that relax discrete choices define additional operations; they are not obtained by taking a conventional derivative of an integer ID.
Repeated indices require scatter-add
For a teaching objective, give each non-padding position a target vector yₜ. Let A be the set of included positions and K its size, which must be positive. The mean half squared loss and row gradient are:
Different positions can contribute to the same row. Assigning the last occurrence’s gradient would lose earlier contributions. Rows that are never selected by an included position have zero data-loss gradient for this objective.
Take E rows (0,0), (1,−1), (2,1), (−1,2), indices (1,2,1,0), and targets (0,0), (1,1), (2,0), (9,9). We explicitly exclude ID zero’s position from this loss, so K=3. Row one receives (1,−1) and (−1,−1), summing to (0,−2) before division by three. Row two gets (1/3,0); rows zero and three get zero.
Initial loss is 5/6. A learning-rate 1/2 update changes row one to (1,−2/3) and row two to (11/6,1), while leaving the other rows unchanged. New loss is 43/72. This is supervised vector fitting, not a language-model objective or evidence of learned semantics.
Coordinates are not intrinsically identifiable
If a downstream linear map uses E followed by W, an invertible D-by-D change of coordinates A can preserve the product:
Thus the same predictions may be represented by different embedding coordinates. A non-orthogonal transformation can change Euclidean distances. This algebra assumes the intervening computation is the displayed linear composition; nonlinearities, normalization and regularization may break that freedom. It explains why the meaning of one coordinate or distance cannot be inferred from a table in isolation.
Train only the rows reached by the loss
The complete Python 3.12 program uses exact fractions and returns a new table. It computes outputs by row lookup, explicitly masks padding positions in the loss, averages over included positions and accumulates repeated row gradients. Every ID, table width and target width is checked; an all-padding loss is rejected rather than divided by zero.
from fractions import Fraction as F
def scalar(x):
if type(x) not in (int,F) or abs(x)>32:raise ValueError('bounded rational required')
return F(x)
def loss_gradient(table,ids,targets,pad=None):
if not 1<=len(table)<=32 or not 1<=len(table[0])<=8:raise ValueError('bounded table required')
d=len(table[0]);e=[tuple(scalar(v) for v in row) for row in table]
if any(len(row)!=d for row in e):raise ValueError('rectangular table required')
if not 1<=len(ids)<=32 or len(ids)!=len(targets):raise ValueError('matching nonempty positions and targets required')
if any(type(i) is not int or not 0<=i<len(e) for i in ids):raise ValueError('valid integer indices required')
if pad is not None and (type(pad) is not int or not 0<=pad<len(e)):raise ValueError('invalid padding index')
targets=[tuple(scalar(v) for v in row) for row in targets]
if any(len(row)!=d for row in targets):raise ValueError('target width mismatch')
valid=[t for t,i in enumerate(ids) if i!=pad]
if not valid:raise ValueError('at least one non-padding position required')
output=[e[i] for i in ids];gradient=[[F(0)]*d for _ in e];loss=F(0)
for t in valid:
for j in range(d):
error=output[t][j]-targets[t][j]
loss+=error**2/(2*len(valid));gradient[ids[t]][j]+=error/len(valid)
return output,loss,gradient
def train_step(table,ids,targets,rate,pad=None):
rate=scalar(rate)
if not 0<=rate<=1:raise ValueError('rate must be in [0,1]')
_,loss,g=loss_gradient(table,ids,targets,pad)
updated=[tuple(F(v)-rate*delta for v,delta in zip(row,grad)) for row,grad in zip(table,g)]
return updated,loss,g
if __name__=='__main__':
table=[(0,0),(1,-1),(2,1),(-1,2)]
ids=[1,2,1,0];targets=[(0,0),(1,1),(2,0),(9,9)]
updated,loss,g=train_step(table,ids,targets,F(1,2),pad=0)
print('initial loss:',loss)
print('gradient:',[[str(v) for v in row] for row in g])
print('updated table:',[[str(v) for v in row] for row in updated])
print('new loss:',loss_gradient(updated,ids,targets,pad=0)[1])
Actual output:
initial loss: 5/6
gradient: [['0', '0'], ['0', '-2/3'], ['1/3', '0'], ['0', '0']]
updated table: [['0', '0'], ['1', '-2/3'], ['11/6', '1'], ['-1', '2']]
new loss: 43/72
Tests check the literal gradient and update, compare all table-coordinate derivatives with finite differences, and verify that repeated lookup equals a separately formed one-hot multiplication. Padding and unused rows stay unchanged under this particular plain-SGD rule. Shape failures, negative/out-of-range IDs and all-padding inputs are covered.
For T positions, lookup and row contributions cost O(TD). A sparse accumulator can store only touched rows, but this easy-to-inspect implementation allocates and updates a dense V-by-D gradient table, so its total work and gradient memory include O(VD). The implementation does not pretend to be a sparse optimizer.
A padding option is not a complete masking policy
The fixed PyTorch API’s padding_idx suppresses that row’s contribution to the embedding operation’s gradient. It does not by itself specify how to mask a later loss or attention operation. Our explicit exclusion from the loss and normalization by K are additional teaching choices, not a full copy of the library behavior.
Zero data gradient does not always mean no parameter change: an optimizer can apply weight decay or momentum state. A custom nonzero padding vector therefore needs care if some other update acts on it. Our example has no momentum or decay and updates only according to the displayed gradient.
The documented options also distinguish sparse gradients, inverse-frequency gradient scaling and max_norm, which can modify the table in-place during a forward call. None is enabled or implemented here. Dividing repeated-row gradients by their frequency changes the update relative to the unweighted objective above; it is not required merely to make repeated IDs work.
An unknown token requires a vocabulary policy, such as an explicit unknown entry or a tokenizer that decomposes it. The table cannot retrieve an out-of-range row. Semantic similarity, recommendation usefulness and transfer performance require suitable objectives and evaluation; they do not follow from the fact that lookup returns vectors.
Which rows receive which gradients?
- What row-one gradient results from the two occurrences in the example?
Answer 1: (0,−2/3), after summing and dividing by three included positions.
- Which rows remain unchanged in the plain-SGD update?
Answer 2: The excluded padding row zero and unused row three.
- Does a direct lookup require materializing a V-dimensional one-hot vector?
Answer 3: No. One-hot multiplication is an equivalent mathematical description, not a required implementation.
- Does zero embedding data gradient guarantee a parameter never changes under every optimizer?
Answer 4: No. Other update terms, such as decay or existing momentum, may still change it.
A learned representation is more than a table operation
The language-model paper supplies a concrete historical example of jointly learned distributed word features, while acknowledging earlier representation ideas. The fixed API supplies the lookup and optional-update contract. Our tiny table, masked vector loss, scatter-add, coordinate-change argument and tests are original; no pretrained vectors or source benchmark were reused.
Read parameter sharing for why repeated uses add gradients, and matrix multiplication for the one-hot identity. Contextual representations later produced by a network should not be confused with the same token’s initial table row.
Make a prediction, then check
What is the gradient of row1 in the example?
Learning objectives
- Accumulate repeated-index gradients into the correct table row.
- Specify padding, loss reduction and update assumptions.
Prerequisites & connections
Explore related knowledge →References
- A Neural Probabilistic Language Model
Yoshua Bengio; Réjean Ducharme; Pascal Vincent; Christian Jauvin · 2003 - Embedding — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Shared gradients, embedding scatter-add, receptive-field geometry and pooling routes are checked against literal references, analytic identities and finite differences. All four examples use exact fractions from the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- A Neural Probabilistic Language Model · Section2 printed1141–1142: vocabulary-by-feature C matrix, lookup and sharing across context positions, joint training; historical example not first-invention claim.
- Embedding — PyTorch 2.8 · Fixed2.8 Embedding body: lookup/shape, padding_idx, sparse gradients, scale_grad_by_freq, max_norm in-place behavior; our masked loss is separately defined, no PyTorch runtime.
Related topics