Write the best possible implementation of a JAX & Flax module that applies rotary positional embeddings (RoPE) to a tensor x of fixed size [B, L, H, D].
By "best implementation", the idea is that it should be clean, short, pythonic, yet efficient.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a clean and efficient JAX/Flax implementation of RoPE:
python
import jax
import jax.numpy as jnp
import flax.linen as nn
from typing import Optional
class RoPE(nn.Module):
"""Rotary Positional Embedding (RoPE) module."""
max_length: int = 8192
base: float = 10000.0
def setup(self):
# Precompute frequency matrix
dim = None # Will be inferred from input
@nn.compact
def __call__(self, x: jnp.ndarray, positions: Optional[jnp.ndarray] = None) -> jnp.ndarray:
"""
Apply RoPE to input tensor.
Args:
x: Input tensor of shape [B, L, H, D]
positions: Optional position indices [B, L]. If None, uses range(L)
Returns:
Tensor with RoPE applied, same shape as input
"""
B, L, H, D = x.shape
# Generate position indices if not provided
if positions is None:
positions = jnp.arange(L)[None, :] # [1, L]
positions = jnp.broadcast_to(positions, (B, L)) # [B, L]
# Compute frequency matrix
dim_pairs = D // 2
inv_freq = 1.0 / (self.base ** (jnp.arange(0, dim_pairs) * 2.0 / D))
# Compute angles: [B, L, D//2]
angles = positions[..., None] * inv_freq[None, None, :]
# Compute cos and sin
cos_vals = jnp.cos(angles) # [B, L, D//2]
sin_vals = jnp.sin(angles) # [B, L, D//2]
# Reshape x for rotation: [B, L, H, D//2, 2]
x_pairs = x.reshape(B, L, H, dim_pairs, 2)
# Apply rotation
x_rot = jnp.stack([
x_pairs[..., 0] * cos_vals[:, :, None, :] - x_pairs[..., 1] * sin_vals[:, :, None, :],
x_pairs[..., 1] * cos_vals[:, :, None, :] + x_pairs[..., 0] * sin_vals[:, :, None, :]
], axis=-1)
# Reshape back to original shape
return x_rot.reshape(B, L, H, D)
# Usage example:
# rope = RoPE()
# x = jnp.ones((2, 512, 8, 64)) # [B, L, H, D]
# x_rope = rope(x)
This implementation is:
Clean: Uses clear variable names and follows standard JAX/Flax patterns with @nn.compact for dynamic shape inference.
Short: ~40 lines including comments and docstring, focusing on the essential RoPE computation.
Pythonic: Leverages JAX's vectorized operations and broadcasting, uses type hints, and follows Python naming conventions.
Efficient:
Precomputes frequencies once per call
Uses vectorized operations throughout
Minimizes reshaping operations
Broadcasts position encodings efficiently across batch and head dimensions
The key insight is reshaping the last dimension into pairs [..., D//2, 2] to apply the 2D rotation matrix efficiently using JAX's vectorized operations, then reshaping back to the original dimensions.