Add token and position embeddings for a GPT input batch

Why it matters GPT-2 style models start every forward pass with this exact sum.

The first layer of a GPT model turns ids into vectors: one learned vector per token id plus one learned vector per position.

Write embed(ids, tok_emb, pos_emb). ids is an int array of shape (B, T). tok_emb has shape (V, d) and pos_emb has shape (L, d), where L is the maximum context length. Return tok_emb[ids] + pos_emb[:T], shape (B, T, d). If T > L, raise ValueError.

Signaturedef embed(ids, tok_emb, pos_emb)

Example

tok_emb = [[1, 0], [0, 1], [2, 2]], pos_emb = [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]], ids = [[2, 0]] gives [[[2.1, 2.1], [1.2, 0.2]]].

Understand the idea

A token id is just a number, so the model gives each id a learned vector, like a dictionary entry. But "dog bites man" and "man bites dog" contain the same tokens, so the model also needs to know where each token sits. GPT-style models learn a second table with one vector per position and add the two.

Example: token table rows are [1,0], [0,1], [2,2], and position table rows are [0.1,0.1], [0.2,0.2]. The input is ids [2, 0]. Position 0 holds token 2: [2,2] + [0.1,0.1] = [2.1,2.1]. Position 1 holds token 0: [1,0] + [0.2,0.2] = [1.2,0.2].

Rule: x[b, t] = tok_emb[ids[b, t]] + pos_emb[t], valid only for t < L.

This sum is the input to the first transformer block in GPT-2 and similar models. Newer models such as Llama drop the position table and rotate queries and keys instead.

Shapes and data flow

ids (B, T) -> tok_emb[ids] (B, T, d) + pos_emb[:T] (T, d) -> (B, T, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleembed([[2, 0]], [[1, 0], [0, 1], [2, 2]], [[0.1, 0.1], [0.2, 0.2], [0.3, 0.3]])
  • Sample 2: batchembed([[0, 1, 1], [2, 2, 0]], [[1, 0], [0, 1], [2, 2]], [[0.1, 0.0], [0.0, 0.1], [0.5, 0.5]])
  • Test 3: too long_raises(lambda: embed([[0, 0, 0]], [[1, 0]], [[0, 0], [1, 1]]))