2 * Copyright (c) 2017 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"
26 #include "utils/Utils.h"
29 #include "arm_compute/core/CL/OpenCL.h"
30 #include "arm_compute/runtime/CL/CLTensor.h"
31 #endif /* ARM_COMPUTE_CL */
33 #include "arm_compute/core/Error.h"
34 #include "arm_compute/core/PixelValue.h"
41 using namespace arm_compute::graph_utils;
43 PPMWriter::PPMWriter(std::string name, unsigned int maximum)
44 : _name(std::move(name)), _iterator(0), _maximum(maximum)
48 bool PPMWriter::access_tensor(ITensor &tensor)
51 ss << _name << _iterator << ".ppm";
53 arm_compute::utils::save_to_ppm(tensor, ss.str());
60 return _iterator < _maximum;
63 DummyAccessor::DummyAccessor(unsigned int maximum)
64 : _iterator(0), _maximum(maximum)
68 bool DummyAccessor::access_tensor(ITensor &tensor)
70 ARM_COMPUTE_UNUSED(tensor);
71 bool ret = _maximum == 0 || _iterator < _maximum;
72 if(_iterator == _maximum)
83 PPMAccessor::PPMAccessor(const std::string &ppm_path, bool bgr, float mean_r, float mean_g, float mean_b)
84 : _ppm_path(ppm_path), _bgr(bgr), _mean_r(mean_r), _mean_g(mean_g), _mean_b(mean_b)
88 bool PPMAccessor::access_tensor(ITensor &tensor)
93 _bgr ? _mean_b : _mean_r,
95 _bgr ? _mean_r : _mean_b
101 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != tensor.info()->dimension(0) || ppm.height() != tensor.info()->dimension(1),
102 "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));
104 // Fill the tensor with the PPM content (BGR)
105 ppm.fill_planar_tensor(tensor, _bgr);
107 // Subtract the mean value from each channel
109 window.use_tensor_dimensions(tensor.info()->tensor_shape());
111 execute_window_loop(window, [&](const Coordinates & id)
113 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - mean[id.z()];
114 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
120 TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
121 : _labels(), _output_stream(output_stream), _top_n(top_n)
129 ifs.exceptions(std::ifstream::badbit);
130 ifs.open(labels_path, std::ios::in | std::ios::binary);
132 for(std::string line; !std::getline(ifs, line).fail();)
134 _labels.emplace_back(line);
137 catch(const std::ifstream::failure &e)
139 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
143 bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
145 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
146 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
148 // Get the predicted class
149 std::vector<float> classes_prob;
150 std::vector<size_t> index;
152 const auto output_net = reinterpret_cast<float *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
153 const size_t num_classes = tensor.info()->dimension(0);
155 classes_prob.resize(num_classes);
156 index.resize(num_classes);
158 std::copy(output_net, output_net + num_classes, classes_prob.begin());
161 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
162 std::sort(std::begin(index), std::end(index),
163 [&](size_t a, size_t b)
165 return classes_prob[a] > classes_prob[b];
168 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
170 for(size_t i = 0; i < _top_n; ++i)
172 _output_stream << std::fixed << std::setprecision(4)
173 << classes_prob[index.at(i)]
174 << " - [id = " << index.at(i) << "]"
175 << ", " << _labels[index.at(i)] << std::endl;
181 RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
182 : _lower(lower), _upper(upper), _seed(seed)
186 template <typename T, typename D>
187 void RandomAccessor::fill(ITensor &tensor, D &&distribution)
189 std::mt19937 gen(_seed);
191 if(tensor.info()->padding().empty())
193 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
195 const T value = distribution(gen);
196 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
201 // If tensor has padding accessing tensor elements through execution window.
203 window.use_tensor_dimensions(tensor.info()->tensor_shape());
205 execute_window_loop(window, [&](const Coordinates & id)
207 const T value = distribution(gen);
208 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
213 bool RandomAccessor::access_tensor(ITensor &tensor)
215 switch(tensor.info()->data_type())
219 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
220 fill<uint8_t>(tensor, distribution_u8);
226 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
227 fill<int8_t>(tensor, distribution_s8);
232 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
233 fill<uint16_t>(tensor, distribution_u16);
239 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
240 fill<int16_t>(tensor, distribution_s16);
245 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
246 fill<uint32_t>(tensor, distribution_u32);
251 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
252 fill<int32_t>(tensor, distribution_s32);
257 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
258 fill<uint64_t>(tensor, distribution_u64);
263 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
264 fill<int64_t>(tensor, distribution_s64);
269 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
270 fill<float>(tensor, distribution_f16);
275 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
276 fill<float>(tensor, distribution_f32);
281 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
282 fill<double>(tensor, distribution_f64);
286 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
291 NumPyBinLoader::NumPyBinLoader(std::string filename)
292 : _filename(std::move(filename))
296 bool NumPyBinLoader::access_tensor(ITensor &tensor)
298 const TensorShape tensor_shape = tensor.info()->tensor_shape();
299 std::vector<unsigned long> shape;
302 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
303 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
304 std::string header = npy::read_header(stream);
307 bool fortran_order = false;
309 npy::parse_header(header, typestr, fortran_order, shape);
311 // Check if the typestring matches the given one
312 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
313 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
315 // Validate tensor shape
316 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
319 for(size_t i = 0; i < shape.size(); ++i)
321 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
326 for(size_t i = 0; i < shape.size(); ++i)
328 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[shape.size() - i - 1], "Tensor dimensions mismatch");
333 if(tensor.info()->padding().empty())
335 // If tensor has no padding read directly from stream.
336 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
340 // If tensor has padding accessing tensor elements through execution window.
342 window.use_tensor_dimensions(tensor_shape);
344 execute_window_loop(window, [&](const Coordinates & id)
346 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());