TorchLean API

NN.API.Data.Dataset

Datasets, Loaders, and File Sources #

TorchLean datasets keep each sample's tensor shapes in its type. A file-backed workflow usually looks like this:

  1. Convert outside-world datasets to canonical .npy tensors or small numeric CSV files.
  2. Describe those files with TensorSource, SupervisedSource, or LabeledSource.
  3. Load them into shape-typed TorchLean tensors and datasets.
  4. Train with batchLoader, BatchLoader.epoch, trainer.train, or a manual trainer loop.

We keep the implementation small and predictable:

PyTorch Mapping #

This is inspired by torch.utils.data:

TorchLean’s key difference is that samples typically carry type-level shapes (via TensorPack), so many helpers here are shape-aware by construction.

Main Types #

For examples and conversion commands, see NN/Examples/Data/README.md.

@[reducible, inline]

Typed analogue of PyTorch's TensorDataset.

In TorchLean, a sample is usually a TensorPack α shapes, i.e. a shape-tracked tuple of tensors.

Instances For

    Build a dataset from an explicit list of samples.

    Instances For
      def TorchLean.Data.requireFiles (exeName : String) (paths : List System.FilePath) (hint : String := "") :

      Require that all paths exist, otherwise raise a user-facing error with a shared hint.

      Instances For
        def TorchLean.Data.requireFile (exeName label : String) (path : System.FilePath) (hint : String := "") :

        Require one named data file to exist.

        Instances For
          def TorchLean.Data.requirePairedFiles (exeName xLabel : String) (xPath : System.FilePath) (yLabel : String) (yPath : System.FilePath) (hint : String := "") :

          Require paired supervised input/target files to exist.

          Instances For

            Write a small CSV file, creating the parent directory if needed.

            Instances For

              Write a one-dimensional prediction probe CSV.

              Rows are i,x,input,target,prediction, where $x=i/(n-1)$ for $n>1$. This writes the compact prediction table used by plotting examples such as 1D operator learning.

              Instances For
                def TorchLean.Data.toList {a : Type} (ds : Dataset a) :

                Materialize a dataset as a list.

                Instances For
                  @[simp]
                  theorem TorchLean.Data.toList_fromList {a : Type} (xs : List a) :
                  toList (fromList xs) = xs

                  Converting a list to a dataset and back yields the original list.

                  def TorchLean.Data.size {a : Type} (ds : Dataset a) :

                  Number of elements in the dataset.

                  Instances For
                    @[simp]
                    theorem TorchLean.Data.size_fromList {a : Type} (xs : List a) :

                    The size of a dataset built from a list is the list length.

                    Whether the dataset is empty.

                    Instances For
                      def TorchLean.Data.cycleList {a : Type} (xs : List a) (h : xs []) :
                      a

                      Build a cycling index function for a nonempty list.

                      cycleList xs h i returns xs[i % xs.length].

                      This is useful for in-memory datasets where a fixed-step “PyTorch-like” loop should avoid repeated Option handling.

                      Instances For
                        def TorchLean.Data.cycleListOrError {a : Type} (xs : List a) (err : String := "empty list") :
                        Except String (a)

                        Like cycleList, but fail with a message if the list is empty.

                        Fixed-step dataset code can check emptiness once and then index without Option.

                        Instances For
                          def TorchLean.Data.cycleDataset {a : Type} (ds : Dataset a) (h : ds.data.size 0) :
                          a

                          Build a cycling index function for a nonempty dataset.

                          cycleDataset ds h i returns ds[i % ds.size].

                          This is the dataset analogue of cycleList. It avoids per-step Option handling in fixed-step training loops.

                          Instances For
                            def TorchLean.Data.cycleDatasetOrError {a : Type} (ds : Dataset a) (err : String := "empty dataset") :
                            Except String (a)

                            Like cycleDataset, but fail with a message if the dataset is empty.

                            This is the preferred helper for “PyTorch-style” fixed-step loops over in-memory datasets.

                            Instances For
                              def TorchLean.Data.get? {a : Type} (ds : Dataset a) (i : ) :

                              Safe indexing into a dataset.

                              Instances For
                                def TorchLean.Data.firstArrayOrError {a : Type} (xs : Array a) (err : String := "empty array") :

                                Return the first array element, or a caller-provided error when the array is empty.

                                Instances For
                                  def TorchLean.Data.map {a b : Type} (f : ab) (ds : Dataset a) :

                                  Map a dataset elementwise (pure, deterministic).

                                  Instances For
                                    def TorchLean.Data.append {a : Type} (x y : Dataset a) :

                                    Append two datasets, preserving order: all samples from x followed by all samples from y.

                                    Instances For
                                      def TorchLean.Data.splitAt {a : Type} (n : ) (ds : Dataset a) :

                                      Split a dataset at position n (prefix, suffix).

                                      Instances For
                                        def TorchLean.Data.shuffle {a : Type} (seed : ) (ds : Dataset a) :

                                        Shuffle a dataset deterministically, returning the updated RNG seed and the shuffled dataset.

                                        This is used to implement DataLoader.shuffle behavior in a purely functional way.

                                        Instances For
                                          def TorchLean.Data.shuffled {a : Type} (seed : ) (ds : Dataset a) :

                                          Deterministically shuffle a dataset when the caller does not need the updated seed.

                                          Instances For
                                            def TorchLean.Data.randomSplitAt {a : Type} (seed n : ) (ds : Dataset a) :

                                            Shuffle once and then split at n.

                                            This is a small building block for train/val splits.

                                            Instances For
                                              def TorchLean.Data.batches {a : Type} (tag : String) (batchSize : ) (ds : Dataset a) :

                                              Split a dataset into equal-sized minibatches (as lists), dropping the final partial batch.

                                              This is a low-level helper; ordinary loader code should use DataLoader.epoch or Data.batchedSupervised.

                                              Instances For
                                                def TorchLean.Data.batchesArray {a : Type} (tag : String) (batchSize : ) (ds : Dataset a) :

                                                Like batches, but return each minibatch as an Array instead of a List.

                                                Instances For
                                                  @[reducible, inline]

                                                  Untyped analogue of PyTorch's torch.utils.data.DataLoader.

                                                  This is the deterministic, purely-functional loader provided by the TorchLean runtime.

                                                  Instances For
                                                    def TorchLean.Data.loader {a : Type} (ds : Dataset a) (batchSize : ) (shuffle : Bool := false) (seed : := 0) (dropLast : Bool := false) :

                                                    Construct a RawDataLoader from a dataset.

                                                    If shuffle := true, shuffling is deterministic w.r.t. seed. If dropLast := true, incomplete final batches are discarded.

                                                    Instances For

                                                      Run one epoch worth of minibatching and return:

                                                      • an updated loader (with the new seed), and
                                                      • the list of minibatches.
                                                      Instances For
                                                        def TorchLean.Data.epochCollate {a b : Type} (name : String) (dl : RawDataLoader a) (collate : List aExcept String b) :

                                                        Like epoch, but apply a user-provided collate function to each minibatch, matching the role of PyTorch's collate_fn= option.

                                                        Instances For
                                                          structure TorchLean.Data.BatchLoader (α : Type) (n : ) (σ τ : Spec.Shape) :

                                                          Typed wrapper around RawDataLoader for supervised samples.

                                                          The batch size n is reflected in the type, and BatchLoader.epoch returns fully-collated dim n minibatches (so dropLast=true is required).

                                                          Instances For
                                                            @[reducible, inline]

                                                            Existential wrapper for loaders when the batch size is chosen at runtime.

                                                            Instances For
                                                              def TorchLean.Data.availableNpyRows (path : System.FilePath) (tailShape : List ) (expectedDesc : String) :

                                                              Read the row count from an .npy file and check its trailing shape.

                                                              For a batched tensor with shape (N, d₁, ..., dₖ), this returns N when the trailing dimensions match tailShape.

                                                              Instances For

                                                                Convert a list of (x, y) float tensors into a dataset of TorchLean supervised samples.

                                                                This casts float data into the selected scalar backend α and packs it into a TensorPack α [σ, τ].

                                                                Instances For

                                                                  Convert a list of (x, label) pairs into a dataset of one-hot classification samples.

                                                                  Labels are given as Nat and converted to one-hot targets of shape Vec classes.

                                                                  Instances For