Sequence Models (RNN, GRU, LSTM)
Train multi-layer and bidirectional RNN, GRU, and LSTM networks with fused gate projections, BPTT, gradient clipping, and zero-GIL train_steps().
ochreml.nn provides native Rust implementations of RNN, GRU, and LSTM with fused gate projections, full Backpropagation Through Time (BPTT), multi-layer stacking, bidirectional execution, and optional zero-GIL train_steps() (*≧ω≦*).
All sequence layers use batch-first tensor layout:
- Input
x:(batch, seq_len, input_size) - Output
out:(batch, seq_len, hidden_size * num_directions)wherenum_directionsis2ifbidirectional=True, else1. - Final hidden state
hn(and cell statecnforLSTM):(num_layers * num_directions, batch, hidden_size).
Fast Zero-GIL Training with train_steps()
RNN, GRU, and LSTM expose a built-in .train_steps() method that runs multiple AdamW + MSE optimization steps (with optional global L2 gradient clipping) entirely inside Rust without Python loop overhead.
import numpy as np
import ochreml.nn as nn
rng = np.random.default_rng(42)
batch, seq_len, in_dim, hidden_dim = 16, 20, 8, 32
# Input and target sequences: (batch, seq_len, features)
X_seq = rng.standard_normal((batch, seq_len, in_dim)).astype(np.float32)
Y_target = rng.standard_normal((batch, seq_len, hidden_dim)).astype(np.float32)
gru = nn.GRU(
input_size=in_dim,
hidden_size=hidden_dim,
num_layers=2,
bidirectional=False,
device="auto",
)
losses = gru.train_steps(
X_seq,
Y_target,
steps=50,
lr=3e-3,
weight_decay=0.01,
grad_clip=1.0,
)
print(f"Step 1 loss: {losses[0]:.4f} -> Step 50 loss: {losses[-1]:.4f}")Custom Sequence Classifier with LSTM and Gradient Clipping
For sequence classification or custom heads, combine LSTM (or RNN / GRU) with Linear inside an nn.Module and clip gradients with nn.clip_grad_norm_() before calling optimizer.step().
import numpy as np
import ochreml.nn as nn
class BiLSTMClassifier(nn.Module):
def __init__(
self,
input_size: int,
hidden_size: int,
num_classes: int,
num_layers: int = 2,
) -> None:
super().__init__()
self.lstm = nn.LSTM(
input_size=input_size,
hidden_size=hidden_size,
num_layers=num_layers,
bidirectional=True,
)
self.head = nn.Linear(hidden_size * 2, num_classes)
def forward(self, x: nn.Tensor) -> nn.Tensor:
out, (hn, cn) = self.lstm(x)
# Pool across the sequence dimension (axis=1) -> (batch, hidden_size * 2)
pooled = out.mean(axis=1)
return self.head(pooled)
model = BiLSTMClassifier(input_size=16, hidden_size=32, num_classes=4)
criterion = nn.CrossEntropyLoss()
optimizer = nn.AdamW(model.parameters(), lr=2e-3, weight_decay=0.01)
rng = np.random.default_rng(0)
x = nn.Tensor(rng.standard_normal((16, 12, 16)).astype(np.float32))
y = rng.integers(0, 4, size=(16,), dtype=np.int64)
for step in range(30):
optimizer.zero_grad()
logits = model(x)
loss = criterion(logits, y)
loss.backward()
# Prevent exploding gradients during BPTT
grad_norm = nn.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()Passing Explicit Initial Hidden States
If you want to carry state across truncated BPTT chunks or initialize states explicitly:
import ochreml.nn as nn
# RNN / GRU take optional h0
rnn = nn.RNN(input_size=8, hidden_size=16, num_layers=1, nonlinearity="tanh")
x = nn.Tensor.randn([4, 10, 8])
h0 = nn.Tensor.zeros([1, 4, 16])
out, hn = rnn(x, h0)
# LSTM takes optional hx=(h0, c0)
lstm = nn.LSTM(input_size=8, hidden_size=16, num_layers=2)
h0 = nn.Tensor.zeros([2, 4, 16])
c0 = nn.Tensor.zeros([2, 4, 16])
out, (hn, cn) = lstm(x, (h0, c0))| Layer | Gates per Step | Return Signature | Extra Constructor Options |
|---|---|---|---|
nn.RNN | 1 (tanh or relu) | (out, hn) | nonlinearity="tanh" (or "relu") |
nn.GRU | 3 (reset, update, new) | (out, hn) | num_layers, bias, bidirectional |
nn.LSTM | 4 (input, forget, cell, output) | (out, (hn, cn)) | num_layers, bias, bidirectional |
CNNs and Residual Networks
Build 2D convolutional networks, depthwise separable blocks, and ResNets with Conv2d, DepthwiseConv2d, BatchNorm2d, MaxPool2d, and ResidualBlock.
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.