2 * Copyright (c) 2017-2018 ARM Limited.
4 * SPDX-License-Identifier: MIT
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:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
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
25 #include "utils/GraphUtils.h"
27 #include "arm_compute/core/Helpers.h"
28 #include "arm_compute/core/Types.h"
29 #include "arm_compute/runtime/SubTensor.h"
30 #include "utils/Utils.h"
34 using namespace arm_compute::graph_utils;
38 std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_paramaters(const arm_compute::TensorShape &shape,
39 arm_compute::DataLayout data_layout)
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)
47 perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
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);
53 return std::make_pair(permuted_shape, perm);
57 void TFPreproccessor::preprocess(ITensor &tensor)
60 window.use_tensor_dimensions(tensor.info()->tensor_shape());
62 execute_window_loop(window, [&](const Coordinates & id)
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;
71 CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
72 : _mean(mean), _bgr(bgr)
76 std::swap(_mean[0], _mean[2]);
80 void CaffePreproccessor::preprocess(ITensor &tensor)
83 window.use_tensor_dimensions(tensor.info()->tensor_shape());
85 execute_window_loop(window, [&](const Coordinates & id)
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;
92 PPMWriter::PPMWriter(std::string name, unsigned int maximum)
93 : _name(std::move(name)), _iterator(0), _maximum(maximum)
97 bool PPMWriter::access_tensor(ITensor &tensor)
100 ss << _name << _iterator << ".ppm";
102 arm_compute::utils::save_to_ppm(tensor, ss.str());
109 return _iterator < _maximum;
112 DummyAccessor::DummyAccessor(unsigned int maximum)
113 : _iterator(0), _maximum(maximum)
117 bool DummyAccessor::access_tensor(ITensor &tensor)
119 ARM_COMPUTE_UNUSED(tensor);
120 bool ret = _maximum == 0 || _iterator < _maximum;
121 if(_iterator == _maximum)
132 NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, std::ostream &output_stream)
133 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
135 NumPyBinLoader loader(_filename);
137 TensorInfo info(shape, 1, data_type);
138 _npy_tensor.allocator()->init(info);
139 _npy_tensor.allocator()->allocate();
141 loader.access_tensor(_npy_tensor);
144 template <typename T>
145 void NumPyAccessor::access_numpy_tensor(ITensor &tensor)
147 const int num_elements = tensor.info()->total_size();
148 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor);
149 float percentage_mismatches = static_cast<float>(num_mismatches) / num_elements;
151 _output_stream << "Results: " << 100.f - (percentage_mismatches * 100) << " % matches with the provided output[" << _filename << "]." << std::endl;
154 bool NumPyAccessor::access_tensor(ITensor &tensor)
156 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
157 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
159 switch(tensor.info()->data_type())
162 access_numpy_tensor<float>(tensor);
165 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
171 PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
172 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
176 bool PPMAccessor::access_tensor(ITensor &tensor)
178 utils::PPMLoader ppm;
183 // Get permutated shape and permutation parameters
184 TensorShape permuted_shape = tensor.info()->tensor_shape();
185 arm_compute::PermutationVector perm;
186 if(tensor.info()->data_layout() != DataLayout::NCHW)
188 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
190 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != permuted_shape.x() || ppm.height() != permuted_shape.y(),
191 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].", ppm.width(), ppm.height(), permuted_shape.x(), permuted_shape.y());
193 // Fill the tensor with the PPM content (BGR)
194 ppm.fill_planar_tensor(tensor, _bgr);
199 _preprocessor->preprocess(tensor);
205 TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
206 : _labels(), _output_stream(output_stream), _top_n(top_n)
214 ifs.exceptions(std::ifstream::badbit);
215 ifs.open(labels_path, std::ios::in | std::ios::binary);
217 for(std::string line; !std::getline(ifs, line).fail();)
219 _labels.emplace_back(line);
222 catch(const std::ifstream::failure &e)
224 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
228 template <typename T>
229 void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
231 // Get the predicted class
232 std::vector<T> classes_prob;
233 std::vector<size_t> index;
235 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
236 const size_t num_classes = tensor.info()->dimension(0);
238 classes_prob.resize(num_classes);
239 index.resize(num_classes);
241 std::copy(output_net, output_net + num_classes, classes_prob.begin());
244 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
245 std::sort(std::begin(index), std::end(index),
246 [&](size_t a, size_t b)
248 return classes_prob[a] > classes_prob[b];
251 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
253 for(size_t i = 0; i < _top_n; ++i)
255 _output_stream << std::fixed << std::setprecision(4)
256 << +classes_prob[index.at(i)]
257 << " - [id = " << index.at(i) << "]"
258 << ", " << _labels[index.at(i)] << std::endl;
262 bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
264 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
265 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
267 switch(tensor.info()->data_type())
269 case DataType::QASYMM8:
270 access_predictions_tensor<uint8_t>(tensor);
273 access_predictions_tensor<float>(tensor);
276 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
282 RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
283 : _lower(lower), _upper(upper), _seed(seed)
287 template <typename T, typename D>
288 void RandomAccessor::fill(ITensor &tensor, D &&distribution)
290 std::mt19937 gen(_seed);
292 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
294 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
296 const T value = distribution(gen);
297 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
302 // If tensor has padding accessing tensor elements through execution window.
304 window.use_tensor_dimensions(tensor.info()->tensor_shape());
306 execute_window_loop(window, [&](const Coordinates & id)
308 const T value = distribution(gen);
309 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
314 bool RandomAccessor::access_tensor(ITensor &tensor)
316 switch(tensor.info()->data_type())
320 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
321 fill<uint8_t>(tensor, distribution_u8);
327 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
328 fill<int8_t>(tensor, distribution_s8);
333 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
334 fill<uint16_t>(tensor, distribution_u16);
340 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
341 fill<int16_t>(tensor, distribution_s16);
346 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
347 fill<uint32_t>(tensor, distribution_u32);
352 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
353 fill<int32_t>(tensor, distribution_s32);
358 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
359 fill<uint64_t>(tensor, distribution_u64);
364 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
365 fill<int64_t>(tensor, distribution_s64);
370 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
371 fill<float>(tensor, distribution_f16);
376 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
377 fill<float>(tensor, distribution_f32);
382 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
383 fill<double>(tensor, distribution_f64);
387 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
392 NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
393 : _filename(std::move(filename)), _file_layout(file_layout)
397 bool NumPyBinLoader::access_tensor(ITensor &tensor)
399 const TensorShape tensor_shape = tensor.info()->tensor_shape();
400 std::vector<unsigned long> shape;
403 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
404 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
405 std::string header = npy::read_header(stream);
408 bool fortran_order = false;
410 npy::parse_header(header, typestr, fortran_order, shape);
412 // Check if the typestring matches the given one
413 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
414 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
416 // Reverse vector in case of non fortran order
419 std::reverse(shape.begin(), shape.end());
422 // Correct dimensions (Needs to match TensorShape dimension corrections)
423 if(shape.size() != tensor_shape.num_dimensions())
425 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
438 bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
440 // Validate tensor ranks
441 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
443 // Set permutation parameters if needed
444 TensorShape permuted_shape = tensor_shape;
445 arm_compute::PermutationVector perm;
446 if(are_layouts_different)
448 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor_shape, tensor.info()->data_layout());
452 for(size_t i = 0; i < shape.size(); ++i)
454 ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != shape[i], "Tensor dimensions mismatch");
457 // Validate shapes and copy tensor
458 if(!are_layouts_different || perm.num_dimensions() <= 2)
461 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
463 // If tensor has no padding read directly from stream.
464 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
468 // If tensor has padding accessing tensor elements through execution window.
470 window.use_tensor_dimensions(tensor_shape);
472 execute_window_loop(window, [&](const Coordinates & id)
474 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
480 // If tensor has padding accessing tensor elements through execution window.
482 window.use_tensor_dimensions(permuted_shape);
484 execute_window_loop(window, [&](const Coordinates & id)
486 Coordinates coords(id);
487 arm_compute::permute(coords, perm);
488 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(coords)), tensor.info()->element_size());