1 // Copyright 2020 Google LLC
2 //
3 // This source code is licensed under the BSD-style license found in the
4 // LICENSE file in the root directory of this source tree.
5 
6 #include <algorithm>
7 #include <array>
8 #include <cmath>
9 #include <functional>
10 #include <limits>
11 #include <random>
12 #include <vector>
13 
14 #include <xnnpack.h>
15 
16 #include <benchmark/benchmark.h>
17 #include "bench/utils.h"
18 #ifdef BENCHMARK_TENSORFLOW_LITE
19 #include "flatbuffers/include/flatbuffers/flatbuffers.h"
20 #include "tensorflow/lite/interpreter.h"
21 #include "tensorflow/lite/kernels/register.h"
22 #include "tensorflow/lite/model.h"
23 #include "tensorflow/lite/schema/schema_generated.h"
24 #include "tensorflow/lite/version.h"
25 #endif  // BENCHMARK_TENSORFLOW_LITE
26 
27 
xnnpack_bankers_rounding_f32(benchmark::State & state)28 static void xnnpack_bankers_rounding_f32(benchmark::State& state) {
29   const size_t batch_size = state.range(0);
30   const size_t channels = state.range(1);
31 
32   std::random_device random_device;
33   auto rng = std::mt19937(random_device());
34   auto f32rng = std::bind(std::uniform_real_distribution<float>(-10.0f, 10.0f), std::ref(rng));
35 
36   std::vector<float> input(batch_size * channels);
37   std::vector<float> output(batch_size * channels);
38   std::generate(input.begin(), input.end(), std::ref(f32rng));
39   std::fill(output.begin(), output.end(), std::nanf(""));
40 
41   xnn_status status = xnn_initialize(nullptr /* allocator */);
42   if (status != xnn_status_success) {
43     state.SkipWithError("failed to initialize XNNPACK");
44     return;
45   }
46 
47   xnn_operator_t bankers_rounding_op = nullptr;
48   status = xnn_create_bankers_rounding_nc_f32(
49     channels, channels /* input stride */, channels /* output stride */,
50     0 /* flags */, &bankers_rounding_op);
51   if (status != xnn_status_success || bankers_rounding_op == nullptr) {
52     state.SkipWithError("failed to create Bankers' Rounding operator");
53     return;
54   }
55 
56   status = xnn_setup_bankers_rounding_nc_f32(
57     bankers_rounding_op,
58     batch_size,
59     input.data(), output.data(),
60     nullptr /* thread pool */);
61   if (status != xnn_status_success) {
62     state.SkipWithError("failed to setup Bankers' Rounding operator");
63     return;
64   }
65 
66   for (auto _ : state) {
67     status = xnn_run_operator(bankers_rounding_op, nullptr /* thread pool */);
68     if (status != xnn_status_success) {
69       state.SkipWithError("failed to run Bankers' Rounding operator");
70       return;
71     }
72   }
73 
74   status = xnn_delete_operator(bankers_rounding_op);
75   if (status != xnn_status_success) {
76     state.SkipWithError("failed to delete Bankers' Rounding operator");
77     return;
78   }
79 
80   const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency();
81   if (cpu_frequency != 0) {
82     state.counters["cpufreq"] = cpu_frequency;
83   }
84 
85   const size_t elements_per_iteration = batch_size * channels;
86   state.counters["elements"] =
87     benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate);
88 
89   const size_t bytes_per_iteration = 2 * elements_per_iteration * sizeof(float);
90   state.counters["bytes"] =
91     benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate);
92 }
93 
94 #ifdef BENCHMARK_TENSORFLOW_LITE
tflite_bankers_rounding_f32(benchmark::State & state)95 static void tflite_bankers_rounding_f32(benchmark::State& state) {
96   const size_t batch_size = state.range(0);
97   const size_t channels = state.range(1);
98 
99   std::random_device random_device;
100   auto rng = std::mt19937(random_device());
101   auto f32rng = std::bind(std::uniform_real_distribution<float>(-10.0f, 10.0f), std::ref(rng));
102 
103   flatbuffers::FlatBufferBuilder builder;
104   const flatbuffers::Offset<tflite::OperatorCode> operator_code =
105       CreateOperatorCode(builder, tflite::BuiltinOperator_ROUND);
106 
107   const std::array<flatbuffers::Offset<tflite::Buffer>, 1> buffers{{
108     tflite::CreateBuffer(builder, builder.CreateVector({})),
109   }};
110 
111   const std::array<int32_t, 4> input_shape{{
112     static_cast<int32_t>(batch_size),
113     static_cast<int32_t>(1 /* height */),
114     static_cast<int32_t>(1 /* width */),
115     static_cast<int32_t>(channels)
116   }};
117   const std::array<int32_t, 4> output_shape{{
118     static_cast<int32_t>(batch_size),
119     static_cast<int32_t>(1 /* height */),
120     static_cast<int32_t>(1 /* width */),
121     static_cast<int32_t>(channels)
122   }};
123 
124   const std::array<flatbuffers::Offset<tflite::Tensor>, 2> tensors{{
125     tflite::CreateTensor(builder,
126                          builder.CreateVector<int32_t>(input_shape.data(), input_shape.size()),
127                          tflite::TensorType_FLOAT32),
128     tflite::CreateTensor(builder,
129                          builder.CreateVector<int32_t>(output_shape.data(), output_shape.size()),
130                          tflite::TensorType_FLOAT32),
131   }};
132 
133   const std::array<int32_t, 1> op_inputs{{ 0 }};
134   const std::array<int32_t, 1> op_outputs{{ 1 }};
135   flatbuffers::Offset<tflite::Operator> op = tflite::CreateOperator(
136       builder,
137       0 /* opcode_index */,
138       builder.CreateVector<int32_t>(op_inputs.data(), op_inputs.size()),
139       builder.CreateVector<int32_t>(op_outputs.data(), op_outputs.size()));
140 
141   const std::array<int32_t, 1> graph_inputs{{ 0 }};
142   const std::array<int32_t, 1> graph_outputs{{ 1 }};
143   const flatbuffers::Offset<tflite::SubGraph> subgraph = tflite::CreateSubGraph(
144       builder,
145       builder.CreateVector(tensors.data(), tensors.size()),
146       builder.CreateVector<int32_t>(graph_inputs.data(), graph_inputs.size()),
147       builder.CreateVector<int32_t>(graph_outputs.data(), graph_outputs.size()),
148       builder.CreateVector(&op, 1));
149 
150   const flatbuffers::Offset<tflite::Model> model_buffer = tflite::CreateModel(builder,
151       TFLITE_SCHEMA_VERSION,
152       builder.CreateVector(&operator_code, 1),
153       builder.CreateVector(&subgraph, 1),
154       builder.CreateString("Round model"),
155       builder.CreateVector(buffers.data(), buffers.size()));
156 
157   builder.Finish(model_buffer);
158 
159   const tflite::Model* model = tflite::GetModel(builder.GetBufferPointer());
160   tflite::ops::builtin::BuiltinOpResolver resolver;
161   tflite::InterpreterBuilder interpreterBuilder(model, resolver);
162   std::unique_ptr<tflite::Interpreter> interpreter;
163   if (interpreterBuilder(&interpreter) != kTfLiteOk) {
164     state.SkipWithError("failed to create TFLite interpreter");
165     return;
166   }
167   if (interpreter == nullptr) {
168     state.SkipWithError("TFLite interpreter is null");
169     return;
170   }
171   interpreter->SetNumThreads(1);
172 
173   if (interpreter->AllocateTensors() != kTfLiteOk) {
174     state.SkipWithError("failed to allocate tensors");
175     return;
176   }
177 
178   std::generate(
179     interpreter->typed_tensor<float>(0),
180     interpreter->typed_tensor<float>(0) + batch_size * channels,
181     std::ref(f32rng));
182 
183   for (auto _ : state) {
184     if (interpreter->Invoke() != kTfLiteOk) {
185       state.SkipWithError("failed to invoke TFLite interpreter");
186       return;
187     }
188   }
189 
190   const uint64_t cpu_frequency = benchmark::utils::GetCurrentCpuFrequency();
191   if (cpu_frequency != 0) {
192     state.counters["cpufreq"] = cpu_frequency;
193   }
194 
195   const size_t elements_per_iteration = batch_size * channels;
196   state.counters["elements"] =
197     benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate);
198 
199   const size_t bytes_per_iteration = 2 * elements_per_iteration * sizeof(float);
200   state.counters["bytes"] =
201     benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate);
202 
203   interpreter.reset();
204 }
205 #endif  // BENCHMARK_TENSORFLOW_LITE
206 
CharacteristicArguments(benchmark::internal::Benchmark * b)207 static void CharacteristicArguments(benchmark::internal::Benchmark* b)
208 {
209   b->ArgNames({"N", "C"});
210 
211   int32_t c = 16;
212   for (int32_t n = 224; n >= 7; n /= 2) {
213     b->Args({n * n, c});
214     c *= 2;
215   }
216 }
217 
218 BENCHMARK(xnnpack_bankers_rounding_f32)->Apply(CharacteristicArguments)->UseRealTime();
219 
220 #ifdef BENCHMARK_TENSORFLOW_LITE
221   BENCHMARK(tflite_bankers_rounding_f32)->Apply(CharacteristicArguments)->UseRealTime();
222 #endif  // BENCHMARK_TENSORFLOW_LITE
223 
224 #ifndef XNNPACK_BENCHMARK_NO_MAIN
225 BENCHMARK_MAIN();
226 #endif
227