Positional Encoding: Giving Attention a Sense of Order

TransformersMedium+20 XP+15

Positional Encoding: Giving Attention a Sense of Order

Attention has no idea what order its inputs came in — shuffle the tokens and it computes the same thing. Positional encoding is the fix: add a distinct, position-dependent vector to every token embedding.

For position pos and dimension index i in a model of width d_model:

indexvalue
even isin(pos / 10000^(2⌊i/2⌋ / d_model))
odd icos(pos / 10000^(2⌊i/2⌋ / d_model))

Note the ⌊i/2⌋ — dimensions 0 and 1 share a frequency, 2 and 3 share the next, and so on. Each sin/cos pair is one rotating clock hand.

Task: write positional_encoding(seq_len, d_model) returning a seq_len × d_model table, every value rounded to 4 decimal places.

  • seq_len = 0 returns an empty list.
  • Positions start at 0.

The wavelengths run from 2π up to about 10000·2π. Low dimensions flip quickly and pin down local order; high dimensions barely move across the whole sequence and encode roughly where you are overall.

Examples

seq_len = 3
d_model = 4
returns [[0.0, 1.0, 0.0, 1.0], [0.8415, 0.5403, 0.01, 1.0], [0.9093, -0.4161, 0.02, 0.9998]]
seq_len = 1
d_model = 2
returns [[0.0, 1.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run