Skip to content

fix(export): translate batched vector and wider-batch matmuls to PyTorch - #41

Merged
Robertboy18 merged 2 commits into
lean-dojo:mainfrom
build4me2:fix/export-batched-vector-matmul
Nov 22, 2026
Merged

Robertboy18 merged 2 commits into
lean-dojo:mainfrom
build4me2:fix/export-batched-vector-matmul

Conversation

@build4me2

@build4me2 build4me2 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Why

The PyTorch exporter writes every matmul and scaledMatmul node as a plain torch.matmul(a, b). torch.matmul decides from the ranks alone: an operand is a vector only at rank one, and the batch is the smallest shape both prefixes broadcast to. Op.matmul states both through lv, rv and batch. Where they disagree the exported module computes something else, or fails:

Graph Graph.eval Exported module on main
left vector with batch [2] × right matrix with batch [2] (lv) shape [2, 2] shape [2, 2, 2], different values
right vector with batch [2] (rv, also in scaledMatmul) shape [2, 2] RuntimeError from torch.matmul
batch = [2] wider than both operands' [] shape [2, 3, 3] shape [3, 3]

These graphs don't come out of the PyTorch, JAX or ONNX importers or NN/Builder.lean. Those produce matmuls in torch.matmul's own form: lv or rv only at rank one, and batch the operands' broadcast (_artifact._matmul, IR.inferMatmulDims). They are graphs built with IR.Graph.Builder or read from IR JSON. The operator table and Graph.eval accept them, and emit translates them without complaint, so the result is a silently wrong module.

What

The exporter now builds the call from the operator's attributes. Where torch.matmul already computes the operator, it still emits the plain call, and that Python text is byte-identical to main. Elsewhere it adds only what is needed. One function in TorchLean/NN/PyTorch/Export/IR.lean, used by both rows.

How

  • matmulExpr computes PyTorch's broadcast batch from batchA and batchB. Each extent of either prefix is one or batch's, so the common shape is the extent other than one at each padded axis. If that equals batch and neither operand is misread, it emits torch.matmul(a, b).
  • Otherwise a vector operand becomes a one-row (unsqueeze(-2)) or one-column (unsqueeze(-1)) matrix. The product is expanded to batch ++ [m, p] when batch is wider, and reshaped to Shape.matmulOut to drop the inserted axes. The product is computed once. expand and the reshape that drops size-one axes are views of it, so the wider batch allocates nothing.
  • A left vector with batch axes against a right operand without them is left as the plain call. torch.matmul then reads the leading axes as rows, which gives the same result.
  • scaledMatmul uses the same expression, then the scale, as before. The order := .leftFold restriction on main is kept on both rows.

Testing

  • TorchLeanTest/Interop/IRPyTorch.lean gains three graphs: a batched left vector, a batched right vector (in a scaledMatmul) and a wider batch. They run the exported module in torch at binary64 and binary32 and compare bit for bit with Graph.eval. On main they fail as in the table. With the change, irpytorch_parity: ok.
  • The sweep below covers plain and scaled × lv × rv × 14 batch configurations, 112 cases. The batches include empty, size-0 and size-1 extents and rank-2 broadcasts. Each case checks shape and values against Graph.eval, and forward and gradient against a loop reference written from the attributes. The values are small integers, so every comparison is exact.
    • main: 40/112 cases match. 38 have the wrong shape, and the rest raise in torch.matmul or in broadcasting.
    • This branch: 112/112 cases match Graph.eval and the loop reference (forward and gradient).
  • Full check, rebased on 6e4b633. Software: torch 2.13.0, JAX 0.11.1 (jaxlib 0.11.1), ONNX 1.23.2, numpy 2.5.5, Python 3.13. The tests ran with TORCHLEAN_REQUIRE_INTEROP=1 TORCHLEAN_REQUIRE_JAX=1, so no interop case could skip.
    • scripts/lake.sh build: OK
    • scripts/lake.sh build TorchLeanExamples TorchLeanTest: OK
    • scripts/lake.sh test: all curated tests passed. Details:
      • PyTorch and JAX captures: Ran 261 tests ... OK, none skipped.
      • Differential fuzzer: JAX 40 accepted and matched, 0 failed; PyTorch 20 accepted and matched, 20 refused, 0 failed.
      • ONNX round trip: 24 artifacts ok.
      • irpytorch_parity: ok.
    • scripts/lake.sh lint: OK, every theorem on propext, Classical.choice and Quot.sound only.
  • Not run: the CUDA kernels (-Kcuda=true). This machine has no NVIDIA GPU. The exporter is not part of the LibTorch backend.
  • Unrelated to this change, seen while setting up:
    • With torch 2.15.0 on Python 3.14, test_a_map_that_draws_is_unrolled fails inside torch.export (UncapturedHigherOrderOpError). It passes on torch 2.13.
    • With JAX 0.12.1 on an Intel Panther Lake CPU, XLA's CPU backend aborts on a bfloat16 kernel (LLVM ERROR: Cannot select ... v8bf16 = X86ISD::VBROADCAST). JAX 0.11.1 runs.
