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:
tok_emb one row per wordx one vector per tokentorch.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.