Embeddings and absolute positional encodings
Turn tokens into vectors with embedding tables, study weight tying and the softmax bottleneck, and derive sinusoidal and learned positional encodings. Compare their behavior beyond training lengths.
After this lesson you can
- Implement embedding lookup and sparse gradient accumulation by index.
- Explain input-output weight tying and measure its parameter and loss effects.
- Prove that a sinusoidal encoding at t + k is a linear transformation of that at t independent of t.
- Compare sinusoidal and learned positions on length interpolation and extrapolation.
- Explain the output head's softmax bottleneck.
Before you start
From indices to sequences
A tokenizer produces integers, not vectors a network can compare. A trainable table converts them into vectors; then a position signal distinguishes the first token from the last. Without that signal, self-attention’s permutation equivariance means that shuffling inputs shuffles outputs in the same way. Here positions start at zero, as in the code.
Token table and sparse gradient
An embedding layer stores , with one row per token. Index returns . This is equivalent to multiplying the one-hot vector , but direct lookup avoids building a vector of length . It is the same trainable distributed representation seen in skip-gram, though now fitted with the complete model objective; contrast it with a local representation.
If a token appears several times, backward sums contributions in its row: . In NumPy np.add.at correctly accumulates repeated indices; dE[idx] += g uses advanced indexing and can lose repetitions. Sparsity describes the input path. If the same table is also used to project logits, the output path usually contributes a dense gradient, and both are added.
The output head and its rank
With state and output table , the logits are ; cross-entropy operates on them. Weight tying sets : input and output share the same parameter. This saves parameters compared with two unbiased tables, while restricting the parameterization. Press and Wolf studied this tying in language models; it does not imply that validation loss always improves.
Initialization matters. An input table with large standard deviation, used directly as a head, can initially produce very large logits. Comparing tied and untied models with different initialization distributions mixes the effect of scale with parameter sharing. In the local experiment both tables start equal and at the same scale; afterward, the untied model can change them separately.
The softmax bottleneck is a rank limitation of the linear head. For contexts, stack states in and unbiased logits in . If , the log-probability matrix is , so . An independent output bias can add another rank-one term and the general bound becomes . This does not say that the probability matrix has that rank: component-wise exponentiation is nonlinear. Yang et al. analyze this restriction and propose mixtures to increase expressiveness.
Absolute position: addition, concatenation, and sinusoids
One way to inject order adds , both of dimension . Addition preserves width and requires the network to separate overlapping signals; if their scales differ greatly, one can initially dominate. Concatenation reserves separate coordinates but increases dimension or requires a later projection. These are generally different parameterizations.
For even and , the sinusoidal positional encoding of Vaswani et al. uses
Frequencies form a geometric progression. These functions resemble a Fourier basis, but we do not claim the channels are orthogonal over every finite window. For the pair , the angle-addition formulas give
Each block is a rotation and an orthogonal matrix. Stacking them gives for every , and depends on and the frequencies, not . The dot product depends only on distance. This property does not force the learned projections or loss to extrapolate well.
A learned positional table stores one row per position and lets each adapt to the task. It costs parameters and is defined only up to the table length. If the table covers positions that receive no examples, those rows receive no direct supervised signal; initialization and regularization can still change them. Interpolating or extending a table is an additional decision, not guaranteed extrapolation.
Embeddings learned in a small model
The figure uses two small causal transformers trained on WikiText-2 training fragments, one tied and one untied. Coordinates are a joint PCA of all four input and output tables, so they share axes; projection loses information. Categories are character labels, not supervised learned classes. Observe whether clusters appear in this run, without assuming they are universal or attributing them to training before comparing initialization and other seeds.
NumPy lab
First verify accumulation and rotation. This example’s position table is constructed directly and its angle is in radians.
import numpy as np
idx=np.array([1,2,1,1]); grad=np.array([[1.,2.],[3.,4.],[5.,6.],[7.,8.]])
dE=np.zeros((4,2));np.add.at(dE,idx,grad)
print('fila repetida:',dE[1]);assert np.allclose(dE[1],[13,16])
def sinusoidal(t,d,base=10000.):
pos=np.arange(t)[:,None];freq=base**(-np.arange(0,d,2)/d);ang=pos*freq
out=np.empty((t,d));out[:,0::2]=np.sin(ang);out[:,1::2]=np.cos(ang);return out
pe=sinusoidal(128,8); k=7; omega=10000.**(-np.arange(0,8,2)/8)
blocks=np.stack([np.stack([np.cos(k*omega),np.sin(k*omega)],axis=-1),np.stack([-np.sin(k*omega),np.cos(k*omega)],axis=-1)],axis=-2)
shifted=np.einsum('hij,thj->thi',blocks,pe[:121].reshape(121,4,2)).reshape(121,8)
print('error máximo de desplazamiento:',np.max(np.abs(shifted-pe[k:])))
assert np.allclose(shifted,pe[k:])The next model is deliberately small: it uses one causal attention layer with zero Q and K, so each position averages previous values; inputs are positions, and a logistic head predicts a periodic label. The head and, in the learned case, the first 64 positional rows are trained. The other rows exist but receive no gradient during training. Positions 64 through 127 are evaluated separately. This reproducible control does not replace training a full transformer and does not by itself predict another model’s extrapolation.
def causal_mean(n):
a=np.tril(np.ones((n,n)));return a/a.sum(axis=1,keepdims=True)
A64=causal_mean(64);A128=causal_mean(128)
target=((np.arange(128)//4)%2).astype(float)
def loss_binary(logits,y): return np.mean(np.logaddexp(0,logits)-y*logits)
def train_position(scheme,steps=300):
rng=np.random.default_rng(1806);d=16
E=sinusoidal(128,d) if scheme=='sinusoidal' else rng.normal(0,.1,(128,d))
w=rng.normal(0,.1,d)
for _ in range(steps):
z=A64@E[:64]; logits=np.clip(z@w,-40,40);p=1/(1+np.exp(-logits));delta=(p-target[:64])/64
dw=z.T@delta; de=A64.T@np.outer(delta,w)
w-=.1*dw
if scheme=='learned':E[:64]-=.1*de
z=A128@E; logits=z@w
return loss_binary(logits[:64],target[:64]),loss_binary(logits[64:],target[64:])sin_train,sin_extra=train_position('sinusoidal')
print('pérdidas primeras 64 y nuevas 64:',sin_train,sin_extra)learn_train,learn_extra=train_position('learned')
print('pérdidas primeras 64 y nuevas 64:',learn_train,learn_extra)Local PyTorch experiment
Download experiment.py and run python experiment.py in an environment with PyTorch, CUDA, NumPy, and datasets. The script contains the complete reproducible experiment and writes experiment-results.json in the current directory. It trains two one-layer positional models for 300 steps at length 64 and evaluates positions 64 through 127 separately; the task is to predict a periodic label from position. It then trains two one-layer causal character transformers for 200 steps, with and without tying, and evaluates loss on separate WikiText-2 validation fragments. The generated file also contains the PCA coordinates feeding the figure for this run.
In the character models, input and output tables start with the same values and scale, and batches are generated with the same seed. A fixed vocabulary of printable characters and newline is used; characters outside it map to ?. Tying saves exactly one table, but later trajectories differ because of gradient sharing. Validation uses a separate generator. These are short runs with one seed: results do not establish general superiority. In the positional task, access to a sinusoid for likewise does not guarantee that a model trained on the prefix interprets it correctly.
In our reference run, positional-task loss on the first 64 positions was approximately with sinusoids and with a learned table. On the 64 new positions it was 9.628 and 5.358 respectively: both fitted the training range and failed to extrapolate on this task and seed. Character models had mean validation loss 2.747 tied and 2.709 untied; they have 17888 and 20960 parameters respectively, a difference of . These figures come from the specified run and may vary with hardware or versions; they should not be treated as a conclusive comparison.
Before running full training, this cell checks on GPU that tying shares the object and accumulates both paths. It does not measure quality: training and evaluation in the script are the requested experiment.
import torch
assert torch.cuda.is_available(), 'Se necesita CUDA para reproducir el experimento'
torch.manual_seed(1806)
embedding=torch.nn.Embedding(5,3,device='cuda')
head=torch.nn.Linear(3,5,bias=False,device='cuda')
head.weight=embedding.weight
ids=torch.tensor([1,1,3],device='cuda'); h=torch.ones(1,3,device='cuda')
loss=embedding(ids).sum()+head(h).sum();loss.backward()
expected=torch.ones(5,3,device='cuda');expected[1]+=2;expected[3]+=1
print('mismo parámetro:',head.weight is embedding.weight,'error de gradiente:',(embedding.weight.grad-expected).abs().max().item())
assert head.weight is embedding.weight and torch.allclose(embedding.weight.grad,expected)npm run lab and open the connection link.Exercises
Step 1 of 2. Which identity do you apply?
import numpy as np
def embedding_backward(dout,idx,vocab_size):
pass