[GlobalOpt] Fold broadcasts into batch_matmul indexing maps (#25114) Replace ConvertBatchMatmulToMatmul, which rewrote `batch_matmul(A, broadcast(B))` into collapse_shape + matmul + expand_shape, with a pass that folds the broadcast into the batch_matmul's indexing maps: the RHS map simply drops the batch dim. The collapse_shape sat between a dequantize and its contraction and kept ConvertQDQToIntegerMath from matching; now the contraction reads its producers directly. CollapseDimensions turns the two-M-dim batch_matmul into a plain matmul during dispatch creation, so codegen and data tiling see the same op as before. The global optimization data tiling path sets encodings before dispatch creation, so it now runs the standalone contraction collapse first. Broadcasts on either input fold, as linalg.broadcast or as a broadcasting (and possibly transposing) generic, by composing maps, which also covers a transposed LHS. Where the named op cannot express the folded map, as for a batch-broadcast [N, K] weight that upstream's verifier rejects, the contraction is carried by a linalg.generic with the same body instead of moving data. --------- Signed-off-by: Florian Walbroel <walbroel@roofline.ai> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
diff --git a/compiler/src/iree/compiler/GlobalOptimization/BUILD.bazel b/compiler/src/iree/compiler/GlobalOptimization/BUILD.bazel index 2d6c95f..0b47848 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/BUILD.bazel +++ b/compiler/src/iree/compiler/GlobalOptimization/BUILD.bazel
@@ -78,7 +78,6 @@ name = "GlobalOptimization", srcs = [ "CleanupNumericNarrowing.cpp", - "ConvertBatchMatmulToMatmul.cpp", "ConvertConvToIm2Col.cpp", "ConvertQDQToIntegerMath.cpp", "ConvertStridedContractionToContraction.cpp", @@ -88,6 +87,7 @@ "DetachElementwiseFromNamedOps.cpp", "EraseUnusedLinalgOperands.cpp", "ExpandTensorShapes.cpp", + "FoldBroadcastIntoBatchMatmul.cpp", "FuseDequantizationMatmul.cpp", "GeneralizeLinalgNamedOps.cpp", "GlobalLoopInvariantCodeMotion.cpp",
diff --git a/compiler/src/iree/compiler/GlobalOptimization/CMakeLists.txt b/compiler/src/iree/compiler/GlobalOptimization/CMakeLists.txt index 3c9ca44..90354cb 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/CMakeLists.txt +++ b/compiler/src/iree/compiler/GlobalOptimization/CMakeLists.txt
@@ -72,7 +72,6 @@ "Utils.h" SRCS "CleanupNumericNarrowing.cpp" - "ConvertBatchMatmulToMatmul.cpp" "ConvertConvToIm2Col.cpp" "ConvertQDQToIntegerMath.cpp" "ConvertStridedContractionToContraction.cpp" @@ -82,6 +81,7 @@ "DetachElementwiseFromNamedOps.cpp" "EraseUnusedLinalgOperands.cpp" "ExpandTensorShapes.cpp" + "FoldBroadcastIntoBatchMatmul.cpp" "FuseDequantizationMatmul.cpp" "GeneralizeLinalgNamedOps.cpp" "GlobalLoopInvariantCodeMotion.cpp"
diff --git a/compiler/src/iree/compiler/GlobalOptimization/ConvertBatchMatmulToMatmul.cpp b/compiler/src/iree/compiler/GlobalOptimization/ConvertBatchMatmulToMatmul.cpp deleted file mode 100644 index 648edf1..0000000 --- a/compiler/src/iree/compiler/GlobalOptimization/ConvertBatchMatmulToMatmul.cpp +++ /dev/null
@@ -1,247 +0,0 @@ -// Copyright 2026 The IREE Authors -// -// Licensed under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - -#include "iree/compiler/GlobalOptimization/Passes.h" -#include "mlir/Dialect/Arith/IR/Arith.h" -#include "mlir/Dialect/Linalg/IR/Linalg.h" -#include "mlir/Dialect/Tensor/IR/Tensor.h" -#include "mlir/IR/AffineExpr.h" -#include "mlir/IR/AffineMap.h" -#include "mlir/IR/PatternMatch.h" -#include "mlir/Transforms/GreedyPatternRewriteDriver.h" - -namespace mlir::iree_compiler::GlobalOptimization { - -#define GEN_PASS_DEF_CONVERTBATCHMATMULTOMATMULPASS -#include "iree/compiler/GlobalOptimization/Passes.h.inc" - -namespace { - -/// If `op` broadcasts a weight along the batch dimension (dim 0) only, returns -/// the original pre-broadcast weight; otherwise returns failure. Handles both -/// linalg.broadcast and its generic form (after generalization). -static FailureOr<Value> getOriginalBroadcastWeight(Operation *op) { - if (auto broadcastOp = dyn_cast<linalg::BroadcastOp>(op)) { - ArrayRef<int64_t> dims = broadcastOp.getDimensions(); - if (dims.size() != 1 || dims[0] != 0) { - return failure(); - } - return broadcastOp.getInput(); - } - - auto genericOp = dyn_cast<linalg::GenericOp>(op); - if (!genericOp) { - return failure(); - } - - // Check generic is a broadcast: 1 input, 1 output, all parallel iterators - if (genericOp.getNumDpsInputs() != 1 || genericOp.getNumDpsInits() != 1) { - return failure(); - } - - auto iterTypes = genericOp.getIteratorTypesArray(); - if (!llvm::all_of(iterTypes, [](utils::IteratorType t) { - return t == utils::IteratorType::parallel; - })) { - return failure(); - } - - SmallVector<AffineMap> maps = genericOp.getIndexingMapsArray(); - AffineMap inputMap = maps[0]; - AffineMap outputMap = maps[1]; - - unsigned numDims = outputMap.getNumDims(); - if (!outputMap.isIdentity()) { - return failure(); - } - - if (!inputMap.isProjectedPermutation()) { - return failure(); - } - - // Check that the input map is exactly (d0, d1, ..., dN) -> (d1, d2, ..., dN) - // i.e., only dimension 0 is broadcast (missing in the result affine expr) and - // the remaining dimensions are in order (not permuted). A permuted map like - // (d0,d1,d2) -> (d2,d1) represents a fused broadcast+transpose, which this - // pattern cannot handle. - if (inputMap.getNumResults() != numDims - 1) { - return failure(); - } - for (unsigned i = 0; i < inputMap.getNumResults(); ++i) { - auto dimExpr = dyn_cast<AffineDimExpr>(inputMap.getResult(i)); - if (!dimExpr || dimExpr.getPosition() != i + 1) { - return failure(); - } - } - - // Check body simply yields the input argument - Block *body = genericOp.getBody(); - if (body->getNumArguments() != 2) { - return failure(); - } - auto yieldOp = dyn_cast<linalg::YieldOp>(body->getTerminator()); - if (!yieldOp || yieldOp.getNumOperands() != 1) { - return failure(); - } - if (yieldOp.getOperand(0) != body->getArgument(0)) { - return failure(); - } - - return genericOp.getDpsInputs()[0]; -} - -static int64_t computeCollapsedDim(int64_t dim0, int64_t dim1) { - if (dim0 == ShapedType::kDynamic || dim1 == ShapedType::kDynamic) { - return ShapedType::kDynamic; - } - return dim0 * dim1; -} - -static Value createCollapseShape(OpBuilder &builder, Location loc, Value input, - RankedTensorType inputType) { - SmallVector<ReassociationIndices> reassoc = {{0, 1}, {2}}; - int64_t collapsedDim0 = - computeCollapsedDim(inputType.getDimSize(0), inputType.getDimSize(1)); - auto collapsedType = RankedTensorType::get( - {collapsedDim0, inputType.getDimSize(2)}, inputType.getElementType()); - return tensor::CollapseShapeOp::create(builder, loc, collapsedType, input, - reassoc); -} - -static Value createExpandShape(OpBuilder &builder, Location loc, Value input, - RankedTensorType outputType, Value originalAct, - Value originalOut) { - SmallVector<ReassociationIndices> reassoc = {{0, 1}, {2}}; - - // Build output shape - extract dynamic dimensions from original tensors - SmallVector<OpFoldResult> outputShape; - for (int64_t i = 0; i < 3; ++i) { - if (outputType.isDynamicDim(i)) { - // For batch (i=0) and M (i=1), get from original activation - // For N (i=2), get from original output - Value source = (i < 2) ? originalAct : originalOut; - Value idx = arith::ConstantIndexOp::create(builder, loc, i); - Value dimVal = tensor::DimOp::create(builder, loc, source, idx); - outputShape.push_back(dimVal); - } else { - outputShape.push_back(builder.getIndexAttr(outputType.getDimSize(i))); - } - } - - return tensor::ExpandShapeOp::create(builder, loc, outputType, input, reassoc, - outputShape); -} - -/// Pattern to convert broadcast + batch_matmul to collapse_shape + matmul + -/// expand_shape. This handles BatchMatmulOp and BatchMatmulTransposeBOp -/// (which share the same underlying op but with different indexing maps). -/// BatchMatmulTransposeAOp is not supported because the collapse would -/// produce mismatched shapes (LHS collapses batch*K but output collapses -/// batch*M). -class ConvertBroadcastBatchMatmulToMatmul - : public OpRewritePattern<linalg::BatchMatmulOp> { -public: - using OpRewritePattern<linalg::BatchMatmulOp>::OpRewritePattern; - - LogicalResult matchAndRewrite(linalg::BatchMatmulOp batchMatmul, - PatternRewriter &rewriter) const override { - // The RHS must be a batch-dim broadcast of a 2-D weight. - Value rhs = batchMatmul.getDpsInputOperand(1)->get(); - Operation *rhsDefOp = rhs.getDefiningOp(); - if (!rhsDefOp) { - return failure(); - } - FailureOr<Value> weight = getOriginalBroadcastWeight(rhsDefOp); - if (failed(weight)) { - return failure(); - } - - // Get LHS activation - Value act = batchMatmul.getDpsInputOperand(0)->get(); - auto actType = cast<RankedTensorType>(act.getType()); - - Value out = batchMatmul.getDpsInitOperand(0)->get(); - auto outType = cast<RankedTensorType>(out.getType()); - - // Classify the contraction layout by comparing the indexing maps directly. - // batch_matmul has four loop dimensions (batch, m, n, k); the canonical - // maps are LHS (batch, m, k), RHS (batch, k, n) and OUT (batch, m, n). - MLIRContext *ctx = batchMatmul.getContext(); - AffineExpr bDim, mDim, nDim, kDim; - bindDims(ctx, bDim, mDim, nDim, kDim); - auto mapOf = [&](ArrayRef<AffineExpr> results) { - return AffineMap::get(/*dimCount=*/4, /*symbolCount=*/0, results, ctx); - }; - SmallVector<AffineMap> maps = batchMatmul.getIndexingMapsArray(); - if (maps.size() != 3) { - return failure(); - } - // Only fold when the LHS is [batch, M, K] and the output is [batch, M, N]. - // A transposed LHS [batch, K, M] cannot be folded: collapsing it merges the - // batch and leading dims into [batch*K, M], which no longer matches the - // output's [batch*M, N] collapse. - if (maps[0] != mapOf({bDim, mDim, kDim}) || - maps[2] != mapOf({bDim, mDim, nDim})) { - return failure(); - } - // The RHS may be plain (batch, k, n) or transpose_b (batch, n, k). - bool transposeB; - if (maps[1] == mapOf({bDim, kDim, nDim})) { - transposeB = false; - } else if (maps[1] == mapOf({bDim, nDim, kDim})) { - transposeB = true; - } else { - return failure(); - } - - Location loc = batchMatmul.getLoc(); - - // Collapse activation: [batch, dim1, dim2] -> [batch*dim1, dim2] - Value collapsedAct = createCollapseShape(rewriter, loc, act, actType); - - // Collapse output init tensor - Value collapsedOut = createCollapseShape(rewriter, loc, out, outType); - - // Create matmul - check if this is a transpose variant - auto collapsedOutType = cast<RankedTensorType>(collapsedOut.getType()); - Value matmulResult; - - if (transposeB) { - matmulResult = linalg::MatmulTransposeBOp::create( - rewriter, loc, collapsedOutType, - ValueRange{collapsedAct, *weight}, collapsedOut) - .getResult(0); - } else { - matmulResult = linalg::MatmulOp::create(rewriter, loc, collapsedOutType, - ValueRange{collapsedAct, *weight}, - collapsedOut) - .getResult(0); - } - - // Expand result back to 3D: [batch*dim1, dim2] -> [batch, dim1, dim2] - Value expandedResult = - createExpandShape(rewriter, loc, matmulResult, outType, act, out); - - rewriter.replaceOp(batchMatmul, expandedResult); - return success(); - } -}; - -struct ConvertBatchMatmulToMatmulPass - : public impl::ConvertBatchMatmulToMatmulPassBase< - ConvertBatchMatmulToMatmulPass> { - void runOnOperation() override { - MLIRContext *context = &getContext(); - RewritePatternSet patterns(context); - patterns.add<ConvertBroadcastBatchMatmulToMatmul>(context); - if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) { - return signalPassFailure(); - } - } -}; - -} // namespace -} // namespace mlir::iree_compiler::GlobalOptimization
diff --git a/compiler/src/iree/compiler/GlobalOptimization/FoldBroadcastIntoBatchMatmul.cpp b/compiler/src/iree/compiler/GlobalOptimization/FoldBroadcastIntoBatchMatmul.cpp new file mode 100644 index 0000000..02efec6 --- /dev/null +++ b/compiler/src/iree/compiler/GlobalOptimization/FoldBroadcastIntoBatchMatmul.cpp
@@ -0,0 +1,180 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +// Folds a broadcast feeding a `linalg.batch_matmul` input into the op's +// indexing maps. `batch_matmul(A, broadcast(B))` with a weight shared across +// the batch becomes a `batch_matmul` over `A` and `B` whose RHS map simply +// drops the batch dim. The contraction then reads its operands directly, which +// keeps producer patterns such as dequantization visible to later rewrites, and +// no broadcast is materialized. Where the named op cannot express the folded +// map, the contraction is carried by a `linalg.generic` with the same body. + +#include "iree/compiler/GlobalOptimization/Passes.h" +#include "mlir/Dialect/Linalg/IR/Linalg.h" +#include "mlir/Dialect/Linalg/Transforms/Transforms.h" +#include "mlir/IR/AffineMap.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" + +namespace mlir::iree_compiler::GlobalOptimization { + +#define GEN_PASS_DEF_FOLDBROADCASTINTOBATCHMATMULPASS +#include "iree/compiler/GlobalOptimization/Passes.h.inc" + +namespace { + +/// A producer that only moves data: its result reads `source` through `map`, +/// which takes result indices to source indices and drops at least one dim. +struct BroadcastProducer { + Value source; + AffineMap map; +}; + +/// Matches `value` as the result of a `linalg.broadcast`, or of a generic that +/// only broadcasts (and possibly permutes) its single input. +static FailureOr<BroadcastProducer> matchBroadcastProducer(Value value) { + Operation *op = value.getDefiningOp(); + if (!op) { + return failure(); + } + if (auto broadcastOp = dyn_cast<linalg::BroadcastOp>(op)) { + return BroadcastProducer{broadcastOp.getInput(), + broadcastOp.getIndexingMapsArray()[0]}; + } + auto genericOp = dyn_cast<linalg::GenericOp>(op); + if (!genericOp || !genericOp.hasPureTensorSemantics() || + genericOp.getNumDpsInputs() != 1 || genericOp.getNumDpsInits() != 1 || + genericOp.getNumParallelLoops() != genericOp.getNumLoops()) { + return failure(); + } + Block *body = genericOp.getBody(); + auto yieldOp = cast<linalg::YieldOp>(body->getTerminator()); + if (yieldOp.getNumOperands() != 1 || + yieldOp.getOperand(0) != body->getArgument(0)) { + return failure(); + } + AffineMap inputMap = genericOp.getIndexingMapsArray()[0]; + AffineMap outputMap = genericOp.getIndexingMapsArray()[1]; + if (!inputMap.isProjectedPermutation() || !outputMap.isPermutation() || + inputMap.getNumResults() == inputMap.getNumDims()) { + return failure(); + } + // Take result indices to iteration indices, then to input indices. + return BroadcastProducer{genericOp.getDpsInputs()[0], + inputMap.compose(inversePermutation(outputMap))}; +} + +/// Returns the default map of the given batch_matmul input. +static AffineMap getDefaultInputMap(linalg::BatchMatmulOp op, bool isLhs) { + SmallVector<AffineMap> defaultMaps = + linalg::BatchMatmulOp::getDefaultIndexingMaps(op.getContext()); + return defaultMaps[isLhs ? 0 : 1]; +} + +/// Returns true if `map` still reads a contraction operand: every result is +/// one of the input's default dims and the reduction dim is among them. The +/// batch_matmul loops are (batch, m, n, k). +static bool isContractionInputMap(linalg::BatchMatmulOp op, AffineMap map, + bool isLhs) { + AffineMap defaultMap = getDefaultInputMap(op, isLhs); + if (map.getNumResults() > defaultMap.getNumResults() || + !map.isFunctionOfDim(/*position=*/3)) { + return false; + } + return llvm::all_of(map.getResults(), [&](AffineExpr expr) { + return isa<AffineDimExpr>(expr) && + llvm::is_contained(defaultMap.getResults(), expr); + }); +} + +/// Mirrors the batch_matmul verifier's rules on top of +/// `isContractionInputMap`: a broadcast (fewer results) is limited to the +/// operand orders upstream accepts, and a full-rank map leads with the batch. +static bool isNamedInputMap(linalg::BatchMatmulOp op, AffineMap map, + bool isLhs) { + AffineMap defaultMap = getDefaultInputMap(op, isLhs); + if (map.getNumResults() < defaultMap.getNumResults()) { + return op.isValidLhsRhsBroadcastMap(map, isLhs); + } + return map.getResult(0).isFunctionOfDim(0); +} + +/// Folds broadcast producers of either batch_matmul input into the op's +/// indexing maps. The broadcast is left for its other users, if any. +struct FoldBroadcastIntoBatchMatmul + : public OpRewritePattern<linalg::BatchMatmulOp> { + using OpRewritePattern<linalg::BatchMatmulOp>::OpRewritePattern; + + LogicalResult matchAndRewrite(linalg::BatchMatmulOp op, + PatternRewriter &rewriter) const override { + if (!op.hasPureTensorSemantics()) { + return failure(); + } + SmallVector<AffineMap> maps = op.getIndexingMapsArray(); + SmallVector<Value> inputs(op.getDpsInputs()); + bool changed = false; + bool needsGeneric = false; + for (auto [idx, input] : llvm::enumerate(inputs)) { + FailureOr<BroadcastProducer> producer = matchBroadcastProducer(input); + if (failed(producer)) { + continue; + } + // Take contraction loops to operand indices, then to source indices. + bool isLhs = idx == 0; + AffineMap foldedMap = producer->map.compose(maps[idx]); + if (!isContractionInputMap(op, foldedMap, isLhs)) { + continue; + } + // The named op accepts a single operand order per broadcast, e.g. a + // batch-broadcast RHS must be [K, N]. Any other folded map is carried + // by a generic with the same body, so no data is moved to satisfy the + // verifier. + if (!isNamedInputMap(op, foldedMap, isLhs)) { + needsGeneric = true; + } + input = producer->source; + maps[idx] = foldedMap; + changed = true; + } + if (!changed) { + return failure(); + } + if (!needsGeneric) { + rewriter.modifyOpInPlace(op, [&] { + op.getInputsMutable().assign(inputs); + op.setIndexingMapsAttr(rewriter.getAffineMapArrayAttr(maps)); + }); + return success(); + } + FailureOr<linalg::LinalgOp> generalized = + linalg::generalizeNamedOp(rewriter, op); + if (failed(generalized)) { + return failure(); + } + auto genericOp = cast<linalg::GenericOp>(generalized->getOperation()); + rewriter.modifyOpInPlace(genericOp, [&] { + genericOp.getInputsMutable().assign(inputs); + genericOp.setIndexingMapsAttr(rewriter.getAffineMapArrayAttr(maps)); + }); + return success(); + } +}; + +struct FoldBroadcastIntoBatchMatmulPass final + : impl::FoldBroadcastIntoBatchMatmulPassBase< + FoldBroadcastIntoBatchMatmulPass> { + void runOnOperation() override { + MLIRContext *context = &getContext(); + RewritePatternSet patterns(context); + patterns.add<FoldBroadcastIntoBatchMatmul>(context); + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) { + return signalPassFailure(); + } + } +}; + +} // namespace +} // namespace mlir::iree_compiler::GlobalOptimization
diff --git a/compiler/src/iree/compiler/GlobalOptimization/Passes.cpp b/compiler/src/iree/compiler/GlobalOptimization/Passes.cpp index d3bbde2..c6a9915 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/Passes.cpp +++ b/compiler/src/iree/compiler/GlobalOptimization/Passes.cpp
@@ -187,10 +187,9 @@ createFuseDequantizationMatmulPass) .addPass(IREE::Flow::createCanonicalizePass) .addPass(mlir::createCSEPass) - // Convert broadcast + batch_matmul before transpose propagation so we - // can match the pure broadcast patterns before they get fused with - // transposes. - .addPass(GlobalOptimization::createConvertBatchMatmulToMatmulPass); + // Fold broadcasts into batch_matmul indexing maps before transpose + // propagation so the contraction consumes its producers directly. + .addPass(createFoldBroadcastIntoBatchMatmulPass); FunctionLikeNest(mainPassManager) // Propagate transposes immediately before set encoding/data tiling @@ -228,6 +227,11 @@ // Enable data tiling after they are in a canonical form. if (transformOptions.dataTiling) { FunctionLikeNest(mainPassManager) + // Data tiling wants a single M, N and K dim. Collapse contractions + // whose loops merge, such as a batch_matmul with a batch-broadcast + // weight after the fold above, before annotating them. The dispatch + // creation data tiling path collapses after dispatch formation instead. + .addPass(DispatchCreation::createCollapseContractionDimensionsPass) .addPass(DispatchCreation::createAnnotateDataTilingHintsPass) .addPass([&]() { return DispatchCreation::createSetEncodingPass(
diff --git a/compiler/src/iree/compiler/GlobalOptimization/Passes.td b/compiler/src/iree/compiler/GlobalOptimization/Passes.td index ebe3025..cc91958 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/Passes.td +++ b/compiler/src/iree/compiler/GlobalOptimization/Passes.td
@@ -14,16 +14,6 @@ let summary = "Cleans up any numeric narrowing ops inserted by iree-global-opt-infer-numeric-narrowing."; } -def ConvertBatchMatmulToMatmulPass : - Pass<"iree-global-opt-convert-batch-matmul-to-matmul", ""> { - let summary = "Converts batch_matmul to reshape + matmul + reshape."; - let dependentDialects = [ - "mlir::arith::ArithDialect", - "mlir::linalg::LinalgDialect", - "mlir::tensor::TensorDialect", - ]; -} - def ConvertConvToIm2ColPass : Pass<"iree-global-opt-convert-conv-to-im2col", ""> { let summary = "Rewrites convolutions as contractions over an im2col gather"; @@ -115,6 +105,26 @@ let summary = "Expands tensor shape dimensions into SSA values across the program."; } +def FoldBroadcastIntoBatchMatmulPass : + InterfacePass<"iree-global-opt-fold-broadcast-into-batch-matmul", "mlir::FunctionOpInterface"> { + let summary = "Folds broadcasts of batch_matmul inputs into its indexing maps."; + let description = [{ + Rewrites `batch_matmul(A, broadcast(B))`, where the weight is shared across + the batch, into a `batch_matmul` over `A` and `B` whose RHS indexing map + drops the batch dim. Broadcasts on either input, as `linalg.broadcast` or + as a broadcasting generic, are folded by composing their map into the + contraction's map. When the named op cannot express the folded map (its + verifier accepts only a few broadcast forms, e.g. a batch-broadcast RHS + must be [K, N]), the contraction is carried by a `linalg.generic` with the + same body instead of moving data. The contraction then consumes its + producers directly, so rewrites that match on them (such as the + dequantization folding) still apply, and no broadcast is materialized. + }]; + let dependentDialects = [ + "mlir::linalg::LinalgDialect", + ]; +} + def PropagateAffineQuantizationPass : InterfacePass<"iree-global-opt-propagate-affine-quantization", "mlir::FunctionOpInterface"> { let summary = "Propagates affine quantization through adjacent tensor operations.";
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/BUILD.bazel b/compiler/src/iree/compiler/GlobalOptimization/test/BUILD.bazel index 31107d5..0d84526 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/test/BUILD.bazel +++ b/compiler/src/iree/compiler/GlobalOptimization/test/BUILD.bazel
@@ -19,7 +19,6 @@ [ "cleanup_numeric_narrowing.mlir", "conv_to_im2col.mlir", - "convert_batch_matmul_to_matmul.mlir", "convert_qdq_to_integer_math_algebra.mlir", "convert_qdq_to_integer_math_maps.mlir", "convert_qdq_to_integer_math_negative.mlir", @@ -29,6 +28,8 @@ "demote_contraction_inputs.mlir", "detach_elementwise_from_named_ops.mlir", "expand_tensor_shapes.mlir", + "fold_broadcast_into_batch_matmul.mlir", + "fold_broadcast_into_batch_matmul_pipeline.mlir", "fuse_dequantization_matmul.mlir", "generalize_named_ops.mlir", "global_loop_invariant_code_motion.mlir",
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/CMakeLists.txt b/compiler/src/iree/compiler/GlobalOptimization/test/CMakeLists.txt index 8c5654a..35f6cd1 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/test/CMakeLists.txt +++ b/compiler/src/iree/compiler/GlobalOptimization/test/CMakeLists.txt
@@ -16,7 +16,6 @@ SRCS "cleanup_numeric_narrowing.mlir" "conv_to_im2col.mlir" - "convert_batch_matmul_to_matmul.mlir" "convert_qdq_to_integer_math_algebra.mlir" "convert_qdq_to_integer_math_maps.mlir" "convert_qdq_to_integer_math_negative.mlir" @@ -26,6 +25,8 @@ "demote_contraction_inputs.mlir" "detach_elementwise_from_named_ops.mlir" "expand_tensor_shapes.mlir" + "fold_broadcast_into_batch_matmul.mlir" + "fold_broadcast_into_batch_matmul_pipeline.mlir" "fuse_dequantization_matmul.mlir" "generalize_named_ops.mlir" "global_loop_invariant_code_motion.mlir"
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/convert_batch_matmul_to_matmul.mlir b/compiler/src/iree/compiler/GlobalOptimization/test/convert_batch_matmul_to_matmul.mlir deleted file mode 100644 index 1d36e5e..0000000 --- a/compiler/src/iree/compiler/GlobalOptimization/test/convert_batch_matmul_to_matmul.mlir +++ /dev/null
@@ -1,290 +0,0 @@ -// RUN: iree-opt --split-input-file --mlir-print-local-scope -iree-global-opt-convert-batch-matmul-to-matmul %s | FileCheck %s - -// Static shapes with named broadcast -// CHECK-LABEL: util.func public @static_broadcast_batch_matmul -// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]: tensor<4x10x10xf32>, %[[ARG1:[a-zA-Z0-9]+]]: tensor<10x10xf32> -// CHECK-DAG: %[[CST:.*]] = arith.constant 0.000000e+00 : f32 -// CHECK: %[[EMPTY:.*]] = tensor.empty() : tensor<4x10x10xf32> -// CHECK: %[[FILL:.*]] = linalg.fill ins(%[[CST]] : f32) outs(%[[EMPTY]] : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> -// CHECK: %[[COLLAPSED_ACT:.*]] = tensor.collapse_shape %[[ARG0]] {{\[}}[0, 1], [2]{{\]}} : tensor<4x10x10xf32> into tensor<40x10xf32> -// CHECK: %[[COLLAPSED_OUT:.*]] = tensor.collapse_shape %[[FILL]] {{\[}}[0, 1], [2]{{\]}} : tensor<4x10x10xf32> into tensor<40x10xf32> -// CHECK: %[[MATMUL:.*]] = linalg.matmul ins(%[[COLLAPSED_ACT]], %[[ARG1]] : tensor<40x10xf32>, tensor<10x10xf32>) outs(%[[COLLAPSED_OUT]] : tensor<40x10xf32>) -> tensor<40x10xf32> -// CHECK: %[[EXPANDED:.*]] = tensor.expand_shape %[[MATMUL]] {{\[}}[0, 1], [2]{{\]}} output_shape [4, 10, 10] : tensor<40x10xf32> into tensor<4x10x10xf32> -// CHECK: util.return %[[EXPANDED]] : tensor<4x10x10xf32> -util.func public @static_broadcast_batch_matmul(%act: tensor<4x10x10xf32>, %weight: tensor<10x10xf32>) -> tensor<4x10x10xf32> { - %init_broadcast = tensor.empty() : tensor<4x10x10xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) - outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<4x10x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) - outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - util.return %result : tensor<4x10x10xf32> -} - -// ----- - -// Dynamic batch dimension (M is static) -// CHECK-LABEL: util.func public @dynamic_batch_broadcast_batch_matmul -// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]: tensor<?x10x10xf32>, %[[ARG1:[a-zA-Z0-9]+]]: tensor<10x10xf32> -// CHECK-DAG: %[[CST:.*]] = arith.constant 0.000000e+00 : f32 -// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index -// CHECK: %[[DIM:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x10x10xf32> -// CHECK: %[[EMPTY:.*]] = tensor.empty(%[[DIM]]) : tensor<?x10x10xf32> -// CHECK: %[[FILL:.*]] = linalg.fill ins(%[[CST]] : f32) outs(%[[EMPTY]] : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> -// CHECK: %[[COLLAPSED_ACT:.*]] = tensor.collapse_shape %[[ARG0]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x10x10xf32> into tensor<?x10xf32> -// CHECK: %[[COLLAPSED_OUT:.*]] = tensor.collapse_shape %[[FILL]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x10x10xf32> into tensor<?x10xf32> -// CHECK: %[[MATMUL:.*]] = linalg.matmul ins(%[[COLLAPSED_ACT]], %[[ARG1]] : tensor<?x10xf32>, tensor<10x10xf32>) outs(%[[COLLAPSED_OUT]] : tensor<?x10xf32>) -> tensor<?x10xf32> -// CHECK: %[[BATCH:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x10x10xf32> -// CHECK: %[[EXPANDED:.*]] = tensor.expand_shape %[[MATMUL]] {{\[}}[0, 1], [2]{{\]}} output_shape [%[[BATCH]], 10, 10] : tensor<?x10xf32> into tensor<?x10x10xf32> -// CHECK: util.return %[[EXPANDED]] : tensor<?x10x10xf32> -util.func public @dynamic_batch_broadcast_batch_matmul(%act: tensor<?x10x10xf32>, %weight: tensor<10x10xf32>) -> tensor<?x10x10xf32> { - %c0 = arith.constant 0 : index - %batch = tensor.dim %act, %c0 : tensor<?x10x10xf32> - %init_broadcast = tensor.empty(%batch) : tensor<?x10x10xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) - outs(%init_broadcast : tensor<?x10x10xf32>) dimensions = [0] - %init_out = tensor.empty(%batch) : tensor<?x10x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> - %result = linalg.batch_matmul ins(%act, %broadcast : tensor<?x10x10xf32>, tensor<?x10x10xf32>) - outs(%fill : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> - util.return %result : tensor<?x10x10xf32> -} - -// ----- - -// Generic broadcast form (after generalization) -// CHECK-LABEL: util.func public @generic_broadcast_batch_matmul -// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]: tensor<?x10x10xf32>, %[[ARG1:[a-zA-Z0-9]+]]: tensor<10x10xf32> -// CHECK-DAG: %[[CST:.*]] = arith.constant 0.000000e+00 : f32 -// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index -// CHECK: %[[DIM:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x10x10xf32> -// CHECK: %[[EMPTY:.*]] = tensor.empty(%[[DIM]]) : tensor<?x10x10xf32> -// CHECK: %[[FILL:.*]] = linalg.fill ins(%[[CST]] : f32) outs(%[[EMPTY]] : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> -// CHECK: %[[COLLAPSED_ACT:.*]] = tensor.collapse_shape %[[ARG0]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x10x10xf32> into tensor<?x10xf32> -// CHECK: %[[COLLAPSED_OUT:.*]] = tensor.collapse_shape %[[FILL]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x10x10xf32> into tensor<?x10xf32> -// CHECK: %[[MATMUL:.*]] = linalg.matmul ins(%[[COLLAPSED_ACT]], %[[ARG1]] : tensor<?x10xf32>, tensor<10x10xf32>) outs(%[[COLLAPSED_OUT]] : tensor<?x10xf32>) -> tensor<?x10xf32> -// CHECK: %[[BATCH:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x10x10xf32> -// CHECK: %[[EXPANDED:.*]] = tensor.expand_shape %[[MATMUL]] {{\[}}[0, 1], [2]{{\]}} output_shape [%[[BATCH]], 10, 10] : tensor<?x10xf32> into tensor<?x10x10xf32> -// CHECK: util.return %[[EXPANDED]] : tensor<?x10x10xf32> -util.func public @generic_broadcast_batch_matmul(%act: tensor<?x10x10xf32>, %weight: tensor<10x10xf32>) -> tensor<?x10x10xf32> { - %c0 = arith.constant 0 : index - %batch = tensor.dim %act, %c0 : tensor<?x10x10xf32> - %init_broadcast = tensor.empty(%batch) : tensor<?x10x10xf32> - // Generic form of broadcast (as produced by GeneralizeLinalgNamedOps) - %broadcast = linalg.generic { - indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d2)>, - affine_map<(d0, d1, d2) -> (d0, d1, d2)>], - iterator_types = ["parallel", "parallel", "parallel"] - } ins(%weight : tensor<10x10xf32>) outs(%init_broadcast : tensor<?x10x10xf32>) { - ^bb0(%in: f32, %out: f32): - linalg.yield %in : f32 - } -> tensor<?x10x10xf32> - %init_out = tensor.empty(%batch) : tensor<?x10x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> - %result = linalg.batch_matmul ins(%act, %broadcast : tensor<?x10x10xf32>, tensor<?x10x10xf32>) - outs(%fill : tensor<?x10x10xf32>) -> tensor<?x10x10xf32> - util.return %result : tensor<?x10x10xf32> -} - -// ----- - -// Negative test - broadcast on LHS (should NOT transform) -// CHECK-LABEL: util.func public @broadcast_on_lhs -// CHECK: linalg.broadcast -// CHECK: linalg.batch_matmul -// CHECK-NOT: tensor.collapse_shape -util.func public @broadcast_on_lhs(%lhs: tensor<10x10xf32>, %rhs: tensor<4x10x10xf32>) -> tensor<4x10x10xf32> { - %init_broadcast = tensor.empty() : tensor<4x10x10xf32> - %broadcast = linalg.broadcast ins(%lhs : tensor<10x10xf32>) - outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<4x10x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - %result = linalg.batch_matmul ins(%broadcast, %rhs : tensor<4x10x10xf32>, tensor<4x10x10xf32>) - outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - util.return %result : tensor<4x10x10xf32> -} - -// ----- - -// Both batch and M are dynamic (should transform with explicit output_shape) -// CHECK-LABEL: util.func public @both_batch_and_m_dynamic -// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]: tensor<?x?x10xf32>, %[[ARG1:[a-zA-Z0-9]+]]: tensor<10x10xf32> -// CHECK-DAG: %[[CST:.*]] = arith.constant 0.000000e+00 : f32 -// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index -// CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index -// CHECK: %[[BATCH:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x?x10xf32> -// CHECK: %[[M:.*]] = tensor.dim %[[ARG0]], %[[C1]] : tensor<?x?x10xf32> -// CHECK: %[[EMPTY:.*]] = tensor.empty(%[[BATCH]], %[[M]]) : tensor<?x?x10xf32> -// CHECK: %[[FILL:.*]] = linalg.fill ins(%[[CST]] : f32) outs(%[[EMPTY]] : tensor<?x?x10xf32>) -> tensor<?x?x10xf32> -// CHECK: %[[COLLAPSED_ACT:.*]] = tensor.collapse_shape %[[ARG0]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x?x10xf32> into tensor<?x10xf32> -// CHECK: %[[COLLAPSED_OUT:.*]] = tensor.collapse_shape %[[FILL]] {{\[}}[0, 1], [2]{{\]}} : tensor<?x?x10xf32> into tensor<?x10xf32> -// CHECK: %[[MATMUL:.*]] = linalg.matmul ins(%[[COLLAPSED_ACT]], %[[ARG1]] : tensor<?x10xf32>, tensor<10x10xf32>) outs(%[[COLLAPSED_OUT]] : tensor<?x10xf32>) -> tensor<?x10xf32> -// CHECK: %[[DIM_BATCH:.*]] = tensor.dim %[[ARG0]], %[[C0]] : tensor<?x?x10xf32> -// CHECK: %[[DIM_M:.*]] = tensor.dim %[[ARG0]], %[[C1]] : tensor<?x?x10xf32> -// CHECK: %[[EXPANDED:.*]] = tensor.expand_shape %[[MATMUL]] {{\[}}[0, 1], [2]{{\]}} output_shape [%[[DIM_BATCH]], %[[DIM_M]], 10] : tensor<?x10xf32> into tensor<?x?x10xf32> -// CHECK: util.return %[[EXPANDED]] : tensor<?x?x10xf32> -util.func public @both_batch_and_m_dynamic(%act: tensor<?x?x10xf32>, %weight: tensor<10x10xf32>) -> tensor<?x?x10xf32> { - %c0 = arith.constant 0 : index - %c1 = arith.constant 1 : index - %batch = tensor.dim %act, %c0 : tensor<?x?x10xf32> - %m = tensor.dim %act, %c1 : tensor<?x?x10xf32> - %init_broadcast = tensor.empty(%batch) : tensor<?x10x10xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) - outs(%init_broadcast : tensor<?x10x10xf32>) dimensions = [0] - %init_out = tensor.empty(%batch, %m) : tensor<?x?x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<?x?x10xf32>) -> tensor<?x?x10xf32> - %result = linalg.batch_matmul ins(%act, %broadcast : tensor<?x?x10xf32>, tensor<?x10x10xf32>) - outs(%fill : tensor<?x?x10xf32>) -> tensor<?x?x10xf32> - util.return %result : tensor<?x?x10xf32> -} - -// ----- - -// Negative test - broadcast adds dimension other than batch (should NOT transform) -// CHECK-LABEL: util.func public @broadcast_non_batch_dim -// CHECK: linalg.broadcast -// CHECK: linalg.batch_matmul -// CHECK-NOT: tensor.collapse_shape -util.func public @broadcast_non_batch_dim(%act: tensor<4x10x10xf32>, %weight: tensor<4x10xf32>) -> tensor<4x10x10xf32> { - %init_broadcast = tensor.empty() : tensor<4x10x10xf32> - // Broadcast adds dimension 1, not 0 - %broadcast = linalg.broadcast ins(%weight : tensor<4x10xf32>) - outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [1] - %init_out = tensor.empty() : tensor<4x10x10xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) - outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> - util.return %result : tensor<4x10x10xf32> -} - -// ----- - -// Transpose B variant (RHS weight is [N, K] instead of [K, N]) -// batch_matmul with indexing_maps specifying transpose_b: RHS accesses (batch, n, k) -// Activation: [4, 8, 10] = [batch, M, K] -// Weight: [6, 10] = [N, K] (transposed) -// After broadcast: [4, 6, 10] = [batch, N, K] -// Output: [4, 8, 6] = [batch, M, N] -// CHECK-LABEL: util.func public @broadcast_batch_matmul_transpose_b -// CHECK-SAME: %[[ARG0:[a-zA-Z0-9]+]]: tensor<4x8x10xf32>, %[[ARG1:[a-zA-Z0-9]+]]: tensor<6x10xf32> -// CHECK-DAG: %[[CST:.*]] = arith.constant 0.000000e+00 : f32 -// CHECK: %[[EMPTY:.*]] = tensor.empty() : tensor<4x8x6xf32> -// CHECK: %[[FILL:.*]] = linalg.fill ins(%[[CST]] : f32) outs(%[[EMPTY]] : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> -// CHECK: %[[COLLAPSED_ACT:.*]] = tensor.collapse_shape %[[ARG0]] {{\[}}[0, 1], [2]{{\]}} : tensor<4x8x10xf32> into tensor<32x10xf32> -// CHECK: %[[COLLAPSED_OUT:.*]] = tensor.collapse_shape %[[FILL]] {{\[}}[0, 1], [2]{{\]}} : tensor<4x8x6xf32> into tensor<32x6xf32> -// CHECK: %[[MATMUL:.*]] = linalg.matmul indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d2)>, affine_map<(d0, d1, d2) -> (d1, d2)>, affine_map<(d0, d1, d2) -> (d0, d1)>] ins(%[[COLLAPSED_ACT]], %[[ARG1]] : tensor<32x10xf32>, tensor<6x10xf32>) outs(%[[COLLAPSED_OUT]] : tensor<32x6xf32>) -> tensor<32x6xf32> -// CHECK: %[[EXPANDED:.*]] = tensor.expand_shape %[[MATMUL]] {{\[}}[0, 1], [2]{{\]}} output_shape [4, 8, 6] : tensor<32x6xf32> into tensor<4x8x6xf32> -// CHECK: util.return %[[EXPANDED]] : tensor<4x8x6xf32> -util.func public @broadcast_batch_matmul_transpose_b(%act: tensor<4x8x10xf32>, %weight: tensor<6x10xf32>) -> tensor<4x8x6xf32> { - %init_broadcast = tensor.empty() : tensor<4x6x10xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<6x10xf32>) - outs(%init_broadcast : tensor<4x6x10xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<4x8x6xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - // batch_matmul with transpose_b indexing: RHS is (batch, n, k) instead of (batch, k, n) - %result = linalg.batch_matmul - indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, - affine_map<(b, m, n, k) -> (b, n, k)>, - affine_map<(b, m, n, k) -> (b, m, n)>] - ins(%act, %broadcast : tensor<4x8x10xf32>, tensor<4x6x10xf32>) - outs(%fill : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - util.return %result : tensor<4x8x6xf32> -} - -// ----- - -// Negative test - fused broadcast + transpose in generic (should NOT transform) -// When transpose propagation folds a transpose into the broadcast generic, the -// input map becomes (d0,d1,d2) -> (d2,d1) instead of (d0,d1,d2) -> (d1,d2). -// The pass must not treat this as a pure broadcast. -// CHECK-LABEL: util.func public @fused_broadcast_transpose_generic -// CHECK: linalg.generic -// CHECK: linalg.batch_matmul -// CHECK-NOT: tensor.collapse_shape -util.func public @fused_broadcast_transpose_generic(%act: tensor<4x10x8xf32>, %weight: tensor<6x8xf32>) -> tensor<4x10x6xf32> { - %init_broadcast = tensor.empty() : tensor<4x8x6xf32> - // Generic that broadcasts on dim 0 AND transposes the inner dims - %broadcast_transpose = linalg.generic { - indexing_maps = [affine_map<(d0, d1, d2) -> (d2, d1)>, - affine_map<(d0, d1, d2) -> (d0, d1, d2)>], - iterator_types = ["parallel", "parallel", "parallel"] - } ins(%weight : tensor<6x8xf32>) outs(%init_broadcast : tensor<4x8x6xf32>) { - ^bb0(%in: f32, %out: f32): - linalg.yield %in : f32 - } -> tensor<4x8x6xf32> - %init_out = tensor.empty() : tensor<4x10x6xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> - %result = linalg.batch_matmul ins(%act, %broadcast_transpose : tensor<4x10x8xf32>, tensor<4x8x6xf32>) - outs(%fill : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> - util.return %result : tensor<4x10x6xf32> -} - -// ----- - -// Transpose A variant (LHS activation is [batch, K, M] instead of [batch, M, K]) -// This should NOT transform because the collapse would produce mismatched shapes: -// - LHS [batch, K, M] collapses to [batch*K, M] -// - Out [batch, M, N] collapses to [batch*M, N] -// These don't match, so transformation is invalid. -// CHECK-LABEL: util.func public @broadcast_batch_matmul_transpose_a -// CHECK: linalg.broadcast -// CHECK: linalg.batch_matmul -// CHECK-NOT: tensor.collapse_shape -util.func public @broadcast_batch_matmul_transpose_a(%act: tensor<4x10x8xf32>, %weight: tensor<10x6xf32>) -> tensor<4x8x6xf32> { - %init_broadcast = tensor.empty() : tensor<4x10x6xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<10x6xf32>) - outs(%init_broadcast : tensor<4x10x6xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<4x8x6xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - // batch_matmul with transpose_a indexing: LHS is (batch, k, m) instead of (batch, m, k) - %result = linalg.batch_matmul - indexing_maps = [affine_map<(b, m, n, k) -> (b, k, m)>, - affine_map<(b, m, n, k) -> (b, k, n)>, - affine_map<(b, m, n, k) -> (b, m, n)>] - ins(%act, %broadcast : tensor<4x10x8xf32>, tensor<4x10x6xf32>) - outs(%fill : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - util.return %result : tensor<4x8x6xf32> -} - -// ----- - -// Negative test - combined transpose_a and transpose_b (should NOT transform). -// The LHS activation is [batch, K, M] and the RHS weight is [N, K]. For the -// same reason as the transpose_a variant, because the LHS is transposed the -// collapse would produce mismatched shapes: -// - LHS [batch, K, M] collapses to [batch*K, M] -// - Out [batch, M, N] collapses to [batch*M, N] -// These don't match, so transformation is invalid. The combined form must be -// rejected even though it is neither a pure transpose_a nor a pure transpose_b. -// CHECK-LABEL: util.func public @broadcast_batch_matmul_transpose_a_and_b -// CHECK: linalg.broadcast -// CHECK: linalg.batch_matmul -// CHECK-NOT: tensor.collapse_shape -// CHECK-NOT: linalg.matmul -util.func public @broadcast_batch_matmul_transpose_a_and_b(%act: tensor<4x10x8xf32>, %weight: tensor<6x10xf32>) -> tensor<4x8x6xf32> { - %init_broadcast = tensor.empty() : tensor<4x6x10xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<6x10xf32>) - outs(%init_broadcast : tensor<4x6x10xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<4x8x6xf32> - %cst = arith.constant 0.0 : f32 - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - // batch_matmul with transpose_a and transpose_b indexing: LHS is (b, k, m) and - // RHS is (b, n, k) instead of (b, m, k) and (b, k, n) - %result = linalg.batch_matmul - indexing_maps = [affine_map<(b, m, n, k) -> (b, k, m)>, - affine_map<(b, m, n, k) -> (b, n, k)>, - affine_map<(b, m, n, k) -> (b, m, n)>] - ins(%act, %broadcast : tensor<4x10x8xf32>, tensor<4x6x10xf32>) - outs(%fill : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> - util.return %result : tensor<4x8x6xf32> -}
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/convert_qdq_to_integer_math_pipeline.mlir b/compiler/src/iree/compiler/GlobalOptimization/test/convert_qdq_to_integer_math_pipeline.mlir index 7b0c470..bdcd34b 100644 --- a/compiler/src/iree/compiler/GlobalOptimization/test/convert_qdq_to_integer_math_pipeline.mlir +++ b/compiler/src/iree/compiler/GlobalOptimization/test/convert_qdq_to_integer_math_pipeline.mlir
@@ -171,6 +171,49 @@ // ----- +// A weight broadcast along the batch dim folds into the batch_matmul's +// indexing maps, so the contraction reads both dequantize results directly. +util.func public @broadcast_dequantized_rhs( + %aq: tensor<4x8x16xi8>, %bq: tensor<16x12xi8>, %sa: f32, %sb: f32, + %za: i8, %zb: i8) -> tensor<4x8x12xf32> { + %ai = tensor.empty() : tensor<4x8x16xf32> + %a = iree_linalg_ext.dequantize_affine + <indexing_maps = [affine_map<(b, m, k) -> (b, m, k)>, + affine_map<(b, m, k) -> ()>, + affine_map<(b, m, k) -> ()>, + affine_map<(b, m, k) -> (b, m, k)>]> + ins(%aq, %sa, %za : tensor<4x8x16xi8>, f32, i8) + outs(%ai : tensor<4x8x16xf32>) -> tensor<4x8x16xf32> + %bi = tensor.empty() : tensor<16x12xf32> + %b = iree_linalg_ext.dequantize_affine + <indexing_maps = [affine_map<(k, n) -> (k, n)>, + affine_map<(k, n) -> ()>, + affine_map<(k, n) -> ()>, + affine_map<(k, n) -> (k, n)>]> + ins(%bq, %sb, %zb : tensor<16x12xi8>, f32, i8) + outs(%bi : tensor<16x12xf32>) -> tensor<16x12xf32> + %bcast_init = tensor.empty() : tensor<4x16x12xf32> + %bcast = linalg.broadcast ins(%b : tensor<16x12xf32>) + outs(%bcast_init : tensor<4x16x12xf32>) dimensions = [0] + %zero = arith.constant 0.0 : f32 + %empty = tensor.empty() : tensor<4x8x12xf32> + %init = linalg.fill ins(%zero : f32) outs(%empty : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + %result = linalg.batch_matmul ins(%a, %bcast : tensor<4x8x16xf32>, tensor<4x16x12xf32>) + outs(%init : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + util.return %result : tensor<4x8x12xf32> +} +// CHECK-LABEL: util.func public @broadcast_dequantized_rhs( +// CHECK-NOT: linalg.broadcast +// CHECK: arith.muli %{{.+}}, %{{.+}} : i32 +// CHECK: arith.sitofp +// DISABLED-LABEL: util.func public @broadcast_dequantized_rhs( +// DISABLED: iree_linalg_ext.dequantize_affine +// DISABLED-NOT: linalg.broadcast +// DISABLED: linalg.batch_matmul +// DISABLED-SAME: indexing_maps + +// ----- + // Blockwise linear layer as produced by the Torch frontend: both operands are // dequantized per block and collapsed back into K, and the weight is // transposed. Propagation expands the matmul over the blocks so the rewrite
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul.mlir b/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul.mlir new file mode 100644 index 0000000..b72a854 --- /dev/null +++ b/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul.mlir
@@ -0,0 +1,221 @@ +// RUN: iree-opt --split-input-file --mlir-print-local-scope --pass-pipeline="builtin.module(util.func(iree-global-opt-fold-broadcast-into-batch-matmul))" %s | FileCheck %s + +// A weight broadcast along the batch dim folds into the RHS map. +util.func public @broadcast_rhs(%act: tensor<4x10x10xf32>, %weight: tensor<10x10xf32>) -> tensor<4x10x10xf32> { + %init_broadcast = tensor.empty() : tensor<4x10x10xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) + outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x10x10xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) + outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + util.return %result : tensor<4x10x10xf32> +} +// CHECK-LABEL: @broadcast_rhs +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x10x10xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<10x10xf32> +// CHECK-NOT: linalg.broadcast +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x10x10xf32>, tensor<10x10xf32>) + +// ----- + +// Dynamic batch and M dims need no shape computation. +util.func public @broadcast_rhs_dynamic(%act: tensor<?x?x10xf32>, %weight: tensor<10x10xf32>) -> tensor<?x?x10xf32> { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %batch = tensor.dim %act, %c0 : tensor<?x?x10xf32> + %m = tensor.dim %act, %c1 : tensor<?x?x10xf32> + %init_broadcast = tensor.empty(%batch) : tensor<?x10x10xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) + outs(%init_broadcast : tensor<?x10x10xf32>) dimensions = [0] + %init_out = tensor.empty(%batch, %m) : tensor<?x?x10xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<?x?x10xf32>) -> tensor<?x?x10xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<?x?x10xf32>, tensor<?x10x10xf32>) + outs(%fill : tensor<?x?x10xf32>) -> tensor<?x?x10xf32> + util.return %result : tensor<?x?x10xf32> +} +// CHECK-LABEL: @broadcast_rhs_dynamic +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<?x?x10xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<10x10xf32> +// CHECK-NOT: linalg.broadcast +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<?x?x10xf32>, tensor<10x10xf32>) + +// ----- + +// The generic form of a broadcast (after generalization) folds the same way. +util.func public @generic_broadcast_rhs(%act: tensor<4x10x10xf32>, %weight: tensor<10x10xf32>) -> tensor<4x10x10xf32> { + %init_broadcast = tensor.empty() : tensor<4x10x10xf32> + %broadcast = linalg.generic { + indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d2)>, + affine_map<(d0, d1, d2) -> (d0, d1, d2)>], + iterator_types = ["parallel", "parallel", "parallel"] + } ins(%weight : tensor<10x10xf32>) outs(%init_broadcast : tensor<4x10x10xf32>) { + ^bb0(%in: f32, %out: f32): + linalg.yield %in : f32 + } -> tensor<4x10x10xf32> + %init_out = tensor.empty() : tensor<4x10x10xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) + outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + util.return %result : tensor<4x10x10xf32> +} +// CHECK-LABEL: @generic_broadcast_rhs +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x10x10xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<10x10xf32> +// CHECK-NOT: linalg.generic +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x10x10xf32>, tensor<10x10xf32>) + +// ----- + +// A broadcast on the LHS folds into the LHS map. +util.func public @broadcast_lhs(%lhs: tensor<10x8xf32>, %rhs: tensor<4x8x6xf32>) -> tensor<4x10x6xf32> { + %init_broadcast = tensor.empty() : tensor<4x10x8xf32> + %broadcast = linalg.broadcast ins(%lhs : tensor<10x8xf32>) + outs(%init_broadcast : tensor<4x10x8xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x10x6xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> + %result = linalg.batch_matmul ins(%broadcast, %rhs : tensor<4x10x8xf32>, tensor<4x8x6xf32>) + outs(%fill : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> + util.return %result : tensor<4x10x6xf32> +} +// CHECK-LABEL: @broadcast_lhs +// CHECK-SAME: %[[LHS:[a-zA-Z0-9]+]]: tensor<10x8xf32>, %[[RHS:[a-zA-Z0-9]+]]: tensor<4x8x6xf32> +// CHECK-NOT: linalg.broadcast +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[LHS]], %[[RHS]] : tensor<10x8xf32>, tensor<4x8x6xf32>) + +// ----- + +// A transposed LHS does not matter: the RHS broadcast still folds. +util.func public @broadcast_rhs_transpose_a(%act: tensor<4x10x8xf32>, %weight: tensor<10x6xf32>) -> tensor<4x8x6xf32> { + %init_broadcast = tensor.empty() : tensor<4x10x6xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<10x6xf32>) + outs(%init_broadcast : tensor<4x10x6xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x8x6xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> + %result = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, k, m)>, + affine_map<(b, m, n, k) -> (b, k, n)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast : tensor<4x10x8xf32>, tensor<4x10x6xf32>) + outs(%fill : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> + util.return %result : tensor<4x8x6xf32> +} +// CHECK-LABEL: @broadcast_rhs_transpose_a +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x10x8xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<10x6xf32> +// CHECK-NOT: linalg.broadcast +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d3, d1)>, affine_map<(d0, d1, d2, d3) -> (d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x10x8xf32>, tensor<10x6xf32>) + +// ----- + +// A broadcast [N, K] weight cannot be expressed as a batch_matmul broadcast +// map, so the contraction is carried by a generic with the folded map. +util.func public @broadcast_rhs_transpose_b(%act: tensor<4x8x10xf32>, %weight: tensor<6x10xf32>) -> tensor<4x8x6xf32> { + %init_broadcast = tensor.empty() : tensor<4x6x10xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<6x10xf32>) + outs(%init_broadcast : tensor<4x6x10xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x8x6xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> + %result = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, + affine_map<(b, m, n, k) -> (b, n, k)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast : tensor<4x8x10xf32>, tensor<4x6x10xf32>) + outs(%fill : tensor<4x8x6xf32>) -> tensor<4x8x6xf32> + util.return %result : tensor<4x8x6xf32> +} +// CHECK-LABEL: @broadcast_rhs_transpose_b +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x8x10xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<6x10xf32> +// CHECK-NOT: linalg.broadcast +// CHECK-NOT: linalg.batch_matmul +// CHECK: linalg.generic +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: iterator_types = ["parallel", "parallel", "parallel", "reduction"] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x8x10xf32>, tensor<6x10xf32>) +// CHECK: arith.mulf +// CHECK: arith.addf + +// ----- + +// A generic that broadcasts and transposes (transpose propagation fuses the +// two) is handled by composing its map: here the weight is [N, K] again. +util.func public @generic_broadcast_transpose_rhs(%act: tensor<4x10x8xf32>, %weight: tensor<6x8xf32>) -> tensor<4x10x6xf32> { + %init_broadcast = tensor.empty() : tensor<4x8x6xf32> + %broadcast_transpose = linalg.generic { + indexing_maps = [affine_map<(d0, d1, d2) -> (d2, d1)>, + affine_map<(d0, d1, d2) -> (d0, d1, d2)>], + iterator_types = ["parallel", "parallel", "parallel"] + } ins(%weight : tensor<6x8xf32>) outs(%init_broadcast : tensor<4x8x6xf32>) { + ^bb0(%in: f32, %out: f32): + linalg.yield %in : f32 + } -> tensor<4x8x6xf32> + %init_out = tensor.empty() : tensor<4x10x6xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> + %result = linalg.batch_matmul ins(%act, %broadcast_transpose : tensor<4x10x8xf32>, tensor<4x8x6xf32>) + outs(%fill : tensor<4x10x6xf32>) -> tensor<4x10x6xf32> + util.return %result : tensor<4x10x6xf32> +} +// CHECK-LABEL: @generic_broadcast_transpose_rhs +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x10x8xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<6x8xf32> +// CHECK-NOT: linalg.batch_matmul +// CHECK: linalg.generic +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d2, d3)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: iterator_types = ["parallel", "parallel", "parallel", "reduction"] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x10x8xf32>, tensor<6x8xf32>) +// CHECK: arith.mulf +// CHECK: arith.addf + +// ----- + +// A broadcast that keeps the batch dim but drops K would no longer read a +// contraction operand, so nothing changes. +util.func public @broadcast_non_batch_dim(%act: tensor<4x10x10xf32>, %weight: tensor<4x10xf32>) -> tensor<4x10x10xf32> { + %init_broadcast = tensor.empty() : tensor<4x10x10xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<4x10xf32>) + outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [1] + %init_out = tensor.empty() : tensor<4x10x10xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) + outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + util.return %result : tensor<4x10x10xf32> +} +// CHECK-LABEL: @broadcast_non_batch_dim +// CHECK: linalg.broadcast +// CHECK: linalg.batch_matmul ins( +// CHECK-NOT: indexing_maps + +// ----- + +// The broadcast stays for its other users; the batch_matmul still folds it. +util.func public @broadcast_with_other_user(%act: tensor<4x10x10xf32>, %weight: tensor<10x10xf32>) -> (tensor<4x10x10xf32>, tensor<4x10x10xf32>) { + %init_broadcast = tensor.empty() : tensor<4x10x10xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<10x10xf32>) + outs(%init_broadcast : tensor<4x10x10xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x10x10xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32>) + outs(%fill : tensor<4x10x10xf32>) -> tensor<4x10x10xf32> + util.return %result, %broadcast : tensor<4x10x10xf32>, tensor<4x10x10xf32> +} +// CHECK-LABEL: @broadcast_with_other_user +// CHECK-SAME: %[[ACT:[a-zA-Z0-9]+]]: tensor<4x10x10xf32>, %[[WEIGHT:[a-zA-Z0-9]+]]: tensor<10x10xf32> +// CHECK: %[[BROADCAST:.+]] = linalg.broadcast ins(%[[WEIGHT]] +// CHECK: linalg.batch_matmul +// CHECK-SAME: indexing_maps = [affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>, affine_map<(d0, d1, d2, d3) -> (d3, d2)>, affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)>] +// CHECK-SAME: ins(%[[ACT]], %[[WEIGHT]] : tensor<4x10x10xf32>, tensor<10x10xf32>) +// CHECK: util.return %{{.+}}, %[[BROADCAST]]
diff --git a/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul_pipeline.mlir b/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul_pipeline.mlir new file mode 100644 index 0000000..dde50ce --- /dev/null +++ b/compiler/src/iree/compiler/GlobalOptimization/test/fold_broadcast_into_batch_matmul_pipeline.mlir
@@ -0,0 +1,58 @@ +// RUN: iree-opt --split-input-file --iree-global-optimization-transformation-pipeline="data-tiling=true" --iree-global-opt-enable-early-materialization=false %s | FileCheck %s + +// The global optimization data tiling path sets encodings before dispatch +// creation, which only accepts contractions with a single M dim. A folded +// broadcast batch_matmul has two, so it is collapsed to a matmul first. + +// CHECK-LABEL: @broadcast_rhs( +// CHECK-NOT: linalg.broadcast +// CHECK-NOT: linalg.batch_matmul +// CHECK: %[[ACT_2D:.+]] = tensor.collapse_shape %{{.+}} {{\[}}[0, 1], [2]] : tensor<4x8x16xf32> into tensor<32x16xf32> +// CHECK-DAG: %[[LHS:.+]] = iree_encoding.set_encoding %[[ACT_2D]] : tensor<32x16xf32> -> tensor<32x16xf32, # +// CHECK-DAG: %[[RHS:.+]] = iree_encoding.set_encoding %{{.+}} : tensor<16x12xf32> -> tensor<16x12xf32, # +// CHECK: %[[MATMUL:.+]] = linalg.generic +// CHECK-SAME: iterator_types = ["parallel", "parallel", "reduction"] +// CHECK-SAME: ins(%[[LHS]], %[[RHS]] +// CHECK: %[[UNSET:.+]] = iree_encoding.unset_encoding %[[MATMUL]] +// CHECK: tensor.expand_shape %[[UNSET]] {{\[}}[0, 1], [2]] output_shape [4, 8, 12] +util.func public @broadcast_rhs(%act: tensor<4x8x16xf32>, %weight: tensor<16x12xf32>) -> tensor<4x8x12xf32> { + %init_broadcast = tensor.empty() : tensor<4x16x12xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<16x12xf32>) + outs(%init_broadcast : tensor<4x16x12xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x8x12xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + %result = linalg.batch_matmul ins(%act, %broadcast : tensor<4x8x16xf32>, tensor<4x16x12xf32>) + outs(%fill : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + util.return %result : tensor<4x8x12xf32> +} + +// ----- + +// A broadcast [N, K] weight is carried by a generic and takes the same path. +// CHECK-LABEL: @broadcast_rhs_transpose_b( +// CHECK-NOT: linalg.broadcast +// CHECK-NOT: linalg.transpose +// CHECK: %[[ACT_2D:.+]] = tensor.collapse_shape %{{.+}} {{\[}}[0, 1], [2]] : tensor<4x8x16xf32> into tensor<32x16xf32> +// CHECK-DAG: %[[LHS:.+]] = iree_encoding.set_encoding %[[ACT_2D]] : tensor<32x16xf32> -> tensor<32x16xf32, # +// CHECK-DAG: %[[RHS:.+]] = iree_encoding.set_encoding %{{.+}} : tensor<12x16xf32> -> tensor<12x16xf32, # +// CHECK: %[[MATMUL:.+]] = linalg.generic +// CHECK-SAME: iterator_types = ["parallel", "parallel", "reduction"] +// CHECK-SAME: ins(%[[LHS]], %[[RHS]] +// CHECK: %[[UNSET:.+]] = iree_encoding.unset_encoding %[[MATMUL]] +// CHECK: tensor.expand_shape %[[UNSET]] {{\[}}[0, 1], [2]] output_shape [4, 8, 12] +util.func public @broadcast_rhs_transpose_b(%act: tensor<4x8x16xf32>, %weight: tensor<12x16xf32>) -> tensor<4x8x12xf32> { + %init_broadcast = tensor.empty() : tensor<4x12x16xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<12x16xf32>) + outs(%init_broadcast : tensor<4x12x16xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<4x8x12xf32> + %cst = arith.constant 0.0 : f32 + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + %result = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, + affine_map<(b, m, n, k) -> (b, n, k)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast : tensor<4x8x16xf32>, tensor<4x12x16xf32>) + outs(%fill : tensor<4x8x12xf32>) -> tensor<4x8x12xf32> + util.return %result : tensor<4x8x12xf32> +}
diff --git a/tests/e2e/regression/BUILD.bazel b/tests/e2e/regression/BUILD.bazel index 79227fb..0486049 100644 --- a/tests/e2e/regression/BUILD.bazel +++ b/tests/e2e/regression/BUILD.bazel
@@ -71,7 +71,7 @@ iree_check_single_backend_test_suite( name = "check_regression_llvm-cpu", srcs = [ - "broadcast_batch_matmul_to_matmul.mlir", + "broadcast_batch_matmul.mlir", "layernorm.mlir", "pack_pad_transpose_1x9_into_2x1x8x4_issue_12546.mlir", "split_reduction_using_tiling.mlir",
diff --git a/tests/e2e/regression/CMakeLists.txt b/tests/e2e/regression/CMakeLists.txt index 9d6799c..6ccdaea 100644 --- a/tests/e2e/regression/CMakeLists.txt +++ b/tests/e2e/regression/CMakeLists.txt
@@ -54,7 +54,7 @@ NAME check_regression_llvm-cpu SRCS - "broadcast_batch_matmul_to_matmul.mlir" + "broadcast_batch_matmul.mlir" "i1_inlined_constant.mlir" "layernorm.mlir" "linalg_ops.mlir"
diff --git a/tests/e2e/regression/broadcast_batch_matmul.mlir b/tests/e2e/regression/broadcast_batch_matmul.mlir new file mode 100644 index 0000000..043c92d --- /dev/null +++ b/tests/e2e/regression/broadcast_batch_matmul.mlir
@@ -0,0 +1,121 @@ +// End-to-end correctness test for folding a batch-dim broadcast into a +// batch_matmul's indexing maps (--iree-global-opt-fold-broadcast-into-batch-matmul), +// which runs as part of the default global optimization pipeline, and for the +// collapse of the resulting contraction into a plain matmul during dispatch +// creation. Each %ref hides its broadcast behind an optimization barrier so +// the fold does not apply to it. + +func.func @broadcast_batch_matmul() { + %act = util.unfoldable_constant dense<[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], + [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]]> : tensor<2x2x3xf32> + %weight = util.unfoldable_constant dense<[[1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 1.0], + [0.0, 0.0, 1.0, 1.0]]> : tensor<3x4xf32> + %cst = arith.constant 0.0 : f32 + %init_broadcast = tensor.empty() : tensor<2x3x4xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<3x4xf32>) + outs(%init_broadcast : tensor<2x3x4xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<2x2x4xf32> + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %opt = linalg.batch_matmul ins(%act, %broadcast : tensor<2x2x3xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x3x4xf32> + %ref = linalg.batch_matmul ins(%act, %broadcast_ref : tensor<2x2x3xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> + return +} + +func.func @broadcast_batch_matmul_transpose_b() { + %act = util.unfoldable_constant dense<[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], + [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]]> : tensor<2x2x3xf32> + %weight = util.unfoldable_constant dense<[[1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + [1.0, 1.0, 1.0]]> : tensor<4x3xf32> + %cst = arith.constant 0.0 : f32 + %init_broadcast = tensor.empty() : tensor<2x4x3xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<4x3xf32>) + outs(%init_broadcast : tensor<2x4x3xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<2x2x4xf32> + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %opt = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, + affine_map<(b, m, n, k) -> (b, n, k)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast : tensor<2x2x3xf32>, tensor<2x4x3xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x4x3xf32> + %ref = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, + affine_map<(b, m, n, k) -> (b, n, k)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast_ref : tensor<2x2x3xf32>, tensor<2x4x3xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> + return +} + +func.func @broadcast_batch_matmul_transpose_a() { + %act = util.unfoldable_constant dense<[[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]], + [[7.0, 10.0], [8.0, 11.0], [9.0, 12.0]]]> : tensor<2x3x2xf32> + %weight = util.unfoldable_constant dense<[[1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 1.0], + [0.0, 0.0, 1.0, 1.0]]> : tensor<3x4xf32> + %cst = arith.constant 0.0 : f32 + %init_broadcast = tensor.empty() : tensor<2x3x4xf32> + %broadcast = linalg.broadcast ins(%weight : tensor<3x4xf32>) + outs(%init_broadcast : tensor<2x3x4xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<2x2x4xf32> + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %opt = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, k, m)>, + affine_map<(b, m, n, k) -> (b, k, n)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast : tensor<2x3x2xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x3x4xf32> + %ref = linalg.batch_matmul + indexing_maps = [affine_map<(b, m, n, k) -> (b, k, m)>, + affine_map<(b, m, n, k) -> (b, k, n)>, + affine_map<(b, m, n, k) -> (b, m, n)>] + ins(%act, %broadcast_ref : tensor<2x3x2xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> + return +} + +func.func @broadcast_batch_matmul_lhs() { + %act = util.unfoldable_constant dense<[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]> : tensor<2x3xf32> + %weight = util.unfoldable_constant dense<[[[1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 1.0], + [0.0, 0.0, 1.0, 1.0]], + [[2.0, 0.0, 0.0, 1.0], + [0.0, 2.0, 0.0, 1.0], + [0.0, 0.0, 2.0, 1.0]]]> : tensor<2x3x4xf32> + %cst = arith.constant 0.0 : f32 + %init_broadcast = tensor.empty() : tensor<2x2x3xf32> + %broadcast = linalg.broadcast ins(%act : tensor<2x3xf32>) + outs(%init_broadcast : tensor<2x2x3xf32>) dimensions = [0] + %init_out = tensor.empty() : tensor<2x2x4xf32> + %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %opt = linalg.batch_matmul ins(%broadcast, %weight : tensor<2x2x3xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x2x3xf32> + %ref = linalg.batch_matmul ins(%broadcast_ref, %weight : tensor<2x2x3xf32>, tensor<2x3x4xf32>) + outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> + + check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> + return +}
diff --git a/tests/e2e/regression/broadcast_batch_matmul_to_matmul.mlir b/tests/e2e/regression/broadcast_batch_matmul_to_matmul.mlir deleted file mode 100644 index 316d6f3..0000000 --- a/tests/e2e/regression/broadcast_batch_matmul_to_matmul.mlir +++ /dev/null
@@ -1,60 +0,0 @@ -// End-to-end correctness test for the batch-matmul-to-matmul pass -// (--iree-global-opt-convert-batch-matmul-to-matmul), which runs as -// part of the default global optimization pipeline. - -func.func @broadcast_batch_matmul() { - %act = util.unfoldable_constant dense<[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], - [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]]> : tensor<2x2x3xf32> - %weight = util.unfoldable_constant dense<[[1.0, 0.0, 0.0, 1.0], - [0.0, 1.0, 0.0, 1.0], - [0.0, 0.0, 1.0, 1.0]]> : tensor<3x4xf32> - %cst = arith.constant 0.0 : f32 - %init_broadcast = tensor.empty() : tensor<2x3x4xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<3x4xf32>) - outs(%init_broadcast : tensor<2x3x4xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<2x2x4xf32> - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - %opt = linalg.batch_matmul ins(%act, %broadcast : tensor<2x2x3xf32>, tensor<2x3x4xf32>) - outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x3x4xf32> - %ref = linalg.batch_matmul ins(%act, %broadcast_ref : tensor<2x2x3xf32>, tensor<2x3x4xf32>) - outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> - return -} - -func.func @broadcast_batch_matmul_transpose_b() { - %act = util.unfoldable_constant dense<[[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], - [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]]> : tensor<2x2x3xf32> - %weight = util.unfoldable_constant dense<[[1.0, 0.0, 0.0], - [0.0, 1.0, 0.0], - [0.0, 0.0, 1.0], - [1.0, 1.0, 1.0]]> : tensor<4x3xf32> - %cst = arith.constant 0.0 : f32 - %init_broadcast = tensor.empty() : tensor<2x4x3xf32> - %broadcast = linalg.broadcast ins(%weight : tensor<4x3xf32>) - outs(%init_broadcast : tensor<2x4x3xf32>) dimensions = [0] - %init_out = tensor.empty() : tensor<2x2x4xf32> - %fill = linalg.fill ins(%cst : f32) outs(%init_out : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - %opt = linalg.batch_matmul - indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, - affine_map<(b, m, n, k) -> (b, n, k)>, - affine_map<(b, m, n, k) -> (b, m, n)>] - ins(%act, %broadcast : tensor<2x2x3xf32>, tensor<2x4x3xf32>) - outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - %broadcast_ref = util.optimization_barrier %broadcast : tensor<2x4x3xf32> - %ref = linalg.batch_matmul - indexing_maps = [affine_map<(b, m, n, k) -> (b, m, k)>, - affine_map<(b, m, n, k) -> (b, n, k)>, - affine_map<(b, m, n, k) -> (b, m, n)>] - ins(%act, %broadcast_ref : tensor<2x2x3xf32>, tensor<2x4x3xf32>) - outs(%fill : tensor<2x2x4xf32>) -> tensor<2x2x4xf32> - - check.expect_almost_eq(%opt, %ref) : tensor<2x2x4xf32> - return -}