Lesson 02 · Embedding and position

An Id Becomes a Vector, and Position Has to Be Added

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

The five lessons; lesson 02 highlighted Both pipelines; the embedding rows are marked

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?

1The chain of this lesson

Definition · embedding (vector per unit) An embedding is the dense vector the model uses in place of a unit. For an id it is a row of a trainable matrix of shape (vocab_size, emb_dim): 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.

LLM Book Figure 2.2: an embedding model converts raw input into a vector representation

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 § tiny
code
vocab_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))
Point cloud One real point's four features multiplied by the first four rows of the embedding weight plus bias, giving its first four channels
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)
code
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

Definition · order blindness Both embeddings are applied per unit: permute the units and the output rows are permuted the same way, nothing else changes. The vector of "the" at position 0 equals the vector of "the" at position 2; the vector of a point does not depend on which patch it will land in.

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.

LLM
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 § order
Point cloud
embed(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

Definition · position (absolute table · relative conv) Absolute position embedding: a second table of shape (context_length, emb_dim); row t is added to whatever token sits at position t. xCPE (PTv3): before every attention, run one sparse 3×3×3 convolution over the occupied cells and add the result back, 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.

LLM Book Figure 3.0: token ids become token embeddings, positional embeddings are added, the sum is the input embedding
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, § position
code
with 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)
Point cloud
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
The 3 by 3 by 3 stencil of xCPE drawn as three slices; occupied neighbours contribute their feature through the weight of their offset, empty cells are skipped
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
⚙ toy: out[i] += cell_feat[j] @ W[offset] over the occupied neighbours j · c02_embedding.py § xcpe_toy, § relative (the real layer is spconv.SubMConv3d)
code
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

2Try it

LLM · a lookup, then an addition

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].

3What this lesson established

Why can GPT-2 not read a 1 025-token prompt?

Its absolute position embedding has 1 024 rows; position 1 024 has no vector to add. Relative schemes (RoPE, ALiBi) remove this limit.

The point embedding already contains x, y, z. Why add position again with xCPE?

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.

Why is xCPE cheaper than PTv1's relative encoding?

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.