blob: f190af488148ea4d9304bfed8e1590587459ee61 [file] [log] [blame]
Kaizen8938bd32017-09-28 14:38:23 +01001/*
Anthony Barbierf45d5a92018-01-24 16:23:15 +00002 * Copyright (c) 2017-2018 ARM Limited.
Kaizen8938bd32017-09-28 14:38:23 +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"
hakanardo29222792018-02-16 10:06:34 +010027#include "arm_compute/runtime/SubTensor.h"
Kaizen8938bd32017-09-28 14:38:23 +010028
29#ifdef ARM_COMPUTE_CL
30#include "arm_compute/core/CL/OpenCL.h"
31#include "arm_compute/runtime/CL/CLTensor.h"
32#endif /* ARM_COMPUTE_CL */
33
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010034#include <iomanip>
Kaizen8938bd32017-09-28 14:38:23 +010035
36using namespace arm_compute::graph_utils;
37
38PPMWriter::PPMWriter(std::string name, unsigned int maximum)
39 : _name(std::move(name)), _iterator(0), _maximum(maximum)
40{
41}
42
43bool PPMWriter::access_tensor(ITensor &tensor)
44{
45 std::stringstream ss;
46 ss << _name << _iterator << ".ppm";
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010047
48 arm_compute::utils::save_to_ppm(tensor, ss.str());
Kaizen8938bd32017-09-28 14:38:23 +010049
50 _iterator++;
51 if(_maximum == 0)
52 {
53 return true;
54 }
55 return _iterator < _maximum;
56}
57
58DummyAccessor::DummyAccessor(unsigned int maximum)
59 : _iterator(0), _maximum(maximum)
60{
61}
62
63bool DummyAccessor::access_tensor(ITensor &tensor)
64{
65 ARM_COMPUTE_UNUSED(tensor);
66 bool ret = _maximum == 0 || _iterator < _maximum;
67 if(_iterator == _maximum)
68 {
69 _iterator = 0;
70 }
71 else
72 {
73 _iterator++;
74 }
75 return ret;
76}
77
Anthony Barbierf45d5a92018-01-24 16:23:15 +000078PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr,
79 float mean_r, float mean_g, float mean_b,
80 float std_r, float std_g, float std_b)
81 : _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)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010082{
83}
84
85bool PPMAccessor::access_tensor(ITensor &tensor)
86{
87 utils::PPMLoader ppm;
88 const float mean[3] =
89 {
90 _bgr ? _mean_b : _mean_r,
91 _mean_g,
92 _bgr ? _mean_r : _mean_b
93 };
Anthony Barbierf45d5a92018-01-24 16:23:15 +000094 const float std[3] =
95 {
96 _bgr ? _std_b : _std_r,
97 _std_g,
98 _bgr ? _std_r : _std_b
99 };
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100100
101 // Open PPM file
102 ppm.open(_ppm_path);
103
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000104 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != tensor.info()->dimension(0) || ppm.height() != tensor.info()->dimension(1),
105 "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));
106
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100107 // Fill the tensor with the PPM content (BGR)
108 ppm.fill_planar_tensor(tensor, _bgr);
109
110 // Subtract the mean value from each channel
111 Window window;
112 window.use_tensor_dimensions(tensor.info()->tensor_shape());
113
114 execute_window_loop(window, [&](const Coordinates & id)
115 {
116 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - mean[id.z()];
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000117 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value / std[id.z()];
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100118 });
119
120 return true;
121}
122
123TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
124 : _labels(), _output_stream(output_stream), _top_n(top_n)
125{
126 _labels.clear();
127
128 std::ifstream ifs;
129
130 try
131 {
132 ifs.exceptions(std::ifstream::badbit);
133 ifs.open(labels_path, std::ios::in | std::ios::binary);
134
135 for(std::string line; !std::getline(ifs, line).fail();)
136 {
137 _labels.emplace_back(line);
138 }
139 }
140 catch(const std::ifstream::failure &e)
141 {
142 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
143 }
144}
145
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000146template <typename T>
147void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100148{
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100149 // Get the predicted class
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000150 std::vector<T> classes_prob;
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100151 std::vector<size_t> index;
152
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000153 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100154 const size_t num_classes = tensor.info()->dimension(0);
155
156 classes_prob.resize(num_classes);
157 index.resize(num_classes);
158
159 std::copy(output_net, output_net + num_classes, classes_prob.begin());
160
161 // Sort results
162 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
163 std::sort(std::begin(index), std::end(index),
164 [&](size_t a, size_t b)
165 {
166 return classes_prob[a] > classes_prob[b];
167 });
168
169 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
170 << std::endl;
171 for(size_t i = 0; i < _top_n; ++i)
172 {
173 _output_stream << std::fixed << std::setprecision(4)
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000174 << +classes_prob[index.at(i)]
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100175 << " - [id = " << index.at(i) << "]"
176 << ", " << _labels[index.at(i)] << std::endl;
177 }
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000178}
179
180bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
181{
182 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
183 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
184
185 switch(tensor.info()->data_type())
186 {
187 case DataType::QASYMM8:
188 access_predictions_tensor<uint8_t>(tensor);
189 break;
190 case DataType::F32:
191 access_predictions_tensor<float>(tensor);
192 break;
193 default:
194 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
195 }
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100196
197 return false;
198}
199
Kaizenbf8b01d2017-10-12 14:26:51 +0100200RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
201 : _lower(lower), _upper(upper), _seed(seed)
202{
203}
204
205template <typename T, typename D>
206void RandomAccessor::fill(ITensor &tensor, D &&distribution)
207{
208 std::mt19937 gen(_seed);
209
hakanardo29222792018-02-16 10:06:34 +0100210 if(tensor.info()->padding().empty() && !dynamic_cast<SubTensor*>(&tensor))
Kaizenbf8b01d2017-10-12 14:26:51 +0100211 {
212 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
213 {
214 const T value = distribution(gen);
215 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
216 }
217 }
218 else
219 {
220 // If tensor has padding accessing tensor elements through execution window.
221 Window window;
222 window.use_tensor_dimensions(tensor.info()->tensor_shape());
223
224 execute_window_loop(window, [&](const Coordinates & id)
225 {
226 const T value = distribution(gen);
227 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
228 });
229 }
230}
231
232bool RandomAccessor::access_tensor(ITensor &tensor)
233{
234 switch(tensor.info()->data_type())
235 {
236 case DataType::U8:
237 {
238 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
239 fill<uint8_t>(tensor, distribution_u8);
240 break;
241 }
242 case DataType::S8:
243 case DataType::QS8:
244 {
245 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
246 fill<int8_t>(tensor, distribution_s8);
247 break;
248 }
249 case DataType::U16:
250 {
251 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
252 fill<uint16_t>(tensor, distribution_u16);
253 break;
254 }
255 case DataType::S16:
256 case DataType::QS16:
257 {
258 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
259 fill<int16_t>(tensor, distribution_s16);
260 break;
261 }
262 case DataType::U32:
263 {
264 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
265 fill<uint32_t>(tensor, distribution_u32);
266 break;
267 }
268 case DataType::S32:
269 {
270 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
271 fill<int32_t>(tensor, distribution_s32);
272 break;
273 }
274 case DataType::U64:
275 {
276 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
277 fill<uint64_t>(tensor, distribution_u64);
278 break;
279 }
280 case DataType::S64:
281 {
282 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
283 fill<int64_t>(tensor, distribution_s64);
284 break;
285 }
286 case DataType::F16:
287 {
288 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
289 fill<float>(tensor, distribution_f16);
290 break;
291 }
292 case DataType::F32:
293 {
294 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
295 fill<float>(tensor, distribution_f32);
296 break;
297 }
298 case DataType::F64:
299 {
300 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
301 fill<double>(tensor, distribution_f64);
302 break;
303 }
304 default:
305 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
306 }
307 return true;
308}
309
Kaizen8938bd32017-09-28 14:38:23 +0100310NumPyBinLoader::NumPyBinLoader(std::string filename)
311 : _filename(std::move(filename))
312{
313}
314
315bool NumPyBinLoader::access_tensor(ITensor &tensor)
316{
317 const TensorShape tensor_shape = tensor.info()->tensor_shape();
318 std::vector<unsigned long> shape;
319
320 // Open file
321 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
322 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000323 std::string header = npy::read_header(stream);
Kaizen8938bd32017-09-28 14:38:23 +0100324
325 // Parse header
326 bool fortran_order = false;
327 std::string typestr;
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000328 npy::parse_header(header, typestr, fortran_order, shape);
Kaizen8938bd32017-09-28 14:38:23 +0100329
330 // Check if the typestring matches the given one
331 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
332 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
333
334 // Validate tensor shape
335 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000336
Kaizen8938bd32017-09-28 14:38:23 +0100337 if(fortran_order)
338 {
339 for(size_t i = 0; i < shape.size(); ++i)
340 {
341 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
342 }
343 }
344 else
345 {
346 for(size_t i = 0; i < shape.size(); ++i)
347 {
348 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[shape.size() - i - 1], "Tensor dimensions mismatch");
349 }
350 }
351
352 // Read data
hakanardo29222792018-02-16 10:06:34 +0100353 if(tensor.info()->padding().empty() && !dynamic_cast<SubTensor*>(&tensor))
Kaizen8938bd32017-09-28 14:38:23 +0100354 {
355 // If tensor has no padding read directly from stream.
356 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
357 }
358 else
359 {
360 // If tensor has padding accessing tensor elements through execution window.
361 Window window;
362 window.use_tensor_dimensions(tensor_shape);
363
364 execute_window_loop(window, [&](const Coordinates & id)
365 {
366 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
367 });
368 }
369 return true;
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000370}