Transformer & LoRA
Attention & KVCache
Tiled FlashAttention-style ScaledDotProductAttention, MHA/GQA/MQA MultiHeadAttention, and pre-allocated KVCache.
ochreml.nn implements tiled FlashAttention-style scaled dot-product attention (ScaledDotProductAttention), Grouped-Query / Multi-Query / Multi-Head Attention (MultiHeadAttention), and pre-allocated key-value caching (KVCache) on top of the N7 and N8 Rust primitives.
Import & Signatures
import ochreml.nn as nn
sdpa = nn.ScaledDotProductAttention()
# sdpa(q, k, v, causal=False, kv_offset=0) -> Tensor
cache = nn.KVCache(batch, num_kv_heads, max_seq_len, head_dim)
# cache.reset(), cache.cur_len(), cache.max_seq_len
mha = nn.MultiHeadAttention(
d_model,
num_heads,
num_kv_heads=None,
bias=True,
causal=False,
use_rope=False,
max_seq_len=2048,
rope_theta=10000.0,
dtype="float32",
device=None,
seed=42,
)
# mha(q, k, v, kv_cache=None) -> TensorMultiHeadAttention Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
d_model | int | required | Model embedding dimension (must be divisible by num_heads). |
num_heads | int | required | Number of query attention heads. |
num_kv_heads | int | None | None | Number of key/value heads (defaults to num_heads; set < num_heads for GQA, 1 for MQA). |
bias | bool | True | Include bias terms in Q/K/V/O projections. |
causal | bool | False | Apply upper-triangular causal attention mask. |
use_rope | bool | False | Apply Rotary Position Embeddings to Q and K before attention. |
max_seq_len | int | 2048 | Maximum sequence length for RoPE precomputation. |
rope_theta | float | 10000.0 | RoPE base frequency. |
Usage Example
import ochreml.nn as nn
# Grouped-Query Attention: 8 query heads sharing 2 KV heads, with RoPE and KV-cache
attn = nn.MultiHeadAttention(
d_model=64, num_heads=8, num_kv_heads=2, causal=True, use_rope=True
)
cache = nn.KVCache(batch=2, num_kv_heads=2, max_seq_len=128, head_dim=8)
x = nn.Tensor.randn([2, 10, 64])
out = attn(x, x, x, kv_cache=cache) # shape: (2, 10, 64)
print("Cached tokens:", cache.cur_len()) # 10