TorchLean API

NN.Spec.Core.Tensor.Linalg

Linear algebra primitives (spec layer) #

This file defines the basic matrix/vector operations used across model specifications:

All operations are shape-indexed in their types, so misuse is caught by elaboration.

These are kept simple, “obvious” definitions (folding over List.finRange) so that:

PyTorch analogies:

Create an identity matrix (n x n).

Notes:

  • The n = 0 case is an empty matrix; it still exists as a well-typed tensor.
  • We use i.val == j.val rather than DecidableEq (Fin n) to keep the definition directly executable across backends.
Instances For
    def Spec.matMulSpec {α : Type} [TorchLean.Storage α] [Add α] [Mul α] [Zero α] {m n p : } (A : TorchLean.Tensor α [m, n]) (B : TorchLean.Tensor α [n, p]) :

    Matrix multiplication (m x n) @ (n x p) = (m x p).

    This is the simplest definitional version: sum over the shared n dimension. For performance-oriented runtime code, use the runtime layer; this spec is about clarity and proofs.

    Instances For
      def Spec.matVecMulSpec {α : Type} [TorchLean.Storage α] [Add α] [Mul α] [Zero α] {m n : } (A : TorchLean.Tensor α [m, n]) (v : TorchLean.Tensor α [n]) :

      Matrix-vector multiplication (m x n) @ (n) = (m).

      Instances For
        def Spec.vecMatMulSpec {α : Type} [TorchLean.Storage α] [Add α] [Mul α] [Zero α] {m n : } (v : TorchLean.Tensor α [m]) (A : TorchLean.Tensor α [m, n]) :

        Rank-one tensor by matrix multiplication: (m) @ (m x n) = (n).

        Instances For

          Outer product (m) otimes (n) = (m x n).

          Instances For
            @[simp]
            theorem Spec.get2_outerProductSpec {α : Type} [TorchLean.Storage α] [Mul α] {m n : } (left : TorchLean.Tensor α [m]) (right : TorchLean.Tensor α [n]) (i : Fin m) (j : Fin n) :
            get2 (outerProductSpec left right) i j = left.getScalar i * right.getScalar j

            A coordinate of an outer product is the product of the corresponding vector entries.