docsexamplesexamples-mlp-scratch
Examples

Training an MLP from Scratch

Complete end-to-end multi-layer perceptron training loop using Dark Forest Core and Autograd.

Training an MLP from Scratch

This tutorial walks through creating and optimizing a multi-layer perceptron (MLP) for binary regression using Dark Forest.

Full Working Example

rust
use darkforest_core::tensor::Tensor;
use darkforest_core::nn::{Linear, Module};
use darkforest_core::optim::AdamW;
use darkforest_core::autograd::backward;

fn main() {
    // 1. Initialize synthetic training data
    let batch_size = 64;
    let in_features = 32;
    let x = Tensor::randn(&[batch_size, in_features]);
    let target = Tensor::ones(&[batch_size, 1]);

    // 2. Define 2-layer network
    let mut fc1 = Linear::new(in_features, 64, true);
    let mut fc2 = Linear::new(64, 1, true);

    // 3. Setup AdamW optimizer
    let mut params = fc1.parameters();
    params.extend(fc2.parameters());
    let mut opt = AdamW::new(params, 0.001, 0.01);

    // 4. Training loop for 100 steps
    for step in 0..100 {
        // Zero previous step gradients
        opt.zero_grad();

        // Forward pass
        let h = fc1.forward(&x).relu();
        let pred = fc2.forward(&h);

        // Mean Squared Error loss
        let diff = &pred - ⌖
        let loss = (&diff * &diff).mean();

        // Backward tape execution
        backward(&loss);

        // Optimizer step
        opt.step();

        if step % 20 == 0 {
            println!("Step {}: Loss = {:.6}", step, loss.item());
        }
    }
}

Key Differences from PyTorch

  1. Explicit ownership passing ensures zero data cloning during matrix multiplication.
  2. The tape worklist executes iteratively, guaranteeing no C-stack overflow even if loops run thousands of iterations without checkpointing.