github ↗
docs menu

Kaun vs. PyTorch — a practical comparison

This guide explains how kaun relates to PyTorch, focusing on:

  • How core concepts map (modules, parameters, optimizers, training loops)
  • Where the APIs feel similar vs. deliberately different
  • How to translate common PyTorch patterns

The main shift is from mutable objects to immutable records: a PyTorch model is an object that owns its parameters and mutates them in place; a kaun model is a record of tensors that functions consume and produce. There is no module base class, no parameter registry, and no trainer.


1. Big-picture differences

Aspect PyTorch kaun (OCaml)
Language Python, dynamic OCaml, statically typed
Model definition nn.Module subclass with forward plain record + apply function
Parameter storage mutable attributes, auto-registered fields of your record
Parameter traversal model.parameters() (reflection) one walk you write, a line per field
Forward pass model(x) (stateful method) Model.apply params x (pure function)
Autograd dynamic tape on tensors (loss.backward()) Rune.value_and_grad (effect handlers)
Gradients .grad attributes, mutated in place a fresh value of your record type
Optimizer torch.optim.AdamW(model.parameters()) Vega.adamw_step model — pure, state threaded explicitly
Train/eval mode model.train() / model.eval() explicit ~training arguments
Buffers (running stats) hidden module state explicit Stats.t you thread through the loop
Data loading DataLoader Data.batches2 returning a Seq.t
Saving state_dict() + torch.save (pickle) named entries + safetensors via Nx_io.Archive
Pretrained models from_pretrained per architecture kaun.hf + an importer you write with Nx_io.Archive.float
RNG global torch.manual_seed explicit keys (~key), and a scope Nx.Rng.with_key opens
Device model.to("cuda") Nx.Ptree.place of the weights on a device set; GPU via Rune.jit

2. Defining models

PyTorch

python
import torch.nn as nn

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.l1 = nn.Linear(4, 8)
        self.l2 = nn.Linear(8, 1)

    def forward(self, x):
        return self.l2(torch.relu(self.l1(x)))

model = MLP()

kaun

ocaml
open Kaun

module Mlp = struct
  type ('a, 'd) t = { l1 : ('a, 'd) Linear.t; l2 : ('a, 'd) Linear.t }

  let walk c { l1; l2 } =
    let open Nx.Ptree.Walk in
    let l1 = field c "l1" Linear.walk l1 in
    let l2 = field c "l2" Linear.walk l2 in
    { l1; l2 }

  let apply p x = Linear.apply p.l2 (Fn.relu (Linear.apply p.l1 x))
end

let mlp = Nx.Ptree.instantiate (module Mlp)

let () =
  let keys = Nx.Rng.split ~n:3 (Nx.Rng.key 0) in
  let model =
    {
      Mlp.l1 = Linear.init ~key:keys.(0) ~inputs:4 ~outputs:8;
      l2 = Linear.init ~key:keys.(1) ~inputs:8 ~outputs:1;
    }
  in
  let y = Mlp.apply model (Nx.Rng.normal ~key:keys.(2) Nx.float32 [| 2; 4 |]) in
  ignore y

Where nn.Module registers parameters by reflection on attribute assignment, kaun asks you to write the record's walk by hand, one line per field, instantiated once by Nx.Ptree.instantiate. That is the entire cost, and it buys full typing: model.l1.w is a tensor field you can read directly, gradients of a model value have the model's own record type, and there is no string-keyed parameter store to drift out of sync.

One deliberate difference: layer hyper-parameters that do not change the parameter shapes are arguments of apply, not stored configuration — Attention.apply ~head_dim:64 ~mask, Layer_norm.apply ~eps:1e-5.


3. The training step

PyTorch — gradients and parameters mutate in place:

python
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)

def step(x, y):
    opt.zero_grad()
    loss = F.cross_entropy(model(x), y)
    loss.backward()
    opt.step()
    return loss.item()

kaun — the step is a pure function from state to state:

ocaml
let step (params, ostate) (x, y) =
  let loss p = Loss.softmax_cross_entropy_sparse (Mlp.apply p x) y in
  let l, grads = Rune.value_and_grad mlp loss params in
  let params, ostate =
    Vega.adamw_step mlp ~lr:(Vega.lr 1e-3) ostate ~params ~grads
  in
  ((params, ostate), Nx.item [] l)

Point-by-point:

  • loss.backward() → Rune.value_and_grad mlp loss params. No .grad attributes: the gradient is returned as a value.
  • opt.zero_grad() → nothing. Gradients are fresh values, never accumulated in place.
  • opt.step() → Vega.adamw_step. The optimizer holds no reference to the model; its state (mu, nu, step) is a record of parameter-shaped values your loop threads explicitly.
  • torch.nn.utils.clip_grad_norm_ → Vega.clip_by_global_norm mlp ~max_norm grads, a pure function applied between the two.
  • LR schedulers → a Vega.Schedule.t maps a step counter to a rate; pass it as ~lr and the step applies it to the state's counter.

Note the layering: Vega is an independent package composed in user code — kaun's library does not depend on it.


4. Train/eval mode and buffers

PyTorch — mode and running statistics are hidden module state:

python
model.train()
...
model.eval()
with torch.no_grad():
    out = model(x)

kaun — mode is an argument, statistics are a value:

ocaml
(* training *)
let pred, stats' = Net.forward params stats ~training:true x in
(* evaluation *)
let pred, _ = Net.forward params stats ~training:false x in

