blob: 2ff40b7fbbfe1f4aa8ddcf542981a523368ba314 [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"
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
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010033#include <iomanip>
Kaizen8938bd32017-09-28 14:38:23 +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";
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010046
47 arm_compute::utils::save_to_ppm(tensor, ss.str());
Kaizen8938bd32017-09-28 14:38:23 +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
Anthony Barbierf45d5a92018-01-24 16:23:15 +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)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +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 };
Anthony Barbierf45d5a92018-01-24 16:23:15 +000093 const float std[3] =
94 {
95 _bgr ? _std_b : _std_r,
96 _std_g,
97 _bgr ? _std_r : _std_b
98 };
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010099
100 // Open PPM file
101 ppm.open(_ppm_path);
102
Anthony Barbier8140e1e2017-12-14 23:48:46 +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
Anthony Barbier8a3da6f2017-10-23 18:55:17 +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()];
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000116 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value / std[id.z()];
Anthony Barbier8a3da6f2017-10-23 18:55:17 +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
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000145template <typename T>
146void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100147{
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100148 // Get the predicted class
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000149 std::vector<T> classes_prob;
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100150 std::vector<size_t> index;
151
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000152 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Anthony Barbier8a3da6f2017-10-23 18:55:17 +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)
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000173 << +classes_prob[index.at(i)]
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100174 << " - [id = " << index.at(i) << "]"
175 << ", " << _labels[index.at(i)] << std::endl;
176 }
Anthony Barbierf45d5a92018-01-24 16:23:15 +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 }
Anthony Barbier8a3da6f2017-10-23 18:55:17 +0100195
196 return false;
197}
198
Kaizenbf8b01d2017-10-12 14:26:51 +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
Kaizen8938bd32017-09-28 14:38:23 +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 Barbier8140e1e2017-12-14 23:48:46 +0000322 std::string header = npy::read_header(stream);
Kaizen8938bd32017-09-28 14:38:23 +0100323
324 // Parse header
325 bool fortran_order = false;
326 std::string typestr;
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000327 npy::parse_header(header, typestr, fortran_order, shape);
Kaizen8938bd32017-09-28 14:38:23 +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
333 // Validate tensor shape
334 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
Anthony Barbierf45d5a92018-01-24 16:23:15 +0000335
Kaizen8938bd32017-09-28 14:38:23 +0100336 if(fortran_order)
337 {
338 for(size_t i = 0; i < shape.size(); ++i)
339 {
340 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[i], "Tensor dimensions mismatch");
341 }
342 }
343 else
344 {
345 for(size_t i = 0; i < shape.size(); ++i)
346 {
347 ARM_COMPUTE_ERROR_ON_MSG(tensor_shape[i] != shape[shape.size() - i - 1], "Tensor dimensions mismatch");
348 }
349 }
350
351 // Read data
352 if(tensor.info()->padding().empty())
353 {
354 // If tensor has no padding read directly from stream.
355 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
356 }
357 else
358 {
359 // If tensor has padding accessing tensor elements through execution window.
360 Window window;
361 window.use_tensor_dimensions(tensor_shape);
362
363 execute_window_loop(window, [&](const Coordinates & id)
364 {
365 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
366 });
367 }
368 return true;
Anthony Barbier8140e1e2017-12-14 23:48:46 +0000369}