Skip to content

Commit 09b2d2a

Browse files
[MHLO] Add pass to move up dynamic broadcasts for fusion
For now, the pass only reifies the required shape computations. Moving broadcasts will follow to allow for fusion across them. PiperOrigin-RevId: 362033715 Change-Id: I63ea38e033e2e5636c1d858c42b6c37041566bb0
1 parent 31d3a54 commit 09b2d2a

7 files changed

Lines changed: 181 additions & 0 deletions

File tree

‎tensorflow/compiler/mlir/hlo/BUILD‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,29 @@ cc_library(
641641
alwayslink = 1,
642642
)
643643

644+
cc_library(
645+
name = "move_up_dynamic_broadcasts_for_fusion",
646+
srcs = ["lib/Dialect/mhlo/transforms/move_up_dynamic_broadcasts_for_fusion.cc"],
647+
hdrs = [
648+
"include/mlir-hlo/Dialect/mhlo/transforms/passes.h",
649+
"include/mlir-hlo/Dialect/mhlo/transforms/rewriters.h",
650+
],
651+
deps = [
652+
":hlo",
653+
":map_chlo_to_hlo_op",
654+
"@llvm-project//llvm:Support",
655+
"@llvm-project//mlir:IR",
656+
"@llvm-project//mlir:InferTypeOpInterface",
657+
"@llvm-project//mlir:Pass",
658+
"@llvm-project//mlir:SCFDialect",
659+
"@llvm-project//mlir:Shape",
660+
"@llvm-project//mlir:StandardOps",
661+
"@llvm-project//mlir:TensorDialect",
662+
"@llvm-project//mlir:Transforms",
663+
],
664+
alwayslink = 1,
665+
)
666+
644667
cc_library(
645668
name = "lhlo_legalize_to_gpu",
646669
srcs = ["lib/Dialect/mhlo/transforms/lhlo_legalize_to_gpu.cc"],
@@ -1013,6 +1036,7 @@ cc_library(
10131036
":mhlo_control_flow_to_scf",
10141037
":mhlo_fusion",
10151038
":mhlo_to_mhlo_lowering_patterns",
1039+
":move_up_dynamic_broadcasts_for_fusion",
10161040
":sink_constants_to_control_flow",
10171041
":test_passes",
10181042
":transform_unranked_hlo",

‎tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/mhlo_passes.td‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,12 @@ def TransformUnrankedHloPass : Pass<"mhlo-transform-unranked-hlo", "FuncOp"> {
110110
let constructor = "createTransformUnrankedHloPass()";
111111
}
112112

113+
def MoveUpDynamicBroadcastsForFusionPass :
114+
Pass<"mhlo-move-up-dynamic-broadcasts-for-fusion", "FuncOp"> {
115+
let summary = "Move up dynamic broadcasts and shape computations to allow "
116+
"for fusion across broadcasts.";
117+
let constructor = "createMoveUpDynamicBroadcastsForFusionPass()";
118+
}
113119

114120
def TestUnfuseBatchNormPass : Pass<"mhlo-test-unfuse-batch-norm", "FuncOp"> {
115121
let summary = "Test pass for materializing 'broadcast_dimensions' attributes.";

‎tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/passes.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ std::unique_ptr<OperationPass<FuncOp>> createMhloFusionPass();
6767
std::unique_ptr<OperationPass<FuncOp>>
6868
createLegalizeTrigonometricToApproximationPass();
6969

70+
std::unique_ptr<FunctionPass> createMoveUpDynamicBroadcastsForFusionPass();
71+
7072
std::unique_ptr<FunctionPass> createOptimizeMhloPass();
7173
std::unique_ptr<FunctionPass> createLowerComplexPass();
7274
std::unique_ptr<::mlir::Pass> createLegalizeGeneralDotPass();

‎tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/rewriters.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ void SetupTransformUnrankedHloLegality(MLIRContext *context,
7979
void PopulateTransformUnrankedHloPatterns(MLIRContext *context,
8080
OwningRewritePatternList *patterns);
8181

82+
void PopulateDynamicShapeFusionPatterns(MLIRContext *context,
83+
OwningRewritePatternList *patterns);
84+
8285
// Populate a collection of conversion patterns for un-fusing
8386
// batch_norm_inference and batch_norm_training into constituent HLO ops.
8487
// TODO(laurenzo): Implement un-fusing of batch_norm_training.
@@ -90,6 +93,11 @@ void PopulateUnfuseBatchNormPatterns(MLIRContext *context,
9093
void PopulateTrigonometricToApproximationPatterns(
9194
MLIRContext *context, OwningRewritePatternList *patterns);
9295

96+
void PopulateMoveUpDynamicBroadcastsForFusionLegality(ConversionTarget *target);
97+
98+
void PopulateMoveUpDynamicBroadcastsForFusionPatterns(
99+
MLIRContext *context, OwningRewritePatternList *patterns);
100+
93101
} // namespace mhlo
94102

95103
namespace chlo {

‎tensorflow/compiler/mlir/hlo/lib/Dialect/mhlo/transforms/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ add_mlir_library(ChloPasses
4848
)
4949

5050
add_mlir_library(MhloPasses
51+
move_up_dynamic_broadcasts_for_fusion.cc
5152
legalize_gather_to_torch_index_select.cc
5253
legalize_trigonometric_to_approximation.cc
5354
lower_complex.cc
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
15+
==============================================================================*/
16+
17+
#include "llvm/ADT/SmallVector.h"
18+
#include "llvm/Support/Casting.h"
19+
#include "mlir-hlo/Dialect/mhlo/IR/chlo_ops.h"
20+
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
21+
#include "mlir-hlo/Dialect/mhlo/transforms/map_chlo_to_hlo_op.h"
22+
#include "mlir-hlo/Dialect/mhlo/transforms/passes.h"
23+
#include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h"
24+
#include "mlir/Dialect/SCF/SCF.h"
25+
#include "mlir/Dialect/Shape/IR/Shape.h"
26+
#include "mlir/Dialect/StandardOps/IR/Ops.h"
27+
#include "mlir/Dialect/Tensor/IR/Tensor.h"
28+
#include "mlir/IR/BuiltinOps.h"
29+
#include "mlir/IR/BuiltinTypes.h"
30+
#include "mlir/IR/MLIRContext.h"
31+
#include "mlir/IR/Operation.h"
32+
#include "mlir/IR/OperationSupport.h"
33+
#include "mlir/IR/PatternMatch.h"
34+
#include "mlir/Interfaces/InferTypeOpInterface.h"
35+
#include "mlir/Pass/Pass.h"
36+
#include "mlir/Transforms/DialectConversion.h"
37+
38+
namespace mlir {
39+
namespace mhlo {
40+
namespace {
41+
42+
struct ShapeOfOpConversion : public OpConversionPattern<shape::ShapeOfOp> {
43+
explicit ShapeOfOpConversion(MLIRContext *context)
44+
: OpConversionPattern<shape::ShapeOfOp>(context) {}
45+
46+
LogicalResult matchAndRewrite(
47+
shape::ShapeOfOp op, ArrayRef<Value> operands,
48+
ConversionPatternRewriter &rewriter) const override {
49+
shape::ShapeOfOp::Adaptor transformed(operands);
50+
51+
auto shape_origin = llvm::dyn_cast_or_null<InferShapedTypeOpInterface>(
52+
transformed.arg().getDefiningOp());
53+
if (!shape_origin) return failure();
54+
55+
llvm::SmallVector<Value, 1> reified_shapes;
56+
if (failed(shape_origin.reifyReturnTypeShapes(rewriter, reified_shapes)))
57+
return failure();
58+
59+
assert(reified_shapes.size() == 1);
60+
Value reified_shape = reified_shapes.front();
61+
if (reified_shape.getType() != op.getType()) {
62+
reified_shape = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(),
63+
reified_shape);
64+
}
65+
66+
rewriter.replaceOp(op, reified_shapes.front());
67+
return success();
68+
}
69+
};
70+
71+
struct MoveUpDynamicBroadcastsForFusionPass
72+
: public PassWrapper<MoveUpDynamicBroadcastsForFusionPass, FunctionPass> {
73+
void getDependentDialects(DialectRegistry &registry) const override {
74+
registry.insert<shape::ShapeDialect, mhlo::MhloDialect>();
75+
}
76+
77+
void runOnFunction() override {
78+
// Setup target legality.
79+
MLIRContext &ctx = getContext();
80+
ConversionTarget target(ctx);
81+
PopulateMoveUpDynamicBroadcastsForFusionLegality(&target);
82+
83+
// Populate rewrite patterns.
84+
OwningRewritePatternList patterns;
85+
mhlo::PopulateMoveUpDynamicBroadcastsForFusionPatterns(&ctx, &patterns);
86+
87+
// Apply transformation.
88+
if (failed(applyPartialConversion(getFunction(), target,
89+
std::move(patterns)))) {
90+
return signalPassFailure();
91+
}
92+
}
93+
};
94+
95+
} // namespace
96+
97+
void PopulateMoveUpDynamicBroadcastsForFusionLegality(
98+
ConversionTarget *target) {
99+
target->addLegalDialect<MhloDialect, StandardOpsDialect,
100+
tensor::TensorDialect>();
101+
}
102+
103+
void PopulateMoveUpDynamicBroadcastsForFusionPatterns(
104+
MLIRContext *context, OwningRewritePatternList *patterns) {
105+
// clang-format off
106+
patterns->insert<ShapeOfOpConversion>(context);
107+
// clang-format on
108+
}
109+
110+
std::unique_ptr<FunctionPass> createMoveUpDynamicBroadcastsForFusionPass() {
111+
return std::make_unique<MoveUpDynamicBroadcastsForFusionPass>();
112+
}
113+
114+
} // namespace mhlo
115+
} // namespace mlir
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// RUN: mlir-hlo-opt --split-input-file --allow-unregistered-dialect --mhlo-move-up-dynamic-broadcasts-for-fusion --canonicalize --cse %s | FileCheck %s
2+
3+
// Shape computations shall be reified.
4+
// CHECK-LABEL: @shape_of_unary
5+
// CHECK-SAME: (%[[ARG:.*]]: tensor<?x32xi16>)
6+
func @shape_of_unary(%arg : tensor<?x32xi16>) {
7+
// CHECK-NOT: shape_of
8+
%0 = "mhlo.convert"(%arg) : (tensor<?x32xi16>) -> tensor<?x32xf16>
9+
%1 = shape.shape_of %0 : tensor<?x32xf16> -> tensor<?xindex>
10+
"use"(%1) : (tensor<?xindex>) -> ()
11+
return
12+
}
13+
14+
// -----
15+
16+
// Shape computations shall be reified.
17+
// CHECK-LABEL: @shape_of_nary
18+
// CHECK-SAME: (%[[ARG0:.*]]: tensor<?x32xf16>, %[[ARG1:.*]]: tensor<?x32xf16>)
19+
func @shape_of_nary(%arg0 : tensor<?x32xf16>, %arg1 : tensor<?x32xf16>) {
20+
// CHECK-NOT: shape_of
21+
%0 = mhlo.subtract %arg0, %arg1 : tensor<?x32xf16>
22+
%1 = shape.shape_of %0 : tensor<?x32xf16> -> tensor<?xindex>
23+
"use"(%1) : (tensor<?xindex>) -> ()
24+
return
25+
}

0 commit comments

Comments
 (0)