Documentation Index
Fetch the complete documentation index at: https://mintlify.com/itsubaki/gpt/llms.txt
Use this file to discover all available pages before exploring further.
function.RoPE implements Rotary Position Embeddings (RoPE), precomputing cosine and sine lookup tables for all positions and head dimensions up to contextLen. It returns a curried RoPEFunc that can be applied to query and key tensors in any attention layer. Because the tables are computed once at model construction, there is no per-step overhead during forward or backward passes.
RoPEFunc type
RoPEFunc is a two-level curried function:
Position offset for KV-cache-based generation — the number of tokens already present in the cache. During training (no cache) this is
0. During incremental decoding, pass the current cache length so that new tokens are embedded at the correct absolute positions.rope(offset) returns a standard autograd-compatible function that accepts a tensor of shape (B, H, C, D) and returns the rotated tensor of the same shape:
| Dimension | Meaning |
|---|---|
B | Batch size |
H | Number of attention heads |
C | Sequence length (context window) |
D | Head dimension (embedDim) — must be even |
RoPE() constructor
RoPEFunc. Panics if embedDim is odd.
Base frequency for the geometric sequence of rotation frequencies. The default is
10000. Higher values extend the effective context length — LLaMA 3 uses 500000.Head dimension from the attention layer. Must be even; the dimension is split into
embedDim/2 rotation pairs.Maximum sequence length. Determines the size of the precomputed tables:
(contextLen, embedDim/2) for both cosine and sine.pos in [0, contextLen) and each dimension pair i in [0, embedDim/2):
contextLen × (embedDim/2), addressed as pos * halfDim + i.
Rotation formula
During the forward pass, each consecutive pair of dimensions(d, d+1) at every position is rotated by the precomputed angle for that (position, pair) index:
(x[d], x[d+1]) as a complex number and multiplying by e^{iθ} = cos + i·sin.
Backward pass
The gradient of the rotation with respect to the input is the transpose of the rotation matrix, which is itself a rotation by the conjugate angle (-θ):
sin sign-flipped for the cross terms.
Backward example:
Usage in model
RoPE is constructed once at model initialisation and the same RoPEFunc is shared across all transformer blocks. Each block applies it independently to its query and key projections:
Offset clamping
Ifoffset + C > contextLen, the offset is automatically clamped to contextLen - C:
contextLen. During normal training (offset = 0, C ≤ contextLen) the clamp is a no-op.