github ↗
docs menu

Layers and models

Kaun has no layer abstraction. A layer is a plain record of tensors with an apply function; a model is a record of layers with a hand-written walk, one line per field. This guide covers the built-in layers, the model-as-record pattern, and stateful layers.

The layer pattern

Every parameterized layer module follows the same shape, with Linear as the reference:

  • a parameter record with a payload hole — ('a, 'd) Linear.t is { w; b }, at tensor payloads w : [| inputs; outputs |] and an optional bias, on the device set 'd;
  • constructors — Linear.init ~key ~inputs ~outputs for the float32 defaults, Linear.make for initializer, bias, and dtype control, each drawing from key and placing the parameters where it lies;
  • an apply function — Linear.apply p x is x @ p.w + p.b, treating leading axes as batch axes;
  • a structure — one walk over the record's fields with an Nx.Ptree.Walk cursor, satisfying Nx.Ptree.S.
ocaml
open Kaun

let () =
  Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
  let layer = Linear.init ~key:(Nx.Rng.next_key ()) ~inputs:4 ~outputs:2 in
  let x = Nx.Rng.normal Nx.float32 [| 8; 4 |] in
  let y = Linear.apply layer x in
  Format.printf "y has shape %a@." Nx.pp_shape (Nx.shape y)
  (* [8; 2] *)

There is nothing else to a layer: layer.w is an ordinary tensor you can read, and { layer with w = ... } an ordinary record update.

The catalog

Module Parameters Apply
Linear w, optional b dense map over the last axis
Conv w, optional b 2-D convolution, NCHW, `Valid/ `Same padding
Embedding table token-id to row lookup (int64 ids in, floats out)
Attention q, k, v, out projections multi-head self-attention, optional causal mask
Layer_norm gamma, beta normalization over the last axis
Batch_norm gamma, beta + separate Stats.t normalization over the batch, running statistics

Stateless companions, all pure functions:

Module Contents
Fn relu, leaky_relu, gelu, gelu_approx, silu, softplus, keep_top_k, keep_top_p
Pool max_pool2d, avg_pool2d over the last two axes
Dropout apply ~rate ~training
Init glorot_*, he_*, lecun_*, variance_scaling, constants

Every apply is differentiable through rune, in both reverse and forward mode.

Models are records of layers

Records nest into records. A model's walk visits each field with the field's own walk, under the field's name, so each leaf's path is the field name followed by the layer's path:

ocaml
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)

mlp is what Rune.grad, Vega.adam_step, Nx_io.Archive.of_value and friends take; its leaves are at l1.w, l1.b, l2.w and l2.b, which are also their names in a saved file. This scales without new concepts: a transformer block is a record of five layers, and a transformer is a record with a block list field, walked with Nx.Ptree.Walk.list. examples/04-gpt2 defines all of GPT-2 this way in ~150 lines.

A CNN mixes parameterized and stateless pieces freely, since a forward pass is just function composition:

ocaml
module Cnn = struct
  type ('a, 'd) t = {
    c1 : ('a, 'd) Conv.t;
    c2 : ('a, 'd) Conv.t;
    fc : ('a, 'd) Linear.t;
  }

  let walk c { c1; c2; fc } =
    let open Nx.Ptree.Walk in
    let c1 = field c "c1" Conv.walk c1 in
    let c2 = field c "c2" Conv.walk c2 in
    let fc = field c "fc" Linear.walk fc in
    { c1; c2; fc }

  let apply p ~training x =
    let n = (Nx.shape x).(0) in
    Conv.apply p.c1 x |> Fn.relu
    |> Pool.max_pool2d ~kernel_size:(2, 2)
    |> Conv.apply p.c2 |> Fn.relu
    |> Pool.max_pool2d ~kernel_size:(2, 2)
    |> Nx.reshape [| n; 16 * 5 * 5 |]
    |> Dropout.apply ~rate:0.25 ~training
    |> Linear.apply p.fc
end

