IRPyTorch #
IR → PyTorch code generation.
This module takes an op-tagged NN.IR.Graph plus a NN.MLTheory.CROWN.Graph.ParamStore payload and
emits a standalone PyTorch nn.Module implementation as a Python source string.
What this is (and isn't):
- This is an extraction/convenience layer used in round-trip examples: run/train in Python, then optionally import weights back to Lean.
- This is not a formal proof of semantic equivalence between PyTorch execution and the Lean IR
denotation. The reference semantics remain the Lean definitions (
NN.IR.Graph.denote*).
Assumptions:
- Node ids index
g.nodesconsistently;nodechecks that invariant. - The ParamStore contains parameters for the node kinds that require them (linear/convolution/etc.).
- Only a supported subset of IR node kinds is lowered.
Failure modes (reported as Except String):
- missing/malformed ParamStore entries,
- shape mismatches between graph nodes and parameters,
- unsupported node kinds.
PyTorch context (comments only):
PyTorch’s ONNX exporter and torch.export can capture graphs for execution in other runtimes.
TorchLean’s emitter here prints readable Python that mirrors the IR, rather than producing an
execution-focused serialized graph artifact.
Flatten a tensor and render it as a Python list literal (used for
torch.tensor([...]).reshape(...)).
Instances For
Return true iff every array entry equals the first one, vacuously for an empty array.
Instances For
Options controlling IR-to-PyTorch emission.
Most knobs here configure example emission, dtype handling, and how to materialize constant nodes as buffers or parameters.
- className : String
Class name to use in the emitted Python source.
- dtypeExpr : String
Python expression used for the tensor dtype (e.g.
"torch.float32"). - includeTrainingSkeleton : Bool
If true, include a small training skeleton and runtime-check in the emitted script.
- learnableConsts : Bool
If true, emit IR
constnodes asnn.Parameterwhen appropriate (learnable).
Instances For
Map from IR constant node id to its Python attribute name, for both buffers and parameters.
Instances For
Emit a torch.tensor([...]).reshape(...) expression from a flat Python list literal and a
Shape.
Instances For
Retrieve a node from the graph and validate its id invariant.
This yields more actionable error messages than directly indexing into g.nodes.
Instances For
Emit a standalone PyTorch nn.Module class for an IR graph.
This is the main entrypoint for IR exporters: it bundles:
- imports,
- a class definition with parameters/buffers materialized from the
ParamStore, - a
forwardmethod implementing the IR, and - (optionally) a compact training file for export checks.