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
Adefmodel form has exactly three parts:
- Constructor arguments — the parameters your model factory function accepts.
- Binding vector — field/value pairs evaluated once when the model is instantiated, identical in structure to
let. forwardform — 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 nativeModule, 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
- Simple shape input
- Complex / LLM input
Pass a shape vector and Clorch will synthesize a
randn tensor of that shape automatically:How the Dry-Run Works
When you callnn/summary, Clorch:
- Sets the model to
evalmode temporarily. - Wraps execution in
autograd/no-gradto suppress gradient bookkeeping. - Binds the dynamic var
*trace*to an atom that intercepts everynn/forwardcall. - Captures the module type, output shape, and parameter count of every layer encountered during that single pass.
Sample Output
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 usingdefmodel.
RMSNorm
RMSNorm
Root Mean Square Layer Normalization — lighter than LayerNorm as it omits the mean-centering step.
SwiGLU
SwiGLU
Gated feed-forward block used in LLaMA-style models. The gate is computed with SiLU.
GroupedQueryAttention
GroupedQueryAttention
Multi-head attention with Grouped Query Attention (GQA), RoPE embeddings, and KV-cache support. Delegates to Pass input as a map to supply optional components:
torch/scaled_dot_product_attention for fused CUDA dispatch.nn/generate — Autoregressive Token Generation
nn/generate — Autoregressive Token Generation
Generates tokens one step at a time using multinomial sampling, with automatic context-window truncation.