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/runtime/SubTensor.h"
28 #include "utils/Utils.h"
31 #include "arm_compute/core/CL/OpenCL.h"
32 #include "arm_compute/runtime/CL/CLTensor.h"
33 #endif /* ARM_COMPUTE_CL */
37 using namespace arm_compute::graph_utils;
39 void TFPreproccessor::preprocess(ITensor &tensor)
42 window.use_tensor_dimensions(tensor.info()->tensor_shape());
44 execute_window_loop(window, [&](const Coordinates & id)
46 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id));
47 float res = value / 255.f; // Normalize to [0, 1]
48 res = (res - 0.5f) * 2.f; // Map to [-1, 1]
49 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
53 CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
54 : _mean(mean), _bgr(bgr)
58 std::swap(_mean[0], _mean[2]);
62 void CaffePreproccessor::preprocess(ITensor &tensor)
65 window.use_tensor_dimensions(tensor.info()->tensor_shape());
67 execute_window_loop(window, [&](const Coordinates & id)
69 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id.z()];
70 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
74 PPMWriter::PPMWriter(std::string name, unsigned int maximum)
75 : _name(std::move(name)), _iterator(0), _maximum(maximum)
79 bool PPMWriter::access_tensor(ITensor &tensor)
82 ss << _name << _iterator << ".ppm";
84 arm_compute::utils::save_to_ppm(tensor, ss.str());
91 return _iterator < _maximum;
94 DummyAccessor::DummyAccessor(unsigned int maximum)
95 : _iterator(0), _maximum(maximum)
99 bool DummyAccessor::access_tensor(ITensor &tensor)
101 ARM_COMPUTE_UNUSED(tensor);
102 bool ret = _maximum == 0 || _iterator < _maximum;
103 if(_iterator == _maximum)
114 PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
115 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
119 bool PPMAccessor::access_tensor(ITensor &tensor)
121 utils::PPMLoader ppm;
126 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != tensor.info()->dimension(0) || ppm.height() != tensor.info()->dimension(1),
127 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].", ppm.width(), ppm.height(), tensor.info()->dimension(0), tensor.info()->dimension(1));
129 // Fill the tensor with the PPM content (BGR)
130 ppm.fill_planar_tensor(tensor, _bgr);
135 _preprocessor->preprocess(tensor);
141 TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
142 : _labels(), _output_stream(output_stream), _top_n(top_n)
150 ifs.exceptions(std::ifstream::badbit);
151 ifs.open(labels_path, std::ios::in | std::ios::binary);
153 for(std::string line; !std::getline(ifs, line).fail();)
155 _labels.emplace_back(line);
158 catch(const std::ifstream::failure &e)
160 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
164 template <typename T>
165 void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
167 // Get the predicted class
168 std::vector<T> classes_prob;
169 std::vector<size_t> index;
171 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
172 const size_t num_classes = tensor.info()->dimension(0);
174 classes_prob.resize(num_classes);
175 index.resize(num_classes);
177 std::copy(output_net, output_net + num_classes, classes_prob.begin());
180 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
181 std::sort(std::begin(index), std::end(index),
182 [&](size_t a, size_t b)
184 return classes_prob[a] > classes_prob[b];
187 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
189 for(size_t i = 0; i < _top_n; ++i)
191 _output_stream << std::fixed << std::setprecision(4)
192 << +classes_prob[index.at(i)]
193 << " - [id = " << index.at(i) << "]"
194 << ", " << _labels[index.at(i)] << std::endl;
198 bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
200 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
201 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
203 switch(tensor.info()->data_type())
205 case DataType::QASYMM8:
206 access_predictions_tensor<uint8_t>(tensor);
209 access_predictions_tensor<float>(tensor);
212 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
218 RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
219 : _lower(lower), _upper(upper), _seed(seed)
223 template <typename T, typename D>
224 void RandomAccessor::fill(ITensor &tensor, D &&distribution)
226 std::mt19937 gen(_seed);
228 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
230 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
232 const T value = distribution(gen);
233 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
238 // If tensor has padding accessing tensor elements through execution window.
240 window.use_tensor_dimensions(tensor.info()->tensor_shape());
242 execute_window_loop(window, [&](const Coordinates & id)
244 const T value = distribution(gen);
245 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
250 bool RandomAccessor::access_tensor(ITensor &tensor)
252 switch(tensor.info()->data_type())
256 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
257 fill<uint8_t>(tensor, distribution_u8);
263 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
264 fill<int8_t>(tensor, distribution_s8);
269 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
270 fill<uint16_t>(tensor, distribution_u16);
276 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
277 fill<int16_t>(tensor, distribution_s16);
282 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
283 fill<uint32_t>(tensor, distribution_u32);
288 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
289 fill<int32_t>(tensor, distribution_s32);
294 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
295 fill<uint64_t>(tensor, distribution_u64);
300 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
301 fill<int64_t>(tensor, distribution_s64);
306 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
307 fill<float>(tensor, distribution_f16);
312 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
313 fill<float>(tensor, distribution_f32);
318 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
319 fill<double>(tensor, distribution_f64);
323 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
328 NumPyBinLoader::NumPyBinLoader(std::string filename)
329 : _filename(std::move(filename))
333 bool NumPyBinLoader::access_tensor(ITensor &tensor)
335 const TensorShape tensor_shape = tensor.info()->tensor_shape();
336 std::vector<unsigned long> shape;
339 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
340 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
341 std::string header = npy::read_header(stream);
344 bool fortran_order = false;
346 npy::parse_header(header, typestr, fortran_order, shape);
348 // Check if the typestring matches the given one
349 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
350 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
352 // Reverse vector in case of non fortran order
355 std::reverse(shape.begin(), shape.end());
358 // Correct dimensions (Needs to match TensorShape dimension corrections)
359 if(shape.size() != tensor_shape.num_dimensions())
361 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
374 // Validate tensor ranks
375 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
378 for(size_t i = 0; i < shape.size(); ++i)
380 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
384 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
386 // If tensor has no padding read directly from stream.
387 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
391 // If tensor has padding accessing tensor elements through execution window.
393 window.use_tensor_dimensions(tensor_shape);
395 execute_window_loop(window, [&](const Coordinates & id)
397 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());