Skip to main content
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.

Common Layers

Linear (Dense) Layers

nn/linear creates a fully-connected layer backed by LibTorch’s LinearImpl. The optional :bias false keyword disables the bias term.

Convolutional Layers

Clorch exposes 1D, 2D, and 3D convolutions and their transpose variants with the full set of spatial options.

Recurrent Layers

LSTM, GRU, and plain RNN delegate directly to LibTorch’s optimized C++ RNN implementations.

Normalization

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.

Pooling & Padding

Containers

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.

Embeddings

Utility Layers


Custom Models with defmodel

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.

The Three Parts

A defmodel form has exactly three parts:
  1. Constructor arguments — the parameters your model factory function accepts.
  2. Binding vector — field/value pairs evaluated once when the model is instantiated, identical in structure to let.
  3. forward form — a method body that may reference any binding by name.

Constructing and Calling the Model

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:

Model Inspection with nn/summary

nn/summary prints a PyTorch-style table showing the output shape and parameter count of every layer visited during a forward pass.

Usage

Pass a shape vector and Clorch will synthesize a randn tensor of that shape automatically:

How the Dry-Run Works

When you call nn/summary, Clorch:
  1. Sets the model to eval mode temporarily.
  2. Wraps execution in autograd/no-grad to suppress gradient bookkeeping.
  3. Binds the dynamic var *trace* to an atom that intercepts every nn/forward call.
  4. 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.

Sample Output

The outermost row (PersistentVector) represents the top-level sequential container. Its parameter count is the cumulative total of all layers inside it.

Lifecycle API

Mode Management

Device and Dtype Transfer

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.

Parameters and State Dictionaries

Gradient Management

Forward Pass

nn/forward is polymorphic: it accepts native Module instances, defmodel records, plain Clojure vectors (sequential), and Clojure functions.

Introspection


LLM-Specific Modules

Clorch ships with production-ready building blocks for large language models, all defined using defmodel.
Root Mean Square Layer Normalization — lighter than LayerNorm as it omits the mean-centering step.
Gated feed-forward block used in LLaMA-style models. The gate is computed with SiLU.
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.
Pass input as a map to supply optional components:
Generates tokens one step at a time using multinomial sampling, with automatic context-window truncation.