summaryrefslogtreecommitdiff
path: root/runtime/contrib/android_benchmark_app/cpp/ndk_main.cpp
blob: f2ca1312ce5277aef183f0c6acfec7324a16451d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#include "ndk_main.h"

#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"

#include "tflite/Assert.h"
#include "tflite/Session.h"
#include "tflite/InterpreterSession.h"
#include "tflite/NNAPISession.h"
#include "tflite/ext/kernels/register.h"

#include "misc/benchmark.h"

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>

#include <cassert>
#include <chrono>
#include <sstream>

#include <android/log.h>

using namespace tflite;
using namespace tflite::ops::builtin;

static StderrReporter error_reporter;

static std::unique_ptr<FlatBufferModel> model;

inline void setText(JNIEnv *env, jobject thisObj, const std::string &message)
{
  jclass thisClass = env->GetObjectClass(thisObj);
  jmethodID setTextMethod = env->GetMethodID(thisClass, "setText", "(Ljava/lang/String;)V");

  assert(setTextMethod != nullptr);

  env->CallVoidMethod(thisObj, setTextMethod, env->NewStringUTF(message.c_str()));
}

inline void setTitle(JNIEnv *env, jobject thisObj, const std::string &message)
{
  jclass thisClass = env->GetObjectClass(thisObj);
  jmethodID setTextMethod = env->GetMethodID(thisClass, "setTitle", "(Ljava/lang/String;)V");

  assert(setTextMethod != nullptr);

  env->CallVoidMethod(thisObj, setTextMethod, env->NewStringUTF(message.c_str()));

  // Clear message
  setText(env, thisObj, "");
}

inline void setText(JNIEnv *env, jobject thisObj, const std::stringstream &ss)
{
  setText(env, thisObj, ss.str());
}

inline std::unique_ptr<FlatBufferModel> loadModel(JNIEnv *env, jobject thisObj,
                                                  jobject model_buffer)
{
  const char *model_base = static_cast<char *>(env->GetDirectBufferAddress(model_buffer));
  jlong model_size = env->GetDirectBufferCapacity(model_buffer);

  return FlatBufferModel::BuildFromBuffer(model_base, static_cast<size_t>(model_size),
                                          &error_reporter);
}

struct Activity
{
  virtual ~Activity() = default;

  virtual void prepare(void) const = 0;
  virtual void run(void) const = 0;
  virtual void teardown(void) const = 0;
};

struct LiteActivity final : public Activity
{
public:
  LiteActivity(nnfw::tflite::Session &sess) : _sess(sess)
  {
    // DO NOTHING
  }

public:
  void prepare(void) const override { _sess.prepare(); }
  void run(void) const override { _sess.run(); }
  void teardown(void) const override { _sess.teardown(); }

private:
  nnfw::tflite::Session &_sess;
};

struct SimpleActivity final : public Activity
{
public:
  SimpleActivity(const std::function<void(void)> &fn) : _fn{fn}
  {
    // DO NOTHING
  }

public:
  void prepare(void) const override {}
  void run(void) const override { _fn(); }
  void teardown(void) const override {}

private:
  std::function<void(void)> _fn;
};

inline void runBenchmark(JNIEnv *env, jobject thisObj, Activity &act)
{
  auto runTrial = [&](void) {
    std::chrono::milliseconds elapsed(0);

    act.prepare();
    nnfw::misc::benchmark::measure(elapsed) << [&](void) { act.run(); };
    act.teardown();

    return elapsed;
  };

  // Warm-up
  for (uint32_t n = 0; n < 3; ++n)
  {
    auto elapsed = runTrial();

    std::stringstream ss;
    ss << "Warm-up #" << n << "  takes " << elapsed.count() << "ms" << std::endl;
    setText(env, thisObj, ss);
  }

  // Measure
  using namespace boost::accumulators;

  accumulator_set<double, stats<tag::mean, tag::min, tag::max>> acc;

  for (uint32_t n = 0; n < 100; ++n)
  {
    auto elapsed = runTrial();

    std::stringstream ss;
    ss << "Iteration #" << n << " takes " << elapsed.count() << "ms" << std::endl;
    setText(env, thisObj, ss);

    acc(elapsed.count());
  }

  std::stringstream ss;
  ss << "Average is " << mean(acc) << "ms" << std::endl;
  ss << "Min is " << min(acc) << "ms" << std::endl;
  ss << "Max is " << max(acc) << "ms" << std::endl;
  setText(env, thisObj, ss);
}

JNIEXPORT void JNICALL Java_com_ndk_tflbench_MainActivity_runInterpreterBenchmark(
    JNIEnv *env, jobject thisObj, jobject model_buffer)
{
  setTitle(env, thisObj, "Running Interpreter Benchmark");

  auto model = loadModel(env, thisObj, model_buffer);
  assert(model != nullptr);

  nnfw::tflite::BuiltinOpResolver resolver;
  InterpreterBuilder builder(*model, resolver);

  std::unique_ptr<Interpreter> interpreter;

  TFLITE_ENSURE(builder(&interpreter));

  interpreter->SetNumThreads(-1);

  nnfw::tflite::InterpreterSession sess(interpreter.get());
  LiteActivity act{sess};
  runBenchmark(env, thisObj, act);
}

static void runNNAPIBenchmark(JNIEnv *env, jobject thisObj, jobject model_buffer)
{
  auto model = loadModel(env, thisObj, model_buffer);
  assert(model != nullptr);

  nnfw::tflite::BuiltinOpResolver resolver;
  InterpreterBuilder builder(*model, resolver);

  std::unique_ptr<Interpreter> interpreter;

  TFLITE_ENSURE(builder(&interpreter));

  nnfw::tflite::NNAPISession sess(interpreter.get());
  LiteActivity act{sess};
  runBenchmark(env, thisObj, act);
}

JNIEXPORT void JNICALL Java_com_ndk_tflbench_MainActivity_runNNAPIBenchmark(JNIEnv *env,
                                                                            jobject thisObj,
                                                                            jobject model_buffer)
{
  setTitle(env, thisObj, "Running NNAPI Benchmark");

  try
  {
    runNNAPIBenchmark(env, thisObj, model_buffer);
  }
  catch (const std::exception &ex)
  {
    std::stringstream ss;
    ss << "Caught an exception " << ex.what();
    setText(env, thisObj, ss);
  }
}

JNIEXPORT jstring JNICALL Java_com_ndk_tflbench_MainActivity_getModelName(JNIEnv *env,
                                                                          jobject thisObj)
{
  return env->NewStringUTF(MODEL_NAME);
}

#define TF_ENSURE(e)                               \
  {                                                \
    if (!(e).ok())                                 \
    {                                              \
      throw std::runtime_error{"'" #e "' FAILED"}; \
    }                                              \
  }