blob: 7912fd6b7d873d64d789d7c2a9ce5d2cb14f5532 [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"
hakanardof36ac352018-02-16 10:06:34 +010026
27#include "arm_compute/runtime/SubTensor.h"
Anthony Barbier2a07e182017-08-04 18:20:27 +010028#include "utils/Utils.h"
29
Gian Marco44ec2e72017-10-19 14:13:38 +010030#include <iomanip>
Anthony Barbier2a07e182017-08-04 18:20:27 +010031
32using namespace arm_compute::graph_utils;
33
Georgios Pinitas140fdc72018-02-16 11:42:38 +000034void TFPreproccessor::preprocess(ITensor &tensor)
35{
36 Window window;
37 window.use_tensor_dimensions(tensor.info()->tensor_shape());
38
39 execute_window_loop(window, [&](const Coordinates & id)
40 {
41 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id));
42 float res = value / 255.f; // Normalize to [0, 1]
43 res = (res - 0.5f) * 2.f; // Map to [-1, 1]
44 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
45 });
46}
47
48CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
49 : _mean(mean), _bgr(bgr)
50{
51 if(_bgr)
52 {
53 std::swap(_mean[0], _mean[2]);
54 }
55}
56
57void CaffePreproccessor::preprocess(ITensor &tensor)
58{
59 Window window;
60 window.use_tensor_dimensions(tensor.info()->tensor_shape());
61
62 execute_window_loop(window, [&](const Coordinates & id)
63 {
64 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id.z()];
65 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
66 });
67}
68
Anthony Barbier2a07e182017-08-04 18:20:27 +010069PPMWriter::PPMWriter(std::string name, unsigned int maximum)
70 : _name(std::move(name)), _iterator(0), _maximum(maximum)
71{
72}
73
74bool PPMWriter::access_tensor(ITensor &tensor)
75{
76 std::stringstream ss;
77 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +010078
79 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +010080
81 _iterator++;
82 if(_maximum == 0)
83 {
84 return true;
85 }
86 return _iterator < _maximum;
87}
88
89DummyAccessor::DummyAccessor(unsigned int maximum)
90 : _iterator(0), _maximum(maximum)
91{
92}
93
94bool DummyAccessor::access_tensor(ITensor &tensor)
95{
96 ARM_COMPUTE_UNUSED(tensor);
97 bool ret = _maximum == 0 || _iterator < _maximum;
98 if(_iterator == _maximum)
99 {
100 _iterator = 0;
101 }
102 else
103 {
104 _iterator++;
105 }
106 return ret;
107}
108
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000109PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
110 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
Gian Marco44ec2e72017-10-19 14:13:38 +0100111{
112}
113
114bool PPMAccessor::access_tensor(ITensor &tensor)
115{
116 utils::PPMLoader ppm;
Gian Marco44ec2e72017-10-19 14:13:38 +0100117
118 // Open PPM file
119 ppm.open(_ppm_path);
120
Isabella Gottardia4c61882017-11-03 12:11:55 +0000121 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != tensor.info()->dimension(0) || ppm.height() != tensor.info()->dimension(1),
122 "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));
123
Gian Marco44ec2e72017-10-19 14:13:38 +0100124 // Fill the tensor with the PPM content (BGR)
125 ppm.fill_planar_tensor(tensor, _bgr);
126
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000127 // Preprocess tensor
128 if(_preprocessor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100129 {
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000130 _preprocessor->preprocess(tensor);
131 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100132
133 return true;
134}
135
136TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
137 : _labels(), _output_stream(output_stream), _top_n(top_n)
138{
139 _labels.clear();
140
141 std::ifstream ifs;
142
143 try
144 {
145 ifs.exceptions(std::ifstream::badbit);
146 ifs.open(labels_path, std::ios::in | std::ios::binary);
147
148 for(std::string line; !std::getline(ifs, line).fail();)
149 {
150 _labels.emplace_back(line);
151 }
152 }
153 catch(const std::ifstream::failure &e)
154 {
155 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
156 }
157}
158
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000159template <typename T>
160void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100161{
Gian Marco44ec2e72017-10-19 14:13:38 +0100162 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000163 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100164 std::vector<size_t> index;
165
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000166 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100167 const size_t num_classes = tensor.info()->dimension(0);
168
169 classes_prob.resize(num_classes);
170 index.resize(num_classes);
171
172 std::copy(output_net, output_net + num_classes, classes_prob.begin());
173
174 // Sort results
175 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
176 std::sort(std::begin(index), std::end(index),
177 [&](size_t a, size_t b)
178 {
179 return classes_prob[a] > classes_prob[b];
180 });
181
182 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
183 << std::endl;
184 for(size_t i = 0; i < _top_n; ++i)
185 {
186 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000187 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100188 << " - [id = " << index.at(i) << "]"
189 << ", " << _labels[index.at(i)] << std::endl;
190 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000191}
192
193bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
194{
195 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
196 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
197
198 switch(tensor.info()->data_type())
199 {
200 case DataType::QASYMM8:
201 access_predictions_tensor<uint8_t>(tensor);
202 break;
203 case DataType::F32:
204 access_predictions_tensor<float>(tensor);
205 break;
206 default:
207 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
208 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100209
210 return false;
211}
212
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100213RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
214 : _lower(lower), _upper(upper), _seed(seed)
215{
216}
217
218template <typename T, typename D>
219void RandomAccessor::fill(ITensor &tensor, D &&distribution)
220{
221 std::mt19937 gen(_seed);
222
hakanardof36ac352018-02-16 10:06:34 +0100223 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100224 {
225 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
226 {
227 const T value = distribution(gen);
228 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
229 }
230 }
231 else
232 {
233 // If tensor has padding accessing tensor elements through execution window.
234 Window window;
235 window.use_tensor_dimensions(tensor.info()->tensor_shape());
236
237 execute_window_loop(window, [&](const Coordinates & id)
238 {
239 const T value = distribution(gen);
240 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
241 });
242 }
243}
244
245bool RandomAccessor::access_tensor(ITensor &tensor)
246{
247 switch(tensor.info()->data_type())
248 {
249 case DataType::U8:
250 {
251 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
252 fill<uint8_t>(tensor, distribution_u8);
253 break;
254 }
255 case DataType::S8:
256 case DataType::QS8:
257 {
258 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
259 fill<int8_t>(tensor, distribution_s8);
260 break;
261 }
262 case DataType::U16:
263 {
264 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
265 fill<uint16_t>(tensor, distribution_u16);
266 break;
267 }
268 case DataType::S16:
269 case DataType::QS16:
270 {
271 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
272 fill<int16_t>(tensor, distribution_s16);
273 break;
274 }
275 case DataType::U32:
276 {
277 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
278 fill<uint32_t>(tensor, distribution_u32);
279 break;
280 }
281 case DataType::S32:
282 {
283 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
284 fill<int32_t>(tensor, distribution_s32);
285 break;
286 }
287 case DataType::U64:
288 {
289 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
290 fill<uint64_t>(tensor, distribution_u64);
291 break;
292 }
293 case DataType::S64:
294 {
295 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
296 fill<int64_t>(tensor, distribution_s64);
297 break;
298 }
299 case DataType::F16:
300 {
301 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
302 fill<float>(tensor, distribution_f16);
303 break;
304 }
305 case DataType::F32:
306 {
307 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
308 fill<float>(tensor, distribution_f32);
309 break;
310 }
311 case DataType::F64:
312 {
313 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
314 fill<double>(tensor, distribution_f64);
315 break;
316 }
317 default:
318 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
319 }
320 return true;
321}
322
Anthony Barbier2a07e182017-08-04 18:20:27 +0100323NumPyBinLoader::NumPyBinLoader(std::string filename)
324 : _filename(std::move(filename))
325{
326}
327
328bool NumPyBinLoader::access_tensor(ITensor &tensor)
329{
330 const TensorShape tensor_shape = tensor.info()->tensor_shape();
331 std::vector<unsigned long> shape;
332
333 // Open file
334 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
335 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000336 std::string header = npy::read_header(stream);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100337
338 // Parse header
339 bool fortran_order = false;
340 std::string typestr;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000341 npy::parse_header(header, typestr, fortran_order, shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100342
343 // Check if the typestring matches the given one
344 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
345 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
346
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000347 // Reverse vector in case of non fortran order
348 if(!fortran_order)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100349 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000350 std::reverse(shape.begin(), shape.end());
351 }
352
353 // Correct dimensions (Needs to match TensorShape dimension corrections)
354 if(shape.size() != tensor_shape.num_dimensions())
355 {
356 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100357 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000358 if(shape[i] == 1)
359 {
360 shape.pop_back();
361 }
362 else
363 {
364 break;
365 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100366 }
367 }
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000368
369 // Validate tensor ranks
370 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
371
372 // Validate shapes
373 for(size_t i = 0; i < shape.size(); ++i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100374 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000375 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
Anthony Barbier2a07e182017-08-04 18:20:27 +0100376 }
377
378 // Read data
hakanardof36ac352018-02-16 10:06:34 +0100379 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Anthony Barbier2a07e182017-08-04 18:20:27 +0100380 {
381 // If tensor has no padding read directly from stream.
382 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
383 }
384 else
385 {
386 // If tensor has padding accessing tensor elements through execution window.
387 Window window;
388 window.use_tensor_dimensions(tensor_shape);
389
390 execute_window_loop(window, [&](const Coordinates & id)
391 {
392 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
393 });
394 }
395 return true;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000396}