Dropout.apply ~rate ~training and Batch_norm.apply p stats ~training take the flag explicitly. What PyTorch calls a buffer (batch-norm running mean/var) is an explicit Batch_norm.Stats.t record: training forwards return the updated statistics, and Rune.value_and_grad_aux returns them from the differentiated objective — see Layers and Models. There is no torch.no_grad() context needed for evaluation: nothing is recorded unless you call a differentiation transformation, and Rune.detach holds a value constant inside one.


5. Data loading

PyTorch

python
loader = DataLoader(dataset, batch_size=128, shuffle=True, drop_last=False)
for x, y in loader:
    ...

kaun — for in-memory tensors, a Seq.t of minibatches:

ocaml
let batches = Data.batches2 ~shuffle:true ~batch_size:128 (train_x, train_y) in
batches |> Seq.iter (fun (x, y) -> ...)

Iterating the sequence again reshuffles — one sequence value serves every epoch. There is no worker pool or async prefetching; datasets are plain tensors (the kaun.datasets library loads MNIST, Fashion-MNIST, CIFAR-10 that way), and stdlib Seq combinators replace DataLoader options.


6. Saving

PyTorch

python
torch.save({"model": model.state_dict(),
            "optim": opt.state_dict(),
            "step": step}, path)
ckpt = torch.load(path)
model.load_state_dict(ckpt["model"])

kaun — state_dict() becomes Nx_io.Archive.of_value over your model's structure, which names each tensor by its path, and files are safetensors:

ocaml
let optim = Vega.adam_ptree mlp

let () =
  Nx_io.save_safetensors path
    (Nx_io.Archive.union
       [
         Nx_io.Archive.of_value ~prefix:"model" mlp params;
         Nx_io.Archive.of_value ~prefix:"optim" optim ostate;
       ])

let params =
  Nx_io.load_safetensors path
  |> Nx_io.Archive.to_value ~prefix:"model" mlp ~like:template

load_state_dict's in-place mutation becomes reading into a value of the same shape: ~like supplies structure, dtypes, shapes and placements, and a fresh value comes back. Nothing is converted on the way, and a file that differs from the value under model fails, naming the entry: a missing or extra entry, or another dtype or shape. The optimizer state's structure, Vega.adam_ptree mlp, nests the model's, so its entries are named after the model's paths. See Saving and Pretrained Weights.


7. Pretrained models

PyTorch / transformers

python
model = AutoModel.from_pretrained("gpt2")

kaun: there is no per-architecture loader. kaun.hf downloads the weights, and an importer you write builds your record from its entries, each read by the file's name with the shape and dtype it must have:

ocaml
let cfg = Gpt2.config_of_json (Kaun_hf.load_config "gpt2") in
let params = Gpt2.of_hf cfg Nx.float32 (Kaun_hf.load_safetensors "gpt2")

Inside the importer a rename is the file's name at the field it fills, Nx.matrix_transpose fixes nn.Linear's outputs × inputs orientation, and Nx.split cuts fused projections like GPT-2's c_attn; both are views. The file is mapped, so at its own dtype the parameters are its entries and nothing is copied. The GPT-2 importer is about fifty lines of user code; examples/04-gpt2 generates text with the result.


8. What Kaun does not have

PyTorch feature Status in kaun
GPU / model.to("cuda") Place the weights with Nx.Ptree.place on a device set minted with Nx.devices from a GPU that rig opens, such as Rig_cuda.gpu 0 from rig.cuda or Rig_metal.gpu 0 from rig.metal; a step compiled with Rune.jit runs there, and nx computes nothing on a GPU set outside one.
torch.compile / JIT Rune.jit compiles a step, and a Rune.scan in it as a loop.
Layer coverage Deliberately small: no recurrent layers; Attention covers grouped queries, rotary embeddings (Rope) and cached decoding (Attention.cached) and nothing beyond, no sliding windows or cross-attention layer; Conv is im2col-based and not tuned for large inputs.
Mixed precision / AMP Manual: cast with Nx.Ptree.cast (module M) dt and scale losses with Vega.Loss_scale; there is no automatic wrapper.
DataLoader workers No; data is in-memory tensors and a Seq.t.
Distributed (DDP) Within one process: a batch placed split ~axis:0 over a device set's devices computes data-parallel. No multi-process training.

9. Quick cheat sheet

Task PyTorch kaun
Define a model nn.Module subclass record + apply + one-line traversals
Construct MLP() { l1 = Linear.init ~key ~inputs ~outputs; ... }
Forward model(x) Mlp.apply params x
Backward loss.backward() Rune.value_and_grad mlp loss params
Zero grads opt.zero_grad() not needed
Optimizer step opt.step() Vega.adamw_step mlp ~lr st ~params ~grads
Clip gradients clip_grad_norm_ Vega.clip_by_global_norm
LR schedule lr_scheduler object Vega.Schedule.t, applied to the optimizer's counter
Train mode model.train() ~training:true arguments
Running stats hidden buffers explicit Stats.t + value_and_grad_aux
Batches DataLoader Data.batches2
Save torch.save(model.state_dict()) Nx_io.save_safetensors + Archive.of_value
Load load_state_dict Nx_io.Archive.to_value ~like
Pretrained from_pretrained("gpt2") Kaun_hf.load_safetensors + Nx_io.Archive.float per entry
Seed torch.manual_seed(42) Nx.Rng.key 42, split into each constructor's ~key
Per-sample grads torch.func.vmap(grad(...)) Rune.vmap of Rune.grad

this page is tested with mdxedit this page ↗