ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Sinusoidal Positional Encoding

Compute the sine and cosine position vectors Transformers add to token embeddings.

สิ่งที่คุณจะได้เรียนรู้

  • Compute sine and cosine position vectors
  • Use different frequencies per dimension
  • Understand how Transformers know word order

โจทย์

ดูฉบับแปล

Attention ignores word order, so the original Transformer adds a positional encoding to each token embedding. For position pos and dimension j (both starting at 0) in a model of size d_model:

  • even j: PE[pos][j] = sin(pos / 10000^(j / d_model))
  • odd j: PE[pos][j] = cos(pos / 10000^((j - 1) / d_model))

So dimensions 0 and 1 share one frequency, dimensions 2 and 3 the next, and so on.

Implement positional_encoding(length, d_model).

Input

length: The number of positions (0 to length - 1).

d_model: The embedding size.

Output

Return a length × d_model matrix.

เงื่อนไข

1 ≤ length ≤ 200, 1 ≤ d_model ≤ 128

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
length = 2
d_model = 4

ผลลัพธ์ที่คาดหวัง:
expected = [
    [0.0, 1.0, 0.0, 1.0],
    [0.841471, 0.540302, 0.01, 0.99995]
]
อินพุต:
long long length = 2;
long long d_model = 4;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<double>> expected = {
    {0.0, 1.0, 0.0, 1.0},
    {0.841471, 0.540302, 0.01, 0.99995}
};
อินพุต:
long length = 2;
long d_model = 4;

ผลลัพธ์ที่คาดหวัง:
double[][] expected = new double[][] {
    new double[] {0.0, 1.0, 0.0, 1.0},
    new double[] {0.841471, 0.540302, 0.01, 0.99995}
};

คำอธิบาย

Position 0 is sin(0) = 0 and cos(0) = 1 for every pair: [0, 1, 0, 1]. Position 1 uses frequencies 1 and 1 / 10000^(2/4) = 0.01: [sin 1, cos 1, sin 0.01, cos 0.01] ≈ [0.841471, 0.540302, 0.01, 0.99995].

ตัวอย่างที่ 2
อินพุต:
length = 3
d_model = 1

ผลลัพธ์ที่คาดหวัง:
expected = [
    [0.0],
    [0.841471],
    [0.909297]
]
อินพุต:
long long length = 3;
long long d_model = 1;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<double>> expected = {
    {0.0},
    {0.841471},
    {0.909297}
};
อินพุต:
long length = 3;
long d_model = 1;

ผลลัพธ์ที่คาดหวัง:
double[][] expected = new double[][] {
    new double[] {0.0},
    new double[] {0.841471},
    new double[] {0.909297}
};

คำอธิบาย

With one dimension only sin(pos) is used: [[0], [0.841471], [0.909297]].

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก