TorchLean API

NN.Runtime.PyTorch.Export.Core

Export Core #

PyTorch code generation helpers.

This module defines shared string-building utilities used by the PyTorch bridge and round-trip examples. It emits readable Python nn.Module code (optionally with weights embedded) and centralizes the common prelude used by the example MLP/CNN/Transformer exporters under NN.Examples.Interop.PyTorch.{MLP,CNN,Transformer}.Export.

Design note (PyTorch export APIs, for context only):

PyTorch also has graph capture / serialization mechanisms such as ONNX export and torch.export. Those APIs produce IR-like artifacts intended for execution in other runtimes. TorchLean's exporter in this folder emits auditable Python source for parity checks and round-trip tests.

Reading map:

References #

Metadata for a generated PyTorch model snippet.

Most exporters in NN/Runtime/PyTorch/Export/* produce a Python string as their final artifact. We keep a small structured record alongside that string so examples can report shapes/layer counts and decide whether weights were embedded.

  • modelName : String

    Human-friendly class/model name used in the emitted Python.

  • inputShape : Spec.Shape

    Expected input shape (TorchLean spec Shape).

  • outputShape : Spec.Shape

    Expected output shape (TorchLean spec Shape).

  • layerCount :

    Count of primitive layers/ops in the model (exporter-specific).

  • operationTypes : List String

    A list of operation tags used for summary reporting in examples.

  • hasWeights : Bool

    Whether the exporter embedded a state_dict literal in the emitted Python.

  • pytorchCode : String

    The emitted Python source (usually a full script or class definition).

Instances For

    Join a list of lines with newline separators.

    Instances For

      Render a Lean Bool as the corresponding Python literal.

      Instances For

        Indent a line by n spaces.

        Instances For

          Indent a line by 2 spaces (common for Python).

          Instances For

            Indent a line by 4 spaces (common for Python block bodies).

            Instances For

              Indent a line by 6 spaces (used in nested Python blocks).

              Instances For

                Indent a line by 8 spaces (used for nested nn.Sequential strings).

                Instances For

                  Common boilerplate fragments #

                  Many exporters emit the same small pieces of Python: @property metadata and a get_model_info dictionary. Shared boilerplate keeps the hand-written example exporters and the more general IR exporter.

                  Emit a standard get_model_info method used by most TorchLean PyTorch example modules.

                  extraFields are inserted after the "model_name" entry. Each element is (key, valueExpr) where valueExpr is emitted verbatim as Python code (e.g. "self.input_shape" or "self.hidden_dim"). This is meant as a formatting helper only; it does not validate Python syntax.

                  Instances For

                    Flatten a Shape into a list of dimension sizes (outermost-first).

                    Instances For

                      Render a Shape as a Python tuple literal.

                      Examples:

                      • .scalar becomes "()",
                      • a 1D shape becomes "(n,)" (note the trailing comma),
                      • higher-rank shapes become "(d0, d1, ...)".
                      Instances For

                        Count the number of primitive layers in a SpecChain.

                        Instances For

                          Convert a 1D float tensor into a Lean list (outermost dimension order).

                          Instances For

                            Render a 1D float tensor as a Python list literal (e.g. [1.0, 2.0]).

                            Instances For

                              Render a 2D float tensor as a Python nested-list literal.

                              Instances For

                                Render the transpose of a 2D float tensor as a Python nested-list literal.

                                TorchLean's matrix-valued specs often follow the mathematical convention where a feature matrix W has shape (in, out) and is applied as X * W. PyTorch stores nn.Linear weights as (out, in) and applies them as X @ W.T + b. This helper prints a TorchLean matrix in the transposed orientation expected by PyTorch.

                                Instances For

                                  Render a 4D float tensor as a Python nested-list literal.

                                  Instances For

                                    Best-effort conversion of a float tensor to a Python list literal.

                                    This is a simple recursive printer used for examples and small regression tests; it is not intended to be fast.

                                    Instances For

                                      Standard imports used by the generated Python snippets.

                                      Instances For

                                        Small helper modules used by some toPyTorch strings in the Lean specs.

                                        These are small, dependency-free Python utilities (selectors, wrappers, a compact attention helper) used so the generated model classes stay short and readable.

                                        Instances For

                                          Generate a generic base nn.Module class skeleton.

                                          This is used by exporters that want a "real" class with an explicit _initialize_layers hook, instead of the simpler nn.Sequential emitter.

                                          Instances For

                                            Emit Python helpers for saving/loading state dictionaries and JSON checkpoints.

                                            Instances For

                                              Emit Python helpers for validating exported models.

                                              Instances For
                                                def Export.PyTorch.generatePyTorchModule {α : Type} {s t : Spec.Shape} (chain : ModSpec.SpecChain α s t) (className : String := "ExportedModel") :

                                                Generate a complete nn.Sequential-based Python module for a SpecChain.

                                                This is the simplest exporter: we extract a list of (opName, pythonLayerString) pairs and drop them into an nn.Sequential(...) in a new class.

                                                Instances For

                                                  Like generateBasePyTorchModule, but also include shared weight/testing helpers.

                                                  Instances For
                                                    def Export.PyTorch.exportGeneralModel {α : Type} {s t : Spec.Shape} (chain : ModSpec.SpecChain α s t) (className : String := "GeneralModel") :

                                                    Export a SpecChain to PyTorch and bundle the result in a metadata record.

                                                    This is the "one call" entrypoint used by some examples.

                                                    Instances For