blob: d94dcb0d86ca3b1b75b138ffcc1ad1365805f823 [file] [log] [blame]
Anthony Barbier2a07e182017-08-04 18:20:27 +01001/*
Giorgio Arenaa66eaa22017-12-21 19:50:06 +00002 * Copyright (c) 2017-2018 ARM Limited.
Anthony Barbier2a07e182017-08-04 18:20:27 +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"
hakanardof36ac352018-02-16 10:06:34 +010026
Georgios Pinitascac13b12018-04-27 19:07:19 +010027#include "arm_compute/core/Helpers.h"
28#include "arm_compute/core/Types.h"
hakanardof36ac352018-02-16 10:06:34 +010029#include "arm_compute/runtime/SubTensor.h"
Georgios Pinitas7c3b9242018-06-21 19:01:25 +010030#include "utils/ImageLoader.h"
Anthony Barbier2a07e182017-08-04 18:20:27 +010031#include "utils/Utils.h"
32
Gian Marco44ec2e72017-10-19 14:13:38 +010033#include <iomanip>
Anthony Barbier2a07e182017-08-04 18:20:27 +010034
35using namespace arm_compute::graph_utils;
36
Georgios Pinitascac13b12018-04-27 19:07:19 +010037namespace
38{
39std::pair<arm_compute::TensorShape, arm_compute::PermutationVector> compute_permutation_paramaters(const arm_compute::TensorShape &shape,
40 arm_compute::DataLayout data_layout)
41{
42 // Set permutation parameters if needed
43 arm_compute::TensorShape permuted_shape = shape;
44 arm_compute::PermutationVector perm;
45 // Permute only if num_dimensions greater than 2
46 if(shape.num_dimensions() > 2)
47 {
48 perm = (data_layout == arm_compute::DataLayout::NHWC) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
49
50 arm_compute::PermutationVector perm_shape = (data_layout == arm_compute::DataLayout::NCHW) ? arm_compute::PermutationVector(2U, 0U, 1U) : arm_compute::PermutationVector(1U, 2U, 0U);
51 arm_compute::permute(permuted_shape, perm_shape);
52 }
53
54 return std::make_pair(permuted_shape, perm);
55}
56} // namespace
57
Georgios Pinitas140fdc72018-02-16 11:42:38 +000058void TFPreproccessor::preprocess(ITensor &tensor)
59{
60 Window window;
61 window.use_tensor_dimensions(tensor.info()->tensor_shape());
62
63 execute_window_loop(window, [&](const Coordinates & id)
64 {
65 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id));
66 float res = value / 255.f; // Normalize to [0, 1]
67 res = (res - 0.5f) * 2.f; // Map to [-1, 1]
68 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = res;
69 });
70}
71
72CaffePreproccessor::CaffePreproccessor(std::array<float, 3> mean, bool bgr)
73 : _mean(mean), _bgr(bgr)
74{
75 if(_bgr)
76 {
77 std::swap(_mean[0], _mean[2]);
78 }
79}
80
81void CaffePreproccessor::preprocess(ITensor &tensor)
82{
83 Window window;
84 window.use_tensor_dimensions(tensor.info()->tensor_shape());
85
86 execute_window_loop(window, [&](const Coordinates & id)
87 {
88 const float value = *reinterpret_cast<float *>(tensor.ptr_to_element(id)) - _mean[id.z()];
89 *reinterpret_cast<float *>(tensor.ptr_to_element(id)) = value;
90 });
91}
92
Anthony Barbier2a07e182017-08-04 18:20:27 +010093PPMWriter::PPMWriter(std::string name, unsigned int maximum)
94 : _name(std::move(name)), _iterator(0), _maximum(maximum)
95{
96}
97
98bool PPMWriter::access_tensor(ITensor &tensor)
99{
100 std::stringstream ss;
101 ss << _name << _iterator << ".ppm";
Gian Marco44ec2e72017-10-19 14:13:38 +0100102
103 arm_compute::utils::save_to_ppm(tensor, ss.str());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100104
105 _iterator++;
106 if(_maximum == 0)
107 {
108 return true;
109 }
110 return _iterator < _maximum;
111}
112
113DummyAccessor::DummyAccessor(unsigned int maximum)
114 : _iterator(0), _maximum(maximum)
115{
116}
117
118bool DummyAccessor::access_tensor(ITensor &tensor)
119{
120 ARM_COMPUTE_UNUSED(tensor);
121 bool ret = _maximum == 0 || _iterator < _maximum;
122 if(_iterator == _maximum)
123 {
124 _iterator = 0;
125 }
126 else
127 {
128 _iterator++;
129 }
130 return ret;
131}
132
Isabella Gottardi88d5b222018-04-06 12:24:55 +0100133NumPyAccessor::NumPyAccessor(std::string npy_path, TensorShape shape, DataType data_type, std::ostream &output_stream)
134 : _npy_tensor(), _filename(std::move(npy_path)), _output_stream(output_stream)
135{
136 NumPyBinLoader loader(_filename);
137
138 TensorInfo info(shape, 1, data_type);
139 _npy_tensor.allocator()->init(info);
140 _npy_tensor.allocator()->allocate();
141
142 loader.access_tensor(_npy_tensor);
143}
144
145template <typename T>
146void NumPyAccessor::access_numpy_tensor(ITensor &tensor)
147{
148 const int num_elements = tensor.info()->total_size();
149 int num_mismatches = utils::compare_tensor<T>(tensor, _npy_tensor);
150 float percentage_mismatches = static_cast<float>(num_mismatches) / num_elements;
151
152 _output_stream << "Results: " << 100.f - (percentage_mismatches * 100) << " % matches with the provided output[" << _filename << "]." << std::endl;
153}
154
155bool NumPyAccessor::access_tensor(ITensor &tensor)
156{
157 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32);
158 ARM_COMPUTE_ERROR_ON(_npy_tensor.info()->dimension(0) != tensor.info()->dimension(0));
159
160 switch(tensor.info()->data_type())
161 {
162 case DataType::F32:
163 access_numpy_tensor<float>(tensor);
164 break;
165 default:
166 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
167 }
168
169 return false;
170}
171
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000172PPMAccessor::PPMAccessor(std::string ppm_path, bool bgr, std::unique_ptr<IPreprocessor> preprocessor)
173 : _ppm_path(std::move(ppm_path)), _bgr(bgr), _preprocessor(std::move(preprocessor))
Gian Marco44ec2e72017-10-19 14:13:38 +0100174{
175}
176
177bool PPMAccessor::access_tensor(ITensor &tensor)
178{
179 utils::PPMLoader ppm;
Gian Marco44ec2e72017-10-19 14:13:38 +0100180
181 // Open PPM file
182 ppm.open(_ppm_path);
183
Georgios Pinitascac13b12018-04-27 19:07:19 +0100184 // Get permutated shape and permutation parameters
185 TensorShape permuted_shape = tensor.info()->tensor_shape();
186 arm_compute::PermutationVector perm;
187 if(tensor.info()->data_layout() != DataLayout::NCHW)
188 {
189 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor.info()->tensor_shape(), tensor.info()->data_layout());
190 }
191 ARM_COMPUTE_ERROR_ON_MSG(ppm.width() != permuted_shape.x() || ppm.height() != permuted_shape.y(),
192 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].", ppm.width(), ppm.height(), permuted_shape.x(), permuted_shape.y());
Isabella Gottardia4c61882017-11-03 12:11:55 +0000193
Gian Marco44ec2e72017-10-19 14:13:38 +0100194 // Fill the tensor with the PPM content (BGR)
195 ppm.fill_planar_tensor(tensor, _bgr);
196
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000197 // Preprocess tensor
198 if(_preprocessor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100199 {
Georgios Pinitas140fdc72018-02-16 11:42:38 +0000200 _preprocessor->preprocess(tensor);
201 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100202
203 return true;
204}
205
Georgios Pinitas7c3b9242018-06-21 19:01:25 +0100206ValidationInputAccessor::ValidationInputAccessor(const std::string &image_list,
207 std::string images_path,
208 bool bgr,
209 unsigned int start,
210 unsigned int end)
211 : _path(std::move(images_path)), _images(), _bgr(bgr), _offset(0)
212{
213 ARM_COMPUTE_ERROR_ON_MSG(start > end, "Invalid validation range!");
214
215 std::ifstream ifs;
216 try
217 {
218 ifs.exceptions(std::ifstream::badbit);
219 ifs.open(image_list, std::ios::in | std::ios::binary);
220
221 // Parse image names
222 unsigned int counter = 0;
223 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
224 {
225 // Add image to process if withing range
226 if(counter >= start)
227 {
228 std::stringstream linestream(line);
229 std::string image_name;
230
231 linestream >> image_name;
232 _images.emplace_back(std::move(image_name));
233 }
234 }
235 }
236 catch(const std::ifstream::failure &e)
237 {
238 ARM_COMPUTE_ERROR("Accessing %s: %s", image_list.c_str(), e.what());
239 }
240}
241
242bool ValidationInputAccessor::access_tensor(arm_compute::ITensor &tensor)
243{
244 bool ret = _offset < _images.size();
245 if(ret)
246 {
247 utils::JPEGLoader jpeg;
248
249 // Open JPEG file
250 jpeg.open(_path + _images[_offset++]);
251
252 // Get permutated shape and permutation parameters
253 TensorShape permuted_shape = tensor.info()->tensor_shape();
254 arm_compute::PermutationVector perm;
255 if(tensor.info()->data_layout() != DataLayout::NCHW)
256 {
257 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor.info()->tensor_shape(),
258 tensor.info()->data_layout());
259 }
260 ARM_COMPUTE_ERROR_ON_MSG(jpeg.width() != permuted_shape.x() || jpeg.height() != permuted_shape.y(),
261 "Failed to load image file: dimensions [%d,%d] not correct, expected [%d,%d].",
262 jpeg.width(), jpeg.height(), permuted_shape.x(), permuted_shape.y());
263
264 // Fill the tensor with the PPM content (BGR)
265 jpeg.fill_planar_tensor(tensor, _bgr);
266 }
267
268 return ret;
269}
270
Georgios Pinitas7908de72018-06-27 12:34:20 +0100271ValidationOutputAccessor::ValidationOutputAccessor(const std::string &image_list,
272 size_t top_n,
273 std::ostream &output_stream,
274 unsigned int start,
275 unsigned int end)
276 : _results(), _output_stream(output_stream), _top_n(top_n), _offset(0), _positive_samples(0)
277{
278 ARM_COMPUTE_ERROR_ON_MSG(start > end, "Invalid validation range!");
279 ARM_COMPUTE_ERROR_ON(top_n == 0);
280
281 std::ifstream ifs;
282 try
283 {
284 ifs.exceptions(std::ifstream::badbit);
285 ifs.open(image_list, std::ios::in | std::ios::binary);
286
287 // Parse image correctly classified labels
288 unsigned int counter = 0;
289 for(std::string line; !std::getline(ifs, line).fail() && counter <= end; ++counter)
290 {
291 // Add label if within range
292 if(counter >= start)
293 {
294 std::stringstream linestream(line);
295 std::string image_name;
296 int result;
297
298 linestream >> image_name >> result;
299 _results.emplace_back(result);
300 }
301 }
302 }
303 catch(const std::ifstream::failure &e)
304 {
305 ARM_COMPUTE_ERROR("Accessing %s: %s", image_list.c_str(), e.what());
306 }
307}
308
309void ValidationOutputAccessor::reset()
310{
311 _offset = 0;
312 _positive_samples = 0;
313}
314
315bool ValidationOutputAccessor::access_tensor(arm_compute::ITensor &tensor)
316{
317 if(_offset < _results.size())
318 {
319 // Get results
320 std::vector<size_t> tensor_results;
321 switch(tensor.info()->data_type())
322 {
323 case DataType::QASYMM8:
324 tensor_results = access_predictions_tensor<uint8_t>(tensor);
325 break;
326 case DataType::F32:
327 tensor_results = access_predictions_tensor<float>(tensor);
328 break;
329 default:
330 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
331 }
332
333 // Check if tensor results are within top-n accuracy
334 size_t correct_label = _results[_offset++];
335 auto is_valid_label = [&](size_t label)
336 {
337 return label == correct_label;
338 };
339
340 if(std::any_of(std::begin(tensor_results), std::begin(tensor_results) + _top_n - 1, is_valid_label))
341 {
342 ++_positive_samples;
343 }
344 }
345
346 // Report top_n accuracy
347 bool ret = _offset >= _results.size();
348 if(ret)
349 {
350 size_t total_samples = _results.size();
351 size_t negative_samples = total_samples - _positive_samples;
352 float accuracy = _positive_samples / static_cast<float>(total_samples);
353
354 _output_stream << "----------Top " << _top_n << " accuracy ----------" << std::endl
355 << std::endl;
356 _output_stream << "Positive samples : " << _positive_samples << std::endl;
357 _output_stream << "Negative samples : " << negative_samples << std::endl;
358 _output_stream << "Accuracy : " << accuracy << std::endl;
359 }
360
361 return ret;
362}
363
364template <typename T>
365std::vector<size_t> ValidationOutputAccessor::access_predictions_tensor(arm_compute::ITensor &tensor)
366{
367 // Get the predicted class
368 std::vector<size_t> index;
369
370 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
371 const size_t num_classes = tensor.info()->dimension(0);
372
373 index.resize(num_classes);
374
375 // Sort results
376 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
377 std::sort(std::begin(index), std::end(index),
378 [&](size_t a, size_t b)
379 {
380 return output_net[a] > output_net[b];
381 });
382
383 return index;
384}
385
Gian Marco44ec2e72017-10-19 14:13:38 +0100386TopNPredictionsAccessor::TopNPredictionsAccessor(const std::string &labels_path, size_t top_n, std::ostream &output_stream)
387 : _labels(), _output_stream(output_stream), _top_n(top_n)
388{
389 _labels.clear();
390
391 std::ifstream ifs;
392
393 try
394 {
395 ifs.exceptions(std::ifstream::badbit);
396 ifs.open(labels_path, std::ios::in | std::ios::binary);
397
398 for(std::string line; !std::getline(ifs, line).fail();)
399 {
400 _labels.emplace_back(line);
401 }
402 }
403 catch(const std::ifstream::failure &e)
404 {
405 ARM_COMPUTE_ERROR("Accessing %s: %s", labels_path.c_str(), e.what());
406 }
407}
408
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000409template <typename T>
410void TopNPredictionsAccessor::access_predictions_tensor(ITensor &tensor)
Gian Marco44ec2e72017-10-19 14:13:38 +0100411{
Gian Marco44ec2e72017-10-19 14:13:38 +0100412 // Get the predicted class
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000413 std::vector<T> classes_prob;
Gian Marco44ec2e72017-10-19 14:13:38 +0100414 std::vector<size_t> index;
415
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000416 const auto output_net = reinterpret_cast<T *>(tensor.buffer() + tensor.info()->offset_first_element_in_bytes());
Gian Marco44ec2e72017-10-19 14:13:38 +0100417 const size_t num_classes = tensor.info()->dimension(0);
418
419 classes_prob.resize(num_classes);
420 index.resize(num_classes);
421
422 std::copy(output_net, output_net + num_classes, classes_prob.begin());
423
424 // Sort results
425 std::iota(std::begin(index), std::end(index), static_cast<size_t>(0));
426 std::sort(std::begin(index), std::end(index),
427 [&](size_t a, size_t b)
428 {
429 return classes_prob[a] > classes_prob[b];
430 });
431
432 _output_stream << "---------- Top " << _top_n << " predictions ----------" << std::endl
433 << std::endl;
434 for(size_t i = 0; i < _top_n; ++i)
435 {
436 _output_stream << std::fixed << std::setprecision(4)
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000437 << +classes_prob[index.at(i)]
Gian Marco44ec2e72017-10-19 14:13:38 +0100438 << " - [id = " << index.at(i) << "]"
439 << ", " << _labels[index.at(i)] << std::endl;
440 }
Giorgio Arenaa66eaa22017-12-21 19:50:06 +0000441}
442
443bool TopNPredictionsAccessor::access_tensor(ITensor &tensor)
444{
445 ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(&tensor, 1, DataType::F32, DataType::QASYMM8);
446 ARM_COMPUTE_ERROR_ON(_labels.size() != tensor.info()->dimension(0));
447
448 switch(tensor.info()->data_type())
449 {
450 case DataType::QASYMM8:
451 access_predictions_tensor<uint8_t>(tensor);
452 break;
453 case DataType::F32:
454 access_predictions_tensor<float>(tensor);
455 break;
456 default:
457 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
458 }
Gian Marco44ec2e72017-10-19 14:13:38 +0100459
460 return false;
461}
462
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100463RandomAccessor::RandomAccessor(PixelValue lower, PixelValue upper, std::random_device::result_type seed)
464 : _lower(lower), _upper(upper), _seed(seed)
465{
466}
467
468template <typename T, typename D>
469void RandomAccessor::fill(ITensor &tensor, D &&distribution)
470{
471 std::mt19937 gen(_seed);
472
hakanardof36ac352018-02-16 10:06:34 +0100473 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100474 {
475 for(size_t offset = 0; offset < tensor.info()->total_size(); offset += tensor.info()->element_size())
476 {
477 const T value = distribution(gen);
478 *reinterpret_cast<T *>(tensor.buffer() + offset) = value;
479 }
480 }
481 else
482 {
483 // If tensor has padding accessing tensor elements through execution window.
484 Window window;
485 window.use_tensor_dimensions(tensor.info()->tensor_shape());
486
487 execute_window_loop(window, [&](const Coordinates & id)
488 {
489 const T value = distribution(gen);
490 *reinterpret_cast<T *>(tensor.ptr_to_element(id)) = value;
491 });
492 }
493}
494
495bool RandomAccessor::access_tensor(ITensor &tensor)
496{
497 switch(tensor.info()->data_type())
498 {
499 case DataType::U8:
500 {
501 std::uniform_int_distribution<uint8_t> distribution_u8(_lower.get<uint8_t>(), _upper.get<uint8_t>());
502 fill<uint8_t>(tensor, distribution_u8);
503 break;
504 }
505 case DataType::S8:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100506 {
507 std::uniform_int_distribution<int8_t> distribution_s8(_lower.get<int8_t>(), _upper.get<int8_t>());
508 fill<int8_t>(tensor, distribution_s8);
509 break;
510 }
511 case DataType::U16:
512 {
513 std::uniform_int_distribution<uint16_t> distribution_u16(_lower.get<uint16_t>(), _upper.get<uint16_t>());
514 fill<uint16_t>(tensor, distribution_u16);
515 break;
516 }
517 case DataType::S16:
Michalis Spyrou53b405f2017-09-27 15:55:31 +0100518 {
519 std::uniform_int_distribution<int16_t> distribution_s16(_lower.get<int16_t>(), _upper.get<int16_t>());
520 fill<int16_t>(tensor, distribution_s16);
521 break;
522 }
523 case DataType::U32:
524 {
525 std::uniform_int_distribution<uint32_t> distribution_u32(_lower.get<uint32_t>(), _upper.get<uint32_t>());
526 fill<uint32_t>(tensor, distribution_u32);
527 break;
528 }
529 case DataType::S32:
530 {
531 std::uniform_int_distribution<int32_t> distribution_s32(_lower.get<int32_t>(), _upper.get<int32_t>());
532 fill<int32_t>(tensor, distribution_s32);
533 break;
534 }
535 case DataType::U64:
536 {
537 std::uniform_int_distribution<uint64_t> distribution_u64(_lower.get<uint64_t>(), _upper.get<uint64_t>());
538 fill<uint64_t>(tensor, distribution_u64);
539 break;
540 }
541 case DataType::S64:
542 {
543 std::uniform_int_distribution<int64_t> distribution_s64(_lower.get<int64_t>(), _upper.get<int64_t>());
544 fill<int64_t>(tensor, distribution_s64);
545 break;
546 }
547 case DataType::F16:
548 {
549 std::uniform_real_distribution<float> distribution_f16(_lower.get<float>(), _upper.get<float>());
550 fill<float>(tensor, distribution_f16);
551 break;
552 }
553 case DataType::F32:
554 {
555 std::uniform_real_distribution<float> distribution_f32(_lower.get<float>(), _upper.get<float>());
556 fill<float>(tensor, distribution_f32);
557 break;
558 }
559 case DataType::F64:
560 {
561 std::uniform_real_distribution<double> distribution_f64(_lower.get<double>(), _upper.get<double>());
562 fill<double>(tensor, distribution_f64);
563 break;
564 }
565 default:
566 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
567 }
568 return true;
569}
570
Georgios Pinitascac13b12018-04-27 19:07:19 +0100571NumPyBinLoader::NumPyBinLoader(std::string filename, DataLayout file_layout)
572 : _filename(std::move(filename)), _file_layout(file_layout)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100573{
574}
575
576bool NumPyBinLoader::access_tensor(ITensor &tensor)
577{
578 const TensorShape tensor_shape = tensor.info()->tensor_shape();
579 std::vector<unsigned long> shape;
580
581 // Open file
582 std::ifstream stream(_filename, std::ios::in | std::ios::binary);
583 ARM_COMPUTE_ERROR_ON_MSG(!stream.good(), "Failed to load binary data");
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000584 std::string header = npy::read_header(stream);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100585
586 // Parse header
587 bool fortran_order = false;
588 std::string typestr;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000589 npy::parse_header(header, typestr, fortran_order, shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100590
591 // Check if the typestring matches the given one
592 std::string expect_typestr = arm_compute::utils::get_typestring(tensor.info()->data_type());
593 ARM_COMPUTE_ERROR_ON_MSG(typestr != expect_typestr, "Typestrings mismatch");
594
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000595 // Reverse vector in case of non fortran order
596 if(!fortran_order)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100597 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000598 std::reverse(shape.begin(), shape.end());
599 }
600
601 // Correct dimensions (Needs to match TensorShape dimension corrections)
602 if(shape.size() != tensor_shape.num_dimensions())
603 {
604 for(int i = static_cast<int>(shape.size()) - 1; i > 0; --i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100605 {
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000606 if(shape[i] == 1)
607 {
608 shape.pop_back();
609 }
610 else
611 {
612 break;
613 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100614 }
615 }
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000616
Georgios Pinitascac13b12018-04-27 19:07:19 +0100617 bool are_layouts_different = (_file_layout != tensor.info()->data_layout());
618
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000619 // Validate tensor ranks
620 ARM_COMPUTE_ERROR_ON_MSG(shape.size() != tensor_shape.num_dimensions(), "Tensor ranks mismatch");
621
Georgios Pinitascac13b12018-04-27 19:07:19 +0100622 // Set permutation parameters if needed
623 TensorShape permuted_shape = tensor_shape;
624 arm_compute::PermutationVector perm;
625 if(are_layouts_different)
626 {
627 std::tie(permuted_shape, perm) = compute_permutation_paramaters(tensor_shape, tensor.info()->data_layout());
628 }
629
Georgios Pinitas7f530b32018-01-22 11:20:44 +0000630 // Validate shapes
631 for(size_t i = 0; i < shape.size(); ++i)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100632 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100633 ARM_COMPUTE_ERROR_ON_MSG(permuted_shape[i] != shape[i], "Tensor dimensions mismatch");
Anthony Barbier2a07e182017-08-04 18:20:27 +0100634 }
635
Georgios Pinitascac13b12018-04-27 19:07:19 +0100636 // Validate shapes and copy tensor
637 if(!are_layouts_different || perm.num_dimensions() <= 2)
Anthony Barbier2a07e182017-08-04 18:20:27 +0100638 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100639 // Read data
640 if(tensor.info()->padding().empty() && (dynamic_cast<SubTensor *>(&tensor) == nullptr))
641 {
642 // If tensor has no padding read directly from stream.
643 stream.read(reinterpret_cast<char *>(tensor.buffer()), tensor.info()->total_size());
644 }
645 else
646 {
647 // If tensor has padding accessing tensor elements through execution window.
648 Window window;
649 window.use_tensor_dimensions(tensor_shape);
650
651 execute_window_loop(window, [&](const Coordinates & id)
652 {
653 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(id)), tensor.info()->element_size());
654 });
655 }
Anthony Barbier2a07e182017-08-04 18:20:27 +0100656 }
657 else
658 {
659 // If tensor has padding accessing tensor elements through execution window.
660 Window window;
Georgios Pinitascac13b12018-04-27 19:07:19 +0100661 window.use_tensor_dimensions(permuted_shape);
Anthony Barbier2a07e182017-08-04 18:20:27 +0100662
663 execute_window_loop(window, [&](const Coordinates & id)
664 {
Georgios Pinitascac13b12018-04-27 19:07:19 +0100665 Coordinates coords(id);
666 arm_compute::permute(coords, perm);
667 stream.read(reinterpret_cast<char *>(tensor.ptr_to_element(coords)), tensor.info()->element_size());
Anthony Barbier2a07e182017-08-04 18:20:27 +0100668 });
669 }
670 return true;
Anthony Barbier87f21cd2017-11-10 16:27:32 +0000671}