Here’s a RoPE written in “one-liner spirit”, but with a small trick:
• We treat every even/odd pair in the last dimension as one complex number
• A rotary position update is nothing but a complex multiplication with e^{iθ}
• jax.lax.complex / real / imag let us stay on the XLA fast-path and avoid extra reshapes/copies
That gives a surprisingly tiny yet very fast implementation.
import jax
import jax.numpy as jnp
import flax.linen as nn
from jax import lax
from typing import Optional
class RoPE(nn.Module):
"""
Rotary Positional Embedding using an interleaved (complex) trick.
Last dim D must be even; pairs [d, d+1] are (real, imag).
"""
base: float = 10_000.0
max_length: int = 8192 # keep for potential KV-cache use
@nn.compact
def __call__(self, x: jnp.ndarray, # [B, L, H, D]
pos: Optional[jnp.ndarray] = None
) -> jnp.ndarray:
B, L, H, D = x.shape
assert D % 2 == 0, "D must be even (pairs form complex numbers)"
# 1. Generate (or receive) positions ..................................
if pos is None: # → [L]
pos = jnp.arange(L, dtype=x.dtype)
pos = pos.reshape(1, L, 1, 1) # [1, L, 1, 1] (broadcast later)
# 2. Build inverse-frequency vector ...................................
idx = jnp.arange(0, D, 2, dtype=x.dtype) # even indices
inv_freq = 1.0 / (self.base ** (idx / D)) # [D/2]
# 3. θ = pos * inv_freq → complex rotation coef e^{iθ} ..............
# θ shape: [1, L, 1, D/2] (broadcast B & H automatically)
theta = pos * inv_freq # broadcast rules do the magic
rotator = lax.complex(jnp.cos(theta), jnp.sin(theta)) # e^{iθ}
# 4. View x as complex, multiply, and split back to real..............
x_c = lax.complex(x[..., 0::2], x[..., 1::2]) # [B,L,H,D/2] complex
x_c = x_c * rotator # rotate
# 5. Scatter real/imag parts back into original tensor shape ..........
out = jnp.empty_like(x)
out = out.at[..., 0::2].set(lax.real(x_c))
out = out.at[..., 1::2].set(lax.imag(x_c))
return out
Why this version has a little “wow” factor 🤩
- Complex trick ⇒ no manual 2×2 rotation math, just a single
* rotator.
lax.complex/real/imag keeps everything on device, avoids Python-level loops and extra reshapes, and fuses nicely under JIT/pmap.
- Broadcasting rules (thanks to the added size-1 axes) remove the need for explicit
jnp.broadcast_to, making the code both shorter and cheaper.
- Works for arbitrary batch & head sizes, for training or autoregressive KV-cache (just slice
pos).
- Readability: the whole rotation core is literally three lines (
theta, rotator, x_c = x_c * rotator).
Quick test:
rng = jax.random.key(0)
x = jax.random.normal(rng, (2, 512, 8, 64)) # B,L,H,D
rope = RoPE()
y = rope.init_with_output(rng, x)[0] # forward + init params
print(y.shape) # (2, 512, 8, 64)