arm_compute v18.05
[platform/upstream/armcl.git] / utils / GraphUtils.cpp
1 /*
2  * Copyright (c) 2017-2018 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
27 #include "arm_compute/core/Helpers.h"
28 #include "arm_compute/core/Types.h"
29 #include "arm_compute/runtime/SubTensor.h"
30 #include "utils/Utils.h"
31
32 #include <iomanip>
33
34 using namespace arm_compute::graph_utils;
35
36 namespace
37 {
38 std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_paramaters(const arm_compute::TensorShape &shape,
39                                                                                                    arm_compute::DataLayout data_layout)
40 {
41     // Set permutation parameters if needed
42     arm_compute::TensorShape       permuted_shape = shape;
43     arm_compute::PermutationVector perm;
44     // Permute only if num_dimensions greater than 2
45     if(shape.num_dimensions() > 2)
46     {
47         perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
48
49         arm_compute::PermutationVector perm_shape = (data_layout == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
50         arm_compute::permute(permuted_shape, perm_shape);
51     }
52
53     return std::make_pair(permuted_shape, perm);
54 }
55 } // namespace
56
57 void TFPreproccessor::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));
65         float       res                                       = value / 255.f;      // Normalize to [0, 1]
66         res                                                   = (res - 0.5f) * 2.f; // Map to [-1, 1]
67         *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
68     });
69 }
70
71 CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
72     : _mean(mean), _bgr(bgr)
73 {
74     if(_bgr)
75     {
76         std::swap(_mean[0], _mean[2]);
77     }
78 }
79
80 void CaffePreproccessor::preprocess(ITensor &tensor)
81 {
82     Window window;
83     window.use_tensor_dimensions(tensor.info()->tensor_shape());
84
85     execute_window_loop(window, [&](const Coordinates & id)
86     {
87         const float value                                     = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id.z()];
88         *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
89     });
90 }
91
92 PPMWriter::PPMWriter(std::string name, unsigned int maximum)
93     : _name(std::move(name)), _iterator(0), _maximum(maximum)
94 {
95 }
96
97 bool PPMWriter::access_tensor(ITensor &tensor)
98 {
99     std::stringstream ss;
100     ss << _name << _iterator << ".ppm";
101
102     arm_compute::utils::save_to_ppm(tensor, ss.str());
103
104     _iterator++;
105     if(_maximum == 0)
106     {
107         return true;
108     }
109     return _iterator < _maximum;
110 }
111
112 DummyAccessor::DummyAccessor(unsigned int maximum)
113     : _iterator(0), _maximum(maximum)
114 {
115 }
116
117 bool DummyAccessor::access_tensor(ITensor &tensor)
118 {
119     ARM_COMPUTE_UNUSED(tensor);
120     bool ret = _maximum == 0 || _iterator < _maximum;
121     if(_iterator == _maximum)
122     {
123         _iterator = 0;
124     }
125     else
126     {
127         _iterator++;
128     }
129     return ret;
130 }
131
132 NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, std::ostream &output_stream)
133     : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
134 {
135     NumPyBinLoader loader(_filename);
136
137     TensorInfo info(shape, 1, data_type);
138     _npy_tensor.allocator()->init(info);
139     _npy_tensor.allocator()->allocate();
140
141     loader.access_tensor(_npy_tensor);
142 }
143
144 template <typename T>
145 void NumPyAccessor::access_numpy_tensor(ITensor &tensor)
146 {
147     const int num_elements          = tensor.info()->total_size();
148     int       num_mismatches        = utils::compare_tensor<T>(tensor, _npy_tensor);
149     float     percentage_mismatches = static_cast<float>(num_mismatches) / num_elements;
150
151     _output_stream << "Results: " << 100.f - (percentage_mismatches * 100) << " % matches with the provided output[" << _filename << "]." << std::endl;
152 }
153
154 bool NumPyAccessor::access_tensor(ITensor &tensor)
155 {
156     ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
157     ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
158
159     switch(tensor.info()->data_type())
160     {
161         case DataType::F32:
162             access_numpy_tensor<float>(tensor);
163             break;
164         default:
165             ARM_COMPUTE_ERROR("NOT SUPPORTED!");
166     }
167
168     return false;
169 }
170
171 PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
172     : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
173 {
174 }
175
176 bool PPMAccessor::access_tensor(ITensor &tensor)
177 {
178     utils::PPMLoader ppm;
179
180     // Open PPM file
181     ppm.open(_ppm_path);
182
183     // Get permutated shape and permutation parameters
184     TensorShape                    permuted_shape = tensor.info()->tensor_shape();
185     arm_compute::PermutationVector perm;
186     if(tensor.info()->data_layout() != DataLayout::NCHW)
187     {
188         std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
189     }
190     ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != permuted_shape.x() || ppm.height() != permuted_shape.y(),
191                              "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].", ppm.width(), ppm.height(), permuted_shape.x(), permuted_shape.y());
192
193     // Fill the tensor with the PPM content (BGR)
194     ppm.fill_planar_tensor(tensor, _bgr);
195
196     // Preprocess tensor
197     if(_preprocessor)
198     {
199         _preprocessor->preprocess(tensor);
200     }
201
202     return true;
203 }
204
205 TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
206     : _labels(), _output_stream(output_stream), _top_n(top_n)
207 {
208     _labels.clear();
209
210     std::ifstream ifs;
211
212     try
213     {
214         ifs.exceptions(std::ifstream::badbit);
215         ifs.open(labels_path, std::ios::in | std::ios::binary);
216
217         for(std::string line; !std::getline(ifs, line).fail();)
218         {
219             _labels.emplace_back(line);
220         }
221     }
222     catch(const std::ifstream::failure &e)
223     {
224         ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
225     }
226 }
227
228 template <typename T>
229 void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
230 {
231     // Get the predicted class
232     std::vector<T>      classes_prob;
233     std::vector<size_t> index;
234
235     const auto   output_net  = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
236     const size_t num_classes = tensor.info()->dimension(0);
237
238     classes_prob.resize(num_classes);
239     index.resize(num_classes);
240
241     std::copy(output_net, output_net + num_classes, classes_prob.begin());
242
243     // Sort results
244     std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
245     std::sort(std::begin(index), std::end(index),
246               [&](size_t a, size_t b)
247     {
248         return classes_prob[a] > classes_prob[b];
249     });
250
251     _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
252                    << std::endl;
253     for(size_t i = 0; i < _top_n; ++i)
254     {
255         _output_stream << std::fixed << std::setprecision(4)
256                        << +classes_prob[index.at(i)]
257                        << " - [id = " << index.at(i) << "]"
258                        << ", " << _labels[index.at(i)] << std::endl;
259     }
260 }
261
262 bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
263 {
264     ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
265     ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
266
267     switch(tensor.info()->data_type())
268     {
269         case DataType::QASYMM8:
270             access_predictions_tensor<uint8_t>(tensor);
271             break;
272         case DataType::F32:
273             access_predictions_tensor<float>(tensor);
274             break;
275         default:
276             ARM_COMPUTE_ERROR("NOT SUPPORTED!");
277     }
278
279     return false;
280 }
281
282 RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
283     : _lower(lower), _upper(upper), _seed(seed)
284 {
285 }
286
287 template <typename T, typename D>
288 void RandomAccessor::fill(ITensor &tensor, D &&distribution)
289 {
290     std::mt19937 gen(_seed);
291
292     if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
293     {
294         for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
295         {
296             const T value                                    = distribution(gen);
297             *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
298         }
299     }
300     else
301     {
302         // If tensor has padding accessing tensor elements through execution window.
303         Window window;
304         window.use_tensor_dimensions(tensor.info()->tensor_shape());
305
306         execute_window_loop(window, [&](const Coordinates & id)
307         {
308             const T value                                     = distribution(gen);
309             *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
310         });
311     }
312 }
313
314 bool RandomAccessor::access_tensor(ITensor &tensor)
315 {
316     switch(tensor.info()->data_type())
317     {
318         case DataType::U8:
319         {
320             std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
321             fill<uint8_t>(tensor, distribution_u8);
322             break;
323         }
324         case DataType::S8:
325         case DataType::QS8:
326         {
327             std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
328             fill<int8_t>(tensor, distribution_s8);
329             break;
330         }
331         case DataType::U16:
332         {
333             std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
334             fill<uint16_t>(tensor, distribution_u16);
335             break;
336         }
337         case DataType::S16:
338         case DataType::QS16:
339         {
340             std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
341             fill<int16_t>(tensor, distribution_s16);
342             break;
343         }
344         case DataType::U32:
345         {
346             std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
347             fill<uint32_t>(tensor, distribution_u32);
348             break;
349         }
350         case DataType::S32:
351         {
352             std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
353             fill<int32_t>(tensor, distribution_s32);
354             break;
355         }
356         case DataType::U64:
357         {
358             std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
359             fill<uint64_t>(tensor, distribution_u64);
360             break;
361         }
362         case DataType::S64:
363         {
364             std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
365             fill<int64_t>(tensor, distribution_s64);
366             break;
367         }
368         case DataType::F16:
369         {
370             std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
371             fill<float>(tensor, distribution_f16);
372             break;
373         }
374         case DataType::F32:
375         {
376             std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
377             fill<float>(tensor, distribution_f32);
378             break;
379         }
380         case DataType::F64:
381         {
382             std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
383             fill<double>(tensor, distribution_f64);
384             break;
385         }
386         default:
387             ARM_COMPUTE_ERROR("NOT SUPPORTED!");
388     }
389     return true;
390 }
391
392 NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
393     : _filename(std::move(filename)), _file_layout(file_layout)
394 {
395 }
396
397 bool NumPyBinLoader::access_tensor(ITensor &tensor)
398 {
399     const TensorShape          tensor_shape = tensor.info()->tensor_shape();
400     std::vector<unsigned long> shape;
401
402     // Open file
403     std::ifstream stream(_filename, std::ios::in | std::ios::binary);
404     ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
405     std::string header = npy::read_header(stream);
406
407     // Parse header
408     bool        fortran_order = false;
409     std::string typestr;
410     npy::parse_header(header, typestr, fortran_order, shape);
411
412     // Check if the typestring matches the given one
413     std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
414     ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
415
416     // Reverse vector in case of non fortran order
417     if(!fortran_order)
418     {
419         std::reverse(shape.begin(), shape.end());
420     }
421
422     // Correct dimensions (Needs to match TensorShape dimension corrections)
423     if(shape.size() != tensor_shape.num_dimensions())
424     {
425         for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
426         {
427             if(shape[i] == 1)
428             {
429                 shape.pop_back();
430             }
431             else
432             {
433                 break;
434             }
435         }
436     }
437
438     bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
439
440     // Validate tensor ranks
441     ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
442
443     // Set permutation parameters if needed
444     TensorShape                    permuted_shape = tensor_shape;
445     arm_compute::PermutationVector perm;
446     if(are_layouts_different)
447     {
448         std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor_shape, tensor.info()->data_layout());
449     }
450
451     // Validate shapes
452     for(size_t i = 0; i < shape.size(); ++i)
453     {
454         ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != shape[i], "Tensor dimensions mismatch");
455     }
456
457     // Validate shapes and copy tensor
458     if(!are_layouts_different || perm.num_dimensions() <= 2)
459     {
460         // Read data
461         if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
462         {
463             // If tensor has no padding read directly from stream.
464             stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
465         }
466         else
467         {
468             // If tensor has padding accessing tensor elements through execution window.
469             Window window;
470             window.use_tensor_dimensions(tensor_shape);
471
472             execute_window_loop(window, [&](const Coordinates & id)
473             {
474                 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
475             });
476         }
477     }
478     else
479     {
480         // If tensor has padding accessing tensor elements through execution window.
481         Window window;
482         window.use_tensor_dimensions(permuted_shape);
483
484         execute_window_loop(window, [&](const Coordinates & id)
485         {
486             Coordinates coords(id);
487             arm_compute::permute(coords, perm);
488             stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(coords)), tensor.info()->element_size());
489         });
490     }
491     return true;
492 }