[LinalgExt] Add group_matmul and group_mmt4d ops (#24909) # What & why This PR introduces a new `group_matmul` operation, to be the IREE equivalent of Torch's [grouped_mm](https://docs.pytorch.org/docs/main/generated/torch.nn.functional.grouped_mm.html). It's purpose is to enable efficient inference of Mixture-of-Experts models. The op is superficially similar to `linalg.matmul` and `linalg.batch_matmul`, but cannot be expressed as a pure `linalg.generic` without masking inactive elements, so I believe it belongs here in LinalgExt. The description in LinalgExtOps.td gives more info. # How 1) We add the standard matmul encodings to LHS, RHS and result of our op in SetEncoding.cpp 2) We define an auxillary `group_mmt4d` op - the grouped equivalent of `mmt4d` 3) In MaterializeEncodingPatterns.cpp, we convert `group_matmul` to `group_mmt4d` 4) We implement the tiling interface for `group_mmt4d` 5) After workgroup tiling, we add a `DecomposeGroupMmt4DPass`, which turns `group_mmt4d` into `mmt4d` + some extra ops a) if all input rows of a tile belong to the same expert, we just slice + `mmt4d` b) otherwise, we loop over experts; for each of them we mask out rows that don't belong to it # Performance Preliminary benchmarks have shown speed close to a matmul of comparable shape. This is expected since: - decomposition of `group_mmt4d` happens after workgroup tiling, so the op turns into a single dispatch - there is no control flow on the host side - the number of tiles containing a boundary between experts is limited: (5a) is much more common than (5b) - only the weights of the active experts need are accessed - no wasted memory bandwidth # Known shortcomings / future work - only LLVMCPU backend is supported currently - dynamic tile sizes (RVV & SVE) not implemented - for compilation to succeed, you must have enabled: - data tiling - distribution tiling (on by default) - LHS and RHS must be floats - integer operands could result in an identity layout (not implemented) - the attribute placed on `group_mmt4d` to support the narrow-N transpose is an ugly hack - this will no longer be needed once we can lower to `inner_tiled` instead - both ops implemented here could possibly be unified into some kind of `group_contract` - by analogy to [linalg.contract](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgcontract-linalgcontractop) - instead of passing in expert offsets, perhaps LHS should just be a proper [ragged tensor](https://iree.dev/reference/mlir-dialects/TensorExt/#iree_tensor_extcast_to_ragged_shape-tensorextcasttoraggedshapeop)? - this feature is still work-in-progress IIUC - gather/scatter should be fused with this op Assisted-by: Codex Signed-off-by: Maksymilian B. Knust <knust@roofline.ai>
diff --git a/compiler/src/iree/compiler/Codegen/Common/MaterializeEncodingPatterns.cpp b/compiler/src/iree/compiler/Codegen/Common/MaterializeEncodingPatterns.cpp index 02d329b..ee3e315 100644 --- a/compiler/src/iree/compiler/Codegen/Common/MaterializeEncodingPatterns.cpp +++ b/compiler/src/iree/compiler/Codegen/Common/MaterializeEncodingPatterns.cpp
@@ -13,6 +13,7 @@ #include "iree/compiler/Codegen/Utils/EncodingUtils.h" #include "iree/compiler/Dialect/Encoding/IR/EncodingOps.h" #include "iree/compiler/Dialect/HAL/IR/HALOps.h" +#include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "iree/compiler/Dialect/TensorExt/IR/TensorExtOps.h" #include "iree/compiler/Dialect/Util/IR/UtilOps.h" #include "llvm/Support/DebugLog.h" @@ -804,6 +805,50 @@ } }; +struct MaterializeGroupMatmulOp + : OpConversionPattern<IREE::LinalgExt::GroupMatmulOp> { + using Base::Base; + + LogicalResult + matchAndRewrite(IREE::LinalgExt::GroupMatmulOp op, + IREE::LinalgExt::GroupMatmulOp::Adaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + auto converter = getTypeConverter<MaterializeEncodingTypeConverter>(); + + // FIXME: not supported currently, but ought to be in the future + for (Value operand : + {op.getInput(), op.getExpertWeights(), op.getOutput()}) { + auto type = cast<RankedTensorType>(operand.getType()); + if (IREE::Codegen::isIdentityLayout(converter->getEncodingInfo(type))) { + return op.emitOpError( + "identity layouts are unsupported for group_matmul encoding " + "materialization; packed layouts are required"); + } + } + + Type resultType = converter->convertType(op.getResult().getType()); + if (!resultType) { + return failure(); + } + + auto outputType = cast<RankedTensorType>(op.getOutput().getType()); + Value rowStride = + tensor::DimOp::create(rewriter, op.getLoc(), adaptor.getInput(), 2); + auto materialized = IREE::LinalgExt::GroupMmt4DOp::create( + rewriter, op.getLoc(), resultType, adaptor.getInput(), + adaptor.getExpertWeights(), adaptor.getExpertOffsets(), + adaptor.getRowBase(), rowStride, adaptor.getOutput()); + + if (converter->getEncodingInfo(outputType).outerDimsPerm == + ArrayRef<int64_t>{1, 0}) { + materialized.setTransposed(true); + } + + rewriter.replaceOp(op, materialized.getResult()); + return success(); + } +}; + static bool isRankedTensorTypeWithEncoding(Type type) { auto rankedTensorType = dyn_cast<RankedTensorType>(type); if (!rankedTensorType) { @@ -873,13 +918,13 @@ isRankedTensorTypeWithEncoding); }); - patterns.insert<MaterializeLinalgOp, SetEncodingOpLoweringConversion, - UnsetEncodingOpLoweringConversion, - MaterializeOperation<tensor::EmptyOp>, - MaterializeOptimizationBarrierOp, - MaterializeTensorExtDispatchTensorLoadOp, - MaterializeTensorExtDispatchTensorStoreOp, - MaterializeInterfaceBindingEncoding, MaterializeFuncReturnOp>( + patterns.insert< + MaterializeLinalgOp, MaterializeGroupMatmulOp, + SetEncodingOpLoweringConversion, UnsetEncodingOpLoweringConversion, + MaterializeOperation<tensor::EmptyOp>, MaterializeOptimizationBarrierOp, + MaterializeTensorExtDispatchTensorLoadOp, + MaterializeTensorExtDispatchTensorStoreOp, + MaterializeInterfaceBindingEncoding, MaterializeFuncReturnOp>( typeConverter, context); };
diff --git a/compiler/src/iree/compiler/Codegen/ExternalInterfaces/test/materialize_encoding_invalid.mlir b/compiler/src/iree/compiler/Codegen/ExternalInterfaces/test/materialize_encoding_invalid.mlir index fe0df34..0225878 100644 --- a/compiler/src/iree/compiler/Codegen/ExternalInterfaces/test/materialize_encoding_invalid.mlir +++ b/compiler/src/iree/compiler/Codegen/ExternalInterfaces/test/materialize_encoding_invalid.mlir
@@ -1,5 +1,5 @@ /// Test that layout compatibility checks are correctly applied when encoding -/// materialization is run on unsupported linalg.generic + encoding combinations. +/// materialization is run on unsupported operation and encoding combinations. /// To avoid any doubt, the examples tested here are synthetic and not expected from /// data tiling/fusion. Testing against these examples enforces cleaner diagnostics /// from codegen passes. @@ -93,3 +93,33 @@ } -> (tensor<4x32xf32, #swizzled_encoding>, tensor<32x4xf32, #output_encoding>) return %result#0, %result#1 : tensor<4x32xf32, #swizzled_encoding>, tensor<32x4xf32, #output_encoding> } + +// ----- + +// Legacy x86_64 resolution has no f64 tile and returns identity layouts. +// Explicit f64 types keep this test independent of input demotion settings. +#lhs_map = affine_map<(d0, d1, d2) -> (d0, d2)> +#rhs_map = affine_map<(d0, d1, d2) -> (d1, d2)> +#out_map = affine_map<(d0, d1, d2) -> (d0, d1)> +#batch_lhs_map = affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)> +#batch_rhs_map = affine_map<(d0, d1, d2, d3) -> (d0, d3, d2)> +#batch_out_map = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2)> +#input_encoding = #iree_encoding.encoding<operand_index = 0, op_type = matmul, element_types = [f64, f64, f64], user_indexing_maps = [#lhs_map, #rhs_map, #out_map], iteration_sizes = [3, 1, 2]> +#weights_encoding = #iree_encoding.encoding<operand_index = 1, op_type = matmul, element_types = [f64, f64, f64], user_indexing_maps = [#batch_lhs_map, #batch_rhs_map, #batch_out_map], iteration_sizes = [2, 3, 1, 2]> +#output_encoding = #iree_encoding.encoding<operand_index = 2, op_type = matmul, element_types = [f64, f64, f64], user_indexing_maps = [#lhs_map, #rhs_map, #out_map], iteration_sizes = [3, 1, 2]> +#target = #hal.executable.target<"llvm-cpu", "xyz", {cpu_features = "+avx2,+fma", iree.encoding.resolver = #iree_cpu.cpu_encoding_resolver<>, target_triple = "x86_64-unknown-linux-gnu"}> +// expected-error @+1 {{'func.func' op materialization failed}} +func.func @group_matmul_f64_identity_x86_64( + %input: tensor<3x2xf64, #input_encoding>, + %weights: tensor<2x2x1xf64, #weights_encoding>, + %offsets: tensor<2xi64>, %row_base: index, + %output: tensor<3x1xf64, #output_encoding>) + -> tensor<3x1xf64, #output_encoding> + attributes {hal.executable.target = #target} { + // expected-error @+2 {{identity layouts are unsupported for group_matmul encoding materialization; packed layouts are required}} + // expected-error @+1 {{failed to legalize operation 'iree_linalg_ext.group_matmul' that was explicitly marked illegal}} + %result = iree_linalg_ext.group_matmul + ins(%input, %weights, %offsets, %row_base : tensor<3x2xf64, #input_encoding>, tensor<2x2x1xf64, #weights_encoding>, tensor<2xi64>, index) + outs(%output : tensor<3x1xf64, #output_encoding>) -> tensor<3x1xf64, #output_encoding> + return %result : tensor<3x1xf64, #output_encoding> +}
diff --git a/compiler/src/iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp b/compiler/src/iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp index 8edc9d1..a41d240 100644 --- a/compiler/src/iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp +++ b/compiler/src/iree/compiler/Codegen/Interfaces/PartitionableLoopsInterface.cpp
@@ -225,6 +225,21 @@ } }; +template <typename OpTy> +struct GroupMatmulPartitionableLoops + : PartitionableLoopsInterface::ExternalModel< + GroupMatmulPartitionableLoops<OpTy>, OpTy> { + llvm::SmallVector<unsigned> + getPartitionableLoops(Operation *, + std::optional<unsigned> maxNumPartitionedLoops) const { + SmallVector<unsigned> loops{0, 1}; + if (maxNumPartitionedLoops && *maxNumPartitionedLoops < loops.size()) { + loops.erase(loops.begin(), loops.end() - *maxNumPartitionedLoops); + } + return loops; + } +}; + /// Registers the `LinalgOpPartitionableLoops` model for all Linalg ops. This /// needs to be done on a op-by-op basis since registration is on an op-by-op /// basis. @@ -305,6 +320,10 @@ AllParallelAsPartitionableLoops<IREE::LinalgExt::MapStoreOp>>(*ctx); IREE::LinalgExt::MapLoadOp::attachInterface< AllParallelAsPartitionableLoops<IREE::LinalgExt::MapLoadOp>>(*ctx); + IREE::LinalgExt::GroupMatmulOp::attachInterface< + GroupMatmulPartitionableLoops<IREE::LinalgExt::GroupMatmulOp>>(*ctx); + IREE::LinalgExt::GroupMmt4DOp::attachInterface< + GroupMatmulPartitionableLoops<IREE::LinalgExt::GroupMmt4DOp>>(*ctx); }); registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) { tensor::PadOp::attachInterface<
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/BUILD.bazel b/compiler/src/iree/compiler/Codegen/LLVMCPU/BUILD.bazel index 4e81511..90f2e5b 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMCPU/BUILD.bazel +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/BUILD.bazel
@@ -62,6 +62,7 @@ "LLVMCPUAssignImportOrdinals.cpp", "LLVMCPUAssignWorkgroupLocalMemory.cpp", "LLVMCPUCheckIRBeforeLLVMConversion.cpp", + "LLVMCPUDecomposeGroupMmt4D.cpp", "LLVMCPUEmitVectorizationRemarks.cpp", "LLVMCPULinkExecutables.cpp", "LLVMCPULowerExecutableTarget.cpp",
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/CMakeLists.txt b/compiler/src/iree/compiler/Codegen/LLVMCPU/CMakeLists.txt index d20f744..910c739 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMCPU/CMakeLists.txt +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/CMakeLists.txt
@@ -59,6 +59,7 @@ "LLVMCPUAssignImportOrdinals.cpp" "LLVMCPUAssignWorkgroupLocalMemory.cpp" "LLVMCPUCheckIRBeforeLLVMConversion.cpp" + "LLVMCPUDecomposeGroupMmt4D.cpp" "LLVMCPUEmitVectorizationRemarks.cpp" "LLVMCPULinkExecutables.cpp" "LLVMCPULowerExecutableTarget.cpp"
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp b/compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp index 2248a21..1a27fdc 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp
@@ -1826,11 +1826,10 @@ } static IREE::Codegen::LoweringConfigAttrInterface -getMmt4dLoweringConfig(linalg::LinalgOp op, DictionaryAttr targetConfig) { - Value lhs = op.getDpsInputs()[0]; - Value rhs = op.getDpsInputs()[1]; - Value acc = op.getDpsInits()[0]; - +getMmt4dLoweringConfig(Operation *op, Value lhs, Value rhs, Value acc, + int mmt4dDimBase, DictionaryAttr targetConfig, + int64_t m0, int64_t n0, int64_t k0, int64_t m1, + int64_t n1, int64_t k1) { const ShapedType lhsType = cast<ShapedType>(lhs.getType()); const ShapedType rhsType = cast<ShapedType>(rhs.getType()); const ShapedType accType = cast<ShapedType>(acc.getType()); @@ -1838,20 +1837,11 @@ const int rhsTypeBits = rhsType.getElementTypeBitWidth(); const int accTypeBits = accType.getElementTypeBitWidth(); - SmallVector<int64_t> distTileSizes(op.getNumLoops(), 0); - const int mmt4dDimBase = isa<linalg::BatchMmt4DOp>(op) ? 1 : 0; + auto tilingOp = cast<TilingInterface>(op); + SmallVector<int64_t> distTileSizes(tilingOp.getLoopIteratorTypes().size(), 0); if (mmt4dDimBase == 1) { distTileSizes[0] = 1; } - const auto lhsShape = lhsType.getShape(); - const auto rhsShape = rhsType.getShape(); - int64_t M0 = lhsShape[mmt4dDimBase + 2]; - int64_t N0 = rhsShape[mmt4dDimBase + 2]; - int64_t K0 = lhsShape[mmt4dDimBase + 3]; - int64_t M1 = lhsShape[mmt4dDimBase + 0]; - int64_t N1 = rhsShape[mmt4dDimBase + 0]; - int64_t K1 = lhsShape[mmt4dDimBase + 1]; - // // Part 1: set the vectorization tile sizes, vecTileSizes. // Normally these are just the M0, N0, K0 dimension sizes, as long as these @@ -1862,34 +1852,37 @@ // tile sizes. // - unsigned numLoops = op.getNumLoops(); + unsigned numLoops = tilingOp.getLoopIteratorTypes().size(); SmallVector<int64_t> vecTileSizes(numLoops, 1); assert(vecTileSizes.size() == mmt4dDimBase + 6); - vecTileSizes[mmt4dDimBase + 3] = M0; - vecTileSizes[mmt4dDimBase + 4] = N0; - vecTileSizes[mmt4dDimBase + 5] = K0; + vecTileSizes[mmt4dDimBase + 3] = m0; + vecTileSizes[mmt4dDimBase + 4] = n0; + vecTileSizes[mmt4dDimBase + 5] = k0; IREE::Codegen::ScalableTileFlags vecScalableTileFlags(mmt4dDimBase + 6, false); bool scalableTilesFound = false; // If scalable vectorization is enabled, adjust the vector tile sizes and the // corresponding scalable flags. - if (targetConfig && isScalableVectorizationEnabled()) { + if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op); + linalgOp && targetConfig && isScalableVectorizationEnabled()) { scalableTilesFound = adjustVectorSizesForScalableVectorization( - op, targetConfig, M0, N0, vecTileSizes, vecScalableTileFlags); + linalgOp, targetConfig, m0, n0, vecTileSizes, vecScalableTileFlags); } // In the existence of scalable tiles, we do not yet support limiting vector // sizes as this assumes static tile sizes. // TODO: extend this mechanism to handle _scalable_ tile sizes as well. if (!scalableTilesFound) { - limitVectorTileSizes(op, vecTileSizes); + if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) { + limitVectorTileSizes(linalgOp, vecTileSizes); + } } // Query back the final M0, N0, K0 values. - M0 = vecTileSizes[mmt4dDimBase + 3]; - N0 = vecTileSizes[mmt4dDimBase + 4]; - K0 = vecTileSizes[mmt4dDimBase + 5]; + m0 = vecTileSizes[mmt4dDimBase + 3]; + n0 = vecTileSizes[mmt4dDimBase + 4]; + k0 = vecTileSizes[mmt4dDimBase + 5]; // By now, if any of these is still dynamic, that's an internal bug. - assert(!ShapedType::isDynamic(M0) && !ShapedType::isDynamic(N0) && - !ShapedType::isDynamic(K0)); + assert(!ShapedType::isDynamic(m0) && !ShapedType::isDynamic(n0) && + !ShapedType::isDynamic(k0)); // // Part 2: set the distribution tile sizes, distTileSizes. @@ -1900,24 +1893,24 @@ // const int64_t kTypicalDynamicSize = 1024; - if (ShapedType::isDynamic(M1)) { - M1 = kTypicalDynamicSize / M0; + if (ShapedType::isDynamic(m1)) { + m1 = kTypicalDynamicSize / m0; } - if (ShapedType::isDynamic(N1)) { - N1 = kTypicalDynamicSize / N0; + if (ShapedType::isDynamic(n1)) { + n1 = kTypicalDynamicSize / n0; } - if (ShapedType::isDynamic(K1)) { - K1 = kTypicalDynamicSize / K0; + if (ShapedType::isDynamic(k1)) { + k1 = kTypicalDynamicSize / k0; } // By now, all 6 size parameters {M,N,K}{0,1} are static. - assert(!ShapedType::isDynamic(M1) && !ShapedType::isDynamic(N1) && - !ShapedType::isDynamic(K1)); + assert(!ShapedType::isDynamic(m1) && !ShapedType::isDynamic(n1) && + !ShapedType::isDynamic(k1)); - const int64_t M = M0 * M1; - const int64_t N = N0 * N1; + const int64_t M = m0 * m1; + const int64_t N = n0 * n1; - const SmallVector<std::pair<int64_t, int64_t>> divisorsOfM1 = getDivisors(M1); - const SmallVector<std::pair<int64_t, int64_t>> divisorsOfN1 = getDivisors(N1); + const SmallVector<std::pair<int64_t, int64_t>> divisorsOfM1 = getDivisors(m1); + const SmallVector<std::pair<int64_t, int64_t>> divisorsOfN1 = getDivisors(n1); // Cost model. auto evalCost = [=](int64_t numTilesM, int64_t numTilesN) -> int64_t { @@ -1933,15 +1926,15 @@ int64_t selectedTileM = 1; int64_t selectedTileN = 1; - int64_t selectedCost = evalCost(M1, N1); + int64_t selectedCost = evalCost(m1, n1); // Iterate over all candidate tile shapes, which are the divisors of (M1, N1). for (auto [tileM, numTilesM] : divisorsOfM1) { for (auto [tileN, numTilesN] : divisorsOfN1) { // Compute candidate tile size in bytes. - int64_t lhsBytes = tileM * M0 * K1 * K0 * lhsTypeBits / 8; - int64_t rhsBytes = tileN * N0 * K1 * K0 * rhsTypeBits / 8; - int64_t accBytes = tileM * N0 * tileN * M0 * accTypeBits / 8; + int64_t lhsBytes = tileM * m0 * k1 * k0 * lhsTypeBits / 8; + int64_t rhsBytes = tileN * n0 * k1 * k0 * rhsTypeBits / 8; + int64_t accBytes = tileM * n0 * tileN * m0 * accTypeBits / 8; // Adjust the tile size to favor fitting whole matrices in one tile. if (numTilesM == 1) { lhsBytes *= clMatmulTileUndercountWholeMatrix; @@ -1975,6 +1968,21 @@ return generator.generateCPULoweringConfig(); } +static IREE::Codegen::LoweringConfigAttrInterface +getMmt4dLoweringConfig(linalg::LinalgOp op, DictionaryAttr targetConfig) { + Value lhs = op.getDpsInputs()[0]; + Value rhs = op.getDpsInputs()[1]; + Value acc = op.getDpsInits()[0]; + const auto lhsShape = cast<ShapedType>(lhs.getType()).getShape(); + const auto rhsShape = cast<ShapedType>(rhs.getType()).getShape(); + const int mmt4dDimBase = isa<linalg::BatchMmt4DOp>(op) ? 1 : 0; + return getMmt4dLoweringConfig( + op, lhs, rhs, acc, mmt4dDimBase, targetConfig, lhsShape[mmt4dDimBase + 2], + rhsShape[mmt4dDimBase + 2], lhsShape[mmt4dDimBase + 3], + lhsShape[mmt4dDimBase + 0], rhsShape[mmt4dDimBase + 0], + lhsShape[mmt4dDimBase + 1]); +} + /// Sets the lowering configuration for dispatch region for linalg.mmt4d /// root op static LogicalResult setRootConfig(mlir::FunctionOpInterface entryPointFn, @@ -3035,6 +3043,33 @@ CPUPipeline::DoubleTilingExpert)); } +static LogicalResult setRootConfig(mlir::FunctionOpInterface entryPointFn, + IREE::LinalgExt::GroupMmt4DOp op) { + assert(!getLoweringConfig(op) && "expected lowering_config is not set"); + + auto inputType = cast<ShapedType>(op.getInput().getType()); + auto outputType = cast<ShapedType>(op.getOutput().getType()); + + ArrayRef<int64_t> outputPermutation = op.getOutputPermutation(); + + int64_t M0 = inputType.getDimSize(2); + int64_t N0 = outputType.getDimSize(outputPermutation[3]); + int64_t K0 = inputType.getDimSize(3); + if (!ShapedType::isStatic(M0) || !ShapedType::isStatic(N0) || + !ShapedType::isStatic(K0)) { + return op.emitOpError( + "CPU lowering does not support dynamic or scalable inner tiles"); + } + + auto loweringConfig = getMmt4dLoweringConfig( + op, op.getInput(), op.getExpertWeights(), op.getOutput(), 0, + /*targetConfig=*/nullptr, M0, N0, K0, inputType.getDimSize(0), + outputType.getDimSize(outputPermutation[1]), inputType.getDimSize(1)); + return setOpConfigAndEntryPointFnTranslation( + entryPointFn, op, loweringConfig, + getCPUTranslationInfo(op.getContext(), CPUPipeline::Mmt4dTilingExpert)); +} + /// Set the default configuration for operations that implement the /// `TiledOpInterface`. static LogicalResult setRootConfig(mlir::FunctionOpInterface entryPointFn, @@ -3233,8 +3268,9 @@ initCPULaunchConfig); }) .Case<IREE::LinalgExt::OnlineAttentionOp, IREE::LinalgExt::FftOp, - IREE::LinalgExt::GatherOp, linalg::PackOp, tensor::PadOp, - linalg::UnPackOp, linalg::Mmt4DOp, linalg::BatchMmt4DOp, + IREE::LinalgExt::GatherOp, IREE::LinalgExt::GroupMmt4DOp, + linalg::PackOp, tensor::PadOp, linalg::UnPackOp, + linalg::Mmt4DOp, linalg::BatchMmt4DOp, IREE::Codegen::InnerTiledOp>( [&](auto op) { return setRootConfig(entryPointFn, op); }) .Case<IREE::LinalgExt::WinogradFilterTransformOp,
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/LLVMCPUDecomposeGroupMmt4D.cpp b/compiler/src/iree/compiler/Codegen/LLVMCPU/LLVMCPUDecomposeGroupMmt4D.cpp new file mode 100644 index 0000000..8110c02 --- /dev/null +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/LLVMCPUDecomposeGroupMmt4D.cpp
@@ -0,0 +1,210 @@ +// 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/Codegen/LLVMCPU/Passes.h" + +#include "iree/compiler/Codegen/Dialect/CPU/IR/IREECPUTypes.h" +#include "iree/compiler/Codegen/Dialect/Codegen/IR/IREECodegenAttrs.h" +#include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Linalg/IR/Linalg.h" +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/Dialect/Utils/IndexingUtils.h" +#include "mlir/IR/PatternMatch.h" + +namespace mlir::iree_compiler { + +#define GEN_PASS_DEF_LLVMCPUDECOMPOSEGROUPMMT4DPASS +#include "iree/compiler/Codegen/LLVMCPU/Passes.h.inc" + +namespace { + +class LLVMCPUDecomposeGroupMmt4DPass final + : public impl::LLVMCPUDecomposeGroupMmt4DPassBase< + LLVMCPUDecomposeGroupMmt4DPass> { +public: + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert<arith::ArithDialect, linalg::LinalgDialect, scf::SCFDialect, + tensor::TensorDialect>(); + } + + void runOnOperation() override { + IRRewriter rewriter(&getContext()); + getOperation().walk([&](IREE::LinalgExt::GroupMmt4DOp op) { + rewriter.setInsertionPoint(op); + Location loc = op.getLoc(); + auto weightsType = + cast<RankedTensorType>(op.getExpertWeights().getType()); + auto outputType = cast<RankedTensorType>(op.getOutput().getType()); + ArrayRef<int64_t> outputPermutation = op.getOutputPermutation(); + int64_t outerRowDim = outputPermutation[0]; + int64_t innerRowDim = outputPermutation[2]; + + Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0); + Value one = arith::ConstantIndexOp::create(rewriter, loc, 1); + Value upper = arith::ConstantIndexOp::create(rewriter, loc, + weightsType.getDimSize(0)); + // Inner-row slices may leave gaps between outer blocks. Bound the + // selected rows by the end of the last block, not by their count. + // Clamp the last block index so empty outer dimensions do not underflow. + Value lastOuterRow = arith::MaxSIOp::create( + rewriter, loc, zero, + arith::SubIOp::create( + rewriter, loc, + tensor::DimOp::create(rewriter, loc, op.getInput(), 0), one)); + Value tileEnd = arith::AddIOp::create( + rewriter, loc, op.getRowBase(), + arith::AddIOp::create( + rewriter, loc, + arith::MulIOp::create(rewriter, loc, lastOuterRow, + op.getRowStride()), + tensor::DimOp::create(rewriter, loc, op.getInput(), 2))); + + auto loop = scf::ForOp::create( + rewriter, loc, zero, upper, one, ValueRange{op.getOutput(), zero}, + [&](OpBuilder &builder, Location bodyLoc, Value expert, + ValueRange iterArgs) { + Value output = iterArgs[0]; + Value expertStart = iterArgs[1]; + Value expertEnd = tensor::ExtractOp::create( + builder, bodyLoc, op.getExpertOffsets(), ValueRange{expert}); + if (!expertEnd.getType().isIndex()) { + expertEnd = arith::IndexCastOp::create( + builder, bodyLoc, builder.getIndexType(), expertEnd); + } + Value activeAfterStart = arith::CmpIOp::create( + builder, bodyLoc, arith::CmpIPredicate::slt, op.getRowBase(), + expertEnd); + Value activeBeforeEnd = arith::CmpIOp::create( + builder, bodyLoc, arith::CmpIPredicate::slt, expertStart, + tileEnd); + Value isActive = arith::AndIOp::create( + builder, bodyLoc, activeAfterStart, activeBeforeEnd); + + auto active = scf::IfOp::create( + builder, bodyLoc, TypeRange{output.getType()}, isActive, + /*withElseRegion=*/true); + { + OpBuilder::InsertionGuard guard(builder); + OpBuilder thenBuilder = + OpBuilder::atBlockBegin(&active.getThenRegion().front()); + SmallVector<OpFoldResult> offsets(5, thenBuilder.getIndexAttr(0)); + offsets[0] = expert; + SmallVector<OpFoldResult> sizes = tensor::getMixedSizes( + thenBuilder, bodyLoc, op.getExpertWeights()); + sizes[0] = thenBuilder.getIndexAttr(1); + SmallVector<OpFoldResult> weightStrides( + 5, thenBuilder.getIndexAttr(1)); + auto expertWeightsType = + weightsType.clone(weightsType.getShape().drop_front()); + Value weights = tensor::ExtractSliceOp::create( + thenBuilder, bodyLoc, expertWeightsType, + op.getExpertWeights(), offsets, sizes, weightStrides); + Value mmtInit = tensor::EmptyOp::create( + thenBuilder, bodyLoc, + tensor::getMixedSizes(thenBuilder, bodyLoc, output), + outputType.getElementType()); + Value zeroElement = arith::ConstantOp::create( + thenBuilder, bodyLoc, + thenBuilder.getZeroAttr(outputType.getElementType())); + mmtInit = linalg::FillOp::create(thenBuilder, bodyLoc, + zeroElement, mmtInit) + .getResult(0); + Value matmul = + linalg::Mmt4DOp::create( + thenBuilder, bodyLoc, output.getType(), + op.getTransposed() ? ValueRange{weights, op.getInput()} + : ValueRange{op.getInput(), weights}, + ValueRange{mmtInit}) + .getResult(0); + if (auto config = getLoweringConfig(op)) { + if (auto cpuConfig = + dyn_cast<IREE::CPU::LoweringConfigAttr>(config); + cpuConfig && op.getTransposed()) { + MLIRContext *ctx = cpuConfig.getContext(); + SmallVector<NamedAttribute> configItems; + for (int i : IREE::CPU::getTilingLevelsAsInts()) { + if (!cpuConfig.hasTilingLevel(i)) { + continue; + } + auto level = static_cast<IREE::CPU::TilingLevel>(i); + auto levelAttr = + cast<IREE::Codegen::LoweringConfigTilingLevelAttr>( + cpuConfig.getTilingLevelAttr(i)); + SmallVector<int64_t> tileSizes(levelAttr.getSizes()); + SmallVector<bool> scalableFlags( + levelAttr.getScalableFlags()); + if (tileSizes.size() == 6) { + applyPermutationToVector(tileSizes, + op.getLoopPermutation()); + scalableFlags.resize(tileSizes.size(), false); + applyPermutationToVector(scalableFlags, + op.getLoopPermutation()); + } + configItems.emplace_back( + IREE::CPU::getTilingLevelName(level), + IREE::CPU::LoweringConfigAttr::getTilingLevelAttr( + ctx, tileSizes, scalableFlags)); + } + setLoweringConfig( + matmul.getDefiningOp(), + IREE::CPU::LoweringConfigAttr::get(ctx, configItems)); + } else { + setLoweringConfig(matmul.getDefiningOp(), config); + } + } + + SmallVector<AffineMap> indexingMaps( + 2, thenBuilder.getMultiDimIdentityMap(outputType.getRank())); + SmallVector<utils::IteratorType> iteratorTypes( + outputType.getRank(), utils::IteratorType::parallel); + auto merge = linalg::GenericOp::create( + thenBuilder, bodyLoc, outputType, ValueRange{matmul}, + ValueRange{output}, indexingMaps, iteratorTypes, + [&](OpBuilder &nestedBuilder, Location nestedLoc, + ValueRange args) { + Value outerRow = linalg::IndexOp::create( + nestedBuilder, nestedLoc, outerRowDim); + Value innerRow = linalg::IndexOp::create( + nestedBuilder, nestedLoc, innerRowDim); + Value row = arith::AddIOp::create( + nestedBuilder, nestedLoc, op.getRowBase(), + arith::AddIOp::create( + nestedBuilder, nestedLoc, + arith::MulIOp::create(nestedBuilder, nestedLoc, + outerRow, op.getRowStride()), + innerRow)); + Value afterStart = arith::CmpIOp::create( + nestedBuilder, nestedLoc, arith::CmpIPredicate::sge, + row, expertStart); + Value beforeEnd = arith::CmpIOp::create( + nestedBuilder, nestedLoc, arith::CmpIPredicate::slt, + row, expertEnd); + Value belongsToExpert = arith::AndIOp::create( + nestedBuilder, nestedLoc, afterStart, beforeEnd); + linalg::YieldOp::create( + nestedBuilder, nestedLoc, + arith::SelectOp::create(nestedBuilder, nestedLoc, + belongsToExpert, args[0], + args[1]) + .getResult()); + }); + scf::YieldOp::create(thenBuilder, bodyLoc, merge.getResult(0)); + OpBuilder elseBuilder = + OpBuilder::atBlockBegin(&active.getElseRegion().front()); + scf::YieldOp::create(elseBuilder, bodyLoc, output); + } + scf::YieldOp::create(builder, bodyLoc, + ValueRange{active.getResult(0), expertEnd}); + }); + rewriter.replaceOp(op, loop.getResult(0)); + }); + } +}; + +} // namespace +} // namespace mlir::iree_compiler
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.cpp b/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.cpp index 9984e0c..9bcfaab 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.cpp +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.cpp
@@ -76,6 +76,7 @@ } funcPassManager.addPass( createTileAndDistributeToWorkgroupsUsingForallOpPass()); + funcPassManager.addPass(createLLVMCPUDecomposeGroupMmt4DPass()); funcPassManager.addPass(createBufferizeDispatchTensorLoadStorePass()); funcPassManager.addPass(createCombineResultLayoutTransformationPass()); funcPassManager.addPass(createConfigTrackingCanonicalizerPass());
diff --git a/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.td b/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.td index 39e24dc..5d291e1 100644 --- a/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.td +++ b/compiler/src/iree/compiler/Codegen/LLVMCPU/Passes.td
@@ -79,6 +79,17 @@ ]; } +def LLVMCPUDecomposeGroupMmt4DPass : + InterfacePass<"iree-llvmcpu-decompose-group-mmt4d", "mlir::FunctionOpInterface"> { + let summary = "Decomposes grouped mmt4d ops after workgroup tiling"; + let dependentDialects = [ + "::mlir::arith::ArithDialect", + "::mlir::linalg::LinalgDialect", + "::mlir::scf::SCFDialect", + "::mlir::tensor::TensorDialect" + ]; +} + def LLVMCPUEmitVectorizationRemarksPass : InterfacePass<"iree-llvmcpu-emit-vectorization-remarks", "mlir::FunctionOpInterface"> { let summary = "Emit vectorization remarks on Linalg ops";
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h index 5fb8186..f8055cb 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h
@@ -31,6 +31,7 @@ } // namespace detail void registerConcatOpTilingInterfaceExternalModel(MLIRContext *ctx); +void registerGroupMatmulTilingInterfaceExternalModel(MLIRContext *ctx); /// Include the generated interface declarations. #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h.inc" // IWYU pragma: export
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp index eb7a33c..2c6f0b2 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp
@@ -996,6 +996,116 @@ } //===----------------------------------------------------------------------===// +// GroupMatmulOp +//===----------------------------------------------------------------------===// + +LogicalResult GroupMatmulOp::verify() { + auto inputType = cast<RankedTensorType>(getInput().getType()); + auto weightsType = cast<RankedTensorType>(getExpertWeights().getType()); + auto offsetsType = cast<RankedTensorType>(getExpertOffsets().getType()); + auto outputType = cast<RankedTensorType>(getOutput().getType()); + + ArrayRef<int64_t> inputShape = inputType.getShape(); + ArrayRef<int64_t> weightsShape = weightsType.getShape(); + ArrayRef<int64_t> offsetsShape = offsetsType.getShape(); + ArrayRef<int64_t> outputShape = outputType.getShape(); + + if (ShapedType::isDynamic(weightsShape[0]) || + ShapedType::isDynamic(offsetsShape[0])) { + return emitOpError("expert count must be static"); + } + if (!ShapedType::isDynamic(inputShape[1]) && + !ShapedType::isDynamic(weightsShape[1]) && + inputShape[1] != weightsShape[1]) { + return emitOpError("input's N dimension must match expert_weights' N"); + } + if (offsetsShape[0] != weightsShape[0]) { + return emitOpError( + "expert_offsets' E dimension must match expert_weights' E"); + } + if (!ShapedType::isDynamic(outputShape[1]) && + !ShapedType::isDynamic(weightsShape[2]) && + outputShape[1] != weightsShape[2]) { + return emitOpError("output's M dimension must match expert_weights' M"); + } + if (!ShapedType::isDynamic(inputShape[0]) && + !ShapedType::isDynamic(outputShape[0]) && + inputShape[0] != outputShape[0]) { + return emitOpError("output's T dimension must match input's T"); + } + if (inputType.getElementType() != weightsType.getElementType() || + inputType.getElementType() != outputType.getElementType()) { + return emitOpError( + "input, expert_weights, and output element types must match"); + } + return success(); +} + +//===----------------------------------------------------------------------===// +// GroupMmt4DOp +//===----------------------------------------------------------------------===// + +ArrayRef<int64_t> GroupMmt4DOp::getOutputPermutation() const { + static constexpr int64_t kIdentity[] = {0, 1, 2, 3}; + static constexpr int64_t kTransposed[] = {1, 0, 3, 2}; + return const_cast<GroupMmt4DOp *>(this)->getTransposed() + ? ArrayRef<int64_t>(kTransposed) + : ArrayRef<int64_t>(kIdentity); +} + +ArrayRef<int64_t> GroupMmt4DOp::getLoopPermutation() const { + static constexpr int64_t kIdentity[] = {0, 1, 2, 3, 4, 5}; + static constexpr int64_t kTransposed[] = {1, 0, 2, 4, 3, 5}; + return const_cast<GroupMmt4DOp *>(this)->getTransposed() + ? ArrayRef<int64_t>(kTransposed) + : ArrayRef<int64_t>(kIdentity); +} + +LogicalResult GroupMmt4DOp::verify() { + auto inputType = cast<RankedTensorType>(getInput().getType()); + auto weightsType = cast<RankedTensorType>(getExpertWeights().getType()); + auto offsetsType = cast<RankedTensorType>(getExpertOffsets().getType()); + auto outputType = cast<RankedTensorType>(getOutput().getType()); + auto dimsMatch = [](int64_t lhs, int64_t rhs) { + return ShapedType::isDynamic(lhs) || ShapedType::isDynamic(rhs) || + lhs == rhs; + }; + ArrayRef<int64_t> inputShape = inputType.getShape(); + ArrayRef<int64_t> weightsShape = weightsType.getShape(); + ArrayRef<int64_t> outputShape = outputType.getShape(); + ArrayRef<int64_t> outputPermutation = getOutputPermutation(); + if (ShapedType::isDynamic(weightsShape[0]) || + ShapedType::isDynamic(offsetsType.getDimSize(0))) { + return emitOpError("expert count must be static"); + } + if (!dimsMatch(inputShape[0], outputShape[outputPermutation[0]]) || + !dimsMatch(inputShape[1], weightsShape[2]) || + !dimsMatch(outputShape[outputPermutation[1]], weightsShape[1]) || + !dimsMatch(inputShape[2], outputShape[outputPermutation[2]]) || + !dimsMatch(outputShape[outputPermutation[3]], weightsShape[3]) || + !dimsMatch(inputShape[3], weightsShape[4])) { + return emitOpError("operand dimensions must match mmt4d"); + } + if (offsetsType.getDimSize(0) != weightsType.getDimSize(0)) { + return emitOpError( + "expert_offsets' E dimension must match expert_weights' E"); + } + if (inputType.getElementType() != weightsType.getElementType() || + inputType.getElementType() != outputType.getElementType()) { + return emitOpError( + "input, expert_weights, and output element types must match"); + } + if (auto stride = getConstantIntValue(getRowStride())) { + if (*stride < 0 || + (!inputType.isDynamicDim(2) && *stride < inputShape[2])) { + return emitOpError("row_stride must be nonnegative and at least the " + "inner row dimension"); + } + } + return success(); +} + +//===----------------------------------------------------------------------===// // SortOp //===----------------------------------------------------------------------===// @@ -3801,6 +3911,8 @@ DEFINE_OP_GET_EFFECTS(ScatterOp) DEFINE_OP_GET_EFFECTS(GatherOp) +DEFINE_OP_GET_EFFECTS(GroupMatmulOp) +DEFINE_OP_GET_EFFECTS(GroupMmt4DOp) DEFINE_OP_GET_EFFECTS(MapStoreOp) DEFINE_OP_GET_EFFECTS(MapLoadOp) DEFINE_OP_GET_EFFECTS(SortOp)
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h index 5f6fd1f..036d844 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h
@@ -9,6 +9,7 @@ #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.h" #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtInterfaces.h" +#include "llvm/ADT/ArrayRef.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/SCF/IR/DeviceMappingInterface.h" #include "mlir/IR/Attributes.h"
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td index b03e89c..272dacb 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.td
@@ -485,6 +485,105 @@ }]; } +def IREELinalgExt_GroupMatmulOp : IREELinalgExt_Op<"group_matmul"> { + let summary = [{Performs a grouped matrix multiplication.}]; + let description = [{ + Multiplies each row of the [N, K] `input` matrix by one of the E + [K, M] matrices in `expert_weights`, producing an [N, M] result. + + The [E] `expert_offsets` tensor specifies absolute, exclusive end + row indices for consecutive expert groups. Its values must be + nonnegative and nondecreasing. Expert 0 starts at row 0; each later + expert starts at the preceding expert's end. Equal consecutive + offsets represent an empty expert. + + For local input row r, let g = row_base + r. Expert e applies when: + + ``` + start[e] <= g < expert_offsets[e] + ``` + + where start[0] = 0 and start[e] = expert_offsets[e - 1] for e > 0. + For example, offsets [2, 2, 5] assign global rows 0–1 to expert 0, + no rows to expert 1, and rows 2–4 to expert 2. + + `row_base` identifies the global row corresponding to local row 0. + Tiling adjusts `row_base` while leaving `expert_offsets` unchanged. + The offsets need not end at the current input slice's boundary. + + For each assigned row, the matrix product replaces the corresponding + destination row; it is not added to the existing destination values. + Rows outside all expert intervals retain their destination values. + + The expert count E must be static. The row count N, reduction dimension K, + and column count M may be dynamic. + }]; + let arguments = (ins + TensorRankOf<[AnyFloat], [2]>:$input, + TensorRankOf<[AnyFloat], [3]>:$expert_weights, + TensorRankOf<[AnySignlessIntegerOrIndex], [1]>:$expert_offsets, + Index:$row_base, + TensorRankOf<[AnyFloat], [2]>:$output); + let results = (outs TensorRankOf<[AnyFloat], [2]>:$result); + let hasVerifier = 1; + let assemblyFormat = [{ + attr-dict `ins` `(` $input `,` $expert_weights `,` $expert_offsets `,` + $row_base `:` type($input) `,` type($expert_weights) `,` + type($expert_offsets) `,` type($row_base) `)` + `outs` `(` $output `:` type($output) `)` `->` type($result) + }]; + let extraClassDeclaration = [{ + MutableOperandRange getDpsInitsMutable() { return getOutputMutable(); } + }]; +} + +def IREELinalgExt_GroupMmt4DOp : IREELinalgExt_Op<"group_mmt4d"> { + let summary = [{Performs a grouped matrix-matrix-transpose multiplication of a packed 4D input by 5D weights.}]; + let description = [{ + Used for data tiling of `group_matmul`, largely analogous to `mmt4d`. + + Expert offsets and destination values follow the same rules as + `group_matmul`: offsets are absolute, exclusive row ends; empty + experts are permitted; assigned rows are overwritten with their + matrix products; and uncovered rows retain their destination values. + + For an input element at index [m, k, mi, ki], the global row used + to choose the expert is: + + ``` + g = row_base + m * row_stride + mi + ``` + + `row_stride` is the distance in logical rows between the starts + of consecutive outer row blocks. Tiling adjusts `row_base` while + preserving `row_stride` and `expert_offsets`. + + If `transposed` is true, the output layout is [N, M, Ni, Mi] + instead of [M, N, Mi, Ni]. This does not change expert selection. + }]; + let arguments = (ins + TensorRankOf<[AnyFloat], [4]>:$input, + TensorRankOf<[AnyFloat], [5]>:$expert_weights, + TensorRankOf<[AnySignlessIntegerOrIndex], [1]>:$expert_offsets, + Index:$row_base, + Index:$row_stride, + TensorRankOf<[AnyFloat], [4]>:$output, + DefaultValuedAttr<BoolAttr, "false">:$transposed); + let results = (outs TensorRankOf<[AnyFloat], [4]>:$result); + let hasVerifier = 1; + let assemblyFormat = [{ + prop-dict attr-dict `ins` `(` $input `,` $expert_weights `,` $expert_offsets `,` + $row_base `,` $row_stride `:` type($input) `,` type($expert_weights) `,` + type($expert_offsets) `,` type($row_base) `,` type($row_stride) `)` + `outs` `(` $output `:` type($output) `)` `->` type($result) + }]; + let extraClassDeclaration = [{ + MutableOperandRange getDpsInitsMutable() { return getOutputMutable(); } + ArrayRef<int64_t> getOutputPermutation() const; + ArrayRef<int64_t> getLoopPermutation() const; + }]; +} + def IREELinalgExt_SortOp : IREELinalgExt_Op<"sort", [AttrSizedOperandSegments, DeclareOpInterfaceMethods<ReifyRankedShapedTypeOpInterface, ["reifyResultShapes"]>,
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp index b83e022..096e1b3 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/TilingInterfaceImpl.cpp
@@ -21,6 +21,7 @@ #include "mlir/Dialect/Utils/StaticValueUtils.h" #include "mlir/IR/IRMapping.h" #include "mlir/IR/OpDefinition.h" +#include "mlir/Interfaces/ValueBoundsOpInterface.h" #define DEBUG_TYPE "linalg-ext-tiling" @@ -4355,6 +4356,211 @@ {tiledConcatOp}, SmallVector<Value>(tiledConcatOp->getResults()), slices}; } +namespace { + +static bool isFullReductionTile(Value input, int64_t dim, OpFoldResult offset, + OpFoldResult size) { + if (!isConstantIntValue(offset, 0)) { + return false; + } + FailureOr<bool> equal = ValueBoundsConstraintSet::areEqual( + size, ValueBoundsConstraintSet::Variable(input, dim)); + return succeeded(equal) && *equal; +} + +struct GroupMatmulTilingExternalModel + : TilingInterface::ExternalModel<GroupMatmulTilingExternalModel, + GroupMatmulOp> { + SmallVector<utils::IteratorType> getLoopIteratorTypes(Operation *) const { + return {utils::IteratorType::parallel, utils::IteratorType::parallel, + utils::IteratorType::reduction}; + } + + SmallVector<Range> getIterationDomain(Operation *op, + OpBuilder &builder) const { + auto groupMatmul = cast<GroupMatmulOp>(op); + OpFoldResult zero = builder.getIndexAttr(0); + OpFoldResult one = builder.getIndexAttr(1); + Location loc = groupMatmul.getLoc(); + return {{zero, getDim(builder, loc, groupMatmul.getInput(), 0), one}, + {zero, getDim(builder, loc, groupMatmul.getOutput(), 1), one}, + {zero, getDim(builder, loc, groupMatmul.getInput(), 1), one}}; + } + + FailureOr<TilingResult> + getTiledImplementation(Operation *op, OpBuilder &builder, + ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes) const { + auto groupMatmul = cast<GroupMatmulOp>(op); + if (!isFullReductionTile(groupMatmul.getInput(), 1, offsets[2], sizes[2])) { + return groupMatmul.emitOpError( + "partial reduction tiling is unsupported; expected zero offset and " + "full K size"); + } + Location loc = groupMatmul.getLoc(); + OpFoldResult zero = builder.getIndexAttr(0); + OpFoldResult one = builder.getIndexAttr(1); + SmallVector<OpFoldResult> inputOffsets{offsets[0], offsets[2]}; + SmallVector<OpFoldResult> inputSizes{sizes[0], sizes[2]}; + Value input = tensor::ExtractSliceOp::create( + builder, loc, groupMatmul.getInput(), inputOffsets, inputSizes, + SmallVector<OpFoldResult>{one, one}); + SmallVector<OpFoldResult> weightOffsets{zero, offsets[2], offsets[1]}; + SmallVector<OpFoldResult> weightSizes{ + getDim(builder, loc, groupMatmul.getExpertWeights(), 0), sizes[2], + sizes[1]}; + Value weights = tensor::ExtractSliceOp::create( + builder, loc, groupMatmul.getExpertWeights(), weightOffsets, + weightSizes, SmallVector<OpFoldResult>{one, one, one}); + SmallVector<OpFoldResult> outputOffsets{offsets[0], offsets[1]}; + SmallVector<OpFoldResult> outputSizes{sizes[0], sizes[1]}; + Value output = tensor::ExtractSliceOp::create( + builder, loc, groupMatmul.getOutput(), outputOffsets, outputSizes, + SmallVector<OpFoldResult>{one, one}); + Value tileRowOffset = + getValueOrCreateConstantIndexOp(builder, loc, offsets[0]); + Value rowBase = arith::AddIOp::create( + builder, loc, groupMatmul.getRowBase(), tileRowOffset); + Operation *tiledOp = mlir::clone( + builder, groupMatmul.getOperation(), TypeRange{output.getType()}, + ValueRange{input, weights, groupMatmul.getExpertOffsets(), rowBase, + output}); + return TilingResult{{tiledOp}, + SmallVector<Value>(tiledOp->getResults()), + {input.getDefiningOp(), weights.getDefiningOp(), + output.getDefiningOp()}}; + } + + FailureOr<TilingResult> getTiledImplementation( + Operation *op, OpBuilder &builder, ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes, ArrayRef<mlir::InnerTileAlignment>) const { + return getTiledImplementation(op, builder, offsets, sizes); + } + + LogicalResult getResultTilePosition( + Operation *, OpBuilder &, unsigned, ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes, SmallVector<OpFoldResult> &resultOffsets, + SmallVector<OpFoldResult> &resultSizes) const { + resultOffsets.assign(offsets.begin(), offsets.begin() + 2); + resultSizes.assign(sizes.begin(), sizes.begin() + 2); + return success(); + } +}; + +struct GroupMmt4DTilingExternalModel + : TilingInterface::ExternalModel<GroupMmt4DTilingExternalModel, + GroupMmt4DOp> { + SmallVector<utils::IteratorType> getLoopIteratorTypes(Operation *) const { + return {utils::IteratorType::parallel, utils::IteratorType::parallel, + utils::IteratorType::reduction, utils::IteratorType::parallel, + utils::IteratorType::parallel, utils::IteratorType::reduction}; + } + + SmallVector<Range> getIterationDomain(Operation *op, + OpBuilder &builder) const { + auto groupMmt4d = cast<GroupMmt4DOp>(op); + Location loc = groupMmt4d.getLoc(); + OpFoldResult zero = builder.getIndexAttr(0); + OpFoldResult one = builder.getIndexAttr(1); + ArrayRef<int64_t> outputPermutation = groupMmt4d.getOutputPermutation(); + return {{zero, getDim(builder, loc, groupMmt4d.getInput(), 0), one}, + {zero, + getDim(builder, loc, groupMmt4d.getOutput(), outputPermutation[1]), + one}, + {zero, getDim(builder, loc, groupMmt4d.getInput(), 1), one}, + {zero, getDim(builder, loc, groupMmt4d.getInput(), 2), one}, + {zero, + getDim(builder, loc, groupMmt4d.getOutput(), outputPermutation[3]), + one}, + {zero, getDim(builder, loc, groupMmt4d.getInput(), 3), one}}; + } + + FailureOr<TilingResult> + getTiledImplementation(Operation *op, OpBuilder &builder, + ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes) const { + auto groupMmt4d = cast<GroupMmt4DOp>(op); + if (!isFullReductionTile(groupMmt4d.getInput(), 1, offsets[2], sizes[2]) || + !isFullReductionTile(groupMmt4d.getInput(), 3, offsets[5], sizes[5])) { + return groupMmt4d.emitOpError( + "partial reduction tiling is unsupported; expected zero offsets and " + "full outer and inner K sizes"); + } + Location loc = groupMmt4d.getLoc(); + OpFoldResult zero = builder.getIndexAttr(0); + OpFoldResult one = builder.getIndexAttr(1); + SmallVector<OpFoldResult> inputOffsets{offsets[0], offsets[2], offsets[3], + offsets[5]}; + SmallVector<OpFoldResult> inputSizes{sizes[0], sizes[2], sizes[3], + sizes[5]}; + Value input = tensor::ExtractSliceOp::create( + builder, loc, groupMmt4d.getInput(), inputOffsets, inputSizes, + SmallVector<OpFoldResult>(4, one)); + SmallVector<OpFoldResult> weightOffsets{zero, offsets[1], offsets[2], + offsets[4], offsets[5]}; + SmallVector<OpFoldResult> weightSizes{ + getDim(builder, loc, groupMmt4d.getExpertWeights(), 0), sizes[1], + sizes[2], sizes[4], sizes[5]}; + Value weights = tensor::ExtractSliceOp::create( + builder, loc, groupMmt4d.getExpertWeights(), weightOffsets, weightSizes, + SmallVector<OpFoldResult>(5, one)); + ArrayRef<int64_t> outputPermutation = groupMmt4d.getOutputPermutation(); + SmallVector<OpFoldResult> outputOffsets{offsets[0], offsets[1], offsets[3], + offsets[4]}; + SmallVector<OpFoldResult> outputSizes{sizes[0], sizes[1], sizes[3], + sizes[4]}; + applyPermutationToVector(outputOffsets, outputPermutation); + applyPermutationToVector(outputSizes, outputPermutation); + Value output = tensor::ExtractSliceOp::create( + builder, loc, groupMmt4d.getOutput(), outputOffsets, outputSizes, + SmallVector<OpFoldResult>(4, one)); + Value outerRowOffset = + getValueOrCreateConstantIndexOp(builder, loc, offsets[0]); + Value innerRowOffset = + getValueOrCreateConstantIndexOp(builder, loc, offsets[3]); + Value rowBase = arith::AddIOp::create( + builder, loc, groupMmt4d.getRowBase(), + arith::AddIOp::create(builder, loc, + arith::MulIOp::create(builder, loc, + outerRowOffset, + groupMmt4d.getRowStride()), + innerRowOffset)); + Operation *tiledOp = mlir::clone( + builder, groupMmt4d.getOperation(), TypeRange{output.getType()}, + ValueRange{input, weights, groupMmt4d.getExpertOffsets(), rowBase, + groupMmt4d.getRowStride(), output}); + return TilingResult{{tiledOp}, + SmallVector<Value>(tiledOp->getResults()), + {input.getDefiningOp(), weights.getDefiningOp(), + output.getDefiningOp()}}; + } + + FailureOr<TilingResult> getTiledImplementation( + Operation *op, OpBuilder &builder, ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes, ArrayRef<mlir::InnerTileAlignment>) const { + return getTiledImplementation(op, builder, offsets, sizes); + } + + LogicalResult getResultTilePosition( + Operation *op, OpBuilder &, unsigned, ArrayRef<OpFoldResult> offsets, + ArrayRef<OpFoldResult> sizes, SmallVector<OpFoldResult> &resultOffsets, + SmallVector<OpFoldResult> &resultSizes) const { + ArrayRef<int64_t> outputPermutation = + cast<GroupMmt4DOp>(op).getOutputPermutation(); + resultOffsets = {offsets[0], offsets[1], offsets[3], offsets[4]}; + resultSizes = {sizes[0], sizes[1], sizes[3], sizes[4]}; + applyPermutationToVector(resultOffsets, outputPermutation); + applyPermutationToVector(resultSizes, outputPermutation); + return success(); + } +}; +} // namespace + +void registerGroupMatmulTilingInterfaceExternalModel(MLIRContext *ctx) { + GroupMatmulOp::attachInterface<GroupMatmulTilingExternalModel>(*ctx); + GroupMmt4DOp::attachInterface<GroupMmt4DTilingExternalModel>(*ctx); +} + void registerConcatOpTilingInterfaceExternalModel(MLIRContext *ctx) { tensor::ConcatOp::attachInterface<ConcatOpTilingExternalModel>(*ctx); }
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/invalid.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/invalid.mlir index 9045007..4fd015b 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/invalid.mlir +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/invalid.mlir
@@ -264,6 +264,96 @@ // ----- +func.func @group_matmul_invalid_dimensions( + %input: tensor<4x8xf32>, %weights: tensor<2x7x3xf32>, + %offsets: tensor<2xi64>, %output: tensor<4x3xf32>) -> tensor<4x3xf32> { + %c0 = arith.constant 0 : index + // expected-error @+1 {{input's N dimension must match expert_weights' N}} + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %c0 : tensor<4x8xf32>, tensor<2x7x3xf32>, + tensor<2xi64>, index) outs(%output : tensor<4x3xf32>) + -> tensor<4x3xf32> + return %result : tensor<4x3xf32> +} + +// ----- + +func.func @group_matmul_invalid_expert_count( + %input: tensor<4x8xf32>, %weights: tensor<2x8x3xf32>, + %offsets: tensor<3xi64>, %output: tensor<4x3xf32>) -> tensor<4x3xf32> { + %c0 = arith.constant 0 : index + // expected-error @+1 {{expert_offsets' E dimension must match expert_weights' E}} + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %c0 : tensor<4x8xf32>, tensor<2x8x3xf32>, + tensor<3xi64>, index) outs(%output : tensor<4x3xf32>) + -> tensor<4x3xf32> + return %result : tensor<4x3xf32> +} + +// ----- + +func.func @group_mmt4d_invalid_dimensions( + %input: tensor<2x3x4x5xf32>, %weights: tensor<2x6x3x7x4xf32>, + %offsets: tensor<2xi64>, %output: tensor<2x6x4x7xf32>) + -> tensor<2x6x4x7xf32> { + %c0 = arith.constant 0 : index + %row_stride_dim = arith.constant 2 : index + %row_stride = tensor.dim %input, %row_stride_dim : tensor<2x3x4x5xf32> + // expected-error @+1 {{operand dimensions must match mmt4d}} + %result = iree_linalg_ext.group_mmt4d ins(%input, %weights, %offsets, %c0, %row_stride : tensor<2x3x4x5xf32>, + tensor<2x6x3x7x4xf32>, tensor<2xi64>, index, index) + outs(%output : tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> + return %result : tensor<2x6x4x7xf32> +} + +// ----- + +func.func @group_mmt4d_invalid_expert_count( + %input: tensor<2x3x4x5xf32>, %weights: tensor<2x6x3x7x5xf32>, + %offsets: tensor<3xi64>, %output: tensor<2x6x4x7xf32>) + -> tensor<2x6x4x7xf32> { + %c0 = arith.constant 0 : index + %row_stride_dim = arith.constant 2 : index + %row_stride = tensor.dim %input, %row_stride_dim : tensor<2x3x4x5xf32> + // expected-error @+1 {{expert_offsets' E dimension must match expert_weights' E}} + %result = iree_linalg_ext.group_mmt4d ins(%input, %weights, %offsets, %c0, %row_stride : tensor<2x3x4x5xf32>, + tensor<2x6x3x7x5xf32>, tensor<3xi64>, index, index) + outs(%output : tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> + return %result : tensor<2x6x4x7xf32> +} + +// ----- + +func.func @group_matmul_invalid_element_types( + %input: tensor<4x8xf32>, %weights: tensor<2x8x3xf16>, + %offsets: tensor<2xi64>, %output: tensor<4x3xf32>) -> tensor<4x3xf32> { + %c0 = arith.constant 0 : index + // expected-error @+1 {{input, expert_weights, and output element types must match}} + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %c0 : tensor<4x8xf32>, tensor<2x8x3xf16>, + tensor<2xi64>, index) outs(%output : tensor<4x3xf32>) + -> tensor<4x3xf32> + return %result : tensor<4x3xf32> +} + +// ----- + +func.func @group_mmt4d_invalid_element_types( + %input: tensor<2x3x4x5xf32>, %weights: tensor<2x6x3x7x5xf16>, + %offsets: tensor<2xi64>, %output: tensor<2x6x4x7xf32>) + -> tensor<2x6x4x7xf32> { + %c0 = arith.constant 0 : index + %row_stride_dim = arith.constant 2 : index + %row_stride = tensor.dim %input, %row_stride_dim : tensor<2x3x4x5xf32> + // expected-error @+1 {{input, expert_weights, and output element types must match}} + %result = iree_linalg_ext.group_mmt4d ins(%input, %weights, %offsets, %c0, %row_stride : tensor<2x3x4x5xf32>, + tensor<2x6x3x7x5xf16>, tensor<2xi64>, index, index) + outs(%output : tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> + return %result : tensor<2x6x4x7xf32> +} + +// ----- + func.func @scatter_rank_mismatch( %update : tensor<?x?x?x?xf32>, %indices : tensor<?x1xi32>, %original : tensor<?x?xf32>) -> tensor<?x?xf32> { @@ -2659,3 +2749,19 @@ outs(%init : tensor<128x64xf32>) -> tensor<128x64xf32> return %0 : tensor<128x64xf32> } + +// ----- + +func.func @group_mmt4d_short_row_stride( + %input: tensor<2x1x4x1xf32>, %weights: tensor<2x1x1x1x1xf32>, + %offsets: tensor<2xi64>, %output: tensor<2x1x4x1xf32>) + -> tensor<2x1x4x1xf32> { + %c0 = arith.constant 0 : index + %stride = arith.constant 2 : index + // expected-error @+1 {{row_stride must be nonnegative and at least the inner row dimension}} + %result = iree_linalg_ext.group_mmt4d + ins(%input, %weights, %offsets, %c0, %stride : + tensor<2x1x4x1xf32>, tensor<2x1x1x1x1xf32>, tensor<2xi64>, index, index) + outs(%output : tensor<2x1x4x1xf32>) -> tensor<2x1x4x1xf32> + return %result : tensor<2x1x4x1xf32> +}
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir index f52f21b..b018017 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/IR/test/roundtrip.mlir
@@ -3033,3 +3033,68 @@ // CHECK: iree_linalg_ext.dequantize_affine // CHECK-SAME: ins(%{{.+}}, %{{.+}} : tensor<128x64xi8>, tensor<128xf32>) // CHECK-SAME: outs(%{{.+}} : tensor<128x64xf16>) + +// ----- + +func.func @group_matmul(%input: tensor<?x16xf32>, + %weights: tensor<4x16x32xf32>, + %counts: tensor<4xi32>, + %row_base: index, + %output: tensor<?x32xf32>) -> tensor<?x32xf32> { + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %counts, %row_base : tensor<?x16xf32>, tensor<4x16x32xf32>, tensor<4xi32>, index) + outs(%output : tensor<?x32xf32>) -> tensor<?x32xf32> + return %result : tensor<?x32xf32> +} +// CHECK-LABEL: func.func @group_matmul( +// CHECK-SAME: %[[INPUT:.+]]: tensor<?x16xf32> +// CHECK-SAME: %[[WEIGHTS:.+]]: tensor<4x16x32xf32> +// CHECK-SAME: %[[COUNTS:.+]]: tensor<4xi32> +// CHECK-SAME: %[[ROW_BASE:.+]]: index +// CHECK-SAME: %[[OUTPUT:.+]]: tensor<?x32xf32> +// CHECK: %[[RESULT:.+]] = iree_linalg_ext.group_matmul ins(%[[INPUT]], %[[WEIGHTS]], %[[COUNTS]], %[[ROW_BASE]] : tensor<?x16xf32>, tensor<4x16x32xf32>, tensor<4xi32>, index) outs(%[[OUTPUT]] : tensor<?x32xf32>) -> tensor<?x32xf32> +// CHECK: return %[[RESULT]] : tensor<?x32xf32> + +func.func @group_mmt4d(%input: tensor<2x3x4x5xf32>, + %weights: tensor<4x6x3x7x5xf32>, + %offsets: tensor<4xi64>, %row_base: index, + %output: tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> { + %row_stride_dim = arith.constant 2 : index + %row_stride = tensor.dim %input, %row_stride_dim : tensor<2x3x4x5xf32> + %result = iree_linalg_ext.group_mmt4d ins(%input, %weights, %offsets, %row_base, %row_stride : tensor<2x3x4x5xf32>, + tensor<4x6x3x7x5xf32>, tensor<4xi64>, index, index) + outs(%output : tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> + return %result : tensor<2x6x4x7xf32> +} +// CHECK-LABEL: func.func @group_mmt4d( +// CHECK-SAME: %[[INPUT:.+]]: tensor<2x3x4x5xf32> +// CHECK-SAME: %[[WEIGHTS:.+]]: tensor<4x6x3x7x5xf32> +// CHECK-SAME: %[[OFFSETS:.+]]: tensor<4xi64> +// CHECK-SAME: %[[ROW_BASE:.+]]: index +// CHECK-SAME: %[[OUTPUT:.+]]: tensor<2x6x4x7xf32> +// CHECK: %[[ROW_STRIDE_DIM:.+]] = arith.constant 2 : index +// CHECK: %[[ROW_STRIDE:.+]] = tensor.dim %[[INPUT]], %[[ROW_STRIDE_DIM]] : tensor<2x3x4x5xf32> +// CHECK: %[[RESULT:.+]] = iree_linalg_ext.group_mmt4d ins(%[[INPUT]], %[[WEIGHTS]], %[[OFFSETS]], %[[ROW_BASE]], %[[ROW_STRIDE]] : tensor<2x3x4x5xf32>, tensor<4x6x3x7x5xf32>, tensor<4xi64>, index, index) outs(%[[OUTPUT]] : tensor<2x6x4x7xf32>) -> tensor<2x6x4x7xf32> +// CHECK: return %[[RESULT]] : tensor<2x6x4x7xf32> + +func.func @group_mmt4d_transposed(%input: tensor<2x3x4x5xf32>, + %weights: tensor<4x6x3x7x5xf32>, + %offsets: tensor<4xi64>, %row_base: index, + %output: tensor<6x2x7x4xf32>) -> tensor<6x2x7x4xf32> { + %row_stride_dim = arith.constant 2 : index + %row_stride = tensor.dim %input, %row_stride_dim : tensor<2x3x4x5xf32> + %result = iree_linalg_ext.group_mmt4d <transposed = true> ins(%input, %weights, %offsets, %row_base, %row_stride : tensor<2x3x4x5xf32>, + tensor<4x6x3x7x5xf32>, tensor<4xi64>, index, index) + outs(%output : tensor<6x2x7x4xf32>) -> tensor<6x2x7x4xf32> + return %result : tensor<6x2x7x4xf32> +} +// CHECK-LABEL: func.func @group_mmt4d_transposed( +// CHECK-SAME: %[[INPUT:.+]]: tensor<2x3x4x5xf32> +// CHECK-SAME: %[[WEIGHTS:.+]]: tensor<4x6x3x7x5xf32> +// CHECK-SAME: %[[OFFSETS:.+]]: tensor<4xi64> +// CHECK-SAME: %[[ROW_BASE:.+]]: index +// CHECK-SAME: %[[OUTPUT:.+]]: tensor<6x2x7x4xf32> +// CHECK: %[[ROW_STRIDE_DIM:.+]] = arith.constant 2 : index +// CHECK: %[[ROW_STRIDE:.+]] = tensor.dim %[[INPUT]], %[[ROW_STRIDE_DIM]] : tensor<2x3x4x5xf32> +// CHECK: %[[RESULT:.+]] = iree_linalg_ext.group_mmt4d <transposed = true> ins(%[[INPUT]], %[[WEIGHTS]], %[[OFFSETS]], %[[ROW_BASE]], %[[ROW_STRIDE]] : tensor<2x3x4x5xf32>, tensor<4x6x3x7x5xf32>, tensor<4xi64>, index, index) outs(%[[OUTPUT]] : tensor<6x2x7x4xf32>) -> tensor<6x2x7x4xf32> +// CHECK: return %[[RESULT]] : tensor<6x2x7x4xf32>
diff --git a/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/tiling.mlir b/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/tiling.mlir index 633cd86..a2958b7 100644 --- a/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/tiling.mlir +++ b/compiler/src/iree/compiler/Dialect/LinalgExt/Transforms/test/tiling.mlir
@@ -4524,3 +4524,25 @@ transform.yield } } + +// ----- + +func.func @group_matmul_partial_k( + %input: tensor<1x2xf32>, %weights: tensor<1x2x1xf32>, + %offsets: tensor<1xi64>, %output: tensor<1x1xf32>) -> tensor<1x1xf32> { + %c0 = arith.constant 0 : index + // expected-error @below {{partial reduction tiling is unsupported}} + // expected-error @below {{failed to tile operation}} + // expected-error @below {{failed to generate tiling loops}} + %result = iree_linalg_ext.group_matmul + ins(%input, %weights, %offsets, %c0 : tensor<1x2xf32>, tensor<1x2x1xf32>, tensor<1xi64>, index) + outs(%output : tensor<1x1xf32>) -> tensor<1x1xf32> + return %result : tensor<1x1xf32> +} +module attributes {transform.with_named_sequence} { + transform.named_sequence @__transform_main(%root: !transform.any_op {transform.readonly}) { + %op = transform.structured.match ops{["iree_linalg_ext.group_matmul"]} in %root : (!transform.any_op) -> !transform.any_op + %tiled, %loop = transform.structured.tile_using_for %op tile_sizes [0, 0, 1] : (!transform.any_op) -> (!transform.any_op, !transform.any_op) + transform.yield + } +}
diff --git a/compiler/src/iree/compiler/DispatchCreation/AnnotateDataTilingHints.cpp b/compiler/src/iree/compiler/DispatchCreation/AnnotateDataTilingHints.cpp index 43d85af..397f77e 100644 --- a/compiler/src/iree/compiler/DispatchCreation/AnnotateDataTilingHints.cpp +++ b/compiler/src/iree/compiler/DispatchCreation/AnnotateDataTilingHints.cpp
@@ -8,6 +8,7 @@ #include "iree/compiler/Dialect/Encoding/IR/EncodingTypes.h" #include "iree/compiler/Dialect/Encoding/Utils/Utils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" +#include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "iree/compiler/Dialect/LinalgExt/Utils/MatchUtils.h" #include "iree/compiler/DispatchCreation/Passes.h" #include "llvm/Support/CommandLine.h" @@ -213,6 +214,10 @@ return WalkResult::interrupt(); } auto linalgOp = dyn_cast<linalg::LinalgOp>(op); + if (enableMatmul && isa<IREE::LinalgExt::GroupMatmulOp>(op)) { + candidates.push_back(op); + return WalkResult::advance(); + } if (!linalgOp) { return WalkResult::advance(); }
diff --git a/compiler/src/iree/compiler/DispatchCreation/SetEncoding.cpp b/compiler/src/iree/compiler/DispatchCreation/SetEncoding.cpp index 7c08638..41807bf 100644 --- a/compiler/src/iree/compiler/DispatchCreation/SetEncoding.cpp +++ b/compiler/src/iree/compiler/DispatchCreation/SetEncoding.cpp
@@ -58,10 +58,10 @@ encodingDims); } -static SmallVector<linalg::LinalgOp> +static SmallVector<Operation *> getDataTilingCandidates(FunctionOpInterface funcOp) { - SmallVector<linalg::LinalgOp> result; - funcOp.walk([&](linalg::LinalgOp op) { + SmallVector<Operation *> result; + funcOp.walk([&](Operation *op) { if (!IREE::Encoding::hasDataTilingHint(op)) { return; } @@ -70,6 +70,77 @@ return result; } +static LogicalResult +setGroupMatmulDataTilingEncodings(RewriterBase &rewriter, + IREE::LinalgExt::GroupMatmulOp groupMatmul) { + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPoint(groupMatmul); + MLIRContext *ctx = rewriter.getContext(); + Location loc = groupMatmul.getLoc(); + + auto inputType = cast<RankedTensorType>(groupMatmul.getInput().getType()); + auto weightsType = + cast<RankedTensorType>(groupMatmul.getExpertWeights().getType()); + Type elementType = inputType.getElementType(); + SmallVector<Type> elementTypes{elementType, elementType, elementType}; + + AffineExpr d0 = rewriter.getAffineDimExpr(0); + AffineExpr d1 = rewriter.getAffineDimExpr(1); + AffineExpr d2 = rewriter.getAffineDimExpr(2); + SmallVector<AffineMap> matmulMaps{AffineMap::get(3, 0, {d0, d2}, ctx), + AffineMap::get(3, 0, {d1, d2}, ctx), + AffineMap::get(3, 0, {d0, d1}, ctx)}; + SmallVector<OpFoldResult> logicalIterationSizes{ + tensor::getMixedSize(rewriter, loc, groupMatmul.getInput(), 0), + tensor::getMixedSize(rewriter, loc, groupMatmul.getOutput(), 1), + tensor::getMixedSize(rewriter, loc, groupMatmul.getInput(), 1)}; + SmallVector<Value> encodingDims; + SmallVector<int64_t> matmulIterationSizes; + dispatchIndexOpFoldResults(logicalIterationSizes, encodingDims, + matmulIterationSizes); + + AffineExpr d3 = rewriter.getAffineDimExpr(3); + SmallVector<AffineMap> batchMatmulMaps{ + AffineMap::get(4, 0, {d0, d1, d3}, ctx), + AffineMap::get(4, 0, {d0, d3, d2}, ctx), + AffineMap::get(4, 0, {d0, d1, d2}, ctx)}; + + SmallVector<int64_t> batchMatmulIterationSizes{weightsType.getDimSize(0)}; + llvm::append_range(batchMatmulIterationSizes, matmulIterationSizes); + + auto makeEncoding = [&](int64_t operandIndex, ArrayRef<AffineMap> maps, + ArrayRef<int64_t> iterationSizes) { + return IREE::Encoding::EncodingAttr::get( + ctx, operandIndex, IREE::Encoding::EncodingOpType::matmul, elementTypes, + /*originalElementType=*/{}, maps, iterationSizes); + }; + auto inputEncoding = makeEncoding(IREE::Encoding::MATMUL_LHS, matmulMaps, + matmulIterationSizes); + auto weightsEncoding = makeEncoding( + IREE::Encoding::MATMUL_RHS, batchMatmulMaps, batchMatmulIterationSizes); + auto outputEncoding = makeEncoding(IREE::Encoding::MATMUL_RESULT, matmulMaps, + matmulIterationSizes); + + Value input = setEncoding(rewriter, loc, groupMatmul.getInput(), + inputEncoding, encodingDims); + Value weights = setEncoding(rewriter, loc, groupMatmul.getExpertWeights(), + weightsEncoding, encodingDims); + Value output = setEncoding(rewriter, loc, groupMatmul.getOutput(), + outputEncoding, encodingDims); + + IREE::Encoding::removeDataTilingHint(groupMatmul); + Operation *tiledOp = mlir::clone( + rewriter, groupMatmul.getOperation(), TypeRange{output.getType()}, + ValueRange{input, weights, groupMatmul.getExpertOffsets(), + groupMatmul.getRowBase(), output}); + SmallVector<OpFoldResult> outputSizes = + tensor::getMixedSizes(rewriter, loc, groupMatmul.getOutput()); + Value result = unsetEncoding(rewriter, loc, tiledOp->getResult(0), + outputSizes, encodingDims); + rewriter.replaceOp(groupMatmul, result); + return success(); +} + /// Set data tiling encodings using the SerializableAttr interface. /// This uses SerializableAttr::getEncodingProperties() to derive encodings /// for all operands and results based on the operation type. @@ -412,12 +483,17 @@ switch (encodingOption) { case EncodingOptions::Generic: { - SmallVector<linalg::LinalgOp> candidates = - getDataTilingCandidates(funcOp); - for (linalg::LinalgOp linalgOp : candidates) { - IREE::Encoding::removeDataTilingHint(linalgOp); - if (failed( - setDataTilingEncodings(rewriter, linalgOp, encodingOption))) { + SmallVector<Operation *> candidates = getDataTilingCandidates(funcOp); + for (Operation *op : candidates) { + LogicalResult result = failure(); + if (auto groupMatmul = dyn_cast<IREE::LinalgExt::GroupMatmulOp>(op)) { + result = setGroupMatmulDataTilingEncodings(rewriter, groupMatmul); + } else { + auto linalgOp = cast<linalg::LinalgOp>(op); + IREE::Encoding::removeDataTilingHint(linalgOp); + result = setDataTilingEncodings(rewriter, linalgOp, encodingOption); + } + if (failed(result)) { return signalPassFailure(); } }
diff --git a/compiler/src/iree/compiler/DispatchCreation/test/set_encoding.mlir b/compiler/src/iree/compiler/DispatchCreation/test/set_encoding.mlir index ef50384..de2433b 100644 --- a/compiler/src/iree/compiler/DispatchCreation/test/set_encoding.mlir +++ b/compiler/src/iree/compiler/DispatchCreation/test/set_encoding.mlir
@@ -71,6 +71,103 @@ // ----- +// Grouped matmul encodings use the same logical M/N/K metadata for input, +// output, and expert weights, including narrow N and dynamic M cases. +util.func public @group_matmul_narrow_n( + %input : tensor<3x2xf32>, %weights : tensor<2x2x1xf32>, + %offsets : tensor<2xi64>, %row_base : index, + %output : tensor<3x1xf32>) -> tensor<3x1xf32> { + %0 = iree_linalg_ext.group_matmul {"iree.opt.data_tiling"} ins( + %input, %weights, %offsets, %row_base : tensor<3x2xf32>, + tensor<2x2x1xf32>, tensor<2xi64>, index) + outs(%output : tensor<3x1xf32>) -> tensor<3x1xf32> + util.return %0 : tensor<3x1xf32> +} +// CHECK-DAG: #[[GROUP_INPUT:.+]] = #iree_encoding.encoding<operand_index = 0 : index, op_type = matmul{{.*}}iteration_sizes = [3, 1, 2]> +// CHECK-DAG: #[[GROUP_WEIGHTS:.+]] = #iree_encoding.encoding<operand_index = 1 : index, op_type = matmul{{.*}}iteration_sizes = [2, 3, 1, 2]> +// CHECK-DAG: #[[GROUP_OUTPUT:.+]] = #iree_encoding.encoding<operand_index = 2 : index, op_type = matmul{{.*}}iteration_sizes = [3, 1, 2]> +// CHECK: iree_encoding.set_encoding %{{.*}} : tensor<3x2xf32> -> tensor<3x2xf32, #[[GROUP_INPUT]]> +// CHECK: iree_encoding.set_encoding %{{.*}} : tensor<2x2x1xf32> -> tensor<2x2x1xf32, #[[GROUP_WEIGHTS]]> +// CHECK: iree_encoding.set_encoding %{{.*}} : tensor<3x1xf32> -> tensor<3x1xf32, #[[GROUP_OUTPUT]]> + +// ----- + +util.func public @group_matmul_dynamic_m( + %input : tensor<?x2xf32>, %weights : tensor<2x2x1xf32>, + %offsets : tensor<2xi64>, %row_base : index, + %output : tensor<?x1xf32>) -> tensor<?x1xf32> { + %0 = iree_linalg_ext.group_matmul {"iree.opt.data_tiling"} ins( + %input, %weights, %offsets, %row_base : tensor<?x2xf32>, + tensor<2x2x1xf32>, tensor<2xi64>, index) + outs(%output : tensor<?x1xf32>) -> tensor<?x1xf32> + util.return %0 : tensor<?x1xf32> +} +// CHECK-DAG: #[[$DYN_GROUP_INPUT:.+]] = #iree_encoding.encoding<operand_index = 0 : index, op_type = matmul{{.*}}iteration_sizes = [?, 1, 2]> +// CHECK-DAG: #[[$DYN_GROUP_WEIGHTS:.+]] = #iree_encoding.encoding<operand_index = 1 : index, op_type = matmul{{.*}}iteration_sizes = [2, ?, 1, 2]> +// CHECK-DAG: #[[$DYN_GROUP_OUTPUT:.+]] = #iree_encoding.encoding<operand_index = 2 : index, op_type = matmul{{.*}}iteration_sizes = [?, 1, 2]> +// CHECK-LABEL: util.func public @group_matmul_dynamic_m( +// CHECK-SAME: %[[INPUT:[^ :]+]]: tensor<?x2xf32> +// CHECK-SAME: %[[OUTPUT:[^ :]+]]: tensor<?x1xf32> +// CHECK: %[[M:.+]] = tensor.dim %[[INPUT]], %{{.*}} +// CHECK: iree_encoding.set_encoding %[[INPUT]] encoding_dims{%[[M]]} : tensor<?x2xf32> -> tensor<?x2xf32, #[[$DYN_GROUP_INPUT]]> +// CHECK: iree_encoding.set_encoding %{{.*}} encoding_dims{%[[M]]} : tensor<2x2x1xf32> -> tensor<2x2x1xf32, #[[$DYN_GROUP_WEIGHTS]]> +// CHECK: iree_encoding.set_encoding %[[OUTPUT]] encoding_dims{%[[M]]} : tensor<?x1xf32> -> tensor<?x1xf32, #[[$DYN_GROUP_OUTPUT]]> +// CHECK: %[[GROUP:.+]] = iree_linalg_ext.group_matmul +// CHECK: %[[OUT_M:.+]] = tensor.dim %[[OUTPUT]], %{{.*}} +// CHECK: iree_encoding.unset_encoding %[[GROUP]] encoding_dims{%[[M]]} : tensor<?x1xf32, #[[$DYN_GROUP_OUTPUT]]> -> tensor<?x1xf32>{%[[OUT_M]]}{{$}} + +// ----- + +util.func public @group_matmul_dynamic_input_static_output( + %input : tensor<?x2xf32>, %weights : tensor<2x2x1xf32>, + %offsets : tensor<2xi64>, %row_base : index, + %output : tensor<3x1xf32>) -> tensor<3x1xf32> { + %0 = iree_linalg_ext.group_matmul {"iree.opt.data_tiling"} ins( + %input, %weights, %offsets, %row_base : tensor<?x2xf32>, + tensor<2x2x1xf32>, tensor<2xi64>, index) + outs(%output : tensor<3x1xf32>) -> tensor<3x1xf32> + util.return %0 : tensor<3x1xf32> +} +// CHECK-DAG: #[[$DYN_INPUT_INPUT:.+]] = #iree_encoding.encoding<operand_index = 0 : index, op_type = matmul{{.*}}iteration_sizes = [?, 1, 2]> +// CHECK-DAG: #[[$DYN_INPUT_WEIGHTS:.+]] = #iree_encoding.encoding<operand_index = 1 : index, op_type = matmul{{.*}}iteration_sizes = [2, ?, 1, 2]> +// CHECK-DAG: #[[$DYN_INPUT_OUTPUT:.+]] = #iree_encoding.encoding<operand_index = 2 : index, op_type = matmul{{.*}}iteration_sizes = [?, 1, 2]> +// CHECK-LABEL: util.func public @group_matmul_dynamic_input_static_output( +// CHECK-SAME: %[[INPUT:[^ :]+]]: tensor<?x2xf32> +// CHECK-SAME: %[[OUTPUT:[^ :]+]]: tensor<3x1xf32> +// CHECK: %[[M:.+]] = tensor.dim %[[INPUT]], %{{.*}} +// CHECK: iree_encoding.set_encoding %[[INPUT]] encoding_dims{%[[M]]} : tensor<?x2xf32> -> tensor<?x2xf32, #[[$DYN_INPUT_INPUT]]> +// CHECK: iree_encoding.set_encoding %{{.*}} encoding_dims{%[[M]]} : tensor<2x2x1xf32> -> tensor<2x2x1xf32, #[[$DYN_INPUT_WEIGHTS]]> +// CHECK: iree_encoding.set_encoding %[[OUTPUT]] encoding_dims{%[[M]]} : tensor<3x1xf32> -> tensor<3x1xf32, #[[$DYN_INPUT_OUTPUT]]> +// CHECK: %[[GROUP:.+]] = iree_linalg_ext.group_matmul +// CHECK: iree_encoding.unset_encoding %[[GROUP]] encoding_dims{%[[M]]} : tensor<3x1xf32, #[[$DYN_INPUT_OUTPUT]]> -> tensor<3x1xf32>{{$}} + +// ----- + +util.func public @group_matmul_static_input_dynamic_output( + %input : tensor<3x2xf32>, %weights : tensor<2x2x1xf32>, + %offsets : tensor<2xi64>, %row_base : index, + %output : tensor<?x1xf32>) -> tensor<?x1xf32> { + %0 = iree_linalg_ext.group_matmul {"iree.opt.data_tiling"} ins( + %input, %weights, %offsets, %row_base : tensor<3x2xf32>, + tensor<2x2x1xf32>, tensor<2xi64>, index) + outs(%output : tensor<?x1xf32>) -> tensor<?x1xf32> + util.return %0 : tensor<?x1xf32> +} +// CHECK-DAG: #[[$DYN_OUTPUT_INPUT:.+]] = #iree_encoding.encoding<operand_index = 0 : index, op_type = matmul{{.*}}iteration_sizes = [3, 1, 2]> +// CHECK-DAG: #[[$DYN_OUTPUT_WEIGHTS:.+]] = #iree_encoding.encoding<operand_index = 1 : index, op_type = matmul{{.*}}iteration_sizes = [2, 3, 1, 2]> +// CHECK-DAG: #[[$DYN_OUTPUT_OUTPUT:.+]] = #iree_encoding.encoding<operand_index = 2 : index, op_type = matmul{{.*}}iteration_sizes = [3, 1, 2]> +// CHECK-LABEL: util.func public @group_matmul_static_input_dynamic_output( +// CHECK-SAME: %[[INPUT:[^ :]+]]: tensor<3x2xf32> +// CHECK-SAME: %[[OUTPUT:[^ :]+]]: tensor<?x1xf32> +// CHECK: iree_encoding.set_encoding %[[INPUT]] : tensor<3x2xf32> -> tensor<3x2xf32, #[[$DYN_OUTPUT_INPUT]]> +// CHECK: iree_encoding.set_encoding %{{.*}} : tensor<2x2x1xf32> -> tensor<2x2x1xf32, #[[$DYN_OUTPUT_WEIGHTS]]> +// CHECK: iree_encoding.set_encoding %[[OUTPUT]] : tensor<?x1xf32> -> tensor<?x1xf32, #[[$DYN_OUTPUT_OUTPUT]]> +// CHECK: %[[GROUP:.+]] = iree_linalg_ext.group_matmul +// CHECK: %[[OUT_M:.+]] = tensor.dim %[[OUTPUT]], %{{.*}} +// CHECK: iree_encoding.unset_encoding %[[GROUP]] : tensor<?x1xf32, #[[$DYN_OUTPUT_OUTPUT]]> -> tensor<?x1xf32>{%[[OUT_M]]}{{$}} + +// ----- + util.func public @matmul_f32f32f32_parallel_reduce_parallel(%arg0 : tensor<32x128xf32>, %arg1 : tensor<128x4096xf32>, %arg2 : tensor<4096x32xf32>) -> tensor<4096x32xf32> { %0 = linalg.generic {indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1)>, affine_map<(d0, d1, d2) -> (d1, d2)>, affine_map<(d0, d1, d2) -> (d2, d0)>], iterator_types = ["parallel", "reduction", "parallel"]} ins(%arg0, %arg1 : tensor<32x128xf32>, tensor<128x4096xf32>) outs(%arg2 : tensor<4096x32xf32>) {
diff --git a/compiler/src/iree/compiler/ExternalInterfaces/LinalgExtExternalModels.cpp b/compiler/src/iree/compiler/ExternalInterfaces/LinalgExtExternalModels.cpp index 2dd2971..a4e3e9d 100644 --- a/compiler/src/iree/compiler/ExternalInterfaces/LinalgExtExternalModels.cpp +++ b/compiler/src/iree/compiler/ExternalInterfaces/LinalgExtExternalModels.cpp
@@ -126,6 +126,10 @@ registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) { IREE::LinalgExt::registerConcatOpTilingInterfaceExternalModel(ctx); }); + registry.addExtension( + +[](MLIRContext *ctx, IREE::LinalgExt::IREELinalgExtDialect *dialect) { + IREE::LinalgExt::registerGroupMatmulTilingInterfaceExternalModel(ctx); + }); } } // namespace mlir::iree_compiler
diff --git a/tests/e2e/linalg_ext_ops/BUILD.bazel b/tests/e2e/linalg_ext_ops/BUILD.bazel index 57238d5..ab07d93 100644 --- a/tests/e2e/linalg_ext_ops/BUILD.bazel +++ b/tests/e2e/linalg_ext_ops/BUILD.bazel
@@ -32,11 +32,23 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "scan_configured.mlir", ], ) iree_check_single_backend_test_suite( + name = "check_llvm-cpu_grouped_matmul_local-task", + srcs = ["grouped_matmul.mlir"], + compiler_flags = [ + "--iree-dispatch-creation-data-tiling=true", + "--iree-llvmcpu-target-cpu=generic", + ], + driver = "local-task", + target_backend = "llvm-cpu", +) + +iree_check_single_backend_test_suite( name = "check_llvm-cpu_local-task", srcs = ALL_SRCS, compiler_flags = ["--iree-llvmcpu-target-cpu=generic"], @@ -68,6 +80,7 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "attention_i1_mask.mlir", "scan_configured.mlir", ], @@ -96,6 +109,7 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "attention.mlir", "attention_i1_mask.mlir", "dynamic_attention.mlir", @@ -136,6 +150,7 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "top-k.mlir", "attention_i1_mask.mlir", "dynamic_attention.mlir", @@ -177,6 +192,7 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "attention.mlir", "attention_i1_mask.mlir", "dynamic_attention.mlir", @@ -209,6 +225,7 @@ ], include = ["*.mlir"], exclude = [ + "grouped_matmul.mlir", "attention.mlir", "attention_i1_mask.mlir", "dynamic_attention.mlir",
diff --git a/tests/e2e/linalg_ext_ops/CMakeLists.txt b/tests/e2e/linalg_ext_ops/CMakeLists.txt index aba7ceb..37c10c7 100644 --- a/tests/e2e/linalg_ext_ops/CMakeLists.txt +++ b/tests/e2e/linalg_ext_ops/CMakeLists.txt
@@ -12,6 +12,20 @@ iree_check_single_backend_test_suite( NAME + check_llvm-cpu_grouped_matmul_local-task + SRCS + "grouped_matmul.mlir" + TARGET_BACKEND + "llvm-cpu" + DRIVER + "local-task" + COMPILER_FLAGS + "--iree-dispatch-creation-data-tiling=true" + "--iree-llvmcpu-target-cpu=generic" +) + +iree_check_single_backend_test_suite( + NAME check_llvm-cpu_local-task SRCS "arg_compare.mlir"
diff --git a/tests/e2e/linalg_ext_ops/grouped_matmul.mlir b/tests/e2e/linalg_ext_ops/grouped_matmul.mlir new file mode 100644 index 0000000..5bd0387 --- /dev/null +++ b/tests/e2e/linalg_ext_ops/grouped_matmul.mlir
@@ -0,0 +1,65 @@ +func.func @grouped_matmul_regular() { + %input = util.unfoldable_constant dense<[[1.0], [2.0], [3.0]]> : tensor<3x1xf32> + %weights = util.unfoldable_constant dense<[ + [[1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], + [[3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]]> : tensor<2x1x8xf32> + %offsets = util.unfoldable_constant dense<[1, 3]> : tensor<2xi64> + %row_base = arith.constant 0 : index + %output = util.unfoldable_constant dense<0.0> : tensor<3x8xf32> + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %row_base : tensor<3x1xf32>, + tensor<2x1x8xf32>, tensor<2xi64>, index) + outs(%output : tensor<3x8xf32>) -> tensor<3x8xf32> + check.expect_almost_eq_const(%result, + dense<[[1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [6.0, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [9.0, 12.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]> : tensor<3x8xf32>) + : tensor<3x8xf32> + return +} + +func.func @grouped_matmul_narrow_n() { + %input = util.unfoldable_constant dense<[ + [1.0, 2.0], + [3.0, 4.0], + [5.0, 6.0]]> : tensor<3x2xf32> + %weights = util.unfoldable_constant dense<[ + [[2.0], [1.0]], + [[4.0], [3.0]]]> : tensor<2x2x1xf32> + %offsets = util.unfoldable_constant dense<[1, 3]> : tensor<2xi64> + %row_base = arith.constant 0 : index + %output = util.unfoldable_constant dense<0.0> : tensor<3x1xf32> + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %row_base : tensor<3x2xf32>, + tensor<2x2x1xf32>, tensor<2xi64>, index) + outs(%output : tensor<3x1xf32>) -> tensor<3x1xf32> + check.expect_almost_eq_const(%result, + dense<[[4.0], [24.0], [38.0]]> : tensor<3x1xf32>) + : tensor<3x1xf32> + return +} + +func.func @grouped_matmul_dynamic_k_and_columns() { + %input = flow.tensor.dynamic_constant dense<[ + [1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]> + : tensor<3x2xf32> -> tensor<3x?xf32> + %weights = flow.tensor.dynamic_constant dense<[ + [[1.0, 2.0], [3.0, 4.0]], + [[5.0, 6.0], [7.0, 8.0]]]> + : tensor<2x2x2xf32> -> tensor<2x?x?xf32> + %offsets = util.unfoldable_constant dense<[1, 3]> : tensor<2xi64> + %row_base = arith.constant 0 : index + %output = flow.tensor.dynamic_constant dense<99.0> + : tensor<3x2xf32> -> tensor<3x?xf32> + %result = iree_linalg_ext.group_matmul ins( + %input, %weights, %offsets, %row_base : tensor<3x?xf32>, + tensor<2x?x?xf32>, tensor<2xi64>, index) + outs(%output : tensor<3x?xf32>) -> tensor<3x?xf32> + // Keep the result shape dynamic until after the grouped matmul is lowered. + %barrier = util.optimization_barrier %result : tensor<3x?xf32> + %result_static = tensor.cast %barrier : tensor<3x?xf32> to tensor<3x2xf32> + check.expect_almost_eq_const(%result_static, + dense<[[7.0, 10.0], [43.0, 50.0], [67.0, 78.0]]> : tensor<3x2xf32>) + : tensor<3x2xf32> + return +}