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