forked from Samsung/ONE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_loader.h
1735 lines (1562 loc) · 63.4 KB
/
base_loader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __BASE_LOADER_BASE_LOADER_H__
#define __BASE_LOADER_BASE_LOADER_H__
#include "ir/Graph.h"
#include "ir/Shape.h"
#include "ir/Operations.Include.h"
#include "flatbuffers/flexbuffers.h"
#include <map>
#include <memory>
#include <fstream>
#include <limits>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <util/logging.h>
namespace onert
{
namespace base_loader
{
template <typename LoaderDomain> class BaseLoader
{
protected:
using Verifier = typename LoaderDomain::Verifier;
using ActivationFunctionType = typename LoaderDomain::ActivationFunctionType;
using Buffer = typename LoaderDomain::Buffer;
using BuiltinOperator = typename LoaderDomain::BuiltinOperator;
using CustomOptionsFormat = typename LoaderDomain::CustomOptionsFormat;
using Model = typename LoaderDomain::Model;
using Operator = typename LoaderDomain::Operator;
using Padding = typename LoaderDomain::Padding;
using Pool2DOptions = typename LoaderDomain::Pool2DOptions;
using SubGraph = typename LoaderDomain::SubGraph;
using Tensor = typename LoaderDomain::Tensor;
using TensorType = typename LoaderDomain::TensorType;
using DimensionType = typename LoaderDomain::DimensionType;
using SparseIndexVector = typename LoaderDomain::SparseIndexVector;
protected:
bool isOptionalInputTensor(std::int32_t idx) { return idx == -1; }
virtual bool allowOptionalInputTensor(BuiltinOperator) = 0;
public:
/**
* @brief Construct a new Loader object
*
* @param model reference to model
*/
explicit BaseLoader(std::unique_ptr<ir::Model> &model)
: _base{nullptr}, _pagesize(getpagesize()), _fd(-1), _model(model), _domain_model{nullptr}
{
_use_mmaped_data = util::getConfigBool(util::config::USE_MMAPED_DATA);
}
/**
* @brief Load a model from file
*
* @param file_path
*/
void loadFromFile(const std::string &file_path);
/**
* @brief Load a model from a buffer
*
* @param buffer buffer pointer
* @param size buffer size
*/
void loadFromBuffer(uint8_t *buffer, size_t size);
protected:
~BaseLoader() = default;
void loadModel();
// Helper functions
ir::Activation convertActivation(ActivationFunctionType type);
ir::DataType tensorTypeToDataType(TensorType type);
ir::OperandIndex tensorIdxToOperandIdx(int32_t tensorIdx);
flexbuffers::Map getCustomOpAttrMap(const Operator *op);
// Create operands form tflite::Tensor
ir::OperandIndex loadOperand(const Tensor *tensor, ir::Graph &subg);
void loadQuantization(const Tensor *tensor, ir::TypeInfo &typeInfo);
void loadSparsity(const Tensor *tensor, ir::TypeInfo &typeInfo);
void loadOperationIO(const Operator *op, ir::OperandIndexSequence &inputs,
ir::OperandIndexSequence &outputs);
// Create operations from Operator
void loadOperation(const Operator *op, ir::Graph &subg);
// Load Strides and Paddings from options to param
template <typename Param, typename OptionsType>
void loadStridesAndPaddings(Param ¶m, const OptionsType *options);
// Load Pool2D param
template <typename Param> void loadPool2DOptions(Param ¶m, const Pool2DOptions *options);
// Get BuiltinOperator
BuiltinOperator getBuiltinOperator(const Operator *op)
{
auto const builtin_opcode = _domain_model->operator_codes()->Get(op->opcode_index());
auto builtin_op = builtin_opcode->builtin_code();
if (builtin_op < BuiltinOperator::BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES)
builtin_op = static_cast<BuiltinOperator>(builtin_opcode->deprecated_builtin_code());
return builtin_op;
}
private:
virtual std::unique_ptr<ir::Graph> loadSubgraph(const SubGraph *subg) = 0;
// Operations
template <typename OpIR, typename... Args>
const OpIR *loadOperationTo(const Operator *op, ir::Graph &subg, Args &&... args);
void loadAddV2(const Operator *op, ir::Graph &subg);
void loadArgMinMax(const Operator *op, ir::Graph &subg, bool is_argmax);
void loadBatchMatMul(const Operator *op, ir::Graph &subg);
void loadBinaryArithmetic(const Operator *op, ir::Graph &subg,
ir::operation::BinaryArithmetic::ArithmeticType op_type);
void loadComparison(const Operator *op, ir::Graph &subg);
void loadConcatenation(const Operator *op, ir::Graph &subg);
void loadConv2D(const Operator *op, ir::Graph &subg);
void loadCustom(const Operator *op, ir::Graph &subg);
void loadDepthToSpace(const Operator *op, ir::Graph &subg);
void loadDepthwiseConv2D(const Operator *op, ir::Graph &subg);
void loadEinsum(const Operator *op, ir::Graph &subg);
void loadElementwiseActivation(const Operator *op, ir::Graph &subg,
ir::operation::ElementwiseActivation::Type op_type,
float alpha = 0.f, float beta = 0.f);
void loadElementwiseBinary(const Operator *op, ir::Graph &subg,
ir::operation::ElementwiseBinary::ElementwiseBinaryType op_type);
void loadElementwiseUnary(const Operator *op, ir::Graph &subg,
ir::operation::ElementwiseUnary::Type op_type);
void loadFC(const Operator *op, ir::Graph &subg);
void loadFusedBatchNorm(const Operator *op, ir::Graph &subg);
void loadGather(const Operator *op, ir::Graph &subg);
void loadIf(const Operator *op, ir::Graph &subg);
void loadLeakyRelu(const Operator *op, ir::Graph &subg);
void loadLogSoftmax(const Operator *op, ir::Graph &subg);
void loadDetectionPostProcess(const Operator *op, ir::Graph &subg);
void loadOneHot(const Operator *op, ir::Graph &subg);
void loadPack(const Operator *op, ir::Graph &subg);
void loadPool2D(const Operator *op, ir::Graph &subg, ir::operation::Pool2D::PoolType op_type);
void loadReduce(const Operator *op, ir::Graph &subg,
ir::operation::Reduce::ReduceType reduce_type);
void loadReduceAll(const Operator *op, ir::Graph &subg);
void loadReshape(const Operator *op, ir::Graph &subg);
void loadResizeBilinear(const Operator *op, ir::Graph &subg);
void loadResizeNearestNeighbor(const Operator *op, ir::Graph &subg);
void loadSoftmax(const Operator *op, ir::Graph &subg);
void loadSpaceToDepth(const Operator *op, ir::Graph &subg);
void loadSplit(const Operator *op, ir::Graph &subg);
void loadSplitV(const Operator *op, ir::Graph &subg);
void loadSqueeze(const Operator *op, ir::Graph &subg);
void loadStridedSlice(const Operator *op, ir::Graph &subg);
void loadTransposeConv(const Operator *op, ir::Graph &subg);
void loadUnidirectionalSequenceLSTM(const Operator *op, ir::Graph &subg);
void loadUnpack(const Operator *op, ir::Graph &subg);
void loadWhile(const Operator *op, ir::Graph &subg);
void verifySubgraphIndex(int subg_index)
{
const auto num_subgraphs = _domain_model->subgraphs()->size();
if (subg_index < 0 || subg_index >= static_cast<int32_t>(num_subgraphs))
throw std::runtime_error{std::string{"Invalid subgraph index - "} +
std::to_string(subg_index)};
}
protected:
// Base address for mapped region for loading (if needed)
uint8_t *_base;
// Memory page size
int32_t _pagesize;
// loaded file description
int _fd;
// Reference to ir::model (to be loaded from _domain_model)
std::unique_ptr<ir::Model> &_model;
const Model *_domain_model;
// Maps Tensor indices to onert Operands.
std::vector<ir::OperandIndex> _tensor_to_operand;
std::unordered_map<ir::OperandIndex, std::string> _tensor_names;
// Verifier
std::unique_ptr<Verifier> _verifier;
// Boolean flag to use MMAPED_DATA
bool _use_mmaped_data = false;
std::unordered_map<uint32_t /* Buffer Index in circle file */, std::shared_ptr<ir::Data>>
_buf_to_data;
};
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::BaseLoader::loadFromFile(const std::string &file_path)
{
_fd = open(file_path.c_str(), O_RDONLY);
if (_fd < 0)
{
throw std::runtime_error("Failed to open file " + file_path);
}
struct stat file_stat;
if (fstat(_fd, &file_stat) != 0)
{
throw std::runtime_error("Fstat failed or file " + file_path + " is not a regular file");
}
int size = file_stat.st_size;
// Map model file into memory region
_base = static_cast<uint8_t *>(mmap(NULL, size, PROT_READ, MAP_PRIVATE, _fd, 0));
if (_base == MAP_FAILED)
{
close(_fd);
throw std::runtime_error("mmap failed - " + std::string(strerror(errno)));
}
_verifier = std::make_unique<Verifier>(reinterpret_cast<const std::uint8_t *>(_base), size);
loadModel();
munmap(_base, size);
close(_fd);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::BaseLoader::loadFromBuffer(uint8_t *buffer, size_t size)
{
_base = buffer;
_verifier = std::make_unique<Verifier>(reinterpret_cast<const std::uint8_t *>(_base), size);
loadModel();
}
template <typename LoaderDomain>
ir::Activation
BaseLoader<LoaderDomain>::BaseLoader::convertActivation(const ActivationFunctionType type)
{
switch (type)
{
case ActivationFunctionType::ActivationFunctionType_NONE:
return ir::Activation::NONE;
case ActivationFunctionType::ActivationFunctionType_RELU:
return ir::Activation::RELU;
case ActivationFunctionType::ActivationFunctionType_RELU_N1_TO_1:
return ir::Activation::RELU1;
case ActivationFunctionType::ActivationFunctionType_RELU6:
return ir::Activation::RELU6;
case ActivationFunctionType::ActivationFunctionType_TANH:
return ir::Activation::TANH;
default:
throw std::runtime_error(std::string("Unsupported or invalid activation type: ") +
std::to_string(static_cast<int>(type)));
}
}
template <typename LoaderDomain>
ir::DataType BaseLoader<LoaderDomain>::BaseLoader::tensorTypeToDataType(const TensorType type)
{
switch (type)
{
case TensorType::TensorType_FLOAT32:
return ir::DataType::FLOAT32;
case TensorType::TensorType_FLOAT16:
return ir::DataType::FLOAT16;
case TensorType::TensorType_INT32:
return ir::DataType::INT32;
case TensorType::TensorType_UINT8:
return ir::DataType::QUANT_UINT8_ASYMM;
case TensorType::TensorType_INT64:
return ir::DataType::INT64;
// case TensorType::TensorType_STRING:
case TensorType::TensorType_BOOL:
return ir::DataType::BOOL8;
case TensorType::TensorType_INT16:
return ir::DataType::QUANT_INT16_ASYMM;
// case TensorType::TensorType_COMPLEX64
case TensorType::TensorType_INT8:
return ir::DataType::QUANT_INT8_ASYMM;
// case TensorType::TensorType_FLOAT64
case TensorType::TensorType_UINT32:
return ir::DataType::UINT32;
default:
throw std::runtime_error(
std::string("Unsupported tensor type: ").append(EnumNameTensorType(type)));
}
}
template <typename LoaderDomain>
ir::OperandIndex BaseLoader<LoaderDomain>::BaseLoader::tensorIdxToOperandIdx(int32_t tensorIdx)
{
return isOptionalInputTensor(tensorIdx) ? ir::OperandIndex() : _tensor_to_operand[tensorIdx];
}
template <typename LoaderDomain>
flexbuffers::Map BaseLoader<LoaderDomain>::BaseLoader::getCustomOpAttrMap(const Operator *op)
{
size_t custom_op_data_size = op->custom_options()->size();
auto custom_op_data = op->custom_options()->Data();
auto data_root = flexbuffers::GetRoot(custom_op_data, custom_op_data_size);
return data_root.AsMap();
}
/* Copy is copied from tensorflow lite */
template <typename T> bool Copy(const T *data_ptr, std::vector<uint16_t> &arr)
{
if (data_ptr->values() == nullptr)
{
return false;
}
int size = data_ptr->values()->size();
arr.reserve(size);
for (int i = 0; i < size; i++)
{
arr.emplace_back(static_cast<uint16_t>(data_ptr->values()->Get(i)));
}
return true;
}
template <typename LoaderDomain>
ir::OperandIndex BaseLoader<LoaderDomain>::loadOperand(const Tensor *tensor, ir::Graph &subg)
{
ir::Shape shape;
// Shape
const auto *tensor_shape = tensor->shape();
if (tensor_shape != nullptr)
{
for (const auto &dim : *tensor_shape)
{
shape.append(dim);
}
}
// Note for tensor->shape_signature()
// We don't handle shape signature
// How we handle:
// If shape_signature[k] == -1, we will use tensor->shape()[k] == 1
// If app wants to change the input shape, call nnfw_apply_input_tensorinfo() can
// be used.
// TypeInfo
ir::TypeInfo type_info(tensorTypeToDataType(tensor->type()));
loadQuantization(tensor, type_info);
loadSparsity(tensor, type_info);
// Create operand
const auto operand_index = subg.addOperand(shape, type_info);
// Constant tensors are indicated by non-empty data.
const auto *data = _domain_model->buffers()->Get(tensor->buffer())->data();
if (data != nullptr)
{
using std::ptrdiff_t;
std::shared_ptr<ir::Data> data_obj;
if (_fd == -1) // Model is from memory
{
data_obj = std::make_shared<ir::ExternalData>(data->data(), data->size());
}
else // Model is loaded(mmap'd) from a file
{
size_t data_size = data->size();
ptrdiff_t unaligned_offset_start = data->data() - _base;
ptrdiff_t offset_end = unaligned_offset_start + data_size;
// Calculated aligned offset from base address of mapped region
// munmap accepts memory address which is a multiple of the pagesize
ptrdiff_t aligned_offset_start = (unaligned_offset_start / _pagesize) * _pagesize;
size_t mmap_size = offset_end - aligned_offset_start;
uint32_t buf_idx = tensor->buffer();
auto buffer_found = _buf_to_data.find(buf_idx);
if (buffer_found != _buf_to_data.end())
{
// Another tensor points this buffer and its matching Data(either CachedData or MMapedData)
// was already created. Let's reuse the Data
data_obj = buffer_found->second;
}
else if (_use_mmaped_data)
{
data_obj = std::make_shared<ir::MMapedData>(_fd, aligned_offset_start, mmap_size,
unaligned_offset_start, data_size);
_buf_to_data[buf_idx] = data_obj;
}
else
{
size_t offset = unaligned_offset_start - aligned_offset_start;
uint8_t *mmap_base = static_cast<uint8_t *>(
mmap(NULL, mmap_size, PROT_READ, MAP_PRIVATE, _fd, aligned_offset_start));
data_obj = std::make_shared<ir::CachedData>(mmap_base + offset, data_size);
_buf_to_data[buf_idx] = data_obj;
munmap(mmap_base, mmap_size);
}
}
subg.setOperandValue(operand_index, std::move(data_obj));
}
_tensor_names.emplace(operand_index, tensor->name()->str());
// Variable
if (tensor->is_variable())
{
if (data != nullptr)
throw std::runtime_error("Variable tensor with buffer is not supported!");
subg.operands().at(operand_index).info().setAsVariable();
}
return operand_index;
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadQuantization(const Tensor *tensor, ir::TypeInfo &typeInfo)
{
auto q_params = tensor->quantization();
if (q_params == nullptr || q_params->scale() == nullptr || q_params->scale()->size() == 0)
{
typeInfo.quantization(0., 0);
return;
}
if (q_params->zero_point() == nullptr)
{
throw std::runtime_error("Quantization params: scale is not null, but zero_point is null.");
}
const size_t num_scales = q_params->scale()->size();
if (num_scales != q_params->zero_point()->size())
{
throw std::runtime_error("Quantization params: scale size != zero_point size");
}
std::vector<float> scales;
std::vector<int32_t> zero_points;
scales.resize(num_scales);
zero_points.resize(num_scales);
for (size_t i = 0; i < num_scales; ++i)
{
scales[i] = q_params->scale()->Get(i);
// zero_point is defined as long (i64) in schema while TypeInfo's zero_point is int32_t.
// int64_t is used instead of long because long is 4 byte in most 32bit architecture.
int64_t zero_point = q_params->zero_point()->Get(i);
if (zero_point < std::numeric_limits<int32_t>::min() ||
zero_point > std::numeric_limits<int32_t>::max())
throw std::runtime_error("Zero_point is out of int32 range.");
zero_points[i] = static_cast<int32_t>(zero_point);
}
auto details = q_params->details_as_CustomQuantization();
if (details != nullptr)
throw std::runtime_error("Custom Quantization is not supported");
typeInfo.quantization(std::move(scales), std::move(zero_points));
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadSparsity(const Tensor *tensor, ir::TypeInfo &typeInfo)
{
auto src_sparsity = tensor->sparsity();
if (src_sparsity != nullptr)
{
std::vector<uint16_t> w1_segments;
std::vector<uint16_t> w1_indices;
// check traversal_order
if (src_sparsity->traversal_order())
{
const int traversal_order_size = src_sparsity->traversal_order()->size();
for (int i = 0; i < traversal_order_size; ++i)
{
if (i != src_sparsity->traversal_order()->Get(i))
throw std::runtime_error("traversal_order [0, 1, ..., n-1] is only supported.");
}
}
// check block_map
int block_rank = 0;
if (src_sparsity->block_map())
{
block_rank = src_sparsity->block_map()->size();
for (int i = 0; i < block_rank; ++i)
{
if (i != src_sparsity->block_map()->Get(i))
throw std::runtime_error("block_map [0, 1, ..., n-1] is only supported.");
}
}
// load metadata
const auto dim_metadata_size = src_sparsity->dim_metadata()->size();
const auto dense_rank = tensor->shape() ? tensor->shape()->size() : 0;
if (dense_rank + block_rank != dim_metadata_size)
throw std::runtime_error("sparsity dim_metadata length is wrong.");
bool random_sparsity = dim_metadata_size == 2 && block_rank == 0;
bool block2D_sparsity = dim_metadata_size == 4 && block_rank == 2;
if (dim_metadata_size != !random_sparsity && !block2D_sparsity)
throw std::runtime_error(
"sparsity is supported only for 2D tensor with random or 16x1 block sparsity.");
const auto *src_metadata = src_sparsity->dim_metadata()->Get(0);
if (src_metadata->format() != DimensionType::DimensionType_DENSE)
throw std::runtime_error("sparse tensor dim[0] is not DENSE");
src_metadata = src_sparsity->dim_metadata()->Get(1);
if (src_metadata->format() != DimensionType::DimensionType_SPARSE_CSR)
throw std::runtime_error("sparse tensor dim[0] is not SPARSE_CSR");
auto ParseSparseIndexVector = [src_metadata, &w1_segments, &w1_indices]() {
if (src_metadata->array_segments() == nullptr || src_metadata->array_indices() == nullptr)
return false;
bool status = true;
/* `onert` inernally uses uint16 type regardless of the value of
the array_segments_type and array_indices_type */
switch (src_metadata->array_segments_type())
{
case SparseIndexVector::SparseIndexVector_Int32Vector:
throw std::runtime_error("sparse tensor with int32 segment type is not supported");
case SparseIndexVector::SparseIndexVector_Uint16Vector:
status = Copy(src_metadata->array_segments_as_Uint16Vector(), w1_segments);
break;
case SparseIndexVector::SparseIndexVector_Uint8Vector:
status = Copy(src_metadata->array_segments_as_Uint8Vector(), w1_segments);
break;
default:
return false;
}
if (status != true)
return false;
switch (src_metadata->array_indices_type())
{
case SparseIndexVector::SparseIndexVector_Int32Vector:
throw std::runtime_error("sparse tensor with int32 indices type is not supported");
case SparseIndexVector::SparseIndexVector_Uint16Vector:
return Copy(src_metadata->array_indices_as_Uint16Vector(), w1_indices);
case SparseIndexVector::SparseIndexVector_Uint8Vector:
return Copy(src_metadata->array_indices_as_Uint8Vector(), w1_indices);
default:
break;
}
return false;
};
if (ParseSparseIndexVector() == false)
throw std::runtime_error("Error during parsing sparsity index information");
// Get block size
std::vector<int32_t> block_size;
for (int i = 0; i < block_rank; ++i)
{
auto block_metadata = src_sparsity->dim_metadata()->Get(dense_rank + i);
if (block_metadata->format() != DimensionType::DimensionType_DENSE)
throw std::runtime_error("block dimension must be DENSE.");
block_size.push_back(block_metadata->dense_size());
}
typeInfo.sparsity(std::make_shared<ir::Sparsity>(std::move(w1_segments), std::move(w1_indices),
std::move(block_size)));
}
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadOperationIO(const Operator *op, ir::OperandIndexSequence &inputs,
ir::OperandIndexSequence &outputs)
{
for (const std::int32_t idx : *op->inputs())
{
// Optional tensors are not supported yet except for FULLY_CONNECTED and BCQ_FULLY_CONNECTED
auto check_optional_input = [&]() {
auto builtin_code = getBuiltinOperator(op);
if (isOptionalInputTensor(idx) && !allowOptionalInputTensor(builtin_code))
throw std::runtime_error(
std::string("loader doesn't support optional input tensor yet for ")
.append(EnumNameBuiltinOperator(builtin_code)));
};
check_optional_input();
inputs.append(tensorIdxToOperandIdx(idx));
}
for (const std::int32_t idx : *op->outputs())
{
outputs.append(tensorIdxToOperandIdx(idx));
}
}
template <typename LoaderDomain>
template <typename Param, typename OptionsType>
void BaseLoader<LoaderDomain>::loadStridesAndPaddings(Param ¶m, const OptionsType *options)
{
// Strides
param.stride.vertical = options->stride_h();
param.stride.horizontal = options->stride_w();
// Paddings
switch (options->padding())
{
case Padding::Padding_SAME:
param.padding.type = ir::PaddingType::SAME;
break;
case Padding::Padding_VALID:
param.padding.type = ir::PaddingType::VALID;
break;
default:
throw std::runtime_error{"Invalid padding type"};
}
// param paddings indexes unused
}
template <typename LoaderDomain>
template <typename Param>
void BaseLoader<LoaderDomain>::loadPool2DOptions(Param ¶m, const Pool2DOptions *options)
{
// Strides and Paddings
if (options->stride_h() <= 0 || options->stride_w() <= 0)
throw std::runtime_error{"Invalid stride vertical or horizontal - both must be bigger than 0"};
loadStridesAndPaddings(param, options);
// Filter width and height
// Strides
if (options->filter_width() <= 0 || options->filter_height() <= 0)
throw std::runtime_error{"Invalid filter width or height - both must be bigger than 0"};
param.kw = options->filter_width();
param.kh = options->filter_height();
// Activation
param.activation = convertActivation(options->fused_activation_function());
}
template <typename LoaderDomain>
template <typename OpIR, typename... Args>
const OpIR *BaseLoader<LoaderDomain>::loadOperationTo(const Operator *op, ir::Graph &subg,
Args &&... args)
{
static_assert(sizeof...(args) <= 1, "You can't have more than 1 arguments!");
ir::OperandIndexSequence inputs;
ir::OperandIndexSequence outputs;
loadOperationIO(op, inputs, outputs);
std::unique_ptr<OpIR> new_op(new OpIR(inputs, outputs, std::forward<Args>(args)...));
auto ret = new_op.get();
subg.addOperation(std::move(new_op));
return ret;
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadConv2D(const Operator *op, ir::Graph &subg)
{
ir::operation::Conv2D::Param param;
const auto *options = op->builtin_options_as_Conv2DOptions();
param.activation = convertActivation(options->fused_activation_function());
loadStridesAndPaddings(param, options);
param.dilation.width_factor = options->dilation_w_factor();
param.dilation.height_factor = options->dilation_h_factor();
const auto conv = loadOperationTo<ir::operation::Conv2D>(op, subg, param);
// TFLite support old hybrid quantization (float input/output, uint8 kernel)
// but it interprets weight type as init8 internally
const auto &input_operand =
subg.operands().at(conv->getInputs().at(ir::operation::Conv2D::INPUT));
auto &weights_operand = subg.operands().at(conv->getInputs().at(ir::operation::Conv2D::KERNEL));
if (input_operand.typeInfo().type() == ir::DataType::FLOAT32 &&
((weights_operand.typeInfo().type() == ir::DataType::QUANT_UINT8_ASYMM) ||
weights_operand.typeInfo().type() == ir::DataType::QUANT_INT8_ASYMM))
{
weights_operand.type(ir::DataType::QUANT_INT8_SYMM);
}
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadDepthwiseConv2D(const Operator *op, ir::Graph &subg)
{
ir::operation::DepthwiseConv2D::Param param;
const auto *options = op->builtin_options_as_DepthwiseConv2DOptions();
param.activation = convertActivation(options->fused_activation_function());
loadStridesAndPaddings(param, options);
param.multiplier = options->depth_multiplier();
// Dilation h/w factor unused
param.dilation.width_factor = options->dilation_w_factor();
param.dilation.height_factor = options->dilation_h_factor();
const auto dconv = loadOperationTo<ir::operation::DepthwiseConv2D>(op, subg, param);
// TFLite does not support old hybrid quantization (float input/output, uint8 kernel)
// for depthwise convolution.
// But for consistency with Conv2D and FC, we interpret weight type as init8 internally
const auto &input_operand =
subg.operands().at(dconv->getInputs().at(ir::operation::DepthwiseConv2D::INPUT));
auto &weights_operand =
subg.operands().at(dconv->getInputs().at(ir::operation::DepthwiseConv2D::KERNEL));
if (input_operand.typeInfo().type() == ir::DataType::FLOAT32 &&
((weights_operand.typeInfo().type() == ir::DataType::QUANT_UINT8_ASYMM) ||
weights_operand.typeInfo().type() == ir::DataType::QUANT_INT8_ASYMM))
{
weights_operand.type(ir::DataType::QUANT_INT8_SYMM);
}
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadTransposeConv(const Operator *op, ir::Graph &subg)
{
ir::operation::TransposeConv::Param param;
const auto *options = op->builtin_options_as_TransposeConvOptions();
loadStridesAndPaddings(param, options);
loadOperationTo<ir::operation::TransposeConv>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadPool2D(const Operator *op, ir::Graph &subg,
ir::operation::Pool2D::PoolType op_type)
{
ir::operation::Pool2D::Param param;
param.op_type = op_type;
const auto *options = op->builtin_options_as_Pool2DOptions();
loadPool2DOptions(param, options);
loadOperationTo<ir::operation::Pool2D>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadReshape(const Operator *op, ir::Graph &subg)
{
ir::operation::Reshape::Param param{};
const auto *options = op->builtin_options_as_ReshapeOptions();
if (options != nullptr)
{
const auto *new_shape = options->new_shape();
if (new_shape)
{
for (uint i = 0; i < new_shape->size(); ++i)
{
param.new_shape.push_back(new_shape->Get(i));
}
}
}
loadOperationTo<ir::operation::Reshape>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadSoftmax(const Operator *op, ir::Graph &subg)
{
ir::operation::Softmax::Param param;
const auto *options = op->builtin_options_as_SoftmaxOptions();
// Beta
param.beta = options->beta();
loadOperationTo<ir::operation::Softmax>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadConcatenation(const Operator *op, ir::Graph &subg)
{
ir::operation::Concat::Param param;
const auto *options = op->builtin_options_as_ConcatenationOptions();
// Axis
param.axis = options->axis();
// activation unused
loadOperationTo<ir::operation::Concat>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadFC(const Operator *op, ir::Graph &subg)
{
ir::operation::FullyConnected::Param param;
const auto *options = op->builtin_options_as_FullyConnectedOptions();
param.activation = convertActivation(options->fused_activation_function());
param.weights_format = static_cast<ir::FullyConnectedWeightsFormat>(options->weights_format());
const auto fc = loadOperationTo<ir::operation::FullyConnected>(op, subg, param);
// TFLite supports old hybrid quantization (float input/output, uint8 kernel)
// but it interprets weight type as init8 internally
const auto &input_operand =
subg.operands().at(fc->getInputs().at(ir::operation::FullyConnected::INPUT));
auto &weights_operand =
subg.operands().at(fc->getInputs().at(ir::operation::FullyConnected::WEIGHT));
if (input_operand.typeInfo().type() == ir::DataType::FLOAT32 &&
((weights_operand.typeInfo().type() == ir::DataType::QUANT_UINT8_ASYMM) ||
weights_operand.typeInfo().type() == ir::DataType::QUANT_INT8_ASYMM))
{
weights_operand.type(ir::DataType::QUANT_INT8_SYMM);
}
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadAddV2(const Operator *op, ir::Graph &subg)
{
ir::operation::BinaryArithmetic::Param param;
param.arithmetic_type = ir::operation::BinaryArithmetic::ArithmeticType::ADD;
if (op->custom_options() == nullptr)
{
param.activation = ir::Activation::NONE;
}
else
{
const auto attr_map = getCustomOpAttrMap(op);
const auto fused_activation_func = static_cast<typename LoaderDomain::ActivationFunctionType>(
attr_map["fused_activation_function"].AsInt8());
param.activation = convertActivation(fused_activation_func);
}
loadOperationTo<ir::operation::BinaryArithmetic>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadDepthToSpace(const Operator *op, ir::Graph &subg)
{
ir::operation::DepthToSpace::Param param;
const auto *options = op->builtin_options_as_DepthToSpaceOptions();
param.block_size = options->block_size();
loadOperationTo<ir::operation::DepthToSpace>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadBinaryArithmetic(
const Operator *op, ir::Graph &subg, ir::operation::BinaryArithmetic::ArithmeticType op_type)
{
ir::operation::BinaryArithmetic::Param param;
param.arithmetic_type = op_type;
switch (op_type)
{
case ir::operation::BinaryArithmetic::ArithmeticType::ADD:
{
const auto *add_options = op->builtin_options_as_AddOptions();
param.activation = convertActivation(add_options->fused_activation_function());
break;
}
case ir::operation::BinaryArithmetic::ArithmeticType::SUB:
{
const auto *sub_options = op->builtin_options_as_SubOptions();
param.activation = convertActivation(sub_options->fused_activation_function());
break;
}
case ir::operation::BinaryArithmetic::ArithmeticType::MUL:
{
const auto *mul_options = op->builtin_options_as_MulOptions();
param.activation = convertActivation(mul_options->fused_activation_function());
break;
}
case ir::operation::BinaryArithmetic::ArithmeticType::DIV:
{
const auto *div_options = op->builtin_options_as_DivOptions();
param.activation = convertActivation(div_options->fused_activation_function());
break;
}
default:
assert(false &&
"The function 'loadBinaryArithmetic' supports only BinaryArithmetic operations");
break;
}
loadOperationTo<ir::operation::BinaryArithmetic>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadPack(const Operator *op, ir::Graph &subg)
{
ir::operation::Pack::Param param;
const auto *options = op->builtin_options_as_PackOptions();
param.num = options->values_count();
param.axis = options->axis();
loadOperationTo<ir::operation::Pack>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadElementwiseActivation(
const Operator *op, ir::Graph &subg, ir::operation::ElementwiseActivation::Type op_type,
float alpha, float beta)
{
ir::operation::ElementwiseActivation::Param param;
param.op_type = op_type;
param.alpha = alpha;
param.beta = beta;
loadOperationTo<ir::operation::ElementwiseActivation>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadResizeBilinear(const Operator *op, ir::Graph &subg)
{
ir::operation::ResizeBilinear::Param param;
param.align_corners = op->builtin_options_as_ResizeBilinearOptions()->align_corners();
param.half_pixel_centers = op->builtin_options_as_ResizeBilinearOptions()->half_pixel_centers();
loadOperationTo<ir::operation::ResizeBilinear>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadResizeNearestNeighbor(const Operator *op, ir::Graph &subg)
{
ir::operation::ResizeNearestNeighbor::Param param;
param.align_corners = op->builtin_options_as_ResizeNearestNeighborOptions()->align_corners();
loadOperationTo<ir::operation::ResizeNearestNeighbor>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadReduce(const Operator *op, ir::Graph &subg,
ir::operation::Reduce::ReduceType reduce_type)
{
ir::operation::Reduce::Param param;
param.reduce_type = reduce_type;
param.keep_dims = op->builtin_options_as_ReducerOptions()->keep_dims();
loadOperationTo<ir::operation::Reduce>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadReduceAll(const Operator *op, ir::Graph &subg)
{
ir::operation::Reduce::Param param;
param.reduce_type = ir::operation::Reduce::ReduceType::ALL;
if (op->custom_options() == nullptr)
{
param.keep_dims = false;
}
else
{
const auto attr_map = getCustomOpAttrMap(op);
param.keep_dims = attr_map["keep_dims"].AsBool();
}
loadOperationTo<ir::operation::Reduce>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadElementwiseBinary(
const Operator *op, ir::Graph &subg,
ir::operation::ElementwiseBinary::ElementwiseBinaryType op_type)
{
ir::operation::ElementwiseBinary::Param param;
param.op_type = op_type;
loadOperationTo<ir::operation::ElementwiseBinary>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadElementwiseUnary(const Operator *op, ir::Graph &subg,
ir::operation::ElementwiseUnary::Type op_type)
{
ir::operation::ElementwiseUnary::Param param;
param.op_type = op_type;
const auto eu = loadOperationTo<ir::operation::ElementwiseUnary>(op, subg, param);
if (op_type == ir::operation::ElementwiseUnary::Type::CAST)
{
auto qasymm8ToUint8 = [](ir::Operand &operand) {
if (operand.typeInfo().type() == ir::DataType::QUANT_UINT8_ASYMM)
{
operand.type(ir::DataType::UINT8);
}
};
qasymm8ToUint8(
subg.operands().at(eu->getInputs().at(ir::operation::ElementwiseUnary::Input::INPUT)));
qasymm8ToUint8(subg.operands().at(eu->getOutputs().at(0)));
}
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadGather(const Operator *op, ir::Graph &subg)
{
ir::operation::Gather::Param param;
param.axis = op->builtin_options_as_GatherOptions()->axis();
loadOperationTo<ir::operation::Gather>(op, subg, param);
}
template <typename LoaderDomain>
void BaseLoader<LoaderDomain>::loadDetectionPostProcess(const Operator *op, ir::Graph &subg)
{
const auto &m = getCustomOpAttrMap(op);
ir::operation::DetectionPostProcess::Param param;
param.max_detections = m["max_detections"].AsInt32();
// TODO fixme
param.max_classes_per_detection = m["max_classes_per_detection"].AsInt32();
if (m["detections_per_class"].IsNull())
param.max_boxes_per_class = 100;
else
param.max_boxes_per_class = m["detections_per_class"].AsInt32();
if (m["use_regular_nms"].IsNull())
param.do_fast_eval = true;
else
param.do_fast_eval = !m["use_regular_nms"].AsBool();
param.score_threshold = m["nms_score_threshold"].AsFloat();
param.iou_threshold = m["nms_iou_threshold"].AsFloat();
// TODO add num classes support
param.num_classes = m["num_classes"].AsInt32();