TorchLean API

NN.Runtime.PyTorch.Import.TorchExport

torch.export / FX Graph JSON Import #

This module is the Lean half of the PyTorch-module import pipeline.

PyTorch has two different artifacts that people often blur together:

The runtime bridge therefore uses a small, explicit JSON format:

{
  "format": "torchlean.ir.v1",
  "input_id": 0,
  "output_ids": [4],
  "nodes": [
    {"id": 0, "kind": "input", "parents": [], "shape": [1, 4]},
    {"id": 1, "kind": "relu", "parents": [0], "shape": [1, 4]}
  ]
}

The parser below is deliberately conservative. It accepts only the current NN.IR.OpKind subset and then runs TorchLean's executable graph validators (checkWellFormed and checkShapes). That gives downstream tools a useful guarantee: if parseGraph succeeds, the resulting graph is structurally acyclic, id-disciplined, arity-correct, and shape-consistent according to the shared IR inference rules.

Op kind strings are not spelled here. They come from the shared table in NN.Runtime.PyTorch.Wire, which the Python-emitting exporters also use. The tag round trip is proved there.

The matching Python-side emitter lives in NN.Runtime.PyTorch.Export.TorchExport.

Node ids whose payloads are synthesized while lowering one raw single-head MHA tuple node.

Keeping this binding explicit prevents payload parsing from depending on incidental node-number offsets or reverse-engineering the generated subgraph.

  • rawId :

    Raw value-graph node that owns the serialized MHA parameters.

  • queryId :

    Generated query projection node.

  • keyId :

    Generated key projection node.

  • valueId :

    Generated value projection node.

  • scaleId :

    Generated attention-score scale constant node.

  • outputId :

    Generated output projection node.

Instances For

    A captured PyTorch graph lowered into TorchLean IR plus its designated interface node ids.

    • graph : NN.IR.Graph

      TorchLean's checked op-tagged graph.

    • inputId :

      Designated runtime input node id.

    • outputIds : Array

      Designated graph output node ids, in PyTorch return order.

    • rawToTensor : Array (Option )

      Map from serialized FX value ids to lowered tensor IR ids.

    • mhaPayloadBindings : Array MhaPayloadBinding

      Payload ownership for subgraphs synthesized from raw MHA tuple nodes.

    Instances For

      Shape metadata for a PyTorch/FX value before it has been lowered to TorchLean's tensor-only IR.

      PyTorch FX nodes may produce non-tensor containers. The most common example is nn.MultiheadAttention, whose forward result is (attn_output, attn_weights). We keep this container structure in the import layer instead of treating every FX node as a tensor node. Only tensor-valued nodes can be lowered into NN.IR.Graph.

      Instances For

        One raw PyTorch/FX value node from torchlean.ir.v1 JSON.

        • id :

          Raw FX node id from the JSON artifact.

        • parents : Array

          Raw parent ids. These may refer to tensor values or tuple/container values.

        • kind : String

          Stable TorchLean/PyTorch import tag, e.g. relu, matmul, or tuple_getitem.

        • valueShape : ValueShape

          Tensor or tuple shape metadata.

        • raw : StateDict

          Original object, retained so tensor nodes can be parsed through parseOpKind.

        Instances For

          Captured PyTorch graph before tuple/container values are lowered away.

          Instances For

            Small JSON helpers #

            A uniform "wrong JSON shape" error, so import failures all read the same way.

            Instances For

              Interpret a JSON number as a natural number.

              Instances For

                Decode a JSON value as a string, reporting the importing context on mismatch.

                Instances For

                  Decode a JSON value as an array, reporting the importing context on mismatch.

                  Instances For

                    Decode a JSON value as an object/state dictionary.

                    Instances For

                      Read a required object field.

                      Instances For

                        Read an optional object field.

                        Instances For

                          Parse a JSON array of natural numbers.

                          Instances For

                            Parse a shape encoded as a dimension list.

                            Examples:

                            • [] means scalar;
                            • [4] means Shape.dim 4 Shape.scalar;
                            • [2, 3] means Shape.dim 2 (Shape.dim 3 Shape.scalar).
                            Instances For

                              Parse a node's parent ids.

                              Instances For

                                Read a natural-number field from a parsed Torch export JSON object.

                                Instances For

                                  Read a Boolean field from a parsed Torch export JSON object.

                                  Instances For

                                    Read a shape-valued field from a parsed Torch export JSON object.

                                    Instances For

                                      Read a natural-number array field from a parsed Torch export JSON object.

                                      Instances For

                                        Read a floating-point field used by numerical operator payloads.

                                        Instances For

                                          Read a shape-indexed floating-point tensor field.

                                          Instances For

                                            Read fixed-length tensor metadata, rejecting inconsistent serialized geometry.

                                            Instances For

                                              Parse generic pooling window metadata.

                                              Instances For

                                                Parse a JSON array whose elements are shape arrays.

                                                Instances For

                                                  Parse the value-level shape metadata emitted by the Python bridge.

                                                  torchlean.ir.v1 artifacts without value_kind are interpreted as tensor-valued nodes with a required shape field. The explicit form uses value_kind = "tensor" or value_kind = "tuple" explicitly.

                                                  Instances For

                                                    Parse a TorchLean IR op kind.

                                                    The schema uses a stable string tag plus op-specific scalar fields. The tag is resolved through Wire.parseOpTag?, which recognizes the fixed v1 spellings. This function then reads the attributes each constructor needs. We avoid trying to parse raw PyTorch operator names here; the Python adapter is responsible for translating torch.ops.aten.* / FX targets into these TorchLean tags.

                                                    Instances For

                                                      Parse one raw PyTorch/FX value node.

                                                      Instances For

                                                        Parse the graph object into the PyTorch/FX value-level graph, before tensor lowering.

                                                        Instances For

                                                          Validate the value graph before raw ids are used as array indices during tensor lowering.

                                                          The tensor IR checker performs the corresponding validation after lowering. This earlier check is still necessary because tuple/container nodes do not enter the tensor IR, and because rawToTensor is indexed by raw node id while lowering is in progress.

                                                          Instances For

                                                            Lower a PyTorch/FX value graph to TorchLean's tensor-only IR.

                                                            Tuple/container nodes are preserved in CapturedValueGraph, but they do not become NN.IR.Nodes. TorchLean's verification and execution passes consume the clean tensor DAG, while the import layer can explain container-valued PyTorch failures without changing their semantics.

                                                            Instances For

                                                              Parse the graph object and lower PyTorch/FX values to the tensor IR.

                                                              Instances For

                                                                Parse and validate a captured PyTorch graph.

                                                                Success means:

                                                                • the JSON uses the TorchLean graph-artifact schema,
                                                                • every op is in the supported TorchLean IR subset,
                                                                • node ids are disciplined and topologically ordered,
                                                                • arities are valid, and
                                                                • declared output shapes match NN.IR.Infer.
                                                                Instances For

                                                                  Parse serialized parameters into the node-keyed Float payload.

                                                                  Instances For

                                                                    Guarantee exposed by the parser: a successfully parsed graph is well-shaped.

                                                                    This theorem is compact but important. It is the theorem downstream verification/export code can quote when it receives a graph artifact through this importer.