Transformer & LoRA
PositionalEncoding & RoPE
Sinusoidal PositionalEncoding and Rotary Position Embeddings (RoPE) with offset support for KV-cached decoding.
ochreml.nn provides both classic additive sinusoidal PositionalEncoding (for [B, S, D] tensors) and modern Rotary Position Embeddings RoPE (for [B, H, S, D] attention tensors), both supporting an offset parameter for incremental KV-cache decoding.
Import & Signatures
import ochreml.nn as nn
pos = nn.PositionalEncoding(max_len, d_model)
# pos(x, offset=0) -> Tensor
rope = nn.RoPE(head_dim, max_seq_len=2048, theta=10000.0)
# rope(x, offset=0) -> TensorParameters
| Class | Parameter | Type | Default | Description |
|---|---|---|---|---|
PositionalEncoding | max_len | int | required | Maximum sequence length. |
PositionalEncoding | d_model | int | required | Embedding dimension D. |
RoPE | head_dim | int | required | Per-head dimension (must be even). |
RoPE | max_seq_len | int | 2048 | Maximum sequence length for frequency table. |
RoPE | theta | float | 10000.0 | Base frequency parameter. |
Usage Example
import ochreml.nn as nn
# Additive sinusoidal encoding on [batch, seq_len, d_model]
pe = nn.PositionalEncoding(max_len=512, d_model=64)
x = nn.Tensor.randn([2, 16, 64])
x_pos = pe(x, offset=0)
# Rotary embeddings on [batch, num_heads, seq_len, head_dim]
rope = nn.RoPE(head_dim=16, max_seq_len=512, theta=10000.0)
q = nn.Tensor.randn([2, 4, 16, 16])
q_rot = rope(q, offset=0)