Skip to content
module

RoFormer

17 members
lucid.models.text.roformer

RoFormer family — Su et al., 2021 (BERT + rotary position embedding).

Language ModelingSequence ClassificationToken Classification
Paper

Su, Jianlin, et al. "RoFormer: Enhanced Transformer with Rotary Position Embedding." Neurocomputing, vol. 568, 2024, article 127063.

Overview

RoFormer replaces BERT's absolute (learned) position embedding with Rotary Position Embedding (RoPE) — a position-encoding scheme that injects relative-position information multiplicatively inside attention rather than additively at the input.

Consider a query/key vector x∈Rdx \in \mathbb{R}^{d} at position mm. RoPE groups the dd features into d/2d/2 complex coordinates and rotates the ii-th pair (x2i,x2i+1)(x_{2i}, x_{2i+1}) by angle mθim \theta_i, where

θi=base−2i/d,i=0,1,…,d/2−1,\theta_i = \text{base}^{-2 i / d}, \qquad i = 0, 1, \dots, d/2 - 1,

and base (default 10 00010\,000) controls the spectrum of rotational frequencies. In complex form zi=x2i+j x2i+1z_i = x_{2i} + j\, x_{2i+1}, the rotation is just zi↦zi ejmθiz_i \mapsto z_i\, e^{j m \theta_i}.

The crucial property is that the attention dot product becomes a function of the relative offset m−nm - n only:

⟨Rm q,  Rn k⟩=Re⁡ ⁣∑izi(q)zi(k)‾ ej(m−n)θi=frel(q,k,m−n),\langle R_m\, q,\; R_n\, k \rangle = \operatorname{Re}\!\sum_i z_i^{(q)} \overline{z_i^{(k)}}\, e^{j (m - n) \theta_i} = f_{\text{rel}}(q, k, m - n),

so RoPE encodes relative positions without any extra parameters and without an additive bias term. This grants three practical benefits: (i) it generalises to longer sequences than seen during training (with mild quality decay), (ii) it composes naturally with linear attention variants because it acts on Q,KQ, K before the softmax, and (iii) it requires the per-head dimension dhead=dmodel/hd_{\text{head}} = d_{\text{model}} / h to be even — enforced by __post_init__ above. RoFormer otherwise mirrors BERT-base (L=12L=12, H=768H=768, A=12A=12) and is the de-facto position-encoding choice for modern LLaMA-/Mistral-style LLMs.

Classes

Functions

Weights