NN #
TorchLean.NN: a compact torch.nn-style builder layer.
This module defines a small torch.nn-style builder layer for constructing shape-typed models.
It packages model-state shapes and initial values together with an execution-polymorphic forward
program, so example code does not have to spell paramShapes := [...] / inputShapes := [...]
everywhere.
Main definitions #
Layer σ τpackages a shape-typed layer with explicit state (parameters and buffers) and a polymorphicforwardprogram.Seq σ τcomposes layers sequentially (PyTorch analogy:torch.nn.Sequential), writtenf >>> g.Seq.Objectivebundles aSeqmodel together with a scalar loss, producing aTorchLean.Module.ObjectiveDefthat the runtime training code can execute.
PyTorch analogies #
Layeris like a smallnn.Moduledefinition, except parameters are an explicit list instead of fields, and the forward pass is a typed TorchLean program.Modeis likemodule.train()vsmodule.eval()(dropout and batchnorm-like layers branch on it).- The
updateBuffersmechanism is like updating non-gradient buffers (e.g. BatchNorm running stats).
The surface here is narrow by design: it supports TorchLean's executable model constructors and
training helpers without trying to mirror the full torch.nn API.
References #
- PyTorch
torch.nn: https://pytorch.org/docs/stable/nn.html
Mode #
TorchLean keeps "train vs eval" behavior explicit. This affects layers like dropout and batch-normalization that behave differently during training vs inference.
Execution mode for layers that branch between training-time and inference-time behavior.
PyTorch analogy: model.train() / model.eval() (affects dropout, batchnorm, etc.).
Instances For
Layer definitions #
A shape-typed layer definition with explicit model state and an execution-polymorphic forward program.
Layer σ τ is the core building block used by Seq (sequential composition). It stores:
- the shapes of parameters and persistent buffers,
- initial values for that state (as
Floattensors, for reproducible initialization), - per-parameter
requiresGradflags, and - a
forwardprogram that is polymorphic over the backend monad and scalar type.
PyTorch analogy: a small nn.Module, where:
stateShapes/initStatecontain parameters and persistent buffers,forwardcorresponds toModule.forward,updateBufferscorresponds to updating things likerunning_mean/running_varin BatchNorm.
- kind : String
Layer label used by public model summaries.
- stateShapes : List Spec.Shape
Shapes of parameters and persistent buffers, in the order expected by
forward. - initState : TorchLean.TensorPack Float self.stateShapes
Initial model state, stored as
Floattensors for convenient initialization. - runtimeInit : Option (Module.RuntimeInit.Plan self.stateShapes)
Optional storage-first initialization plan for executable
Floatbackends.This does not replace
initState: the tensor-valued initializers remain available to the specification and proof layers. The plan lets a runtime create equivalent parameter storage without first enumerating those tensors on the host. Gradient flags for model state (defaults to all
true). Buffers usefalse.PyTorch analogy:
tensor.requires_grad_(...)on parameters/buffers.Validate static layer configuration before allocating runtime state or lowering a graph.
Shape compatibility remains enforced by the type. This check is for value-level configuration such as a dropout probability that must belong to a finite numeric interval.
- updateBuffers : Option (Mode → {α : Type} → [inst : TorchLean.Storage α] → [Context α] → TorchLean.TensorPack α self.stateShapes → TorchLean.Tensor α σ → IO (TorchLean.TensorPack α self.stateShapes))
Optional buffer update function (used for running-statistics style layers).
This is called during a forward pass (typically in
Mode.train) to produce updated parameter/buffer state values. A canonical example is BatchNorm updating itsrunning_mean/running_varbuffers. - updatesBuffersInForward : Bool
Composite layers delegate runtime buffer updates to their nested forward programs.
- forward : Mode → {α : Type} → [inst : TorchLean.Storage α] → [inst✝ : Context α] → Program α (self.stateShapes ++ [σ]) τ
Forward pass as a typed TorchLean program.
The program expects
(stateShapes ++ [σ])inputs (model state, then the layer input) and produces an output of shapeτ.
Instances For
Update running statistics of any shape using momentum.
This implements an exponential moving average:
next = (1 - momentum) * running + momentum * batch.
PyTorch analogy: the update performed for running_mean / running_var in BatchNorm.
Instances For
Convert the biased variance used by BatchNorm's training forward pass into the unbiased estimate stored in its running buffer. For a singleton sample set there is no unbiased estimate; TorchLean keeps the finite biased value rather than dividing by zero.
Instances For
Compute per-channel mean and biased variance for a batched tensor.
The first two axes are batch and channel; every remaining axis is reduced. The result is a pair of
vectors indexed by channel. A running-variance update uses
unbiasedRunningVariance vars (batch * spatial.size) instead.
Instances For
Validate a layer's complete static contract.
Configuration checks supplied by the layer are combined with generic state-metadata and runtime initializer checks so every execution path rejects malformed custom layers consistently.
Instances For
Run a Layer forward given parameter refs and an input ref.
This is the "module forward" operation at the reference level.
PyTorch analogy: calling layer(x) where the layer's parameters are already allocated.
Instances For
Run a Layer on concrete tensors by lowering its forward program to a typed graph.
This is primarily used by runtime utilities (e.g. sequential updateBuffers) where we want to run
forward to obtain intermediate activations.
PyTorch analogy: running a forward pass eagerly on concrete tensors.