4/29
Part 1 of 5 · From words to vectorsLearn and do

Positions get a table too

A second table, pos_emb, has one row per position: row 0 for the first position, row 1 for the second, and so on, up to block_size rows. Each token's vector is its word's row plus its position's row:

# one row per position
pos_emb = nn.Embedding(6, 3)
x = tok_emb(idx) + pos_emb(torch.arange(6))
# "the" at 0 and 4, now
print(torch.equal(x[0, 0], x[0, 4]))
False

Tap a word to see the row it reads, then switch the positions on:

The cat sat on the mat, as vectorsInteractive
tok_emb one row per word
0 the1.5-0.3-2.21 cat0.6-1.1-1.42 sat0.40.8-0.73 on-0.4-0.60.24 mat-0.91.1-1.1
x one vector per token
0 the1 cat2 sat3 on4 the5 mat
Position 4 is the (id 0): its row [1.54, -0.29, -2.18]. Positions 0 and 4 hold the same vector, so nothing later can tell them apart.

torch.arange(T) is the positions 0 to T - 1. The position vectors are (T, C), and broadcasting adds the same positions to every sentence in the batch. In the model, build them on the same device as idx: torch.arange(T, device=idx.device). A plain torch.arange(T) sits on the CPU, and the model fails the first time it runs on a GPU.

Write embed(idx, tok_emb, pos_emb): each token's row of tok_emb plus its position's row of pos_emb. It's the first line of the model's forward, so build the positions on idx's device.