blob: e248929cc2ee2ab5a45364c14b3a868ba48c5c66 [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
Gian Marco44ec2e72017-10-19 14:13:38 +010033#include <iomanip>
Anthony Barbier2a07e182017-08-04 18:20:27 +010034
35using namespace arm_compute::graph_utils;
36
37PPMWriter::PPMWriter(std::string name, unsigned int maximum)
38 : _name(std::move(name)), _iterator(0), _maximum(maximum)
39{
40}
41
42bool PPMWriter::access_tensor(ITensor &tensor)
43{
44 std::stringstream ss;
45 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +010046
47 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +010048
49 _iterator++;
50 if(_maximum == 0)
51 {
52 return true;
53 }
54 return _iterator < _maximum;
55}
56
57DummyAccessor::DummyAccessor(unsigned int maximum)
58 : _iterator(0), _maximum(maximum)
59{
60}
61
62bool DummyAccessor::access_tensor(ITensor &tensor)
63{
64 ARM_COMPUTE_UNUSED(tensor);
65 bool ret = _maximum == 0 || _iterator < _maximum;
66 if(_iterator == _maximum)
67 {
68 _iterator = 0;
69 }
70 else
71 {
72 _iterator++;
73 }
74 return ret;
75}
76
Georgios Pinitas652bde52018-01-10 15:33:28 +000077PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr,
78 float mean_r, float mean_g, float mean_b,
79 float std_r, float std_g, float std_b)
80 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _mean_r(mean_r), _mean_g(mean_g), _mean_b(mean_b), _std_r(std_r), _std_g(std_g), _std_b(std_b)
Gian Marco44ec2e72017-10-19 14:13:38 +010081{
82}
83
84bool PPMAccessor::access_tensor(ITensor &tensor)
85{
86 utils::PPMLoader ppm;
87 const float mean[3] =
88 {
89 _bgr ? _mean_b : _mean_r,
90 _mean_g,
91 _bgr ? _mean_r : _mean_b
92 };
Georgios Pinitas652bde52018-01-10 15:33:28 +000093 const float std[3] =
94 {
95 _bgr ? _std_b : _std_r,
96 _std_g,
97 _bgr ? _std_r : _std_b
98 };
Gian Marco44ec2e72017-10-19 14:13:38 +010099
100 // Open PPM file
101 ppm.open(_ppm_path);
102
Isabella Gottardia4c61882017-11-03 12:11:55 +0000103 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != tensor.info()->dimension(0) || ppm.height() != tensor.info()->dimension(1),
104 "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));
105
Gian Marco44ec2e72017-10-19 14:13:38 +0100106 // Fill the tensor with the PPM content (BGR)
107 ppm.fill_planar_tensor(tensor, _bgr);
108
109 // Subtract the mean value from each channel
110 Window window;
111 window.use_tensor_dimensions(tensor.info()->tensor_shape());
112
113 execute_window_loop(window, [&](const Coordinates & id)
114 {
115 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - mean[id.z()];
Georgios Pinitas652bde52018-01-10 15:33:28 +0000116 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value / std[id.z()];
Gian Marco44ec2e72017-10-19 14:13:38 +0100117 });
118
119 return true;
120}
121
122TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
123 : _labels(), _output_stream(output_stream), _top_n(top_n)
124{
125 _labels.clear();
126
127 std::ifstream ifs;
128
129 try
130 {
131 ifs.exceptions(std::ifstream::badbit);
132 ifs.open(labels_path, std::ios::in | std::ios::binary);
133
134 for(std::string line; !std::getline(ifs, line).fail();)
135 {
136 _labels.emplace_back(line);
137 }
138 }
139 catch(const std::ifstream::failure &e)
140 {
141 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
142 }
143}
144
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000145template <typename T>
146void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100147{
Gian Marco44ec2e72017-10-19 14:13:38 +0100148 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000149 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100150 std::vector<size_t> index;
151
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000152 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100153 const size_t num_classes = tensor.info()->dimension(0);
154
155 classes_prob.resize(num_classes);
156 index.resize(num_classes);
157
158 std::copy(output_net, output_net + num_classes, classes_prob.begin());
159
160 // Sort results
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)
164 {
165 return classes_prob[a] > classes_prob[b];
166 });
167
168 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
169 << std::endl;
170 for(size_t i = 0; i < _top_n; ++i)
171 {
172 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000173 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100174 << " - [id = " << index.at(i) << "]"
175 << ", " << _labels[index.at(i)] << std::endl;
176 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000177}
178
179bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
180{
181 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
182 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
183
184 switch(tensor.info()->data_type())
185 {
186 case DataType::QASYMM8:
187 access_predictions_tensor<uint8_t>(tensor);
188 break;
189 case DataType::F32:
190 access_predictions_tensor<float>(tensor);
191 break;
192 default:
193 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
194 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100195
196 return false;
197}
198
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100199RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
200 : _lower(lower), _upper(upper), _seed(seed)
201{
202}
203
204template <typename T, typename D>
205void RandomAccessor::fill(ITensor &tensor, D &&distribution)
206{
207 std::mt19937 gen(_seed);
208
209 if(tensor.info()->padding().empty())
210 {
211 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
212 {
213 const T value = distribution(gen);
214 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
215 }
216 }
217 else
218 {
219 // If tensor has padding accessing tensor elements through execution window.
220 Window window;
221 window.use_tensor_dimensions(tensor.info()->tensor_shape());
222
223 execute_window_loop(window, [&](const Coordinates & id)
224 {
225 const T value = distribution(gen);
226 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
227 });
228 }
229}
230
231bool RandomAccessor::access_tensor(ITensor &tensor)
232{
233 switch(tensor.info()->data_type())
234 {
235 case DataType::U8:
236 {
237 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
238 fill<uint8_t>(tensor, distribution_u8);
239 break;
240 }
241 case DataType::S8:
242 case DataType::QS8:
243 {
244 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
245 fill<int8_t>(tensor, distribution_s8);
246 break;
247 }
248 case DataType::U16:
249 {
250 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
251 fill<uint16_t>(tensor, distribution_u16);
252 break;
253 }
254 case DataType::S16:
255 case DataType::QS16:
256 {
257 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
258 fill<int16_t>(tensor, distribution_s16);
259 break;
260 }
261 case DataType::U32:
262 {
263 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
264 fill<uint32_t>(tensor, distribution_u32);
265 break;
266 }
267 case DataType::S32:
268 {
269 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
270 fill<int32_t>(tensor, distribution_s32);
271 break;
272 }
273 case DataType::U64:
274 {
275 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
276 fill<uint64_t>(tensor, distribution_u64);
277 break;
278 }
279 case DataType::S64:
280 {
281 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
282 fill<int64_t>(tensor, distribution_s64);
283 break;
284 }
285 case DataType::F16:
286 {
287 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
288 fill<float>(tensor, distribution_f16);
289 break;
290 }
291 case DataType::F32:
292 {
293 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
294 fill<float>(tensor, distribution_f32);
295 break;
296 }
297 case DataType::F64:
298 {
299 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
300 fill<double>(tensor, distribution_f64);
301 break;
302 }
303 default:
304 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
305 }
306 return true;
307}
308
Anthony Barbier2a07e182017-08-04 18:20:27 +0100309NumPyBinLoader::NumPyBinLoader(std::string filename)
310 : _filename(std::move(filename))
311{
312}
313
314bool NumPyBinLoader::access_tensor(ITensor &tensor)
315{
316 const TensorShape tensor_shape = tensor.info()->tensor_shape();
317 std::vector<unsigned long> shape;
318
319 // Open file
320 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
321 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000322 std::string header = npy::read_header(stream);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100323
324 // Parse header
325 bool fortran_order = false;
326 std::string typestr;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000327 npy::parse_header(header, typestr, fortran_order, shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100328
329 // Check if the typestring matches the given one
330 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
331 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
332
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000333 // Reverse vector in case of non fortran order
334 if(!fortran_order)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100335 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000336 std::reverse(shape.begin(), shape.end());
337 }
338
339 // Correct dimensions (Needs to match TensorShape dimension corrections)
340 if(shape.size() != tensor_shape.num_dimensions())
341 {
342 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100343 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000344 if(shape[i] == 1)
345 {
346 shape.pop_back();
347 }
348 else
349 {
350 break;
351 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100352 }
353 }
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000354
355 // Validate tensor ranks
356 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
357
358 // Validate shapes
359 for(size_t i = 0; i < shape.size(); ++i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100360 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000361 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
Anthony Barbier2a07e182017-08-04 18:20:27 +0100362 }
363
364 // Read data
365 if(tensor.info()->padding().empty())
366 {
367 // If tensor has no padding read directly from stream.
368 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
369 }
370 else
371 {
372 // If tensor has padding accessing tensor elements through execution window.
373 Window window;
374 window.use_tensor_dimensions(tensor_shape);
375
376 execute_window_loop(window, [&](const Coordinates & id)
377 {
378 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
379 });
380 }
381 return true;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000382}