1/* Copyright 2020 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 <string>
17
18#include "tensorflow/core/framework/graph.pb.h"
19#include "tensorflow/core/framework/node_def.pb.h"
20#include "tensorflow/tools/graph_transforms/transform_utils.h"
21
22namespace tensorflow {
23namespace graph_transforms {
24
25Status RenameNode(const GraphDef& input_graph_def,
26 const TransformFuncContext& context,
27 GraphDef* output_graph_def) {
28 if (!context.params.count("old_node_name") ||
29 (context.params.at("old_node_name").size() != 1) ||
30 !context.params.count("new_node_name") ||
31 (context.params.at("new_node_name").size() != 1)) {
32 return errors::InvalidArgument(
33 "rename_node expects exactly one 'old_node_name' and one "
34 "'new_node_name' argument, e.g. "
35 "rename_node(old_attribute_name=super/deep/output, "
36 "new_attribute_name=output)");
37 }
38
39 const std::string old_node_name = context.params.at("old_node_name")[0];
40 const std::string new_node_name = context.params.at("new_node_name")[0];
41
42 output_graph_def->Clear();
43 for (const NodeDef& input_node : input_graph_def.node()) {
44 NodeDef* node = output_graph_def->mutable_node()->Add();
45 *node = input_node;
46 if (node->name() == new_node_name) {
47 return Status(error::Code::INVALID_ARGUMENT,
48 "A node is alreading using " + new_node_name + "as name.");
49 }
50 if (node->name() == old_node_name) {
51 node->set_name(new_node_name);
52 }
53 for (std::string& input_name : *node->mutable_input()) {
54 std::string prefix;
55 std::string input_node_name;
56 std::string suffix;
57 NodeNamePartsFromInput(input_name, &prefix, &input_node_name, &suffix);
58 if (input_node_name == old_node_name) {
59 std::string new_input_name = prefix + new_node_name + suffix;
60 input_name = new_input_name;
61 }
62 }
63 }
64
65 return OkStatus();
66}
67
68REGISTER_GRAPH_TRANSFORM("rename_node", RenameNode);
69} // namespace graph_transforms
70} // namespace tensorflow
71