v9.1.1
Menu

Sinusoidal Positional Encoding

mediumFREEEmbeddings & Positional EncodingLLM 1: Foundations

Implement the sinusoidal positional encoding from "Attention Is All You Need".

For a sequence of length L and model dimension D, compute the positional encoding matrix PE where:

  • PE(pos, 2i) = sin(pos / 10000^(2i/D))
  • PE(pos, 2i+1) = cos(pos / 10000^(2i/D))

Input:

  • L: sequence length (number of positions)
  • D: model dimension (even)

Output: Implement sinusoidal_pe(L, D) returning the L x D positional encoding matrix as a NumPy array, one row per position. The tests print each value to 4 decimal places.

Example

Input
2 4
Output
[0.0000 1.0000 0.0000 1.0000]
[0.8415 0.5403 0.0100 1.0000]
Reasoning
  • Inputs: L =2= 2 positions (rows 0 and 1) and D =4= 4 dimensions, so the result is a 2×42 \times 4 matrix. The 4 columns form 2 sin/cos pairs, one pair per frequency.
  • Denominators: pair i=0i = 0 (columns 0–1) uses 100000/4=110000^{0/4} = 1; pair i=1i = 1 (columns 2–3) uses 100002/4=10010000^{2/4} = 100.
  • pos = 0: every angle is 00, so each pair gives sin⁡0=0\sin 0 = 0, cos⁡0=1\cos 0 = 1 → [0.0000 1.0000 0.0000 1.0000]. Position 0 always looks like this, whatever DD is.
  • pos = 1, pair 0: angle 1/1=11/1 = 1 radian → sin⁡1≈0.8415\sin 1 \approx 0.8415, cos⁡1≈0.5403\cos 1 \approx 0.5403.
  • pos = 1, pair 1: angle 1/100=0.011/100 = 0.01 → sin⁡0.01≈0.0099998→0.0100\sin 0.01 \approx 0.0099998 \to 0.0100 and cos⁡0.01≈0.99995→1.0000\cos 0.01 \approx 0.99995 \to 1.0000 after rounding to 4 decimal places.
  • Notice that the first pair swings a full radian per step while the second barely moves: higher pairs rotate more slowly, which is how the encoding distinguishes positions far apart.

Constraints

  • 1 <= L <= 20, 2 <= D <= 16 (D is even)
  • Use base 10000 for the frequency
  • Round to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.