Skip to Content
OchreML
Transformer & LoRA

CausalLM

LLaMA-style causal language model with RMSNorm, GQA + RoPE, SwiGLU, zero-GIL train_steps() and generate(), and .dit Tag 101 persistence.

ochreml.nn.CausalLM is a complete LLaMA-style decoder-only language model implemented natively in Rust with RMSNorm, Grouped-Query Attention (num_kv_heads), RoPE, SwiGLU, pre-allocated KVCache inference, zero-GIL train_steps() / generate(), and .dit Tag 101 binary persistence.

Import & Signature

import ochreml.nn as nn

lm = nn.CausalLM(
    vocab_size,
    d_model,
    num_layers,
    num_heads,
    num_kv_heads=None,
    ffn_hidden_dim=None,
    max_seq_len=2048,
    rope_theta=10000.0,
    norm_eps=1e-5,
    dtype="float32",
    device=None,
    seed=42,
)

Key Methods

MethodSignatureDescription
forward(input_ids, batch=None, seq_len=None, kv_caches=None) -> TensorComputes next-token logits (batch, seq_len, vocab_size).
new_kv_caches(batch=1) -> list[KVCache]Allocates one KVCache per transformer layer.
train_steps(input_ids, targets, batch=None, seq_len=None, steps=1, lr=1e-3, weight_decay=0.0, grad_clip=None) -> list[float]Zero-GIL multi-step AdamW + CrossEntropy training in Rust.
generate(prompt_ids, max_new_tokens=32, temperature=1.0, top_k=0, top_p=1.0, seed=42) -> list[int]Zero-GIL autoregressive sampling with pre-allocated KVCache.
save / loadsave(path) / CausalLM.load(path, device=None)Binary .dit persistence (Tag 101); also works with ochreml.save() / ochreml.load().
to_dit_bytes / from_dit_bytesto_dit_bytes() -> bytes / CausalLM.from_dit_bytes(data, device=None)In-memory .dit serialization.

Usage Example

import numpy as np
import ochreml
import ochreml.nn as nn

lm = nn.CausalLM(vocab_size=128, d_model=64, num_layers=2, num_heads=4, num_kv_heads=2)

rng = np.random.default_rng(42)
tokens = rng.integers(0, 128, size=(4, 17), dtype=np.int64)
losses = lm.train_steps(tokens[:, :-1], tokens[:, 1:], steps=10, lr=3e-3, grad_clip=1.0)

output_ids = lm.generate([1, 5, 9], max_new_tokens=16, temperature=0.8, top_k=20)
ochreml.save(lm, "causal_lm.dit")
reloaded = nn.CausalLM.load("causal_lm.dit", device="cpu")

On this page