Skip to Content
OchreML
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) -> Tensor

MultiHeadAttention Parameters

ParameterTypeDefaultDescription
d_modelintrequiredModel embedding dimension (must be divisible by num_heads).
num_headsintrequiredNumber of query attention heads.
num_kv_headsint | NoneNoneNumber of key/value heads (defaults to num_heads; set < num_heads for GQA, 1 for MQA).
biasboolTrueInclude bias terms in Q/K/V/O projections.
causalboolFalseApply upper-triangular causal attention mask.
use_ropeboolFalseApply Rotary Position Embeddings to Q and K before attention.
max_seq_lenint2048Maximum sequence length for RoPE precomputation.
rope_thetafloat10000.0RoPE 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

On this page