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#include <Python.h>
16
17#include <memory>
18#include <string>
19
20#include "pybind11/detail/common.h"
21#include "pybind11/pybind11.h"
22#include "pybind11/pytypes.h"
23#include "tensorflow/core/framework/function.pb.h"
24#include "tensorflow/core/framework/graph.pb.h"
25#include "tensorflow/core/platform/errors.h"
26#include "tensorflow/core/platform/protobuf.h"
27#include "tensorflow/python/lib/core/pybind11_status.h"
28
29struct ProtoComparisonOptions; // Forward declaration
30
31namespace tensorflow {
32
33namespace {
34
35namespace py = pybind11;
36namespace tf = tensorflow;
37
38struct ProtoComparisonOptions {
39 bool treat_nan_as_equal;
40};
41
42bool EqualsGraphDef(string graphdef_string1, string graphdef_string2,
43 const ProtoComparisonOptions& options) {
44 GraphDef graph_def_1;
45 if (!graph_def_1.ParseFromString(graphdef_string1)) {
46 MaybeRaiseFromStatus(errors::InvalidArgument(
47 "Couldn't interpret first argument as a GraphDef"));
48 }
49 GraphDef graph_def_2;
50 if (!graph_def_2.ParseFromString(graphdef_string2)) {
51 MaybeRaiseFromStatus(errors::InvalidArgument(
52 "Couldn't interpret second argument as a GraphDef"));
53 }
54 tf::protobuf::util::MessageDifferencer differencer;
55 // Order doesnt matter in node defs, or functions in the function library and
56 // their nested nodes.
57 differencer.TreatAsSet(GraphDef::descriptor()->FindFieldByName("node"));
58 differencer.TreatAsSet(
59 FunctionDefLibrary::descriptor()->FindFieldByName("function"));
60 differencer.TreatAsSet(
61 FunctionDefLibrary::descriptor()->FindFieldByName("gradient"));
62 differencer.TreatAsSet(
63 FunctionDef::descriptor()->FindFieldByName("node_def"));
64 tf::protobuf::util::DefaultFieldComparator comparator;
65 comparator.set_treat_nan_as_equal(options.treat_nan_as_equal);
66 differencer.set_field_comparator(&comparator);
67 return differencer.Compare(graph_def_1, graph_def_2);
68}
69
70PYBIND11_MODULE(_proto_comparators, m) {
71 py::class_<tensorflow::ProtoComparisonOptions>(m, "ProtoComparisonOptions")
72 .def(py::init<const bool&>());
73 m.def("EqualsGraphDef", &EqualsGraphDef,
74 "GraphDef equality test taking comparison options.");
75}
76
77} // anonymous namespace
78
79} // namespace tensorflow
80