CNNs and Residual Networks
Build 2D convolutional networks, depthwise separable blocks, and ResNets with Conv2d, DepthwiseConv2d, BatchNorm2d, MaxPool2d, and ResidualBlock.
ochreml.nn implements 2D convolutions and pooling directly on top of OchreML's N10 (im2col / col2im + pool2d) and E1/E2 GEMM primitives — delivering fast CPU and GPU execution without bundling cuDNN (^▽^).
All vision layers expect standard NCHW tensors of shape (batch, channels, height, width).
Building a CNN with Sequential.fit()
Because Conv2d, DepthwiseConv2d, BatchNorm2d, MaxPool2d, AvgPool2d, GlobalAvgPool2d, Flatten, and ResidualBlock are all built-in Rust Sequential layers, you can train an entire CNN zero-GIL with model.fit().
import numpy as np
import ochreml
import ochreml.nn as nn
# Synthetic NCHW image batch: 128 RGB images of size 16x16, 4 classes
rng = np.random.default_rng(42)
X_img = rng.standard_normal((128, 3, 16, 16)).astype(np.float32)
y_cls = rng.integers(0, 4, size=(128,), dtype=np.int64)
cnn = nn.Sequential(
nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # -> (N, 16, 8, 8)
nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.GlobalAvgPool2d(keep_dims=False), # -> (N, 32)
nn.Linear(32, 4),
device="auto",
)
losses = cnn.fit(
X_img,
y_cls,
epochs=10,
batch_size=32,
lr=1e-3,
optimizer="adamw",
loss="cross_entropy",
)
# Save full CNN architecture + BatchNorm running stats to .dit
ochreml.save(cnn, "mini_cnn.dit")Building a Mini-ResNet with ResidualBlock
nn.ResidualBlock(in_channels, out_channels, stride=1) implements a ResNet-style basic residual block (Conv3x3 -> BN -> ReLU -> Conv3x3 -> BN + shortcut -> ReLU) executed natively in Rust. When stride > 1 or in_channels != out_channels, it automatically creates a 1x1 projection shortcut.
import ochreml.nn as nn
class MiniResNet(nn.Module):
def __init__(self, in_channels: int = 3, num_classes: int = 10) -> None:
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(in_channels, 16, kernel_size=3, stride=1, padding=1, bias=False),
nn.BatchNorm2d(16),
nn.ReLU(),
)
self.stage1 = nn.ResidualBlock(16, 16, stride=1)
self.stage2 = nn.ResidualBlock(16, 32, stride=2) # downsamples H, W by 2x
self.pool = nn.GlobalAvgPool2d(keep_dims=False)
self.fc = nn.Linear(32, num_classes)
def forward(self, x: nn.Tensor) -> nn.Tensor:
h = self.stem(x)
h = self.stage1(h)
h = self.stage2(h)
h = self.pool(h)
return self.fc(h)
net = MiniResNet(in_channels=3, num_classes=10)
x = nn.Tensor.randn([8, 3, 16, 16])
logits = net(x) # shape: (8, 10)Depthwise Separable Convolutions (DepthwiseConv2d)
For lightweight MobileNet-style blocks, nn.DepthwiseConv2d executes directly without im2col matrix expansion overhead. Pair it with a 1x1 pointwise nn.Conv2d:
import ochreml.nn as nn
class DepthwiseSeparableBlock(nn.Module):
def __init__(self, in_ch: int, out_ch: int, stride: int = 1) -> None:
super().__init__()
self.dw = nn.DepthwiseConv2d(
in_channels=in_ch,
depth_multiplier=1,
kernel_size=3,
stride=stride,
padding=1,
bias=False,
)
self.bn1 = nn.BatchNorm2d(in_ch)
self.pw = nn.Conv2d(in_ch, out_ch, kernel_size=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_ch)
self.act = nn.SiLU()
def forward(self, x: nn.Tensor) -> nn.Tensor:
h = self.act(self.bn1(self.dw(x)))
return self.act(self.bn2(self.pw(h)))Managing BatchNorm2d Train vs. Eval Mode
BatchNorm2d maintains running_mean and running_var buffers updated with exponential moving average (momentum=0.1 by default) during training:
- Call
model.train()before training steps soBatchNorm2duses mini-batch statistics and updates its running buffers. - Call
model.eval()before validation or inference soBatchNorm2d(andResidualBlock's internal BatchNorm layers) normalize with frozen running statistics. - When using
Sequential.fit(),predict(),predict_proba(), andpredict_classes(), mode switching is handled automatically in Rust.
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().
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().