Skip to Content
OchreML
How-To Guides

Transformers, CausalLM, and LoRA

Build LLaMA-style CausalLM models with GQA, RoPE, and KV-Cache, compose custom Transformers, and fine-tune with LoRALinear and .dit persistence.

ochreml.nn includes a complete Rust Transformer stack built on the N7, N8, and N9 primitives: tiled FlashAttention-style ScaledDotProductAttention, Grouped-Query Attention (GQA), Rotary Position Embeddings (RoPE), pre-allocated KVCache, LLaMA-style CausalLM, and parameter-efficient LoRALinear fine-tuning with .dit persistence (^▽^).


LLaMA-Style CausalLM with GQA, RoPE, and KV-Cache

nn.CausalLM wires together token embeddings, RMSNorm, GQA MultiHeadAttention with RoPE, and SwiGLU feed-forward blocks in a single Rust module. Both train_steps() and generate() run 100% zero-GIL in Rust.

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

# 4-layer LLaMA-style LM using Grouped-Query Attention (4 query heads, 2 KV heads)
lm = nn.CausalLM(
    vocab_size=256,
    d_model=128,
    num_layers=4,
    num_heads=4,
    num_kv_heads=2,
    ffn_hidden_dim=384,
    max_seq_len=512,
    rope_theta=10000.0,
    dtype="float32",
    device="auto",
)
print(f"Total parameters: {lm.num_parameters():,}")

# Prepare next-token prediction pairs: input_ids and shifted targets
rng = np.random.default_rng(42)
tokens = rng.integers(0, 256, size=(4, 17), dtype=np.int64)
input_ids = tokens[:, :-1]   # shape: (4, 16)
targets = tokens[:, 1:]      # shape: (4, 16)

# Zero-GIL multi-step AdamW + CrossEntropy training in Rust
losses = lm.train_steps(
    input_ids,
    targets,
    steps=20,
    lr=3e-3,
    weight_decay=0.01,
    grad_clip=1.0,
)
print(f"Loss: {losses[0]:.4f} -> {losses[-1]:.4f}")

# Zero-GIL autoregressive generation using pre-allocated KVCaches
generated = lm.generate(
    prompt_ids=[1, 42, 7],
    max_new_tokens=24,
    temperature=0.8,
    top_k=40,
    top_p=0.9,
    seed=42,
)

# Persist full CausalLM to compact binary .dit (Tag 101)
ochreml.save(lm, "tiny_llm.dit")
reloaded = nn.CausalLM.load("tiny_llm.dit", device="auto")

Manual Incremental Decoding with KVCache

For custom sampling loops or beam search, allocate per-layer KVCache objects with lm.new_kv_caches(batch) and pass them into lm(...):

caches = lm.new_kv_caches(batch=1)

# 1. Prefill prompt tokens (populates KV caches up to len(prompt))
prefill_logits = lm([[1, 42, 7]], kv_caches=caches)  # shape: (1, 3, vocab_size)

# 2. Decode one token at a time reusing cached keys & values
next_token = int(prefill_logits.numpy()[0, -1].argmax())
step_logits = lm([[next_token]], kv_caches=caches)   # shape: (1, 1, vocab_size)
print(f"Cached sequence length: {caches[0].cur_len()}")

# Reset caches before starting a new sequence
for c in caches:
    c.reset()

Custom Transformer Encoders & Decoders

You can also compose encoder-only or encoder-decoder architectures using Embedding, PositionalEncoding, TransformerEncoder, and TransformerDecoder:

import ochreml.nn as nn


class Seq2SeqTransformer(nn.Module):
    def __init__(self, vocab_size: int, d_model: int = 64) -> None:
        super().__init__()
        self.embed = nn.Embedding(vocab_size, d_model)
        self.pos = nn.PositionalEncoding(max_len=256, d_model=d_model)
        self.encoder = nn.TransformerEncoder(
            num_layers=2, d_model=d_model, num_heads=4, d_ff=256, pre_norm=True
        )
        self.decoder = nn.TransformerDecoder(
            num_layers=2,
            d_model=d_model,
            num_heads=4,
            d_ff=256,
            with_cross_attn=True,
            use_swiglu=True,
        )
        self.lm_head = nn.Linear(d_model, vocab_size, bias=False)

    def forward(self, src_ids, tgt_ids) -> nn.Tensor:
        memory = self.encoder(self.pos(self.embed(src_ids)))
        decoded = self.decoder(self.pos(self.embed(tgt_ids)), memory=memory)
        return self.lm_head(decoded)

Parameter-Efficient Fine-Tuning with LoRALinear

nn.LoRALinear wraps a frozen base Linear weight W with trainable low-rank adapters A (shape (rank, in_features)) and B (shape (out_features, rank)), computing:

y = x @ W^T + (alpha / rank) * ((x @ A^T) @ B^T) + b

Only lora_a and lora_b are exposed in parameters(), keeping VRAM usage and adapter checkpoint sizes tiny (*≧ω≦*).

import ochreml.nn as nn

# Wrap an existing pretrained Linear layer with a frozen base weight
base_linear = nn.Linear(128, 128)
lora_layer = nn.LoRALinear.from_linear(base_linear, rank=4, alpha=8.0)

# Only lora_a and lora_b are trainable
optimizer = nn.AdamW(lora_layer.parameters(), lr=1e-3)
x = nn.Tensor.randn([8, 128])
target = nn.Tensor.randn([8, 128])

for _ in range(10):
    optimizer.zero_grad()
    loss = nn.MSELoss()(lora_layer(x), target)
    loss.backward()
    optimizer.step()

# Fold LoRA delta into the base weight for zero-overhead inference
lora_layer.merge_weights()
assert lora_layer.merged is True
fast_out = lora_layer(x)

# Unmerge before further training or swapping adapters
lora_layer.unmerge_weights()

Persisting LoRA Adapters (.dit Tag 102)

Store one or many named LoRALinear adapters in a compact .dit file using nn.LoRAAdapterState (Tag 102) — without duplicating the frozen base weights:

import ochreml.nn as nn

# Collect named adapters and save to a single .dit file
adapters = nn.LoRAAdapterState()
adapters.insert("attn.q_proj", lora_layer)
adapters.save("task_adapter.dit")

# Reload on any device and apply onto a matching LoRALinear layer
loaded = nn.LoRAAdapterState.load("task_adapter.dit", device="cpu")
print("Adapters in file:", loaded.names())  # ['attn.q_proj']

fresh_lora = nn.LoRALinear.from_linear(base_linear, rank=4, alpha=8.0)
loaded.apply_to("attn.q_proj", fresh_lora)

For a single layer, you can also call lora_layer.save_adapter("single.dit", name="default") and lora_layer.load_adapter("single.dit", name="default") directly.

On this page