github ↗
docs menu

Getting started

This guide walks through the whole kaun pattern once: define a model as a record, write the training step yourself, run the loop, evaluate. Everything else in the library is a refinement of this page.

Installation

bash
opam install kaun vega

Or build from source:

bash
git clone https://github.com/raven-ml/raven
cd raven && dune build kaun

Add to your dune file:

dune
(executable
 (name main)
 (libraries kaun rune vega nx))

Note the layering: kaun's library depends only on nx. Differentiation comes from rune and optimizers from vega, which you depend on directly and compose in your own code — there is no trainer in between.

A model is a record

A kaun layer is a plain record with a payload hole and an apply function; ('a, 'd) Linear.t holds a weight matrix and an optional bias, arrays of type 'a on the device set 'd (Nx.host for the process's own memory). A model is a record of layers with one function, walk, that visits each field with the field's own walk and names it. Nx.Ptree.instantiate turns the module into a structure at its tensor type, which every Raven transformation, optimizer and saved file takes:

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 (Nx.tanh (Linear.apply p.l1 x))
end

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

apply is just a function — no base class, no forward method, no parameter registry. walk is what lets Rune differentiate your parameter values, Vega step them, and Nx_io.Archive save them under the names it gives (l1.w, l1.b, l2.w, l2.b). Writing structures covers walk in full.

Initialize parameters

Constructors take ~key, an Nx.Rng.key, and draw from it: equal keys give equal parameters, and the parameters lie where the key lies. Nx.Rng.split derives independent keys from one. Linear.init gives Glorot-uniform weights and zero bias:

ocaml
let () =
  let keys = Nx.Rng.split (Nx.Rng.key 42) in
  (* XOR dataset. *)
  let x =
    Nx.create Nx.float32 [| 4; 2 |] [| 0.; 0.; 0.; 1.; 1.; 0.; 1.; 1. |]
  in
  let y = Nx.create Nx.float32 [| 4; 1 |] [| 0.; 1.; 1.; 0. |] in

  let params =
    {
      Mlp.l1 = Linear.init ~key:keys.(0) ~inputs:2 ~outputs:8;
      l2 = Linear.init ~key:keys.(1) ~inputs:8 ~outputs:1;
    }
  in

  (* The objective: logits from the model, binary cross-entropy on top.
     Losses take raw logits and evaluate in log space. *)
  let loss p = Loss.sigmoid_bce (Mlp.apply p x) y in

  (* The training step: value_and_grad + one Adam update. Gradients and
     optimizer moments have the parameters' record type. *)
  let step (params, ostate) =
    let l, grads = Rune.value_and_grad mlp loss params in
    let params, ostate =
      Vega.adam_step mlp ~lr:(Vega.lr 0.05) ostate ~params ~grads
    in
    ((params, ostate), Nx.item [] l)
  in

  (* The loop: plain OCaml. *)
  let state = ref (params, Vega.adam_init mlp params) in
  for i = 1 to 500 do
    let s, l = step !state in
    state := s;
    if i mod 100 = 0 then Printf.printf "step %4d  loss %.6f\n" i l
  done;

  (* Evaluate. *)
  let pred = Nx.sigmoid (Mlp.apply (fst !state) x) in
  for i = 0 to 3 do
    Printf.printf "[%.0f, %.0f] -> %.3f\n"
      (Nx.item [ i; 0 ] x)
      (Nx.item [ i; 1 ] x)
      (Nx.item [ i; 0 ] pred)
  done

This is the complete program — it is examples/01-xor nearly verbatim. Three things to notice:

  • Every piece of training state is a value of your type. Parameters, gradients, and the Adam moments (ostate.mu, ostate.nu) are all (Nx.host Nx.float32_t, Nx.host) Mlp.t values you can print, inspect, save, or swap.
  • The step is yours. Want gradient clipping? Insert Vega.clip_by_global_norm mlp ~max_norm:1.0 grads before the update. A learning-rate schedule? Evaluate one at your step counter. Nothing is hidden behind a trainer.
  • Nx.Ptree.instantiate (module Mlp) is the only plumbing. Bind the structure once; it drives differentiation, optimization and saving.

Scaling up: Minibatches

For real datasets, Data.batches2 cuts paired tensors into a Seq.t of minibatches, and the epoch loop is ordinary Seq iteration. With ~shuffle:true, each traversal of the sequence draws a fresh permutation from the RNG scope that Nx.Rng.with_key opens, so iterating once per epoch reshuffles every epoch:

ocaml
Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
let train_x, train_y, test_x, test_y = Kaun_datasets.mnist () in
let batches = Data.batches2 ~shuffle:true ~batch_size:128 (train_x, train_y) in
let state = ref (params, Vega.adamw_init mlp params) in
for _epoch = 1 to 3 do
  batches
  |> Seq.iter (fun (x, y) ->
      let s, _ = step !state (x, y) in
      state := s)
done

where step now takes the batch as an argument so the loss closes over it:

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)

examples/02-mnist runs this end to end, reaching ~97% test accuracy in one epoch.

Next steps

this page is tested with mdxedit this page ↗