This repository has been archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
/
operators.py
3178 lines (2496 loc) · 99.7 KB
/
operators.py
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
# -*- coding: utf-8 -*-
# Copyright 2018 The Blueoil Authors. 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.
# =============================================================================
"""Definition of operators."""
import copy
import functools
import warnings
from termcolor import colored
from abc import abstractmethod
from itertools import dropwhile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast
import numpy as np
from blueoil.converter.core.view import View
from blueoil.converter.util import classproperty
from .data_types import DataType
if TYPE_CHECKING:
import blueoil.converter.core.operators as ops
Ops = Dict[str, 'Operator']
OutOps = Dict[str, List['Operator']]
warning_sign = colored('WRN', 'red', attrs=['blink'])
class Operator(object):
"""Base class of operators."""
_input_names: List[str] = ['input']
_output_names: List[str] = ['output']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
dimension_format: str = 'NHWC') -> None:
"""Init the operator."""
self._name: str = name
self._input_ops: Ops = input_ops
self._output_ops: OutOps = {}
self._dtype = dtype
self._data = np.zeros(shape, dtype=dtype.nptype())
self.update_shape(shape, dimension_format)
self.view: View = View(self)
self.__connect_to_outputs()
self._check_consistency()
self._rank = len(shape)
self._available_buffer = ''
def update_shape(self, shape: List[int], dimension_format: str) -> None:
self._shape: List[int] = shape
self._rank = len(shape)
self._dimension_format = dimension_format
dimension_format_list = []
for ch in dimension_format:
if ch.isupper():
dimension_format_list.append(ch)
else:
dimension_format_list[-1] += ch
self.index_H = dimension_format_list.index('H') if 'H' in dimension_format_list else None
self.index_W = dimension_format_list.index('W') if 'W' in dimension_format_list else None
self.index_N = dimension_format_list.index('N') if 'N' in dimension_format_list \
else dimension_format_list.index('Oh') if 'Oh' in dimension_format_list \
else dimension_format_list.index('O') if 'O' in dimension_format_list else None
self.index_C = dimension_format_list.index('C') if 'C' in dimension_format_list \
else dimension_format_list.index('Ch') if 'Ch' in dimension_format_list \
else dimension_format_list.index('I') if 'I' in dimension_format_list \
else dimension_format_list.index('Ih') if 'Ih' in dimension_format_list else None
self.index_C_low = dimension_format_list.index('Cl') if 'Cl' in dimension_format_list else None
def __connect_to_outputs(self) -> None:
"""Connect input operators' outputs to this object."""
for ip in self._input_ops.values():
if ip.op_type == 'Split':
for x in ip.output_names:
if x not in ip._output_ops.keys():
ip.add_output(x, self)
break
else:
key = ip.output_names[0]
ip.add_output(key, self)
def _assert(self, predicate: bool, message: str = '') -> None:
"""Assert a predicate. When it fails, raise an error.
This is a substitute for an `assert` statement. The `assert` is
not checked in byte-compiled code, but this is always checked.
Args:
predicate (bool): Assertion to be true
message (str): Error message in the failure of the assertion
"""
if not predicate:
raise AssertionError(message) if message else AssertionError()
def _check_consistency(self) -> None:
"""Check data consistency in the initialization."""
# check the input ops
self._assert(set(self._input_ops.keys()).issubset(set(self._input_names)),
f"Operator inputs must consist of {', '.join(self._input_names)}")
def equals(self, other: Any) -> bool:
"""Return if these two objects are equivalent."""
if other is None or not isinstance(other, Operator):
print(f'{self.name} has different type.')
return False
eq_type = self.op_type == other.op_type
if not eq_type:
print(f'{self.name} and {other.name} have different type: {self.op_type} and {other.op_type}')
eq_shape = self.shape == other.shape
if not eq_shape:
print(f'{self.name} and {other.name} have different shape: {self.shape} and {other.shape}')
eq_dtype = self.dtype == other.dtype
if not eq_dtype:
print(f'{self.name} and {other.name} have different dtype: {self.dtype} and {other.dtype}')
eq_dim = self._dimension_format.replace('I', 'C').replace('O', 'N') \
== other._dimension_format.replace('I', 'C').replace('O', 'N')
if not eq_dim:
print(f'{self.name} and {other.name} have different dimension: {self.dimension} and {other.dimension}')
eq_data = eq_shape and np.allclose(self.data, other.data)
if not eq_data:
print(f'{self.name} and {other.name} have different data: {self.data} and {other.data}')
return eq_type and eq_shape and eq_dtype and eq_dim and eq_data
@property
def name(self) -> str:
"""Return name. This must be a unique name in the graph."""
return self._name
@property
def op_type(self) -> str:
"""Return the operation type."""
return type(self).__name__
@property
def input_ops(self) -> Ops:
"""Return a dict of input operators.
Returns:
dict: Collection of input operators in a dictionary format.
The keys are input symbols, which can be taken from `input_names` property.
"""
return self._input_ops
@classproperty
def input_names(cls) -> List[str]:
"""Return the input key names the operator provides.
For example, `Conv` has two inputs, 'X' for the input data and 'W' for the weight.
So `Conv.input_names` returns the list `['X', 'W']`.
Returns:
list[str]: List of key names
"""
return cls._input_names
@property
def input_nodes(self) -> List['Operator']:
"""Return a list of input operators in proper order (original protobuf argument order).
Returns:
list[Operator]: This list is already ordered following the order of the arguments in the original
protobuf operators (positional order in the list of arguments).
"""
return [self._input_ops[i] for i in self.input_names if self.input_ops.get(i)]
@property
def output_ops(self) -> OutOps:
"""Return a dict of output operators.
Returns:
dict: Collection of (list of) output operators in a dictionary format.
The keys are output symbols, which can be taken from `output_names` property.
"""
return self._output_ops
@property
def output_op_list(self) -> List['Operator']:
"""Return a list of output operators.
Returns:
list[Operator]: List of output operators.
"""
return sum(list(self._output_ops.values()), [])
@classproperty
def output_names(cls) -> List[str]:
"""Return the output key names the operator provides.
For example, `Conv` has one output 'Y'.
So `Conv.output_names` returns the list `['Y']`.
Returns:
list[str]: List of key names
"""
return cls._output_names
def add_input(self, ident: str, node: 'Operator') -> None:
"""Add input node.
Args
ident (str): key name of the input. This has to be in list `input_names`.
node (Operator): Node to be registered as the input.
"""
self._assert(ident in self._input_names, "Illegal input name")
self._input_ops[ident] = node
def add_inputs(self, inputs: Ops) -> None:
"""Add input (possibly multiple) nodes at a once.
Args:
outputs (dict): Collection of pair of key name and a operator to be registered as the input.
All the key names have to be in list `input_names`.
"""
assert set(inputs.keys()).issubset(set(self._input_names)), "Illegal output names included"
self._input_ops.update(inputs)
def add_output(self, ident: str, node: 'Operator') -> None:
"""Add output node.
Args:
ident (str): key name of the output. This has to be in list `output_names`.
node (Operator): Node to be registered as the output.
"""
self._assert(ident in self._output_names, "Illegal output name")
lst: Optional[List['Operator']] = self._output_ops.get(ident)
if lst is not None:
lst.append(node)
else:
self._output_ops[ident] = [node]
def add_outputs(self, outputs: OutOps) -> None:
"""Add output (possibly multiple) nodes at a once.
Args:
outputs (Dict of str to list of Operators): Collection of pair of key name
and a list of operators to be registered as the output.
All the key names have to be in list `output_names`.
"""
assert set(outputs.keys()).issubset(set(self._output_names)), f"Illegal output names included"
for n in outputs.keys():
lst = self._output_ops.get(n)
if lst is not None:
lst += [x for x in outputs[n] if x not in lst]
else:
self._output_ops[n] = list(outputs[n])
self._output_ops.update(outputs)
def remove_input(self, ident: str) -> None:
"""Remove an input node.
Args:
ident (str): Key name of the input node to be removed.
This key is in `input_names`, not the name of the operator.
"""
self._input_ops.pop(ident)
def remove_output(self, ident: str) -> None:
"""Remove an output node.
Args:
ident (str): Key name of the output node to be removed.
This key is in `output_names`, not the name of the operator.
"""
self._output_ops.pop(ident)
@property
def shape(self) -> List[int]:
"""Get the shape defined in this node."""
return self._shape
@shape.setter
def shape(self, v: List[int]) -> None:
"""Set the shape defined in this node."""
self._shape = v
@property
def dtype(self) -> DataType:
"""Get the data type defined in this node."""
return self._dtype
@dtype.setter
def dtype(self, v: DataType) -> None:
"""Set the data type defined in this node."""
self._dtype = v
@property
def ndims(self) -> int:
"""Get the number of dimension defined in this node."""
return len(self._shape)
@property
def dimension(self) -> str:
"""Return dimension in string.
This dimension consists of 'N', 'C', 'H', and 'W', where 'N' is the number of batch size,
'C' is the number of channels, 'H' and 'C' are the height and the weight in the 2-D image.
"""
return self._dimension_format
@property
def size(self) -> int:
"""Get the whole size of the output data."""
import operator
pred = functools.partial(functools.reduce, operator.mul)
return int(pred(self._shape, 1)) # type: ignore
@property
def is_variable(self) -> bool:
"""Return if this node is a variable node (i.e. Input or Output)."""
return False
@property
def is_scalar(self) -> bool:
"""Return if this node is a scalar node (i.e. `ndim == 0`)."""
return self.ndim == 0
@property
def height(self) -> int:
"""Get the size of height in the shape."""
if self.index_H is not None:
return self.shape[self.index_H]
else:
raise ValueError(f'Operator {self.name} does not have the height property.')
@property
def width(self) -> int:
"""Get the size of width in the shape."""
if self.index_W is not None:
return self.shape[self.index_W]
else:
raise ValueError(f'Operator {self.name} does not have the width property.')
@property
def channel(self) -> int:
"""Get the number of channels in the shape."""
if self.index_C is not None:
if self.index_C_low is not None:
return self.shape[self.index_C] * self.shape[self.index_C_low]
else:
return self.shape[self.index_C]
else:
raise ValueError(f'Operator {self.name} does not have the channel property.')
@property
def batchsize(self) -> int:
"""Get the number of batch size in the shape."""
if self.index_N is not None:
return self.shape[self.index_N]
else:
raise ValueError(f'Operator {self.name} does not have the batchsize property.')
@property
def rank(self) -> int:
return self._rank
@property
def available_buffer(self) -> str:
return self._available_buffer
@available_buffer.setter
def available_buffer(self, v: str) -> None:
self._available_buffer = v
def transpose(self, perm: List[int]) -> None:
"""Transpose the shape and format. This operation is destructive."""
self._assert(len(set(perm)) == len(self._shape), "Illegal permutation specified.")
self._assert(max(perm) == len(self._shape) - 1, "Illegal permutation specified.")
self._assert(min(perm) == 0, "Illegal permutation specified.")
# change the shape
new_shape: List[int] = [self._shape[i] for i in perm]
# change the format
new_format: str = functools.reduce(
lambda x, y: x + y, [self._dimension_format[i] for i in perm])
# update
self.update_shape(new_shape, new_format)
@property
def data(self) -> np.ndarray:
"""Get the output data.
This value is valid only after `run_forward()` or some value has assigned with the setter.
"""
return self._data
@property
def is_monotonic(self) -> bool:
raise NotImplementedError(f'operator {self.name} is monotonic or not?')
def run(self, **kwargs) -> Dict:
"""The intermediate runtime, run the operator with external data
This is actually an abstract method and should be overridden.
"""
raise NotImplementedError('run is not implemented yet')
def run_forward(self) -> np.ndarray:
"""Run the operator, calculate and set the result.
This is actually an abstract method and should be overridden.
"""
raise NotImplementedError(
f'operator {self.op_type} does not have runtime implementation yet.')
@property
def _dispatch_name(self) -> str:
return type(self).__name__.lower()
@classmethod
def infer_shape(cls, lists: Dict[str, List[int]], format: str, input_formats: List[str],
attrs: Dict[str, Any]) -> List[int]:
"""Infer its output shape from inputs' shapes.
This is actually an abstract method and should be overridden.
"""
raise NotImplementedError(f'operator {cls.__name__} cannot infer its shape.')
@property
def preserve_quantization(self) -> bool:
"""whether to preserve the operator for quantization"""
raise NotImplementedError(
f'Preservation for quantization of operator {self.op_type} is not defined.')
class Variable(Operator):
"""Variable class, which must be Input, Output or a constant."""
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
data: np.ndarray,
dimension_format: str = 'NHWC') -> None:
"""Init the variable."""
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
self._data = data
@property
def is_variable(self) -> bool:
"""Return True, as this is a variable."""
return True
@property
def is_monotonic(self) -> bool:
return False
def transpose(self, perm: List[int]) -> None:
"""Transpose the shape and format. This operation is destructive."""
super().transpose(perm)
self._data = self._data.transpose(perm)
@property
def data(self) -> np.ndarray:
"""Return data."""
return self._data
@data.setter
def data(self, val: np.ndarray) -> None:
self._data = val
@property
def preserve_quantization(self) -> bool:
return False
class Input(Variable):
"""Input class. This is a placeholder."""
_input_names: List[str] = []
_output_names = ['output']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
dimension_format: str = 'NHWC') -> None:
"""Init the input variable."""
data = np.zeros(shape, dtype=dtype.nptype())
super().__init__(name, shape, dtype, {}, data, dimension_format=dimension_format)
class Constant(Variable):
"""Constant class. This object has data inside."""
_input_names: List[str] = []
_output_names = ['output']
def __init__(self,
name: str,
dtype: DataType,
data: np.ndarray,
dimension_format: str = 'OHWI',
transposed_dimension_format: str = 'OHWI',
packed: bool = False,
actual_shape: List[int] = [],
transposed_data: List[int] = None,
transposed_shape: List[int] = None,
kn2row_data: List[int] = None,
kn2row_dimension_format: str = 'HWOI',
kn2row_shape: List[int] = None,) -> None:
"""Init the variable.
If the constant is hard quantized, data is packed and the actual shape
must be expressed with `actual_shape`.
"""
shape = list(data.shape) if not packed else actual_shape
self._packed = packed
self._transposed_data = transposed_data
self._transposed_shape = transposed_shape
self._transposed_dimension_format = transposed_dimension_format
self._kn2row_data = kn2row_data
self._kn2row_dimension_format = kn2row_dimension_format
self._kn2row_shape = kn2row_shape
super().__init__(name, shape, dtype, {}, data, dimension_format=dimension_format)
def run_forward(self) -> np.ndarray:
return self._data
@property
def is_packed(self) -> bool:
return self._packed
@property
def transposed_data(self) -> List[int]:
"""Return transposed data."""
return self._transposed_data
@property
def transposed_dimension_format(self) -> str:
return self._transposed_dimension_format
@property
def transposed_shape(self) -> List[int]:
return self._transposed_shape
@property
def kn2row_data(self) -> List[int]:
return self._kn2row_data
@property
def kn2row_dimension_format(self) -> str:
return self._kn2row_dimension_format
@property
def kn2row_shape(self) -> List[int]:
return self._kn2row_shape
class Output(Variable):
"""Output class."""
_input_names = ['input']
_output_names: List[str] = []
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
dimension_format: str = ''
) -> None:
"""Init the output variable."""
data = np.zeros(shape, dtype=dtype.nptype())
super().__init__(name, shape, dtype, input_ops, data, dimension_format=dimension_format)
def _check_consistency(self) -> None:
super()._check_consistency()
self._assert(len(self._input_ops) == 1, f'output {self.name} has {len(self._input_ops)} inputs.')
self._assert(self._input_ops['input'].shape == self.shape,
f'Shape mismatch at {self.op_type} "{self.name}"')
self._assert(self._input_ops['input'].dtype == self.dtype,
f'Type mismatch at {self.op_type} "{self.name}"')
class Identity(Operator):
"""Identity operator.
Inputs
------
input
Input tensor
Output
------
output
Tensor to copy input
"""
_input_names = ['input']
_output_names = ['output']
def __init__(self, name: str, shape: List[int], dtype: DataType, input_ops: Ops,
dimension_format: str = 'NHWC') -> None:
"""Init the identity operator."""
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
def _check_consistency(self) -> None:
super()._check_consistency()
self._assert(self._input_ops['input'].shape == self.shape,
f'Shape mismatch at {self.op_type} "{self.name}"')
def run_forward(self) -> np.ndarray:
self._data = self._input_ops['input'].data
return self._data
@property
def is_monotonic(self) -> bool:
return self.input_ops['input'].is_monotonic
@classmethod
def infer_shape(cls, lists: Dict[str, List[int]], format: str, input_formats: List[str],
attrs: Dict[str, Any]) -> List[int]:
return lists['input']
@property
def preserve_quantization(self) -> bool:
return True
class Quantizer(Operator):
"""Base class for quantizers."""
_input_names = ['input']
_output_names = ['output']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
dimension_format: str = 'NHWC') -> None:
"""Init this quantization operator."""
self._scaling_factor = np.float32(0)
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
def equals(self, other: Any) -> bool:
sup = super().equals(other)
return sup and np.isclose(self.scaling_factor, other.scaling_factor)
@property
def nbit(self) -> int:
raise NotImplementedError('Quantizer does not have bit value defined')
@property
def max_v(self) -> float:
raise NotImplementedError('Quantizer does not have max value defined')
@property
def scaling_factor(self) -> np.float32:
return self._scaling_factor
@property
def preserve_quantization(self) -> bool:
return False
@scaling_factor.setter
def scaling_factor(self, val: np.float32) -> None:
self._scaling_factor = val
@abstractmethod
def binarizer(self, data: np.ndarray) -> np.ndarray:
"""Maps the quantized values into >= 0 integer values.
This is actually an abstract method and should be overridden.
"""
raise NotImplementedError(
f'operator {self.op_type} need to implement the binarizer method')
class BinaryMeanScalingQuantizer(Quantizer):
"""Quantization operator using binary scaling.
Input
-----
input
Input tensor, which must have float values.
Output
------
output
Quantized tensor
"""
_input_names = ['input']
_output_names = ['output']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
dimension_format: str = 'NHWC') -> None:
"""Init the quantization operator."""
self._scaling_factor = 0
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
def _check_consistency(self) -> None:
super()._check_consistency()
self._assert(self._input_ops['input'].shape == self.shape,
f'Shape mismatch at {self.op_type}" {self.name}"')
@property
def is_monotonic(self) -> bool:
return False
@property
def _dispatch_name(self) -> str:
return type(self).__name__
def run_forward(self) -> np.ndarray:
in_data = self.input_ops['input'].data
self._scaling_factor = np.mean(np.abs(in_data))
self._data = np.sign(in_data)
return self._data * self._scaling_factor
def run_forward_no_scaling_factor(self) -> np.ndarray:
in_data = self.input_ops['input'].data
self._scaling_factor = np.mean(np.abs(in_data))
self._data = np.sign(in_data)
return self._data
@classmethod
def infer_shape(cls, lists: Dict[str, List[int]], format: str, input_formats: List[str],
attrs: Dict[str, Any]) -> List[int]:
return lists['input']
def binarizer(self, data: np.ndarray) -> np.ndarray:
"""Maps the quantized values into >= 0 integer values."""
bdata = copy.deepcopy(data)
bdata[bdata < 0] = 0
return bdata
class SpaceToDepth(Operator):
"""Space to Depth operator.
Input
-----
input
Input tensor
Output
------
output
A tensor with reduced height and width and increased depth
Attributes (optional constructor parameters)
----------
block_size : integer
Input block size
"""
_input_names = ['input']
_output_names = ['output']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
dimension_format: str = 'NHWC',
block_size: int = 2) -> None:
"""Init the quantization operator."""
self._block_size = block_size
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
def _check_consistency(self) -> None:
"""
This check the following constraints:
Output depth must be
1. (multiple of kernel_size^2 * 32) OR
2. (kernel_size^2 * {8, 16}).
"""
super()._check_consistency()
if self.channel % 32 != 0:
warnings.warn(warning_sign +
f" Output channels need to be multiple of 32 for {self.name} of {self.op_type}, "
f"but got output channel size of {self.channel}",
stacklevel=2)
@property
def is_monotonic(self) -> bool:
return False
@property
def _dispatch_name(self) -> str:
return type(self).__name__
@property
def block_size(self) -> np.int32:
return self._block_size
@classmethod
def infer_shape(cls, lists: Dict[str, List[int]], format: str, input_formats: List[str],
attrs: Dict[str, Any]) -> List[int]:
return lists['input']
@property
def preserve_quantization(self) -> bool:
return True
class Transpose(Operator):
"""Transpose operator.
Transpose the input tensor similar to numpy.transpose. For example, when perm=[3, 1, 0, 2],
given an input tensor of shape [1, 2, 3, 4], the output shape will be [4, 2, 1, 3].
Inputs
------
data
An input tensor.
Outputs
-------
transposed
Transposed output.
Attributes (optional constructor parameters)
perm : list of ints
A list of integers. By default, reverse the dimensions, otherwise permute the axes according
to the values given.
"""
_input_names = ['data']
_output_names = ['transposed']
def __init__(self, name: str, shape: List[int], dtype: DataType, input_ops: Ops,
perm: List[int] = [], dimension_format: str = 'NHWC') -> None:
self._permutation = perm if perm else [i for i in range(len(shape) - 1, -1, -1)]
super().__init__(name, shape, dtype, input_ops, dimension_format=dimension_format)
def _check_consistency(self) -> None:
super()._check_consistency()
self._assert(len(self.permutation) == len(self.shape),
f'Illegal permutation for Transpose: {self.permutation}.')
self._assert(set(self.permutation) == set([i for i in range(len(self.shape))]),
f'Illegal permutation for Transpose: {self.permutation}.')
transposed_shape = [self._input_ops['data'].shape[i] for i in self.permutation]
self._assert(self.shape == transposed_shape,
f'Shape mismatch at {self.op_type} "{self.name}"')
@property
def is_monotonic(self) -> bool:
return False
@property
def permutation(self) -> List[int]:
"""Get transpose permutation in list of ints."""
return self._permutation
def run_forward(self) -> np.ndarray:
self._data = self._input_ops['data'].data.transpose(self._permutation)
return self._data
@classmethod
def infer_shape(cls, lists: Dict[str, List[int]], format: str, input_formats: List[str],
attrs: Dict[str, Any]) -> List[int]:
perm = attrs['perm']
return [lists['data'][i] for i in perm]
@property
def preserve_quantization(self) -> bool:
return True
class Conv(Operator):
"""Convolution operator.
The convolution operator consumes an input tensor and a weight, and computes the output.
Currently this is only for 2-D images.
Inputs
------
X
Input data tensor from previous layer. Note that this is for the 2D image.
W
The weight tensor that will be used in the convolutions.
B (Optional)
1D bias.
Outputs
-------
Y
Output data tensor that contains the result of the convolution.
The output dimensions are functions of the kernel size, stride size, and pad lengths.
Attributes (Optional constructor parameters)
----------
kernel_shape : list of ints
The shape of the convolution kernel. If not present, should be inferred from input W.
kernel_dimensions : int
The dimension of the input. The default value is 2, which means 2-D image.
dimension_format : str
Dimension denotation, which must consists of 'N', 'C', 'H', and 'W', where 'N' is the
number of batch size, 'C' is the number of channels, 'H' and 'W' are the height and
width of input image. The default is 'NHWC'.
kernel_dim_format : str
Dimension denotation, which must consists of 'H' and 'W', where 'H' and 'W' are the
height and width of input image. The default is 'HW'.
dilations : list of ints
Dilation value along each axis of the filter. If not present, the dilation defaults to 1
along each axis.
pads : list of ints
Padding for the beginning and ending along each axis, it can take any value greater than
or equal to 0. The value represent the number of pixels added to the beginning and end
part of the corresponding axis.
`pads` format should be as follow [x1_begin, x2_begin, x1_end, x2_end], where
xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number
of pixels added at the end of axis `i`.
If not present, the padding defaults to 0 along start and end of each axis.
strides : list of ints
Stride along each axis. If not present, the stride defaults to 1 along each axis.
quantized : bool
Whether it is quantized. If not present, the switch defaults to False.
thresholds : list of floats
Threshold values that are used in threshold skipping. If not present, this defaults to
an empty list. Ignored if `quantized` is not true.
"""
_input_names = ['X', 'W', 'B']
_output_names = ['Y']
def __init__(self,
name: str,
shape: List[int],
dtype: DataType,
input_ops: Ops,
kernel_shape: List[int] = [],
kernel_dimensions: int = 2,
dimension_format: str = 'NHWC',
kernel_dim_format: str = 'HW',
dilations: List[int] = [1, 1],
pads: List[int] = [0, 0, 0, 0],
strides: List[int] = [1, 1],
quantized: bool = False,
thresholds: List[float] = []) -> None:
# currently, only 2-D is supported.
if kernel_dimensions != 2:
raise NotImplementedError(f"Convolution for {kernel_dimensions}-D is not defined!")
self._num_dimensions = kernel_dimensions