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.v2",
  "input_ids": [0],
  "output_ids": [1],
  "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 tensor or container value from a graph artifact.

        • 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 kind.

        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

                        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

                            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.

                                              A node without value_kind is tensor-valued and has a required shape field. The explicit form uses value_kind = "tensor" or value_kind = "tuple" explicitly.

                                              Instances For

                                                Parse a pointwise operator from its kind and attribute field.

                                                A GELU must state its approximate string. A division without a rounding_mode field, or with a JSON null, is true division, as in PyTorch.

                                                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.parseTag?, which recognizes the fixed 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

                                                      Read the ordered tensor interface: input_ids lists every runtime input in argument order.

                                                      Instances For

                                                        Parse the value-level graph, retaining the first argument for single-input consumers.

                                                        Instances For

                                                          Look up a raw value node by id.

                                                          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

                                                                Validate a lowered graph and its designated interface, preserving check order.

                                                                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

                                                                      Successfully parsed graphs satisfy the IR shape checks.