let () =
  Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
  let params =
    {
      Cnn.c1 =
        Conv.init ~key:(Nx.Rng.next_key ()) ~in_channels:1 ~out_channels:8
          ~kernel_size:(3, 3);
      c2 =
        Conv.init ~key:(Nx.Rng.next_key ()) ~in_channels:8 ~out_channels:16
          ~kernel_size:(3, 3);
      fc = Linear.init ~key:(Nx.Rng.next_key ()) ~inputs:(16 * 5 * 5) ~outputs:10;
    }
  in
  let x = Nx.Rng.normal Nx.float32 [| 2; 1; 28; 28 |] in
  let logits = Cnn.apply params ~training:false x in
  Format.printf "logits: %a@." Nx.pp_shape (Nx.shape logits)
  (* [2; 10] *)

Note the ~training flag threaded to Dropout.apply: mode is an argument, not a mutable model state. Without ~key, dropout draws from the scope Nx.Rng.with_key opens, which a host computation reads; a compiled step passes its own ~key. This is examples/03-mnist-cnn's model.

Attention

Attention.t is four Linear projections (query, key, value, output). Head counts are not parameters: head_dim is an argument of apply, like eps of Layer_norm.apply, and the layer reads the number of query heads and of key-value heads from the projection widths. Attention.make ~kv_dim makes the key and value projections narrower, which is grouped-query attention.

ocaml
let () =
  Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
  let attn = Attention.init ~key:(Nx.Rng.next_key ()) ~embed_dim:16 in
  let x = Nx.Rng.normal Nx.float32 [| 2; 5; 16 |] in
  (* batch 2, sequence 5 *)
  let y = Attention.apply ~head_dim:4 ~mask:Nx.causal attn x in
  Format.printf "y: %a@." Nx.pp_shape (Nx.shape y)
  (* [2; 5; 16] — same shape; the mask hides future positions *)

scaled_dot_product_attention is the pure core — softmax (q @ kᵀ / sqrt d) @ v, no parameters, no head bookkeeping — computed by Nx.attention, in float16, bfloat16, float32 or float64. Leading axes broadcast, so stacked heads are just a batch axis. Use it directly for cross-attention, externally projected queries and keys, or custom masking via ?mask:

ocaml
let () =
  Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
  let q = Nx.Rng.normal Nx.float32 [| 3; 8 |] in
  let k = Nx.Rng.normal Nx.float32 [| 5; 8 |] in
  let v = Nx.Rng.normal Nx.float32 [| 5; 4 |] in
  let y = Attention.scaled_dot_product_attention q k v in
  Format.printf "y: %a@." Nx.pp_shape (Nx.shape y)
  (* [3; 4] — one weighted average of value rows per query row *)

