TorchLean API

NN.API.Trainer.Manual.Core

Supervised Runtime Training #

Supervised tasks, runners, steppers, optimizer configs, trainer aliases, and the low-level session exports that back executable examples.

Built-in loss choices for SeqTask.

Instances For

    A supervised task is just a model plus a choice of loss.

    Instances For

      Build a ScalarModuleDef for a task, choosing an explicit model mode (train/eval).

      This is the underlying "instantiate me as a runnable module" step for training.

      Instances For

        Default module definition for a task (training mode).

        Instances For

          Constructor: regression task (MSE loss).

          Instances For

            Constructor: one-hot classification task (cross-entropy loss).

            Instances For
              @[reducible, inline]

              Parameter shapes for a task (delegates to Seq.paramShapes).

              Instances For

                Optimizer hyperparameter configuration for the supervised training helpers.

                This configuration covers the optimizer choices exposed by the public training helpers. It mirrors a few common PyTorch optimizers by name/defaults, but it does not try to cover the full option surface of torch.optim.*.

                Instances For

                  Step-based training configuration for trainSamples / trainDataset.

                  Fields:

                  • steps: number of parameter updates,
                  • batchSize: number of samples consumed by one public step for in-memory datasets,
                  • optimizer: optimizer hyperparameters,
                  • scheduler: optional learning-rate schedule (applied per step),
                  • logEvery: progress printing frequency (0 disables logging).
                  • steps :

                    Number of optimizer updates.

                  • batchSize :

                    Number of dataset items consumed by one training step.

                    The loop differentiates every item at the same parameter point, averages the resulting gradient packs, and performs one optimizer update. If each item is already a fixed-size tensor minibatch, keep this value at 1 for one vectorized forward/backward pass per update.

                  • optimizer : OptimizerConfig

                    Optimizer configuration.

                  • Scheduler configuration.

                  • logEvery :

                    Log once every this many steps.

                  • cudaMemWatch :

                    Sample CUDA allocator state every this many completed steps; 0 disables sampling.

                  Instances For

                    State carried by the CUDA-memory drift detector used by sustained training runs.

                    Instances For

                      Resolve an explicit CUDA-memory cadence, or enable periodic sampling for very long runs.

                      Instances For

                        Sample the CUDA allocator and warn when sustained free-memory loss projects exhaustion before the requested run completes.

                        Instances For

                          Small summary returned by lower training helpers.

                          By default, before and after are mean loss values, but the type is polymorphic so callers can report other scalars in the same shape.

                          • before : α

                            Metrics before training.

                          • after : α

                            Metrics after training.

                          Instances For

                            Epoch-based training configuration for trainLoader (data-loader training).

                            Fields:

                            • epochs: number of epochs (each epoch iterates once over the loader),
                            • optimizer: optimizer hyperparameters,
                            • scheduler: optional learning-rate schedule applied once per epoch,
                            • logEvery: progress printing frequency (0 disables logging).
                            Instances For

                              Extract the base learning rate encoded in an optimizer configuration.

                              Instances For

                                Resolve the learning rate to use at a given training step.

                                If a scheduler is present, it takes precedence over the optimizer's baked-in base learning rate. Otherwise it returns optimizerLR cfg.

                                Instances For
                                  def TorchLean.Trainer.Manual.mapStateList {State : TypeSpec.ShapeType} {α : Type} {ss : List Spec.Shape} :
                                  ({s : Spec.Shape} → State α sState α s)Runtime.Autograd.TorchLean.StateList State α ssRuntime.Autograd.TorchLean.StateList State α ss

                                  Map a state update over every optimizer-state entry in a shape-indexed parameter list.

                                  Instances For

                                    Set the learning rate field of every Adam optimizer state entry to lr.

                                    Instances For

                                      Set the learning rate field of every plain-SGD optimizer state entry to lr.

                                      Instances For

                                        Set the learning rate field of every momentum-SGD optimizer state entry to lr.

                                        Instances For

                                          Set the learning rate field of every AdaGrad optimizer state entry to lr.

                                          Instances For

                                            Set the learning rate field of every RMSProp optimizer state entry to lr.

                                            Instances For

                                              Set the learning rate field of every AdamW optimizer state entry to lr.

                                              Instances For

                                                Set the learning rate field of every Adadelta optimizer state entry to lr.

                                                Instances For
                                                  structure TorchLean.Trainer.Manual.Runner (α : Type) [Context α] [DecidableEq Spec.Shape] {σ τ : Spec.Shape} (task : SeqTask σ τ) :

                                                  A fully instantiated supervised task runner.

                                                  This bundles:

                                                  • the imperative ScalarModule (parameters/buffers stored in refs),
                                                  • compiled forward artifacts and loss functions for both .train and .eval modes (so switching mode is low-overhead),
                                                  • and the current mode stored in an IO.Ref.

                                                  The mode influences both operator behavior (e.g. dropout/batchnorm) and whether buffers are updated during training.

                                                  Instances For

                                                    Finish runner construction once parameter storage has been instantiated.

                                                    Instances For

                                                      Instantiate a Runner by explicitly providing a Float → α cast and backend.

                                                      Use this when you want to run the same task over different numeric backends (e.g. Float vs IEEE32Exec) or when you want custom literal injection.

                                                      Instances For

                                                        Instantiate a Float runner using storage-first parameter initialization when the model provides it. Models without a runtime plan automatically retain the ordinary tensor initializer path.

                                                        Instances For

                                                          Instantiate a Runner by explicitly providing a Float → α cast and a backend selector.

                                                          Instantiate a module with explicit runtime options.

                                                          Instances For

                                                            Instantiate a Runner using the standard runtime literal injection _root_.TorchLean.Runtime.ofFloat.

                                                            This is the common entrypoint for executable examples.

                                                            Instances For

                                                              Instantiate a Runner using the standard runtime literal injection _root_.TorchLean.Runtime.ofFloat and a backend selector.

                                                              Instantiate a module after parsing runtime options.

                                                              Instances For
                                                                def TorchLean.Trainer.Manual.run {σ τ : Spec.Shape} (task : SeqTask σ τ) (args : List String) (k : {α : Type} → [inst : Context α] → [inst_1 : DecidableEq Spec.Shape] → [ToString α] → [Runtime.FromFloat α] → Runner α taskList StringIO Unit) :

                                                                Run a TorchLean task with CLI-style dtype/backend selection, then call k with a fully constructed runner.

                                                                This is used by lake exe entrypoints: run takes care of parsing dtype flags and instantiating the underlying module/compiled programs.

                                                                Instances For
                                                                  def TorchLean.Trainer.Manual.params {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) :

                                                                  Read the current parameter list from a runner.

                                                                  Instances For

                                                                    Read the runner's current mode (.train or .eval).

                                                                    Instances For

                                                                      Set the runner mode (.train or .eval).

                                                                      Instances For
                                                                        def TorchLean.Trainer.Manual.trainMode {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) :

                                                                        Convenience: setMode runner .train.

                                                                        Instances For
                                                                          def TorchLean.Trainer.Manual.evalMode {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) :

                                                                          Convenience: setMode runner .eval.

                                                                          Instances For
                                                                            def TorchLean.Trainer.Manual.isTraining {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) :

                                                                            Predicate: are we in training mode?

                                                                            Instances For

                                                                              Pick the predictor compiled for the runner's current mode (.train or .eval).

                                                                              Instances For

                                                                                Pick the loss program compiled for the runner's current mode (.train or .eval).

                                                                                Instances For
                                                                                  def TorchLean.Trainer.Manual.updateRunnerBuffers {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) (sample : Runtime.Autograd.Torch.TList α [σ, τ]) :

                                                                                  Refresh mode-dependent runner buffers using one supervised sample.

                                                                                  This mutates the module parameters only in .train mode, mirroring PyTorch-style buffer updates for layers such as normalization. In .eval mode it is a no-op.

                                                                                  Instances For

                                                                                    Run one forward/backward pass on a single supervised sample and return gradients for all parameters. Unlike PyTorch's in-place .grad convention, this API returns the gradient pack explicitly.

                                                                                    Instances For
                                                                                      def TorchLean.Trainer.Manual.predict {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) (x : Spec.Tensor α σ) :
                                                                                      IO (Spec.Tensor α τ)

                                                                                      Predict on one input tensor using the runner's active mode (.train or .eval).

                                                                                      Instances For
                                                                                        def TorchLean.Trainer.Manual.predictBatch {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) (xs : List (Spec.Tensor α σ)) :
                                                                                        IO (List (Spec.Tensor α τ))

                                                                                        Predict on a list of inputs by repeatedly calling predict.

                                                                                        Instances For

                                                                                          For classification heads: run predict, then take argmax over the logits (if defined).

                                                                                          Instances For

                                                                                            Compute (correct, total) for a one-hot classification dataset.

                                                                                            Instances For
                                                                                              def TorchLean.Trainer.Manual.meanLoss {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] [ToString α] (runner : Runner α task) (samples : List (Runtime.Autograd.Torch.TList α [σ, τ])) :
                                                                                              IO α

                                                                                              Mean scalar loss over a list of supervised samples (uses the runner's active mode).

                                                                                              Instances For

                                                                                                Mean scalar loss over a dataset (materialized via dataset.toList).

                                                                                                Instances For
                                                                                                  def TorchLean.Trainer.Manual.moduleLoss {σ τ : Spec.Shape} {task : SeqTask σ τ} {α : Type} [Context α] [DecidableEq Spec.Shape] (runner : Runner α task) (sample : Runtime.Autograd.Torch.TList α [σ, τ]) :
                                                                                                  IO α

                                                                                                  Scalar loss for one sample through the instantiated runtime module.

                                                                                                  Instances For

                                                                                                    Treat 0 as the conservative single-sample step size.

                                                                                                    Instances For
                                                                                                      def TorchLean.Trainer.Manual.nextCyclicBatch {α : Type} (context : String) (samples : List α) (restRef : IO.Ref (List α)) (batchSize : ) :
                                                                                                      IO (List α)

                                                                                                      Take the next cyclic group of samples from an in-memory training set.

                                                                                                      Instances For