61. Rotary Positional Embedding medium
Implement a GPU program that computes the Rotary Positional Embedding (RoPE) for a batch of query vectors. RoPE is a method for encoding positional information in transformer models by rotating the query and key vectors using precomputed cosine and sine components.
Mathematically, given a query vector and corresponding cosine and sine vectors, the operation is defined as:
Where denotes element-wise multiplication. The operation swaps the first and second halves of the vector and negates the first half. For a vector of dimension :
Implementation Requirements
- External libraries are not permitted
- The
solvefunction signature must remain unchanged - The input tensors
Q,cos, andsinhave shape(M, D), whereMis the number of tokens andDis the head dimension cosandsinuse half-split layout: values at dimensionsjandj + D/2are identical for each rowD(head dimension) is guaranteed to be an even number- The final result must be stored in the output variable with the same shape
(M, D)
Example 1:
Input: Q = [[1.0, 2.0, 3.0, 4.0],
[1.0, 1.0, 1.0, 1.0]]
Cos = [[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 0.0]]
Sin = [[0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 1.0, 1.0]]
Output: result = [[1.0, 2.0, 3.0, 4.0],
[-1.0, -1.0, 1.0, 1.0]]
(Row 0 is identity via Cos; Row 1 is rotated via Sin)
Constraints
Q,cos, andsinhave identical dimensionsD% 2 == 0- 1 ≤
M,D≤ 10,000 - Performance is measured with
D= 128,M= 1,048,576
Starter code (CUDA)
#include <cuda_runtime.h>
// Q, cos, sin, output are device pointers
extern "C" void solve(float* Q, float* cos, float* sin, float* output, int M, int D) {}
From LeetGPU, CC BY-NC-ND 4.0.