blob: bcfc0f7994abfef18e9250825de05b33c7a5d918 [file] [log] [blame]
Kaizen8938bd32017-09-28 14:38:23 +01001/*
2 * Copyright (c) 2017 ARM Limited.
3 *
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"
Kaizenbf8b01d2017-10-12 14:26:51 +010034#include "arm_compute/core/PixelValue.h"
Kaizen8938bd32017-09-28 14:38:23 +010035#include "libnpy/npy.hpp"
36
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010037#include <algorithm>
38#include <iomanip>
39#include <ostream>
Kaizenbf8b01d2017-10-12 14:26:51 +010040#include <random>
Kaizen8938bd32017-09-28 14:38:23 +010041
42using namespace arm_compute::graph_utils;
43
44PPMWriter::PPMWriter(std::string name, unsigned int maximum)
45 : _name(std::move(name)), _iterator(0), _maximum(maximum)
46{
47}
48
49bool PPMWriter::access_tensor(ITensor &tensor)
50{
51 std::stringstream ss;
52 ss << _name << _iterator << ".ppm";
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010053
54 arm_compute::utils::save_to_ppm(tensor, ss.str());
Kaizen8938bd32017-09-28 14:38:23 +010055
56 _iterator++;
57 if(_maximum == 0)
58 {
59 return true;
60 }
61 return _iterator < _maximum;
62}
63
64DummyAccessor::DummyAccessor(unsigned int maximum)
65 : _iterator(0), _maximum(maximum)
66{
67}
68
69bool DummyAccessor::access_tensor(ITensor &tensor)
70{
71 ARM_COMPUTE_UNUSED(tensor);
72 bool ret = _maximum == 0 || _iterator < _maximum;
73 if(_iterator == _maximum)
74 {
75 _iterator = 0;
76 }
77 else
78 {
79 _iterator++;
80 }
81 return ret;
82}
83
Anthony Barbier8a3da6f2017-10-23 18:55:17 +010084PPMAccessor::PPMAccessor(const std::string &ppm_path, bool bgr, float mean_r, float mean_g, float mean_b)
85 : _ppm_path(ppm_path), _bgr(bgr), _mean_r(mean_r), _mean_g(mean_g), _mean_b(mean_b)
86{
87}
88
89bool PPMAccessor::access_tensor(ITensor &tensor)
90{
91 utils::PPMLoader ppm;
92 const float mean[3] =
93 {
94 _bgr ? _mean_b : _mean_r,
95 _mean_g,
96 _bgr ? _mean_r : _mean_b
97 };
98
99 // Open PPM file
100 ppm.open(_ppm_path);
101
102 // Fill the tensor with the PPM content (BGR)
103 ppm.fill_planar_tensor(tensor, _bgr);
104
105 // Subtract the mean value from each channel
106 Window window;
107 window.use_tensor_dimensions(tensor.info()->tensor_shape());
108
109 execute_window_loop(window, [&](const Coordinates & id)
110 {
111 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - mean[id.z()];
112 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
113 });
114
115 return true;
116}
117
118TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
119 : _labels(), _output_stream(output_stream), _top_n(top_n)
120{
121 _labels.clear();
122
123 std::ifstream ifs;
124
125 try
126 {
127 ifs.exceptions(std::ifstream::badbit);
128 ifs.open(labels_path, std::ios::in | std::ios::binary);
129
130 for(std::string line; !std::getline(ifs, line).fail();)
131 {
132 _labels.emplace_back(line);
133 }
134 }
135 catch(const std::ifstream::failure &e)
136 {
137 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
138 }
139}
140
141bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
142{
143 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
144 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
145
146 // Get the predicted class
147 std::vector<float> classes_prob;
148 std::vector<size_t> index;
149
150 const auto output_net = reinterpret_cast<float *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
151 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)
171 << classes_prob[index.at(i)]
172 << " - [id = " << index.at(i) << "]"
173 << ", " << _labels[index.at(i)] << std::endl;
174 }
175
176 return false;
177}
178
Kaizenbf8b01d2017-10-12 14:26:51 +0100179RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
180 : _lower(lower), _upper(upper), _seed(seed)
181{
182}
183
184template <typename T, typename D>
185void RandomAccessor::fill(ITensor &tensor, D &&distribution)
186{
187 std::mt19937 gen(_seed);
188
189 if(tensor.info()->padding().empty())
190 {
191 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
192 {
193 const T value = distribution(gen);
194 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
195 }
196 }
197 else
198 {
199 // If tensor has padding accessing tensor elements through execution window.
200 Window window;
201 window.use_tensor_dimensions(tensor.info()->tensor_shape());
202
203 execute_window_loop(window, [&](const Coordinates & id)
204 {
205 const T value = distribution(gen);
206 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
207 });
208 }
209}
210
211bool RandomAccessor::access_tensor(ITensor &tensor)
212{
213 switch(tensor.info()->data_type())
214 {
215 case DataType::U8:
216 {
217 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
218 fill<uint8_t>(tensor, distribution_u8);
219 break;
220 }
221 case DataType::S8:
222 case DataType::QS8:
223 {
224 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
225 fill<int8_t>(tensor, distribution_s8);
226 break;
227 }
228 case DataType::U16:
229 {
230 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
231 fill<uint16_t>(tensor, distribution_u16);
232 break;
233 }
234 case DataType::S16:
235 case DataType::QS16:
236 {
237 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
238 fill<int16_t>(tensor, distribution_s16);
239 break;
240 }
241 case DataType::U32:
242 {
243 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
244 fill<uint32_t>(tensor, distribution_u32);
245 break;
246 }
247 case DataType::S32:
248 {
249 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
250 fill<int32_t>(tensor, distribution_s32);
251 break;
252 }
253 case DataType::U64:
254 {
255 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
256 fill<uint64_t>(tensor, distribution_u64);
257 break;
258 }
259 case DataType::S64:
260 {
261 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
262 fill<int64_t>(tensor, distribution_s64);
263 break;
264 }
265 case DataType::F16:
266 {
267 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
268 fill<float>(tensor, distribution_f16);
269 break;
270 }
271 case DataType::F32:
272 {
273 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
274 fill<float>(tensor, distribution_f32);
275 break;
276 }
277 case DataType::F64:
278 {
279 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
280 fill<double>(tensor, distribution_f64);
281 break;
282 }
283 default:
284 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
285 }
286 return true;
287}
288
Kaizen8938bd32017-09-28 14:38:23 +0100289NumPyBinLoader::NumPyBinLoader(std::string filename)
290 : _filename(std::move(filename))
291{
292}
293
294bool NumPyBinLoader::access_tensor(ITensor &tensor)
295{
296 const TensorShape tensor_shape = tensor.info()->tensor_shape();
297 std::vector<unsigned long> shape;
298
299 // Open file
300 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
301 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
302 // Check magic bytes and version number
303 unsigned char v_major = 0;
304 unsigned char v_minor = 0;
305 npy::read_magic(stream, &v_major, &v_minor);
306
307 // Read header
308 std::string header;
309 if(v_major == 1 && v_minor == 0)
310 {
311 header = npy::read_header_1_0(stream);
312 }
313 else if(v_major == 2 && v_minor == 0)
314 {
315 header = npy::read_header_2_0(stream);
316 }
317 else
318 {
319 ARM_COMPUTE_ERROR("Unsupported file format version");
320 }
321
322 // Parse header
323 bool fortran_order = false;
324 std::string typestr;
325 npy::ParseHeader(header, typestr, &fortran_order, shape);
326
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;
Kaizenbf8b01d2017-10-12 14:26:51 +0100366}