blob: 6b3dffc1a4fe168ee1007cefbfc92bd312862846 [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"
26#include "utils/Utils.h"
27
28#ifdef ARM_COMPUTE_CL
29#include "arm_compute/core/CL/OpenCL.h"
30#include "arm_compute/runtime/CL/CLTensor.h"
31#endif /* ARM_COMPUTE_CL */
32
33#include "arm_compute/core/Error.h"
Michalis Spyrou53b405f2017-09-27 15:55:31 +010034#include "arm_compute/core/PixelValue.h"
Anthony Barbier2a07e182017-08-04 18:20:27 +010035
Gian Marco44ec2e72017-10-19 14:13:38 +010036#include <algorithm>
37#include <iomanip>
38#include <ostream>
Michalis Spyrou53b405f2017-09-27 15:55:31 +010039#include <random>
Anthony Barbier2a07e182017-08-04 18:20:27 +010040
41using namespace arm_compute::graph_utils;
42
43PPMWriter::PPMWriter(std::string name, unsigned int maximum)
44 : _name(std::move(name)), _iterator(0), _maximum(maximum)
45{
46}
47
48bool PPMWriter::access_tensor(ITensor &tensor)
49{
50 std::stringstream ss;
51 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +010052
53 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +010054
55 _iterator++;
56 if(_maximum == 0)
57 {
58 return true;
59 }
60 return _iterator < _maximum;
61}
62
63DummyAccessor::DummyAccessor(unsigned int maximum)
64 : _iterator(0), _maximum(maximum)
65{
66}
67
68bool DummyAccessor::access_tensor(ITensor &tensor)
69{
70 ARM_COMPUTE_UNUSED(tensor);
71 bool ret = _maximum == 0 || _iterator < _maximum;
72 if(_iterator == _maximum)
73 {
74 _iterator = 0;
75 }
76 else
77 {
78 _iterator++;
79 }
80 return ret;
81}
82
Gian Marco44ec2e72017-10-19 14:13:38 +010083PPMAccessor::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)
85{
86}
87
88bool PPMAccessor::access_tensor(ITensor &tensor)
89{
90 utils::PPMLoader ppm;
91 const float mean[3] =
92 {
93 _bgr ? _mean_b : _mean_r,
94 _mean_g,
95 _bgr ? _mean_r : _mean_b
96 };
97
98 // Open PPM file
99 ppm.open(_ppm_path);
100
Isabella Gottardia4c61882017-11-03 12:11:55 +0000101 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));
103
Gian Marco44ec2e72017-10-19 14:13:38 +0100104 // Fill the tensor with the PPM content (BGR)
105 ppm.fill_planar_tensor(tensor, _bgr);
106
107 // Subtract the mean value from each channel
108 Window window;
109 window.use_tensor_dimensions(tensor.info()->tensor_shape());
110
111 execute_window_loop(window, [&](const Coordinates & id)
112 {
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;
115 });
116
117 return true;
118}
119
120TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
121 : _labels(), _output_stream(output_stream), _top_n(top_n)
122{
123 _labels.clear();
124
125 std::ifstream ifs;
126
127 try
128 {
129 ifs.exceptions(std::ifstream::badbit);
130 ifs.open(labels_path, std::ios::in | std::ios::binary);
131
132 for(std::string line; !std::getline(ifs, line).fail();)
133 {
134 _labels.emplace_back(line);
135 }
136 }
137 catch(const std::ifstream::failure &e)
138 {
139 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
140 }
141}
142
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000143template <typename T>
144void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100145{
Gian Marco44ec2e72017-10-19 14:13:38 +0100146 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000147 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100148 std::vector<size_t> index;
149
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000150 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100151 const size_t num_classes = tensor.info()->dimension(0);
152
153 classes_prob.resize(num_classes);
154 index.resize(num_classes);
155
156 std::copy(output_net, output_net + num_classes, classes_prob.begin());
157
158 // Sort results
159 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
160 std::sort(std::begin(index), std::end(index),
161 [&](size_t a, size_t b)
162 {
163 return classes_prob[a] > classes_prob[b];
164 });
165
166 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
167 << std::endl;
168 for(size_t i = 0; i < _top_n; ++i)
169 {
170 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000171 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100172 << " - [id = " << index.at(i) << "]"
173 << ", " << _labels[index.at(i)] << std::endl;
174 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000175}
176
177bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
178{
179 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
180 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
181
182 switch(tensor.info()->data_type())
183 {
184 case DataType::QASYMM8:
185 access_predictions_tensor<uint8_t>(tensor);
186 break;
187 case DataType::F32:
188 access_predictions_tensor<float>(tensor);
189 break;
190 default:
191 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
192 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100193
194 return false;
195}
196
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100197RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
198 : _lower(lower), _upper(upper), _seed(seed)
199{
200}
201
202template <typename T, typename D>
203void RandomAccessor::fill(ITensor &tensor, D &&distribution)
204{
205 std::mt19937 gen(_seed);
206
207 if(tensor.info()->padding().empty())
208 {
209 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
210 {
211 const T value = distribution(gen);
212 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
213 }
214 }
215 else
216 {
217 // If tensor has padding accessing tensor elements through execution window.
218 Window window;
219 window.use_tensor_dimensions(tensor.info()->tensor_shape());
220
221 execute_window_loop(window, [&](const Coordinates & id)
222 {
223 const T value = distribution(gen);
224 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
225 });
226 }
227}
228
229bool RandomAccessor::access_tensor(ITensor &tensor)
230{
231 switch(tensor.info()->data_type())
232 {
233 case DataType::U8:
234 {
235 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
236 fill<uint8_t>(tensor, distribution_u8);
237 break;
238 }
239 case DataType::S8:
240 case DataType::QS8:
241 {
242 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
243 fill<int8_t>(tensor, distribution_s8);
244 break;
245 }
246 case DataType::U16:
247 {
248 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
249 fill<uint16_t>(tensor, distribution_u16);
250 break;
251 }
252 case DataType::S16:
253 case DataType::QS16:
254 {
255 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
256 fill<int16_t>(tensor, distribution_s16);
257 break;
258 }
259 case DataType::U32:
260 {
261 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
262 fill<uint32_t>(tensor, distribution_u32);
263 break;
264 }
265 case DataType::S32:
266 {
267 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
268 fill<int32_t>(tensor, distribution_s32);
269 break;
270 }
271 case DataType::U64:
272 {
273 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
274 fill<uint64_t>(tensor, distribution_u64);
275 break;
276 }
277 case DataType::S64:
278 {
279 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
280 fill<int64_t>(tensor, distribution_s64);
281 break;
282 }
283 case DataType::F16:
284 {
285 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
286 fill<float>(tensor, distribution_f16);
287 break;
288 }
289 case DataType::F32:
290 {
291 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
292 fill<float>(tensor, distribution_f32);
293 break;
294 }
295 case DataType::F64:
296 {
297 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
298 fill<double>(tensor, distribution_f64);
299 break;
300 }
301 default:
302 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
303 }
304 return true;
305}
306
Anthony Barbier2a07e182017-08-04 18:20:27 +0100307NumPyBinLoader::NumPyBinLoader(std::string filename)
308 : _filename(std::move(filename))
309{
310}
311
312bool NumPyBinLoader::access_tensor(ITensor &tensor)
313{
314 const TensorShape tensor_shape = tensor.info()->tensor_shape();
315 std::vector<unsigned long> shape;
316
317 // Open file
318 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
319 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000320 std::string header = npy::read_header(stream);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100321
322 // Parse header
323 bool fortran_order = false;
324 std::string typestr;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000325 npy::parse_header(header, typestr, fortran_order, shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100326
327 // Check if the typestring matches the given one
328 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
329 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
330
331 // Validate tensor shape
332 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
333 if(fortran_order)
334 {
335 for(size_t i = 0; i < shape.size(); ++i)
336 {
337 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
338 }
339 }
340 else
341 {
342 for(size_t i = 0; i < shape.size(); ++i)
343 {
344 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[shape.size() - i - 1], "Tensor dimensions mismatch");
345 }
346 }
347
348 // Read data
349 if(tensor.info()->padding().empty())
350 {
351 // If tensor has no padding read directly from stream.
352 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
353 }
354 else
355 {
356 // If tensor has padding accessing tensor elements through execution window.
357 Window window;
358 window.use_tensor_dimensions(tensor_shape);
359
360 execute_window_loop(window, [&](const Coordinates & id)
361 {
362 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
363 });
364 }
365 return true;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000366}