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 #include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h"
17
18 #include "tensorflow/compiler/jit/xla_compilation_cache.h"
19 #include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h"
20 #include "tensorflow/compiler/mlir/utils/array_container_utils.h"
21
22 namespace tensorflow {
23
24 namespace {
25
ContextToXlaArgs(XlaOpKernelContext * ctx,std::vector<XlaCompiler::Argument> & xla_args)26 Status ContextToXlaArgs(XlaOpKernelContext* ctx,
27 std::vector<XlaCompiler::Argument>& xla_args) {
28 int num_inputs = ctx->num_inputs();
29 xla_args.reserve(num_inputs);
30 for (int i = 0; i < num_inputs; ++i) {
31 // TODO(b/180448676): If the input `XlaExpression` kind is `kConstant`, then
32 // create a constant `XlaArgument`.
33 // TODO(b/180448774): Handle kResource and kTensorList.
34 XlaExpression::Kind ctx_kind_i = ctx->InputExpression(i).kind();
35 if (ctx_kind_i != XlaExpression::Kind::kXlaOp &&
36 ctx_kind_i != XlaExpression::Kind::kConstant)
37 return tensorflow::errors::InvalidArgument(
38 absl::StrCat("Input ", i, " to an MlirXlaOpKernel is invalid: ",
39 ctx->InputExpression(i).HumanString()));
40 XlaCompiler::Argument arg;
41 arg.kind = XlaCompiler::Argument::kParameter;
42 arg.type = ctx->input_type(i);
43 arg.shape = ctx->InputXlaShape(i).ValueOrDie();
44 arg.name = absl::StrCat("_arg", i);
45 xla_args.push_back(arg);
46 }
47 return Status::OK();
48 }
49
50 } // namespace
51
ConstructXlaOp(XlaOpKernelContext * ctx)52 Status MlirXlaOpKernel::ConstructXlaOp(XlaOpKernelContext* ctx) {
53 // Create input XlaArguments.
54 std::vector<XlaCompiler::Argument> xla_args;
55 TF_RETURN_IF_ERROR(ContextToXlaArgs(ctx, xla_args));
56
57 // Create input XlaOps.
58 llvm::SmallVector<xla::XlaOp, 4> xla_params(ctx->num_inputs());
59 for (int i = 0, end = ctx->num_inputs(); i < end; ++i) {
60 xla_params[i] = ctx->Input(i);
61 }
62
63 // Create outputs.
64 std::vector<DataType> result_dtypes(ctx->num_outputs());
65 for (int i = 0, end = result_dtypes.size(); i < end; ++i) {
66 result_dtypes[i] = ctx->expected_output_dtype(i);
67 }
68
69 // When there are no data-flow outputs from the node, the node is used as a
70 // control output by the graph to TensorflowDialect importer.
71 std::vector<std::string> control_rets;
72 if (result_dtypes.empty()) {
73 control_rets.push_back(def().name());
74 }
75
76 // Get the context's device.
77 auto device = dynamic_cast<Device*>(ctx->op_kernel_context()->device());
78 if (!device) {
79 return tensorflow::errors::InvalidArgument(
80 "Expected the XlaOpKernelContext argument's device to have type "
81 "Device.");
82 }
83
84 // Create a graph that wraps the kernel.
85 TF_ASSIGN_OR_RETURN(auto graph, CreateGraph(def(), xla_args, result_dtypes));
86
87 // Compile the graph to HLO.
88 GraphDebugInfo debug_info;
89 std::vector<xla::XlaOp> returns(1);
90 TF_RETURN_IF_ERROR(BuildHloFromGraph(
91 *graph, *ctx->builder(), xla_params, returns,
92 mlir::SpanToArrayRef<XlaCompiler::Argument>(xla_args), control_rets,
93 device->device_type(),
94 *ctx->function_library()->GetFunctionLibraryDefinition(), debug_info,
95 {}));
96
97 // Set context outputs.
98 for (int i = 0, end = returns.size(); i < end; ++i) {
99 ctx->SetOutput(i, returns[i]);
100 }
101
102 return Status::OK();
103 }
104
Compile(XlaOpKernelContext * ctx)105 void MlirXlaOpKernel::Compile(XlaOpKernelContext* ctx) {
106 auto status = ConstructXlaOp(ctx);
107 if (!status.ok()) {
108 errors::AppendToMessage(&status, "Failure to legalize ", def().name(),
109 " using MlirXlaOpKernel in the tf2xla bridge.");
110 }
111 OP_REQUIRES_OK(ctx, status);
112 }
113
114 } // namespace tensorflow
115