TorchLean API

NN.API.Neural.Indexed

Indexed Models and Embeddings #

This module defines models with non-differentiable tensor inputs, their scalar objectives, and embedding-table builders. Import NN.API.Neural.Indexed when constructing or executing an indexed model; ordinary sequential builders remain in NN.API.Neural.Builders.

structure TorchLean.nn.IndexedModel (σ τ : Shape) (β : Type) [Storage β] :

A shape-typed model with one non-differentiable tensor input.

Instances For
    opaque TorchLean.nn.IndexedModel.Internal.create {σ τ : Shape} {β : Type} [Storage β] (stateShapes : List Shape) (initialState : State Float stateShapes) (program : Mode → {α : Type} → [inst : Storage α] → [inst_1 : Context α] → Runtime.Autograd.Model.Program.Data α β stateShapes [σ] τ) (kind : String := "IndexedModel") (initializationPlan : Option (Module.RuntimeInit.Plan stateShapes) := none) (trainableMask : Array Bool := Array.replicate stateShapes.length true) (validateModel : Except String Unit := pure ()) (validateInput : Tensor β σ → Except String Unit := fun (x : Tensor β σ) => pure ()) :
    IndexedModel σ τ β

    Construct an indexed model from its complete runtime definition.

    def TorchLean.nn.IndexedModel.Internal.invalidConfiguration {β : Type} [Storage β] (input output : Shape) (kind message : String) :
    IndexedModel input output β

    Build an indexed-model placeholder whose static configuration is known to be invalid.

    The placeholder owns no parameters or buffers and is rejected by IndexedModel.validate before allocation or execution.

    Instances For

      The model readers are opaque so proofs cannot unfold them into private fields. Public readers expose model metadata; this namespace supplies the runtime-only configuration and program readers. Builders can change the representation without exposing it to downstream proofs.

      How the runtime should fill the state at allocation time, or none for an unplanned model.

      Static verdict on the configuration, checked before anything is allocated.

      opaque TorchLean.nn.IndexedModel.Internal.validateInput {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) (input : Tensor β σ) :

      Verdict on one concrete input, for conditions the shape type cannot express.

      opaque TorchLean.nn.IndexedModel.Internal.program {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) (mode : Mode) {α : Type} [Storage α] [Context α] :

      The runtime program for a given Mode, scalar-polymorphic in its execution type.

      opaque TorchLean.nn.IndexedModel.kind {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) :

      Model label used in summaries and diagnostics.

      opaque TorchLean.nn.IndexedModel.initialState {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) :

      Semantic initial values for the complete model state.

      opaque TorchLean.nn.IndexedModel.requiresGrad {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) :

      Gradient flags aligned with stateShapes.

      def TorchLean.nn.IndexedModel.validate {σ τ : Shape} {β : Type} [Storage β] (model : IndexedModel σ τ β) :

      Validate static model configuration before allocation or graph execution.

      Instances For
        def TorchLean.nn.IndexedModel.andThen {β : Type} [Storage β] {σ τ υ : Shape} (first : IndexedModel σ τ β) (rest : Sequential τ υ) :
        IndexedModel σ υ β

        Append an ordinary sequential model after an indexed-input model.

        Instances For

          Scalar objectives #

          def TorchLean.nn.IndexedModel.Objective.fromLoss {β : Type} [Storage β] {σ τ υ : Shape} (model : IndexedModel σ τ β) (loss : {α : Type} → [inst : Storage α] → [inst_1 : Context α] → Runtime.Autograd.Model.Program α [τ, υ] []) (mode : Mode := Mode.train) :

          Pair an indexed-input model with a scalar loss.

          The resulting objective definition has one ordinary target tensor and a separate non-differentiable model-input tensor. Keeping those packs separate ensures that indices cannot receive gradients or be reinterpreted through the model's floating-point element type.

          The target shape is independent of the model output shape, so this constructor also supports losses whose labels use a different representation from the prediction. Training mode is the default.

          Instances For

            Pair an indexed-input model with mean-squared error.

            Instances For
              structure TorchLean.nn.Embedding (vocabularySize embeddingWidth : ℕ) :

              A reusable trainable embedding table with vocabularySize rows and vectors of length embeddingWidth.

              Unlike IndexedModel, this definition is independent of the eventual token-tensor shape. Calling table.model indices specializes it to an input shape with bounded Fin vocabularySize indices. Instantiating that model produces mutable weight storage; the definition itself remains immutable so it can be lowered and used in proofs.

              Instances For
                opaque TorchLean.nn.Embedding.Internal.create {vocabularySize embeddingWidth : ℕ} (initialWeight : Tensor Float [vocabularySize, embeddingWidth]) (initializationPlan : Module.RuntimeInit.Plan [[vocabularySize, embeddingWidth]]) (trainable : Bool := true) (validation : Except String Unit := pure ()) :
                Embedding vocabularySize embeddingWidth

                Construct an embedding table at the runtime-builder boundary.

                opaque TorchLean.nn.Embedding.Internal.initializationPlan {vocabularySize embeddingWidth : ℕ} (table : Embedding vocabularySize embeddingWidth) :
                Module.RuntimeInit.Plan [[vocabularySize, embeddingWidth]]

                How the runtime should fill that matrix at allocation time.

                opaque TorchLean.nn.Embedding.Internal.isTrainable {vocabularySize embeddingWidth : ℕ} (table : Embedding vocabularySize embeddingWidth) :

                Whether the optimizer may update the table, false for a frozen lookup.

                opaque TorchLean.nn.Embedding.Internal.validation {vocabularySize embeddingWidth : ℕ} (table : Embedding vocabularySize embeddingWidth) :

                Static configuration verdict, including errors from Embedding.Internal.invalid.

                def TorchLean.nn.Embedding.Internal.invalid (vocabularySize embeddingWidth : ℕ) (message : String) :
                Embedding vocabularySize embeddingWidth

                Construct a rejected table value without exposing parameter state through Embedding.model.

                Instances For
                  opaque TorchLean.nn.Embedding.initialWeight {vocabularySize embeddingWidth : ℕ} (table : Embedding vocabularySize embeddingWidth) :
                  Tensor Float [vocabularySize, embeddingWidth]

                  Initial table values, with one row per vocabulary item.

                  Construction options for a freshly initialized embedding table.

                  • weightInitialization : Init.Scheme

                    Initialization scheme for the table.

                    The default agrees with torch.nn.Embedding.reset_parameters: independent samples from the standard normal distribution. Language-model constructors normally override this with their architecture-specific initialization, such as GPT-2's standard deviation 0.02.

                  • freeze : Bool

                    Freeze the table by excluding it from reverse-mode parameter gradients.

                  Instances For

                    Validate dimensions shared by configured and exact-weight embeddings.

                    Instances For
                      def TorchLean.nn.Embedding.Config.validate (config : Config) (vocabularySize embeddingWidth : ℕ) :

                      Validate embedding dimensions and initialization.

                      Instances For
                        def TorchLean.nn.Embedding.fromWeight {vocabularySize embeddingWidth : ℕ} (weight : Tensor Float [vocabularySize, embeddingWidth]) (freeze : Bool := false) :
                        Embedding vocabularySize embeddingWidth

                        Construct an embedding from an exact initial weight table.

                        This is the typed counterpart of passing _weight to torch.nn.Embedding. The supplied tensor fixes both dimensions at compile time and is also recorded as an exact row-major runtime initializer, so CPU and CUDA module construction start from the same payload.

                        Instances For
                          def TorchLean.nn.Embedding.model {vocabularySize embeddingWidth : ℕ} (table : Embedding vocabularySize embeddingWidth) (input : Shape) :
                          IndexedModel input (input.appendDim embeddingWidth) (Fin vocabularySize)

                          Specialize an embedding table to a concrete index-tensor shape.

                          Instances For