-
Notifications
You must be signed in to change notification settings - Fork 14.3k
[mlir][gpu] Add patterns to break down subgroup reduce #76271
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
150 changes: 150 additions & 0 deletions
150
mlir/lib/Dialect/GPU/Transforms/SubgroupReduceLowering.cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
//===- SubgroupReduceLowering.cpp - subgroup_reduce lowering patterns -----===// | ||
// | ||
// Part of the LLVM Project, 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 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// Implements gradual lowering of `gpu.subgroup_reduce` ops. | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "mlir/Dialect/Arith/IR/Arith.h" | ||
#include "mlir/Dialect/GPU/IR/GPUDialect.h" | ||
#include "mlir/Dialect/GPU/Transforms/Passes.h" | ||
#include "mlir/Dialect/Vector/IR/VectorOps.h" | ||
#include "mlir/IR/Location.h" | ||
#include "mlir/IR/PatternMatch.h" | ||
#include "mlir/Support/LogicalResult.h" | ||
#include "llvm/Support/FormatVariadic.h" | ||
#include "llvm/Support/MathExtras.h" | ||
#include <cassert> | ||
|
||
using namespace mlir; | ||
|
||
namespace { | ||
|
||
/// Example, assumes `maxShuffleBitwidth` equal to 32: | ||
/// ``` | ||
/// %a = gpu.subgroup_reduce add %x : (vector<3xf16>) -> vector<3xf16> | ||
/// ==> | ||
/// %v0 = arith.constant dense<0.0> : vector<3xf16> | ||
/// %e0 = vector.extract_strided_slice %x | ||
/// {offsets = [0], sizes = [2], strides = [1}: vector<3xf32> to vector<2xf32> | ||
/// %r0 = gpu.subgroup_reduce add %e0 : (vector<2xf16>) -> vector<2xf16> | ||
/// %v1 = vector.insert_strided_slice %r0, %v0 | ||
/// {offsets = [0], strides = [1}: vector<2xf32> into vector<3xf32> | ||
/// %e1 = vector.extract %x[2] : f16 from vector<2xf16> | ||
/// %r1 = gpu.subgroup_reduce add %e1 : (f16) -> f16 | ||
/// %a = vector.insert %r1, %v1[2] : f16 into vector<3xf16> | ||
/// ``` | ||
struct BreakDownSubgroupReduce final : OpRewritePattern<gpu::SubgroupReduceOp> { | ||
BreakDownSubgroupReduce(MLIRContext *ctx, unsigned maxShuffleBitwidth, | ||
PatternBenefit benefit) | ||
: OpRewritePattern(ctx, benefit), maxShuffleBitwidth(maxShuffleBitwidth) { | ||
} | ||
|
||
LogicalResult matchAndRewrite(gpu::SubgroupReduceOp op, | ||
PatternRewriter &rewriter) const override { | ||
auto vecTy = dyn_cast<VectorType>(op.getType()); | ||
if (!vecTy || vecTy.getNumElements() < 2) | ||
return rewriter.notifyMatchFailure(op, "not a multi-element reduction"); | ||
|
||
assert(vecTy.getRank() == 1 && "Unexpected vector type"); | ||
assert(!vecTy.isScalable() && "Unexpected vector type"); | ||
|
||
Type elemTy = vecTy.getElementType(); | ||
unsigned elemBitwidth = elemTy.getIntOrFloatBitWidth(); | ||
if (elemBitwidth >= maxShuffleBitwidth) | ||
return rewriter.notifyMatchFailure( | ||
op, llvm::formatv("element type too large {0}, cannot break down " | ||
"into vectors of bitwidth {1} or less", | ||
elemBitwidth, maxShuffleBitwidth)); | ||
|
||
unsigned elementsPerShuffle = maxShuffleBitwidth / elemBitwidth; | ||
assert(elementsPerShuffle >= 1); | ||
|
||
unsigned numNewReductions = | ||
llvm::divideCeil(vecTy.getNumElements(), elementsPerShuffle); | ||
assert(numNewReductions >= 1); | ||
if (numNewReductions == 1) | ||
return rewriter.notifyMatchFailure(op, "nothing to break down"); | ||
|
||
Location loc = op.getLoc(); | ||
Value res = | ||
rewriter.create<arith::ConstantOp>(loc, rewriter.getZeroAttr(vecTy)); | ||
|
||
for (unsigned i = 0; i != numNewReductions; ++i) { | ||
int64_t startIdx = i * elementsPerShuffle; | ||
int64_t endIdx = | ||
std::min(startIdx + elementsPerShuffle, vecTy.getNumElements()); | ||
int64_t numElems = endIdx - startIdx; | ||
|
||
Value extracted; | ||
if (numElems == 1) { | ||
extracted = | ||
rewriter.create<vector::ExtractOp>(loc, op.getValue(), startIdx); | ||
} else { | ||
extracted = rewriter.create<vector::ExtractStridedSliceOp>( | ||
loc, op.getValue(), /*offsets=*/startIdx, /*sizes=*/numElems, | ||
/*strides=*/1); | ||
} | ||
|
||
Value reduce = rewriter.create<gpu::SubgroupReduceOp>( | ||
loc, extracted, op.getOp(), op.getUniform()); | ||
if (numElems == 1) { | ||
res = rewriter.create<vector::InsertOp>(loc, reduce, res, startIdx); | ||
continue; | ||
} | ||
|
||
res = rewriter.create<vector::InsertStridedSliceOp>( | ||
loc, reduce, res, /*offsets=*/startIdx, /*strides=*/1); | ||
kuhar marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
rewriter.replaceOp(op, res); | ||
return success(); | ||
} | ||
|
||
private: | ||
unsigned maxShuffleBitwidth = 0; | ||
}; | ||
|
||
/// Example: | ||
/// ``` | ||
/// %a = gpu.subgroup_reduce add %x : (vector<1xf32>) -> vector<1xf32> | ||
/// ==> | ||
/// %e0 = vector.extract %x[0] : f32 from vector<1xf32> | ||
/// %r0 = gpu.subgroup_reduce add %e0 : (f32) -> f32 | ||
/// %a = vector.broadcast %r0 : f32 to vector<1xf32> | ||
/// ``` | ||
struct ScalarizeSingleElementReduce final | ||
: OpRewritePattern<gpu::SubgroupReduceOp> { | ||
using OpRewritePattern::OpRewritePattern; | ||
|
||
LogicalResult matchAndRewrite(gpu::SubgroupReduceOp op, | ||
PatternRewriter &rewriter) const override { | ||
auto vecTy = dyn_cast<VectorType>(op.getType()); | ||
if (!vecTy || vecTy.getNumElements() != 1) | ||
return rewriter.notifyMatchFailure(op, "not a single-element reduction"); | ||
|
||
assert(vecTy.getRank() == 1 && "Unexpected vector type"); | ||
assert(!vecTy.isScalable() && "Unexpected vector type"); | ||
Location loc = op.getLoc(); | ||
Value extracted = rewriter.create<vector::ExtractOp>(loc, op.getValue(), 0); | ||
Value reduce = rewriter.create<gpu::SubgroupReduceOp>( | ||
loc, extracted, op.getOp(), op.getUniform()); | ||
rewriter.replaceOpWithNewOp<vector::BroadcastOp>(op, vecTy, reduce); | ||
return success(); | ||
} | ||
}; | ||
|
||
} // namespace | ||
|
||
void mlir::populateGpuBreakDownSubgrupReducePatterns( | ||
RewritePatternSet &patterns, unsigned maxShuffleBitwidth, | ||
PatternBenefit benefit) { | ||
patterns.add<BreakDownSubgroupReduce>(patterns.getContext(), | ||
maxShuffleBitwidth, benefit); | ||
patterns.add<ScalarizeSingleElementReduce>(patterns.getContext(), benefit); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// RUN: mlir-opt --allow-unregistered-dialect --test-gpu-subgroup-reduce-lowering %s | FileCheck %s | ||
|
||
// CHECK: gpu.module @kernels { | ||
gpu.module @kernels { | ||
|
||
// CHECK-LABEL: gpu.func @kernel0( | ||
// CHECK-SAME: %[[ARG0:.+]]: vector<5xf16>) | ||
gpu.func @kernel0(%arg0: vector<5xf16>) kernel { | ||
// CHECK: %[[VZ:.+]] = arith.constant dense<0.0{{.*}}> : vector<5xf16> | ||
// CHECK: %[[E0:.+]] = vector.extract_strided_slice %[[ARG0]] {offsets = [0], sizes = [2], strides = [1]} : vector<5xf16> to vector<2xf16> | ||
// CHECK: %[[R0:.+]] = gpu.subgroup_reduce add %[[E0]] : (vector<2xf16>) -> vector<2xf16> | ||
// CHECK: %[[V0:.+]] = vector.insert_strided_slice %[[R0]], %[[VZ]] {offsets = [0], strides = [1]} : vector<2xf16> into vector<5xf16> | ||
// CHECK: %[[E1:.+]] = vector.extract_strided_slice %[[ARG0]] {offsets = [2], sizes = [2], strides = [1]} : vector<5xf16> to vector<2xf16> | ||
// CHECK: %[[R1:.+]] = gpu.subgroup_reduce add %[[E1]] : (vector<2xf16>) -> vector<2xf16> | ||
// CHECK: %[[V1:.+]] = vector.insert_strided_slice %[[R1]], %[[V0]] {offsets = [2], strides = [1]} : vector<2xf16> into vector<5xf16> | ||
// CHECK: %[[E2:.+]] = vector.extract %[[ARG0]][4] : f16 from vector<5xf16> | ||
// CHECK: %[[R2:.+]] = gpu.subgroup_reduce add %[[E2]] : (f16) -> f16 | ||
// CHECK: %[[V2:.+]] = vector.insert %[[R2]], %[[V1]] [4] : f16 into vector<5xf16> | ||
// CHECK: "test.consume"(%[[V2]]) : (vector<5xf16>) -> () | ||
%sum0 = gpu.subgroup_reduce add %arg0 : (vector<5xf16>) -> (vector<5xf16>) | ||
"test.consume"(%sum0) : (vector<5xf16>) -> () | ||
|
||
|
||
// CHECK-COUNT-3: gpu.subgroup_reduce mul {{.+}} uniform | ||
// CHECK: "test.consume" | ||
%sum1 = gpu.subgroup_reduce mul %arg0 uniform : (vector<5xf16>) -> (vector<5xf16>) | ||
"test.consume"(%sum1) : (vector<5xf16>) -> () | ||
|
||
// CHECK: gpu.return | ||
gpu.return | ||
} | ||
|
||
// CHECK-LABEL: gpu.func @kernel1( | ||
// CHECK-SAME: %[[ARG0:.+]]: vector<1xf32>) | ||
gpu.func @kernel1(%arg0: vector<1xf32>) kernel { | ||
// CHECK: %[[E0:.+]] = vector.extract %[[ARG0]][0] : f32 from vector<1xf32> | ||
// CHECK: %[[R0:.+]] = gpu.subgroup_reduce add %[[E0]] : (f32) -> f32 | ||
// CHECK: %[[V0:.+]] = vector.broadcast %[[R0]] : f32 to vector<1xf32> | ||
// CHECK: "test.consume"(%[[V0]]) : (vector<1xf32>) -> () | ||
%sum0 = gpu.subgroup_reduce add %arg0 : (vector<1xf32>) -> (vector<1xf32>) | ||
"test.consume"(%sum0) : (vector<1xf32>) -> () | ||
|
||
// CHECK: gpu.subgroup_reduce add {{.+}} uniform : (f32) -> f32 | ||
// CHECK: "test.consume" | ||
%sum1 = gpu.subgroup_reduce add %arg0 uniform : (vector<1xf32>) -> (vector<1xf32>) | ||
"test.consume"(%sum1) : (vector<1xf32>) -> () | ||
|
||
// CHECK: gpu.return | ||
gpu.return | ||
} | ||
|
||
// These vectors fit the native shuffle size and should not be broken down. | ||
// | ||
// CHECK-LABEL: gpu.func @kernel2( | ||
// CHECK-SAME: %[[ARG0:.+]]: vector<3xi8>, %[[ARG1:.+]]: vector<4xi8>) | ||
gpu.func @kernel2(%arg0: vector<3xi8>, %arg1: vector<4xi8>) kernel { | ||
// CHECK: %[[R0:.+]] = gpu.subgroup_reduce add %[[ARG0]] : (vector<3xi8>) -> vector<3xi8> | ||
// CHECK: "test.consume"(%[[R0]]) : (vector<3xi8>) -> () | ||
%sum0 = gpu.subgroup_reduce add %arg0 : (vector<3xi8>) -> (vector<3xi8>) | ||
"test.consume"(%sum0) : (vector<3xi8>) -> () | ||
|
||
// CHECK: %[[R1:.+]] = gpu.subgroup_reduce add %[[ARG1]] : (vector<4xi8>) -> vector<4xi8> | ||
// CHECK: "test.consume"(%[[R1]]) : (vector<4xi8>) -> () | ||
%sum1 = gpu.subgroup_reduce add %arg1 : (vector<4xi8>) -> (vector<4xi8>) | ||
"test.consume"(%sum1) : (vector<4xi8>) -> () | ||
|
||
// CHECK: gpu.return | ||
gpu.return | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.