?mask says which keys each query may see, as Nx.attention takes it: Nx code over the coordinates of one query-key pair. Nx.causal lets query i see keys j <= i; a boolean array b of shape [| seq; seq |] is the mask fun _ -> b, one of [| batch; seq; seq |] is fun _ -> Nx.reshape [| batch; 1; seq; seq |] b (a mask's arrays align on the right of [| batch; heads; seq; seq |]), and padding composes, fun p -> Nx.logical_and (Nx.causal p) valid for valid of shape [| batch; 1; 1; seq |]. A query that sees no key, a padded one for instance, yields zero and never nan. ?rope takes a Rope.t schedule, built on the host and moved beside the model with Rope.place, and rotates queries and keys by position.

For autoregressive decoding, Attention.cached runs causal self-attention of a few new tokens over a functional key-value cache. The cache (Attention.Cache) is a flat pool of slots with no batch axis, and a Cache_index.t, built on the host and moved with Cache_index.place, says where the call's tokens sit: each token's position and the slot holding each position of each sequence. One contiguous run per sequence (Cache_index.rows), paged allocation and a prefix shared by two sequences are all values of a cache index, and the layer is the same for each. Over Cache_index.whole, which reads and keeps nothing, the same function is plain causal attention, so a model has one forward pass for training and decoding. Positions and slots enter as tensors, so a generation step keeps fixed shapes and compiles once; compiled with Rune.jit on Nx.Ptree.(tensor @-> v Cache_index.walk @-> caches @-> returns (pair tensor caches)) and called with the caches donated (Nx.Ptree.donate), the old caches are consumed. A prompt fed whole, in chunks or token by token gives the same outputs.

Stateful layers: Batch_norm

Batch_norm is the one layer with non-parameter state. It is two structures: trainable parameters (Batch_norm.t, the affine gamma and beta — differentiated and optimized like any other parameters) and running statistics (Batch_norm.Stats.t, per-feature mean and variance — never differentiated, updated by every training forward).

apply in training mode normalizes with the current batch's statistics and returns updated running statistics; in eval mode it normalizes with the running statistics and returns them unchanged. A training step returns the updated statistics from the objective beside the loss, through Rune.value_and_grad_aux, which takes their structure and gives them back undifferentiated:

ocaml
module Net = struct
  type ('a, 'd) t = {
    l1 : ('a, 'd) Linear.t;
    bn : ('a, 'd) Batch_norm.t;
    l2 : ('a, 'd) Linear.t;
  }

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

  let forward p stats ~training x =
    let h = Linear.apply p.l1 x in
    let h, stats = Batch_norm.apply p.bn stats ~training h in
    (Linear.apply p.l2 (Fn.relu h), stats)
end

let net = Nx.Ptree.instantiate (module Net)

let () =
  Nx.Rng.with_key (Nx.Rng.key 0) @@ fun () ->
  let x = Nx.Rng.normal Nx.float32 [| 16; 4 |] in
  let y = Nx.Rng.normal Nx.float32 [| 16; 1 |] in
  let bn, stats = Batch_norm.init ~features:8 Nx.Host.on in
  let params =
    {
      Net.l1 = Linear.init ~key:(Nx.Rng.next_key ()) ~inputs:4 ~outputs:8;
      bn;
      l2 = Linear.init ~key:(Nx.Rng.next_key ()) ~inputs:8 ~outputs:1;
    }
  in

  (* One training step: stats' leaves the objective beside the loss. *)
  let bn_stats = Nx.Ptree.instantiate (module Batch_norm.Stats) in
  let step (params, stats, ostate) =
    let objective p =
      let pred, stats' = Net.forward p stats ~training:true x in
      (Loss.mse pred y, stats')
    in
    let loss, grads, stats' =
      Rune.value_and_grad_aux net bn_stats objective params
    in
    let params, ostate =
      Vega.adam_step net ~lr:(Vega.lr 1e-2) ostate ~params ~grads
    in
    ((params, stats', ostate), Nx.item [] loss)
  in

  let state = ref (params, stats, Vega.adam_init net params) in
  for _ = 1 to 20 do
    let s, _ = step !state in
    state := s
  done;

  (* Evaluation reuses the same forward with ~training:false and discards
     the returned statistics. *)
  let params, stats, _ = !state in
  let pred, _ = Net.forward params stats ~training:false x in
  Format.printf "eval predictions: %a@." Nx.pp_shape (Nx.shape pred)

The loss never depends on stats': training mode normalizes with the batch's statistics, so the running statistics are a side output, and Rune.value_and_grad_aux returns them as plain values. Statistics have their own walk (Batch_norm.Stats satisfies Nx.Ptree.S itself), so they are saved like parameters under their own field; see Saving.

Batch_norm.init builds float32 parameters (cast with Nx.Ptree.cast (module Batch_norm) dt for other precisions); apply is generic over float dtypes, like the other layers' make, computing half- and quarter-precision statistics in a float32 island.

Initializers

An initializer is a plain function from a key, fan geometry, dtype, and shape to a fresh tensor at the key's placement — Init.t. Layers accept one as ?w_init/?bias_init and supply the fans from their own geometry:

ocaml
let () =
  (* He-normal weights for a ReLU network, no bias. *)
  let layer =
    Linear.make ~w_init:Init.he_normal ~bias:false ~key:(Nx.Rng.key 0)
      ~inputs:64 ~outputs:64 Nx.float32
  in
  ignore layer

The named families (Glorot/Xavier, He/Kaiming, LeCun) are instances of Init.variance_scaling; any function of the right type is an initializer, so custom schemes need no registration. Random initializers draw from the key they are given, so equal keys give equal parameters.

Next steps

this page is tested with mdxedit this page ↗