Sweep: MatmulSweep.lean (run from the repository root)
import TorchLeanTest.Interop.IRPyTorch
open TorchLean

/-- One `matmul` (or `scaledMatmul` by 0.5) of input 0 by a constant, exported and evaluated. -/
def sweepCase (k : Nat) (scaled lv rv : Bool) (bA bB batch : Shape) :
    Except String (Option (String × String)) := do
  let m := if lv then 1 else 2
  let n := 3
  let p := if rv then 1 else 2
  if hl : lv = true → m = 1 then
  if hr : rv = true → p = 1 then
  if ha : Shape.CanBroadcastTo bA batch then
  if hb : Shape.CanBroadcastTo bB batch then
    let sa := Shape.matmulLeft lv bA m n
    let sb := Shape.matmulRight rv bB n p
    let b : IR.Graph.Builder := {}
    let (b, x) := b.input 0 (.value sa)
    let bv : Op.Value Float := ⟨.value sb, Tensor.generateFlat sb fun i => (i * 7 % 11).toFloat - 5⟩
    let (b, P, c) := b.constant ({} : IR.Payload Float) bv
    let (b, y) ←
      if scaled then
        let sv : Op.Value Float := ⟨.frozen [], Tensor.generateFlat [] fun _ => 0.5⟩
        let (b, P', s) := b.constant P sv
        let (b, y) := b.op (Op.scaledMatmul (batchA := bA) (batchB := bB) (batch := batch) (m := m)
          (n := n) (p := p) lv rv hl hr ha hb) [x, c, s]
        pure ((b, P'), y)
      else
        let (b, y) := b.op (Op.matmul (batchA := bA) (batchB := bB) (batch := batch) (m := m)
          (n := n) (p := p) lv rv hl hr ha hb) [x, c]
        pure ((b, P), y)
    let (b, P) := b
    let g ← b.build #[y.headD x]
    let name := s!"Sweep{k}"
    let opts : PyTorch.Options := { className := name, dtypeExpr := "torch.float64" }
    let opts := { opts with includeTrainingSkeleton := false, learnableConsts := false }
    let src ← PyTorch.emit ⟨g, P, #[]⟩ opts
    let xs : Array Float := (List.range sa.size).toArray.map fun i => (i * 5 % 13).toFloat - 6
    let want ← match ← g.eval P [⟨.value sa, Tensor.generateFlat sa fun i => xs[i]!⟩] with
      | [⟨⟨.value, _⟩, t⟩] => pure (Tensor.to t (Array Float))
      | _ => throw "not one value output"
    let bvals : Array Float := (List.range sb.size).toArray.map fun i => (i * 7 % 11).toFloat - 5
    let lst (s : Shape) : List Nat := s
    let py (b : Bool) : String := if b then "True" else "False"
    let fields : List String := [s!"'{name}'", py scaled, py lv, py rv, toString (lst bA),
      toString (lst bB), toString (lst batch), toString m, toString n, toString p,
      toString xs.toList, toString bvals.toList, toString want.toList]
    pure (some (src, "(" ++ ", ".intercalate fields ++ ")"))
  else pure none else pure none else pure none else pure none

def batches : List (Shape × Shape × Shape) :=
  [([], [], []), ([2], [], [2]), ([], [2], [2]), ([2], [2], [2]), ([1], [3], [3]),
   ([3], [1], [3]), ([], [], [2]), ([1], [1], [2, 3]), ([2], [1, 2], [4, 2]), ([0], [1], [0]),
   ([2, 1], [3], [2, 3]), ([1], [], [1]), ([], [1], [4]), ([2, 3], [2, 3], [2, 3])]

def main : IO Unit := do
  let mut mods := ""
  let mut runs := #[]
  let mut k := 0
  for scaled in [false, true] do
    for lv in [false, true] do
      for rv in [false, true] do
        for (bA, bB, batch) in batches do
          match sweepCase k scaled lv rv bA bB batch with
          | .ok (some (src, run)) => mods := mods ++ src ++ "\n\n"; runs := runs.push run
          | .ok none => throw (IO.userError s!"bad config {k}")
          | .error e => throw (IO.userError s!"case {k}: {e}")
          k := k + 1
  IO.println (mods ++ s!"RUNS = [{", ".intercalate runs.toList}]")
Sweep: matmul_sweep_check.py
"""Check the exported matmul sweep against Graph.eval and a loop reference.

Usage: python matmul_sweep_check.py sweep_mods.py

sweep_mods.py is the output of MatmulSweep.lean: one exported module per case and RUNS, the
rows (name, scaled, lv, rv, batchA, batchB, batch, m, n, p, x, b, Graph.eval's output).
Every value is a small integer or half of one, so each sum is exact in binary64 and the checks
compare exactly.
"""

import itertools
import sys

import torch


def entry(t, prefix, batch_index, tail):
    """t at batch_index (broadcast right-aligned into prefix) followed by tail."""
    lead = len(batch_index) - len(prefix)
    idx = [0 if e == 1 else batch_index[lead + j] for j, e in enumerate(prefix)]
    return t[tuple(idx + tail)]


def reference(x, b, scaled, lv, rv, bA, bB, batch, m, n, p):
    """Op.matmul from its attributes: lv / rv operands are vectors, batches broadcast to batch."""
    rows = []
    for bi in itertools.product(*[range(e) for e in batch]):
        bi = list(bi)
        out = []
        for i in range(m):
            row = []
            for j in range(p):
                acc = torch.zeros((), dtype=torch.float64)
                for k in range(n):
                    av = entry(x, bA, bi, [k] if lv else [i, k])
                    bv = entry(b, bB, bi, [k] if rv else [k, j])
                    acc = acc + av * bv
                row.append(acc * 0.5 if scaled else acc)
            out.append(row)
        rows.append(out)
    # An empty batch has no entries; tie the empty result to x so its gradient (zero) exists.
    full = torch.stack([torch.stack([torch.stack(r) for r in o]) for o in rows]) if rows else \
        torch.zeros([0, m, p], dtype=torch.float64) + x.sum() * 0
    full = full.reshape(list(batch) + [m, p])
    if lv:
        full = full.squeeze(-2) if not rv else full.squeeze(-1).squeeze(-1)
    elif rv:
        full = full.squeeze(-1)
    return full


def main(path):
    scope = {}
    with open(path) as f:
        exec(f.read(), scope)
    failures = 0
    for (name, scaled, lv, rv, bA, bB, batch, m, n, p, xs, bs, want) in scope["RUNS"]:
        sa = bA + ([n] if lv else [m, n])
        sb = bB + ([n] if rv else [n, p])
        out_shape = list(batch) + ([] if lv else [m]) + ([] if rv else [p])
        problems = []
        try:
            model = scope[name]()
            x = torch.tensor(xs, dtype=torch.float64).reshape(sa).requires_grad_(True)
            y = model(x)
            if list(y.shape) != out_shape:
                problems.append(f"shape {list(y.shape)}, want {out_shape}")
            elif y.flatten().tolist() != want:
                problems.append("values differ from Graph.eval")
            else:
                b = torch.tensor(bs, dtype=torch.float64).reshape(sb)
                xr = x.detach().clone().requires_grad_(True)
                yr = reference(xr, b, scaled, lv, rv, bA, bB, batch, m, n, p)
                w = torch.arange(y.numel(), dtype=torch.float64).reshape(y.shape) - 3
                (gx,) = torch.autograd.grad((y * w).sum(), x, allow_unused=True)
                (gr,) = torch.autograd.grad((yr * w).sum(), xr, allow_unused=True)
                gx = torch.zeros_like(x) if gx is None else gx
                gr = torch.zeros_like(x) if gr is None else gr
                if not torch.equal(yr.detach(), y.detach()):
                    problems.append("forward differs from the loop reference")
                if not torch.equal(gx, gr):
                    problems.append("gradient differs from the loop reference")
        except Exception as e:  # a crash is a failed case, reported with its message
            problems.append(f"{type(e).__name__}: {str(e).splitlines()[0]}")
        if problems:
            failures += 1
            print(f"FAIL {name} scaled={scaled} lv={lv} rv={rv} batchA={bA} batchB={bB} "
                  f"batch={batch}: {'; '.join(problems)}")
    total = len(scope["RUNS"])
    print(f"{total - failures}/{total} cases match Graph.eval and the loop reference "
          "(forward and gradient)")
    return 1 if failures else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1]))

