Skip to Content
OchreML

Your First Neural Network

Train neural networks in Rust with ochreml.nn using zero-GIL Sequential.fit() or PyTorch-style nn.Module and loss.backward().

ochreml.nn is OchreML's lightweight deep learning package backed 100% by Rust autograd and hardware-accelerated kernels (CPU AVX2+FMA+Rayon, CUDA/cuBLAS, wgpu, and Google TPU StableHLO) — with zero PyTorch, TensorFlow, or cuDNN runtime dependencies (^▽^).

It provides a dual-style API:

  1. High-Level Sequential + model.fit() — Scikit-Learn ergonomics where the entire epoch and mini-batch loop runs zero-GIL in Rust.
  2. Low-Level nn.Module + loss.backward() — PyTorch-style dynamic autograd for custom architectures, losses, and training loops.

Option 1: High-Level Sequential.fit() (Zero-GIL Rust Loop)

When your model is a linear stack of built-in layers (Linear, Conv2d, BatchNorm2d, ResidualBlock, LayerNorm, RMSNorm, activations, pooling, Dropout, Flatten), nn.Sequential.fit() executes the entire forward pass, loss computation, backward pass, and optimizer update inside Rust without re-acquiring the Python GIL per batch.

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

# Synthetic binary classification dataset
rng = np.random.default_rng(42)
X = rng.standard_normal((1024, 32)).astype(np.float32)
y = (X[:, 0] + 0.5 * X[:, 1] > 0).astype(np.int64)

# Define a 2-layer MLP
model = nn.Sequential(
    nn.Linear(32, 64),
    nn.GELU(),
    nn.Dropout(p=0.1),
    nn.Linear(64, 2),
    dtype="float32",
    device="auto",
)

# Train 100% zero-GIL in Rust (returns per-epoch mean loss)
history = model.fit(
    X,
    y,
    epochs=20,
    batch_size=64,
    lr=1e-3,
    optimizer="adamw",
    loss="cross_entropy",
    weight_decay=0.01,
    grad_clip=1.0,
    shuffle=True,
    seed=42,
)
print(f"Initial loss: {history[0]:.4f} -> Final loss: {history[-1]:.4f}")

# Inference in eval mode
probs = model.predict_proba(X[:5])     # float32 softmax probabilities, shape (5, 2)
preds = model.predict_classes(X[:5])   # int64 class indices, shape (5,)
logits = model.predict(X[:5])          # raw float32 logits, shape (5, 2)

# Cross-device binary persistence (.dit Tag 100)
ochreml.save(model, "mlp_classifier.dit")
reloaded = ochreml.load("mlp_classifier.dit", device="cpu")

For regression tasks with Sequential.fit(), pass loss="mse" and float targets y (optionally setting out_dim for multi-output regression).


Option 2: Low-Level nn.Module + loss.backward()

For custom forward graphs, skip connections, multiple inputs, or custom schedules, subclass nn.Module just like PyTorch. All parameters assigned as nn.Parameter or nested nn.Module attributes are tracked automatically by model.parameters() and model.state_dict().

import numpy as np
import ochreml.nn as nn


class ResidualMLP(nn.Module):
    def __init__(self, in_dim: int, hidden_dim: int, num_classes: int) -> None:
        super().__init__()
        self.in_proj = nn.Linear(in_dim, hidden_dim)
        self.norm = nn.RMSNorm(hidden_dim)
        self.hidden = nn.Linear(hidden_dim, hidden_dim)
        self.act = nn.SiLU()
        self.head = nn.Linear(hidden_dim, num_classes)

    def forward(self, x: nn.Tensor) -> nn.Tensor:
        h = self.act(self.in_proj(x))
        h = h + self.act(self.hidden(self.norm(h)))  # residual skip connection
        return self.head(h)


model = ResidualMLP(in_dim=32, hidden_dim=64, num_classes=3)
criterion = nn.CrossEntropyLoss(label_smoothing=0.05)
optimizer = nn.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
scheduler = nn.WarmupCosineLR(optimizer, warmup_steps=5, total_steps=50, min_lr=1e-4)

rng = np.random.default_rng(7)
X_batch = nn.Tensor(rng.standard_normal((64, 32)).astype(np.float32))
y_batch = rng.integers(0, 3, size=(64,), dtype=np.int64)

model.train()
for step in range(50):
    optimizer.zero_grad()
    logits = model(X_batch)
    loss = criterion(logits, y_batch)
    loss.backward()

    # Global L2 gradient clipping in Rust
    nn.clip_grad_norm_(model.parameters(), max_norm=1.0)
    optimizer.step()
    scheduler.step()

# Switch to eval mode and disable autograd tape for inference
model.eval()
with nn.no_grad():
    val_logits = model(X_batch)
    val_preds = val_logits.numpy().argmax(axis=-1)

Choosing Between High-Level and Low-Level APIs

FeatureSequential.fit()Custom nn.Module + loss.backward()
Training Loop100% zero-GIL in RustPython loop driving Rust kernels
Arbitrary GraphsLinear stack of built-in layersFull dynamic control flow, branching, multi-input
Optimizers & LossesBuilt-in (adamw, adam, sgd; cross_entropy, mse)Any custom loss, SGD/Adam/AdamW, LR schedulers
PersistenceDirect .dit binary (ochreml.save / load)state_dict() / load_state_dict() (or CausalLM / LoRAAdapterState .dit)
Best ForMaximum throughput MLPs & CNNsResearch architectures, custom losses, hybrid pipelines

Next Steps

On this page