Export Core #
PyTorch code generation helpers.
This module defines shared string-building utilities used by the PyTorch bridge and round-trip
demos. 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 instead emits plain Python source primarily for readability and for round-trip tests.
Reading map:
generatePyTorchImports/generatePyTorchHelperModulesprovide the shared Python prelude.generateBasePyTorchModuleis the reusable class skeleton for the example exporters.generatePyTorchModuleis the simplest end-to-end exporter for aSpecChain.generateCompletePyTorchExportcombines the codegen pieces into a single script.NN.Runtime.PyTorch.Export.StateDictis the general checkpoint-to-JSON adapter for users who already have PyTorch weights.
References #
- PyTorch ONNX export: https://pytorch.org/docs/stable/onnx.html
- PyTorch
torch.export: https://pytorch.org/docs/stable/export.html
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 demos 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).
A list of operation tags used for lightweight reporting in demos.
- hasWeights : Bool
Whether the exporter embedded a
state_dictliteral 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
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 demo exporters
and the more general IR exporter.
Emit a standard get_model_info method used by most TorchLean PyTorch demo 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:
.scalarbecomes"()",- 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 demos 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 lightweight checkpoints.
Instances For
Emit lightweight Python helpers for validating exported models.
Instances For
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
Export a SpecChain to PyTorch and bundle the result in a metadata record.
This is the "one call" entrypoint used by some demos.