Building Neural Networks in Clorch: Layers and Lifecycle
Complete reference for clorch.nn: linear, conv, recurrent, normalization, pooling, defmodel macro, lifecycle API, and model inspection with nn/summary.
Use this file to discover all available pages before exploring further.
Clorch’s clorch.nn namespace is the primary entry point for building neural networks. Every layer wraps LibTorch’s C++ frontend directly, giving you native performance with no intermediate overhead — while remaining composable with ordinary Clojure data structures like vectors and maps.
nn/layernorm and nn/rmsnorm are implemented as Clojure records (not native modules) so their learnable parameters participate fully in nn/parameters, nn/to, and state-dict traversal.
;; Max and average pooling(nn/max-pool2d 2)(nn/avg-pool2d 2)(nn/adaptive-avg-pool2d [7 7]);; Zero padding(nn/zeropad2d 1);; Reflection and constant padding(nn/reflection-pad2d 2)(nn/constant-pad2d 1 3.14)
nn/sequential returns a plain Clojure vector. Because Clorch’s IModule protocol is extended to APersistentVector, the vector itself acts as a sequential container: nn/forward, nn/train, and nn/to all traverse it automatically.
;; Learnable embedding table(nn/embedding 10000 256);; Initialize from pre-trained weight matrix (frozen by default)(nn/embedding-from-pretrained pretrained-weight);; Allow the embeddings to be fine-tuned(nn/embedding-from-pretrained pretrained-weight :freeze false)
;; Flatten all dimensions starting from dim 1(nn/flatten);; Unflatten dimension 1 into [2 8](nn/unflatten 1 [2 8]);; Pass-through identity layer(nn/identity);; Nearest-neighbour upsample to a fixed size or by a scale factor(nn/upsample :size [64 64] :mode :nearest)(nn/upsample :scale-factor 2 :mode :nearest)
defmodel is a macro that generates a fully-featured Clojure record implementing the IModule protocol. It eliminates boilerplate: no manual defrecord, no hand-written -train or -to implementations.
How Registered Fields Participate in Lifecycle Operations
Any field whose value is a native Module, a Parameter, a Tensor, a TensorVector, a Clojure vector, or a Clojure map is automatically traversed by every lifecycle operation:
Operation
Behaviour on fields
nn/train
Recursively sets training/eval mode on all sub-modules
nn/to
Recursively moves tensors and parameters to device/dtype
nn/parameters
Recursively collects all leaf tensors into a TensorVector
nn/state-dict
Recursively extracts a nested map of weight tensors
Wraps execution in autograd/no-grad to suppress gradient bookkeeping.
Binds the dynamic var *trace* to an atom that intercepts every nn/forward call.
Captures the module type, output shape, and parameter count of every layer encountered during that single pass.
Because the trace is driven by a real forward pass, it faithfully captures dynamic shapes, conditional branches, and any reshape operations inside your model logic.
The outermost row (PersistentVector) represents the top-level sequential container. Its parameter count is the cumulative total of all layers inside it.
nn/to recursively traverses the entire model tree — native modules, records, vectors, maps, and bare tensors — and moves every parameter to the target device or dtype.
(nn/to model :cuda) ;; Move entire model to GPU(nn/to model :float16) ;; Cast all parameters to half precision(nn/to model :float64) ;; Cast all parameters to double
;; Collect all leaf parameters into a native TensorVector (for optimizers)(nn/parameters model);; Extract a nested Clojure map of all named weights and biases(nn/state-dict model);; Copy weights from a saved state dict into an existing model(nn/load-state-dict model saved-sd);; Save model weights to disk (state-dict format)(nn/save-weights model "checkpoint.pt");; Load weights from disk into an existing model(nn/load-weights model "checkpoint.pt")
;; Zero all gradients in the model (alternative to optim/zero-grad on the model)(nn/zero-grad model);; Clip gradient norm to prevent exploding gradients(nn/clip-grad-norm! (nn/parameters model) 1.0)
;; Flat map of all parameter name paths to tensors(nn/named-parameters model);; Sequence of all sub-modules (native and record) in the tree(nn/modules model);; Apply a side-effecting function to every module in the tree(nn/apply model (fn [m] (println (type m))))
Multi-head attention with Grouped Query Attention (GQA), RoPE embeddings, and KV-cache support. Delegates to torch/scaled_dot_product_attention for fused CUDA dispatch.
Generates tokens one step at a time using multinomial sampling, with automatic context-window truncation.
;; model: any defmodel with a forward that accepts token indices;; idx: [batch, seq-len] int64 tensor of prompt tokens(nn/generate model idx 100 context-size)