19/23
Part 6 of 6 · One decode step, and long linesLearn and do

One step of text generation

A model that generates text adds one token per step. It returns logits of shape (B, T, V): for every sentence and every position, one score for each of the V tokens in the vocabulary. Only the last position predicts the next token.

idx = torch.tensor([[0, 2],
                    [1, 1]])
logits = torch.tensor([[[2.0, 0.0, 1.0],
                        [0.5, 0.1, 3.0]],
                       [[0.0, 1.0, 0.0],
                        [4.0, 2.0, 1.0]]])
last = logits[:, -1]
nxt = last.argmax(dim=-1, keepdim=True)
print(nxt)
print(torch.cat([idx, nxt], dim=1))
tensor([[2],
        [0]])
tensor([[0, 2, 2],
        [1, 1, 0]])

The largest last-position scores, 3.0 and 4.0, sit at ids 2 and 0, so those ids go on the end.

One decode stepInteractive
logits (B, T, V) = (2, 2, 3). A score for every token, at every position of every sentence.
1last = logits[:, -1]2nxt = last.argmax(dim=-1, keepdim=True)3idx = torch.cat([idx, nxt], dim=1)

Three moves: take the last position, pick the best token in each row, glue it on. Repeat them, and the text grows one token per step.

Predict

Without keepdim=True, the picks are a flat list, (2,). What does torch.cat([idx, picks], dim=1) do?

Pick an answer above to see the rest