1 /* Copyright 2020 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 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "mlir/Dialect/Func/IR/FuncOps.h"  // from @llvm-project
20 #include "mlir/IR/Attributes.h"  // from @llvm-project
21 #include "mlir/IR/Builders.h"  // from @llvm-project
22 #include "mlir/IR/SymbolTable.h"  // from @llvm-project
23 #include "mlir/Pass/Pass.h"  // from @llvm-project
24 #include "mlir/Pass/PassManager.h"  // from @llvm-project
25 #include "mlir/Support/LLVM.h"  // from @llvm-project
26 #include "mlir/Transforms/Passes.h"  // from @llvm-project
27 #include "mlir/Transforms/RegionUtils.h"  // from @llvm-project
28 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
29 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
30 #include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
31 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
32 #include "tensorflow/compiler/mlir/tensorflow/transforms/passes_detail.h"
33 #include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h"
34 #include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
35 
36 namespace mlir {
37 namespace tf_executor {
38 
39 namespace {
40 constexpr llvm::StringRef kNestedModule = "_tpu_v1_compat_outlined";
41 constexpr llvm::StringRef kOutlinedFuncPrefix = "_tpu_v1_compat_outlined_func";
42 
43 // Extract the islands containing a TPU cluster computation into an outlined
44 // function in a nested module. This will allow to run the usual bridge on this
45 // nested module which exhibit a more friendly "V2-like" structure.
46 // This is only intended for V1 compatibility mode where the bridge runs without
47 // feed/fetches on session create/extend.
48 struct TPUBridgeExecutorIslandOutlining
49     : public TF::TPUBridgeExecutorIslandOutliningPassBase<
50           TPUBridgeExecutorIslandOutlining> {
51   void runOnOperation() override;
52 };
53 
54 // Move FuncOp referenced by `symbol_ref` from one symbol table to another.
MoveFuncOp(FlatSymbolRefAttr & symbol_ref,SymbolTable & from,SymbolTable & to)55 void MoveFuncOp(FlatSymbolRefAttr &symbol_ref, SymbolTable &from,
56                 SymbolTable &to) {
57   if (to.lookup<func::FuncOp>(symbol_ref.getValue())) return;
58   func::FuncOp callee = from.lookup<func::FuncOp>(symbol_ref.getValue());
59   callee.getOperation()->getBlock()->getOperations().remove(
60       callee.getOperation());
61   to.insert(callee);
62 }
63 
runOnOperation()64 void TPUBridgeExecutorIslandOutlining::runOnOperation() {
65   MLIRContext *ctx = &getContext();
66 
67   SymbolTable symbol_table(getOperation());
68   if (Operation *nested_module = symbol_table.lookup(kNestedModule)) {
69     nested_module->emitOpError("unexpected already present outlined module.");
70     return signalPassFailure();
71   }
72   ModuleOp outlined_module = ModuleOp::create(getOperation().getLoc());
73   outlined_module->setAttrs(getOperation()->getAttrDictionary());
74   outlined_module->setAttr(SymbolTable::getSymbolAttrName(),
75                            StringAttr::get(ctx, kNestedModule));
76   symbol_table.insert(outlined_module);
77   SymbolTable outlined_symbol_table(outlined_module);
78 
79   // Find every island that contains a TPU node and extract it into a new module
80   // to run the V1 bridge there.
81   llvm::SmallVector<IslandOp, 8> islands_to_outline;
82   getOperation().walk([&](IslandOp island_op) {
83     auto parent_func = island_op->getParentOfType<func::FuncOp>();
84     auto skip_island_outlining =
85         parent_func->getAttrOfType<BoolAttr>(mlir::TF::kSkipIslandOutlining);
86     if (skip_island_outlining && skip_island_outlining.getValue()) {
87       // Island was marked to be skipped.
88       return WalkResult::advance();
89     }
90     for (Operation &op : island_op.GetBody().without_terminator()) {
91       if (isa<TF::TPUReplicateMetadataOp>(&op)) {
92         // Handle replicated TPU case.
93         islands_to_outline.push_back(island_op);
94         break;
95       }
96       auto device_type =
97           op.getAttrOfType<StringAttr>(TF::kCompileDeviceTypeAttr);
98       if (device_type && device_type.getValue() == TF::kTpuDevice &&
99           !op.hasAttrOfType<StringAttr>(TF::kReplicationInfoAttr)) {
100         // Handle single-core TPU case (no `TPUReplicateMetadataOp`).
101         islands_to_outline.push_back(island_op);
102         break;
103       }
104     }
105     return WalkResult::advance();
106   });
107   int prefix_id = 0;
108   for (IslandOp island_op : islands_to_outline) {
109     // Build the function signature.
110 
111     // First the captured values in the island are function arguments
112     llvm::SetVector<Value> operands;
113     getUsedValuesDefinedAbove(island_op.body(), operands);
114 
115     SmallVector<Type, 16> func_operand_types;
116     func_operand_types.reserve(operands.size());
117     for (Value operand : operands)
118       func_operand_types.push_back(operand.getType());
119 
120     // Function results are the yield operands
121     SmallVector<Type, 16> func_result_types;
122     for (Value operand : island_op.GetYield().getOperands())
123       func_result_types.push_back(operand.getType());
124     FunctionType func_type =
125         FunctionType::get(ctx, func_operand_types, func_result_types);
126 
127     // Create the outlined function
128     SmallString<32> name = kOutlinedFuncPrefix;
129     name += llvm::Twine(prefix_id++).str();
130     auto outlined_func = OpBuilder(ctx).create<func::FuncOp>(island_op.getLoc(),
131                                                              name, func_type);
132     outlined_symbol_table.insert(outlined_func);
133     outlined_func.setNested();
134 
135     // We will "steal" the body of the island and replace it with a call to the
136     // new function later.
137     {
138       YieldOp yield_op = island_op.GetYield();
139       outlined_func.getBody().takeBody(island_op.body());
140 
141       // Replace the yield with a return
142       OpBuilder replacer(yield_op);
143       island_op.body().push_back(new Block);
144       replacer.create<mlir::func::ReturnOp>(yield_op.getLoc(),
145                                             yield_op.getOperands());
146       yield_op.erase();
147     }
148 
149     // Remap the captured operands in the (former) island block with newly
150     // created entry block arguments in the function body.
151     {
152       Block &entry_block = outlined_func.getBody().front();
153       auto loc = outlined_func.getLoc();
154       for (Value operand : operands) {
155         BlockArgument newArg = entry_block.addArgument(operand.getType(), loc);
156         replaceAllUsesInRegionWith(operand, newArg, outlined_func.getBody());
157       }
158     }
159 
160     // The function is in place in the nested module, create a call and yield in
161     // the original island.
162     OpBuilder builder = OpBuilder::atBlockEnd(&island_op.GetBody());
163     auto call_op = builder.create<mlir::TF::PartitionedCallOp>(
164         island_op.getLoc(), func_result_types, operands.getArrayRef(),
165         SymbolRefAttr::get(
166             builder.getContext(), kNestedModule,
167             SymbolRefAttr::get(builder.getContext(), outlined_func.getName())),
168         /*config=*/builder.getStringAttr(""),
169         /*config_proto=*/builder.getStringAttr(""),
170         /*executor_type=*/builder.getStringAttr(""));
171     SmallVector<Value, 16> yield_operands(call_op.getResults());
172     builder.create<YieldOp>(island_op.getLoc(), yield_operands);
173   }
174 
175   // Outline all the transitively called functions by moving them in the
176   // outlined module.
177   for (func::FuncOp func : outlined_module.getOps<func::FuncOp>()) {
178     func.walk([&](Operation *op) {
179       for (NamedAttribute attr : op->getAttrs()) {
180         if (auto symbol_ref = attr.getValue().dyn_cast<FlatSymbolRefAttr>()) {
181           MoveFuncOp(symbol_ref, symbol_table, outlined_symbol_table);
182           continue;
183         }
184         if (auto array_attr = attr.getValue().dyn_cast<ArrayAttr>()) {
185           for (const Attribute &attribute : array_attr) {
186             auto symbol_ref = attribute.dyn_cast<FlatSymbolRefAttr>();
187             if (!symbol_ref) continue;
188             MoveFuncOp(symbol_ref, symbol_table, outlined_symbol_table);
189           }
190         }
191       }
192     });
193   }
194   // Remove `kSkipIslandOutlining` attributes.
195   for (func::FuncOp func_op : getOperation().getOps<func::FuncOp>()) {
196     if (func_op->hasAttr(mlir::TF::kSkipIslandOutlining)) {
197       func_op->removeAttr(mlir::TF::kSkipIslandOutlining);
198     }
199   }
200 }
201 
202 }  // namespace
203 
204 std::unique_ptr<OperationPass<ModuleOp>>
CreateTFExecutorTPUV1IslandOutliningPass()205 CreateTFExecutorTPUV1IslandOutliningPass() {
206   return std::make_unique<TPUBridgeExecutorIslandOutlining>();
207 }
208 
209 }  // namespace tf_executor
210 }  // namespace mlir
211