blob: 42ba853d6e0afc1f6c91f4a38b9e54012312b78f [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
Dwight Lidmana9390f72020-05-13 12:00:08 +020024from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Tim Hall79d07d22020-04-27 18:20:16 +010025from .numeric_util import round_up_divide
Diego Russoe8a10452020-04-21 17:39:10 +010026from .range_set import MemoryRangeSet
Tim Hall79d07d22020-04-27 18:20:16 +010027
28
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020029class MemType(enum.IntFlag):
30 Unknown = 0
31 Permanent_NPU = 1
32 Permanent_CPU = 2
33 Scratch = 3
34 Scratch_fast = 4
35 Size = Scratch_fast + 1
36
37 def display_name(self):
38 return ("Unknown", "Permanent_NPU", "Permanent_CPU", "Scratch", "Scratch_fast", "Size")[self.value]
39
40 def identifier_name(self):
41 return ("unknown", "permanent_npu", "permanent_cpu", "scratch", "scratch_fast", "size")[self.value]
42
43 def all():
44 return (MemType.Permanent_NPU, MemType.Permanent_CPU, MemType.Scratch, MemType.Scratch_fast)
45
46 def __str__(self):
47 return self.name
48
49
Tim Hall79d07d22020-04-27 18:20:16 +010050class MemArea(enum.IntFlag):
51 Unknown = 0
52 Sram = 1
53 Dram = 2
54 OnChipFlash = 3
55 OffChipFlash = 4
56 Size = OffChipFlash + 1
57
58 def display_name(self):
59 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "Size")[self.value]
60
61 def identifier_name(self):
62 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "size")[self.value]
63
64 def all():
65 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash)
66
67 def __str__(self):
68 return self.name
69
70
71class TensorPurpose(enum.IntFlag):
72 Unknown = 0
73 Weights = 1
74 FeatureMap = 2
75 Scratch = 3
76 Size = 4
77
78 def display_name(self):
79 return ("Unknown", "Weights", "FeatureMap", "Scratch", "Size")[self.value]
80
81 def identifier_name(self):
82 return ("unknown", "weights", "feature_map", "scratch", "size")[self.value]
83
84 def all():
85 return (TensorPurpose.Weights, TensorPurpose.FeatureMap)
86
87
88class TensorSubPurpose(enum.Enum):
89 Standard = 0
90 DoubleBuffer = 1
91 RollingBufferX = 2
92 RollingBufferY = 3
93 RollingBufferXY = 4
94
95 def display_name(self):
96 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
97
98 def identifier_name(self):
99 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
100
101 def all():
102 return (
103 TensorSubPurpose.Standard,
104 TensorSubPurpose.DoubleBuffer,
105 TensorSubPurpose.RollingBufferX,
106 TensorSubPurpose.RollingBufferY,
107 TensorSubPurpose.RollingBufferXY,
108 )
109
110
111class TensorFormat(enum.Flag):
112 Unknown = 0
113 WeightsCompressed = 1
114 NHWC = 2
115 NHCWB16 = 3
116
117 def __str__(self):
118 return self.name
119
120
121class TensorBlockTraversal(enum.Enum):
122 Default = 0
123 DepthWise = 1
124 DepthFirst = 2
125 PartKernelFirst = 3
126
127
128def shape_num_elements(shp):
129 elems = 1
130 if shp is None:
131 return None
132 for d in shp:
133 if d is None:
134 return None
135 elems *= d
136 return elems
137
138
139def shape_fully_defined(shp):
140 if shp is None:
141 return False
142 for d in shp:
143 if d is None:
144 return False
145 return True
146
147
148def shape_round_to_quantum(shp, quantum):
149 new_shp = list(shp)
150
151 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
152 for i in range(-1, -len(shp) - 1, -1):
153 if new_shp[i] is not None:
154 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
155 return new_shp
156
157
158class QuantizationParameters:
159 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
160
161 def __init__(self, min=None, max=None, num_bits=None, narrow_range=None):
162 self.min = min
163 self.max = max
164
165 self.num_bits = num_bits
166 self.narrow_range = narrow_range
167
168 self.scale_f32 = None
169 self.zero_point = None
170 self.quant_min = None
171 self.quant_max = None
172
173 def __str__(self):
174 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
175 self.min,
176 self.max,
177 self.num_bits,
178 self.scale_f32,
179 self.zero_point,
180 )
181
182 __repr__ = __str__
183
Dwight Lidmanebe26c72020-06-09 11:40:54 +0200184 def __eq__(self, other):
185 if other is None:
186 return False
187 if not isinstance(other, QuantizationParameters):
188 return False
189
190 pairs = ((getattr(self, s), getattr(other, s)) for s in QuantizationParameters.__slots__)
191
192 return all(np.array_equal(a, b) for a, b in pairs)
193
194 def __ne__(self, other):
195 return not self == other
196
Tim Hall79d07d22020-04-27 18:20:16 +0100197 def clone(self):
198 res = QuantizationParameters()
199 res.min = self.min
200 res.max = self.max
201
202 res.num_bits = self.num_bits
203 res.narrow_range = self.narrow_range
204
205 res.scale_f32 = self.scale_f32
206 res.zero_point = self.zero_point
207 res.quant_min = self.quant_min
208 res.quant_max = self.quant_max
209 return res
210
211 def dequantize(self, values):
212 if self.zero_point.size == 1 and self.scale_f32.size == 1:
213 # same scale is used for all values
214 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
215 else:
216 # a different scale is used for different sets of values
217 values_as_float = values.astype(np.float64)
218
219 # this is not compatible with the format of depthwise weights,
220 # where input is at index 3 (Output, Kh, Kw, Input)
221 # return the quantized values
222 return np.ndarray((values_as_float.shape))
223
224 shape = values_as_float.shape[0]
225 assert self.zero_point.size == self.scale_f32.size == shape
226 res = np.ndarray(values_as_float.shape)
227 for i in range(shape):
228 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
229
230 return res
231
232
233class Tensor:
234 __slots__ = (
235 "shape",
236 "storage_shape",
237 "bandwidth_shape",
238 "dtype",
239 "name",
240 "ops",
241 "consumer_list",
242 "values",
243 "quant_values",
244 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100245 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100246 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200247 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100248 "format",
249 "purpose",
250 "sub_purpose",
251 "alignment",
252 "weight_transpose_depthwise",
253 "storage_compression_scale",
254 "bandwidth_compression_scale",
255 "compression_scale_for_worst_weight_stream",
256 "weight_compression_scales",
257 "weight_compression_config",
258 "storage_rounding_quantum",
259 "brick_size",
260 "address",
261 "quantization",
262 "weight_compressed_offsets",
263 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100264 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100265 "cpu_tensor",
266 "npu_tensor",
267 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200268 "resampling_mode",
Tim Hall79d07d22020-04-27 18:20:16 +0100269 )
270 AllocationQuantum = 16
271
272 def __init__(self, shape, dtype, name):
273 self.shape = shape
274 self.storage_shape = shape
275 self.bandwidth_shape = shape
276 self.dtype = dtype
277 self.name = name
278 self.equivalence_id = uuid.uuid4()
279
280 self.ops = []
281 self.consumer_list = []
282 # Below attributes are only set if a tensor has been cloned,
283 # either from Cpu -> Npu or vice versa. Needed for offline allocation
284 self.cpu_tensor = None # reference to the corresponding Cpu tensor
285 self.npu_tensor = None # reference to the corresponding Npu tensor
286
287 self.values = None
288 self.quant_values = None
289 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100290 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100291 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200292 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100293 self.format = TensorFormat.Unknown
294 self.purpose = TensorPurpose.Unknown
295 self.sub_purpose = TensorSubPurpose.Standard
296 self.alignment = Tensor.AllocationQuantum
297 self.weight_transpose_depthwise = False
298
299 self.storage_compression_scale = 1.0
300 self.bandwidth_compression_scale = 1.0
301 self.compression_scale_for_worst_weight_stream = 1.0
302 self.weight_compression_scales = None
303 self.weight_compression_config = None
304 self.weight_compressed_offsets = []
305 self.storage_rounding_quantum = (1, 1, 1, 1)
306 self.brick_size = (1, 1, 1, 1)
Charles Xu04ce34c2020-06-23 12:42:28 +0200307 self.address = None # start address of tensor. will be filled in by tensor allocator
Tim Hall79d07d22020-04-27 18:20:16 +0100308 self.element_size_bytes = 0
309
310 # quantization parameters
311 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100312 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200313 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100314
315 def element_size(self):
316 if self.element_size_bytes == 0:
317 return self.dtype.size_in_bits() / 8
318 return self.element_size_bytes
319
320 def clone(self, suffix="_clone"):
321 res = Tensor(self.shape, self.dtype, self.name + suffix)
322 res.storage_shape = list(self.storage_shape)
323 res.bandwidth_shape = list(self.bandwidth_shape)
324
325 res.ops = []
326 res.consumer_list = []
327 res.equivalence_id = self.equivalence_id
328
329 res.values = self.values
330 res.quant_values = self.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100331 res.mem_area = self.mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200332 res.mem_type = self.mem_type
Tim Hall79d07d22020-04-27 18:20:16 +0100333 res.format = self.format
334 res.purpose = self.purpose
335 res.sub_purpose = self.sub_purpose
336 res.alignment = self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100337 res.bandwidth_compression_scale = self.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100338 res.storage_rounding_quantum = self.storage_rounding_quantum
Charles Xu04ce34c2020-06-23 12:42:28 +0200339 res.address = None
Tim Hall79d07d22020-04-27 18:20:16 +0100340
341 if self.quantization is not None:
342 res.quantization = self.quantization.clone()
343 else:
344 res.quantization = None
345
Dwight Lidmana9390f72020-05-13 12:00:08 +0200346 res.resampling_mode = self.resampling_mode
347
Louis Verhaard3c07c972020-05-07 08:12:58 +0200348 res.copy_compressed_weight_info(self)
Tim Hall79d07d22020-04-27 18:20:16 +0100349 return res
350
351 def clone_into_fast_storage(self, arch):
352 res = self.clone(suffix="_fast_storage")
353 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200354 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100355 return res
356
Louis Verhaard3c07c972020-05-07 08:12:58 +0200357 def copy_compressed_weight_info(self, src_tens):
358 # Copies compressed values + all related weight compression info from the given tensor
359 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100360 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200361 self.storage_shape = src_tens.storage_shape
362 self.brick_size = src_tens.brick_size
363 self.weight_compression_scales = src_tens.weight_compression_scales
364 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
365 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
366 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
367 self.storage_compression_scale = src_tens.storage_compression_scale
368 self.block_traversal = src_tens.block_traversal
369 self.weight_compression_config = src_tens.weight_compression_config
370
Tim Hall79d07d22020-04-27 18:20:16 +0100371 def set_format(self, fmt, arch):
372 self.format = fmt
373 shape_len = 0
374 try:
375 shape_len = len(self.shape)
376 except TypeError:
377 pass
378
379 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
380 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100381 self.brick_size = arch.brick_sizes[self.format]
382 self.brick_size = self.brick_size[-shape_len:]
383 if self.shape is None:
384 return
385
386 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
387 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
388
389 if fmt == TensorFormat.WeightsCompressed:
390 compression_ratio = 5 / 8
391 self.storage_compression_scale = compression_ratio
392 self.bandwidth_compression_scale = compression_ratio
393 self.compression_scale_for_worst_weight_stream = compression_ratio
394
395 def storage_elements(self):
396 elems = shape_num_elements(self.storage_shape)
397 if elems is None:
398 return 0
399 return elems
400
401 def elements(self):
402 elems = shape_num_elements(self.shape)
403 if elems is None:
404 return 0
405 return elems
406
407 def has_fully_defined_shape(self):
408 return shape_fully_defined(self.shape)
409
410 def storage_size(self):
411 raw_size = self.storage_elements() * self.element_size()
412 if raw_size == 0:
413 raw_size = 1 # force it to take up space
414 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
415 return rounded_size
416
417 def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
418 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
419 elems = shape_num_elements(alt_shape)
420 if elems is None:
421 return 0
422 if sub_purpose == TensorSubPurpose.DoubleBuffer:
423 raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream
424 else:
425 raw_size = elems * self.element_size() * self.storage_compression_scale
426 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
427 return rounded_size
428
429 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100430 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200431 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100432 assert len(shp) >= 2
433 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100434 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200435 shp = list(self.storage_shape)
436 if sub_purpose == TensorSubPurpose.RollingBufferX:
437 assert len(shp) == 4
438 shp[0] = 1
439 shp[2] = min(shp[2], param_a)
440 elif sub_purpose == TensorSubPurpose.RollingBufferY:
441 assert len(shp) == 4
442 shp[0] = 1
443 shp[1] = min(shp[1], param_a)
444 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
445 assert len(shp) == 4
446 shp[0] = 1
447 shp[2] = min(shp[2], param_a)
448 shp[1] = min(shp[1], param_b)
449 elif sub_purpose == TensorSubPurpose.Standard:
450 pass
451 else:
452 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
453
Tim Hall79d07d22020-04-27 18:20:16 +0100454 return shp
455
456 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
457 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
458 self.sub_purpose = sub_purpose
459 if sub_purpose == TensorSubPurpose.DoubleBuffer:
460 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
461
462 def bandwidth(self):
463 elems = shape_num_elements(self.bandwidth_shape)
464 if elems is None:
465 return 0
466 return elems * self.element_size() * self.bandwidth_compression_scale
467
468 def consumers(self):
469 return self.consumer_list
470
471 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
472 if self.sub_purpose in set(
473 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
474 ):
475 # build dummy coordinates that cover the entire buffer
476 start_coord = [0] * len(start_coord)
477 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
478
479 start = self.address_for_coordinate(start_coord, is_top_box=False)
480 end = self.address_for_coordinate(end_coord, is_top_box=True)
481 return MemoryRangeSet(self.mem_area, start, end)
482
483 def addresses_for_rolling_buffer(self, start_coord, end_coord):
484 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
485
486 if len(start_coord) < 4:
487 box_height0 = 1
488 box_width = 1
489
490 if len(start_coord) >= 2:
491 box_width = end_coord[-2] - start_coord[-2]
492
493 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
494
495 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
496 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
497
498 crossing_y = min(crossing_y, end_coord[1])
499 crossing_x = min(crossing_x, end_coord[2])
500
501 box_height0 = crossing_y - start_coord[1]
502 box_width = crossing_x - start_coord[2]
503
504 addresses = [None] * 4
505 addresses[0] = self.address_for_coordinate(start_coord)
506
507 if end_coord[2] > crossing_x:
508 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
509 raise Exception("Striping in vertical direction is not supported")
510 if end_coord[1] > crossing_y:
511 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
512 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
513 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
514
515 return box_height0, box_height0, box_width, addresses
516
517 def address_for_coordinate(self, coord, is_top_box=False):
518 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
519
520 def get_strides_and_coord(self, coord=None):
521 if coord is None:
522 coord = [0] * len(self.storage_shape)
523
524 augmented_coord = coord
525 augmented_shape = self.storage_shape
526 while len(augmented_shape) < 4:
527 augmented_shape = [1] + augmented_shape
528
529 while len(augmented_coord) < 4:
530 augmented_coord = [0] + augmented_coord
531
532 assert len(augmented_coord) == len(augmented_shape)
533
534 if self.format == TensorFormat.NHWC:
535 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
536 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
537 stride_order = [4, 1, 3, 2, 0]
538
539 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200540 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100541 augmented_shape = augmented_shape[0:4] + [1]
542 augmented_coord = (
543 [augmented_coord[0], augmented_coord[3] // channel_divisor]
544 + augmented_coord[1:3]
545 + [augmented_coord[3] % channel_divisor]
546 )
547
548 if augmented_shape[1] == 0:
549 augmented_shape[1] = 1
550
551 else:
552 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
553 return None, None
554
555 strides = [0] * len(augmented_shape)
556 stride = self.element_size() * self.storage_compression_scale
557
558 if self.format != TensorFormat.NHCWB16:
559 for i in stride_order:
560 strides[i] = stride
561 stride *= augmented_shape[i]
562 else:
563 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100564 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200565 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100566 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200567 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100568 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
569
570 return strides, augmented_coord
571
572 def get_strides(self):
573 strides, _ = self.get_strides_and_coord()
574
575 return strides
576
Louis Verhaard3c07c972020-05-07 08:12:58 +0200577 def needs_dma(self):
578 return len(self.ops) == 1 and self.ops[0].type == "DMA"
579
580 def get_dma_src_tensor(self):
581 # For weight tensors that need DMA: returns the source tensor in Flash, else None
582 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
583 return self.ops[0].inputs[0] if self.needs_dma() else None
584
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200585 def find_npu_op(self):
586 # Returns the NPU operator that uses this tensor, excluding DMA operators.
587 for op in self.consumers():
588 if op.type == "DMA":
589 return op.outputs[0].find_npu_op()
590 if "npu_block_type" in op.attrs:
591 return op
592 return None
593
Tim Hall79d07d22020-04-27 18:20:16 +0100594 def compressed_stream_index_from_coord(self, coord):
595 assert self.format == TensorFormat.WeightsCompressed
596 assert len(self.compressed_values) > 0
597 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
598
599 depth = coord[-1]
600 brick_depth = self.brick_size[-1]
601 # Clamp position at final element index
602 if depth > self.shape[-1]:
603 depth = self.shape[-1]
604
605 # Always round up to next boundary
606 index = round_up_divide(depth, brick_depth)
607
608 # Check boundaries on all but last weight set (which may be shorter
609 # than the brick we divided it up into)
610 if index < len(self.weight_compressed_offsets) - 1:
611 # There are no half-way points in the weights
612 if (depth % brick_depth) != 0:
613 raise Exception("Offset into weights must be aligned to a brick")
614
615 return index
616
617 def size_of_compressed_stream(self, index):
618 assert 0 <= index < len(self.compressed_values)
619 return len(self.compressed_values[index])
620
621 def is_last_index_in_compressed_stream(self, index):
622 assert 0 <= index < len(self.compressed_values)
623 return index == len(self.compressed_values) - 1
624
625 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
626 address_offset = 0
627 coord = orig_coord
628
629 coord = coord[-len(self.storage_shape) :]
630
631 if self.sub_purpose == TensorSubPurpose.Standard:
632 for idx, c in enumerate(coord):
633 if is_top_box:
634 assert c > 0 and c <= self.shape[idx]
635 else:
636 assert c >= 0 and c < self.shape[idx]
637
638 if self.format == TensorFormat.WeightsCompressed:
639 if len(self.weight_compressed_offsets) == 0:
640 return 0
641
Louis Verhaard3c07c972020-05-07 08:12:58 +0200642 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100643 depth = orig_coord[-1]
644 brick_depth = self.brick_size[-1]
645 # Clamp position at final element index
646 if depth > self.shape[-1]:
647 depth = self.shape[-1]
648
649 # Always round up to next boundary
650 index = round_up_divide(depth, brick_depth)
651 index = index % 2
652
653 if len(self.compressed_values) <= 2:
654 if is_top_box and index == 0:
655 for cv in self.compressed_values:
656 address_offset += len(cv)
657 else:
658 address_offset = index * len(self.compressed_values[0])
659 else:
660 if is_top_box and index == 0:
661 address_offset = self.storage_shape[-1]
662 else:
663 address_offset = index * (self.storage_shape[-1] // 2)
664 else:
665 index = self.compressed_stream_index_from_coord(orig_coord)
666 assert index < len(self.weight_compressed_offsets)
667 address_offset = self.weight_compressed_offsets[index]
668 else:
669 if is_top_box:
670 coord = [c - 1 for c in coord]
671
672 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
673 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
674
675 strides, augmented_coord = self.get_strides_and_coord(coord)
676 if strides is None:
677 return None
678
679 if is_top_box:
680 address_offset += 1 * strides[-1] # one element
681
682 address_offset += np.dot(augmented_coord, strides)
683
684 assert address_offset >= 0
685 assert address_offset <= self.storage_size()
686 return address_offset
687
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200688 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
689 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
690 return True
691 return False
692
Tim Hall79d07d22020-04-27 18:20:16 +0100693 def __str__(self):
694 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
695
696 __repr__ = __str__