1 /* Copyright 2022 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/dtensor/mlir/sparse_expansions/dynamic_enqueue_sparse_expander.h"
17 
18 #include "mlir/IR/BuiltinAttributes.h"  // from @llvm-project
19 #include "mlir/IR/Operation.h"  // from @llvm-project
20 #include "mlir/IR/OperationSupport.h"  // from @llvm-project
21 #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
22 #include "tensorflow/compiler/mlir/tensorflow/transforms/collection_ops_util.h"
23 #include "tensorflow/core/platform/errors.h"
24 #include "tensorflow/core/platform/statusor.h"
25 #include "tensorflow/dtensor/mlir/sparse_expander_common.h"
26 #include "tensorflow/dtensor/mlir/value_utils.h"
27 
28 namespace tensorflow {
29 namespace dtensor {
30 
31 namespace {
32 
33 // Indices tensor should be transformed from a shape [?, 2] tensor to a
34 // [?, 3] tensor padded with 0's because
35 // EnqueueTPUEmbeddingArbitraryTensorBatchOp expects a [?, 3] indices tensor.
ExpandIndices(mlir::OpBuilder & builder,mlir::Value indices)36 StatusOr<mlir::Value> ExpandIndices(mlir::OpBuilder& builder,
37                                     mlir::Value indices) {
38   int64_t num_dim =
39       indices.getType().dyn_cast<mlir::RankedTensorType>().getDimSize(1);
40   if (num_dim != 2)
41     return errors::Unimplemented(
42         "Sparse tensors with dense rank not equal to 2 is not yet supported in "
43         "DTensor.");
44   mlir::Location loc = indices.getLoc();
45   auto indices_padded_type = mlir::RankedTensorType::get(
46       {-1, 3},
47       indices.getType().dyn_cast<mlir::RankedTensorType>().getElementType());
48   // Little trick to make a rank-2 tensor of [[0,0], [0,1]] using rank 1
49   // constants.
50   mlir::Value indices_padding = builder.create<mlir::TF::ReshapeOp>(
51       loc,
52       mlir::TF::collection_ops_util::GetR1Const({0, 0, 0, 1}, builder, loc),
53       mlir::TF::collection_ops_util::GetR1Const({2, 2}, builder, loc));
54   mlir::Value indices_padded =
55       builder.create<mlir::TF::PadOp>(loc, indices_padded_type,
56                                       /*input=*/indices,
57                                       /*paddings=*/indices_padding);
58   return indices_padded;
59 }
60 
61 }  // namespace
62 
ExpandOp(mlir::Operation * op)63 StatusOr<mlir::Operation*> DynamicEnqueueSparseExpander::ExpandOp(
64     mlir::Operation* op) {
65   mlir::TF::DynamicEnqueueTPUEmbeddingArbitraryTensorBatchOp dense_enqueue_op =
66       mlir::cast<mlir::TF::DynamicEnqueueTPUEmbeddingArbitraryTensorBatchOp>(
67           op);
68 
69   mlir::OpBuilder builder(dense_enqueue_op);
70   mlir::Location location = dense_enqueue_op->getLoc();
71 
72   mlir::OperandRange feature = dense_enqueue_op.embedding_indices();
73   llvm::SmallVector<mlir::Value, 4> indices;
74   llvm::SmallVector<mlir::Value, 4> values;
75 
76   for (mlir::Value sparse_feature_value : feature) {
77     if (!IsSparseValue(sparse_feature_value)) {
78       return errors::Internal(
79           "Expected feature input to DynamicEnqueueOp to be a sparse input, "
80           "but was not. This should not happen.");
81     }
82     // Indices tensor may need to be expanded to a different shape
83     // for Enqueue op to work properly.
84     TF_ASSIGN_OR_RETURN(
85         mlir::Value expanded_indices,
86         ExpandIndices(
87             builder,
88             GetIndicesFromSparseTensor(sparse_feature_value).ValueOrDie()));
89     indices.push_back(expanded_indices);
90     values.push_back(
91         GetValuesFromSparseTensor(sparse_feature_value).ValueOrDie());
92   }
93   // Insert a new op with new sparse operands, and delete the old one.
94   // This op does not have a return value so we do not need to replace any
95   // consumers.
96   mlir::Operation* sparse_enqueue_op =
97       builder
98           .create<mlir::TF::DynamicEnqueueTPUEmbeddingArbitraryTensorBatchOp>(
99               location,
100               /*sample_indices_or_row_splits_list=*/indices,
101               /*embedding_indices=*/values,
102               /*aggregation_weights=*/dense_enqueue_op.aggregation_weights(),
103               /*mode_override=*/
104               dense_enqueue_op.mode_override(),
105               /*device_ordinal=*/dense_enqueue_op.device_ordinal(),
106               /*combiners=*/dense_enqueue_op.combiners());
107   dense_enqueue_op.erase();
108   return sparse_enqueue_op;
109 }
110 
111 }  // namespace dtensor
112 }  // namespace tensorflow
113