blob: 145e44950bc485a7cb95d3365375167a29cd51f8 [file] [log] [blame]
Anthony Barbier2a07e182017-08-04 18:20:27 +01001/*
Giorgio Arenaa66eaa22017-12-21 19:50:06 +00002 * Copyright (c) 2017-2018 ARM Limited.
Anthony Barbier2a07e182017-08-04 18:20:27 +01003 *
4 * SPDX-License-Identifier: MIT
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25#include "utils/GraphUtils.h"
hakanardof36ac352018-02-16 10:06:34 +010026
Georgios Pinitascac13b12018-04-27 19:07:19 +010027#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/Types.h"
hakanardof36ac352018-02-16 10:06:34 +010029#include "arm_compute/runtime/SubTensor.h"
Anthony Barbier2a07e182017-08-04 18:20:27 +010030#include "utils/Utils.h"
31
Gian Marco44ec2e72017-10-19 14:13:38 +010032#include <iomanip>
Anthony Barbier2a07e182017-08-04 18:20:27 +010033
34using namespace arm_compute::graph_utils;
35
Georgios Pinitascac13b12018-04-27 19:07:19 +010036namespace
37{
38std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_paramaters(const arm_compute::TensorShape &shape,
39 arm_compute::DataLayout data_layout)
40{
41 // Set permutation parameters if needed
42 arm_compute::TensorShape permuted_shape = shape;
43 arm_compute::PermutationVector perm;
44 // Permute only if num_dimensions greater than 2
45 if(shape.num_dimensions() > 2)
46 {
47 perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
48
49 arm_compute::PermutationVector perm_shape = (data_layout == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
50 arm_compute::permute(permuted_shape, perm_shape);
51 }
52
53 return std::make_pair(permuted_shape, perm);
54}
55} // namespace
56
Georgios Pinitas140fdc72018-02-16 11:42:38 +000057void TFPreproccessor::preprocess(ITensor &tensor)
58{
59 Window window;
60 window.use_tensor_dimensions(tensor.info()->tensor_shape());
61
62 execute_window_loop(window, [&](const Coordinates & id)
63 {
64 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id));
65 float res = value / 255.f; // Normalize to [0, 1]
66 res = (res - 0.5f) * 2.f; // Map to [-1, 1]
67 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
68 });
69}
70
71CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
72 : _mean(mean), _bgr(bgr)
73{
74 if(_bgr)
75 {
76 std::swap(_mean[0], _mean[2]);
77 }
78}
79
80void CaffePreproccessor::preprocess(ITensor &tensor)
81{
82 Window window;
83 window.use_tensor_dimensions(tensor.info()->tensor_shape());
84
85 execute_window_loop(window, [&](const Coordinates & id)
86 {
87 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id.z()];
88 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
89 });
90}
91
Anthony Barbier2a07e182017-08-04 18:20:27 +010092PPMWriter::PPMWriter(std::string name, unsigned int maximum)
93 : _name(std::move(name)), _iterator(0), _maximum(maximum)
94{
95}
96
97bool PPMWriter::access_tensor(ITensor &tensor)
98{
99 std::stringstream ss;
100 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +0100101
102 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100103
104 _iterator++;
105 if(_maximum == 0)
106 {
107 return true;
108 }
109 return _iterator < _maximum;
110}
111
112DummyAccessor::DummyAccessor(unsigned int maximum)
113 : _iterator(0), _maximum(maximum)
114{
115}
116
117bool DummyAccessor::access_tensor(ITensor &tensor)
118{
119 ARM_COMPUTE_UNUSED(tensor);
120 bool ret = _maximum == 0 || _iterator < _maximum;
121 if(_iterator == _maximum)
122 {
123 _iterator = 0;
124 }
125 else
126 {
127 _iterator++;
128 }
129 return ret;
130}
131
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000132PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
133 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
Gian Marco44ec2e72017-10-19 14:13:38 +0100134{
135}
136
137bool PPMAccessor::access_tensor(ITensor &tensor)
138{
139 utils::PPMLoader ppm;
Gian Marco44ec2e72017-10-19 14:13:38 +0100140
141 // Open PPM file
142 ppm.open(_ppm_path);
143
Georgios Pinitascac13b12018-04-27 19:07:19 +0100144 // Get permutated shape and permutation parameters
145 TensorShape permuted_shape = tensor.info()->tensor_shape();
146 arm_compute::PermutationVector perm;
147 if(tensor.info()->data_layout() != DataLayout::NCHW)
148 {
149 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
150 }
151 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != permuted_shape.x() || ppm.height() != permuted_shape.y(),
152 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].", ppm.width(), ppm.height(), permuted_shape.x(), permuted_shape.y());
Isabella Gottardia4c61882017-11-03 12:11:55 +0000153
Gian Marco44ec2e72017-10-19 14:13:38 +0100154 // Fill the tensor with the PPM content (BGR)
155 ppm.fill_planar_tensor(tensor, _bgr);
156
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000157 // Preprocess tensor
158 if(_preprocessor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100159 {
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000160 _preprocessor->preprocess(tensor);
161 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100162
163 return true;
164}
165
166TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
167 : _labels(), _output_stream(output_stream), _top_n(top_n)
168{
169 _labels.clear();
170
171 std::ifstream ifs;
172
173 try
174 {
175 ifs.exceptions(std::ifstream::badbit);
176 ifs.open(labels_path, std::ios::in | std::ios::binary);
177
178 for(std::string line; !std::getline(ifs, line).fail();)
179 {
180 _labels.emplace_back(line);
181 }
182 }
183 catch(const std::ifstream::failure &e)
184 {
185 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
186 }
187}
188
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000189template <typename T>
190void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100191{
Gian Marco44ec2e72017-10-19 14:13:38 +0100192 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000193 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100194 std::vector<size_t> index;
195
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000196 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100197 const size_t num_classes = tensor.info()->dimension(0);
198
199 classes_prob.resize(num_classes);
200 index.resize(num_classes);
201
202 std::copy(output_net, output_net + num_classes, classes_prob.begin());
203
204 // Sort results
205 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
206 std::sort(std::begin(index), std::end(index),
207 [&](size_t a, size_t b)
208 {
209 return classes_prob[a] > classes_prob[b];
210 });
211
212 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
213 << std::endl;
214 for(size_t i = 0; i < _top_n; ++i)
215 {
216 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000217 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100218 << " - [id = " << index.at(i) << "]"
219 << ", " << _labels[index.at(i)] << std::endl;
220 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000221}
222
223bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
224{
225 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
226 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
227
228 switch(tensor.info()->data_type())
229 {
230 case DataType::QASYMM8:
231 access_predictions_tensor<uint8_t>(tensor);
232 break;
233 case DataType::F32:
234 access_predictions_tensor<float>(tensor);
235 break;
236 default:
237 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
238 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100239
240 return false;
241}
242
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100243RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
244 : _lower(lower), _upper(upper), _seed(seed)
245{
246}
247
248template <typename T, typename D>
249void RandomAccessor::fill(ITensor &tensor, D &&distribution)
250{
251 std::mt19937 gen(_seed);
252
hakanardof36ac352018-02-16 10:06:34 +0100253 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100254 {
255 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
256 {
257 const T value = distribution(gen);
258 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
259 }
260 }
261 else
262 {
263 // If tensor has padding accessing tensor elements through execution window.
264 Window window;
265 window.use_tensor_dimensions(tensor.info()->tensor_shape());
266
267 execute_window_loop(window, [&](const Coordinates & id)
268 {
269 const T value = distribution(gen);
270 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
271 });
272 }
273}
274
275bool RandomAccessor::access_tensor(ITensor &tensor)
276{
277 switch(tensor.info()->data_type())
278 {
279 case DataType::U8:
280 {
281 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
282 fill<uint8_t>(tensor, distribution_u8);
283 break;
284 }
285 case DataType::S8:
286 case DataType::QS8:
287 {
288 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
289 fill<int8_t>(tensor, distribution_s8);
290 break;
291 }
292 case DataType::U16:
293 {
294 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
295 fill<uint16_t>(tensor, distribution_u16);
296 break;
297 }
298 case DataType::S16:
299 case DataType::QS16:
300 {
301 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
302 fill<int16_t>(tensor, distribution_s16);
303 break;
304 }
305 case DataType::U32:
306 {
307 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
308 fill<uint32_t>(tensor, distribution_u32);
309 break;
310 }
311 case DataType::S32:
312 {
313 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
314 fill<int32_t>(tensor, distribution_s32);
315 break;
316 }
317 case DataType::U64:
318 {
319 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
320 fill<uint64_t>(tensor, distribution_u64);
321 break;
322 }
323 case DataType::S64:
324 {
325 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
326 fill<int64_t>(tensor, distribution_s64);
327 break;
328 }
329 case DataType::F16:
330 {
331 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
332 fill<float>(tensor, distribution_f16);
333 break;
334 }
335 case DataType::F32:
336 {
337 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
338 fill<float>(tensor, distribution_f32);
339 break;
340 }
341 case DataType::F64:
342 {
343 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
344 fill<double>(tensor, distribution_f64);
345 break;
346 }
347 default:
348 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
349 }
350 return true;
351}
352
Georgios Pinitascac13b12018-04-27 19:07:19 +0100353NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
354 : _filename(std::move(filename)), _file_layout(file_layout)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100355{
356}
357
358bool NumPyBinLoader::access_tensor(ITensor &tensor)
359{
360 const TensorShape tensor_shape = tensor.info()->tensor_shape();
361 std::vector<unsigned long> shape;
362
363 // Open file
364 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
365 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000366 std::string header = npy::read_header(stream);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100367
368 // Parse header
369 bool fortran_order = false;
370 std::string typestr;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000371 npy::parse_header(header, typestr, fortran_order, shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100372
373 // Check if the typestring matches the given one
374 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
375 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
376
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000377 // Reverse vector in case of non fortran order
378 if(!fortran_order)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100379 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000380 std::reverse(shape.begin(), shape.end());
381 }
382
383 // Correct dimensions (Needs to match TensorShape dimension corrections)
384 if(shape.size() != tensor_shape.num_dimensions())
385 {
386 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100387 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000388 if(shape[i] == 1)
389 {
390 shape.pop_back();
391 }
392 else
393 {
394 break;
395 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100396 }
397 }
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000398
Georgios Pinitascac13b12018-04-27 19:07:19 +0100399 bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
400
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000401 // Validate tensor ranks
402 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
403
Georgios Pinitascac13b12018-04-27 19:07:19 +0100404 // Set permutation parameters if needed
405 TensorShape permuted_shape = tensor_shape;
406 arm_compute::PermutationVector perm;
407 if(are_layouts_different)
408 {
409 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor_shape, tensor.info()->data_layout());
410 }
411
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000412 // Validate shapes
413 for(size_t i = 0; i < shape.size(); ++i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100414 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100415 ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != shape[i], "Tensor dimensions mismatch");
Anthony Barbier2a07e182017-08-04 18:20:27 +0100416 }
417
Georgios Pinitascac13b12018-04-27 19:07:19 +0100418 // Validate shapes and copy tensor
419 if(!are_layouts_different || perm.num_dimensions() <= 2)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100420 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100421 // Read data
422 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
423 {
424 // If tensor has no padding read directly from stream.
425 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
426 }
427 else
428 {
429 // If tensor has padding accessing tensor elements through execution window.
430 Window window;
431 window.use_tensor_dimensions(tensor_shape);
432
433 execute_window_loop(window, [&](const Coordinates & id)
434 {
435 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
436 });
437 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100438 }
439 else
440 {
441 // If tensor has padding accessing tensor elements through execution window.
442 Window window;
Georgios Pinitascac13b12018-04-27 19:07:19 +0100443 window.use_tensor_dimensions(permuted_shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100444
445 execute_window_loop(window, [&](const Coordinates & id)
446 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100447 Coordinates coords(id);
448 arm_compute::permute(coords, perm);
449 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(coords)), tensor.info()->element_size());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100450 });
451 }
452 return true;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000453}