1/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/dtensor/mlir/sparse_expander.h"
17
18#include <memory>
19#include <string>
20
21#include "absl/container/flat_hash_map.h"
22#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
23#include "tensorflow/dtensor/mlir/op_utils.h"
24#include "tensorflow/dtensor/mlir/sparse_expander_common.h"
25
26namespace tensorflow {
27namespace dtensor {
28
29// static
30SparseExpanderRegistry* SparseExpanderRegistry::Global() {
31 static SparseExpanderRegistry* registry = new SparseExpanderRegistry();
32 return registry;
33}
34
35SparseExpanderBase* SparseExpanderRegistry::GetSparseExpansionFnForOp(
36 mlir::Operation* op) {
37 auto key = OpName(op);
38 auto fn = op_to_sparse_expansion_fn_map_.find(key);
39 if (fn == op_to_sparse_expansion_fn_map_.end()) return nullptr;
40 return fn->second.get();
41}
42
43InitOnStartupMarker SparseExpanderRegistry::RegisterSparseExpansionFn(
44 std::string opName, std::unique_ptr<SparseExpanderBase> prop) {
45 CHECK(op_to_sparse_expansion_fn_map_ // Crash ok
46 .insert_or_assign(opName, std::move(prop))
47 .second);
48 return {};
49}
50
51Status RunSparseExpansion(mlir::Operation* op, mlir::Operation** output) {
52 // Only expand if there are any SparseTensor inputs.
53 if (HasAnySparseInput(op)) {
54 SparseExpanderBase* expander =
55 SparseExpanderRegistry::Global()->GetSparseExpansionFnForOp(op);
56 if (expander != nullptr) {
57 auto expanded_op = expander->ExpandOp(op);
58 if (expanded_op.ok()) *output = expanded_op.value();
59 return expanded_op.status();
60 } else {
61 VLOG(1) << "No sparse expansion found for " << OpName(op) << "\n";
62 *output = op;
63 }
64 } else { // If there is no SparseTensor inputs then just return the op.
65 *output = op;
66 }
67 return OkStatus();
68}
69
70} // namespace dtensor
71} // namespace tensorflow
72