Session #
TorchLean unified imperative session.
Session state #
A Session α is TorchLean's runtime analogue of a PyTorch "training loop environment". It:
- owns a collection of leaf tensors (parameters and inputs),
- records an eager computation on a tape or builds typed SSA graph data,
- can run reverse-mode AD to produce gradients for all leaves, and
- can apply simple optimizer steps (e.g. SGD) in a session-style workflow.
TorchLean exposes a single API with two execution modes selected at construction time:
.eager: a tape-backed runtime session (imperative autograd tape; useful for debugging and interactive examples),.typedGraph: a session that records shape-indexed graph data while building the runtime tape, then executes viaRuntime.Autograd.Torch.Internal.TypedGraphSession.
Both modes use the same Session API; each operation dispatches through Session.state.
Typical Training Loop (PyTorch Analogy) #
Think of the following mapping (approximately):
Session.param~ create atorch.nn.Parameter(and later include it in astate_dict-like bundle).Session.use~ read a parameter as a tensor in the current recording phase.Session.input~ add a leaf tensor input (like feeding a batch tensor into the forward pass).Session.resetTape~ start a fresh recording phase (closest in spirit tooptimizer.zero_grad()+ new forward).Session.backwardScalarDenseAll~loss.backward()(but returns gradients explicitly as an array).Session.sgdStepAll~optimizer.step()(dense helper; higher-level training lives inNN.API.*).Session.detach~tensor.detach()(cut the gradient edge at a value).
TorchLean does not store mutable .grad fields on each tensor ref; instead, gradients are
returned
explicitly (see grad, vjp, and the backward*DenseAll functions).
Non-Differentiable State (NatRef) #
NatRef stores the seed and counter used by the explicit random stream. Non-differentiable tensor
inputs use the element-polymorphic data-input channel rather than a second session tensor type.
Deterministic RNG (Session-Level) #
RngState provides explicit, deterministic RNG state (closer to JAX PRNG keys than a global RNG).
freshSeedIO is a convenience for sampling an initial seed at the IO boundary, while the core
semantics remains seed-threaded and replayable.
Connection To TorchLean IR / Graph Execution #
In .typedGraph execution, the session records executable GraphData while building the tape.
Each call to resetTape starts a new recording phase. Callers that need one reusable artifact
should use Runtime.Autograd.Torch.TypedGraph directly; the high-level scalar trainer uses that
artifact and records its loss graph once.
The type-level context checks graph shapes. Correctness of a stored JVP or VJP is a separate claim,
proved only for operations connected to the proof-carrying Proofs.Autograd.Algebra.Node layer.
Practical note: the current .typedGraph implementation expects all leaves (tensor
inputs/parameters and NatRefs) to be created before any op nodes are recorded. For portability,
allocate leaves and initialize/split RNG up-front, then build the typed graph.
PyTorch References #
torch.autograd: https://pytorch.org/docs/stable/autograd.html- Tensor hooks (conceptual analogue of
backwardDenseAllWithHook): https://pytorch.org/docs/stable/generated/torch.Tensor.register_hook.html
AD References #
This code follows the classic "tape / Wengert list" view of reverse-mode AD:
- Andreas Griewank and Andrea Walther, Evaluating Derivatives, 2nd ed., 2008.
- Seppo Linnainmaa, 1970 (reverse accumulation; precursor to modern backprop/autograd).
Eager-only session wrapper.
This is the public eager-session record backed by the internal tape session
Runtime.Autograd.Torch.Internal.EagerSession. Users normally interact with the unified Session
API; this type exists to support execution-mode dispatch (SessionState.eager).
- inner : Torch.Internal.EagerSession α
The internal tape session being wrapped. The extra layer exists so the execution-mode dispatch in
SessionStatehas a public type to name.
Instances For
Create a new eager (tape-backed) session.
This corresponds to the .eager execution mode of Session.new.
Instances For
Reset the eager autograd tape and begin a fresh recording phase.
Instances For
Create a learnable parameter owned by this session.
PyTorch analogy: creating a torch.nn.Parameter during module initialization.
Instances For
Use a parameter in the current eager recording.
PyTorch analogy: reading a parameter in forward (it becomes part of the autograd graph).
Instances For
Add a tensor input leaf to the current graph.
requiresGrad controls whether this input is recorded as a differentiable leaf.
Instances For
Add a non-differentiable Nat leaf to the session.
Used for labels/indices and gather-style ops.
Instances For
Read a NatRef value.
Instances For
Mutate a NatRef value.
Instances For
Insert a constant tensor into the current graph.
PyTorch analogy: using a tensor literal/constant in the forward pass (as a leaf constant node).
Instances For
Read the concrete value for a tensor ref (for logging/debugging).
Instances For
Detach a tensor ref from the tape (stop gradient flow through it).
PyTorch analogy: x.detach().
Instances For
Elementwise addition on tensor refs (eager execution path).
Instances For
Elementwise subtraction on tensor refs (eager execution path).
Instances For
Elementwise multiplication on tensor refs (eager execution path).
Instances For
Elementwise scaling by a scalar constant c (eager execution path).
Instances For
Elementwise absolute value (eager execution path).
Instances For
Elementwise square root (eager execution path).
Instances For
Elementwise clamp to [minVal, maxVal] (eager execution path).
Instances For
Elementwise maximum (eager execution path).
Instances For
Elementwise minimum (eager execution path).
Instances For
Matrix multiplication with broadcasted batch prefixes (eager execution path).
Instances For
Concatenate along the outermost dimension (dimension 0) (eager execution path).
PyTorch analogy: torch.cat([a, b], dim=0).
Instances For
Slice a contiguous [start, start+len) range from dimension 0 (eager execution path).
PyTorch analogy: x[start:start+len] for the first dimension.
Instances For
Apply max pooling over an arbitrary number of spatial axes.
Instances For
Apply smooth max pooling over an arbitrary number of spatial axes.
Instances For
Apply average pooling over an arbitrary number of spatial axes.
Instances For
Elementwise ReLU activation (eager execution path).
Instances For
Elementwise sigmoid activation (eager execution path).
Instances For
Elementwise tanh activation (eager execution path).
Instances For
Softmax along an explicitly selected tensor dimension (eager execution path).
Instances For
Stable log-softmax along an explicitly selected tensor dimension (eager execution path).
Instances For
Elementwise softplus activation (eager execution path).
Instances For
Elementwise exponential (eager execution path).
Instances For
Elementwise sine of angles in radians, recorded on the eager session's tape.
Instances For
Elementwise cosine with the eager tape's -sin(x) * dLdy backward rule.
Instances For
Elementwise logarithm (eager execution path).
Instances For
Elementwise safeLog activation (log(softplus(x) + ε)) (eager execution path).
Instances For
Sum-reduce a tensor to a scalar (eager execution path).
Instances For
Flatten a tensor into a 1D vector (eager execution path).
Instances For
Reshape a tensor, given a proof that the total number of elements is preserved (eager execution path).
PyTorch analogy: x.reshape(...) when the element count matches.
Instances For
Generic "swap adjacent axes" view operation (eager execution path).
This is a shape-driven permutation helper used in some attention/transformer code.
Instances For
Broadcast a tensor to a larger shape (eager execution path).
Instances For
Reduce-sum along an axis (eager execution path).
Instances For
Reduce-mean along an axis (eager execution path).
Instances For
Select one bounded coordinate from an arbitrary tensor axis.
Instances For
Select several bounded coordinates from an arbitrary tensor axis.
Instances For
Add source slices into an arbitrary tensor axis at bounded coordinates.
Instances For
Fully-connected (affine) layer on vectors: y = w·x + b (eager execution path).
PyTorch analogue: torch.nn.functional.linear (with weight shape (outDim, inDim)).
Instances For
Mean squared error loss returning a scalar (eager execution path).
PyTorch analogue: torch.nn.functional.mse_loss(..., reduction='mean').
Instances For
LayerNorm over a seqLen × embedDim tensor (eager execution path).
PyTorch analogue: torch.nn.LayerNorm(embedDim) applied per token.
Instances For
Batch normalization over every spatial axis of a channel-first tensor.
Instances For
N-D convolution over a channels-first tensor (inC, spatial...) (eager execution path).
PyTorch analogue: torch.nn.functional.conv{d}d specialized to a single sample.
Instances For
N-D transpose convolution over a channels-first tensor (inC, spatial...) (eager execution path).
PyTorch analogue: torch.nn.functional.conv_transpose{d}d specialized to a single sample.
Instances For
Multi-head self-attention (eager execution path).
This is the eager implementation used by the transformer examples (approximately analogous to
torch.nn.MultiheadAttention in self-attention mode).
Instances For
Run a backward pass and return dense gradients for all leaves (eager execution path).
See the unified version Session.backwardDenseAll for the public API.
Instances For
Backward pass specialized to scalar losses (seed is implicitly 1) (eager execution path).
Instances For
Apply an SGD step to all learnable parameters given a dense gradient array (eager execution path).
PyTorch analogy: optimizer.step() for an SGD optimizer, with gradients supplied explicitly.