TensorTonic
Study Plans
Study Plan
Rotary Query and Key Embeddings
Language ModelsTransformers
Medium

Apply rotary position embeddings to adjacent coordinate pairs in query and key tensors of shape (B, H, S, D). For position p and pair index i, the rotation is

θi=pωi.\theta_i=p\omega_i.θi​=pωi​. x2i′=x2icos⁡θi−x2i+1sin⁡θi.x'_{2i}=x_{2i}\cos\theta_i-x_{2i+1}\sin\theta_i.x2i′​=x2i​cosθi​−x2i+1​sinθi​. x2i+1′=x2isin⁡θi+x2i+1cos⁡θi.x'_{2i+1}=x_{2i}\sin\theta_i+x_{2i+1}\cos\theta_i.x2i+1′​=x2i​sinθi​+x2i+1​cosθi​.

Here B is batch size, H is head count, S is sequence length, and D is the even head width. The vector x is one query or key, x' is its rotated value, i runs from zero to D/2 minus one, omega is the supplied inverse-frequency vector, and theta is an angle in radians. Positions of shape (S) are shared across batches; shape (B, S) supplies batch-specific positions.

Return a Python dictionary with q_rotated and k_rotated as PyTorch tensors, each preserving its corresponding input's shape, dtype, and device.

Loading visualization...

Examples

Input: q = [[[[1,0],[0,1]]]], k = [[[[1,1],[1,0]]]], positions = [0,1], inv_freq = [1]

Output: {"q_rotated":[[[[1,0],[-0.841471,0.540302]]]],"k_rotated":[[[[1,1],[0.540302,0.841471]]]]}

Explanation: Position zero leaves the first coordinate pair unchanged. Position one rotates the second pair by one radian.

Input: q = [[[[2,3]]]], k = [[[[1,0.5]]]], positions = [50], inv_freq = [0.01]

Output: {"q_rotated":[[[[0.316888,3.591599]]]],"k_rotated":[[[[0.63787,0.918217]]]]}

Input: q = [[[[1,0],[1,0]]],[[[1,0],[1,0]]]], k = [[[[0,1],[0,1]]],[[[0,1],[0,1]]]], positions = [[0,1],[2,3]], inv_freq = [1]

Output: {"q_rotated":[[[[1,0],[0.540302,0.841471]]],[[[-0.416147,0.909297],[-0.989992,0.14112]]]],"k_rotated":[[[[0,1],[-0.841471,0.540302]]],[[[-0.909297,-0.416147],[-0.14112,-0.989992]]]]}

Hint 1

A step-two slice selects alternating coordinates along the last axis.

Hint 2

Tensor.unsqueeze adds axes for position-frequency broadcasting.

Hint 3

torch.stack and Tensor.flatten can interleave paired coordinates.

Requirements

  • Use PyTorch with float32 arithmetic for angles and rotations, preserving each query or key input dtype in its result.
  • Query and key dtypes may be float32 or bfloat16; positions and inverse frequencies are float32 tensors.
  • Public cases and custom Run inputs use float32 throughout.
  • Leave all four input tensors unchanged.

Constraints

  • q and k are PyTorch tensors with the same shape (B, H, S, D); all dimensions are positive and D is even.
  • positions is a PyTorch float32 tensor of shape (S) or (B, S).
  • inv_freq is a PyTorch float32 tensor of shape (D / 2).
  • Query and key tensors have float32 or bfloat16 dtype; all inputs share a device and contain finite values.
Try Similar Problems
Causal Grouped-Query AttentionHardAssign Multimodal RoPE CoordinatesMediumParameter-Matched SwiGLU BlockMediumDecode Attention with a KV CacheHardPatchify a Batch of ImagesEasyNamed-Dimension Batched Attention ScoresEasyTransformer Training FLOP EstimatorEasyRMSNorm Forward PassEasyImplement Multi-Head Attention (MHA)MediumImplement Prefix Cache Matching and ReuseMediumImplement Autoregressive Decoding with a KV CacheMediumMasked Causal AttentionMedium

Accepts: array

Accepts: array

Accepts: array

Accepts: array

