docscore conceptsconcept-layers-and-modules
Core Concepts

Neural Network Layers & Modules

Composable neural network primitives in Dark Forest: Linear, Conv2d, BatchNorm, and Module traits.

Layers & Modules

In Dark Forest, neural network layers implement the Module trait, standardizing forward execution, parameter registration, and state updates.

The Module Trait

rust
pub trait Module {
    fn forward(&self, input: &Tensor) -> Tensor;
    fn parameters(&self) -> Vec<Tensor>;
    fn zero_grad(&mut self);
}

Linear Layer Example

The Linear layer applies an affine transformation: $y = x A^T + b$

rust
use darkforest_core::nn::Linear;
use darkforest_core::tensor::Tensor;

// Create a linear layer with 128 input features and 64 output features
let mut fc = Linear::new(128, 64, true);

// Input tensor of shape [batch_size, 128]
let x = Tensor::randn(&[32, 128]);

// Forward pass
let y = fc.forward(&x);
assert_eq!(y.shape(), &[32, 64]);

Invariants & Memory Layout

  • Weights storage: Stored in row-major layout with 64-byte alignment, enabling direct dispatch into SIMD matrix multiplication routines.
  • Biases: Optional 1D tensor broadcasted across the batch dimension during forward evaluation.
  • Gradient tracking: Parameters have requires_grad = true by default. When passed through tape autograd, gradients automatically accumulate in parameter .grad() nodes.