1 /* Copyright 2018 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 #ifndef TENSORFLOW_LITE_TOOLS_BENCHMARK_BENCHMARK_TFLITE_MODEL_H_
17 #define TENSORFLOW_LITE_TOOLS_BENCHMARK_BENCHMARK_TFLITE_MODEL_H_
18 
19 #include <algorithm>
20 #include <map>
21 #include <memory>
22 #include <random>
23 #include <string>
24 #include <vector>
25 
26 #include "tensorflow/lite/model.h"
27 #include "tensorflow/lite/profiling/profiler.h"
28 #include "tensorflow/lite/tools/benchmark/benchmark_model.h"
29 
30 namespace tflite {
31 namespace benchmark {
32 
33 // Benchmarks a TFLite model by running tflite interpreter.
34 class BenchmarkTfLiteModel : public BenchmarkModel {
35  public:
36   struct InputLayerInfo {
InputLayerInfoInputLayerInfo37     InputLayerInfo() : has_value_range(false) {}
38 
39     std::string name;
40     std::vector<int> shape;
41 
42     // The input value is randomly generated when benchmarking the NN model.
43     // However, the NN model might require the value be limited to a certain
44     // range [low, high] for this particular input layer. For simplicity,
45     // support integer value first.
46     bool has_value_range;
47     int low;
48     int high;
49 
50     // The input value will be loaded from 'input_file_path' INSTEAD OF being
51     // randomly generated. Note the input file will be opened in binary mode.
52     std::string input_file_path;
53   };
54 
55   explicit BenchmarkTfLiteModel(BenchmarkParams params = DefaultParams());
56   ~BenchmarkTfLiteModel() override;
57 
58   std::vector<Flag> GetFlags() override;
59   void LogParams() override;
60   TfLiteStatus ValidateParams() override;
61   uint64_t ComputeInputBytes() override;
62   TfLiteStatus Init() override;
63   TfLiteStatus RunImpl() override;
64   static BenchmarkParams DefaultParams();
65 
66  protected:
67   TfLiteStatus PrepareInputData() override;
68   TfLiteStatus ResetInputsAndOutputs() override;
69 
70   int64_t MayGetModelFileSize() override;
71 
72   virtual TfLiteStatus LoadModel();
73 
74   // Allow subclasses to create a customized Op resolver during init.
75   virtual std::unique_ptr<tflite::OpResolver> GetOpResolver() const;
76 
77   // Allow subclass to initialize a customized tflite interpereter.
78   virtual TfLiteStatus InitInterpreter();
79 
80   // Create a BenchmarkListener that's specifically for TFLite profiling if
81   // necessary.
82   virtual std::unique_ptr<BenchmarkListener> MayCreateProfilingListener() const;
83 
84   void CleanUp();
85 
86   std::unique_ptr<tflite::FlatBufferModel> model_;
87   std::unique_ptr<tflite::Interpreter> interpreter_;
88   std::unique_ptr<tflite::ExternalCpuBackendContext> external_context_;
89 
90  private:
91   // Implement type erasure with unique_ptr with custom deleter.
92   using VoidUniquePtr = std::unique_ptr<void, void (*)(void*)>;
93 
94   struct InputTensorData {
InputTensorDataInputTensorData95     InputTensorData() : data(nullptr, nullptr) {}
96 
97     VoidUniquePtr data;
98     size_t bytes;
99   };
100 
101   template <typename T, typename Distribution>
CreateInputTensorData(int num_elements,Distribution distribution)102   inline InputTensorData CreateInputTensorData(int num_elements,
103                                                Distribution distribution) {
104     InputTensorData tmp;
105     tmp.bytes = sizeof(T) * num_elements;
106     T* raw = new T[num_elements];
107     std::generate_n(raw, num_elements, [&]() {
108       return static_cast<T>(distribution(random_engine_));
109     });
110     tmp.data = VoidUniquePtr(static_cast<void*>(raw),
111                              [](void* ptr) { delete[] static_cast<T*>(ptr); });
112     return tmp;
113   }
114 
115   InputTensorData CreateRandomTensorData(const TfLiteTensor& t,
116                                          const InputLayerInfo* layer_info);
117 
118   InputTensorData LoadInputTensorData(const TfLiteTensor& t,
119                                       const std::string& input_file_path);
120 
121   std::vector<InputLayerInfo> inputs_;
122   std::vector<InputTensorData> inputs_data_;
123   std::unique_ptr<BenchmarkListener> profiling_listener_ = nullptr;
124   std::unique_ptr<BenchmarkListener> ruy_profiling_listener_ = nullptr;
125   std::mt19937 random_engine_;
126   std::vector<Interpreter::TfLiteDelegatePtr> owned_delegates_;
127   // Always TFLITE_LOG the benchmark result.
128   BenchmarkLoggingListener log_output_;
129 };
130 
131 }  // namespace benchmark
132 }  // namespace tflite
133 
134 #endif  // TENSORFLOW_LITE_TOOLS_BENCHMARK_BENCHMARK_TFLITE_MODEL_H_
135