blob: 0d299e15031985b5c49a88ee1c3a654c5051b126 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Internal representation of a Neural Network Tensor.
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +010018import copy
Tim Hall79d07d22020-04-27 18:20:16 +010019import enum
Tim Hall79d07d22020-04-27 18:20:16 +010020import uuid
Jacob Bohlin1a666972020-09-11 10:04:15 +020021from collections import defaultdict
Louis Verhaard9db529a2020-09-23 10:27:11 +020022from functools import lru_cache
Diego Russoea6111a2020-04-14 18:41:58 +010023
24import numpy as np
25
26from . import numeric_util
Tim Hall93582962020-09-09 21:58:15 +010027from .data_type import BaseType
Michael McGeagh5778ffd2020-08-06 17:31:02 +010028from .data_type import DataType
Dwight Lidmana9390f72020-05-13 12:00:08 +020029from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaardaee5d752020-09-30 09:01:52 +020030from .operation import Op
Michael McGeagh5778ffd2020-08-06 17:31:02 +010031from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010032from .range_set import MemoryRangeSet
Tim Hall79d07d22020-04-27 18:20:16 +010033
34
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020035class MemType(enum.IntFlag):
36 Unknown = 0
37 Permanent_NPU = 1
38 Permanent_CPU = 2
39 Scratch = 3
40 Scratch_fast = 4
41 Size = Scratch_fast + 1
42
43 def display_name(self):
44 return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value]
45
46 def identifier_name(self):
47 return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value]
48
49 def all():
50 return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast)
51
52 def __str__(self):
53 return self.name
54
55
Tim Hall79d07d22020-04-27 18:20:16 +010056class MemArea(enum.IntFlag):
57 Unknown = 0
58 Sram = 1
59 Dram = 2
60 OnChipFlash = 3
61 OffChipFlash = 4
Louis Verhaard0b8268a2020-08-05 16:11:29 +020062 Shram = 5 # for LUT
63 Size = Shram + 1
Tim Hall79d07d22020-04-27 18:20:16 +010064
65 def display_name(self):
Louis Verhaard0b8268a2020-08-05 16:11:29 +020066 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "SHRAM", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010067
68 def identifier_name(self):
Louis Verhaard0b8268a2020-08-05 16:11:29 +020069 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "shram", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010070
71 def all():
Louis Verhaard0b8268a2020-08-05 16:11:29 +020072 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash, MemArea.Shram)
Tim Hall79d07d22020-04-27 18:20:16 +010073
74 def __str__(self):
75 return self.name
76
77
78class TensorPurpose(enum.IntFlag):
79 Unknown = 0
80 Weights = 1
81 FeatureMap = 2
82 Scratch = 3
Fredrik Svedberga0c36242020-06-03 15:43:31 +020083 LUT = 4
Andreas Nevalainen897cc142020-10-28 15:42:08 +010084 FSBias = 5
85 Size = 6
Tim Hall79d07d22020-04-27 18:20:16 +010086
87 def display_name(self):
Andreas Nevalainen897cc142020-10-28 15:42:08 +010088 return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "FastStorageBias", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010089
90 def identifier_name(self):
Andreas Nevalainen897cc142020-10-28 15:42:08 +010091 return ("unknown", "weights", "feature_map", "scratch", "lut", "fast_storage_bias", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010092
93 def all():
Andreas Nevalainen897cc142020-10-28 15:42:08 +010094 return (TensorPurpose.Weights, TensorPurpose.FeatureMap, TensorPurpose.FSBias)
Tim Hall79d07d22020-04-27 18:20:16 +010095
96
97class TensorSubPurpose(enum.Enum):
98 Standard = 0
99 DoubleBuffer = 1
100 RollingBufferX = 2
101 RollingBufferY = 3
102 RollingBufferXY = 4
103
104 def display_name(self):
105 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
106
107 def identifier_name(self):
108 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
109
110 def all():
111 return (
112 TensorSubPurpose.Standard,
113 TensorSubPurpose.DoubleBuffer,
114 TensorSubPurpose.RollingBufferX,
115 TensorSubPurpose.RollingBufferY,
116 TensorSubPurpose.RollingBufferXY,
117 )
118
119
120class TensorFormat(enum.Flag):
121 Unknown = 0
122 WeightsCompressed = 1
123 NHWC = 2
124 NHCWB16 = 3
125
126 def __str__(self):
127 return self.name
128
129
130class TensorBlockTraversal(enum.Enum):
131 Default = 0
132 DepthWise = 1
133 DepthFirst = 2
134 PartKernelFirst = 3
135
136
137def shape_num_elements(shp):
138 elems = 1
139 if shp is None:
140 return None
141 for d in shp:
142 if d is None:
143 return None
144 elems *= d
145 return elems
146
147
148def shape_fully_defined(shp):
149 if shp is None:
150 return False
151 for d in shp:
152 if d is None:
153 return False
154 return True
155
156
157def shape_round_to_quantum(shp, quantum):
158 new_shp = list(shp)
159
160 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
161 for i in range(-1, -len(shp) - 1, -1):
162 if new_shp[i] is not None:
163 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
164 return new_shp
165
166
Louis Verhaard9db529a2020-09-23 10:27:11 +0200167@lru_cache(maxsize=None)
168def create_equivalence_id(key):
169 # Generates equivalence_id based on the given key.
170 return uuid.uuid4()
171
172
Tim Hall79d07d22020-04-27 18:20:16 +0100173class QuantizationParameters:
174 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
175
176 def __init__(self, min=None, max=None, num_bits=None, narrow_range=None):
177 self.min = min
178 self.max = max
179
180 self.num_bits = num_bits
181 self.narrow_range = narrow_range
182
183 self.scale_f32 = None
184 self.zero_point = None
185 self.quant_min = None
186 self.quant_max = None
187
188 def __str__(self):
189 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
190 self.min,
191 self.max,
192 self.num_bits,
193 self.scale_f32,
194 self.zero_point,
195 )
196
197 __repr__ = __str__
198
199 def clone(self):
200 res = QuantizationParameters()
201 res.min = self.min
202 res.max = self.max
203
204 res.num_bits = self.num_bits
205 res.narrow_range = self.narrow_range
206
207 res.scale_f32 = self.scale_f32
208 res.zero_point = self.zero_point
209 res.quant_min = self.quant_min
210 res.quant_max = self.quant_max
211 return res
212
213 def dequantize(self, values):
214 if self.zero_point.size == 1 and self.scale_f32.size == 1:
215 # same scale is used for all values
216 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
217 else:
218 # a different scale is used for different sets of values
219 values_as_float = values.astype(np.float64)
220
221 # this is not compatible with the format of depthwise weights,
222 # where input is at index 3 (Output, Kh, Kw, Input)
223 # return the quantized values
224 return np.ndarray((values_as_float.shape))
225
226 shape = values_as_float.shape[0]
227 assert self.zero_point.size == self.scale_f32.size == shape
228 res = np.ndarray(values_as_float.shape)
229 for i in range(shape):
230 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
231
232 return res
233
Tim Halle3786ac2020-07-28 17:40:50 +0100234 def is_scaling_equal(self, other):
Tim Hall93582962020-09-09 21:58:15 +0100235 # quantisation parameter scaling is not equal if 'other' is None because
236 # it implies that the tensor it belongs to is not quantised. otherwise,
237 # it depends upon whether the scale and zero point are equal
238
239 if other is None:
Tim Halle3786ac2020-07-28 17:40:50 +0100240 return False
241
Tim Hall93582962020-09-09 21:58:15 +0100242 assert isinstance(other, QuantizationParameters)
243
Tim Halle3786ac2020-07-28 17:40:50 +0100244 return self.scale_f32 == other.scale_f32 and self.zero_point == other.zero_point
245
Tim Hall93582962020-09-09 21:58:15 +0100246 def is_valid(self):
247 # quantisation parameters are consider valid if they have a scale and zero point
248
249 return None not in (self.scale_f32, self.zero_point)
250
Tim Hall79d07d22020-04-27 18:20:16 +0100251
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100252def create_const_tensor(name, shape, dtype, values, value_dtype=None, purpose=TensorPurpose.Unknown, quantization=None):
253 # Tensor
254 const_tensor = Tensor(shape, dtype, name + "_0")
255 const_tensor.purpose = purpose
256 const_tensor.quantization = quantization
257 const_tensor.values = np.array(values, dtype=value_dtype)
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200258 const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100259 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200260 const_op = Operation(Op.Const, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100261 const_op.set_output_tensor(const_tensor)
262 return const_tensor
263
264
265def create_reshape_tensor(tens, shape, ifm_reshape=True):
266 if shape == tens.shape:
267 return tens
268 # Tensors
269 name = tens.name + "_reshape"
270 reshape_ifm = tens
271 reshape_ofm = tens.clone("_reshaped")
272 reshape_ofm.set_all_shapes(shape)
273 if not ifm_reshape:
274 reshape_ifm, reshape_ofm = reshape_ofm, reshape_ifm
275 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200276 reshape_op = Operation(Op.Reshape, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100277 reshape_op.attrs["new_shape"] = shape
278 reshape_op.add_input_tensor(reshape_ifm)
279 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, shape))
280 reshape_op.set_output_tensor(reshape_ofm)
281 return reshape_ofm if ifm_reshape else reshape_ifm
282
283
Jacob Bohlin1a666972020-09-11 10:04:15 +0200284# class that keeps track of all tensor addresses in the different memory types
285class TensorAddressMap:
286 address_map = defaultdict(dict) # dict (tens.equivalence_id -> dict (mem_type -> address))
287
288 @classmethod
289 def get_address_for_tens(cls, tens_id, mem_type):
290 return cls.address_map[tens_id].get(mem_type)
291
292 @classmethod
293 def set_address_for_tens(cls, tens_id, mem_type, address):
294 # Check previous address if there is one
295 previous_address = cls.address_map[tens_id].get(mem_type)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200296 if address is not None and previous_address is not None:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200297 assert previous_address == address, "Two different addresses cannot be assigned to the same tensor."
298
299 # Set tensor's address for memory type
300 cls.address_map[tens_id][mem_type] = address
301
302
Tim Hall79d07d22020-04-27 18:20:16 +0100303class Tensor:
304 __slots__ = (
305 "shape",
306 "storage_shape",
307 "bandwidth_shape",
308 "dtype",
309 "name",
310 "ops",
311 "consumer_list",
312 "values",
313 "quant_values",
314 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100315 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100316 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200317 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100318 "format",
319 "purpose",
320 "sub_purpose",
321 "alignment",
322 "weight_transpose_depthwise",
323 "storage_compression_scale",
324 "bandwidth_compression_scale",
325 "compression_scale_for_worst_weight_stream",
326 "weight_compression_scales",
327 "weight_compression_config",
Louis Verhaard9db529a2020-09-23 10:27:11 +0200328 "value_id",
Tim Hall79d07d22020-04-27 18:20:16 +0100329 "storage_rounding_quantum",
330 "brick_size",
Tim Hall79d07d22020-04-27 18:20:16 +0100331 "quantization",
332 "weight_compressed_offsets",
333 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100334 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100335 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200336 "resampling_mode",
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200337 "avoid_NHCWB16",
Tim Hall79d07d22020-04-27 18:20:16 +0100338 )
339 AllocationQuantum = 16
340
341 def __init__(self, shape, dtype, name):
342 self.shape = shape
343 self.storage_shape = shape
344 self.bandwidth_shape = shape
345 self.dtype = dtype
346 self.name = name
347 self.equivalence_id = uuid.uuid4()
348
349 self.ops = []
350 self.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100351
352 self.values = None
353 self.quant_values = None
354 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100355 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100356 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200357 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100358 self.format = TensorFormat.Unknown
359 self.purpose = TensorPurpose.Unknown
360 self.sub_purpose = TensorSubPurpose.Standard
361 self.alignment = Tensor.AllocationQuantum
362 self.weight_transpose_depthwise = False
363
364 self.storage_compression_scale = 1.0
365 self.bandwidth_compression_scale = 1.0
366 self.compression_scale_for_worst_weight_stream = 1.0
367 self.weight_compression_scales = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200368 # if two tensors have the same weight_compression_config, then they have the same compressed values
Tim Hall79d07d22020-04-27 18:20:16 +0100369 self.weight_compression_config = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200370 # if two tensors have the same value_id, then they have the same values
371 self.value_id = uuid.uuid4()
Tim Hall79d07d22020-04-27 18:20:16 +0100372 self.weight_compressed_offsets = []
373 self.storage_rounding_quantum = (1, 1, 1, 1)
374 self.brick_size = (1, 1, 1, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100375 self.element_size_bytes = 0
376
377 # quantization parameters
378 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100379 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200380 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100381
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200382 self.avoid_NHCWB16 = False
383
Jacob Bohlin1a666972020-09-11 10:04:15 +0200384 @property
385 def address(self):
386 return TensorAddressMap.get_address_for_tens(self.equivalence_id, self.mem_type)
387
388 @address.setter
389 def address(self, address):
390 TensorAddressMap.set_address_for_tens(self.equivalence_id, self.mem_type, address)
391
Tim Hall79d07d22020-04-27 18:20:16 +0100392 def element_size(self):
393 if self.element_size_bytes == 0:
394 return self.dtype.size_in_bits() / 8
395 return self.element_size_bytes
396
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100397 # Returns a copy, renamed to self.name + suffix
398 # The references to Operators will be empty when returned
399 # Depending on set_unique, the copy is shallow, or deep
400 # For set_unique==True, a new equivalence_id will be set
401 def clone(self, suffix="_clone", set_unique=False):
402 if set_unique:
403 res = copy.deepcopy(self)
404 res.equivalence_id = uuid.uuid4()
405 else:
406 res = copy.copy(self)
407 res.storage_shape = list(self.storage_shape)
408 res.bandwidth_shape = list(self.bandwidth_shape)
409 if self.quantization is not None:
410 res.quantization = self.quantization.clone()
Tim Hall79d07d22020-04-27 18:20:16 +0100411
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100412 res.name = res.name + suffix
Tim Hall79d07d22020-04-27 18:20:16 +0100413 res.ops = []
414 res.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100415
Tim Hall79d07d22020-04-27 18:20:16 +0100416 return res
417
418 def clone_into_fast_storage(self, arch):
419 res = self.clone(suffix="_fast_storage")
420 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200421 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100422 return res
423
Louis Verhaard3c07c972020-05-07 08:12:58 +0200424 def copy_compressed_weight_info(self, src_tens):
425 # Copies compressed values + all related weight compression info from the given tensor
Louis Verhaard9db529a2020-09-23 10:27:11 +0200426 self.equivalence_id = src_tens.equivalence_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200427 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100428 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200429 self.storage_shape = src_tens.storage_shape
430 self.brick_size = src_tens.brick_size
431 self.weight_compression_scales = src_tens.weight_compression_scales
432 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
433 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
434 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
435 self.storage_compression_scale = src_tens.storage_compression_scale
Diqing Zhong7e1d1d12020-10-30 15:10:46 +0100436 self.bandwidth_compression_scale = src_tens.bandwidth_compression_scale
Louis Verhaard3c07c972020-05-07 08:12:58 +0200437 self.block_traversal = src_tens.block_traversal
438 self.weight_compression_config = src_tens.weight_compression_config
Louis Verhaard9db529a2020-09-23 10:27:11 +0200439 self.value_id = src_tens.value_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200440
Tim Hall79d07d22020-04-27 18:20:16 +0100441 def set_format(self, fmt, arch):
442 self.format = fmt
443 shape_len = 0
444 try:
445 shape_len = len(self.shape)
446 except TypeError:
447 pass
448
Louis Verhaard0411edb2020-11-16 16:37:11 +0100449 if shape_len > 4:
450 return
Tim Hall79d07d22020-04-27 18:20:16 +0100451 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
452 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100453 self.brick_size = arch.brick_sizes[self.format]
454 self.brick_size = self.brick_size[-shape_len:]
455 if self.shape is None:
456 return
457
458 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
459 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
460
461 if fmt == TensorFormat.WeightsCompressed:
462 compression_ratio = 5 / 8
463 self.storage_compression_scale = compression_ratio
464 self.bandwidth_compression_scale = compression_ratio
465 self.compression_scale_for_worst_weight_stream = compression_ratio
466
467 def storage_elements(self):
468 elems = shape_num_elements(self.storage_shape)
469 if elems is None:
470 return 0
471 return elems
472
473 def elements(self):
474 elems = shape_num_elements(self.shape)
475 if elems is None:
476 return 0
477 return elems
478
479 def has_fully_defined_shape(self):
480 return shape_fully_defined(self.shape)
481
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200482 def storage_size(self, scale=1.0):
483 raw_size = self.storage_elements() * self.element_size() * scale
Tim Hall79d07d22020-04-27 18:20:16 +0100484 if raw_size == 0:
485 raw_size = 1 # force it to take up space
486 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
487 return rounded_size
488
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200489 def storage_size_for_sub_purpose(self, arch, sub_purpose, param_a=None, param_b=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100490 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
491 elems = shape_num_elements(alt_shape)
492 if elems is None:
493 return 0
494 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200495 raw_size = (
496 elems
497 * self.element_size()
498 * self.compression_scale_for_worst_weight_stream
499 * arch.weight_estimation_scaling
500 )
Tim Hall79d07d22020-04-27 18:20:16 +0100501 else:
Patrik Gustavsson9baa4c32020-08-20 13:59:01 +0200502 # Rolling buffers are used for intermediate data in ifm streaming
503 # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension
504 if alt_shape[-1] % 16 != 0:
505 nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)]
506 elems = shape_num_elements(nhcwb16_shape)
507
Tim Hall79d07d22020-04-27 18:20:16 +0100508 raw_size = elems * self.element_size() * self.storage_compression_scale
509 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
510 return rounded_size
511
512 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100513 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200514 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100515 assert len(shp) >= 2
516 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100517 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200518 shp = list(self.storage_shape)
519 if sub_purpose == TensorSubPurpose.RollingBufferX:
520 assert len(shp) == 4
521 shp[0] = 1
522 shp[2] = min(shp[2], param_a)
523 elif sub_purpose == TensorSubPurpose.RollingBufferY:
524 assert len(shp) == 4
525 shp[0] = 1
526 shp[1] = min(shp[1], param_a)
527 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
528 assert len(shp) == 4
529 shp[0] = 1
530 shp[2] = min(shp[2], param_a)
531 shp[1] = min(shp[1], param_b)
532 elif sub_purpose == TensorSubPurpose.Standard:
533 pass
534 else:
535 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
536
Tim Hall79d07d22020-04-27 18:20:16 +0100537 return shp
538
539 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
540 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
541 self.sub_purpose = sub_purpose
542 if sub_purpose == TensorSubPurpose.DoubleBuffer:
543 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
544
545 def bandwidth(self):
546 elems = shape_num_elements(self.bandwidth_shape)
547 if elems is None:
548 return 0
549 return elems * self.element_size() * self.bandwidth_compression_scale
550
551 def consumers(self):
552 return self.consumer_list
553
554 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
555 if self.sub_purpose in set(
556 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
557 ):
558 # build dummy coordinates that cover the entire buffer
559 start_coord = [0] * len(start_coord)
560 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
561
562 start = self.address_for_coordinate(start_coord, is_top_box=False)
563 end = self.address_for_coordinate(end_coord, is_top_box=True)
564 return MemoryRangeSet(self.mem_area, start, end)
565
566 def addresses_for_rolling_buffer(self, start_coord, end_coord):
567 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
568
569 if len(start_coord) < 4:
570 box_height0 = 1
571 box_width = 1
572
573 if len(start_coord) >= 2:
574 box_width = end_coord[-2] - start_coord[-2]
575
576 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
577
578 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
579 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
580
581 crossing_y = min(crossing_y, end_coord[1])
582 crossing_x = min(crossing_x, end_coord[2])
583
584 box_height0 = crossing_y - start_coord[1]
585 box_width = crossing_x - start_coord[2]
586
587 addresses = [None] * 4
588 addresses[0] = self.address_for_coordinate(start_coord)
589
590 if end_coord[2] > crossing_x:
591 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
592 raise Exception("Striping in vertical direction is not supported")
593 if end_coord[1] > crossing_y:
594 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
595 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
596 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
597
598 return box_height0, box_height0, box_width, addresses
599
600 def address_for_coordinate(self, coord, is_top_box=False):
601 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
602
603 def get_strides_and_coord(self, coord=None):
604 if coord is None:
605 coord = [0] * len(self.storage_shape)
606
607 augmented_coord = coord
608 augmented_shape = self.storage_shape
609 while len(augmented_shape) < 4:
610 augmented_shape = [1] + augmented_shape
611
612 while len(augmented_coord) < 4:
613 augmented_coord = [0] + augmented_coord
614
615 assert len(augmented_coord) == len(augmented_shape)
616
617 if self.format == TensorFormat.NHWC:
618 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
619 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
620 stride_order = [4, 1, 3, 2, 0]
621
622 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200623 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100624 augmented_shape = augmented_shape[0:4] + [1]
625 augmented_coord = (
626 [augmented_coord[0], augmented_coord[3] // channel_divisor]
627 + augmented_coord[1:3]
628 + [augmented_coord[3] % channel_divisor]
629 )
630
631 if augmented_shape[1] == 0:
632 augmented_shape[1] = 1
633
634 else:
635 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
636 return None, None
637
638 strides = [0] * len(augmented_shape)
639 stride = self.element_size() * self.storage_compression_scale
640
641 if self.format != TensorFormat.NHCWB16:
642 for i in stride_order:
643 strides[i] = stride
644 stride *= augmented_shape[i]
645 else:
646 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100647 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200648 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100649 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200650 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100651 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
652
653 return strides, augmented_coord
654
655 def get_strides(self):
656 strides, _ = self.get_strides_and_coord()
657
658 return strides
659
Louis Verhaard3c07c972020-05-07 08:12:58 +0200660 def needs_dma(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200661 return len(self.ops) == 1 and self.ops[0].type == Op.DMA
Louis Verhaard3c07c972020-05-07 08:12:58 +0200662
663 def get_dma_src_tensor(self):
664 # For weight tensors that need DMA: returns the source tensor in Flash, else None
665 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
666 return self.ops[0].inputs[0] if self.needs_dma() else None
667
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200668 def find_npu_op(self):
669 # Returns the NPU operator that uses this tensor, excluding DMA operators.
670 for op in self.consumers():
Louis Verhaardaee5d752020-09-30 09:01:52 +0200671 if op.type == Op.DMA:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200672 return op.outputs[0].find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200673 if op.run_on_npu:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200674 return op
675 return None
676
Tim Hall79d07d22020-04-27 18:20:16 +0100677 def compressed_stream_index_from_coord(self, coord):
678 assert self.format == TensorFormat.WeightsCompressed
679 assert len(self.compressed_values) > 0
680 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
681
682 depth = coord[-1]
683 brick_depth = self.brick_size[-1]
684 # Clamp position at final element index
685 if depth > self.shape[-1]:
686 depth = self.shape[-1]
687
688 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100689 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100690
691 # Check boundaries on all but last weight set (which may be shorter
692 # than the brick we divided it up into)
693 if index < len(self.weight_compressed_offsets) - 1:
694 # There are no half-way points in the weights
695 if (depth % brick_depth) != 0:
696 raise Exception("Offset into weights must be aligned to a brick")
697
698 return index
699
700 def size_of_compressed_stream(self, index):
701 assert 0 <= index < len(self.compressed_values)
702 return len(self.compressed_values[index])
703
704 def is_last_index_in_compressed_stream(self, index):
705 assert 0 <= index < len(self.compressed_values)
706 return index == len(self.compressed_values) - 1
707
708 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
709 address_offset = 0
710 coord = orig_coord
711
712 coord = coord[-len(self.storage_shape) :]
713
714 if self.sub_purpose == TensorSubPurpose.Standard:
715 for idx, c in enumerate(coord):
716 if is_top_box:
717 assert c > 0 and c <= self.shape[idx]
718 else:
719 assert c >= 0 and c < self.shape[idx]
720
721 if self.format == TensorFormat.WeightsCompressed:
722 if len(self.weight_compressed_offsets) == 0:
723 return 0
724
Louis Verhaard3c07c972020-05-07 08:12:58 +0200725 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100726 depth = orig_coord[-1]
727 brick_depth = self.brick_size[-1]
728 # Clamp position at final element index
729 if depth > self.shape[-1]:
730 depth = self.shape[-1]
731
732 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100733 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100734 index = index % 2
735
736 if len(self.compressed_values) <= 2:
737 if is_top_box and index == 0:
738 for cv in self.compressed_values:
739 address_offset += len(cv)
740 else:
741 address_offset = index * len(self.compressed_values[0])
742 else:
743 if is_top_box and index == 0:
744 address_offset = self.storage_shape[-1]
745 else:
746 address_offset = index * (self.storage_shape[-1] // 2)
747 else:
748 index = self.compressed_stream_index_from_coord(orig_coord)
749 assert index < len(self.weight_compressed_offsets)
750 address_offset = self.weight_compressed_offsets[index]
751 else:
752 if is_top_box:
753 coord = [c - 1 for c in coord]
754
755 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
756 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
757
758 strides, augmented_coord = self.get_strides_and_coord(coord)
759 if strides is None:
760 return None
761
762 if is_top_box:
763 address_offset += 1 * strides[-1] # one element
764
765 address_offset += np.dot(augmented_coord, strides)
766
767 assert address_offset >= 0
768 assert address_offset <= self.storage_size()
769 return address_offset
770
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200771 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
772 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
773 return True
774 return False
775
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200776 def equivalent(self, tens):
777 return self.equivalence_id == tens.equivalence_id
778
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100779 def set_all_shapes(self, shape):
780 self.shape = shape
781 self.storage_shape = shape
782 self.bandwidth_shape = shape
783
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100784 def get_full_shape(self):
785 d = len(self.shape)
786 if d in (1, 3):
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100787 return numeric_util.full_shape(4, self.shape, 1)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100788 elif d == 2:
789 return [self.shape[0], 1, 1, self.shape[1]]
790 else:
Fredrik Svedberg835d8e12020-09-04 09:46:17 +0200791 return self.shape.copy()
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100792
Tim Hall93582962020-09-09 21:58:15 +0100793 def is_quantized(self):
794 # a tensor is quantized if it has an integral type and it contains valid quantization params
795
796 if (self.dtype.type & BaseType.Int) == 0 or self.quantization is None:
797 return False
798
Tim Hall7b1654b2020-10-22 14:22:47 +0100799 assert isinstance(self.quantization, QuantizationParameters)
Tim Hall93582962020-09-09 21:58:15 +0100800 assert self.quantization.is_valid()
801
802 return True
803
Tim Hall79d07d22020-04-27 18:20:16 +0100804 def __str__(self):
805 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
806
807 __repr__ = __str__
Tim Hall93582962020-09-09 21:58:15 +0100808
809
810def check_tens_quantized(tens):
811 # checks that a tensor is quantized
812
813 return isinstance(tens, Tensor) and tens.is_quantized()
814
815
816def check_quantized_tens_scaling_equal(tens_a, tens_b):
817 # checks that the scaling of two quantized tensors are equal
818
819 assert check_tens_quantized(tens_a)
820 assert check_tens_quantized(tens_b)
821
822 return tens_a.quantization.is_scaling_equal(tens_b.quantization)