You must run your code first.

Rotary Query and Key Embeddings

Language ModelsTransformers
Medium

Apply rotary position embeddings to adjacent coordinate pairs in query and key tensors of shape (B, H, S, D). For position p and pair index i, the rotation is

θi=pωi.\theta_i=p\omega_i.θi​=pωi​. x2i′=x2icos⁡θi−x2i+1sin⁡θi.x'_{2i}=x_{2i}\cos\theta_i-x_{2i+1}\sin\theta_i.x2i′​=x2i​cosθi​−x2i+1​sinθi​. x2i+1′=x2isin⁡θi+x2i+1cos⁡θi.x'_{2i+1}=x_{2i}\sin\theta_i+x_{2i+1}\cos\theta_i.x2i+1′​=x2i​sinθi​+x2i+1​cosθi​.

Here B is batch size, H is head count, S is sequence length, and D is the even head width. The vector x is one query or key, x' is its rotated value, i runs from zero to D/2 minus one, omega is the supplied inverse-frequency vector, and theta is an angle in radians. Positions of shape (S) are shared across batches; shape (B, S) supplies batch-specific positions.

Return a Python dictionary with q_rotated and k_rotated as PyTorch tensors, each preserving its corresponding input's shape, dtype, and device.

Loading visualization...

Examples

Input: q = [[[[1,0],[0,1]]]], k = [[[[1,1],[1,0]]]], positions = [0,1], inv_freq = [1]

Output: {"q_rotated":[[[[1,0],[-0.841471,0.540302]]]],"k_rotated":[[[[1,1],[0.540302,0.841471]]]]}

Explanation: Position zero leaves the first coordinate pair unchanged. Position one rotates the second pair by one radian.

Input: q = [[[[2,3]]]], k = [[[[1,0.5]]]], positions = [50], inv_freq = [0.01]

Output: {"q_rotated":[[[[0.316888,3.591599]]]],"k_rotated":[[[[0.63787,0.918217]]]]}

Input: q = [[[[1,0],[1,0]]],[[[1,0],[1,0]]]], k = [[[[0,1],[0,1]]],[[[0,1],[0,1]]]], positions = [[0,1],[2,3]], inv_freq = [1]

Output: {"q_rotated":[[[[1,0],[0.540302,0.841471]]],[[[-0.416147,0.909297],[-0.989992,0.14112]]]],"k_rotated":[[[[0,1],[-0.841471,0.540302]]],[[[-0.909297,-0.416147],[-0.14112,-0.989992]]]]}

Hint 1

A step-two slice selects alternating coordinates along the last axis.

Hint 2

Tensor.unsqueeze adds axes for position-frequency broadcasting.

Hint 3

torch.stack and Tensor.flatten can interleave paired coordinates.

Requirements

  • Use PyTorch with float32 arithmetic for angles and rotations, preserving each query or key input dtype in its result.
  • Query and key dtypes may be float32 or bfloat16; positions and inverse frequencies are float32 tensors.
  • Public cases and custom Run inputs use float32 throughout.
  • Leave all four input tensors unchanged.

Constraints

  • q and k are PyTorch tensors with the same shape (B, H, S, D); all dimensions are positive and D is even.
  • positions is a PyTorch float32 tensor of shape (S) or (B, S).
  • inv_freq is a PyTorch float32 tensor of shape (D / 2).
  • Query and key tensors have float32 or bfloat16 dtype; all inputs share a device and contain finite values.
Try Similar Problems
Causal Grouped-Query AttentionHardAssign Multimodal RoPE CoordinatesMediumParameter-Matched SwiGLU BlockMediumDecode Attention with a KV CacheHardPatchify a Batch of ImagesEasyNamed-Dimension Batched Attention ScoresEasyTransformer Training FLOP EstimatorEasyRMSNorm Forward PassEasyImplement Multi-Head Attention (MHA)MediumImplement Prefix Cache Matching and ReuseMediumImplement Autoregressive Decoding with a KV CacheMediumMasked Causal AttentionMedium

Accepts: array

Accepts: array

Accepts: array

Accepts: array

You must run your code first.