summaryrefslogtreecommitdiff
path: root/tests/tools/nnpackage_run/src/nnpackage_run.cc
blob: 97edebf4ce1f986ee1738bc86c04e639e3645d52 (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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
 * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "args.h"
#include "tflite/Diff.h"
#include "tensor_dumper.h"
#include "hdf5.h"
#include "nnfw.h"

#include <assert.h>
#include <iostream>

#include <chrono>

#define NNPR_ENSURE_STATUS(a)        \
  do                                 \
  {                                  \
    if ((a) != NNFW_STATUS_NO_ERROR) \
    {                                \
      exit(-1);                      \
    }                                \
  } while (0)

uint64_t NowMicros()
{
  auto time_point = std::chrono::high_resolution_clock::now();
  auto since_epoch = time_point.time_since_epoch();
  // default precision of high resolution clock is 10e-9 (nanoseconds)
  return std::chrono::duration_cast<std::chrono::microseconds>(since_epoch).count();
}

uint64_t num_elems(const nnfw_tensorinfo *ti)
{
  uint64_t n = 1;
  for (uint32_t i = 0; i < ti->rank; ++i)
  {
    assert(ti->dims[i] >= 0);
    n *= ti->dims[i];
  }
  return n;
};

std::vector<float> randomData(RandomGenerator &randgen, uint64_t size)
{
  std::vector<float> vec(size);
  for (uint64_t i = 0; i < size; i++)
    vec[i] = randgen.generate<float>();
  return vec;
}

static const char *h5_value_grpname = "value";

int main(const int argc, char **argv)
{
  NNPackageRun::Args args(argc, argv);
  auto nnpackage_path = args.getPackageFilename();

  nnfw_session *session = nullptr;
  NNPR_ENSURE_STATUS(nnfw_create_session(&session));
  NNPR_ENSURE_STATUS(nnfw_load_model_from_file(session, nnpackage_path.c_str()));

  uint32_t num_inputs;
  NNPR_ENSURE_STATUS(nnfw_input_size(session, &num_inputs));

  // verify input and output

  if (num_inputs == 0)
  {
    std::cerr << "[ ERROR ] "
              << "No inputs in model => execution is not possible" << std::endl;
    exit(1);
  }

  auto verifyInputTypes = [session]() {
    uint32_t sz;
    NNPR_ENSURE_STATUS(nnfw_input_size(session, &sz));
    for (uint32_t i = 0; i < sz; ++i)
    {
      nnfw_tensorinfo ti;
      NNPR_ENSURE_STATUS(nnfw_input_tensorinfo(session, i, &ti));
      if (ti.dtype != NNFW_TYPE_TENSOR_FLOAT32)
      {
        std::cerr << "Only float 32bit is supported." << std::endl;
        exit(-1);
      }
    }
  };

  auto verifyOutputTypes = [session]() {
    uint32_t sz;
    NNPR_ENSURE_STATUS(nnfw_output_size(session, &sz));

    for (uint32_t i = 0; i < sz; ++i)
    {
      nnfw_tensorinfo ti;
      NNPR_ENSURE_STATUS(nnfw_output_tensorinfo(session, i, &ti));
      if (ti.dtype != NNFW_TYPE_TENSOR_FLOAT32)
      {
        std::cerr << "Only float 32bit is supported." << std::endl;
        exit(-1);
      }
    }
  };

  verifyInputTypes();
  verifyOutputTypes();

  // prepare execution

  uint64_t prepare_ms = NowMicros();
  NNPR_ENSURE_STATUS(nnfw_prepare(session));
  prepare_ms = NowMicros() - prepare_ms;

  // prepare input

  std::vector<std::vector<float>> inputs(num_inputs);

  auto loadInputs = [session, num_inputs, &inputs](std::string filename) {
    hid_t file_id = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);
    if (file_id < 0)
    {
      std::cerr << "error during opening file " << filename << "." << std::endl;
      exit(-1);
    }
    hid_t valgrp_id = H5Gopen(file_id, h5_value_grpname, H5P_DEFAULT);
    if (valgrp_id < 0)
    {
      std::cerr << "error during opening group " << h5_value_grpname << "." << std::endl;
      H5Fclose(file_id);
      exit(-1);
    }
    for (uint32_t i = 0; i < num_inputs; ++i)
    {
      nnfw_tensorinfo ti;
      NNPR_ENSURE_STATUS(nnfw_input_tensorinfo(session, i, &ti));

      hid_t dset_id = H5Dopen(valgrp_id, std::to_string(i).c_str(), H5P_DEFAULT);
      if (dset_id < 0)
      {
        std::cerr << "error during opening dataset " << std::to_string(i) << "." << std::endl;
        H5Gclose(valgrp_id);
        H5Fclose(file_id);
        exit(-1);
      }

      // check type
      hid_t type = H5Dget_type(dset_id);
      if (!H5Tequal(type, H5T_IEEE_F32BE))
      {
        std::cerr << "h5 input has non-float32 type. nnpkg_run supports float32 only." << std::endl;
        H5Dclose(dset_id);
        H5Gclose(valgrp_id);
        H5Fclose(file_id);
        exit(-1);
      }
      // allocate memory for data
      auto sz = num_elems(&ti);
      inputs[i].resize(sz);
      // read data
      H5Dread(dset_id, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, inputs[i].data());

      NNPR_ENSURE_STATUS(nnfw_set_input(session, i, NNFW_TYPE_TENSOR_FLOAT32, inputs[i].data(),
                                        sizeof(float) * num_elems(&ti)));
      // clean up
      H5Dclose(dset_id);
    }
    H5Gclose(valgrp_id);
    H5Fclose(file_id);
  };

  auto generateInputs = [session, num_inputs, &inputs]() {
    // generate random data
    const int seed = 1;
    RandomGenerator randgen{seed, 0.0f, 2.0f};
    for (uint32_t i = 0; i < num_inputs; ++i)
    {
      nnfw_tensorinfo ti;
      NNPR_ENSURE_STATUS(nnfw_input_tensorinfo(session, i, &ti));
      auto input_num_elements = num_elems(&ti);
      inputs[i] = randomData(randgen, input_num_elements);
      NNPR_ENSURE_STATUS(nnfw_set_input(session, i, NNFW_TYPE_TENSOR_FLOAT32, inputs[i].data(),
                                        sizeof(float) * input_num_elements));
    }
  };

  if (!args.getLoadFilename().empty())
    loadInputs(args.getLoadFilename());
  else
    generateInputs();

  // prepare output

  uint32_t num_outputs = 0;
  NNPR_ENSURE_STATUS(nnfw_output_size(session, &num_outputs));
  std::vector<std::vector<float>> outputs(num_outputs);

  for (uint32_t i = 0; i < num_outputs; i++)
  {
    nnfw_tensorinfo ti;
    NNPR_ENSURE_STATUS(nnfw_output_tensorinfo(session, i, &ti));
    auto output_num_elements = num_elems(&ti);
    outputs[i].resize(output_num_elements);
    NNPR_ENSURE_STATUS(nnfw_set_output(session, i, NNFW_TYPE_TENSOR_FLOAT32, outputs[i].data(),
                                       sizeof(float) * output_num_elements));
  }

  uint64_t run_ms = NowMicros();
  NNPR_ENSURE_STATUS(nnfw_run(session));
  run_ms = NowMicros() - run_ms;

  // dump output tensors

  auto dumpOutputs = [session, num_outputs, &outputs](std::string filename) {
    hid_t file_id = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    for (uint32_t i = 0; i < num_outputs; i++)
    {
      nnfw_tensorinfo ti;
      NNPR_ENSURE_STATUS(nnfw_output_tensorinfo(session, i, &ti));
      std::vector<hsize_t> dims;
      dims.resize(ti.rank);
      for (uint32_t j = 0; j < ti.rank; ++j)
      {
        assert(ti.dims[j] >= 0);
        dims[j] = ti.dims[j];
      }
      hid_t valgrp_id = H5Gcreate(file_id, h5_value_grpname, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
      hid_t dsp_id = H5Screate_simple(ti.rank, dims.data(), NULL);
      hid_t dset_id = H5Dcreate2(valgrp_id, std::to_string(i).c_str(), H5T_IEEE_F32BE, dsp_id,
                                 H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
      H5Dwrite(dset_id, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, outputs[i].data());
      H5Dclose(dset_id);
      H5Sclose(dsp_id);
    }
    H5Fclose(file_id);
  };

  if (!args.getDumpFilename().empty())
    dumpOutputs(args.getDumpFilename());

  std::cout << "nnfw_prepare takes " << prepare_ms / 1e3 << " sec" << std::endl;
  std::cout << "nnfw_run     takes " << run_ms / 1e3 << " sec" << std::endl;

  NNPR_ENSURE_STATUS(nnfw_close_session(session));

  return 0;
}