1 /* Copyright 2019 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/jit/introduce_floating_point_jitter_pass.h"
17 #include "absl/algorithm/container.h"
18 #include "absl/container/flat_hash_map.h"
19 #include "tensorflow/cc/framework/scope_internal.h"
20 #include "tensorflow/cc/ops/const_op.h"
21 #include "tensorflow/cc/ops/math_ops.h"
22 #include "tensorflow/compiler/jit/flags.h"
23 #include "tensorflow/core/graph/tensor_id.h"
24
25 namespace tensorflow {
26 namespace {
GetNodesToModify(const Graph & g,absl::Span<const string> tensor_names)27 std::vector<std::pair<Node*, std::vector<int>>> GetNodesToModify(
28 const Graph& g, absl::Span<const string> tensor_names) {
29 absl::flat_hash_map<string, Node*> name_to_node;
30 for (Node* n : g.op_nodes()) {
31 name_to_node[n->name()] = n;
32 }
33
34 absl::flat_hash_map<Node*, std::vector<int>> nodes_to_modify_map;
35
36 for (const string& tensor_name : tensor_names) {
37 TensorId tensor_id = ParseTensorName(tensor_name);
38 auto it = name_to_node.find(tensor_id.node());
39 DCHECK(it != name_to_node.end());
40 nodes_to_modify_map[it->second].push_back(tensor_id.index());
41 }
42
43 std::vector<std::pair<Node*, std::vector<int>>> nodes_to_modify;
44 absl::c_copy(nodes_to_modify_map, std::back_inserter(nodes_to_modify));
45
46 absl::c_sort(nodes_to_modify,
47 [](const std::pair<Node*, std::vector<int>>& a,
48 const std::pair<Node*, std::vector<int>>& b) {
49 return a.first->id() < b.first->id();
50 });
51
52 for (auto& p : nodes_to_modify) {
53 absl::c_sort(p.second);
54 p.second.erase(std::unique(p.second.begin(), p.second.end()),
55 p.second.end());
56 }
57
58 return nodes_to_modify;
59 }
60
IntroduceJitterToTensor(Graph * g,Node * n,int oidx,float jitter_amount,absl::flat_hash_map<std::pair<DataType,Node * >,Output> * node_to_jitter_constant)61 Status IntroduceJitterToTensor(
62 Graph* g, Node* n, int oidx, float jitter_amount,
63 absl::flat_hash_map<std::pair<DataType, Node*>, Output>*
64 node_to_jitter_constant) {
65 std::vector<const Edge*> edges_to_update;
66 absl::c_copy_if(n->out_edges(), std::back_inserter(edges_to_update),
67 [&](const Edge* e) { return e->src_output() == oidx; });
68
69 if (edges_to_update.empty()) {
70 VLOG(1) << "No users for " << TensorId(n->name(), oidx).ToString();
71 return OkStatus();
72 }
73
74 VLOG(1) << "Updating " << edges_to_update.size() << " users for "
75 << TensorId(n->name(), oidx).ToString();
76
77 Status status;
78 Scope s = NewInternalScope(g, &status, /*refiner=*/nullptr)
79 .NewSubScope(absl::StrCat(n->name(), "/jitter"));
80
81 Output node_out(n, oidx);
82 Output jitter_constant;
83 DataType dtype = n->output_type(oidx);
84 auto it = node_to_jitter_constant->find({dtype, n});
85 if (it == node_to_jitter_constant->end()) {
86 Tensor constant_tensor;
87 if (dtype == DT_FLOAT) {
88 constant_tensor = Tensor(static_cast<float>(jitter_amount));
89 } else if (dtype == DT_HALF) {
90 constant_tensor = Tensor(Eigen::half(jitter_amount));
91 } else {
92 return errors::Unimplemented("Only float and half are supported");
93 }
94
95 jitter_constant =
96 ops::Const(s.WithOpName("jitter_amount"), constant_tensor);
97 (*node_to_jitter_constant)[{dtype, n}] = jitter_constant;
98 } else {
99 jitter_constant = it->second;
100 }
101
102 Output jittered_output =
103 ops::Add(s.NewSubScope(absl::StrCat(oidx)).WithOpName("jittered_output"),
104 jitter_constant, node_out);
105
106 TF_RETURN_IF_ERROR(status);
107
108 for (const Edge* e : edges_to_update) {
109 VLOG(3) << "Updating " << e->dst()->name();
110 TF_RETURN_IF_ERROR(
111 g->UpdateEdge(jittered_output.node(), 0, e->dst(), e->dst_input()));
112 }
113
114 // Add a control edge to make sure that the two inputs to jittered_output are
115 // from the same frame.
116 g->AddControlEdge(n, jitter_constant.node());
117
118 return OkStatus();
119 }
120 } // namespace
121
IntroduceFloatingPointJitter(Graph * graph,absl::Span<string const> tensor_names,float jitter_amount)122 Status IntroduceFloatingPointJitter(Graph* graph,
123 absl::Span<string const> tensor_names,
124 float jitter_amount) {
125 if (tensor_names.empty()) {
126 VLOG(3) << "Nothing to do";
127 return OkStatus();
128 }
129
130 std::vector<std::pair<Node*, std::vector<int>>> nodes_to_modify =
131 GetNodesToModify(*graph, tensor_names);
132
133 absl::flat_hash_map<std::pair<DataType, Node*>, Output>
134 node_to_jitter_constant;
135 for (const auto& p : nodes_to_modify) {
136 for (int oidx : p.second) {
137 TF_RETURN_IF_ERROR(IntroduceJitterToTensor(
138 graph, p.first, oidx, jitter_amount, &node_to_jitter_constant));
139 }
140 }
141
142 return OkStatus();
143 }
144
Run(const GraphOptimizationPassOptions & options)145 Status IntroduceFloatingPointJitterPass::Run(
146 const GraphOptimizationPassOptions& options) {
147 const IntroduceFloatingPointJitterPassFlags& flags =
148 GetIntroduceFloatingPointJitterPassFlags();
149
150 return IntroduceFloatingPointJitter(options.graph->get(), flags.tensor_names,
151 flags.jitter_amount);
152 }
153 } // namespace tensorflow
154