📘
Sinusoidal Positional Encoding
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:
- Line 1: L D (sequence length, model dimension)
Output: The L x D positional encoding matrix, values rounded to 4 decimal places, one row per position.
Example:
Input:
2 4
Output:
[ 0.0000 1.0000 0.0000 1.0000] [ 0.8415 0.5403 0.0100 0.9999]
Reasoning:
- We calculate the positional encoding matrix
PEfor a sequence of lengthL = 2and model dimensionD = 4. - For each position
posin the sequence, we compute the values ofPE(pos, 2i)andPE(pos, 2i+1)using the given formulas: PE(pos,2i)=sin(pos/100002i/D) and PE(pos,2i+1)=cos(pos/100002i/D). - We evaluate these formulas for
pos = 0andpos = 1, andi = 0andi = 1, to get the values for the first and second positions:- For
pos = 0, we get PE(0,0)=sin(0/100000/4)=sin(0)=0, PE(0,1)=cos(0/100000/4)=cos(0)=1, PE(0,2)=sin(0/100001/4)=sin(0)=0, PE(0,3)=cos(0/100001/4)=cos(0)=1. - For
pos = 1, we get PE(1,0)=sin(1/100000/4)=sin(1)≈0.8415, PE(1,1)=cos(1/100000/4)=cos(1)≈0.5403, PE(1,2)=sin(1/100001/4)≈sin(0.0100)≈0.0100, PE(1,3)=cos(1/100001/4)≈cos(0.0100)≈0.9999.
- For
- The final output is the matrix with these computed values, rounded to 4 decimal places: [ 0.0000 1.0000
Constraints:
- 1 <= L <= 20, 2 <= D <= 16 (D is even)
- Use base 10000 for the frequency
- Round to 4 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.