🎓 A1Learner
🔍
0 of 53 lessons completed

PyTorch Adding Token and Position

Adding token and position vectors merges two signals into one vector of the same size. Addition is the standard merge because the merged vector stays at n_embd numbers.

Addition keeps the width

Addition merges the two rows at each position into one row. The merged window keeps the shape of each part.

torch.manual_seed(3)
token_table = nn.Embedding(47, 8)
position_table = nn.Embedding(64, 8)
window = torch.tensor([21, 27, 4])
token_rows = token_table(window).detach()
position_rows = position_table(torch.arange(3)).detach()
summed = token_rows + position_rows
print(tuple(token_rows.shape))
print(tuple(position_rows.shape))
print(tuple(summed.shape))

Concatenation doubles the width

Concatenation joins two vectors end to end into one longer vector. A concatenated row holds 16 numbers where an added row holds 8.

joined = torch.cat([token_rows, position_rows], dim=-1)
print(tuple(joined.shape))
print(joined.shape[-1])

Both signals survive the sum

Changing the character changes the sum, and changing the position changes the sum. Both signals stay inside the merged vector.

torch.manual_seed(3)
token_table = nn.Embedding(47, 4)
position_table = nn.Embedding(64, 4)


def summed_row(char_number, position):
    parts = token_table(torch.tensor([char_number])) + position_table(torch.tensor([position]))
    return parts.detach()


a = summed_row(27, 0)
b = summed_row(23, 0)
c = summed_row(27, 1)
print(torch.equal(a, b))
print(torch.equal(a, c))

Example

import torch
import torch.nn as nn
import torch.nn.functional as F

CORPUS = """The sun came up over the hill. Moss the cat woke in the warm house. Nan put milk in a blue bowl. Moss drank the milk and licked her lips. Then Moss went out to the garden.

Pip the sparrow sat on the wall. Good morning, Moss, said Pip. Good morning, Pip, said Moss. The sun is warm, said Pip. The sun is warm and the sky is clear, said Moss.

Bram the dog ran down the lane. Bram had a stick in his mouth. Drop the stick, Bram, said Nan. Bram dropped the stick. Good dog, said Nan. Bram wagged his tail and barked at the sky.

The three friends walked to the river. The river ran cold and clear over the white stones. A silver fish jumped in the river. Splash! The fish jumped again. Moss watched the fish. Pip watched the fish. Bram put one paw in the water. The water was cold. Bram shook his wet paw. The friends laughed in the sun.

At noon, Nan called the friends home. Bread and cheese waited on the table. The friends ate in the garden. The garden smelled of rain and roses. Bees hummed in the warm air. It was a good day, and the day was not over yet.

The rain came in the night. Rain tapped on the roof. Rain ran down the lane. Rain filled the blue bowl in the garden. Moss sat at the window and watched the rain. Pip hid under the wall. Bram slept by the fire and dreamed of sticks.

In the morning, the rain was gone. The sun came up over the hill. The lane was wet and the garden was green. A snail crossed the step, slow and silver. Good morning, snail, said Moss. The snail said nothing. The snail had far to go.

Nan gave Moss a fish for lunch. Nan gave Bram a bone for lunch. Nan gave Pip a crust of bread. Pip pecked the crust. Bram chewed the bone. Moss ate the fish, bite by bite. Then all three slept in the sun, full and warm and glad.

One day, a red ball rolled into the garden. The ball rolled past Moss. The ball rolled past Bram. The ball rolled under the wall and stopped by the river. Whose ball is this? said Pip. Tom came down the lane. Tom was a small boy with red boots. My ball! said Tom. Thank you, friends!

Tom threw the ball. Bram ran and caught the ball. Tom threw the ball again. Pip flew over the ball. Moss hid in the grass and jumped out. Boo! said Moss. Tom laughed and laughed. The friends played until the sun went down.

When the sun went down, the sky turned red and gold. The friends walked home in the soft light. Nan had soup on the fire. The soup was hot and good. Eat, said Nan, and rest. Tomorrow is a new day.

The moon came up over the hill. The stars came out, one by one. Moss curled on the step. Pip slept in the tree. Bram slept by the door, one ear up. The house was quiet. The river ran on in the dark, cold and clear. Sleep well, little friends, said the moon. And they did.

In the spring, the garden woke up. Green shoots came out of the dark earth. A bee came to the garden. The bee hummed from rose to rose. Pip sang in the tree. Bram dug a hole by the wall. Moss rolled in the warm grass. Spring is here, said Moss. Spring is here at last.

Nan planted seeds in the garden. Small seeds, brown and round. Moss watched the seeds go into the earth. Pip watched for worms. Bram watched for Tom. Rain came, soft and warm. Sun came, warm and gold. The seeds slept in the dark. Then, one morning, a green shoot! And then two! And then ten!

The shoots grew tall in the summer sun. Red roses opened on the wall. The garden was full of bees and birds. Tom picked peas in the garden. Nan picked beans. Moss picked a warm spot and slept in it. It was a good summer, a long, warm summer.

One hot day, the friends went up the hill. The hill was high and the grass was dry. From the top of the hill, the friends saw the river. They saw the lane and the house and the garden. They saw the whole world, small and bright. I can see my house, said Tom. I can see my river, said Moss. I can see everything, said Pip, and Pip flew up, up, up into the blue.

At the top of the hill, the wind blew. The wind blew the grass. The wind blew the tree. The wind took the song of Pip and carried it over the river. Sing again, Pip, said Bram. Pip sang again, loud and sweet. The sun shone. The wind blew. It was good to be alive.

When autumn came, the leaves turned gold and red. Leaves fell from the tree. Leaves covered the lane. Bram jumped in the leaves. Moss hid in the leaves. Pip rode on a leaf down to the river. Splash! Pip shook the water off and laughed. Autumn is fun, said Pip. Autumn is cold, said Moss, and Moss went home to the fire.

Nan made a pie in the autumn. The pie was full of apples. The house smelled of apples and spice. Tom ate two slices of pie. Bram ate the crumbs. Moss drank warm milk. Pip pecked at a seed cake. Outside, the leaves fell. Inside, the fire burned, warm and bright.

One cold morning, frost covered the garden. The grass was white. The bowl was ice. The river ran slow under a skin of ice. Moss put one paw on the ice. The ice was cold and hard. Winter is coming, said Moss. Winter is coming soon.

Snow fell in the night, soft and deep. In the morning, the world was white. The hill was white. The lane was white. The tree was white, and the wall was white. Bram ran in the snow. Tom rolled in the snow. Pip sat in the tree and shivered. Come down, Pip, said Nan. Come in by the fire.

By the fire, the friends were warm. Nan read a story out loud. The story was about a cat, a dog, and a bird. That is us! said Tom. That is us, said Moss, and Moss purred. The snow fell outside. The fire burned inside. It was the best place in the whole white world.

And when the snow melted, the river ran fast and full. The sun came up over the hill, warm as ever. Moss sat on the step. Pip sang in the tree. Bram ran down the lane with a stick. Spring had come again, and the friends were glad. The end."""

text = CORPUS
chars = sorted(set(text))
vocab_size = len(chars)
stoi = {ch: i for i, ch in enumerate(chars)}
itos = {i: ch for ch, i in stoi.items()}


def encode(s):
    return [stoi[ch] for ch in s]


def decode(ids):
    return "".join(itos[i] for i in ids)


data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9 * len(data))
train_data = data[:n]
val_data = data[n:]

batch_size = 32
block_size = 64
n_embd = 32


def get_batch(split):
    d = train_data if split == "train" else val_data
    ix = torch.randint(len(d) - block_size, (batch_size,))
    x = torch.stack([d[i:i + block_size] for i in ix])
    y = torch.stack([d[i + 1:i + block_size + 1] for i in ix])
    return x, y


class AveragingModel(nn.Module):
    def __init__(self, use_position):
        super().__init__()
        self.token_table = nn.Embedding(vocab_size, n_embd)
        self.head = nn.Linear(n_embd, vocab_size)
        self.use_position = use_position
        if use_position:
            self.position_table = nn.Embedding(block_size, n_embd)

    def forward(self, idx, targets=None):
        B, T = idx.shape
        x = self.token_table(idx)
        if self.use_position:
            x = x + self.position_table(torch.arange(T))
        counts = torch.arange(1, T + 1, dtype=x.dtype).view(1, T, 1)
        averaged = torch.cumsum(x, dim=1) / counts
        logits = self.head(averaged)
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.view(B * T, vocab_size), targets.view(B * T))
        return logits, loss


def train_and_score(use_position):
    torch.manual_seed(7)
    model = AveragingModel(use_position)
    torch.manual_seed(99)
    optimizer = torch.optim.AdamW(model.parameters(), lr=0.003)
    for step in range(50):
        xb, yb = get_batch("train")
        _, loss = model(xb, yb)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    torch.manual_seed(123)
    model.eval()
    losses = []
    with torch.no_grad():
        for _ in range(10):
            xb, yb = get_batch("val")
            _, batch_loss = model(xb, yb)
            losses.append(batch_loss.item())
    return sum(losses) / len(losses)


token_only = train_and_score(False)
token_and_position = train_and_score(True)
print("Steps per model: 50")
print(f"Token only validation loss: {token_only:.4f}")
print(f"Token + position validation loss: {token_and_position:.4f}")

Key points

  • An added pair of rows holds n_embd numbers
  • A concatenated pair of rows holds 2 × n_embd numbers
  • Later layers take the merged width as their input width
  • Both tables must use the same n_embd, or the rows cannot be added

In this example, one AveragingModel class runs in two modes, with and without a position table. The class is the averaging model from Averaging Previous Tokens, with an optional position table. The seed is reset before each run, so both modes start from the same token table and head. A second reset gives both modes the same training batches in the same order. Each mode trains for 50 steps and scores on the same seeded validation batches. The token-only loss is 3.0431, and the token + position loss is 3.0262. The two losses land almost level, and that near-tie is the honest result here. Averaging blends the position rows into nearly the same blend for every window. Self-Attention, the next entry, reads each position before any blending, and it can spend the signal that averaging cannot.

Note

A summed window keeps the shape (batch, time, n_embd)

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why is addition the standard merge for token and position vectors?