blob: 98dfa3d3d9a914868058e9a304d31d18a4b81e0f [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.
Tim Hall79d07d22020-04-27 18:20:16 +010018import enum
Tim Hall79d07d22020-04-27 18:20:16 +010019import uuid
Jacob Bohlin1a666972020-09-11 10:04:15 +020020from collections import defaultdict
Louis Verhaard9db529a2020-09-23 10:27:11 +020021from functools import lru_cache
Diego Russoea6111a2020-04-14 18:41:58 +010022
23import numpy as np
24
25from . import numeric_util
Michael McGeagh5778ffd2020-08-06 17:31:02 +010026from .data_type import DataType
Dwight Lidmana9390f72020-05-13 12:00:08 +020027from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Louis Verhaardaee5d752020-09-30 09:01:52 +020028from .operation import Op
Michael McGeagh5778ffd2020-08-06 17:31:02 +010029from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010030from .range_set import MemoryRangeSet
Tim Hall79d07d22020-04-27 18:20:16 +010031
32
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020033class MemType(enum.IntFlag):
34 Unknown = 0
35 Permanent_NPU = 1
36 Permanent_CPU = 2
37 Scratch = 3
38 Scratch_fast = 4
39 Size = Scratch_fast + 1
40
41 def display_name(self):
42 return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value]
43
44 def identifier_name(self):
45 return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value]
46
47 def all():
48 return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast)
49
50 def __str__(self):
51 return self.name
52
53
Tim Hall79d07d22020-04-27 18:20:16 +010054class MemArea(enum.IntFlag):
55 Unknown = 0
56 Sram = 1
57 Dram = 2
58 OnChipFlash = 3
59 OffChipFlash = 4
Louis Verhaard0b8268a2020-08-05 16:11:29 +020060 Shram = 5 # for LUT
61 Size = Shram + 1
Tim Hall79d07d22020-04-27 18:20:16 +010062
63 def display_name(self):
Louis Verhaard0b8268a2020-08-05 16:11:29 +020064 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "SHRAM", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010065
66 def identifier_name(self):
Louis Verhaard0b8268a2020-08-05 16:11:29 +020067 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "shram", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010068
69 def all():
Louis Verhaard0b8268a2020-08-05 16:11:29 +020070 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash, MemArea.Shram)
Tim Hall79d07d22020-04-27 18:20:16 +010071
72 def __str__(self):
73 return self.name
74
75
76class TensorPurpose(enum.IntFlag):
77 Unknown = 0
78 Weights = 1
79 FeatureMap = 2
80 Scratch = 3
Fredrik Svedberga0c36242020-06-03 15:43:31 +020081 LUT = 4
82 Size = 5
Tim Hall79d07d22020-04-27 18:20:16 +010083
84 def display_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020085 return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010086
87 def identifier_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020088 return ("unknown", "weights", "feature_map", "scratch", "lut", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010089
90 def all():
91 return (TensorPurpose.Weights, TensorPurpose.FeatureMap)
92
93
94class TensorSubPurpose(enum.Enum):
95 Standard = 0
96 DoubleBuffer = 1
97 RollingBufferX = 2
98 RollingBufferY = 3
99 RollingBufferXY = 4
100
101 def display_name(self):
102 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
103
104 def identifier_name(self):
105 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
106
107 def all():
108 return (
109 TensorSubPurpose.Standard,
110 TensorSubPurpose.DoubleBuffer,
111 TensorSubPurpose.RollingBufferX,
112 TensorSubPurpose.RollingBufferY,
113 TensorSubPurpose.RollingBufferXY,
114 )
115
116
117class TensorFormat(enum.Flag):
118 Unknown = 0
119 WeightsCompressed = 1
120 NHWC = 2
121 NHCWB16 = 3
122
123 def __str__(self):
124 return self.name
125
126
127class TensorBlockTraversal(enum.Enum):
128 Default = 0
129 DepthWise = 1
130 DepthFirst = 2
131 PartKernelFirst = 3
132
133
134def shape_num_elements(shp):
135 elems = 1
136 if shp is None:
137 return None
138 for d in shp:
139 if d is None:
140 return None
141 elems *= d
142 return elems
143
144
145def shape_fully_defined(shp):
146 if shp is None:
147 return False
148 for d in shp:
149 if d is None:
150 return False
151 return True
152
153
154def shape_round_to_quantum(shp, quantum):
155 new_shp = list(shp)
156
157 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
158 for i in range(-1, -len(shp) - 1, -1):
159 if new_shp[i] is not None:
160 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
161 return new_shp
162
163
Louis Verhaard9db529a2020-09-23 10:27:11 +0200164@lru_cache(maxsize=None)
165def create_equivalence_id(key):
166 # Generates equivalence_id based on the given key.
167 return uuid.uuid4()
168
169
Tim Hall79d07d22020-04-27 18:20:16 +0100170class QuantizationParameters:
171 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
172
173 def __init__(self, min=None, max=None, num_bits=None, narrow_range=None):
174 self.min = min
175 self.max = max
176
177 self.num_bits = num_bits
178 self.narrow_range = narrow_range
179
180 self.scale_f32 = None
181 self.zero_point = None
182 self.quant_min = None
183 self.quant_max = None
184
185 def __str__(self):
186 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
187 self.min,
188 self.max,
189 self.num_bits,
190 self.scale_f32,
191 self.zero_point,
192 )
193
194 __repr__ = __str__
195
196 def clone(self):
197 res = QuantizationParameters()
198 res.min = self.min
199 res.max = self.max
200
201 res.num_bits = self.num_bits
202 res.narrow_range = self.narrow_range
203
204 res.scale_f32 = self.scale_f32
205 res.zero_point = self.zero_point
206 res.quant_min = self.quant_min
207 res.quant_max = self.quant_max
208 return res
209
210 def dequantize(self, values):
211 if self.zero_point.size == 1 and self.scale_f32.size == 1:
212 # same scale is used for all values
213 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
214 else:
215 # a different scale is used for different sets of values
216 values_as_float = values.astype(np.float64)
217
218 # this is not compatible with the format of depthwise weights,
219 # where input is at index 3 (Output, Kh, Kw, Input)
220 # return the quantized values
221 return np.ndarray((values_as_float.shape))
222
223 shape = values_as_float.shape[0]
224 assert self.zero_point.size == self.scale_f32.size == shape
225 res = np.ndarray(values_as_float.shape)
226 for i in range(shape):
227 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
228
229 return res
230
Tim Halle3786ac2020-07-28 17:40:50 +0100231 def is_scaling_equal(self, other):
232 if other is None or not isinstance(other, QuantizationParameters):
233 return False
234
235 return self.scale_f32 == other.scale_f32 and self.zero_point == other.zero_point
236
Tim Hall79d07d22020-04-27 18:20:16 +0100237
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100238def create_const_tensor(name, shape, dtype, values, value_dtype=None, purpose=TensorPurpose.Unknown, quantization=None):
239 # Tensor
240 const_tensor = Tensor(shape, dtype, name + "_0")
241 const_tensor.purpose = purpose
242 const_tensor.quantization = quantization
243 const_tensor.values = np.array(values, dtype=value_dtype)
Jacob Bohlina41cd4d2020-08-26 18:21:28 +0200244 const_tensor.quant_values = np.frombuffer(const_tensor.values.tobytes(), dtype=np.uint8)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100245 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200246 const_op = Operation(Op.Const, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100247 const_op.set_output_tensor(const_tensor)
248 return const_tensor
249
250
251def create_reshape_tensor(tens, shape, ifm_reshape=True):
252 if shape == tens.shape:
253 return tens
254 # Tensors
255 name = tens.name + "_reshape"
256 reshape_ifm = tens
257 reshape_ofm = tens.clone("_reshaped")
258 reshape_ofm.set_all_shapes(shape)
259 if not ifm_reshape:
260 reshape_ifm, reshape_ofm = reshape_ofm, reshape_ifm
261 # Operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200262 reshape_op = Operation(Op.Reshape, name)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100263 reshape_op.attrs["new_shape"] = shape
264 reshape_op.add_input_tensor(reshape_ifm)
265 reshape_op.add_input_tensor(create_const_tensor(name + "_shape", [1], DataType.int32, shape))
266 reshape_op.set_output_tensor(reshape_ofm)
267 return reshape_ofm if ifm_reshape else reshape_ifm
268
269
Jacob Bohlin1a666972020-09-11 10:04:15 +0200270# class that keeps track of all tensor addresses in the different memory types
271class TensorAddressMap:
272 address_map = defaultdict(dict) # dict (tens.equivalence_id -> dict (mem_type -> address))
273
274 @classmethod
275 def get_address_for_tens(cls, tens_id, mem_type):
276 return cls.address_map[tens_id].get(mem_type)
277
278 @classmethod
279 def set_address_for_tens(cls, tens_id, mem_type, address):
280 # Check previous address if there is one
281 previous_address = cls.address_map[tens_id].get(mem_type)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200282 if address is not None and previous_address is not None:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200283 assert previous_address == address, "Two different addresses cannot be assigned to the same tensor."
284
285 # Set tensor's address for memory type
286 cls.address_map[tens_id][mem_type] = address
287
288
Tim Hall79d07d22020-04-27 18:20:16 +0100289class Tensor:
290 __slots__ = (
291 "shape",
292 "storage_shape",
293 "bandwidth_shape",
294 "dtype",
295 "name",
296 "ops",
297 "consumer_list",
298 "values",
299 "quant_values",
300 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100301 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100302 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200303 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100304 "format",
305 "purpose",
306 "sub_purpose",
307 "alignment",
308 "weight_transpose_depthwise",
309 "storage_compression_scale",
310 "bandwidth_compression_scale",
311 "compression_scale_for_worst_weight_stream",
312 "weight_compression_scales",
313 "weight_compression_config",
Louis Verhaard9db529a2020-09-23 10:27:11 +0200314 "value_id",
Tim Hall79d07d22020-04-27 18:20:16 +0100315 "storage_rounding_quantum",
316 "brick_size",
Tim Hall79d07d22020-04-27 18:20:16 +0100317 "quantization",
318 "weight_compressed_offsets",
319 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100320 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100321 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200322 "resampling_mode",
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200323 "avoid_NHCWB16",
Tim Hall79d07d22020-04-27 18:20:16 +0100324 )
325 AllocationQuantum = 16
326
327 def __init__(self, shape, dtype, name):
328 self.shape = shape
329 self.storage_shape = shape
330 self.bandwidth_shape = shape
331 self.dtype = dtype
332 self.name = name
333 self.equivalence_id = uuid.uuid4()
334
335 self.ops = []
336 self.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100337
338 self.values = None
339 self.quant_values = None
340 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100341 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100342 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200343 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100344 self.format = TensorFormat.Unknown
345 self.purpose = TensorPurpose.Unknown
346 self.sub_purpose = TensorSubPurpose.Standard
347 self.alignment = Tensor.AllocationQuantum
348 self.weight_transpose_depthwise = False
349
350 self.storage_compression_scale = 1.0
351 self.bandwidth_compression_scale = 1.0
352 self.compression_scale_for_worst_weight_stream = 1.0
353 self.weight_compression_scales = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200354 # if two tensors have the same weight_compression_config, then they have the same compressed values
Tim Hall79d07d22020-04-27 18:20:16 +0100355 self.weight_compression_config = None
Louis Verhaard9db529a2020-09-23 10:27:11 +0200356 # if two tensors have the same value_id, then they have the same values
357 self.value_id = uuid.uuid4()
Tim Hall79d07d22020-04-27 18:20:16 +0100358 self.weight_compressed_offsets = []
359 self.storage_rounding_quantum = (1, 1, 1, 1)
360 self.brick_size = (1, 1, 1, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100361 self.element_size_bytes = 0
362
363 # quantization parameters
364 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100365 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200366 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100367
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200368 self.avoid_NHCWB16 = False
369
Jacob Bohlin1a666972020-09-11 10:04:15 +0200370 @property
371 def address(self):
372 return TensorAddressMap.get_address_for_tens(self.equivalence_id, self.mem_type)
373
374 @address.setter
375 def address(self, address):
376 TensorAddressMap.set_address_for_tens(self.equivalence_id, self.mem_type, address)
377
Tim Hall79d07d22020-04-27 18:20:16 +0100378 def element_size(self):
379 if self.element_size_bytes == 0:
380 return self.dtype.size_in_bits() / 8
381 return self.element_size_bytes
382
383 def clone(self, suffix="_clone"):
384 res = Tensor(self.shape, self.dtype, self.name + suffix)
385 res.storage_shape = list(self.storage_shape)
386 res.bandwidth_shape = list(self.bandwidth_shape)
387
388 res.ops = []
389 res.consumer_list = []
Tim Hall79d07d22020-04-27 18:20:16 +0100390
391 res.values = self.values
392 res.quant_values = self.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100393 res.mem_area = self.mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200394 res.mem_type = self.mem_type
Tim Hall79d07d22020-04-27 18:20:16 +0100395 res.format = self.format
396 res.purpose = self.purpose
397 res.sub_purpose = self.sub_purpose
398 res.alignment = self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100399 res.bandwidth_compression_scale = self.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100400 res.storage_rounding_quantum = self.storage_rounding_quantum
Tim Hall79d07d22020-04-27 18:20:16 +0100401
402 if self.quantization is not None:
403 res.quantization = self.quantization.clone()
404 else:
405 res.quantization = None
406
Dwight Lidmana9390f72020-05-13 12:00:08 +0200407 res.resampling_mode = self.resampling_mode
408
Louis Verhaard3c07c972020-05-07 08:12:58 +0200409 res.copy_compressed_weight_info(self)
Patrik Gustavsson458a2082020-08-13 13:41:05 +0200410 res.avoid_NHCWB16 = self.avoid_NHCWB16
Tim Hall79d07d22020-04-27 18:20:16 +0100411 return res
412
413 def clone_into_fast_storage(self, arch):
414 res = self.clone(suffix="_fast_storage")
415 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200416 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100417 return res
418
Louis Verhaard3c07c972020-05-07 08:12:58 +0200419 def copy_compressed_weight_info(self, src_tens):
420 # Copies compressed values + all related weight compression info from the given tensor
Louis Verhaard9db529a2020-09-23 10:27:11 +0200421 self.equivalence_id = src_tens.equivalence_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200422 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100423 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200424 self.storage_shape = src_tens.storage_shape
425 self.brick_size = src_tens.brick_size
426 self.weight_compression_scales = src_tens.weight_compression_scales
427 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
428 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
429 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
430 self.storage_compression_scale = src_tens.storage_compression_scale
431 self.block_traversal = src_tens.block_traversal
432 self.weight_compression_config = src_tens.weight_compression_config
Louis Verhaard9db529a2020-09-23 10:27:11 +0200433 self.value_id = src_tens.value_id
Louis Verhaard3c07c972020-05-07 08:12:58 +0200434
Tim Hall79d07d22020-04-27 18:20:16 +0100435 def set_format(self, fmt, arch):
436 self.format = fmt
437 shape_len = 0
438 try:
439 shape_len = len(self.shape)
440 except TypeError:
441 pass
442
443 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
444 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100445 self.brick_size = arch.brick_sizes[self.format]
446 self.brick_size = self.brick_size[-shape_len:]
447 if self.shape is None:
448 return
449
450 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
451 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
452
453 if fmt == TensorFormat.WeightsCompressed:
454 compression_ratio = 5 / 8
455 self.storage_compression_scale = compression_ratio
456 self.bandwidth_compression_scale = compression_ratio
457 self.compression_scale_for_worst_weight_stream = compression_ratio
458
459 def storage_elements(self):
460 elems = shape_num_elements(self.storage_shape)
461 if elems is None:
462 return 0
463 return elems
464
465 def elements(self):
466 elems = shape_num_elements(self.shape)
467 if elems is None:
468 return 0
469 return elems
470
471 def has_fully_defined_shape(self):
472 return shape_fully_defined(self.shape)
473
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200474 def storage_size(self, scale=1.0):
475 raw_size = self.storage_elements() * self.element_size() * scale
Tim Hall79d07d22020-04-27 18:20:16 +0100476 if raw_size == 0:
477 raw_size = 1 # force it to take up space
478 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
479 return rounded_size
480
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200481 def storage_size_for_sub_purpose(self, arch, sub_purpose, param_a=None, param_b=None):
Tim Hall79d07d22020-04-27 18:20:16 +0100482 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
483 elems = shape_num_elements(alt_shape)
484 if elems is None:
485 return 0
486 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Patrik Gustavsson90831bc2020-08-24 16:26:11 +0200487 raw_size = (
488 elems
489 * self.element_size()
490 * self.compression_scale_for_worst_weight_stream
491 * arch.weight_estimation_scaling
492 )
Tim Hall79d07d22020-04-27 18:20:16 +0100493 else:
Patrik Gustavsson9baa4c32020-08-20 13:59:01 +0200494 # Rolling buffers are used for intermediate data in ifm streaming
495 # These will all use the NHCWB16 format, and need to be aligned to 16 in the C-dimension
496 if alt_shape[-1] % 16 != 0:
497 nhcwb16_shape = alt_shape[0:-1] + [numeric_util.round_up(alt_shape[-1], 16)]
498 elems = shape_num_elements(nhcwb16_shape)
499
Tim Hall79d07d22020-04-27 18:20:16 +0100500 raw_size = elems * self.element_size() * self.storage_compression_scale
501 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
502 return rounded_size
503
504 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100505 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200506 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100507 assert len(shp) >= 2
508 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100509 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200510 shp = list(self.storage_shape)
511 if sub_purpose == TensorSubPurpose.RollingBufferX:
512 assert len(shp) == 4
513 shp[0] = 1
514 shp[2] = min(shp[2], param_a)
515 elif sub_purpose == TensorSubPurpose.RollingBufferY:
516 assert len(shp) == 4
517 shp[0] = 1
518 shp[1] = min(shp[1], param_a)
519 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
520 assert len(shp) == 4
521 shp[0] = 1
522 shp[2] = min(shp[2], param_a)
523 shp[1] = min(shp[1], param_b)
524 elif sub_purpose == TensorSubPurpose.Standard:
525 pass
526 else:
527 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
528
Tim Hall79d07d22020-04-27 18:20:16 +0100529 return shp
530
531 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
532 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
533 self.sub_purpose = sub_purpose
534 if sub_purpose == TensorSubPurpose.DoubleBuffer:
535 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
536
537 def bandwidth(self):
538 elems = shape_num_elements(self.bandwidth_shape)
539 if elems is None:
540 return 0
541 return elems * self.element_size() * self.bandwidth_compression_scale
542
543 def consumers(self):
544 return self.consumer_list
545
546 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
547 if self.sub_purpose in set(
548 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
549 ):
550 # build dummy coordinates that cover the entire buffer
551 start_coord = [0] * len(start_coord)
552 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
553
554 start = self.address_for_coordinate(start_coord, is_top_box=False)
555 end = self.address_for_coordinate(end_coord, is_top_box=True)
556 return MemoryRangeSet(self.mem_area, start, end)
557
558 def addresses_for_rolling_buffer(self, start_coord, end_coord):
559 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
560
561 if len(start_coord) < 4:
562 box_height0 = 1
563 box_width = 1
564
565 if len(start_coord) >= 2:
566 box_width = end_coord[-2] - start_coord[-2]
567
568 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
569
570 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
571 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
572
573 crossing_y = min(crossing_y, end_coord[1])
574 crossing_x = min(crossing_x, end_coord[2])
575
576 box_height0 = crossing_y - start_coord[1]
577 box_width = crossing_x - start_coord[2]
578
579 addresses = [None] * 4
580 addresses[0] = self.address_for_coordinate(start_coord)
581
582 if end_coord[2] > crossing_x:
583 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
584 raise Exception("Striping in vertical direction is not supported")
585 if end_coord[1] > crossing_y:
586 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
587 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
588 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
589
590 return box_height0, box_height0, box_width, addresses
591
592 def address_for_coordinate(self, coord, is_top_box=False):
593 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
594
595 def get_strides_and_coord(self, coord=None):
596 if coord is None:
597 coord = [0] * len(self.storage_shape)
598
599 augmented_coord = coord
600 augmented_shape = self.storage_shape
601 while len(augmented_shape) < 4:
602 augmented_shape = [1] + augmented_shape
603
604 while len(augmented_coord) < 4:
605 augmented_coord = [0] + augmented_coord
606
607 assert len(augmented_coord) == len(augmented_shape)
608
609 if self.format == TensorFormat.NHWC:
610 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
611 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
612 stride_order = [4, 1, 3, 2, 0]
613
614 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200615 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100616 augmented_shape = augmented_shape[0:4] + [1]
617 augmented_coord = (
618 [augmented_coord[0], augmented_coord[3] // channel_divisor]
619 + augmented_coord[1:3]
620 + [augmented_coord[3] % channel_divisor]
621 )
622
623 if augmented_shape[1] == 0:
624 augmented_shape[1] = 1
625
626 else:
627 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
628 return None, None
629
630 strides = [0] * len(augmented_shape)
631 stride = self.element_size() * self.storage_compression_scale
632
633 if self.format != TensorFormat.NHCWB16:
634 for i in stride_order:
635 strides[i] = stride
636 stride *= augmented_shape[i]
637 else:
638 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100639 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200640 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100641 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200642 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100643 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
644
645 return strides, augmented_coord
646
647 def get_strides(self):
648 strides, _ = self.get_strides_and_coord()
649
650 return strides
651
Louis Verhaard3c07c972020-05-07 08:12:58 +0200652 def needs_dma(self):
Louis Verhaardaee5d752020-09-30 09:01:52 +0200653 return len(self.ops) == 1 and self.ops[0].type == Op.DMA
Louis Verhaard3c07c972020-05-07 08:12:58 +0200654
655 def get_dma_src_tensor(self):
656 # For weight tensors that need DMA: returns the source tensor in Flash, else None
657 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
658 return self.ops[0].inputs[0] if self.needs_dma() else None
659
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200660 def find_npu_op(self):
661 # Returns the NPU operator that uses this tensor, excluding DMA operators.
662 for op in self.consumers():
Louis Verhaardaee5d752020-09-30 09:01:52 +0200663 if op.type == Op.DMA:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200664 return op.outputs[0].find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200665 if op.run_on_npu:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200666 return op
667 return None
668
Tim Hall79d07d22020-04-27 18:20:16 +0100669 def compressed_stream_index_from_coord(self, coord):
670 assert self.format == TensorFormat.WeightsCompressed
671 assert len(self.compressed_values) > 0
672 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
673
674 depth = coord[-1]
675 brick_depth = self.brick_size[-1]
676 # Clamp position at final element index
677 if depth > self.shape[-1]:
678 depth = self.shape[-1]
679
680 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100681 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100682
683 # Check boundaries on all but last weight set (which may be shorter
684 # than the brick we divided it up into)
685 if index < len(self.weight_compressed_offsets) - 1:
686 # There are no half-way points in the weights
687 if (depth % brick_depth) != 0:
688 raise Exception("Offset into weights must be aligned to a brick")
689
690 return index
691
692 def size_of_compressed_stream(self, index):
693 assert 0 <= index < len(self.compressed_values)
694 return len(self.compressed_values[index])
695
696 def is_last_index_in_compressed_stream(self, index):
697 assert 0 <= index < len(self.compressed_values)
698 return index == len(self.compressed_values) - 1
699
700 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
701 address_offset = 0
702 coord = orig_coord
703
704 coord = coord[-len(self.storage_shape) :]
705
706 if self.sub_purpose == TensorSubPurpose.Standard:
707 for idx, c in enumerate(coord):
708 if is_top_box:
709 assert c > 0 and c <= self.shape[idx]
710 else:
711 assert c >= 0 and c < self.shape[idx]
712
713 if self.format == TensorFormat.WeightsCompressed:
714 if len(self.weight_compressed_offsets) == 0:
715 return 0
716
Louis Verhaard3c07c972020-05-07 08:12:58 +0200717 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100718 depth = orig_coord[-1]
719 brick_depth = self.brick_size[-1]
720 # Clamp position at final element index
721 if depth > self.shape[-1]:
722 depth = self.shape[-1]
723
724 # Always round up to next boundary
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100725 index = numeric_util.round_up_divide(depth, brick_depth)
Tim Hall79d07d22020-04-27 18:20:16 +0100726 index = index % 2
727
728 if len(self.compressed_values) <= 2:
729 if is_top_box and index == 0:
730 for cv in self.compressed_values:
731 address_offset += len(cv)
732 else:
733 address_offset = index * len(self.compressed_values[0])
734 else:
735 if is_top_box and index == 0:
736 address_offset = self.storage_shape[-1]
737 else:
738 address_offset = index * (self.storage_shape[-1] // 2)
739 else:
740 index = self.compressed_stream_index_from_coord(orig_coord)
741 assert index < len(self.weight_compressed_offsets)
742 address_offset = self.weight_compressed_offsets[index]
743 else:
744 if is_top_box:
745 coord = [c - 1 for c in coord]
746
747 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
748 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
749
750 strides, augmented_coord = self.get_strides_and_coord(coord)
751 if strides is None:
752 return None
753
754 if is_top_box:
755 address_offset += 1 * strides[-1] # one element
756
757 address_offset += np.dot(augmented_coord, strides)
758
759 assert address_offset >= 0
760 assert address_offset <= self.storage_size()
761 return address_offset
762
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200763 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
764 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
765 return True
766 return False
767
Louis Verhaardb9fc33c2020-08-13 11:47:36 +0200768 def is_scaling_equal(self, tens):
769 return self.quantization.is_scaling_equal(tens.quantization)
770
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200771 def equivalent(self, tens):
772 return self.equivalence_id == tens.equivalence_id
773
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100774 def set_all_shapes(self, shape):
775 self.shape = shape
776 self.storage_shape = shape
777 self.bandwidth_shape = shape
778
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100779 def get_full_shape(self):
780 d = len(self.shape)
781 if d in (1, 3):
Michael McGeagh8d3216f2020-08-10 11:35:57 +0100782 return numeric_util.full_shape(4, self.shape, 1)
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100783 elif d == 2:
784 return [self.shape[0], 1, 1, self.shape[1]]
785 else:
Fredrik Svedberg835d8e12020-09-04 09:46:17 +0200786 return self.shape.copy()
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100787
Tim Hall79d07d22020-04-27 18:20:16 +0100788 def __str__(self):
789 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
790
791 __repr__ = __str__