1 /* Copyright 2017 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/xla/protobuf_util.h"
17
18 #include "absl/hash/hash.h"
19 #include "tensorflow/compiler/xla/status_macros.h"
20 #include "tensorflow/compiler/xla/types.h"
21 #include "tensorflow/compiler/xla/util.h"
22 #include "tensorflow/core/lib/io/path.h"
23 #include "tensorflow/core/platform/env.h"
24 #include "tensorflow/core/platform/mutex.h"
25 #include "tensorflow/core/platform/protobuf.h"
26
27 namespace xla {
28 namespace protobuf_util {
29
ProtobufEquals(const tensorflow::protobuf::Message & m1,const tensorflow::protobuf::Message & m2)30 bool ProtobufEquals(const tensorflow::protobuf::Message& m1,
31 const tensorflow::protobuf::Message& m2) {
32 // This is a bit fast and loose, but avoids introducing a dependency on
33 // the much more complex protobuf::util::MessageDifferencer class. For
34 // our purposes we just say that two protobufs are equal if their serialized
35 // representations are equal.
36 string serialized1, serialized2;
37 m1.AppendToString(&serialized1);
38 m2.AppendToString(&serialized2);
39 return (serialized1 == serialized2);
40 }
41
ProtobufHash(const tensorflow::protobuf::Message & m)42 size_t ProtobufHash(const tensorflow::protobuf::Message& m) {
43 // This is a bit fast and loose, but avoids introducing a dependency on
44 // the much more complex protobuf::util::MessageDifferencer class.
45 // We perform the hash on their serialized representation.
46 string serialized;
47 m.AppendToString(&serialized);
48 return absl::Hash<string>()(serialized);
49 }
50
DumpProtoToDirectory(const tensorflow::protobuf::Message & message,const string & directory,const string & file_name,string * full_path)51 Status DumpProtoToDirectory(const tensorflow::protobuf::Message& message,
52 const string& directory, const string& file_name,
53 string* full_path) {
54 tensorflow::Env* env = tensorflow::Env::Default();
55 TF_RETURN_IF_ERROR(env->RecursivelyCreateDir(directory));
56 string safe_file_name = SanitizeFileName(file_name) + ".pb";
57 string full_path_impl;
58 if (!full_path) {
59 full_path = &full_path_impl;
60 }
61 *full_path = tensorflow::io::JoinPath(directory, safe_file_name);
62 return tensorflow::WriteBinaryProto(env, *full_path, message);
63 }
64
65 } // namespace protobuf_util
66 } // namespace xla
67