v9.1.1
Menu

Simulate Sinusoidal Positional Encoding

mediumFREETransformersMath, ArrayAdvanced Architectures

Positional Encoding injects positional information into Transformer input sequences, as self-attention is inherently permutation invariant.

The sinusoidal positional encoding for token at position ii with embedding dimension DD is calculated as:

pi,k={sin⁡(i/10000k/D)if k is evencos⁡(i/10000(k−1)/D)if k is oddp_{i,k} = \begin{cases} \sin(i / 10000^{k/D}) & \text{if } k \text{ is even} \\ \cos(i / 10000^{(k-1)/D}) & \text{if } k \text{ is odd} \end{cases}

Task: Implement a function that generates the positional encoding vector pp of length DD for a token at sequence index ii.

Example

Input
i=0, D=4
Output
[0.0000, 1.0000, 0.0000, 1.0000]
Reasoning
  • Inputs: i is the token's position in the sequence (here i=0i = 0, the first token) and D is the embedding size (here D=4D = 4), so the output is a vector of 4 numbers indexed k=0,1,2,3k = 0, 1, 2, 3.
  • Pairing: dimensions come in sine/cosine pairs that share one frequency. For D=4D = 4: pair (k=0,k=1)(k=0, k=1) divides by 100000/4=110000^{0/4} = 1, and pair (k=2,k=3)(k=2, k=3) divides by 100002/4=10010000^{2/4} = 100.
  • Angles: every angle is ii divided by that scale, so at i=0i = 0 all angles are 0/1=00/1 = 0 and 0/100=00/100 = 0.
  • Values: even slots take the sine of 0, which is 00, and odd slots take the cosine of 0, which is 11, producing [0.0000, 1.0000, 0.0000, 1.0000].
  • Notice: position 0 hides the frequencies entirely. At i=1i = 1 the first pair becomes sine and cosine of 11 radian (0.84150.8415, 0.54030.5403), while the slow pair barely moves: sine and cosine of 0.010.01 give 0.010.01 and 1.01.0. Later dimensions rotate more slowly, which is what lets distant positions stay distinguishable.

Constraints

  • 0≤i<10000 \leq i < 1000
  • DD is an even integer: 2≤D≤5122 \leq D \leq 512

Learn this in

More from Advanced Architectures

solution.py

Test results

Sign in to run your code against the test cases.