Repository navigation
fix(export): translate batched vector and wider-batch matmuls to PyTorch - #41
Merged
Robertboy18 merged 2 commits intoNov 22, 2026
Merged
Conversation
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.
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
The PyTorch exporter writes every
matmulandscaledMatmulnode as a plaintorch.matmul(a, b).torch.matmuldecides 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.matmulstates both throughlv,rvandbatch. Where they disagree the exported module computes something else, or fails:Graph.evalmain[2]× right matrix with batch[2](lv)[2, 2][2, 2, 2], different values[2](rv, also inscaledMatmul)[2, 2]RuntimeErrorfromtorch.matmulbatch = [2]wider than both operands'[][2, 3, 3][3, 3]These graphs don't come out of the PyTorch, JAX or ONNX importers or
NN/Builder.lean. Those produce matmuls intorch.matmul's own form:lvorrvonly at rank one, andbatchthe operands' broadcast (_artifact._matmul,IR.inferMatmulDims). They are graphs built withIR.Graph.Builderor read from IR JSON. The operator table andGraph.evalaccept them, andemittranslates 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.matmulalready computes the operator, it still emits the plain call, and that Python text is byte-identical tomain. Elsewhere it adds only what is needed. One function inTorchLean/NN/PyTorch/Export/IR.lean, used by both rows.How
matmulExprcomputes PyTorch's broadcast batch frombatchAandbatchB. Each extent of either prefix is one orbatch's, so the common shape is the extent other than one at each padded axis. If that equalsbatchand neither operand is misread, it emitstorch.matmul(a, b).unsqueeze(-2)) or one-column (unsqueeze(-1)) matrix. The product isexpanded tobatch ++ [m, p]whenbatchis wider, andreshaped toShape.matmulOutto drop the inserted axes. The product is computed once.expandand the reshape that drops size-one axes are views of it, so the wider batch allocates nothing.torch.matmulthen reads the leading axes as rows, which gives the same result.scaledMatmuluses the same expression, then the scale, as before. Theorder := .leftFoldrestriction onmainis kept on both rows.Testing
TorchLeanTest/Interop/IRPyTorch.leangains three graphs: a batched left vector, a batched right vector (in ascaledMatmul) and a wider batch. They run the exported module in torch at binary64 and binary32 and compare bit for bit withGraph.eval. Onmainthey fail as in the table. With the change,irpytorch_parity: ok.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 againstGraph.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 intorch.matmulor in broadcasting.112/112 cases match Graph.eval and the loop reference (forward and gradient).TORCHLEAN_REQUIRE_INTEROP=1 TORCHLEAN_REQUIRE_JAX=1, so no interop case could skip.scripts/lake.sh build: OKscripts/lake.sh build TorchLeanExamples TorchLeanTest: OKscripts/lake.sh test:all curated tests passed. Details:Ran 261 tests ... OK, none skipped.40 accepted and matched, 0 failed; PyTorch20 accepted and matched, 20 refused, 0 failed.ONNX round trip: 24 artifacts ok.irpytorch_parity: ok.scripts/lake.sh lint: OK, every theorem onpropext,Classical.choiceandQuot.soundonly.-Kcuda=true). This machine has no NVIDIA GPU. The exporter is not part of the LibTorch backend.test_a_map_that_draws_is_unrolledfails insidetorch.export(UncapturedHigherOrderOpError). It passes on torch 2.13.LLVM ERROR: Cannot select ... v8bf16 = X86ISD::VBROADCAST). JAX 0.11.1 runs.Sweep:
MatmulSweep.lean(run from the repository root)Sweep:
matmul_sweep_check.pyTo 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.pyThe
.soname is the Linux one.