Generate sinusoidal position encodings

Attention has no sense of order by itself. The original transformer added a fixed pattern of sines and cosines to each token embedding.

Write sinusoidal_pe(seq_len, d) for even d. Return (seq_len, d) where for position p and i from 0 to d/2 - 1:
PE[p, 2i] = sin(p / 10000 ** (2i / d))
PE[p, 2i + 1] = cos(p / 10000 ** (2i / d))

Signaturedef sinusoidal_pe(seq_len, d)

Understand the idea

Attention treats its input as a set, so it needs extra information about word order. The original transformer adds a fixed pattern of sines and cosines to each token embedding. Each pair of columns is a wave at one frequency: early columns wiggle fast, later columns slowly, like the second, minute and hour hands of a clock together telling a unique time. Worked example: d = 4, position p = 1. For i = 0 the divisor is 10000^(0/4) = 1, so columns 0 and 1 are sin(1) = 0.841 and cos(1) = 0.540. For i = 1 the divisor is 10000^(2/4) = 100, so columns 2 and 3 are sin(0.01) = 0.010 and cos(0.01) = 1.000. Row 1 is [0.841, 0.540, 0.010, 1.000]. Position 0 is always [0, 1, 0, 1, ...]. Rule: PE[p, 2i] = sin(p / 10000^(2i/d)), PE[p, 2i + 1] = cos(p / 10000^(2i/d)). Using i / d in the exponent is a common bug. The original transformer and many encoders use this encoding.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: 4 positions, d = 6sinusoidal_pe(4, 6)
  • Sample 2: position 0sinusoidal_pe(1, 4)[0]
  • Test 3: position 50sinusoidal_pe(51, 8)[50]