Torch Utils #
Helpers for writing PyTorch-style training loops on top of Runtime.Autograd.Torch.
This file focuses on training-loop ergonomics:
- extract scalar values,
- build short
TLists, - run simple SGD loops for
Torch.ScalarTrainer.
Stateful optimizer loops live in Runtime.Autograd.TorchLean, because those depend on
TorchLean.Optim. Keeping that dependency out of this low-level utility module prevents the
session/ref layer from depending upward on the model/optimizer API surface.
Initialization helpers (Float constants) #
Deterministic initialization schemes stored as Float constants.
PyTorch comparison:
.zeros/.onescorrespond totorch.nn.init.zeros_/torch.nn.init.ones_.uniform lo hicorresponds totorch.nn.init.uniform_(with explicita=lo,b=hi).xavierUniform fanIn fanOutcorresponds totorch.nn.init.xavier_uniform_.kaimingUniform fanIncorresponds totorch.nn.init.kaiming_uniform_withnonlinearity="relu"
References:
- https://pytorch.org/docs/stable/nn.init.html
- https://pytorch.org/docs/stable/generated/torch.nn.init.xavier_uniform_.html
- https://pytorch.org/docs/stable/generated/torch.nn.init.kaiming_uniform_.html
- zeros : Scheme
- ones : Scheme
- uniform (lo hi : Float) : Scheme
- normal (mean std : Float) : Scheme
- xavierUniform (fanIn fanOut : ℕ) : Scheme
- kaimingUniform (fanIn : ℕ) : Scheme
Instances For
SplitMix64 mixing used by indexed parameter initialization.
Instances For
Deterministic U[0,1) sampler derived independently from a seed and scalar index.
Indexing is constant-time, so constructing an n-element tensor takes O(n) sampler work. The
same key/index formula is used by TorchLean's storage-first runtime initializer.
Instances For
Sample the idx-th scalar of a tensor initialized using Scheme.
This is the scalar-level primitive used by Init.tensor.
Instances For
Create a Tensor Float s by sampling a Scheme deterministically.
This pure initializer is convenient for model definitions and reproducible examples. Runtime initialization paths can provide more specialized allocation strategies for very large tensors.
PyTorch comparison: this mimics using torch.nn.init.* routines on freshly allocated parameters,
but here we work with pure Tensor Float s values (no mutation) and use a deterministic
seeded sampler for reproducibility.
Instances For
Instances For
Xavier/Glorot-uniform initializer for 2D weight matrices.
PyTorch comparison: torch.nn.init.xavier_uniform_ with gain=1.
Instances For
Kaiming/He-uniform initializer for 2D weight matrices.
PyTorch comparison: torch.nn.init.kaiming_uniform_ with nonlinearity="relu" and default
parameters (so the bound is sqrt(6/fan_in)).
Instances For
Conveniences for scalar training loops #
Extract the scalar value from a scalar-shaped tensor.
PyTorch comparison: like t.item() for a 0-dim tensor.
Instances For
Build a one-element TList (useful for curried trainer APIs).
Instances For
TList syntax sugar #
Build a TList from a comma-separated list of terms.
This is meant for training code where tlistSingleton/tlistPair/… becomes tedious.
Example:
let xs : TList Float [.dim 2 .scalar, .dim 1 .scalar] :=
tlist![x, y]
Instances For
Build a two-element TList (useful for curried trainer APIs).
Instances For
Build a three-element TList (useful for curried trainer APIs).
Instances For
Build a four-element TList (useful for curried trainer APIs).
Instances For
Uncurried forward pass for ScalarTrainer.
ScalarTrainer.forward is stored as a curried function over the input shapes; this helper lets you
pass a TList (like a tuple of tensors).
Instances For
Uncurried loss-and-gradient pass for ScalarTrainer.
The loss and gradients come from the same tape. Use this instead of calling forwardT followed by
backwardT when both results are needed.
Instances For
Uncurried backward pass for ScalarTrainer.
Returns per-parameter gradients (aligned with paramShapes).
Instances For
Uncurried SGD step for ScalarTrainer.
PyTorch comparison: analogous to loss.backward(); optimizer.step() for a fixed SGD optimizer,
except here the trainer bundles the update rule.
Instances For
Uncurried SGD step that returns the loss used to compute the update.
Instances For
Train steps SGD updates, cycling through samples.
PyTorch comparison: this matches the common eager training skeleton:
for step in range(steps):
batch = dataset[step % len(dataset)]
loss = forward(batch)
step(lr, batch) # typically: loss.backward(); optimizer.step()
Note: ScalarTrainer.step is the "bundled SGD optimizer" for the trainer. Stateful optimizers
(Adam, RMSProp, ...) are exposed from Runtime.Autograd.TorchLean.
Instances For
Evaluate mean loss over a dataset.
PyTorch comparison: like running a model in torch.no_grad() over a dataloader and averaging
the scalar loss values, except here we call ScalarTrainer.forwardT directly.