xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 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/tf2tensorrt/utils/trt_testutils.h"
17 
18 #if GOOGLE_CUDA && GOOGLE_TENSORRT
19 
20 #include <map>
21 #include <string>
22 #include <vector>
23 
24 #include <gmock/gmock.h>
25 
26 namespace tensorflow {
27 
28 namespace tensorrt {
29 namespace convert {
30 
ArrayFloatNear(const std::vector<float> & values,float max_abs_error,bool nan_sensitive)31 ::testing::Matcher<std::vector<float>> ArrayFloatNear(
32     const std::vector<float>& values, float max_abs_error, bool nan_sensitive) {
33   std::vector<::testing::Matcher<float>> matchers;
34   matchers.reserve(values.size());
35   for (const float& v : values) {
36     if (nan_sensitive) {
37       matchers.emplace_back(::testing::NanSensitiveFloatNear(v, max_abs_error));
38     } else if (max_abs_error == 0) {
39       matchers.emplace_back(::testing::FloatEq(v));
40     } else {
41       EXPECT_GE(max_abs_error, 0);
42       matchers.emplace_back(::testing::FloatNear(v, max_abs_error));
43     }
44   }
45   return ::testing::ElementsAreArray(matchers);
46 }
47 
CreateDims(const std::vector<int> & d)48 nvinfer1::Dims CreateDims(const std::vector<int>& d) {
49   nvinfer1::Dims dims;
50   dims.nbDims = d.size();
51   for (int i = 0; i < d.size(); ++i) {
52     dims.d[i] = d[i];
53   }
54   return dims;
55 }
56 
MakeNodeDef(const std::string & name,const std::string & op,const std::vector<std::string> & inputs,const std::map<std::string,AttrValue> attrs)57 NodeDef MakeNodeDef(const std::string& name, const std::string& op,
58                     const std::vector<std::string>& inputs,
59                     const std::map<std::string, AttrValue> attrs) {
60   NodeDef node_def;
61   node_def.set_name(name);
62   node_def.set_op(op);
63   for (const auto& input : inputs) {
64     node_def.add_input(input);
65   }
66   for (const auto& attr : attrs) {
67     (*node_def.mutable_attr())[attr.first] = attr.second;
68   }
69   return node_def;
70 }
71 
72 }  // namespace convert
73 }  // namespace tensorrt
74 }  // namespace tensorflow
75 
76 #endif  // GOOGLE_CUDA && GOOGLE_TENSORRT
77