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_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 | |
26 | namespace tensorflow { |
27 | namespace dtensor { |
28 | |
29 | // static |
30 | SparseExpanderRegistry* SparseExpanderRegistry::Global() { |
31 | static SparseExpanderRegistry* registry = new SparseExpanderRegistry(); |
32 | return registry; |
33 | } |
34 | |
35 | SparseExpanderBase* 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 | |
43 | InitOnStartupMarker 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 | |
51 | Status 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 |