aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/tools/graph_transforms/transform_utils.cc
blob: af17fd75bc1ccac61538c17658d59ee2efd6254a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/tools/graph_transforms/transform_utils.h"

#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/lib/hash/hash.h"
#include "tensorflow/core/lib/strings/str_util.h"

namespace tensorflow {
namespace graph_transforms {

namespace {
inline bool IsMerge(const NodeDef& node_def) {
  return node_def.op() == "Merge" || node_def.op() == "RefMerge";
}

void RecordMatchedNodes(const NodeMatch& match,
                        std::set<string>* matched_nodes) {
  matched_nodes->insert(match.node.name());
  for (const NodeMatch& input_match : match.inputs) {
    RecordMatchedNodes(input_match, matched_nodes);
  }
}

inline uint64 Hash64String(const string& input) {
  return Hash64(input.data(), input.size());
}
}  // namespace

void MatchedNodesAsArray(const NodeMatch& match, std::vector<NodeDef>* result) {
  std::set<string> found_nodes;
  std::vector<NodeMatch> current_matches = {match};
  while (!current_matches.empty()) {
    std::vector<NodeMatch> next_matches;
    for (const NodeMatch& current_match : current_matches) {
      if (found_nodes.count(current_match.node.name())) {
        continue;
      }
      found_nodes.insert(current_match.node.name());
      result->push_back(current_match.node);
      for (const NodeMatch& input_match : current_match.inputs) {
        next_matches.push_back(input_match);
      }
    }
    current_matches = next_matches;
  }
}

void MapNamesToNodes(const GraphDef& graph_def,
                     std::map<string, const NodeDef*>* result) {
  for (const NodeDef& node : graph_def.node()) {
    (*result)[node.name()] = &node;
  }
}

void MapNodesToOutputs(const GraphDef& graph_def,
                       std::map<string, std::vector<const NodeDef*>>* result) {
  std::map<string, const NodeDef*> node_map;
  MapNamesToNodes(graph_def, &node_map);
  for (const NodeDef& node : graph_def.node()) {
    for (const string& input : node.input()) {
      string input_node_name = NodeNameFromInput(input);
      (*result)[input_node_name].push_back(&node);
    }
  }
}

void NodeNamePartsFromInput(const string& input_name, string* prefix,
                            string* node_name, string* suffix) {
  std::vector<string> input_parts = str_util::Split(input_name, ':');
  if (input_parts.size() < 2) {
    *suffix = "";
  } else {
    *suffix = ":" + input_parts[1];
  }
  StringPiece node_name_piece(input_parts[0]);
  if (str_util::ConsumePrefix(&node_name_piece, "^")) {
    *prefix = "^";
  } else {
    *prefix = "";
  }
  *node_name = std::string(node_name_piece);
}

string NodeNameFromInput(const string& input_name) {
  string prefix;
  string node_name;
  string suffix;
  NodeNamePartsFromInput(input_name, &prefix, &node_name, &suffix);
  return node_name;
}

string CanonicalInputName(const string& input_name) {
  string prefix;
  string node_name;
  string suffix;
  NodeNamePartsFromInput(input_name, &prefix, &node_name, &suffix);
  if (suffix.empty()) {
    suffix = ":0";
  }
  return prefix + node_name + suffix;
}

uint64 HashNodeDef(const NodeDef& node) {
  uint64 hash = Hash64String(node.op());
  hash = Hash64Combine(hash, Hash64String(node.name()));
  for (const string& input : node.input()) {
    hash = Hash64Combine(hash, Hash64String(CanonicalInputName(input)));
  }
  hash = Hash64Combine(hash, Hash64String(node.device()));
  std::vector<string> attr_names;
  attr_names.reserve(node.attr().size());
  for (const auto& attr : node.attr()) {
    attr_names.push_back(attr.first);
  }
  std::sort(attr_names.begin(), attr_names.end());
  string attr_serialized;
  for (const string& attr_name : attr_names) {
    auto attr = node.attr().at(attr_name);
    attr.SerializeToString(&attr_serialized);
    hash = Hash64Combine(hash, Hash64String(attr_serialized));
  }
  return hash;
}

void AddNodeInput(const string& input_name, NodeDef* node) {
  *(node->mutable_input()->Add()) = input_name;
}

void CopyNodeAttr(const NodeDef& source, const string& source_key,
                  const string& dest_key, NodeDef* dest) {
  CHECK_NE(0, source.attr().count(source_key))
      << "No key '" << source_key << "' found in " << source.DebugString();
  (*(dest->mutable_attr()))[dest_key] = source.attr().at(source_key);
}

Tensor GetNodeTensorAttr(const NodeDef& node, const string& key) {
  TensorProto tensor_proto = node.attr().at(key).tensor();
  Tensor tensor;
  CHECK(tensor.FromProto(tensor_proto));
  return tensor;
}

void FilterGraphDef(const GraphDef& input_graph_def,
                    std::function<bool(const NodeDef&)> selector,
                    GraphDef* output_graph_def) {
  output_graph_def->mutable_node()->Clear();
  for (const NodeDef& node : input_graph_def.node()) {
    if (selector(node)) {
      *output_graph_def->mutable_node()->Add() = node;
    }
  }
}

void RemoveAttributes(const GraphDef& input_graph_def,
                      const std::vector<string>& attributes,
                      GraphDef* output_graph_def) {
  output_graph_def->mutable_node()->Clear();
  for (const NodeDef& node : input_graph_def.node()) {
    NodeDef* new_node = output_graph_def->mutable_node()->Add();
    *new_node = node;
    for (const string& attribute : attributes) {
      new_node->mutable_attr()->erase(attribute);
    }
  }
}

Status SortByExecutionOrder(const GraphDef& input_graph_def,
                            GraphDef* output_graph_def) {
  const int num_nodes = input_graph_def.node_size();
  std::vector<int> ready;
  std::vector<int> pending_count;
  pending_count.reserve(num_nodes);
  std::vector<gtl::InlinedVector<int, 4>> outputs(num_nodes);

  std::map<string, int> name_index;
  for (int i = 0; i < input_graph_def.node_size(); ++i) {
    const NodeDef& node(input_graph_def.node(i));
    name_index[node.name()] = i;
  }

  // Parse the inputs for each node.
  for (int n = 0; n < num_nodes; ++n) {
    const NodeDef& node_def(input_graph_def.node(n));
    if (IsMerge(node_def)) {
      // for merge only wait for one non-control input.
      int32 num_control_edges = 0;
      for (int i = 0; i < node_def.input_size(); ++i) {
        if (str_util::StartsWith(node_def.input(i), "^")) {
          num_control_edges++;
        }
      }
      pending_count.push_back(num_control_edges + 1);
    } else {
      pending_count.push_back(node_def.input_size());
    }
    if (node_def.input_size() == 0) {
      ready.push_back(n);
      continue;
    }
    for (int i = 0; i < node_def.input_size(); ++i) {
      const string& input_name = node_def.input(i);
      const string& input_node_name = NodeNameFromInput(input_name);
      if (!name_index.count(input_node_name)) {
        return errors::InvalidArgument("Node '", node_def.name(),
                                       "': Unknown input node '",
                                       node_def.input(i), "'");
      }
      outputs[name_index[input_node_name]].push_back(n);
    }
  }

  int processed = 0;
  output_graph_def->Clear();
  // Process the NodeDefs in topological order.
  // Code above sets this up by filling in ready_ with nodes that have no
  // inputs, pending_counts_ with the number of inputs for each node and
  // outputs_ with the outputs of each node.
  while (!ready.empty()) {
    int o = ready.back();
    ready.pop_back();
    ++processed;
    const NodeDef& node_def(input_graph_def.node(o));
    *output_graph_def->mutable_node()->Add() = node_def;

    // Update pending_count for outputs.
    for (size_t i = 0; i < outputs[o].size(); ++i) {
      const int output = outputs[o][i];
      pending_count[output]--;
      if (pending_count[output] == 0) {
        ready.push_back(output);
      }
    }
  }

  if (processed < input_graph_def.node_size()) {
    return errors::InvalidArgument(input_graph_def.node_size() - processed,
                                   " nodes in a cycle");
  }
  return Status::OK();
}

string OpTypePattern::DebugString() const {
  string result = "{" + op + ", {";
  for (const OpTypePattern& input : inputs) {
    result += input.DebugString() + ",";
  }
  result += "}}";
  return result;
}

string NodeMatch::DebugString() const {
  string result = "{";
  result += node.DebugString();
  result += ", {";
  for (const NodeMatch& input : inputs) {
    result += input.DebugString() + ",";
  }
  result += "}}";
  return result;
}

GraphMatcher::GraphMatcher(const GraphDef& graph_def) {
  SortByExecutionOrder(graph_def, &graph_def_).IgnoreError();
  MapNamesToNodes(graph_def_, &node_map_);
}

Status GraphMatcher::GetOpTypeMatches(const OpTypePattern& pattern,
                                      std::vector<NodeMatch>* matches) {
  std::set<string> matched_nodes;
  for (const NodeDef& node : graph_def_.node()) {
    // Skip any nodes that are already part of a match.
    if (matched_nodes.count(node.name())) {
      continue;
    }
    NodeMatch match;
    if (DoesOpTypeMatch(node, pattern, matched_nodes, &match)) {
      RecordMatchedNodes(match, &matched_nodes);
      matches->push_back(match);
    }
  }
  return Status::OK();
}

bool GraphMatcher::DoesOpTypeMatch(
    const NodeDef& node, const OpTypePattern& pattern,
    const std::set<string>& previously_matched_nodes, NodeMatch* match) {
  VLOG(1) << "Looking at node " << node.DebugString();
  VLOG(1) << "pattern=" << pattern.DebugString();
  VLOG(1) << "match=" << match->DebugString();
  if (previously_matched_nodes.count(node.name())) {
    VLOG(1) << "node " << node.name() << " has been previously matched";
    return false;
  }
  bool pattern_matched = false;
  if (pattern.op == "*") {
    pattern_matched = true;
  } else {
    std::vector<string> pattern_ops = str_util::Split(pattern.op, '|');
    for (const string& pattern_op : pattern_ops) {
      if (node.op() == pattern_op) {
        pattern_matched = true;
      }
    }
  }
  if (!pattern_matched) {
    VLOG(1) << "node.op() != pattern.op()";
    return false;
  }
  match->node = node;
  // Ignore any control inputs for pattern-matching purposes
  std::vector<string> non_control_inputs;
  for (const string& input : node.input()) {
    if (!input.empty() && (input[0] != '^')) {
      non_control_inputs.push_back(input);
    }
  }
  if (pattern.inputs.empty()) {
    // If there are no inputs, assume that's the end of the pattern.
    return true;
  }
  if (non_control_inputs.size() != pattern.inputs.size()) {
    VLOG(1) << "non_control_inputs.size() != pattern.inputs.size()";
    return false;
  }
  for (int i = 0; i < pattern.inputs.size(); ++i) {
    const string& input_node_name = NodeNameFromInput(non_control_inputs[i]);
    const NodeDef& input_node = *(node_map_[input_node_name]);
    const OpTypePattern& input_pattern = pattern.inputs[i];
    match->inputs.push_back(NodeMatch());
    NodeMatch* input_match = &(match->inputs.back());
    if (!DoesOpTypeMatch(input_node, input_pattern, previously_matched_nodes,
                         input_match)) {
      return false;
    }
  }
  return true;
}

Status ReplaceMatchingOpTypes(
    const GraphDef& input_graph_def, const OpTypePattern& pattern,
    const std::function<Status(const NodeMatch&, const std::set<string>&,
                               const std::set<string>&, std::vector<NodeDef>*)>&
        node_generator,
    const ReplaceMatchingOpTypesOptions& options, GraphDef* output_graph_def) {
  // Start off by retrieving all the matching subgraphs.
  GraphMatcher matcher(input_graph_def);
  std::vector<NodeMatch> matches;
  TF_RETURN_IF_ERROR(matcher.GetOpTypeMatches(pattern, &matches));

  // Do some housekeeping so we can easily look up the resulting matches given
  // a node name.
  std::set<string> matched_nodes;
  std::map<string, const NodeMatch*> matches_by_head_name;
  for (const NodeMatch& match : matches) {
    matches_by_head_name[match.node.name()] = &match;
    RecordMatchedNodes(match, &matched_nodes);
  }
  std::map<string, std::vector<const NodeDef*>> outputs_map;
  MapNodesToOutputs(input_graph_def, &outputs_map);

  // Go through all the nodes in the input graph, see if they are part of a
  // match or if they can be left untouched.
  output_graph_def->Clear();
  for (const NodeDef& input_node : input_graph_def.node()) {
    if (matches_by_head_name.count(input_node.name())) {
      // This node is the beginning of a match, so call the replacement function
      // after setting up some information it will need.
      const NodeMatch* match = matches_by_head_name[input_node.name()];
      std::vector<NodeDef> matched_nodes_array;
      MatchedNodesAsArray(*match, &matched_nodes_array);
      // This tells us whether a node is part of the current match.
      std::set<string> matched_nodes_lookup;
      for (const NodeDef& matched_node : matched_nodes_array) {
        matched_nodes_lookup.insert(matched_node.name());
      }
      // These are helper arrays that the replacement function can use to tell
      // whether it can safely remove an internal node (because nothing outside
      // of the match uses it) or whether external nodes depend on it.
      std::set<string> input_nodes;
      std::set<string> output_nodes;
      for (const NodeDef& matched_node : matched_nodes_array) {
        // Look through all of this node's inputs, and if any of them come from
        // outside the match, then this should be noted as one of the external
        // inputs of the subgraph.
        for (const string& input_name : matched_node.input()) {
          string input_node_name = NodeNameFromInput(input_name);
          if (!matched_nodes_lookup.count(input_node_name)) {
            input_nodes.insert(matched_node.name());
          }
        }
        // Do a reverse input lookup, to see which other nodes use the current
        // one as an input. If any of those nodes are outside the match
        // subgraph, then the current node is marked as an output node that
        // shouldn't be removed.
        if (outputs_map.count(matched_node.name())) {
          for (const NodeDef* dependent_node :
               outputs_map[matched_node.name()]) {
            if (!matched_nodes_lookup.count(dependent_node->name())) {
              output_nodes.insert(matched_node.name());
            }
          }
        }
      }
      // Call the generator function and add all the returned nodes to the
      // graph.
      std::vector<NodeDef> new_nodes;
      TF_RETURN_IF_ERROR(
          node_generator(*match, input_nodes, output_nodes, &new_nodes));
      std::set<string> new_node_names;
      for (const NodeDef& new_node : new_nodes) {
        new_node_names.insert(new_node.name());
      }
      // Check to make sure the generator function preserved all of the nodes
      // that are used elsewhere in the graph, and add them back in if not.
      bool abort_replacement = false;
      if (!options.allow_inconsistencies) {
        for (const string& expected_output : output_nodes) {
          if (!new_node_names.count(expected_output)) {
            LOG(WARNING) << "Expected " << expected_output
                         << " to be preserved.";
            abort_replacement = true;
          }
        }
      }
      if (abort_replacement) {
        LOG(WARNING) << "Generator function didn't preserve needed nodes, "
                     << "copying old replacements back in instead.";
        std::vector<NodeDef> old_nodes;
        MatchedNodesAsArray(*match, &old_nodes);
        for (const NodeDef& old_node : old_nodes) {
          NodeDef* added_node = output_graph_def->mutable_node()->Add();
          *added_node = old_node;
        }
      } else {
        for (const NodeDef& new_node : new_nodes) {
          NodeDef* added_node = output_graph_def->mutable_node()->Add();
          *added_node = new_node;
        }
      }
    } else if (!matched_nodes.count(input_node.name())) {
      // This node isn't part of any match, so just copy it over.
      NodeDef* added_node = output_graph_def->mutable_node()->Add();
      *added_node = input_node;
    } else {
      // Do nothing, because this is an internal part of a matching subgraph,
      // and so will have been replaced by a new replacement subgraph.
    }
  }

  return Status::OK();
}

Status RenameNodeInputs(const GraphDef& input_graph_def,
                        const std::map<string, string>& inputs_to_rename,
                        const std::unordered_set<string>& nodes_to_ignore,
                        GraphDef* output_graph_def) {
  std::map<string, std::vector<std::pair<string, string>>>
      canonical_inputs_to_rename;
  for (const auto& input_to_rename : inputs_to_rename) {
    canonical_inputs_to_rename[NodeNameFromInput(input_to_rename.first)]
        .push_back({input_to_rename.first, input_to_rename.second});
  }

  output_graph_def->Clear();
  for (const NodeDef& node : input_graph_def.node()) {
    NodeDef* new_node = output_graph_def->mutable_node()->Add();
    *new_node = node;
    new_node->mutable_input()->Clear();
    for (const string& input_name : node.input()) {
      std::set<string> already_visited;
      string new_input_name = input_name;
      while (
          canonical_inputs_to_rename.count(NodeNameFromInput(new_input_name))) {
        string input_node_name = NodeNameFromInput(new_input_name);
        if (already_visited.count(input_node_name)) {
          return errors::InvalidArgument(
              "RenameNodeInputs argument contains a cycle for ",
              input_node_name);
        }
        already_visited.insert(input_node_name);
        if (nodes_to_ignore.count(node.name())) {
          break;
        }
        bool any_match_found = false;
        for (const std::pair<string, string>& input_to_rename :
             canonical_inputs_to_rename.at(input_node_name)) {
          const string& source_name = input_to_rename.first;
          const string& dest_name = input_to_rename.second;
          bool is_match;
          string match_name;
          if (str_util::EndsWith(source_name, ":*")) {
            is_match = true;
            string prefix;
            string unused_node_name;
            string suffix;
            NodeNamePartsFromInput(new_input_name, &prefix, &unused_node_name,
                                   &suffix);
            match_name = prefix + dest_name + suffix;
          } else {
            is_match = (CanonicalInputName(source_name) ==
                        CanonicalInputName(new_input_name));
            match_name = dest_name;
          }
          if (is_match) {
            new_input_name = match_name;
            any_match_found = true;
          }
        }
        if (!any_match_found) {
          break;
        }
      }
      *(new_node->mutable_input()->Add()) = new_input_name;
    }
  }
  return Status::OK();
}

void CopyOriginalMatch(const NodeMatch& match,
                       std::vector<NodeDef>* new_nodes) {
  std::vector<NodeDef> old_nodes;
  MatchedNodesAsArray(match, &old_nodes);
  for (const NodeDef& old_node : old_nodes) {
    new_nodes->push_back(old_node);
  }
}

TransformRegistry* GetTransformRegistry() {
  static TransformRegistry transform_registry;
  return &transform_registry;
}

void FindInvalidInputs(const GraphDef& graph_def,
                       std::vector<std::pair<string, string>>* invalid_inputs) {
  std::map<string, const NodeDef*> node_map;
  MapNamesToNodes(graph_def, &node_map);

  for (const NodeDef& node : graph_def.node()) {
    for (const string& input : node.input()) {
      string input_node = NodeNameFromInput(input);
      if (!node_map.count(input_node)) {
        invalid_inputs->push_back({node.name(), input_node});
      }
    }
  }
}

Status IsGraphValid(const GraphDef& graph_def) {
  std::vector<std::pair<string, string>> invalid_inputs;
  FindInvalidInputs(graph_def, &invalid_inputs);
  if (!invalid_inputs.empty()) {
    std::map<string, const NodeDef*> node_map;
    MapNamesToNodes(graph_def, &node_map);
    for (const std::pair<string, string>& invalid_input : invalid_inputs) {
      LOG(ERROR) << "Invalid input " << invalid_input.second << " for node "
                 << invalid_input.first << " - "
                 << node_map[invalid_input.first]->DebugString();
    }
    return errors::Internal(
        "Invalid graph with inputs referring to nonexistent nodes");
  }
  return Status::OK();
}

Status GetInOutTypes(const NodeDef& node_def, DataTypeVector* inputs,
                     DataTypeVector* outputs) {
  const OpDef* op_def;
  TF_RETURN_IF_ERROR(OpRegistry::Global()->LookUpOpDef(node_def.op(), &op_def));
  TF_RETURN_IF_ERROR(InOutTypesForNode(node_def, *op_def, inputs, outputs));
  return Status::OK();
}

Status TensorShapeFromString(const string& shape_string, TensorShape* result) {
  if (shape_string.empty()) {
    return errors::InvalidArgument("Specificed shape is empty.");
  }
  std::vector<int64> dims;
  if (!str_util::SplitAndParseAsInts(shape_string, ',', &dims)) {
    return errors::InvalidArgument("Could parse as shape: '", shape_string,
                                   "'");
  }
  *result = TensorShape(dims);
  return Status::OK();
}

int TransformFuncContext::CountParameters(const string& name) const {
  if (params.count(name)) {
    return params.at(name).size();
  } else {
    return 0;
  }
}

Status TransformFuncContext::GetOneStringParameter(const string& name,
                                                   const string& default_value,
                                                   string* result) const {
  const int params_count = CountParameters(name);
  if (params_count == 0) {
    *result = default_value;
    return Status::OK();
  } else if (params_count == 1) {
    *result = params.at(name).at(0);
    return Status::OK();
  } else {
    return errors::InvalidArgument("Expected a single '", name,
                                   "' parameter, but found ", params_count,
                                   " occurrences");
  }
}

Status TransformFuncContext::GetOneInt32Parameter(const string& name,
                                                  int32 default_value,
                                                  int32* result) const {
  const int params_count = CountParameters(name);
  if (params_count == 0) {
    *result = default_value;
    return Status::OK();
  }
  string string_value;
  TF_RETURN_IF_ERROR(GetOneStringParameter(name, "", &string_value));
  if (!strings::safe_strto32(StringPiece(string_value), result)) {
    return errors::InvalidArgument("Couldn't interpret the ", name,
                                   " argument as a number:", string_value);
  }
  return Status::OK();
}

Status TransformFuncContext::GetOneInt64Parameter(const string& name,
                                                  int64 default_value,
                                                  int64* result) const {
  const int params_count = CountParameters(name);
  if (params_count == 0) {
    *result = default_value;
    return Status::OK();
  }
  string string_value;
  TF_RETURN_IF_ERROR(GetOneStringParameter(name, "", &string_value));
  if (!strings::safe_strto64(StringPiece(string_value), result)) {
    return errors::InvalidArgument("Couldn't interpret the ", name,
                                   " argument as a number:", string_value);
  }
  return Status::OK();
}

Status TransformFuncContext::GetOneFloatParameter(const string& name,
                                                  float default_value,
                                                  float* result) const {
  const int params_count = CountParameters(name);
  if (params_count == 0) {
    *result = default_value;
    return Status::OK();
  }
  string string_value;
  TF_RETURN_IF_ERROR(GetOneStringParameter(name, "", &string_value));
  if (!strings::safe_strtof(string_value.c_str(), result)) {
    return errors::InvalidArgument(
        "Couldn't interpret the ", name,
        " argument as a float number:", string_value);
  }
  return Status::OK();
}

Status TransformFuncContext::GetOneBoolParameter(const string& name,
                                                 bool default_value,
                                                 bool* result) const {
  const int params_count = CountParameters(name);
  if (params_count == 0) {
    *result = default_value;
    return Status::OK();
  }
  string string_value;
  TF_RETURN_IF_ERROR(GetOneStringParameter(name, "", &string_value));
  if (string_value == "true" || string_value == "1") {
    *result = true;
  } else if (string_value == "false" || string_value == "0") {
    *result = false;
  } else {
    return errors::InvalidArgument("Couldn't interpret the ", name,
                                   " argument as a boolean:", string_value,
                                   " (expected true, false, 0 or 1)");
  }
  return Status::OK();
}

}  // namespace graph_transforms
}  // namespace tensorflow