---
title: "Train a TypeNN model"
description: "Use Module, Linear, CrossEntropyLoss, Tensor autograd, and Adam in an explicit training loop."
url: https://nn.typeshade.dev/guide/training/
language: en
---

Guides

# Train a model

The Module API keeps the training loop explicit: clear gradients, run forward, backpropagate, update parameters, and release the batch graph.

## Model definition

The MNIST example uses a 784 → 128 → 10 MLP with ReLU and Dropout. This snippet follows the source model; it omits only the seeded weight options.

MNIST model examples/mnist/model.ts

```ts
export class SimpleMLP extends nn.Module {
  private readonly flatten: nn.Flatten;
  private readonly fc1: nn.Linear;
  private readonly relu: nn.ReLU;
  private readonly dropout: nn.Dropout;
  private readonly fc2: nn.Linear;

  constructor() {
    super();
    this.flatten = this.register("flatten", new nn.Flatten());
    this.fc1 = this.register("fc1", new nn.Linear(784, 128));
    this.relu = this.register("relu", new nn.ReLU());
    this.dropout = this.register("dropout", new nn.Dropout(0.2));
    this.fc2 = this.register("fc2", new nn.Linear(128, 10));
  }

  forward(input: nn.Tensor): nn.Tensor {
    return this.fc2.forward(this.dropout.forward(
      this.relu.forward(this.fc1.forward(this.flatten.forward(input))),
    ));
  }
}
```

## Training loop

The loop below follows the example's batch lifecycle. It explicitly reads the batch loss for logging, then runs backward and Adam before releasing temporary tensors.

Forward, backward, update examples/mnist/train.ts

```ts
const model = new SimpleMLP().to(device);
const parameters = model.parameters();
const criterion = new nn.CrossEntropyLoss();
const optimizer = nn.optim.Adam(parameters, { lr: 0.001 });

model.train();
let totalLoss = 0;
let totalSamples = 0;
for await (const batch of new DataLoader(trainData, 64, true)) {
  await optimizer.zeroGrad();
  const images = device.tensor(batch.images, {
    shape: [batch.size, 1, 28, 28],
  });
  const logits = model.forward(images);
  const loss = criterion.forward(logits, batch.labels);
  const batchLoss = (await loss.data())[0];
  if (batchLoss === undefined) throw new Error("CrossEntropyLoss returned no value.");
  await loss.backward();
  await optimizer.step();
  totalLoss += batchLoss * batch.size;
  totalSamples += batch.size;
  await loss.disposeGraph(parameters);
}
```

## What happens in a training step

On every tier, the forward and backward operations run as TypeShade kernel functions. When a requested Tensor has no computed array, `data()` runs the kernels needed to produce it. `optimizer.step()` computes the gradients and updates parameters and Adam moments in one device plan. It reads no gradient back and uploads no parameter. A layer's `weight` and `bias` arrays are host copies: `await model.sync()` refreshes them, and `parameter.data()` reads one parameter. On SwiftShader the device update is not faster than the host loop it replaced.

**Explicit reads remain reads.** Calling `loss.data()` or `parameter.data()` requests a host result. The sample loop above reads back only the loss each step.

## Dispose each batch graph

`disposeGraph(model.parameters())` releases temporary tensors while retaining model parameters. Keep the Device alive for the training session and dispose it after the final batch and any pending work finish.

[Open the full MNIST example ↗](https://github.com/typeshade/typenn/tree/main/examples/mnist)

## Operations covered by this example

Tensor graph autograd computes gradients for selected operations. This guide follows the MNIST Module example; it does not claim support for arbitrary user-defined kernels or gradients for every Tensor operation.
