blob: df8f8868d3237306239f7e696f8e58b195192768 [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
Diqing Zhongf842b692020-12-11 13:07:37 +010022from enum import auto
Louis Verhaard9db529a2020-09-23 10:27:11 +020023from functools import lru_cache
Louis Verhaard6c74c3b2020-12-17 13:54:09 +010024from functools import total_ordering
Louis Verhaard93719a92020-12-08 10:02:31 +010025from typing import Dict
26from typing import List
27from typing import Optional
28from typing import Tuple
29from typing import Union
30from uuid import UUID
Diego Russoea6111a2020-04-14 18:41:58 +010031
32import numpy as np
33
34from . import numeric_util
Tim Hall93582962020-09-09 21:58:15 +010035from .data_type import BaseType
Michael McGeagh5778ffd2020-08-06 17:31:02 +010036from .data_type import DataType
Michael McGeagh528a56d2020-12-16 11:33:21 +000037from .errors import UnsupportedFeatureError
38from .errors import VelaError
Dwight Lidmana9390f72020-05-13 12:00:08 +020039from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Patrik Gustavsson2349d422020-12-01 16:02:29 +010040from .numeric_util import full_shape
Louis Verhaardaee5d752020-09-30 09:01:52 +020041from .operation import Op
Michael McGeagh5778ffd2020-08-06 17:31:02 +010042from .operation import Operation
Louis Verhaard93719a92020-12-08 10:02:31 +010043
44Shape = List
Tim Hall79d07d22020-04-27 18:20:16 +010045
46
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020047class MemType(enum.IntFlag):
48 Unknown = 0
49 Permanent_NPU = 1
50 Permanent_CPU = 2
51 Scratch = 3
52 Scratch_fast = 4
53 Size = Scratch_fast + 1
54
Louis Verhaard93719a92020-12-08 10:02:31 +010055 def display_name(self) -> str:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020056 return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value]
57
Louis Verhaard93719a92020-12-08 10:02:31 +010058 def identifier_name(self) -> str:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020059 return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value]
60
Louis Verhaard93719a92020-12-08 10:02:31 +010061 @staticmethod
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020062 def all():
63 return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast)
64
65 def __str__(self):
66 return self.name
67
68
Diqing Zhongf842b692020-12-11 13:07:37 +010069class BandwidthDirection(enum.IntEnum):
70 Read = 0
71 Write = auto()
72 Size = auto()
73
74 def display_name(self):
75 return self.name
76
77 def identifier_name(self):
78 return self.name.lower()
79
80 @staticmethod
81 def all():
82 return (BandwidthDirection.Read, BandwidthDirection.Write)
83
84
Tim Hall79d07d22020-04-27 18:20:16 +010085class MemArea(enum.IntFlag):
86 Unknown = 0
87 Sram = 1
88 Dram = 2
89 OnChipFlash = 3
90 OffChipFlash = 4
Louis Verhaard0b8268a2020-08-05 16:11:29 +020091 Shram = 5 # for LUT
92 Size = Shram + 1
Tim Hall79d07d22020-04-27 18:20:16 +010093
Louis Verhaard93719a92020-12-08 10:02:31 +010094 def display_name(self) -> str:
Louis Verhaard0b8268a2020-08-05 16:11:29 +020095 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "SHRAM", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010096
Louis Verhaard93719a92020-12-08 10:02:31 +010097 def identifier_name(self) -> str:
Louis Verhaard0b8268a2020-08-05 16:11:29 +020098 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "shram", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010099
Louis Verhaard93719a92020-12-08 10:02:31 +0100100 @staticmethod
Tim Hall79d07d22020-04-27 18:20:16 +0100101 def all():
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200102 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash, MemArea.Shram)
Tim Hall79d07d22020-04-27 18:20:16 +0100103
104 def __str__(self):
105 return self.name
106
107
108class TensorPurpose(enum.IntFlag):
109 Unknown = 0
110 Weights = 1
111 FeatureMap = 2
112 Scratch = 3
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200113 LUT = 4
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100114 FSBias = 5
115 Size = 6
Tim Hall79d07d22020-04-27 18:20:16 +0100116
Louis Verhaard93719a92020-12-08 10:02:31 +0100117 def display_name(self) -> str:
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100118 return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "FastStorageBias", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +0100119
Louis Verhaard93719a92020-12-08 10:02:31 +0100120 def identifier_name(self) -> str:
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100121 return ("unknown", "weights", "feature_map", "scratch", "lut", "fast_storage_bias", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +0100122
Louis Verhaard93719a92020-12-08 10:02:31 +0100123 @staticmethod
Tim Hall79d07d22020-04-27 18:20:16 +0100124 def all():
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100125 return (TensorPurpose.Weights, TensorPurpose.FeatureMap, TensorPurpose.FSBias)
Tim Hall79d07d22020-04-27 18:20:16 +0100126
127
128class TensorSubPurpose(enum.Enum):
129 Standard = 0
130 DoubleBuffer = 1
131 RollingBufferX = 2
132 RollingBufferY = 3
133 RollingBufferXY = 4
134
Louis Verhaard93719a92020-12-08 10:02:31 +0100135 def display_name(self) -> str:
Tim Hall79d07d22020-04-27 18:20:16 +0100136 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
137
Louis Verhaard93719a92020-12-08 10:02:31 +0100138 def identifier_name(self) -> str:
Tim Hall79d07d22020-04-27 18:20:16 +0100139 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
140
Louis Verhaard93719a92020-12-08 10:02:31 +0100141 @staticmethod
Tim Hall79d07d22020-04-27 18:20:16 +0100142 def all():
143 return (
144 TensorSubPurpose.Standard,
145 TensorSubPurpose.DoubleBuffer,
146 TensorSubPurpose.RollingBufferX,
147 TensorSubPurpose.RollingBufferY,
148 TensorSubPurpose.RollingBufferXY,
149 )
150
151
152class TensorFormat(enum.Flag):
153 Unknown = 0
154 WeightsCompressed = 1
155 NHWC = 2
156 NHCWB16 = 3
157
158 def __str__(self):
159 return self.name
160
161
162class TensorBlockTraversal(enum.Enum):
163 Default = 0
164 DepthWise = 1
165 DepthFirst = 2
166 PartKernelFirst = 3
167
168
Louis Verhaard93719a92020-12-08 10:02:31 +0100169def shape_num_elements(shp: Shape) -> Optional[int]:
Tim Hall79d07d22020-04-27 18:20:16 +0100170 elems = 1
171 if shp is None:
172 return None
173 for d in shp:
174 if d is None:
175 return None
176 elems *= d
177 return elems
178
179
Louis Verhaard93719a92020-12-08 10:02:31 +0100180def shape_fully_defined(shp: Shape) -> bool:
Tim Hall79d07d22020-04-27 18:20:16 +0100181 if shp is None:
182 return False
183 for d in shp:
184 if d is None:
185 return False
186 return True
187
188
Louis Verhaard93719a92020-12-08 10:02:31 +0100189def shape_round_to_quantum(shp: Shape, quantum: Tuple) -> Shape:
Tim Hall79d07d22020-04-27 18:20:16 +0100190 new_shp = list(shp)
191
192 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
193 for i in range(-1, -len(shp) - 1, -1):
194 if new_shp[i] is not None:
195 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
196 return new_shp
197
198
Louis Verhaard9db529a2020-09-23 10:27:11 +0200199@lru_cache(maxsize=None)
Louis Verhaard93719a92020-12-08 10:02:31 +0100200def create_equivalence_id(key) -> UUID:
Louis Verhaard9db529a2020-09-23 10:27:11 +0200201 # Generates equivalence_id based on the given key.
202 return uuid.uuid4()
203
204
Tim Hall79d07d22020-04-27 18:20:16 +0100205class QuantizationParameters:
206 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
207
Louis Verhaard93719a92020-12-08 10:02:31 +0100208 def __init__(
209 self,
210 min: Union[float, np.ndarray, None] = None,
211 max: Union[float, np.ndarray, None] = None,
212 num_bits=None,
213 narrow_range=None,
214 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100215 self.min = min
216 self.max = max
217
218 self.num_bits = num_bits
219 self.narrow_range = narrow_range
220
Louis Verhaard93719a92020-12-08 10:02:31 +0100221 self.scale_f32: Union[float, np.ndarray, None] = None
222 self.zero_point: Union[int, np.ndarray, None] = None
223 self.quant_min: Optional[float] = None
224 self.quant_max: Optional[float] = None
Tim Hall79d07d22020-04-27 18:20:16 +0100225
226 def __str__(self):
227 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
228 self.min,
229 self.max,
230 self.num_bits,
231 self.scale_f32,
232 self.zero_point,
233 )
234
235 __repr__ = __str__
236
Louis Verhaard93719a92020-12-08 10:02:31 +0100237 def clone(self) -> "QuantizationParameters":
Tim Hall79d07d22020-04-27 18:20:16 +0100238 res = QuantizationParameters()
239 res.min = self.min
240 res.max = self.max
241
242 res.num_bits = self.num_bits
243 res.narrow_range = self.narrow_range
244
245 res.scale_f32 = self.scale_f32
246 res.zero_point = self.zero_point
247 res.quant_min = self.quant_min
248 res.quant_max = self.quant_max
249 return res
250
251 def dequantize(self, values):
252 if self.zero_point.size == 1 and self.scale_f32.size == 1:
253 # same scale is used for all values
254 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
255 else:
256 # a different scale is used for different sets of values
257 values_as_float = values.astype(np.float64)
258
259 # this is not compatible with the format of depthwise weights,
260 # where input is at index 3 (Output, Kh, Kw, Input)
261 # return the quantized values
262 return np.ndarray((values_as_float.shape))
263
Tim Hall79d07d22020-04-27 18:20:16 +0100264 return res
265
Louis Verhaard93719a92020-12-08 10:02:31 +0100266 def is_scaling_equal(self, other: Optional["QuantizationParameters"]) -> bool:
Tim Hall93582962020-09-09 21:58:15 +0100267 # quantisation parameter scaling is not equal if 'other' is None because
268 # it implies that the tensor it belongs to is not quantised. otherwise,
269 # it depends upon whether the scale and zero point are equal
270
Tim Hall89567612020-10-27 11:57:57 +0000271 if not isinstance(other, QuantizationParameters):
Tim Halle3786ac2020-07-28 17:40:50 +0100272 return False
273
274 return self.scale_f32 == other.scale_f32 and self.zero_point == other.zero_point
275
Louis Verhaard93719a92020-12-08 10:02:31 +0100276 def is_valid(self) -> bool:
Tim Hall93582962020-09-09 21:58:15 +0100277 # quantisation parameters are consider valid if they have a scale and zero point
278
279 return None not in (self.scale_f32, self.zero_point)
280
Louis Verhaard93719a92020-12-08 10:02:31 +0100281 def is_per_axis(self) -> bool:
Dwight Lidmanc7187432020-11-16 17:40:46 +0100282 """Returns True if either the scale, zero point, minimum or maximum values are arrays"""
283 for attr in ("scale_f32", "zero_point", "min", "max"):
284 if isinstance(getattr(self, attr), np.ndarray):
285 return True
286 return False
287
Tim Hall79d07d22020-04-27 18:20:16 +0100288
Louis Verhaard93719a92020-12-08 10:02:31 +0100289def create_const_tensor(
290 name: str,
291 shape: Shape,
292 dtype: DataType,
293 values: np.ndarray,
294 value_dtype: np.dtype = None,
295 purpose: TensorPurpose = TensorPurpose.Unknown,
296 quantization: QuantizationParameters = None,
297):
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100298 # Tensor
299 const_tensor = Tensor(shape, dtype, name + "_0")
300 const_tensor.purpose = purpose
301 const_tensor.quantization = quantization
302 const_tensor.values = np.array(values, dtype=value_dtype)
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200303 const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100304 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200305 const_op = Operation(Op.Const, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100306 const_op.set_output_tensor(const_tensor)
307 return const_tensor
308
309
310def create_reshape_tensor(tens, shape, ifm_reshape=True):
311 if shape == tens.shape:
312 return tens
313 # Tensors
314 name = tens.name + "_reshape"
315 reshape_ifm = tens
316 reshape_ofm = tens.clone("_reshaped")
317 reshape_ofm.set_all_shapes(shape)
318 if not ifm_reshape:
319 reshape_ifm, reshape_ofm = reshape_ofm, reshape_ifm
320 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200321 reshape_op = Operation(Op.Reshape, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100322 reshape_op.attrs["new_shape"] = shape
323 reshape_op.add_input_tensor(reshape_ifm)
324 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, shape))
325 reshape_op.set_output_tensor(reshape_ofm)
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100326 reshape_op.ifm_shapes.append(full_shape(4, reshape_ifm.shape, 1))
327 reshape_op.ofm_shapes.append(full_shape(4, reshape_ofm.shape, 1))
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100328 return reshape_ofm if ifm_reshape else reshape_ifm
329
330
Jacob Bohlin1a666972020-09-11 10:04:15 +0200331# class that keeps track of all tensor addresses in the different memory types
332class TensorAddressMap:
Louis Verhaard93719a92020-12-08 10:02:31 +0100333 address_map: Dict = defaultdict(dict) # dict (tens.equivalence_id -> dict (mem_type -> address))
Jacob Bohlin1a666972020-09-11 10:04:15 +0200334
335 @classmethod
Louis Verhaard93719a92020-12-08 10:02:31 +0100336 def get_address_for_tens(cls, tens_id: UUID, mem_type: MemType) -> int:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200337 return cls.address_map[tens_id].get(mem_type)
338
339 @classmethod
Louis Verhaard93719a92020-12-08 10:02:31 +0100340 def set_address_for_tens(cls, tens_id: UUID, mem_type: MemType, address: int):
Jacob Bohlin1a666972020-09-11 10:04:15 +0200341 # Check previous address if there is one
342 previous_address = cls.address_map[tens_id].get(mem_type)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200343 if address is not None and previous_address is not None:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200344 assert previous_address == address, "Two different addresses cannot be assigned to the same tensor."
345
346 # Set tensor's address for memory type
347 cls.address_map[tens_id][mem_type] = address
348
349
Louis Verhaard6c74c3b2020-12-17 13:54:09 +0100350@total_ordering
Tim Hall79d07d22020-04-27 18:20:16 +0100351class Tensor:
352 __slots__ = (
353 "shape",
354 "storage_shape",
355 "bandwidth_shape",
356 "dtype",
357 "name",
358 "ops",
359 "consumer_list",
360 "values",
361 "quant_values",
362 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100363 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100364 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200365 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100366 "format",
367 "purpose",
368 "sub_purpose",
369 "alignment",
370 "weight_transpose_depthwise",
371 "storage_compression_scale",
372 "bandwidth_compression_scale",
373 "compression_scale_for_worst_weight_stream",
374 "weight_compression_scales",
375 "weight_compression_config",
Louis Verhaard9db529a2020-09-23 10:27:11 +0200376 "value_id",
Tim Hall79d07d22020-04-27 18:20:16 +0100377 "storage_rounding_quantum",
378 "brick_size",
Tim Hall79d07d22020-04-27 18:20:16 +0100379 "quantization",
380 "weight_compressed_offsets",
381 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100382 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100383 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200384 "resampling_mode",
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200385 "avoid_NHCWB16",
Tim Hall79d07d22020-04-27 18:20:16 +0100386 )
387 AllocationQuantum = 16
388
Louis Verhaard93719a92020-12-08 10:02:31 +0100389 def __init__(self, shape: Shape, dtype: DataType, name: str):
Tim Hall79d07d22020-04-27 18:20:16 +0100390 self.shape = shape
391 self.storage_shape = shape
392 self.bandwidth_shape = shape
393 self.dtype = dtype
394 self.name = name
Louis Verhaard93719a92020-12-08 10:02:31 +0100395 self.equivalence_id: UUID = uuid.uuid4()
Tim Hall79d07d22020-04-27 18:20:16 +0100396
Louis Verhaard93719a92020-12-08 10:02:31 +0100397 self.ops: List[Operation] = []
398 self.consumer_list: List[Operation] = []
Tim Hall79d07d22020-04-27 18:20:16 +0100399
Louis Verhaard93719a92020-12-08 10:02:31 +0100400 self.values: Optional[np.ndarray] = None
401 self.quant_values: Optional[np.ndarray] = None
402 self.compressed_values: Optional[np.ndarray] = None
403 self.compressed_values_substream_offsets: Optional[List] = None
404 self.mem_area: MemArea = MemArea.Unknown
405 self.mem_type: MemType = MemType.Unknown
406 self.format: TensorFormat = TensorFormat.Unknown
407 self.purpose: TensorPurpose = TensorPurpose.Unknown
408 self.sub_purpose: TensorSubPurpose = TensorSubPurpose.Standard
409 self.alignment: int = Tensor.AllocationQuantum
410 self.weight_transpose_depthwise: bool = False
Tim Hall79d07d22020-04-27 18:20:16 +0100411
Louis Verhaard93719a92020-12-08 10:02:31 +0100412 self.storage_compression_scale: float = 1.0
413 self.bandwidth_compression_scale: float = 1.0
414 self.compression_scale_for_worst_weight_stream: float = 1.0
415 self.weight_compression_scales: Optional[np.ndarray] = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200416 # if two tensors have the same weight_compression_config, then they have the same compressed values
Tim Hall79d07d22020-04-27 18:20:16 +0100417 self.weight_compression_config = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200418 # if two tensors have the same value_id, then they have the same values
Louis Verhaard93719a92020-12-08 10:02:31 +0100419 self.value_id: UUID = uuid.uuid4()
420 self.weight_compressed_offsets: List = []
421 self.storage_rounding_quantum: Tuple = (1, 1, 1, 1)
422 self.brick_size: Tuple = (1, 1, 1, 1)
423 self.element_size_bytes: int = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100424
425 # quantization parameters
Louis Verhaard93719a92020-12-08 10:02:31 +0100426 self.quantization: Optional[QuantizationParameters] = None
427 self.block_traversal: TensorBlockTraversal = TensorBlockTraversal.Default
428 self.resampling_mode: resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100429
Louis Verhaard93719a92020-12-08 10:02:31 +0100430 self.avoid_NHCWB16: bool = False
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200431
Jacob Bohlin1a666972020-09-11 10:04:15 +0200432 @property
Louis Verhaard93719a92020-12-08 10:02:31 +0100433 def address(self) -> int:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200434 return TensorAddressMap.get_address_for_tens(self.equivalence_id, self.mem_type)
435
436 @address.setter
Louis Verhaard93719a92020-12-08 10:02:31 +0100437 def address(self, address: int):
Jacob Bohlin1a666972020-09-11 10:04:15 +0200438 TensorAddressMap.set_address_for_tens(self.equivalence_id, self.mem_type, address)
439
Louis Verhaard93719a92020-12-08 10:02:31 +0100440 def element_size(self) -> int:
Tim Hall79d07d22020-04-27 18:20:16 +0100441 if self.element_size_bytes == 0:
442 return self.dtype.size_in_bits() / 8
443 return self.element_size_bytes
444
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100445 # Returns a copy, renamed to self.name + suffix
446 # The references to Operators will be empty when returned
447 # Depending on set_unique, the copy is shallow, or deep
448 # For set_unique==True, a new equivalence_id will be set
Louis Verhaard93719a92020-12-08 10:02:31 +0100449 def clone(self, suffix="_clone", set_unique: bool = False) -> "Tensor":
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100450 if set_unique:
451 res = copy.deepcopy(self)
452 res.equivalence_id = uuid.uuid4()
453 else:
454 res = copy.copy(self)
455 res.storage_shape = list(self.storage_shape)
456 res.bandwidth_shape = list(self.bandwidth_shape)
457 if self.quantization is not None:
458 res.quantization = self.quantization.clone()
Tim Hall79d07d22020-04-27 18:20:16 +0100459
Patrik Gustavsson6ae0e422020-11-04 12:43:50 +0100460 res.name = res.name + suffix
Tim Hall79d07d22020-04-27 18:20:16 +0100461 res.ops = []
462 res.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100463
Tim Hall79d07d22020-04-27 18:20:16 +0100464 return res
465
Louis Verhaard93719a92020-12-08 10:02:31 +0100466 def clone_into_fast_storage(self, arch) -> "Tensor":
Tim Hall79d07d22020-04-27 18:20:16 +0100467 res = self.clone(suffix="_fast_storage")
468 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200469 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100470 return res
471
Louis Verhaard93719a92020-12-08 10:02:31 +0100472 def copy_compressed_weight_info(self, src_tens: "Tensor"):
Louis Verhaard3c07c972020-05-07 08:12:58 +0200473 # Copies compressed values + all related weight compression info from the given tensor
Louis Verhaard9db529a2020-09-23 10:27:11 +0200474 self.equivalence_id = src_tens.equivalence_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200475 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100476 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200477 self.storage_shape = src_tens.storage_shape
478 self.brick_size = src_tens.brick_size
479 self.weight_compression_scales = src_tens.weight_compression_scales
480 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
481 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
482 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
483 self.storage_compression_scale = src_tens.storage_compression_scale
Diqing Zhong7e1d1d12020-10-30 15:10:46 +0100484 self.bandwidth_compression_scale = src_tens.bandwidth_compression_scale
Louis Verhaard3c07c972020-05-07 08:12:58 +0200485 self.block_traversal = src_tens.block_traversal
486 self.weight_compression_config = src_tens.weight_compression_config
Louis Verhaard9db529a2020-09-23 10:27:11 +0200487 self.value_id = src_tens.value_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200488
Louis Verhaard93719a92020-12-08 10:02:31 +0100489 def set_format(self, fmt: TensorFormat, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100490 self.format = fmt
491 shape_len = 0
492 try:
493 shape_len = len(self.shape)
494 except TypeError:
495 pass
496
Louis Verhaard0411edb2020-11-16 16:37:11 +0100497 if shape_len > 4:
498 return
Tim Hall79d07d22020-04-27 18:20:16 +0100499 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
Louis Verhaard93719a92020-12-08 10:02:31 +0100500 self.storage_rounding_quantum = tuple(self.storage_rounding_quantum[-shape_len:])
Tim Hall79d07d22020-04-27 18:20:16 +0100501 self.brick_size = arch.brick_sizes[self.format]
Louis Verhaard93719a92020-12-08 10:02:31 +0100502 self.brick_size = tuple(self.brick_size[-shape_len:])
Tim Hall79d07d22020-04-27 18:20:16 +0100503 if self.shape is None:
504 return
505
506 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
507 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
508
509 if fmt == TensorFormat.WeightsCompressed:
510 compression_ratio = 5 / 8
511 self.storage_compression_scale = compression_ratio
512 self.bandwidth_compression_scale = compression_ratio
513 self.compression_scale_for_worst_weight_stream = compression_ratio
514
Louis Verhaard93719a92020-12-08 10:02:31 +0100515 def storage_elements(self) -> int:
Tim Hall79d07d22020-04-27 18:20:16 +0100516 elems = shape_num_elements(self.storage_shape)
517 if elems is None:
518 return 0
519 return elems
520
Louis Verhaard93719a92020-12-08 10:02:31 +0100521 def elements(self) -> int:
Tim Hall79d07d22020-04-27 18:20:16 +0100522 elems = shape_num_elements(self.shape)
523 if elems is None:
524 return 0
525 return elems
526
Louis Verhaard93719a92020-12-08 10:02:31 +0100527 def has_fully_defined_shape(self) -> bool:
Tim Hall79d07d22020-04-27 18:20:16 +0100528 return shape_fully_defined(self.shape)
529
Louis Verhaard93719a92020-12-08 10:02:31 +0100530 def storage_size(self, scale: float = 1.0) -> int:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200531 raw_size = self.storage_elements() * self.element_size() * scale
Tim Hall79d07d22020-04-27 18:20:16 +0100532 if raw_size == 0:
533 raw_size = 1 # force it to take up space
534 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
535 return rounded_size
536
Louis Verhaard93719a92020-12-08 10:02:31 +0100537 def storage_size_for_sub_purpose(
538 self, arch, sub_purpose: TensorSubPurpose, param_a: Optional[int] = None, param_b: Optional[int] = None
539 ) -> int:
Tim Hall79d07d22020-04-27 18:20:16 +0100540 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
541 elems = shape_num_elements(alt_shape)
542 if elems is None:
543 return 0
544 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200545 raw_size = (
546 elems
547 * self.element_size()
548 * self.compression_scale_for_worst_weight_stream
549 * arch.weight_estimation_scaling
550 )
Tim Hall79d07d22020-04-27 18:20:16 +0100551 else:
Patrik Gustavsson9baa4c32020-08-20 13:59:01 +0200552 # Rolling buffers are used for intermediate data in ifm streaming
553 # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension
554 if alt_shape[-1] % 16 != 0:
555 nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)]
556 elems = shape_num_elements(nhcwb16_shape)
557
Tim Hall79d07d22020-04-27 18:20:16 +0100558 raw_size = elems * self.element_size() * self.storage_compression_scale
559 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
560 return rounded_size
561
Louis Verhaard93719a92020-12-08 10:02:31 +0100562 def storage_shape_for_sub_purpose(
563 self, sub_purpose: TensorSubPurpose, param_a: Optional[int], param_b: Optional[int]
564 ) -> Shape:
Tim Hall79d07d22020-04-27 18:20:16 +0100565 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200566 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100567 assert len(shp) >= 2
Louis Verhaard93719a92020-12-08 10:02:31 +0100568 assert param_a is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100569 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100570 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200571 shp = list(self.storage_shape)
572 if sub_purpose == TensorSubPurpose.RollingBufferX:
573 assert len(shp) == 4
Louis Verhaard93719a92020-12-08 10:02:31 +0100574 assert param_a is not None
Jacob Bohline843d332020-06-23 12:12:56 +0200575 shp[0] = 1
576 shp[2] = min(shp[2], param_a)
577 elif sub_purpose == TensorSubPurpose.RollingBufferY:
578 assert len(shp) == 4
Louis Verhaard93719a92020-12-08 10:02:31 +0100579 assert param_a is not None
Jacob Bohline843d332020-06-23 12:12:56 +0200580 shp[0] = 1
581 shp[1] = min(shp[1], param_a)
582 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
583 assert len(shp) == 4
Louis Verhaard93719a92020-12-08 10:02:31 +0100584 assert param_a is not None
585 assert param_b is not None
Jacob Bohline843d332020-06-23 12:12:56 +0200586 shp[0] = 1
587 shp[2] = min(shp[2], param_a)
588 shp[1] = min(shp[1], param_b)
589 elif sub_purpose == TensorSubPurpose.Standard:
590 pass
591 else:
592 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
593
Tim Hall79d07d22020-04-27 18:20:16 +0100594 return shp
595
Louis Verhaard93719a92020-12-08 10:02:31 +0100596 def set_new_sub_purpose(self, sub_purpose: TensorSubPurpose, param_a=None, param_b=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100597 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
598 self.sub_purpose = sub_purpose
599 if sub_purpose == TensorSubPurpose.DoubleBuffer:
600 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
601
Louis Verhaard93719a92020-12-08 10:02:31 +0100602 def bandwidth(self) -> float:
Tim Hall79d07d22020-04-27 18:20:16 +0100603 elems = shape_num_elements(self.bandwidth_shape)
604 if elems is None:
605 return 0
606 return elems * self.element_size() * self.bandwidth_compression_scale
607
Louis Verhaard93719a92020-12-08 10:02:31 +0100608 def consumers(self) -> List[Operation]:
Tim Hall79d07d22020-04-27 18:20:16 +0100609 return self.consumer_list
610
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100611 def addresses_for_rolling_buffer(self, start_coord: Shape, end_coord: Shape, fm_shape: Shape) -> Tuple:
Tim Hall79d07d22020-04-27 18:20:16 +0100612 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
613
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100614 if self.storage_shape == []:
615 return (
616 1,
617 1,
618 1,
619 [self.address_for_coordinate(start_coord, shape=fm_shape), None, None, None],
620 )
Tim Hall79d07d22020-04-27 18:20:16 +0100621
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100622 storage_shape_4D = full_shape(4, self.storage_shape, 1)
623 crossing_y = numeric_util.round_up(start_coord[1] + 1, storage_shape_4D[1])
624 crossing_x = numeric_util.round_up(start_coord[2] + 1, storage_shape_4D[2])
Tim Hall79d07d22020-04-27 18:20:16 +0100625
626 crossing_y = min(crossing_y, end_coord[1])
627 crossing_x = min(crossing_x, end_coord[2])
628
629 box_height0 = crossing_y - start_coord[1]
630 box_width = crossing_x - start_coord[2]
631
Louis Verhaard93719a92020-12-08 10:02:31 +0100632 addresses: List = [None] * 4
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100633 addresses[0] = self.address_for_coordinate(start_coord, shape=fm_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100634
635 if end_coord[2] > crossing_x:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100636 addresses[1] = self.address_for_coordinate(
637 [start_coord[0], start_coord[1], crossing_x, start_coord[3]], shape=fm_shape
638 )
Michael McGeagh528a56d2020-12-16 11:33:21 +0000639 raise UnsupportedFeatureError("Striping in vertical direction is not supported")
Tim Hall79d07d22020-04-27 18:20:16 +0100640 if end_coord[1] > crossing_y:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100641 addresses[2] = self.address_for_coordinate(
642 [start_coord[0], crossing_y, start_coord[2], start_coord[3]], shape=fm_shape
643 )
Tim Hall79d07d22020-04-27 18:20:16 +0100644 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100645 addresses[3] = self.address_for_coordinate(
646 [start_coord[0], crossing_y, crossing_x, start_coord[3]], shape=fm_shape
647 )
Tim Hall79d07d22020-04-27 18:20:16 +0100648
649 return box_height0, box_height0, box_width, addresses
650
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100651 def address_for_coordinate(self, coord: Shape, is_top_box: bool = False, shape: Shape = None) -> int:
652 if shape is None:
653 shape = self.shape
654 offset = self.address_offset_for_coordinate(coord, shape, is_top_box)
Louis Verhaard93719a92020-12-08 10:02:31 +0100655 assert offset is not None
656 return self.address + offset
Tim Hall79d07d22020-04-27 18:20:16 +0100657
Louis Verhaard93719a92020-12-08 10:02:31 +0100658 def get_strides_and_coord(self, coord: Optional[Shape] = None) -> Tuple[Optional[Shape], Optional[Shape]]:
Tim Hall79d07d22020-04-27 18:20:16 +0100659 if coord is None:
660 coord = [0] * len(self.storage_shape)
661
662 augmented_coord = coord
663 augmented_shape = self.storage_shape
664 while len(augmented_shape) < 4:
665 augmented_shape = [1] + augmented_shape
666
667 while len(augmented_coord) < 4:
668 augmented_coord = [0] + augmented_coord
669
670 assert len(augmented_coord) == len(augmented_shape)
671
672 if self.format == TensorFormat.NHWC:
673 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
674 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
Tim Hall79d07d22020-04-27 18:20:16 +0100675
676 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200677 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100678 augmented_shape = augmented_shape[0:4] + [1]
679 augmented_coord = (
680 [augmented_coord[0], augmented_coord[3] // channel_divisor]
681 + augmented_coord[1:3]
682 + [augmented_coord[3] % channel_divisor]
683 )
684
685 if augmented_shape[1] == 0:
686 augmented_shape[1] = 1
687
688 else:
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000689 assert self.format in (TensorFormat.Unknown, TensorFormat.WeightsCompressed)
Tim Hall79d07d22020-04-27 18:20:16 +0100690 return None, None
691
Louis Verhaard93719a92020-12-08 10:02:31 +0100692 strides: List = [0] * len(augmented_shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100693 stride = self.element_size() * self.storage_compression_scale
694
695 if self.format != TensorFormat.NHCWB16:
Louis Verhaard93719a92020-12-08 10:02:31 +0100696 stride_order = [4, 1, 3, 2, 0]
Tim Hall79d07d22020-04-27 18:20:16 +0100697 for i in stride_order:
698 strides[i] = stride
699 stride *= augmented_shape[i]
700 else:
701 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100702 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200703 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100704 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200705 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100706 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
707
708 return strides, augmented_coord
709
Louis Verhaard93719a92020-12-08 10:02:31 +0100710 def get_strides(self) -> Shape:
Tim Hall79d07d22020-04-27 18:20:16 +0100711 strides, _ = self.get_strides_and_coord()
Louis Verhaard93719a92020-12-08 10:02:31 +0100712 assert strides is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100713 return strides
714
Louis Verhaard93719a92020-12-08 10:02:31 +0100715 def needs_dma(self) -> bool:
Louis Verhaardaee5d752020-09-30 09:01:52 +0200716 return len(self.ops) == 1 and self.ops[0].type == Op.DMA
Louis Verhaard3c07c972020-05-07 08:12:58 +0200717
Louis Verhaard93719a92020-12-08 10:02:31 +0100718 def get_dma_src_tensor(self) -> "Optional[Tensor]":
Louis Verhaard3c07c972020-05-07 08:12:58 +0200719 # For weight tensors that need DMA: returns the source tensor in Flash, else None
720 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
721 return self.ops[0].inputs[0] if self.needs_dma() else None
722
Louis Verhaard93719a92020-12-08 10:02:31 +0100723 def find_npu_op(self) -> Optional[Operation]:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200724 # Returns the NPU operator that uses this tensor, excluding DMA operators.
725 for op in self.consumers():
Louis Verhaardaee5d752020-09-30 09:01:52 +0200726 if op.type == Op.DMA:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200727 return op.outputs[0].find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200728 if op.run_on_npu:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200729 return op
Louis Verhaard93719a92020-12-08 10:02:31 +0100730 return None
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200731
Louis Verhaard93719a92020-12-08 10:02:31 +0100732 def compressed_stream_index_from_coord(self, coord: Shape) -> int:
Tim Hall79d07d22020-04-27 18:20:16 +0100733 assert self.format == TensorFormat.WeightsCompressed
Louis Verhaard93719a92020-12-08 10:02:31 +0100734 assert self.compressed_values is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100735 assert len(self.compressed_values) > 0
736 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
737
738 depth = coord[-1]
739 brick_depth = self.brick_size[-1]
740 # Clamp position at final element index
741 if depth > self.shape[-1]:
742 depth = self.shape[-1]
743
744 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100745 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100746
747 # Check boundaries on all but last weight set (which may be shorter
748 # than the brick we divided it up into)
749 if index < len(self.weight_compressed_offsets) - 1:
750 # There are no half-way points in the weights
751 if (depth % brick_depth) != 0:
Michael McGeagh528a56d2020-12-16 11:33:21 +0000752 raise UnsupportedFeatureError("Offset into weights must be aligned to a brick")
Tim Hall79d07d22020-04-27 18:20:16 +0100753
754 return index
755
Louis Verhaard93719a92020-12-08 10:02:31 +0100756 def size_of_compressed_stream(self, index: int) -> int:
757 assert self.compressed_values is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100758 assert 0 <= index < len(self.compressed_values)
759 return len(self.compressed_values[index])
760
Louis Verhaard93719a92020-12-08 10:02:31 +0100761 def is_last_index_in_compressed_stream(self, index: int) -> bool:
762 assert self.compressed_values is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100763 assert 0 <= index < len(self.compressed_values)
764 return index == len(self.compressed_values) - 1
765
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100766 def address_offset_for_coordinate(self, orig_coord: Shape, shape: Shape, is_top_box: bool = False) -> Optional[int]:
Tim Hall79d07d22020-04-27 18:20:16 +0100767 address_offset = 0
768 coord = orig_coord
769
770 coord = coord[-len(self.storage_shape) :]
771
772 if self.sub_purpose == TensorSubPurpose.Standard:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100773 for idx, c in enumerate(orig_coord):
Tim Hall79d07d22020-04-27 18:20:16 +0100774 if is_top_box:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100775 assert c > 0 and c <= shape[idx]
Tim Hall79d07d22020-04-27 18:20:16 +0100776 else:
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100777 assert c >= 0 and c < shape[idx]
Tim Hall79d07d22020-04-27 18:20:16 +0100778
779 if self.format == TensorFormat.WeightsCompressed:
780 if len(self.weight_compressed_offsets) == 0:
781 return 0
782
Louis Verhaard3c07c972020-05-07 08:12:58 +0200783 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100784 depth = orig_coord[-1]
785 brick_depth = self.brick_size[-1]
786 # Clamp position at final element index
787 if depth > self.shape[-1]:
788 depth = self.shape[-1]
789
790 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100791 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100792 index = index % 2
Louis Verhaard93719a92020-12-08 10:02:31 +0100793 assert self.compressed_values is not None
Tim Hall79d07d22020-04-27 18:20:16 +0100794
795 if len(self.compressed_values) <= 2:
796 if is_top_box and index == 0:
797 for cv in self.compressed_values:
798 address_offset += len(cv)
799 else:
800 address_offset = index * len(self.compressed_values[0])
801 else:
802 if is_top_box and index == 0:
803 address_offset = self.storage_shape[-1]
804 else:
805 address_offset = index * (self.storage_shape[-1] // 2)
806 else:
807 index = self.compressed_stream_index_from_coord(orig_coord)
808 assert index < len(self.weight_compressed_offsets)
809 address_offset = self.weight_compressed_offsets[index]
810 else:
811 if is_top_box:
812 coord = [c - 1 for c in coord]
813
814 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
815 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
816
817 strides, augmented_coord = self.get_strides_and_coord(coord)
818 if strides is None:
819 return None
820
821 if is_top_box:
822 address_offset += 1 * strides[-1] # one element
823
824 address_offset += np.dot(augmented_coord, strides)
825
826 assert address_offset >= 0
827 assert address_offset <= self.storage_size()
828 return address_offset
829
Louis Verhaard93719a92020-12-08 10:02:31 +0100830 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area: MemArea) -> bool:
Michael McGeaghf3e3ad72020-12-02 12:39:03 +0000831 return (self.mem_area == scratch_tensor_mem_area) and (self.mem_type in (MemType.Scratch, MemType.Scratch_fast))
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200832
Louis Verhaard93719a92020-12-08 10:02:31 +0100833 def equivalent(self, tens: "Tensor") -> bool:
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200834 return self.equivalence_id == tens.equivalence_id
835
Louis Verhaard93719a92020-12-08 10:02:31 +0100836 def set_all_shapes(self, shape: Shape):
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100837 self.shape = shape
838 self.storage_shape = shape
839 self.bandwidth_shape = shape
840
Louis Verhaard93719a92020-12-08 10:02:31 +0100841 def get_full_shape(self) -> Shape:
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100842 d = len(self.shape)
843 if d in (1, 3):
Patrik Gustavsson2349d422020-12-01 16:02:29 +0100844 return full_shape(4, self.shape, 1)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100845 elif d == 2:
846 return [self.shape[0], 1, 1, self.shape[1]]
847 else:
Fredrik Svedberg835d8e12020-09-04 09:46:17 +0200848 return self.shape.copy()
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100849
Louis Verhaard93719a92020-12-08 10:02:31 +0100850 def is_quantized(self) -> bool:
Tim Hall93582962020-09-09 21:58:15 +0100851 # a tensor is quantized if it has an integral type and it contains valid quantization params
852
Tim Hall89567612020-10-27 11:57:57 +0000853 if not isinstance(self.quantization, QuantizationParameters):
Tim Hall93582962020-09-09 21:58:15 +0100854 return False
855
Tim Hall89567612020-10-27 11:57:57 +0000856 return (self.dtype.type & BaseType.Int) != 0 and self.quantization.is_valid()
Tim Hall93582962020-09-09 21:58:15 +0100857
Louis Verhaard6c74c3b2020-12-17 13:54:09 +0100858 def __lt__(self, other: "Tensor") -> bool:
859 return self.equivalence_id < other.equivalence_id
860
Tim Hall79d07d22020-04-27 18:20:16 +0100861 def __str__(self):
862 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
863
864 __repr__ = __str__
Tim Hall93582962020-09-09 21:58:15 +0100865
Michael McGeagh528a56d2020-12-16 11:33:21 +0000866 def error(self, msg):
867 """
868 Raises a VelaError exception for errors encountered when parsing a Tensor
869
870 :param self: Tensor object that resulted in the error
871 :param msg: str object that contains a description of the specific error encountered
872 """
873
874 def _print_operators(ops):
875 lines = []
876 for idx, op in enumerate(ops):
877 op_type = getattr(op, "type", "Not an Operation")
878 op_id = getattr(op, "op_index", "-")
879 lines.append(f" {idx} = {op_type} ({op_id})")
880 return lines
881
882 lines = [f"Invalid {self.name} tensor. {msg}"]
883
884 lines += [" Driving operators:"]
885 lines += _print_operators(self.ops)
886
887 lines += [" Consuming operators:"]
888 lines += _print_operators(self.consumer_list)
889
890 raise VelaError("\n".join(lines))
891
Tim Hall93582962020-09-09 21:58:15 +0100892
Louis Verhaard93719a92020-12-08 10:02:31 +0100893def check_quantized_tens_scaling_equal(tens_a: Tensor, tens_b: Tensor) -> bool:
Tim Hall93582962020-09-09 21:58:15 +0100894 # checks that the scaling of two quantized tensors are equal
895
Tim Hall89567612020-10-27 11:57:57 +0000896 return tens_a.is_quantized() and tens_b.is_quantized() and tens_a.quantization.is_scaling_equal(tens_b.quantization)