Lesson 1 left us with integers. Integers are labels: id 5 is not between id 4 and id 6. The network needs a dense vector per unit that training can shape, and because attention (lesson 3) is blind to order, it also needs to know where each unit sits. The LLM solves both with lookup tables. The point cloud has nothing to look up.
map · flow · code: code/llm/c02_embedding.py, code/pc/c02_embedding.py · book: chapter 2, sections 2.7 and 2.8
Where we are. This lesson builds the rows inside the dashed box: ids → vectors, plus position. The question: how does an integer or a point become a vector, and where is position?
nn.Embedding returns row id, which is the same as one-hot × matrix. For a point, whose features are already numbers, it is a small linear map from (x, y, z, intensity) to 32 channels.
Why we need it: every later layer adds, multiplies and compares vectors, so similar units must be able to become similar vectors. An id cannot; a trained row can (book Figure 2.3 shows "cat" and "dog" ending up close). Four raw coordinates cannot either: they have no channels for the network to write features into.
A 6-row table with 3 dimensions, seed 123, and the lookup of ids [2, 3, 5, 1]:
embedding table (6 ids x 3 dims):
Parameter containing:
tensor([[ 0.3374, -0.1778, -0.1690],
[ 0.9178, 1.5810, 1.3010],
[ 1.2753, -0.2010, -0.1606],
[-0.4015, 0.9666, -1.1481],
[-1.1589, 0.3255, -0.6315],
[-2.8400, -0.7849, -1.4096]], requires_grad=True)
lookup of ids [2, 3, 5, 1]:
tensor([[ 1.2753, -0.2010, -0.1606],
[-0.4015, 0.9666, -1.1481],
[-2.8400, -0.7849, -1.4096],
[ 0.9178, 1.5810, 1.3010]], grad_fn=<EmbeddingBackward0>)
nn.Embedding(6, 3)(torch.tensor([2, 3, 5, 1])) · c02_embedding.py § tinyvocab_size, output_dim = 6, 3
torch.manual_seed(123)
embedding_layer = nn.Embedding(vocab_size, output_dim)
print("embedding table (6 ids x 3 dims):")
print(embedding_layer.weight)
input_ids = torch.tensor([2, 3, 5, 1])
print("lookup of ids [2, 3, 5, 1]:")
print(embedding_layer(input_ids))input features: (2500, 4) = (points, [x, y, z, intensity]) embedded : (2500, 32) = (points, channels) no nn.Embedding(table) here: the input is continuous, there is nothing to look up
nn.Linear(4, 32)(feats) · c02_embedding.py § embed (the paper uses a small sparse-conv stem for the same job)coords, intensity = load_car(n_sub=2500, seed=0)
feats = torch.tensor(np.c_[coords, intensity / intensity.max()], dtype=torch.float32) # (N, 4): x y z intensity
print("input features:", tuple(feats.shape), " = (points, [x, y, z, intensity])")
embedding = nn.Linear(4, 32) # PTv3 embeds with a small conv/linear stem to 32 channels
x = embedding(feats)
print("embedded :", tuple(x.shape), " = (points, channels)")
print("no nn.Embedding(table) here: the input is continuous, there is nothing to look up")↓ the same lookup for the same id, wherever it appears — the embedding does not know where it is
Why we need it: this is not a defect to fix here, it is the fact that forces the next card. Attention (lesson 3) is order-blind as well, so if position is not put into the vectors now, nothing downstream will ever know it.
embed([5,1,3]) rows == embed([3,5,1]) rows, just permuted: True -> the embedding alone carries no information about WHERE a token sits
torch.equal(emb(ids)[[2,0,1]], emb(ids[[2,0,1]])) · c02_embedding.py § orderembed(points[perm]) == embed(points)[perm]: True -> like the token table, the point embedding is blind to order; and here there is no position table to add
torch.allclose(embedding(feats[perm]), embedding(feats)[perm]) · c02_embedding.py § order↓ so position must be added — and here the two sides part ways
x ← x + SparseConv(x). Each kernel weight belongs to one relative offset, so the output encodes "what sits at which offset around me".
Why we need it: the LLM has a fixed, integer position axis, so a table works and costs one addition per token. The point cloud has neither a fixed length nor integer positions, and a table indexed by cell would need about 107 rows for one room and never see most of them. What attention actually needs is relative geometry; a convolution supplies it in one pass. PTv1/PTv2 computed it per attended pair instead, which cost PTv2 26 % of its forward time.
Token IDs:
tensor([[ 40, 367, 2885, 1464],
[ 1807, 3619, 402, 271],
[10899, 2138, 257, 7026],
[15632, 438, 2016, 257],
[ 922, 5891, 1576, 438],
[ 568, 340, 373, 645],
[ 1049, 5975, 284, 502],
[ 284, 3285, 326, 11]])
Inputs shape: torch.Size([8, 4])
token_embeddings.shape: torch.Size([8, 4, 256])
pos_embeddings.shape: torch.Size([4, 256]) (one vector per POSITION 0..3, shared by every sequence)
input_embeddings.shape: torch.Size([8, 4, 256])
same token id 464 at positions 0 and 2: token vectors equal? True input vectors equal? False their difference is exactly pos[2]-pos[0]: True context_length = 1024 -> the position table has 1024 rows; a 1025th token has no row
tok_emb(ids) + pos_emb(torch.arange(T)) · c02_embedding.py § gpt2, § positionwith open(VERDICT, "r", encoding="utf-8") as f:
raw_text = f.read()
vocab_size, output_dim, max_length = 50257, 256, 4
token_embedding_layer = nn.Embedding(vocab_size, output_dim)
dataloader = create_dataloader_v1(raw_text, batch_size=8, max_length=max_length, stride=max_length, shuffle=False)
inputs, targets = next(iter(dataloader))
print("Token IDs:\n", inputs)
print("Inputs shape:", inputs.shape)
token_embeddings = token_embedding_layer(inputs)
print("token_embeddings.shape:", token_embeddings.shape)
pos_embedding_layer = nn.Embedding(max_length, output_dim)
pos_embeddings = pos_embedding_layer(torch.arange(max_length))
print("pos_embeddings.shape:", pos_embeddings.shape, " (one vector per POSITION 0..3, shared by every sequence)")
input_embeddings = token_embeddings + pos_embeddings
print("input_embeddings.shape:", input_embeddings.shape)why not an absolute position table? points per scene: 2500 here, up to ~10^6 in a building -> no fixed 'context length' coordinates are continuous: x in [0, 1.64] m; at 2 cm there are 82 x-cells alone a table indexed by (x,y,z) cell would have ~10^7 rows for a room and never see most of them
grid 0.2 m: 356 occupied cells; a 3x3x3 kernel finds on average 11.6 of 27 neighbours (the rest are empty space) output: (356, 32) -> one 'position-aware' vector per cell, added back to the features (x <- x + conv(x))
translate the entire scene by (3, 5, 1) cells -> conv output unchanged: True -> the conv encodes RELATIVE position (which neighbour sits at which offset), never absolute coordinates that is exactly what attention lacks, and it costs one pass over the voxels, not one pass per pair
out[i] += cell_feat[j] @ W[offset] over the occupied neighbours j · c02_embedding.py § xcpe_toy, § relative (the real layer is spconv.SubMConv3d)GRID = 0.20
cells = quantize_to_grid(coords, GRID)
cell_key = {tuple(c): i for i, c in enumerate(np.unique(cells, axis=0))}
owner = np.array([cell_key[tuple(c)] for c in cells])
n_cells = len(cell_key)
# pool point features into cells (mean), as the sparse conv sees one feature per occupied voxel
cell_feat = torch.zeros(n_cells, 32).index_add_(0, torch.as_tensor(owner), x) / torch.bincount(torch.as_tensor(owner), minlength=n_cells)[:, None]
offsets = [(dx, dy, dz) for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1)]
W = nn.Parameter(torch.randn(27, 32, 32) * 0.05) # one weight matrix per RELATIVE offset
def sparse_conv(cell_feat, cell_key):
out = torch.zeros_like(cell_feat); found = 0
for key, i in cell_key.items():
for o, off in enumerate(offsets):
j = cell_key.get((key[0] + off[0], key[1] + off[1], key[2] + off[2]))
if j is not None:
out[i] += cell_feat[j] @ W[o]; found += 1
return out, found / len(cell_key)
y, avg_nb = sparse_conv(cell_feat, cell_key)
print(f"grid {GRID} m: {n_cells} occupied cells; a 3x3x3 kernel finds on average {avg_nb:.1f} of 27 neighbours (the rest are empty space)")
print("output:", tuple(y.shape), "-> one 'position-aware' vector per cell, added back to the features (x <- x + conv(x))")↓ every unit is now a vector that knows its position — lesson 3 lets the vectors look at each other
The table is the real 6 × 3 embedding from the output above (seed 123). The same token at positions 0 and 2 gets two input vectors that differ by exactly pos[2] − pos[0].
Its absolute position embedding has 1 024 rows; position 1 024 has no vector to add. Relative schemes (RoPE, ALiBi) remove this limit.
Attention compares projected features of pairs; it has no notion of "offset between i and j" unless the features encode it. The conv mixes each cell with its specific neighbours by offset, so after it a point's feature knows its local arrangement, and only the relative part.
PTv1 evaluates an MLP for every (i, j) pair inside every neighbourhood: cost grows with pairs. The conv touches each occupied cell once with at most 27 neighbours: cost grows with points.