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. |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 18 | import enum |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 19 | import uuid |
Diego Russo | ea6111a | 2020-04-14 18:41:58 +0100 | [diff] [blame] | 20 | |
| 21 | import numpy as np |
| 22 | |
| 23 | from . import numeric_util |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 24 | from .data_type import DataType |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 25 | from .ethos_u55_regs.ethos_u55_regs import resampling_mode |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 26 | from .operation import Operation |
Diego Russo | e8a1045 | 2020-04-21 17:39:10 +0100 | [diff] [blame] | 27 | from .range_set import MemoryRangeSet |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 28 | |
| 29 | |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 30 | class MemType(enum.IntFlag): |
| 31 | Unknown = 0 |
| 32 | Permanent_NPU = 1 |
| 33 | Permanent_CPU = 2 |
| 34 | Scratch = 3 |
| 35 | Scratch_fast = 4 |
| 36 | Size = Scratch_fast + 1 |
| 37 | |
| 38 | def display_name(self): |
| 39 | return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value] |
| 40 | |
| 41 | def identifier_name(self): |
| 42 | return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value] |
| 43 | |
| 44 | def all(): |
| 45 | return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast) |
| 46 | |
| 47 | def __str__(self): |
| 48 | return self.name |
| 49 | |
| 50 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 51 | class MemArea(enum.IntFlag): |
| 52 | Unknown = 0 |
| 53 | Sram = 1 |
| 54 | Dram = 2 |
| 55 | OnChipFlash = 3 |
| 56 | OffChipFlash = 4 |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 57 | Shram = 5 # for LUT |
| 58 | Size = Shram + 1 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 59 | |
| 60 | def display_name(self): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 61 | 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] | 62 | |
| 63 | def identifier_name(self): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 64 | 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] | 65 | |
| 66 | def all(): |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 67 | return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash, MemArea.Shram) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 68 | |
| 69 | def __str__(self): |
| 70 | return self.name |
| 71 | |
| 72 | |
| 73 | class TensorPurpose(enum.IntFlag): |
| 74 | Unknown = 0 |
| 75 | Weights = 1 |
| 76 | FeatureMap = 2 |
| 77 | Scratch = 3 |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 78 | LUT = 4 |
| 79 | Size = 5 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 80 | |
| 81 | def display_name(self): |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 82 | return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "Size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 83 | |
| 84 | def identifier_name(self): |
Fredrik Svedberg | a0c3624 | 2020-06-03 15:43:31 +0200 | [diff] [blame] | 85 | return ("unknown", "weights", "feature_map", "scratch", "lut", "size")[self.value] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 86 | |
| 87 | def all(): |
| 88 | return (TensorPurpose.Weights, TensorPurpose.FeatureMap) |
| 89 | |
| 90 | |
| 91 | class TensorSubPurpose(enum.Enum): |
| 92 | Standard = 0 |
| 93 | DoubleBuffer = 1 |
| 94 | RollingBufferX = 2 |
| 95 | RollingBufferY = 3 |
| 96 | RollingBufferXY = 4 |
| 97 | |
| 98 | def display_name(self): |
| 99 | return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value] |
| 100 | |
| 101 | def identifier_name(self): |
| 102 | return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value] |
| 103 | |
| 104 | def all(): |
| 105 | return ( |
| 106 | TensorSubPurpose.Standard, |
| 107 | TensorSubPurpose.DoubleBuffer, |
| 108 | TensorSubPurpose.RollingBufferX, |
| 109 | TensorSubPurpose.RollingBufferY, |
| 110 | TensorSubPurpose.RollingBufferXY, |
| 111 | ) |
| 112 | |
| 113 | |
| 114 | class TensorFormat(enum.Flag): |
| 115 | Unknown = 0 |
| 116 | WeightsCompressed = 1 |
| 117 | NHWC = 2 |
| 118 | NHCWB16 = 3 |
| 119 | |
| 120 | def __str__(self): |
| 121 | return self.name |
| 122 | |
| 123 | |
| 124 | class TensorBlockTraversal(enum.Enum): |
| 125 | Default = 0 |
| 126 | DepthWise = 1 |
| 127 | DepthFirst = 2 |
| 128 | PartKernelFirst = 3 |
| 129 | |
| 130 | |
| 131 | def shape_num_elements(shp): |
| 132 | elems = 1 |
| 133 | if shp is None: |
| 134 | return None |
| 135 | for d in shp: |
| 136 | if d is None: |
| 137 | return None |
| 138 | elems *= d |
| 139 | return elems |
| 140 | |
| 141 | |
| 142 | def shape_fully_defined(shp): |
| 143 | if shp is None: |
| 144 | return False |
| 145 | for d in shp: |
| 146 | if d is None: |
| 147 | return False |
| 148 | return True |
| 149 | |
| 150 | |
| 151 | def shape_round_to_quantum(shp, quantum): |
| 152 | new_shp = list(shp) |
| 153 | |
| 154 | # Traverse backwards using length of shape since there may be more rounding quantums than shape elements |
| 155 | for i in range(-1, -len(shp) - 1, -1): |
| 156 | if new_shp[i] is not None: |
| 157 | new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i]) |
| 158 | return new_shp |
| 159 | |
| 160 | |
| 161 | class QuantizationParameters: |
| 162 | __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max" |
| 163 | |
| 164 | def __init__(self, min=None, max=None, num_bits=None, narrow_range=None): |
| 165 | self.min = min |
| 166 | self.max = max |
| 167 | |
| 168 | self.num_bits = num_bits |
| 169 | self.narrow_range = narrow_range |
| 170 | |
| 171 | self.scale_f32 = None |
| 172 | self.zero_point = None |
| 173 | self.quant_min = None |
| 174 | self.quant_max = None |
| 175 | |
| 176 | def __str__(self): |
| 177 | return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % ( |
| 178 | self.min, |
| 179 | self.max, |
| 180 | self.num_bits, |
| 181 | self.scale_f32, |
| 182 | self.zero_point, |
| 183 | ) |
| 184 | |
| 185 | __repr__ = __str__ |
| 186 | |
Dwight Lidman | ebe26c7 | 2020-06-09 11:40:54 +0200 | [diff] [blame] | 187 | def __eq__(self, other): |
| 188 | if other is None: |
| 189 | return False |
| 190 | if not isinstance(other, QuantizationParameters): |
| 191 | return False |
| 192 | |
| 193 | pairs = ((getattr(self, s), getattr(other, s)) for s in QuantizationParameters.__slots__) |
| 194 | |
| 195 | return all(np.array_equal(a, b) for a, b in pairs) |
| 196 | |
| 197 | def __ne__(self, other): |
| 198 | return not self == other |
| 199 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 200 | def clone(self): |
| 201 | res = QuantizationParameters() |
| 202 | res.min = self.min |
| 203 | res.max = self.max |
| 204 | |
| 205 | res.num_bits = self.num_bits |
| 206 | res.narrow_range = self.narrow_range |
| 207 | |
| 208 | res.scale_f32 = self.scale_f32 |
| 209 | res.zero_point = self.zero_point |
| 210 | res.quant_min = self.quant_min |
| 211 | res.quant_max = self.quant_max |
| 212 | return res |
| 213 | |
| 214 | def dequantize(self, values): |
| 215 | if self.zero_point.size == 1 and self.scale_f32.size == 1: |
| 216 | # same scale is used for all values |
| 217 | res = (values.astype(np.float64) - self.zero_point) * self.scale_f32 |
| 218 | else: |
| 219 | # a different scale is used for different sets of values |
| 220 | values_as_float = values.astype(np.float64) |
| 221 | |
| 222 | # this is not compatible with the format of depthwise weights, |
| 223 | # where input is at index 3 (Output, Kh, Kw, Input) |
| 224 | # return the quantized values |
| 225 | return np.ndarray((values_as_float.shape)) |
| 226 | |
| 227 | shape = values_as_float.shape[0] |
| 228 | assert self.zero_point.size == self.scale_f32.size == shape |
| 229 | res = np.ndarray(values_as_float.shape) |
| 230 | for i in range(shape): |
| 231 | res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i] |
| 232 | |
| 233 | return res |
| 234 | |
| 235 | |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 236 | def create_const_tensor(name, shape, dtype, values, value_dtype=None, purpose=TensorPurpose.Unknown, quantization=None): |
| 237 | # Tensor |
| 238 | const_tensor = Tensor(shape, dtype, name + "_0") |
| 239 | const_tensor.purpose = purpose |
| 240 | const_tensor.quantization = quantization |
| 241 | const_tensor.values = np.array(values, dtype=value_dtype) |
| 242 | const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8) |
| 243 | # Operator |
| 244 | const_op = Operation("Const", name) |
| 245 | const_op.set_output_tensor(const_tensor) |
| 246 | return const_tensor |
| 247 | |
| 248 | |
| 249 | def create_reshape_tensor(tens, shape, ifm_reshape=True): |
| 250 | if shape == tens.shape: |
| 251 | return tens |
| 252 | # Tensors |
| 253 | name = tens.name + "_reshape" |
| 254 | reshape_ifm = tens |
| 255 | reshape_ofm = tens.clone("_reshaped") |
| 256 | reshape_ofm.set_all_shapes(shape) |
| 257 | if not ifm_reshape: |
| 258 | reshape_ifm, reshape_ofm = reshape_ofm, reshape_ifm |
| 259 | # Operator |
| 260 | reshape_op = Operation("Reshape", name) |
| 261 | reshape_op.attrs["new_shape"] = shape |
| 262 | reshape_op.add_input_tensor(reshape_ifm) |
| 263 | reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, shape)) |
| 264 | reshape_op.set_output_tensor(reshape_ofm) |
| 265 | return reshape_ofm if ifm_reshape else reshape_ifm |
| 266 | |
| 267 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 268 | class Tensor: |
| 269 | __slots__ = ( |
| 270 | "shape", |
| 271 | "storage_shape", |
| 272 | "bandwidth_shape", |
| 273 | "dtype", |
| 274 | "name", |
| 275 | "ops", |
| 276 | "consumer_list", |
| 277 | "values", |
| 278 | "quant_values", |
| 279 | "compressed_values", |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 280 | "compressed_values_substream_offsets", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 281 | "mem_area", |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 282 | "mem_type", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 283 | "format", |
| 284 | "purpose", |
| 285 | "sub_purpose", |
| 286 | "alignment", |
| 287 | "weight_transpose_depthwise", |
| 288 | "storage_compression_scale", |
| 289 | "bandwidth_compression_scale", |
| 290 | "compression_scale_for_worst_weight_stream", |
| 291 | "weight_compression_scales", |
| 292 | "weight_compression_config", |
| 293 | "storage_rounding_quantum", |
| 294 | "brick_size", |
| 295 | "address", |
| 296 | "quantization", |
| 297 | "weight_compressed_offsets", |
| 298 | "element_size_bytes", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 299 | "block_traversal", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 300 | "cpu_tensor", |
| 301 | "npu_tensor", |
| 302 | "equivalence_id", |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 303 | "resampling_mode", |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 304 | "avoid_NHCWB16", |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 305 | ) |
| 306 | AllocationQuantum = 16 |
| 307 | |
| 308 | def __init__(self, shape, dtype, name): |
| 309 | self.shape = shape |
| 310 | self.storage_shape = shape |
| 311 | self.bandwidth_shape = shape |
| 312 | self.dtype = dtype |
| 313 | self.name = name |
| 314 | self.equivalence_id = uuid.uuid4() |
| 315 | |
| 316 | self.ops = [] |
| 317 | self.consumer_list = [] |
| 318 | # Below attributes are only set if a tensor has been cloned, |
| 319 | # either from Cpu -> Npu or vice versa. Needed for offline allocation |
| 320 | self.cpu_tensor = None # reference to the corresponding Cpu tensor |
| 321 | self.npu_tensor = None # reference to the corresponding Npu tensor |
| 322 | |
| 323 | self.values = None |
| 324 | self.quant_values = None |
| 325 | self.compressed_values = None |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 326 | self.compressed_values_substream_offsets = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 327 | self.mem_area = MemArea.Unknown |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 328 | self.mem_type = MemType.Unknown |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 329 | self.format = TensorFormat.Unknown |
| 330 | self.purpose = TensorPurpose.Unknown |
| 331 | self.sub_purpose = TensorSubPurpose.Standard |
| 332 | self.alignment = Tensor.AllocationQuantum |
| 333 | self.weight_transpose_depthwise = False |
| 334 | |
| 335 | self.storage_compression_scale = 1.0 |
| 336 | self.bandwidth_compression_scale = 1.0 |
| 337 | self.compression_scale_for_worst_weight_stream = 1.0 |
| 338 | self.weight_compression_scales = None |
| 339 | self.weight_compression_config = None |
| 340 | self.weight_compressed_offsets = [] |
| 341 | self.storage_rounding_quantum = (1, 1, 1, 1) |
| 342 | self.brick_size = (1, 1, 1, 1) |
Charles Xu | 04ce34c | 2020-06-23 12:42:28 +0200 | [diff] [blame] | 343 | self.address = None # start address of tensor. will be filled in by tensor allocator |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 344 | self.element_size_bytes = 0 |
| 345 | |
| 346 | # quantization parameters |
| 347 | self.quantization = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 348 | self.block_traversal = TensorBlockTraversal.Default |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 349 | self.resampling_mode = resampling_mode.NONE |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 350 | |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 351 | self.avoid_NHCWB16 = False |
| 352 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 353 | def element_size(self): |
| 354 | if self.element_size_bytes == 0: |
| 355 | return self.dtype.size_in_bits() / 8 |
| 356 | return self.element_size_bytes |
| 357 | |
| 358 | def clone(self, suffix="_clone"): |
| 359 | res = Tensor(self.shape, self.dtype, self.name + suffix) |
| 360 | res.storage_shape = list(self.storage_shape) |
| 361 | res.bandwidth_shape = list(self.bandwidth_shape) |
| 362 | |
| 363 | res.ops = [] |
| 364 | res.consumer_list = [] |
| 365 | res.equivalence_id = self.equivalence_id |
| 366 | |
| 367 | res.values = self.values |
| 368 | res.quant_values = self.quant_values |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 369 | res.mem_area = self.mem_area |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 370 | res.mem_type = self.mem_type |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 371 | res.format = self.format |
| 372 | res.purpose = self.purpose |
| 373 | res.sub_purpose = self.sub_purpose |
| 374 | res.alignment = self.alignment |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 375 | res.bandwidth_compression_scale = self.bandwidth_compression_scale |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 376 | res.storage_rounding_quantum = self.storage_rounding_quantum |
Charles Xu | 04ce34c | 2020-06-23 12:42:28 +0200 | [diff] [blame] | 377 | res.address = None |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 378 | |
| 379 | if self.quantization is not None: |
| 380 | res.quantization = self.quantization.clone() |
| 381 | else: |
| 382 | res.quantization = None |
| 383 | |
Dwight Lidman | a9390f7 | 2020-05-13 12:00:08 +0200 | [diff] [blame] | 384 | res.resampling_mode = self.resampling_mode |
| 385 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 386 | res.copy_compressed_weight_info(self) |
Patrik Gustavsson | 458a208 | 2020-08-13 13:41:05 +0200 | [diff] [blame] | 387 | res.avoid_NHCWB16 = self.avoid_NHCWB16 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 388 | return res |
| 389 | |
| 390 | def clone_into_fast_storage(self, arch): |
| 391 | res = self.clone(suffix="_fast_storage") |
| 392 | res.mem_area = arch.fast_storage_mem_area |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 393 | res.mem_type = MemType.Scratch_fast |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 394 | return res |
| 395 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 396 | def copy_compressed_weight_info(self, src_tens): |
| 397 | # Copies compressed values + all related weight compression info from the given tensor |
| 398 | self.compressed_values = src_tens.compressed_values |
Tim Hall | f7e810a | 2020-06-25 15:04:31 +0100 | [diff] [blame] | 399 | self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 400 | self.storage_shape = src_tens.storage_shape |
| 401 | self.brick_size = src_tens.brick_size |
| 402 | self.weight_compression_scales = src_tens.weight_compression_scales |
| 403 | self.weight_compressed_offsets = src_tens.weight_compressed_offsets |
| 404 | self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise |
| 405 | self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream |
| 406 | self.storage_compression_scale = src_tens.storage_compression_scale |
| 407 | self.block_traversal = src_tens.block_traversal |
| 408 | self.weight_compression_config = src_tens.weight_compression_config |
| 409 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 410 | def set_format(self, fmt, arch): |
| 411 | self.format = fmt |
| 412 | shape_len = 0 |
| 413 | try: |
| 414 | shape_len = len(self.shape) |
| 415 | except TypeError: |
| 416 | pass |
| 417 | |
| 418 | self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format] |
| 419 | self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:] |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 420 | self.brick_size = arch.brick_sizes[self.format] |
| 421 | self.brick_size = self.brick_size[-shape_len:] |
| 422 | if self.shape is None: |
| 423 | return |
| 424 | |
| 425 | self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size) |
| 426 | self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum) |
| 427 | |
| 428 | if fmt == TensorFormat.WeightsCompressed: |
| 429 | compression_ratio = 5 / 8 |
| 430 | self.storage_compression_scale = compression_ratio |
| 431 | self.bandwidth_compression_scale = compression_ratio |
| 432 | self.compression_scale_for_worst_weight_stream = compression_ratio |
| 433 | |
| 434 | def storage_elements(self): |
| 435 | elems = shape_num_elements(self.storage_shape) |
| 436 | if elems is None: |
| 437 | return 0 |
| 438 | return elems |
| 439 | |
| 440 | def elements(self): |
| 441 | elems = shape_num_elements(self.shape) |
| 442 | if elems is None: |
| 443 | return 0 |
| 444 | return elems |
| 445 | |
| 446 | def has_fully_defined_shape(self): |
| 447 | return shape_fully_defined(self.shape) |
| 448 | |
| 449 | def storage_size(self): |
| 450 | raw_size = self.storage_elements() * self.element_size() |
| 451 | if raw_size == 0: |
| 452 | raw_size = 1 # force it to take up space |
| 453 | rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment) |
| 454 | return rounded_size |
| 455 | |
| 456 | def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None): |
| 457 | alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b) |
| 458 | elems = shape_num_elements(alt_shape) |
| 459 | if elems is None: |
| 460 | return 0 |
| 461 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
| 462 | raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream |
| 463 | else: |
Patrik Gustavsson | 9baa4c3 | 2020-08-20 13:59:01 +0200 | [diff] [blame] | 464 | # Rolling buffers are used for intermediate data in ifm streaming |
| 465 | # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension |
| 466 | if alt_shape[-1] % 16 != 0: |
| 467 | nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)] |
| 468 | elems = shape_num_elements(nhcwb16_shape) |
| 469 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 470 | raw_size = elems * self.element_size() * self.storage_compression_scale |
| 471 | rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment) |
| 472 | return rounded_size |
| 473 | |
| 474 | 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] | 475 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 476 | shp = list(self.shape) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 477 | assert len(shp) >= 2 |
| 478 | shp[-1] = min(shp[-1], param_a * 2) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 479 | else: |
Jacob Bohlin | e843d33 | 2020-06-23 12:12:56 +0200 | [diff] [blame] | 480 | shp = list(self.storage_shape) |
| 481 | if sub_purpose == TensorSubPurpose.RollingBufferX: |
| 482 | assert len(shp) == 4 |
| 483 | shp[0] = 1 |
| 484 | shp[2] = min(shp[2], param_a) |
| 485 | elif sub_purpose == TensorSubPurpose.RollingBufferY: |
| 486 | assert len(shp) == 4 |
| 487 | shp[0] = 1 |
| 488 | shp[1] = min(shp[1], param_a) |
| 489 | elif sub_purpose == TensorSubPurpose.RollingBufferXY: |
| 490 | assert len(shp) == 4 |
| 491 | shp[0] = 1 |
| 492 | shp[2] = min(shp[2], param_a) |
| 493 | shp[1] = min(shp[1], param_b) |
| 494 | elif sub_purpose == TensorSubPurpose.Standard: |
| 495 | pass |
| 496 | else: |
| 497 | assert 0, "did not expect new sub purpose %s" % (sub_purpose,) |
| 498 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 499 | return shp |
| 500 | |
| 501 | def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None): |
| 502 | self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b) |
| 503 | self.sub_purpose = sub_purpose |
| 504 | if sub_purpose == TensorSubPurpose.DoubleBuffer: |
| 505 | self.storage_compression_scale = self.compression_scale_for_worst_weight_stream |
| 506 | |
| 507 | def bandwidth(self): |
| 508 | elems = shape_num_elements(self.bandwidth_shape) |
| 509 | if elems is None: |
| 510 | return 0 |
| 511 | return elems * self.element_size() * self.bandwidth_compression_scale |
| 512 | |
| 513 | def consumers(self): |
| 514 | return self.consumer_list |
| 515 | |
| 516 | def get_address_ranges_for_coordinates(self, start_coord, end_coord): |
| 517 | if self.sub_purpose in set( |
| 518 | (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY) |
| 519 | ): |
| 520 | # build dummy coordinates that cover the entire buffer |
| 521 | start_coord = [0] * len(start_coord) |
| 522 | end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))] |
| 523 | |
| 524 | start = self.address_for_coordinate(start_coord, is_top_box=False) |
| 525 | end = self.address_for_coordinate(end_coord, is_top_box=True) |
| 526 | return MemoryRangeSet(self.mem_area, start, end) |
| 527 | |
| 528 | def addresses_for_rolling_buffer(self, start_coord, end_coord): |
| 529 | # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] ) |
| 530 | |
| 531 | if len(start_coord) < 4: |
| 532 | box_height0 = 1 |
| 533 | box_width = 1 |
| 534 | |
| 535 | if len(start_coord) >= 2: |
| 536 | box_width = end_coord[-2] - start_coord[-2] |
| 537 | |
| 538 | return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None] |
| 539 | |
| 540 | crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1]) |
| 541 | crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2]) |
| 542 | |
| 543 | crossing_y = min(crossing_y, end_coord[1]) |
| 544 | crossing_x = min(crossing_x, end_coord[2]) |
| 545 | |
| 546 | box_height0 = crossing_y - start_coord[1] |
| 547 | box_width = crossing_x - start_coord[2] |
| 548 | |
| 549 | addresses = [None] * 4 |
| 550 | addresses[0] = self.address_for_coordinate(start_coord) |
| 551 | |
| 552 | if end_coord[2] > crossing_x: |
| 553 | addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]]) |
| 554 | raise Exception("Striping in vertical direction is not supported") |
| 555 | if end_coord[1] > crossing_y: |
| 556 | addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]]) |
| 557 | if end_coord[1] > crossing_y and end_coord[2] > crossing_x: |
| 558 | addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]]) |
| 559 | |
| 560 | return box_height0, box_height0, box_width, addresses |
| 561 | |
| 562 | def address_for_coordinate(self, coord, is_top_box=False): |
| 563 | return self.address + self.address_offset_for_coordinate(coord, is_top_box) |
| 564 | |
| 565 | def get_strides_and_coord(self, coord=None): |
| 566 | if coord is None: |
| 567 | coord = [0] * len(self.storage_shape) |
| 568 | |
| 569 | augmented_coord = coord |
| 570 | augmented_shape = self.storage_shape |
| 571 | while len(augmented_shape) < 4: |
| 572 | augmented_shape = [1] + augmented_shape |
| 573 | |
| 574 | while len(augmented_coord) < 4: |
| 575 | augmented_coord = [0] + augmented_coord |
| 576 | |
| 577 | assert len(augmented_coord) == len(augmented_shape) |
| 578 | |
| 579 | if self.format == TensorFormat.NHWC: |
| 580 | augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1] |
| 581 | augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0] |
| 582 | stride_order = [4, 1, 3, 2, 0] |
| 583 | |
| 584 | elif self.format == TensorFormat.NHCWB16: |
Patrik Gustavsson | 2213e90 | 2020-05-05 17:49:35 +0200 | [diff] [blame] | 585 | channel_divisor = 16 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 586 | augmented_shape = augmented_shape[0:4] + [1] |
| 587 | augmented_coord = ( |
| 588 | [augmented_coord[0], augmented_coord[3] // channel_divisor] |
| 589 | + augmented_coord[1:3] |
| 590 | + [augmented_coord[3] % channel_divisor] |
| 591 | ) |
| 592 | |
| 593 | if augmented_shape[1] == 0: |
| 594 | augmented_shape[1] = 1 |
| 595 | |
| 596 | else: |
| 597 | assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed)) |
| 598 | return None, None |
| 599 | |
| 600 | strides = [0] * len(augmented_shape) |
| 601 | stride = self.element_size() * self.storage_compression_scale |
| 602 | |
| 603 | if self.format != TensorFormat.NHCWB16: |
| 604 | for i in stride_order: |
| 605 | strides[i] = stride |
| 606 | stride *= augmented_shape[i] |
| 607 | else: |
| 608 | assert len(strides) == 5 |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 609 | strides[4] = stride |
Patrik Gustavsson | 2213e90 | 2020-05-05 17:49:35 +0200 | [diff] [blame] | 610 | strides[3] = 16 * stride # STRIDE_X |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 611 | strides[1] = strides[3] * augmented_shape[2] # STRIDE_C |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 612 | strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 613 | strides[0] = strides[2] * augmented_shape[1] # STRIDE_N |
| 614 | |
| 615 | return strides, augmented_coord |
| 616 | |
| 617 | def get_strides(self): |
| 618 | strides, _ = self.get_strides_and_coord() |
| 619 | |
| 620 | return strides |
| 621 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 622 | def needs_dma(self): |
| 623 | return len(self.ops) == 1 and self.ops[0].type == "DMA" |
| 624 | |
| 625 | def get_dma_src_tensor(self): |
| 626 | # For weight tensors that need DMA: returns the source tensor in Flash, else None |
| 627 | # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor |
| 628 | return self.ops[0].inputs[0] if self.needs_dma() else None |
| 629 | |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 630 | def find_npu_op(self): |
| 631 | # Returns the NPU operator that uses this tensor, excluding DMA operators. |
| 632 | for op in self.consumers(): |
| 633 | if op.type == "DMA": |
| 634 | return op.outputs[0].find_npu_op() |
Dwight Lidman | 940fdee | 2020-08-13 13:11:48 +0200 | [diff] [blame] | 635 | if op.run_on_npu: |
Louis Verhaard | b2fb212 | 2020-06-04 15:51:24 +0200 | [diff] [blame] | 636 | return op |
| 637 | return None |
| 638 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 639 | def compressed_stream_index_from_coord(self, coord): |
| 640 | assert self.format == TensorFormat.WeightsCompressed |
| 641 | assert len(self.compressed_values) > 0 |
| 642 | assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets) |
| 643 | |
| 644 | depth = coord[-1] |
| 645 | brick_depth = self.brick_size[-1] |
| 646 | # Clamp position at final element index |
| 647 | if depth > self.shape[-1]: |
| 648 | depth = self.shape[-1] |
| 649 | |
| 650 | # Always round up to next boundary |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 651 | index = numeric_util.round_up_divide(depth, brick_depth) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 652 | |
| 653 | # Check boundaries on all but last weight set (which may be shorter |
| 654 | # than the brick we divided it up into) |
| 655 | if index < len(self.weight_compressed_offsets) - 1: |
| 656 | # There are no half-way points in the weights |
| 657 | if (depth % brick_depth) != 0: |
| 658 | raise Exception("Offset into weights must be aligned to a brick") |
| 659 | |
| 660 | return index |
| 661 | |
| 662 | def size_of_compressed_stream(self, index): |
| 663 | assert 0 <= index < len(self.compressed_values) |
| 664 | return len(self.compressed_values[index]) |
| 665 | |
| 666 | def is_last_index_in_compressed_stream(self, index): |
| 667 | assert 0 <= index < len(self.compressed_values) |
| 668 | return index == len(self.compressed_values) - 1 |
| 669 | |
| 670 | def address_offset_for_coordinate(self, orig_coord, is_top_box=False): |
| 671 | address_offset = 0 |
| 672 | coord = orig_coord |
| 673 | |
| 674 | coord = coord[-len(self.storage_shape) :] |
| 675 | |
| 676 | if self.sub_purpose == TensorSubPurpose.Standard: |
| 677 | for idx, c in enumerate(coord): |
| 678 | if is_top_box: |
| 679 | assert c > 0 and c <= self.shape[idx] |
| 680 | else: |
| 681 | assert c >= 0 and c < self.shape[idx] |
| 682 | |
| 683 | if self.format == TensorFormat.WeightsCompressed: |
| 684 | if len(self.weight_compressed_offsets) == 0: |
| 685 | return 0 |
| 686 | |
Louis Verhaard | 3c07c97 | 2020-05-07 08:12:58 +0200 | [diff] [blame] | 687 | if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer: |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 688 | depth = orig_coord[-1] |
| 689 | brick_depth = self.brick_size[-1] |
| 690 | # Clamp position at final element index |
| 691 | if depth > self.shape[-1]: |
| 692 | depth = self.shape[-1] |
| 693 | |
| 694 | # Always round up to next boundary |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 695 | index = numeric_util.round_up_divide(depth, brick_depth) |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 696 | index = index % 2 |
| 697 | |
| 698 | if len(self.compressed_values) <= 2: |
| 699 | if is_top_box and index == 0: |
| 700 | for cv in self.compressed_values: |
| 701 | address_offset += len(cv) |
| 702 | else: |
| 703 | address_offset = index * len(self.compressed_values[0]) |
| 704 | else: |
| 705 | if is_top_box and index == 0: |
| 706 | address_offset = self.storage_shape[-1] |
| 707 | else: |
| 708 | address_offset = index * (self.storage_shape[-1] // 2) |
| 709 | else: |
| 710 | index = self.compressed_stream_index_from_coord(orig_coord) |
| 711 | assert index < len(self.weight_compressed_offsets) |
| 712 | address_offset = self.weight_compressed_offsets[index] |
| 713 | else: |
| 714 | if is_top_box: |
| 715 | coord = [c - 1 for c in coord] |
| 716 | |
| 717 | # handle wraparound for partial buffers. make sure to do this after subtracting top box: |
| 718 | coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)] |
| 719 | |
| 720 | strides, augmented_coord = self.get_strides_and_coord(coord) |
| 721 | if strides is None: |
| 722 | return None |
| 723 | |
| 724 | if is_top_box: |
| 725 | address_offset += 1 * strides[-1] # one element |
| 726 | |
| 727 | address_offset += np.dot(augmented_coord, strides) |
| 728 | |
| 729 | assert address_offset >= 0 |
| 730 | assert address_offset <= self.storage_size() |
| 731 | return address_offset |
| 732 | |
Patrik Gustavsson | eca2e95 | 2020-05-27 09:15:11 +0200 | [diff] [blame] | 733 | def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area): |
| 734 | if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))): |
| 735 | return True |
| 736 | return False |
| 737 | |
Louis Verhaard | 0b8268a | 2020-08-05 16:11:29 +0200 | [diff] [blame] | 738 | def equivalent(self, tens): |
| 739 | return self.equivalence_id == tens.equivalence_id |
| 740 | |
Michael McGeagh | 6a8d424 | 2020-07-28 12:17:59 +0100 | [diff] [blame] | 741 | def set_all_shapes(self, shape): |
| 742 | self.shape = shape |
| 743 | self.storage_shape = shape |
| 744 | self.bandwidth_shape = shape |
| 745 | |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 746 | def get_full_shape(self): |
| 747 | d = len(self.shape) |
| 748 | if d in (1, 3): |
Michael McGeagh | 8d3216f | 2020-08-10 11:35:57 +0100 | [diff] [blame] | 749 | return numeric_util.full_shape(4, self.shape, 1) |
Michael McGeagh | 5778ffd | 2020-08-06 17:31:02 +0100 | [diff] [blame] | 750 | elif d == 2: |
| 751 | return [self.shape[0], 1, 1, self.shape[1]] |
| 752 | else: |
| 753 | return self.shape |
| 754 | |
Tim Hall | 79d07d2 | 2020-04-27 18:20:16 +0100 | [diff] [blame] | 755 | def __str__(self): |
| 756 | return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype) |
| 757 | |
| 758 | __repr__ = __str__ |