To run it, use a CPU build and a Python with torch:

scripts/lake.sh build TorchLeanTest
scripts/lake.sh env lean --load-dynlib=.lake/build/lib/libtorchlean_tensor_cpu.so \
  --run MatmulSweep.lean > sweep_mods.py
python matmul_sweep_check.py sweep_mods.py

The .so name is the Linux one.

The PyTorch exporter wrote every matmul and scaledMatmul node as a
plain torch.matmul call. torch.matmul reads an operand as a vector only
at rank one and broadcasts the batch prefixes to their smallest common
shape, while Op.matmul states both through its lv, rv and batch
attributes. Where the two disagree the exported module computes
something else: a left vector with batch axes against a batched right
operand gives an extra axis and wrong values, a right vector with batch
axes raises a shape error, and a batch wider than both operands' is
dropped.

The exporter now builds the call from the attributes. A vector operand
that torch.matmul would misread becomes a one-row or one-column matrix,
the product is expanded to the declared batch when that is wider, and
the inserted axes are reshaped away. Every graph that was translated
correctly before emits the same Python text as before.

The PyTorch parity test gains three graphs covering the batched left
vector, the batched right vector (in a scaled product) and the wider
batch.
Shape is List Nat, so the re-bindings and the cast added nothing. The
note on left vectors that need no view moves from the docstring to the
condition it explains.
@Robertboy18
Robertboy18 merged commit f9dff85 into lean-dojo:main Nov 22, 2026
2 checks passed
@Robertboy18

Copy link
Copy Markdown
Member

Thanks for the careful report and fix! The silent mismatch for batched vectors and wider output batches was a real exporter bug. I ran the irpytorch_parity case locally with PyTorch 2.11; it passed with your change. The shared translation for matmul and scaledMatmul, together with the focused regression cases, makes this a clean fix. Squash-merged as f9dff85. I appreciate the detailed sweep and the clear explanation of where imported graphs differ from hand-built IR.

@build4me2
build4me2 deleted the fix/export-batched-vector-matmul branch November 23, 2026 19:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants