blob: 49f93cd996f570d0de84ede4b72ea749531569fe [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
84 Size = 5
Tim Hall79d07d22020-04-27 18:20:16 +010085
86 def display_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020087 return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010088
89 def identifier_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020090 return ("unknown", "weights", "feature_map", "scratch", "lut", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010091
92 def all():
93 return (TensorPurpose.Weights, TensorPurpose.FeatureMap)
94
95
96class TensorSubPurpose(enum.Enum):
97 Standard = 0
98 DoubleBuffer = 1
99 RollingBufferX = 2
100 RollingBufferY = 3
101 RollingBufferXY = 4
102
103 def display_name(self):
104 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
105
106 def identifier_name(self):
107 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
108
109 def all():
110 return (
111 TensorSubPurpose.Standard,
112 TensorSubPurpose.DoubleBuffer,
113 TensorSubPurpose.RollingBufferX,
114 TensorSubPurpose.RollingBufferY,
115 TensorSubPurpose.RollingBufferXY,
116 )
117
118
119class TensorFormat(enum.Flag):
120 Unknown = 0
121 WeightsCompressed = 1
122 NHWC = 2
123 NHCWB16 = 3
124
125 def __str__(self):
126 return self.name
127
128
129class TensorBlockTraversal(enum.Enum):
130 Default = 0
131 DepthWise = 1
132 DepthFirst = 2
133 PartKernelFirst = 3
134
135
136def shape_num_elements(shp):
137 elems = 1
138 if shp is None:
139 return None
140 for d in shp:
141 if d is None:
142 return None
143 elems *= d
144 return elems
145
146
147def shape_fully_defined(shp):
148 if shp is None:
149 return False
150 for d in shp:
151 if d is None:
152 return False
153 return True
154
155
156def shape_round_to_quantum(shp, quantum):
157 new_shp = list(shp)
158
159 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
160 for i in range(-1, -len(shp) - 1, -1):
161 if new_shp[i] is not None:
162 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
163 return new_shp
164
165
Louis Verhaard9db529a2020-09-23 10:27:11 +0200166@lru_cache(maxsize=None)
167def create_equivalence_id(key):
168 # Generates equivalence_id based on the given key.
169 return uuid.uuid4()
170
171
Tim Hall79d07d22020-04-27 18:20:16 +0100172class QuantizationParameters:
173 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
174
175 def __init__(self, min=None, max=None, num_bits=None, narrow_range=None):
176 self.min = min
177 self.max = max
178
179 self.num_bits = num_bits
180 self.narrow_range = narrow_range
181
182 self.scale_f32 = None
183 self.zero_point = None
184 self.quant_min = None
185 self.quant_max = None
186
187 def __str__(self):
188 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
189 self.min,
190 self.max,
191 self.num_bits,
192 self.scale_f32,
193 self.zero_point,
194 )
195
196 __repr__ = __str__
197
198 def clone(self):
199 res = QuantizationParameters()
200 res.min = self.min
201 res.max = self.max
202
203 res.num_bits = self.num_bits
204 res.narrow_range = self.narrow_range
205
206 res.scale_f32 = self.scale_f32
207 res.zero_point = self.zero_point
208 res.quant_min = self.quant_min
209 res.quant_max = self.quant_max
210 return res
211
212 def dequantize(self, values):
213 if self.zero_point.size == 1 and self.scale_f32.size == 1:
214 # same scale is used for all values
215 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
216 else:
217 # a different scale is used for different sets of values
218 values_as_float = values.astype(np.float64)
219
220 # this is not compatible with the format of depthwise weights,
221 # where input is at index 3 (Output, Kh, Kw, Input)
222 # return the quantized values
223 return np.ndarray((values_as_float.shape))
224
225 shape = values_as_float.shape[0]
226 assert self.zero_point.size == self.scale_f32.size == shape
227 res = np.ndarray(values_as_float.shape)
228 for i in range(shape):
229 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
230
231 return res
232
Tim Halle3786ac2020-07-28 17:40:50 +0100233 def is_scaling_equal(self, other):
Tim Hall93582962020-09-09 21:58:15 +0100234 # quantisation parameter scaling is not equal if 'other' is None because
235 # it implies that the tensor it belongs to is not quantised. otherwise,
236 # it depends upon whether the scale and zero point are equal
237
238 if other is None:
Tim Halle3786ac2020-07-28 17:40:50 +0100239 return False
240
Tim Hall93582962020-09-09 21:58:15 +0100241 assert isinstance(other, QuantizationParameters)
242
Tim Halle3786ac2020-07-28 17:40:50 +0100243 return self.scale_f32 == other.scale_f32 and self.zero_point == other.zero_point
244
Tim Hall93582962020-09-09 21:58:15 +0100245 def is_valid(self):
246 # quantisation parameters are consider valid if they have a scale and zero point
247
248 return None not in (self.scale_f32, self.zero_point)
249
Tim Hall79d07d22020-04-27 18:20:16 +0100250
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100251def create_const_tensor(name, shape, dtype, values, value_dtype=None, purpose=TensorPurpose.Unknown, quantization=None):
252 # Tensor
253 const_tensor = Tensor(shape, dtype, name + "_0")
254 const_tensor.purpose = purpose
255 const_tensor.quantization = quantization
256 const_tensor.values = np.array(values, dtype=value_dtype)
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200257 const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100258 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200259 const_op = Operation(Op.Const, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100260 const_op.set_output_tensor(const_tensor)
261 return const_tensor
262
263
264def create_reshape_tensor(tens, shape, ifm_reshape=True):
265 if shape == tens.shape:
266 return tens
267 # Tensors
268 name = tens.name + "_reshape"
269 reshape_ifm = tens
270 reshape_ofm = tens.clone("_reshaped")
271 reshape_ofm.set_all_shapes(shape)
272 if not ifm_reshape:
273 reshape_ifm, reshape_ofm = reshape_ofm, reshape_ifm
274 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200275 reshape_op = Operation(Op.Reshape, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100276 reshape_op.attrs["new_shape"] = shape
277 reshape_op.add_input_tensor(reshape_ifm)
278 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, shape))
279 reshape_op.set_output_tensor(reshape_ofm)
280 return reshape_ofm if ifm_reshape else reshape_ifm
281
282
Jacob Bohlin1a666972020-09-11 10:04:15 +0200283# class that keeps track of all tensor addresses in the different memory types
284class TensorAddressMap:
285 address_map = defaultdict(dict) # dict (tens.equivalence_id -> dict (mem_type -> address))
286
287 @classmethod
288 def get_address_for_tens(cls, tens_id, mem_type):
289 return cls.address_map[tens_id].get(mem_type)
290
291 @classmethod
292 def set_address_for_tens(cls, tens_id, mem_type, address):
293 # Check previous address if there is one
294 previous_address = cls.address_map[tens_id].get(mem_type)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200295 if address is not None and previous_address is not None:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200296 assert previous_address == address, "Two different addresses cannot be assigned to the same tensor."
297
298 # Set tensor's address for memory type
299 cls.address_map[tens_id][mem_type] = address
300
301
Tim Hall79d07d22020-04-27 18:20:16 +0100302class Tensor:
303 __slots__ = (
304 "shape",
305 "storage_shape",
306 "bandwidth_shape",
307 "dtype",
308 "name",
309 "ops",
310 "consumer_list",
311 "values",
312 "quant_values",
313 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100314 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100315 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200316 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100317 "format",
318 "purpose",
319 "sub_purpose",
320 "alignment",
321 "weight_transpose_depthwise",
322 "storage_compression_scale",
323 "bandwidth_compression_scale",
324 "compression_scale_for_worst_weight_stream",
325 "weight_compression_scales",
326 "weight_compression_config",
Louis Verhaard9db529a2020-09-23 10:27:11 +0200327 "value_id",
Tim Hall79d07d22020-04-27 18:20:16 +0100328 "storage_rounding_quantum",
329 "brick_size",
Tim Hall79d07d22020-04-27 18:20:16 +0100330 "quantization",
331 "weight_compressed_offsets",
332 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100333 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100334 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200335 "resampling_mode",
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200336 "avoid_NHCWB16",
Tim Hall79d07d22020-04-27 18:20:16 +0100337 )
338 AllocationQuantum = 16
339
340 def __init__(self, shape, dtype, name):
341 self.shape = shape
342 self.storage_shape = shape
343 self.bandwidth_shape = shape
344 self.dtype = dtype
345 self.name = name
346 self.equivalence_id = uuid.uuid4()
347
348 self.ops = []
349 self.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100350
351 self.values = None
352 self.quant_values = None
353 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100354 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100355 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200356 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100357 self.format = TensorFormat.Unknown
358 self.purpose = TensorPurpose.Unknown
359 self.sub_purpose = TensorSubPurpose.Standard
360 self.alignment = Tensor.AllocationQuantum
361 self.weight_transpose_depthwise = False
362
363 self.storage_compression_scale = 1.0
364 self.bandwidth_compression_scale = 1.0
365 self.compression_scale_for_worst_weight_stream = 1.0
366 self.weight_compression_scales = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200367 # if two tensors have the same weight_compression_config, then they have the same compressed values
Tim Hall79d07d22020-04-27 18:20:16 +0100368 self.weight_compression_config = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200369 # if two tensors have the same value_id, then they have the same values
370 self.value_id = uuid.uuid4()
Tim Hall79d07d22020-04-27 18:20:16 +0100371 self.weight_compressed_offsets = []
372 self.storage_rounding_quantum = (1, 1, 1, 1)
373 self.brick_size = (1, 1, 1, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100374 self.element_size_bytes = 0
375
376 # quantization parameters
377 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100378 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200379 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100380
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200381 self.avoid_NHCWB16 = False
382
Jacob Bohlin1a666972020-09-11 10:04:15 +0200383 @property
384 def address(self):
385 return TensorAddressMap.get_address_for_tens(self.equivalence_id, self.mem_type)
386
387 @address.setter
388 def address(self, address):
389 TensorAddressMap.set_address_for_tens(self.equivalence_id, self.mem_type, address)
390
Tim Hall79d07d22020-04-27 18:20:16 +0100391 def element_size(self):
392 if self.element_size_bytes == 0:
393 return self.dtype.size_in_bits() / 8
394 return self.element_size_bytes
395
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100396 # Returns a copy, renamed to self.name + suffix
397 # The references to Operators will be empty when returned
398 # Depending on set_unique, the copy is shallow, or deep
399 # For set_unique==True, a new equivalence_id will be set
400 def clone(self, suffix="_clone", set_unique=False):
401 if set_unique:
402 res = copy.deepcopy(self)
403 res.equivalence_id = uuid.uuid4()
404 else:
405 res = copy.copy(self)
406 res.storage_shape = list(self.storage_shape)
407 res.bandwidth_shape = list(self.bandwidth_shape)
408 if self.quantization is not None:
409 res.quantization = self.quantization.clone()
Tim Hall79d07d22020-04-27 18:20:16 +0100410
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100411 res.name = res.name + suffix
Tim Hall79d07d22020-04-27 18:20:16 +0100412 res.ops = []
413 res.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100414
Tim Hall79d07d22020-04-27 18:20:16 +0100415 return res
416
417 def clone_into_fast_storage(self, arch):
418 res = self.clone(suffix="_fast_storage")
419 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200420 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100421 return res
422
Louis Verhaard3c07c972020-05-07 08:12:58 +0200423 def copy_compressed_weight_info(self, src_tens):
424 # Copies compressed values + all related weight compression info from the given tensor
Louis Verhaard9db529a2020-09-23 10:27:11 +0200425 self.equivalence_id = src_tens.equivalence_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200426 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100427 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200428 self.storage_shape = src_tens.storage_shape
429 self.brick_size = src_tens.brick_size
430 self.weight_compression_scales = src_tens.weight_compression_scales
431 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
432 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
433 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
434 self.storage_compression_scale = src_tens.storage_compression_scale
Diqing Zhong7e1d1d12020-10-30 15:10:46 +0100435 self.bandwidth_compression_scale = src_tens.bandwidth_compression_scale
Louis Verhaard3c07c972020-05-07 08:12:58 +0200436 self.block_traversal = src_tens.block_traversal
437 self.weight_compression_config = src_tens.weight_compression_config
Louis Verhaard9db529a2020-09-23 10:27:11 +0200438 self.value_id = src_tens.value_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200439
Tim Hall79d07d22020-04-27 18:20:16 +0100440 def set_format(self, fmt, arch):
441 self.format = fmt
442 shape_len = 0
443 try:
444 shape_len = len(self.shape)
445 except TypeError:
446 pass
447
448 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
449 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100450 self.brick_size = arch.brick_sizes[self.format]
451 self.brick_size = self.brick_size[-shape_len:]
452 if self.shape is None:
453 return
454
455 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
456 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
457
458 if fmt == TensorFormat.WeightsCompressed:
459 compression_ratio = 5 / 8
460 self.storage_compression_scale = compression_ratio
461 self.bandwidth_compression_scale = compression_ratio
462 self.compression_scale_for_worst_weight_stream = compression_ratio
463
464 def storage_elements(self):
465 elems = shape_num_elements(self.storage_shape)
466 if elems is None:
467 return 0
468 return elems
469
470 def elements(self):
471 elems = shape_num_elements(self.shape)
472 if elems is None:
473 return 0
474 return elems
475
476 def has_fully_defined_shape(self):
477 return shape_fully_defined(self.shape)
478
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200479 def storage_size(self, scale=1.0):
480 raw_size = self.storage_elements() * self.element_size() * scale
Tim Hall79d07d22020-04-27 18:20:16 +0100481 if raw_size == 0:
482 raw_size = 1 # force it to take up space
483 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
484 return rounded_size
485
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200486 def storage_size_for_sub_purpose(self, arch, sub_purpose, param_a=None, param_b=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100487 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
488 elems = shape_num_elements(alt_shape)
489 if elems is None:
490 return 0
491 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200492 raw_size = (
493 elems
494 * self.element_size()
495 * self.compression_scale_for_worst_weight_stream
496 * arch.weight_estimation_scaling
497 )
Tim Hall79d07d22020-04-27 18:20:16 +0100498 else:
Patrik Gustavsson9baa4c32020-08-20 13:59:01 +0200499 # Rolling buffers are used for intermediate data in ifm streaming
500 # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension
501 if alt_shape[-1] % 16 != 0:
502 nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)]
503 elems = shape_num_elements(nhcwb16_shape)
504
Tim Hall79d07d22020-04-27 18:20:16 +0100505 raw_size = elems * self.element_size() * self.storage_compression_scale
506 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
507 return rounded_size
508
509 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100510 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200511 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100512 assert len(shp) >= 2
513 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100514 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200515 shp = list(self.storage_shape)
516 if sub_purpose == TensorSubPurpose.RollingBufferX:
517 assert len(shp) == 4
518 shp[0] = 1
519 shp[2] = min(shp[2], param_a)
520 elif sub_purpose == TensorSubPurpose.RollingBufferY:
521 assert len(shp) == 4
522 shp[0] = 1
523 shp[1] = min(shp[1], param_a)
524 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
525 assert len(shp) == 4
526 shp[0] = 1
527 shp[2] = min(shp[2], param_a)
528 shp[1] = min(shp[1], param_b)
529 elif sub_purpose == TensorSubPurpose.Standard:
530 pass
531 else:
532 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
533
Tim Hall79d07d22020-04-27 18:20:16 +0100534 return shp
535
536 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
537 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
538 self.sub_purpose = sub_purpose
539 if sub_purpose == TensorSubPurpose.DoubleBuffer:
540 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
541
542 def bandwidth(self):
543 elems = shape_num_elements(self.bandwidth_shape)
544 if elems is None:
545 return 0
546 return elems * self.element_size() * self.bandwidth_compression_scale
547
548 def consumers(self):
549 return self.consumer_list
550
551 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
552 if self.sub_purpose in set(
553 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
554 ):
555 # build dummy coordinates that cover the entire buffer
556 start_coord = [0] * len(start_coord)
557 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
558
559 start = self.address_for_coordinate(start_coord, is_top_box=False)
560 end = self.address_for_coordinate(end_coord, is_top_box=True)
561 return MemoryRangeSet(self.mem_area, start, end)
562
563 def addresses_for_rolling_buffer(self, start_coord, end_coord):
564 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
565
566 if len(start_coord) < 4:
567 box_height0 = 1
568 box_width = 1
569
570 if len(start_coord) >= 2:
571 box_width = end_coord[-2] - start_coord[-2]
572
573 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
574
575 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
576 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
577
578 crossing_y = min(crossing_y, end_coord[1])
579 crossing_x = min(crossing_x, end_coord[2])
580
581 box_height0 = crossing_y - start_coord[1]
582 box_width = crossing_x - start_coord[2]
583
584 addresses = [None] * 4
585 addresses[0] = self.address_for_coordinate(start_coord)
586
587 if end_coord[2] > crossing_x:
588 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
589 raise Exception("Striping in vertical direction is not supported")
590 if end_coord[1] > crossing_y:
591 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
592 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
593 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
594
595 return box_height0, box_height0, box_width, addresses
596
597 def address_for_coordinate(self, coord, is_top_box=False):
598 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
599
600 def get_strides_and_coord(self, coord=None):
601 if coord is None:
602 coord = [0] * len(self.storage_shape)
603
604 augmented_coord = coord
605 augmented_shape = self.storage_shape
606 while len(augmented_shape) < 4:
607 augmented_shape = [1] + augmented_shape
608
609 while len(augmented_coord) < 4:
610 augmented_coord = [0] + augmented_coord
611
612 assert len(augmented_coord) == len(augmented_shape)
613
614 if self.format == TensorFormat.NHWC:
615 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
616 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
617 stride_order = [4, 1, 3, 2, 0]
618
619 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200620 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100621 augmented_shape = augmented_shape[0:4] + [1]
622 augmented_coord = (
623 [augmented_coord[0], augmented_coord[3] // channel_divisor]
624 + augmented_coord[1:3]
625 + [augmented_coord[3] % channel_divisor]
626 )
627
628 if augmented_shape[1] == 0:
629 augmented_shape[1] = 1
630
631 else:
632 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
633 return None, None
634
635 strides = [0] * len(augmented_shape)
636 stride = self.element_size() * self.storage_compression_scale
637
638 if self.format != TensorFormat.NHCWB16:
639 for i in stride_order:
640 strides[i] = stride
641 stride *= augmented_shape[i]
642 else:
643 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100644 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200645 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100646 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200647 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100648 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
649
650 return strides, augmented_coord
651
652 def get_strides(self):
653 strides, _ = self.get_strides_and_coord()
654
655 return strides
656
Louis Verhaard3c07c972020-05-07 08:12:58 +0200657 def needs_dma(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200658 return len(self.ops) == 1 and self.ops[0].type == Op.DMA
Louis Verhaard3c07c972020-05-07 08:12:58 +0200659
660 def get_dma_src_tensor(self):
661 # For weight tensors that need DMA: returns the source tensor in Flash, else None
662 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
663 return self.ops[0].inputs[0] if self.needs_dma() else None
664
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200665 def find_npu_op(self):
666 # Returns the NPU operator that uses this tensor, excluding DMA operators.
667 for op in self.consumers():
Louis Verhaardaee5d752020-09-30 09:01:52 +0200668 if op.type == Op.DMA:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200669 return op.outputs[0].find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200670 if op.run_on_npu:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200671 return op
672 return None
673
Tim Hall79d07d22020-04-27 18:20:16 +0100674 def compressed_stream_index_from_coord(self, coord):
675 assert self.format == TensorFormat.WeightsCompressed
676 assert len(self.compressed_values) > 0
677 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
678
679 depth = coord[-1]
680 brick_depth = self.brick_size[-1]
681 # Clamp position at final element index
682 if depth > self.shape[-1]:
683 depth = self.shape[-1]
684
685 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100686 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100687
688 # Check boundaries on all but last weight set (which may be shorter
689 # than the brick we divided it up into)
690 if index < len(self.weight_compressed_offsets) - 1:
691 # There are no half-way points in the weights
692 if (depth % brick_depth) != 0:
693 raise Exception("Offset into weights must be aligned to a brick")
694
695 return index
696
697 def size_of_compressed_stream(self, index):
698 assert 0 <= index < len(self.compressed_values)
699 return len(self.compressed_values[index])
700
701 def is_last_index_in_compressed_stream(self, index):
702 assert 0 <= index < len(self.compressed_values)
703 return index == len(self.compressed_values) - 1
704
705 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
706 address_offset = 0
707 coord = orig_coord
708
709 coord = coord[-len(self.storage_shape) :]
710
711 if self.sub_purpose == TensorSubPurpose.Standard:
712 for idx, c in enumerate(coord):
713 if is_top_box:
714 assert c > 0 and c <= self.shape[idx]
715 else:
716 assert c >= 0 and c < self.shape[idx]
717
718 if self.format == TensorFormat.WeightsCompressed:
719 if len(self.weight_compressed_offsets) == 0:
720 return 0
721
Louis Verhaard3c07c972020-05-07 08:12:58 +0200722 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100723 depth = orig_coord[-1]
724 brick_depth = self.brick_size[-1]
725 # Clamp position at final element index
726 if depth > self.shape[-1]:
727 depth = self.shape[-1]
728
729 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100730 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100731 index = index % 2
732
733 if len(self.compressed_values) <= 2:
734 if is_top_box and index == 0:
735 for cv in self.compressed_values:
736 address_offset += len(cv)
737 else:
738 address_offset = index * len(self.compressed_values[0])
739 else:
740 if is_top_box and index == 0:
741 address_offset = self.storage_shape[-1]
742 else:
743 address_offset = index * (self.storage_shape[-1] // 2)
744 else:
745 index = self.compressed_stream_index_from_coord(orig_coord)
746 assert index < len(self.weight_compressed_offsets)
747 address_offset = self.weight_compressed_offsets[index]
748 else:
749 if is_top_box:
750 coord = [c - 1 for c in coord]
751
752 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
753 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
754
755 strides, augmented_coord = self.get_strides_and_coord(coord)
756 if strides is None:
757 return None
758
759 if is_top_box:
760 address_offset += 1 * strides[-1] # one element
761
762 address_offset += np.dot(augmented_coord, strides)
763
764 assert address_offset >= 0
765 assert address_offset <= self.storage_size()
766 return address_offset
767
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200768 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
769 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
770 return True
771 return False
772
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200773 def equivalent(self, tens):
774 return self.equivalence_id == tens.equivalence_id
775
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100776 def set_all_shapes(self, shape):
777 self.shape = shape
778 self.storage_shape = shape
779 self.bandwidth_shape = shape
780
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100781 def get_full_shape(self):
782 d = len(self.shape)
783 if d in (1, 3):
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100784 return numeric_util.full_shape(4, self.shape, 1)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100785 elif d == 2:
786 return [self.shape[0], 1, 1, self.shape[1]]
787 else:
Fredrik Svedberg835d8e12020-09-04 09:46:17 +0200788 return self.shape.copy()
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100789
Tim Hall93582962020-09-09 21:58:15 +0100790 def is_quantized(self):
791 # a tensor is quantized if it has an integral type and it contains valid quantization params
792
793 if (self.dtype.type & BaseType.Int) == 0 or self.quantization is None:
794 return False
795
Tim Hall7b1654b2020-10-22 14:22:47 +0100796 assert isinstance(self.quantization, QuantizationParameters)
Tim Hall93582962020-09-09 21:58:15 +0100797 assert self.quantization.is_valid()
798
799 return True
800
Tim Hall79d07d22020-04-27 18:20:16 +0100801 def __str__(self):
802 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
803
804 __repr__ = __str__
Tim Hall93582962020-09-09 21:58:15 +0100805
806
807def check_tens_quantized(tens):
808 # checks that a tensor is quantized
809
810 return isinstance(tens, Tensor) and tens.is_quantized()
811
812
813def check_quantized_tens_scaling_equal(tens_a, tens_b):
814 # checks that the scaling of two quantized tensors are equal
815
816 assert check_tens_quantized(tens_a)
817 assert check_tens_quantized(tens_b)
818
819 return tens_a.quantization.is_scaling_equal(tens_b.quantization)