blob: 98487324b7f67d23fde60c8334d054efc3724c5c [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
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
22
23from . import numeric_util
Michael McGeagh5778ffd2020-08-06 17:31:02 +010024from .data_type import DataType
Dwight Lidmana9390f72020-05-13 12:00:08 +020025from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Tim Hall79d07d22020-04-27 18:20:16 +010026from .numeric_util import round_up_divide
Michael McGeagh5778ffd2020-08-06 17:31:02 +010027from .operation import Operation
Diego Russoe8a10452020-04-21 17:39:10 +010028from .range_set import MemoryRangeSet
Tim Hall79d07d22020-04-27 18:20:16 +010029
30
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020031class MemType(enum.IntFlag):
32 Unknown = 0
33 Permanent_NPU = 1
34 Permanent_CPU = 2
35 Scratch = 3
36 Scratch_fast = 4
37 Size = Scratch_fast + 1
38
39 def display_name(self):
40 return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value]
41
42 def identifier_name(self):
43 return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value]
44
45 def all():
46 return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast)
47
48 def __str__(self):
49 return self.name
50
51
Tim Hall79d07d22020-04-27 18:20:16 +010052class MemArea(enum.IntFlag):
53 Unknown = 0
54 Sram = 1
55 Dram = 2
56 OnChipFlash = 3
57 OffChipFlash = 4
58 Size = OffChipFlash + 1
59
60 def display_name(self):
61 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "Size")[self.value]
62
63 def identifier_name(self):
64 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "size")[self.value]
65
66 def all():
67 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash)
68
69 def __str__(self):
70 return self.name
71
72
73class TensorPurpose(enum.IntFlag):
74 Unknown = 0
75 Weights = 1
76 FeatureMap = 2
77 Scratch = 3
Fredrik Svedberga0c36242020-06-03 15:43:31 +020078 LUT = 4
79 Size = 5
Tim Hall79d07d22020-04-27 18:20:16 +010080
81 def display_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020082 return ("Unknown", "Weights", "FeatureMap", "Scratch", "LUT", "Size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010083
84 def identifier_name(self):
Fredrik Svedberga0c36242020-06-03 15:43:31 +020085 return ("unknown", "weights", "feature_map", "scratch", "lut", "size")[self.value]
Tim Hall79d07d22020-04-27 18:20:16 +010086
87 def all():
88 return (TensorPurpose.Weights, TensorPurpose.FeatureMap)
89
90
91class 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
114class 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
124class TensorBlockTraversal(enum.Enum):
125 Default = 0
126 DepthWise = 1
127 DepthFirst = 2
128 PartKernelFirst = 3
129
130
131def 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
142def 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
151def 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
161class 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 Lidmanebe26c72020-06-09 11:40:54 +0200187 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 Hall79d07d22020-04-27 18:20:16 +0100200 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 McGeagh5778ffd2020-08-06 17:31:02 +0100236def 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
249def 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 Hall79d07d22020-04-27 18:20:16 +0100268class 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 Hallf7e810a2020-06-25 15:04:31 +0100280 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100281 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200282 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100283 "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 Hall79d07d22020-04-27 18:20:16 +0100299 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100300 "cpu_tensor",
301 "npu_tensor",
302 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200303 "resampling_mode",
Tim Hall79d07d22020-04-27 18:20:16 +0100304 )
305 AllocationQuantum = 16
306
307 def __init__(self, shape, dtype, name):
308 self.shape = shape
309 self.storage_shape = shape
310 self.bandwidth_shape = shape
311 self.dtype = dtype
312 self.name = name
313 self.equivalence_id = uuid.uuid4()
314
315 self.ops = []
316 self.consumer_list = []
317 # Below attributes are only set if a tensor has been cloned,
318 # either from Cpu -> Npu or vice versa. Needed for offline allocation
319 self.cpu_tensor = None # reference to the corresponding Cpu tensor
320 self.npu_tensor = None # reference to the corresponding Npu tensor
321
322 self.values = None
323 self.quant_values = None
324 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100325 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100326 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200327 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100328 self.format = TensorFormat.Unknown
329 self.purpose = TensorPurpose.Unknown
330 self.sub_purpose = TensorSubPurpose.Standard
331 self.alignment = Tensor.AllocationQuantum
332 self.weight_transpose_depthwise = False
333
334 self.storage_compression_scale = 1.0
335 self.bandwidth_compression_scale = 1.0
336 self.compression_scale_for_worst_weight_stream = 1.0
337 self.weight_compression_scales = None
338 self.weight_compression_config = None
339 self.weight_compressed_offsets = []
340 self.storage_rounding_quantum = (1, 1, 1, 1)
341 self.brick_size = (1, 1, 1, 1)
Charles Xu04ce34c2020-06-23 12:42:28 +0200342 self.address = None # start address of tensor. will be filled in by tensor allocator
Tim Hall79d07d22020-04-27 18:20:16 +0100343 self.element_size_bytes = 0
344
345 # quantization parameters
346 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100347 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200348 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100349
350 def element_size(self):
351 if self.element_size_bytes == 0:
352 return self.dtype.size_in_bits() / 8
353 return self.element_size_bytes
354
355 def clone(self, suffix="_clone"):
356 res = Tensor(self.shape, self.dtype, self.name + suffix)
357 res.storage_shape = list(self.storage_shape)
358 res.bandwidth_shape = list(self.bandwidth_shape)
359
360 res.ops = []
361 res.consumer_list = []
362 res.equivalence_id = self.equivalence_id
363
364 res.values = self.values
365 res.quant_values = self.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100366 res.mem_area = self.mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200367 res.mem_type = self.mem_type
Tim Hall79d07d22020-04-27 18:20:16 +0100368 res.format = self.format
369 res.purpose = self.purpose
370 res.sub_purpose = self.sub_purpose
371 res.alignment = self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100372 res.bandwidth_compression_scale = self.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100373 res.storage_rounding_quantum = self.storage_rounding_quantum
Charles Xu04ce34c2020-06-23 12:42:28 +0200374 res.address = None
Tim Hall79d07d22020-04-27 18:20:16 +0100375
376 if self.quantization is not None:
377 res.quantization = self.quantization.clone()
378 else:
379 res.quantization = None
380
Dwight Lidmana9390f72020-05-13 12:00:08 +0200381 res.resampling_mode = self.resampling_mode
382
Louis Verhaard3c07c972020-05-07 08:12:58 +0200383 res.copy_compressed_weight_info(self)
Tim Hall79d07d22020-04-27 18:20:16 +0100384 return res
385
386 def clone_into_fast_storage(self, arch):
387 res = self.clone(suffix="_fast_storage")
388 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200389 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100390 return res
391
Louis Verhaard3c07c972020-05-07 08:12:58 +0200392 def copy_compressed_weight_info(self, src_tens):
393 # Copies compressed values + all related weight compression info from the given tensor
394 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100395 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200396 self.storage_shape = src_tens.storage_shape
397 self.brick_size = src_tens.brick_size
398 self.weight_compression_scales = src_tens.weight_compression_scales
399 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
400 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
401 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
402 self.storage_compression_scale = src_tens.storage_compression_scale
403 self.block_traversal = src_tens.block_traversal
404 self.weight_compression_config = src_tens.weight_compression_config
405
Tim Hall79d07d22020-04-27 18:20:16 +0100406 def set_format(self, fmt, arch):
407 self.format = fmt
408 shape_len = 0
409 try:
410 shape_len = len(self.shape)
411 except TypeError:
412 pass
413
414 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
415 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100416 self.brick_size = arch.brick_sizes[self.format]
417 self.brick_size = self.brick_size[-shape_len:]
418 if self.shape is None:
419 return
420
421 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
422 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
423
424 if fmt == TensorFormat.WeightsCompressed:
425 compression_ratio = 5 / 8
426 self.storage_compression_scale = compression_ratio
427 self.bandwidth_compression_scale = compression_ratio
428 self.compression_scale_for_worst_weight_stream = compression_ratio
429
430 def storage_elements(self):
431 elems = shape_num_elements(self.storage_shape)
432 if elems is None:
433 return 0
434 return elems
435
436 def elements(self):
437 elems = shape_num_elements(self.shape)
438 if elems is None:
439 return 0
440 return elems
441
442 def has_fully_defined_shape(self):
443 return shape_fully_defined(self.shape)
444
445 def storage_size(self):
446 raw_size = self.storage_elements() * self.element_size()
447 if raw_size == 0:
448 raw_size = 1 # force it to take up space
449 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
450 return rounded_size
451
452 def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
453 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
454 elems = shape_num_elements(alt_shape)
455 if elems is None:
456 return 0
457 if sub_purpose == TensorSubPurpose.DoubleBuffer:
458 raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream
459 else:
460 raw_size = elems * self.element_size() * self.storage_compression_scale
461 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
462 return rounded_size
463
464 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100465 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200466 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100467 assert len(shp) >= 2
468 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100469 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200470 shp = list(self.storage_shape)
471 if sub_purpose == TensorSubPurpose.RollingBufferX:
472 assert len(shp) == 4
473 shp[0] = 1
474 shp[2] = min(shp[2], param_a)
475 elif sub_purpose == TensorSubPurpose.RollingBufferY:
476 assert len(shp) == 4
477 shp[0] = 1
478 shp[1] = min(shp[1], param_a)
479 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
480 assert len(shp) == 4
481 shp[0] = 1
482 shp[2] = min(shp[2], param_a)
483 shp[1] = min(shp[1], param_b)
484 elif sub_purpose == TensorSubPurpose.Standard:
485 pass
486 else:
487 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
488
Tim Hall79d07d22020-04-27 18:20:16 +0100489 return shp
490
491 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
492 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
493 self.sub_purpose = sub_purpose
494 if sub_purpose == TensorSubPurpose.DoubleBuffer:
495 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
496
497 def bandwidth(self):
498 elems = shape_num_elements(self.bandwidth_shape)
499 if elems is None:
500 return 0
501 return elems * self.element_size() * self.bandwidth_compression_scale
502
503 def consumers(self):
504 return self.consumer_list
505
506 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
507 if self.sub_purpose in set(
508 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
509 ):
510 # build dummy coordinates that cover the entire buffer
511 start_coord = [0] * len(start_coord)
512 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
513
514 start = self.address_for_coordinate(start_coord, is_top_box=False)
515 end = self.address_for_coordinate(end_coord, is_top_box=True)
516 return MemoryRangeSet(self.mem_area, start, end)
517
518 def addresses_for_rolling_buffer(self, start_coord, end_coord):
519 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
520
521 if len(start_coord) < 4:
522 box_height0 = 1
523 box_width = 1
524
525 if len(start_coord) >= 2:
526 box_width = end_coord[-2] - start_coord[-2]
527
528 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
529
530 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
531 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
532
533 crossing_y = min(crossing_y, end_coord[1])
534 crossing_x = min(crossing_x, end_coord[2])
535
536 box_height0 = crossing_y - start_coord[1]
537 box_width = crossing_x - start_coord[2]
538
539 addresses = [None] * 4
540 addresses[0] = self.address_for_coordinate(start_coord)
541
542 if end_coord[2] > crossing_x:
543 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
544 raise Exception("Striping in vertical direction is not supported")
545 if end_coord[1] > crossing_y:
546 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
547 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
548 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
549
550 return box_height0, box_height0, box_width, addresses
551
552 def address_for_coordinate(self, coord, is_top_box=False):
553 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
554
555 def get_strides_and_coord(self, coord=None):
556 if coord is None:
557 coord = [0] * len(self.storage_shape)
558
559 augmented_coord = coord
560 augmented_shape = self.storage_shape
561 while len(augmented_shape) < 4:
562 augmented_shape = [1] + augmented_shape
563
564 while len(augmented_coord) < 4:
565 augmented_coord = [0] + augmented_coord
566
567 assert len(augmented_coord) == len(augmented_shape)
568
569 if self.format == TensorFormat.NHWC:
570 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
571 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
572 stride_order = [4, 1, 3, 2, 0]
573
574 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200575 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100576 augmented_shape = augmented_shape[0:4] + [1]
577 augmented_coord = (
578 [augmented_coord[0], augmented_coord[3] // channel_divisor]
579 + augmented_coord[1:3]
580 + [augmented_coord[3] % channel_divisor]
581 )
582
583 if augmented_shape[1] == 0:
584 augmented_shape[1] = 1
585
586 else:
587 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
588 return None, None
589
590 strides = [0] * len(augmented_shape)
591 stride = self.element_size() * self.storage_compression_scale
592
593 if self.format != TensorFormat.NHCWB16:
594 for i in stride_order:
595 strides[i] = stride
596 stride *= augmented_shape[i]
597 else:
598 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100599 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200600 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100601 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200602 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100603 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
604
605 return strides, augmented_coord
606
607 def get_strides(self):
608 strides, _ = self.get_strides_and_coord()
609
610 return strides
611
Louis Verhaard3c07c972020-05-07 08:12:58 +0200612 def needs_dma(self):
613 return len(self.ops) == 1 and self.ops[0].type == "DMA"
614
615 def get_dma_src_tensor(self):
616 # For weight tensors that need DMA: returns the source tensor in Flash, else None
617 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
618 return self.ops[0].inputs[0] if self.needs_dma() else None
619
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200620 def find_npu_op(self):
621 # Returns the NPU operator that uses this tensor, excluding DMA operators.
622 for op in self.consumers():
623 if op.type == "DMA":
624 return op.outputs[0].find_npu_op()
625 if "npu_block_type" in op.attrs:
626 return op
627 return None
628
Tim Hall79d07d22020-04-27 18:20:16 +0100629 def compressed_stream_index_from_coord(self, coord):
630 assert self.format == TensorFormat.WeightsCompressed
631 assert len(self.compressed_values) > 0
632 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
633
634 depth = coord[-1]
635 brick_depth = self.brick_size[-1]
636 # Clamp position at final element index
637 if depth > self.shape[-1]:
638 depth = self.shape[-1]
639
640 # Always round up to next boundary
641 index = round_up_divide(depth, brick_depth)
642
643 # Check boundaries on all but last weight set (which may be shorter
644 # than the brick we divided it up into)
645 if index < len(self.weight_compressed_offsets) - 1:
646 # There are no half-way points in the weights
647 if (depth % brick_depth) != 0:
648 raise Exception("Offset into weights must be aligned to a brick")
649
650 return index
651
652 def size_of_compressed_stream(self, index):
653 assert 0 <= index < len(self.compressed_values)
654 return len(self.compressed_values[index])
655
656 def is_last_index_in_compressed_stream(self, index):
657 assert 0 <= index < len(self.compressed_values)
658 return index == len(self.compressed_values) - 1
659
660 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
661 address_offset = 0
662 coord = orig_coord
663
664 coord = coord[-len(self.storage_shape) :]
665
666 if self.sub_purpose == TensorSubPurpose.Standard:
667 for idx, c in enumerate(coord):
668 if is_top_box:
669 assert c > 0 and c <= self.shape[idx]
670 else:
671 assert c >= 0 and c < self.shape[idx]
672
673 if self.format == TensorFormat.WeightsCompressed:
674 if len(self.weight_compressed_offsets) == 0:
675 return 0
676
Louis Verhaard3c07c972020-05-07 08:12:58 +0200677 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100678 depth = orig_coord[-1]
679 brick_depth = self.brick_size[-1]
680 # Clamp position at final element index
681 if depth > self.shape[-1]:
682 depth = self.shape[-1]
683
684 # Always round up to next boundary
685 index = round_up_divide(depth, brick_depth)
686 index = index % 2
687
688 if len(self.compressed_values) <= 2:
689 if is_top_box and index == 0:
690 for cv in self.compressed_values:
691 address_offset += len(cv)
692 else:
693 address_offset = index * len(self.compressed_values[0])
694 else:
695 if is_top_box and index == 0:
696 address_offset = self.storage_shape[-1]
697 else:
698 address_offset = index * (self.storage_shape[-1] // 2)
699 else:
700 index = self.compressed_stream_index_from_coord(orig_coord)
701 assert index < len(self.weight_compressed_offsets)
702 address_offset = self.weight_compressed_offsets[index]
703 else:
704 if is_top_box:
705 coord = [c - 1 for c in coord]
706
707 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
708 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
709
710 strides, augmented_coord = self.get_strides_and_coord(coord)
711 if strides is None:
712 return None
713
714 if is_top_box:
715 address_offset += 1 * strides[-1] # one element
716
717 address_offset += np.dot(augmented_coord, strides)
718
719 assert address_offset >= 0
720 assert address_offset <= self.storage_size()
721 return address_offset
722
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200723 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
724 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
725 return True
726 return False
727
Michael McGeagh6a8d4242020-07-28 12:17:59 +0100728 def set_all_shapes(self, shape):
729 self.shape = shape
730 self.storage_shape = shape
731 self.bandwidth_shape = shape
732
Michael McGeagh5778ffd2020-08-06 17:31:02 +0100733 def get_full_shape(self):
734 d = len(self.shape)
735 if d in (1, 3):
736 return [1] * (4 - d) + self.shape
737 elif d == 2:
738 return [self.shape[0], 1, 1, self.shape[1]]
739 else:
740 return self.shape
741
Tim Hall79d07d22020-04-27 18:20:16 +0100742 def __str__(self):
743 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
744
745 __repr__ = __str__