Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 1 | # 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 16 | # Description: |
| 17 | # Internal representation of a Neural Network Tensor. |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 18 | import copy |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 19 | import enum |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 20 | import uuid |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 21 | from collections import defaultdict |
Louis Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 22 | from functools import lru_cache |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 23 | |
| 24 | import numpy as np |
| 25 | |
| 26 | from . import numeric_util |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 27 | from .data_type import BaseType |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 28 | from .data_type import DataType |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 29 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 30 | from .operation import Op |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 31 | from .operation import Operation |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 32 | from .range_set import MemoryRangeSet |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 33 | |
| 34 | |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 35 | class 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 56 | class MemArea(enum.IntFlag): |
| 57 | Unknown = 0 |
| 58 | Sram = 1 |
| 59 | Dram = 2 |
| 60 | OnChipFlash = 3 |
| 61 | OffChipFlash = 4 |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 62 | Shram = 5 # for LUT |
| 63 | Size = Shram + 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 64 | |
| 65 | def display_name(self): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 66 | return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "SHRAM", "Size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 67 | |
| 68 | def identifier_name(self): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 69 | return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "shram", "size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 70 | |
| 71 | def all(): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 72 | return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash, MemArea.Shram) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 73 | |
| 74 | def __str__(self): |
| 75 | return self.name |
| 76 | |
| 77 | |
| 78 | class TensorPurpose(enum.IntFlag): |
| 79 | Unknown = 0 |
| 80 | Weights = 1 |
| 81 | FeatureMap = 2 |
| 82 | Scratch = 3 |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 83 | LUT = 4 |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 84 | FSBias = 5 |
| 85 | Size = 6 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 86 | |
| 87 | def display_name(self): |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 88 | return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "FastStorageBias", "Size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 89 | |
| 90 | def identifier_name(self): |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 91 | return ("unknown", "weights", "feature_map", "scratch", "lut", "fast_storage_bias", "size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 92 | |
| 93 | def all(): |
Andreas Nevalainen | 897cc14 | 2020-10-28 15:42:08 +0100 | [diff] [blame] | 94 | return (TensorPurpose.Weights, TensorPurpose.FeatureMap, TensorPurpose.FSBias) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 95 | |
| 96 | |
| 97 | class 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 | |
| 120 | class 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 | |
| 130 | class TensorBlockTraversal(enum.Enum): |
| 131 | Default = 0 |
| 132 | DepthWise = 1 |
| 133 | DepthFirst = 2 |
| 134 | PartKernelFirst = 3 |
| 135 | |
| 136 | |
| 137 | def 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 | |
| 148 | def 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 | |
| 157 | def 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 Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 167 | @lru_cache(maxsize=None) |
| 168 | def create_equivalence_id(key): |
| 169 | # Generates equivalence_id based on the given key. |
| 170 | return uuid.uuid4() |
| 171 | |
| 172 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 173 | class 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 Hall | e3786ac | 2020-07-28 17:40:50 +0100 | [diff] [blame] | 234 | def is_scaling_equal(self, other): |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 235 | # 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 Hall | e3786ac | 2020-07-28 17:40:50 +0100 | [diff] [blame] | 240 | return False |
| 241 | |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 242 | assert isinstance(other, QuantizationParameters) |
| 243 | |
Tim Hall | e3786ac | 2020-07-28 17:40:50 +0100 | [diff] [blame] | 244 | return self.scale_f32 == other.scale_f32 and self.zero_point == other.zero_point |
| 245 | |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 246 | 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 251 | |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 252 | def 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 Bohlin | a41cd4d | 2020-08-26 18:21:28 +0200 | [diff] [blame] | 258 | const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 259 | # Operator |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 260 | const_op = Operation(Op.Const, name) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 261 | const_op.set_output_tensor(const_tensor) |
| 262 | return const_tensor |
| 263 | |
| 264 | |
| 265 | def 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 Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 276 | reshape_op = Operation(Op.Reshape, name) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 277 | 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 Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 284 | # class that keeps track of all tensor addresses in the different memory types |
| 285 | class 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 Verhaard | 0b9c9a3 | 2020-09-15 14:05:38 +0200 | [diff] [blame] | 296 | if address is not None and previous_address is not None: |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 297 | 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 303 | class 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 Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 315 | "compressed_values_substream_offsets", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 316 | "mem_area", |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 317 | "mem_type", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 318 | "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 Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 328 | "value_id", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 329 | "storage_rounding_quantum", |
| 330 | "brick_size", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 331 | "quantization", |
| 332 | "weight_compressed_offsets", |
| 333 | "element_size_bytes", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 334 | "block_traversal", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 335 | "equivalence_id", |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 336 | "resampling_mode", |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 337 | "avoid_NHCWB16", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 338 | ) |
| 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 351 | |
| 352 | self.values = None |
| 353 | self.quant_values = None |
| 354 | self.compressed_values = None |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 355 | self.compressed_values_substream_offsets = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 356 | self.mem_area = MemArea.Unknown |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 357 | self.mem_type = MemType.Unknown |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 358 | 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 Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 368 | # if two tensors have the same weight_compression_config, then they have the same compressed values |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 369 | self.weight_compression_config = None |
Louis Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 370 | # if two tensors have the same value_id, then they have the same values |
| 371 | self.value_id = uuid.uuid4() |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 372 | self.weight_compressed_offsets = [] |
| 373 | self.storage_rounding_quantum = (1, 1, 1, 1) |
| 374 | self.brick_size = (1, 1, 1, 1) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 375 | self.element_size_bytes = 0 |
| 376 | |
| 377 | # quantization parameters |
| 378 | self.quantization = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 379 | self.block_traversal = TensorBlockTraversal.Default |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 380 | self.resampling_mode = resampling_mode.NONE |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 381 | |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 382 | self.avoid_NHCWB16 = False |
| 383 | |
Jacob Bohlin | 1a66697 | 2020-09-11 10:04:15 +0200 | [diff] [blame] | 384 | @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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 392 | 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 Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 397 | # 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 Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 411 | |
Patrik Gustavsson | 6ae0e42 | 2020-11-04 12:43:50 +0100 | [diff] [blame] | 412 | res.name = res.name + suffix |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 413 | res.ops = [] |
| 414 | res.consumer_list = [] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 415 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 416 | 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 Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 421 | res.mem_type = MemType.Scratch_fast |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 422 | return res |
| 423 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 424 | def copy_compressed_weight_info(self, src_tens): |
| 425 | # Copies compressed values + all related weight compression info from the given tensor |
Louis Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 426 | self.equivalence_id = src_tens.equivalence_id |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 427 | self.compressed_values = src_tens.compressed_values |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 428 | self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 429 | 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 Zhong | 7e1d1d1 | 2020-10-30 15:10:46 +0100 | [diff] [blame] | 436 | self.bandwidth_compression_scale = src_tens.bandwidth_compression_scale |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 437 | self.block_traversal = src_tens.block_traversal |
| 438 | self.weight_compression_config = src_tens.weight_compression_config |
Louis Verhaard | 9db529a | 2020-09-23 10:27:11 +0200 | [diff] [blame] | 439 | self.value_id = src_tens.value_id |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 440 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 441 | 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 | |
| 449 | self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format] |
| 450 | self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 451 | self.brick_size = arch.brick_sizes[self.format] |
| 452 | self.brick_size = self.brick_size[-shape_len:] |
| 453 | if self.shape is None: |
| 454 | return |
| 455 | |
| 456 | self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size) |
| 457 | self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum) |
| 458 | |
| 459 | if fmt == TensorFormat.WeightsCompressed: |
| 460 | compression_ratio = 5 / 8 |
| 461 | self.storage_compression_scale = compression_ratio |
| 462 | self.bandwidth_compression_scale = compression_ratio |
| 463 | self.compression_scale_for_worst_weight_stream = compression_ratio |
| 464 | |
| 465 | def storage_elements(self): |
| 466 | elems = shape_num_elements(self.storage_shape) |
| 467 | if elems is None: |
| 468 | return 0 |
| 469 | return elems |
| 470 | |
| 471 | def elements(self): |
| 472 | elems = shape_num_elements(self.shape) |
| 473 | if elems is None: |
| 474 | return 0 |
| 475 | return elems |
| 476 | |
| 477 | def has_fully_defined_shape(self): |
| 478 | return shape_fully_defined(self.shape) |
| 479 | |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 480 | def storage_size(self, scale=1.0): |
| 481 | raw_size = self.storage_elements() * self.element_size() * scale |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 482 | if raw_size == 0: |
| 483 | raw_size = 1 # force it to take up space |
| 484 | rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment) |
| 485 | return rounded_size |
| 486 | |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 487 | def storage_size_for_sub_purpose(self, arch, sub_purpose, param_a=None, param_b=None): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 488 | alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b) |
| 489 | elems = shape_num_elements(alt_shape) |
| 490 | if elems is None: |
| 491 | return 0 |
| 492 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
Patrik Gustavsson | 90831bc | 2020-08-24 16:26:11 +0200 | [diff] [blame] | 493 | raw_size = ( |
| 494 | elems |
| 495 | * self.element_size() |
| 496 | * self.compression_scale_for_worst_weight_stream |
| 497 | * arch.weight_estimation_scaling |
| 498 | ) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 499 | else: |
Patrik Gustavsson | 9baa4c3 | 2020-08-20 13:59:01 +0200 | [diff] [blame] | 500 | # Rolling buffers are used for intermediate data in ifm streaming |
| 501 | # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension |
| 502 | if alt_shape[-1] % 16 != 0: |
| 503 | nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)] |
| 504 | elems = shape_num_elements(nhcwb16_shape) |
| 505 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 506 | raw_size = elems * self.element_size() * self.storage_compression_scale |
| 507 | rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment) |
| 508 | return rounded_size |
| 509 | |
| 510 | def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b): |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 511 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 512 | shp = list(self.shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 513 | assert len(shp) >= 2 |
| 514 | shp[-1] = min(shp[-1], param_a * 2) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 515 | else: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 516 | shp = list(self.storage_shape) |
| 517 | if sub_purpose == TensorSubPurpose.RollingBufferX: |
| 518 | assert len(shp) == 4 |
| 519 | shp[0] = 1 |
| 520 | shp[2] = min(shp[2], param_a) |
| 521 | elif sub_purpose == TensorSubPurpose.RollingBufferY: |
| 522 | assert len(shp) == 4 |
| 523 | shp[0] = 1 |
| 524 | shp[1] = min(shp[1], param_a) |
| 525 | elif sub_purpose == TensorSubPurpose.RollingBufferXY: |
| 526 | assert len(shp) == 4 |
| 527 | shp[0] = 1 |
| 528 | shp[2] = min(shp[2], param_a) |
| 529 | shp[1] = min(shp[1], param_b) |
| 530 | elif sub_purpose == TensorSubPurpose.Standard: |
| 531 | pass |
| 532 | else: |
| 533 | assert 0, "did not expect new sub purpose %s" % (sub_purpose,) |
| 534 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 535 | return shp |
| 536 | |
| 537 | def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None): |
| 538 | self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b) |
| 539 | self.sub_purpose = sub_purpose |
| 540 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
| 541 | self.storage_compression_scale = self.compression_scale_for_worst_weight_stream |
| 542 | |
| 543 | def bandwidth(self): |
| 544 | elems = shape_num_elements(self.bandwidth_shape) |
| 545 | if elems is None: |
| 546 | return 0 |
| 547 | return elems * self.element_size() * self.bandwidth_compression_scale |
| 548 | |
| 549 | def consumers(self): |
| 550 | return self.consumer_list |
| 551 | |
| 552 | def get_address_ranges_for_coordinates(self, start_coord, end_coord): |
| 553 | if self.sub_purpose in set( |
| 554 | (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY) |
| 555 | ): |
| 556 | # build dummy coordinates that cover the entire buffer |
| 557 | start_coord = [0] * len(start_coord) |
| 558 | end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))] |
| 559 | |
| 560 | start = self.address_for_coordinate(start_coord, is_top_box=False) |
| 561 | end = self.address_for_coordinate(end_coord, is_top_box=True) |
| 562 | return MemoryRangeSet(self.mem_area, start, end) |
| 563 | |
| 564 | def addresses_for_rolling_buffer(self, start_coord, end_coord): |
| 565 | # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] ) |
| 566 | |
| 567 | if len(start_coord) < 4: |
| 568 | box_height0 = 1 |
| 569 | box_width = 1 |
| 570 | |
| 571 | if len(start_coord) >= 2: |
| 572 | box_width = end_coord[-2] - start_coord[-2] |
| 573 | |
| 574 | return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None] |
| 575 | |
| 576 | crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1]) |
| 577 | crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2]) |
| 578 | |
| 579 | crossing_y = min(crossing_y, end_coord[1]) |
| 580 | crossing_x = min(crossing_x, end_coord[2]) |
| 581 | |
| 582 | box_height0 = crossing_y - start_coord[1] |
| 583 | box_width = crossing_x - start_coord[2] |
| 584 | |
| 585 | addresses = [None] * 4 |
| 586 | addresses[0] = self.address_for_coordinate(start_coord) |
| 587 | |
| 588 | if end_coord[2] > crossing_x: |
| 589 | addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]]) |
| 590 | raise Exception("Striping in vertical direction is not supported") |
| 591 | if end_coord[1] > crossing_y: |
| 592 | addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]]) |
| 593 | if end_coord[1] > crossing_y and end_coord[2] > crossing_x: |
| 594 | addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]]) |
| 595 | |
| 596 | return box_height0, box_height0, box_width, addresses |
| 597 | |
| 598 | def address_for_coordinate(self, coord, is_top_box=False): |
| 599 | return self.address + self.address_offset_for_coordinate(coord, is_top_box) |
| 600 | |
| 601 | def get_strides_and_coord(self, coord=None): |
| 602 | if coord is None: |
| 603 | coord = [0] * len(self.storage_shape) |
| 604 | |
| 605 | augmented_coord = coord |
| 606 | augmented_shape = self.storage_shape |
| 607 | while len(augmented_shape) < 4: |
| 608 | augmented_shape = [1] + augmented_shape |
| 609 | |
| 610 | while len(augmented_coord) < 4: |
| 611 | augmented_coord = [0] + augmented_coord |
| 612 | |
| 613 | assert len(augmented_coord) == len(augmented_shape) |
| 614 | |
| 615 | if self.format == TensorFormat.NHWC: |
| 616 | augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1] |
| 617 | augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0] |
| 618 | stride_order = [4, 1, 3, 2, 0] |
| 619 | |
| 620 | elif self.format == TensorFormat.NHCWB16: |
Patrik Gustavsson | 2213e90 | 2020-05-05 17:49:35 +0200 | [diff] [blame] | 621 | channel_divisor = 16 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 622 | augmented_shape = augmented_shape[0:4] + [1] |
| 623 | augmented_coord = ( |
| 624 | [augmented_coord[0], augmented_coord[3] // channel_divisor] |
| 625 | + augmented_coord[1:3] |
| 626 | + [augmented_coord[3] % channel_divisor] |
| 627 | ) |
| 628 | |
| 629 | if augmented_shape[1] == 0: |
| 630 | augmented_shape[1] = 1 |
| 631 | |
| 632 | else: |
| 633 | assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed)) |
| 634 | return None, None |
| 635 | |
| 636 | strides = [0] * len(augmented_shape) |
| 637 | stride = self.element_size() * self.storage_compression_scale |
| 638 | |
| 639 | if self.format != TensorFormat.NHCWB16: |
| 640 | for i in stride_order: |
| 641 | strides[i] = stride |
| 642 | stride *= augmented_shape[i] |
| 643 | else: |
| 644 | assert len(strides) == 5 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 645 | strides[4] = stride |
Patrik Gustavsson | 2213e90 | 2020-05-05 17:49:35 +0200 | [diff] [blame] | 646 | strides[3] = 16 * stride # STRIDE_X |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 647 | strides[1] = strides[3] * augmented_shape[2] # STRIDE_C |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 648 | strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 649 | strides[0] = strides[2] * augmented_shape[1] # STRIDE_N |
| 650 | |
| 651 | return strides, augmented_coord |
| 652 | |
| 653 | def get_strides(self): |
| 654 | strides, _ = self.get_strides_and_coord() |
| 655 | |
| 656 | return strides |
| 657 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 658 | def needs_dma(self): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 659 | return len(self.ops) == 1 and self.ops[0].type == Op.DMA |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 660 | |
| 661 | def get_dma_src_tensor(self): |
| 662 | # For weight tensors that need DMA: returns the source tensor in Flash, else None |
| 663 | # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor |
| 664 | return self.ops[0].inputs[0] if self.needs_dma() else None |
| 665 | |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 666 | def find_npu_op(self): |
| 667 | # Returns the NPU operator that uses this tensor, excluding DMA operators. |
| 668 | for op in self.consumers(): |
Louis Verhaard | aee5d75 | 2020-09-30 09:01:52 +0200 | [diff] [blame] | 669 | if op.type == Op.DMA: |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 670 | return op.outputs[0].find_npu_op() |
Dwight Lidman | 940fdee | 2020-08-13 13:11:48 +0200 | [diff] [blame] | 671 | if op.run_on_npu: |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 672 | return op |
| 673 | return None |
| 674 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 675 | def compressed_stream_index_from_coord(self, coord): |
| 676 | assert self.format == TensorFormat.WeightsCompressed |
| 677 | assert len(self.compressed_values) > 0 |
| 678 | assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets) |
| 679 | |
| 680 | depth = coord[-1] |
| 681 | brick_depth = self.brick_size[-1] |
| 682 | # Clamp position at final element index |
| 683 | if depth > self.shape[-1]: |
| 684 | depth = self.shape[-1] |
| 685 | |
| 686 | # Always round up to next boundary |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 687 | index = numeric_util.round_up_divide(depth, brick_depth) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 688 | |
| 689 | # Check boundaries on all but last weight set (which may be shorter |
| 690 | # than the brick we divided it up into) |
| 691 | if index < len(self.weight_compressed_offsets) - 1: |
| 692 | # There are no half-way points in the weights |
| 693 | if (depth % brick_depth) != 0: |
| 694 | raise Exception("Offset into weights must be aligned to a brick") |
| 695 | |
| 696 | return index |
| 697 | |
| 698 | def size_of_compressed_stream(self, index): |
| 699 | assert 0 <= index < len(self.compressed_values) |
| 700 | return len(self.compressed_values[index]) |
| 701 | |
| 702 | def is_last_index_in_compressed_stream(self, index): |
| 703 | assert 0 <= index < len(self.compressed_values) |
| 704 | return index == len(self.compressed_values) - 1 |
| 705 | |
| 706 | def address_offset_for_coordinate(self, orig_coord, is_top_box=False): |
| 707 | address_offset = 0 |
| 708 | coord = orig_coord |
| 709 | |
| 710 | coord = coord[-len(self.storage_shape) :] |
| 711 | |
| 712 | if self.sub_purpose == TensorSubPurpose.Standard: |
| 713 | for idx, c in enumerate(coord): |
| 714 | if is_top_box: |
| 715 | assert c > 0 and c <= self.shape[idx] |
| 716 | else: |
| 717 | assert c >= 0 and c < self.shape[idx] |
| 718 | |
| 719 | if self.format == TensorFormat.WeightsCompressed: |
| 720 | if len(self.weight_compressed_offsets) == 0: |
| 721 | return 0 |
| 722 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 723 | if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 724 | depth = orig_coord[-1] |
| 725 | brick_depth = self.brick_size[-1] |
| 726 | # Clamp position at final element index |
| 727 | if depth > self.shape[-1]: |
| 728 | depth = self.shape[-1] |
| 729 | |
| 730 | # Always round up to next boundary |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 731 | index = numeric_util.round_up_divide(depth, brick_depth) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 732 | index = index % 2 |
| 733 | |
| 734 | if len(self.compressed_values) <= 2: |
| 735 | if is_top_box and index == 0: |
| 736 | for cv in self.compressed_values: |
| 737 | address_offset += len(cv) |
| 738 | else: |
| 739 | address_offset = index * len(self.compressed_values[0]) |
| 740 | else: |
| 741 | if is_top_box and index == 0: |
| 742 | address_offset = self.storage_shape[-1] |
| 743 | else: |
| 744 | address_offset = index * (self.storage_shape[-1] // 2) |
| 745 | else: |
| 746 | index = self.compressed_stream_index_from_coord(orig_coord) |
| 747 | assert index < len(self.weight_compressed_offsets) |
| 748 | address_offset = self.weight_compressed_offsets[index] |
| 749 | else: |
| 750 | if is_top_box: |
| 751 | coord = [c - 1 for c in coord] |
| 752 | |
| 753 | # handle wraparound for partial buffers. make sure to do this after subtracting top box: |
| 754 | coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)] |
| 755 | |
| 756 | strides, augmented_coord = self.get_strides_and_coord(coord) |
| 757 | if strides is None: |
| 758 | return None |
| 759 | |
| 760 | if is_top_box: |
| 761 | address_offset += 1 * strides[-1] # one element |
| 762 | |
| 763 | address_offset += np.dot(augmented_coord, strides) |
| 764 | |
| 765 | assert address_offset >= 0 |
| 766 | assert address_offset <= self.storage_size() |
| 767 | return address_offset |
| 768 | |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 769 | def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area): |
| 770 | if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))): |
| 771 | return True |
| 772 | return False |
| 773 | |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 774 | def equivalent(self, tens): |
| 775 | return self.equivalence_id == tens.equivalence_id |
| 776 | |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 777 | def set_all_shapes(self, shape): |
| 778 | self.shape = shape |
| 779 | self.storage_shape = shape |
| 780 | self.bandwidth_shape = shape |
| 781 | |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 782 | def get_full_shape(self): |
| 783 | d = len(self.shape) |
| 784 | if d in (1, 3): |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 785 | return numeric_util.full_shape(4, self.shape, 1) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 786 | elif d == 2: |
| 787 | return [self.shape[0], 1, 1, self.shape[1]] |
| 788 | else: |
Fredrik Svedberg | 835d8e1 | 2020-09-04 09:46:17 +0200 | [diff] [blame] | 789 | return self.shape.copy() |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 790 | |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 791 | def is_quantized(self): |
| 792 | # a tensor is quantized if it has an integral type and it contains valid quantization params |
| 793 | |
| 794 | if (self.dtype.type & BaseType.Int) == 0 or self.quantization is None: |
| 795 | return False |
| 796 | |
Tim Hall | 7b1654b | 2020-10-22 14:22:47 +0100 | [diff] [blame] | 797 | assert isinstance(self.quantization, QuantizationParameters) |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 798 | assert self.quantization.is_valid() |
| 799 | |
| 800 | return True |
| 801 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 802 | def __str__(self): |
| 803 | return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype) |
| 804 | |
| 805 | __repr__ = __str__ |
Tim Hall | 9358296 | 2020-09-09 21:58:15 +0100 | [diff] [blame] | 806 | |
| 807 | |
| 808 | def check_tens_quantized(tens): |
| 809 | # checks that a tensor is quantized |
| 810 | |
| 811 | return isinstance(tens, Tensor) and tens.is_quantized() |
| 812 | |
| 813 | |
| 814 | def check_quantized_tens_scaling_equal(tens_a, tens_b): |
| 815 | # checks that the scaling of two quantized tensors are equal |
| 816 | |
| 817 | assert check_tens_quantized(tens_a) |
| 818 | assert check_tens_quantized(tens_b) |
| 819 | |
| 820 | return tens_a.quantization.is_scaling_equal(tens_b.quantization) |