blob: 5e97cfe8097dd06c66f96af118e8eec1bab844c0 [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
184 def clone(self):
185 res = QuantizationParameters()
186 res.min = self.min
187 res.max = self.max
188
189 res.num_bits = self.num_bits
190 res.narrow_range = self.narrow_range
191
192 res.scale_f32 = self.scale_f32
193 res.zero_point = self.zero_point
194 res.quant_min = self.quant_min
195 res.quant_max = self.quant_max
196 return res
197
198 def dequantize(self, values):
199 if self.zero_point.size == 1 and self.scale_f32.size == 1:
200 # same scale is used for all values
201 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
202 else:
203 # a different scale is used for different sets of values
204 values_as_float = values.astype(np.float64)
205
206 # this is not compatible with the format of depthwise weights,
207 # where input is at index 3 (Output, Kh, Kw, Input)
208 # return the quantized values
209 return np.ndarray((values_as_float.shape))
210
211 shape = values_as_float.shape[0]
212 assert self.zero_point.size == self.scale_f32.size == shape
213 res = np.ndarray(values_as_float.shape)
214 for i in range(shape):
215 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
216
217 return res
218
219
220class Tensor:
221 __slots__ = (
222 "shape",
223 "storage_shape",
224 "bandwidth_shape",
225 "dtype",
226 "name",
227 "ops",
228 "consumer_list",
229 "values",
230 "quant_values",
231 "compressed_values",
Tim Hallf7e810a2020-06-25 15:04:31 +0100232 "compressed_values_substream_offsets",
Tim Hall79d07d22020-04-27 18:20:16 +0100233 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200234 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100235 "format",
236 "purpose",
237 "sub_purpose",
238 "alignment",
239 "weight_transpose_depthwise",
240 "storage_compression_scale",
241 "bandwidth_compression_scale",
242 "compression_scale_for_worst_weight_stream",
243 "weight_compression_scales",
244 "weight_compression_config",
245 "storage_rounding_quantum",
246 "brick_size",
247 "address",
248 "quantization",
249 "weight_compressed_offsets",
250 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100251 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100252 "cpu_tensor",
253 "npu_tensor",
254 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200255 "resampling_mode",
Tim Hall79d07d22020-04-27 18:20:16 +0100256 )
257 AllocationQuantum = 16
258
259 def __init__(self, shape, dtype, name):
260 self.shape = shape
261 self.storage_shape = shape
262 self.bandwidth_shape = shape
263 self.dtype = dtype
264 self.name = name
265 self.equivalence_id = uuid.uuid4()
266
267 self.ops = []
268 self.consumer_list = []
269 # Below attributes are only set if a tensor has been cloned,
270 # either from Cpu -> Npu or vice versa. Needed for offline allocation
271 self.cpu_tensor = None # reference to the corresponding Cpu tensor
272 self.npu_tensor = None # reference to the corresponding Npu tensor
273
274 self.values = None
275 self.quant_values = None
276 self.compressed_values = None
Tim Hallf7e810a2020-06-25 15:04:31 +0100277 self.compressed_values_substream_offsets = None
Tim Hall79d07d22020-04-27 18:20:16 +0100278 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200279 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100280 self.format = TensorFormat.Unknown
281 self.purpose = TensorPurpose.Unknown
282 self.sub_purpose = TensorSubPurpose.Standard
283 self.alignment = Tensor.AllocationQuantum
284 self.weight_transpose_depthwise = False
285
286 self.storage_compression_scale = 1.0
287 self.bandwidth_compression_scale = 1.0
288 self.compression_scale_for_worst_weight_stream = 1.0
289 self.weight_compression_scales = None
290 self.weight_compression_config = None
291 self.weight_compressed_offsets = []
292 self.storage_rounding_quantum = (1, 1, 1, 1)
293 self.brick_size = (1, 1, 1, 1)
Charles Xu04ce34c2020-06-23 12:42:28 +0200294 self.address = None # start address of tensor. will be filled in by tensor allocator
Tim Hall79d07d22020-04-27 18:20:16 +0100295 self.element_size_bytes = 0
296
297 # quantization parameters
298 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100299 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200300 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100301
302 def element_size(self):
303 if self.element_size_bytes == 0:
304 return self.dtype.size_in_bits() / 8
305 return self.element_size_bytes
306
307 def clone(self, suffix="_clone"):
308 res = Tensor(self.shape, self.dtype, self.name + suffix)
309 res.storage_shape = list(self.storage_shape)
310 res.bandwidth_shape = list(self.bandwidth_shape)
311
312 res.ops = []
313 res.consumer_list = []
314 res.equivalence_id = self.equivalence_id
315
316 res.values = self.values
317 res.quant_values = self.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100318 res.mem_area = self.mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200319 res.mem_type = self.mem_type
Tim Hall79d07d22020-04-27 18:20:16 +0100320 res.format = self.format
321 res.purpose = self.purpose
322 res.sub_purpose = self.sub_purpose
323 res.alignment = self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100324 res.bandwidth_compression_scale = self.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100325 res.storage_rounding_quantum = self.storage_rounding_quantum
Charles Xu04ce34c2020-06-23 12:42:28 +0200326 res.address = None
Tim Hall79d07d22020-04-27 18:20:16 +0100327
328 if self.quantization is not None:
329 res.quantization = self.quantization.clone()
330 else:
331 res.quantization = None
332
Dwight Lidmana9390f72020-05-13 12:00:08 +0200333 res.resampling_mode = self.resampling_mode
334
Louis Verhaard3c07c972020-05-07 08:12:58 +0200335 res.copy_compressed_weight_info(self)
Tim Hall79d07d22020-04-27 18:20:16 +0100336 return res
337
338 def clone_into_fast_storage(self, arch):
339 res = self.clone(suffix="_fast_storage")
340 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200341 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100342 return res
343
Louis Verhaard3c07c972020-05-07 08:12:58 +0200344 def copy_compressed_weight_info(self, src_tens):
345 # Copies compressed values + all related weight compression info from the given tensor
346 self.compressed_values = src_tens.compressed_values
Tim Hallf7e810a2020-06-25 15:04:31 +0100347 self.compressed_values_substream_offsets = src_tens.compressed_values_substream_offsets
Louis Verhaard3c07c972020-05-07 08:12:58 +0200348 self.storage_shape = src_tens.storage_shape
349 self.brick_size = src_tens.brick_size
350 self.weight_compression_scales = src_tens.weight_compression_scales
351 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
352 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
353 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
354 self.storage_compression_scale = src_tens.storage_compression_scale
355 self.block_traversal = src_tens.block_traversal
356 self.weight_compression_config = src_tens.weight_compression_config
357
Tim Hall79d07d22020-04-27 18:20:16 +0100358 def set_format(self, fmt, arch):
359 self.format = fmt
360 shape_len = 0
361 try:
362 shape_len = len(self.shape)
363 except TypeError:
364 pass
365
366 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
367 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100368 self.brick_size = arch.brick_sizes[self.format]
369 self.brick_size = self.brick_size[-shape_len:]
370 if self.shape is None:
371 return
372
373 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
374 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
375
376 if fmt == TensorFormat.WeightsCompressed:
377 compression_ratio = 5 / 8
378 self.storage_compression_scale = compression_ratio
379 self.bandwidth_compression_scale = compression_ratio
380 self.compression_scale_for_worst_weight_stream = compression_ratio
381
382 def storage_elements(self):
383 elems = shape_num_elements(self.storage_shape)
384 if elems is None:
385 return 0
386 return elems
387
388 def elements(self):
389 elems = shape_num_elements(self.shape)
390 if elems is None:
391 return 0
392 return elems
393
394 def has_fully_defined_shape(self):
395 return shape_fully_defined(self.shape)
396
397 def storage_size(self):
398 raw_size = self.storage_elements() * self.element_size()
399 if raw_size == 0:
400 raw_size = 1 # force it to take up space
401 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
402 return rounded_size
403
404 def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
405 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
406 elems = shape_num_elements(alt_shape)
407 if elems is None:
408 return 0
409 if sub_purpose == TensorSubPurpose.DoubleBuffer:
410 raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream
411 else:
412 raw_size = elems * self.element_size() * self.storage_compression_scale
413 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
414 return rounded_size
415
416 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
Tim Hall79d07d22020-04-27 18:20:16 +0100417 if sub_purpose == TensorSubPurpose.DoubleBuffer:
Jacob Bohline843d332020-06-23 12:12:56 +0200418 shp = list(self.shape)
Tim Hall79d07d22020-04-27 18:20:16 +0100419 assert len(shp) >= 2
420 shp[-1] = min(shp[-1], param_a * 2)
Tim Hall79d07d22020-04-27 18:20:16 +0100421 else:
Jacob Bohline843d332020-06-23 12:12:56 +0200422 shp = list(self.storage_shape)
423 if sub_purpose == TensorSubPurpose.RollingBufferX:
424 assert len(shp) == 4
425 shp[0] = 1
426 shp[2] = min(shp[2], param_a)
427 elif sub_purpose == TensorSubPurpose.RollingBufferY:
428 assert len(shp) == 4
429 shp[0] = 1
430 shp[1] = min(shp[1], param_a)
431 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
432 assert len(shp) == 4
433 shp[0] = 1
434 shp[2] = min(shp[2], param_a)
435 shp[1] = min(shp[1], param_b)
436 elif sub_purpose == TensorSubPurpose.Standard:
437 pass
438 else:
439 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
440
Tim Hall79d07d22020-04-27 18:20:16 +0100441 return shp
442
443 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
444 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
445 self.sub_purpose = sub_purpose
446 if sub_purpose == TensorSubPurpose.DoubleBuffer:
447 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
448
449 def bandwidth(self):
450 elems = shape_num_elements(self.bandwidth_shape)
451 if elems is None:
452 return 0
453 return elems * self.element_size() * self.bandwidth_compression_scale
454
455 def consumers(self):
456 return self.consumer_list
457
458 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
459 if self.sub_purpose in set(
460 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
461 ):
462 # build dummy coordinates that cover the entire buffer
463 start_coord = [0] * len(start_coord)
464 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
465
466 start = self.address_for_coordinate(start_coord, is_top_box=False)
467 end = self.address_for_coordinate(end_coord, is_top_box=True)
468 return MemoryRangeSet(self.mem_area, start, end)
469
470 def addresses_for_rolling_buffer(self, start_coord, end_coord):
471 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
472
473 if len(start_coord) < 4:
474 box_height0 = 1
475 box_width = 1
476
477 if len(start_coord) >= 2:
478 box_width = end_coord[-2] - start_coord[-2]
479
480 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
481
482 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
483 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
484
485 crossing_y = min(crossing_y, end_coord[1])
486 crossing_x = min(crossing_x, end_coord[2])
487
488 box_height0 = crossing_y - start_coord[1]
489 box_width = crossing_x - start_coord[2]
490
491 addresses = [None] * 4
492 addresses[0] = self.address_for_coordinate(start_coord)
493
494 if end_coord[2] > crossing_x:
495 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
496 raise Exception("Striping in vertical direction is not supported")
497 if end_coord[1] > crossing_y:
498 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
499 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
500 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
501
502 return box_height0, box_height0, box_width, addresses
503
504 def address_for_coordinate(self, coord, is_top_box=False):
505 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
506
507 def get_strides_and_coord(self, coord=None):
508 if coord is None:
509 coord = [0] * len(self.storage_shape)
510
511 augmented_coord = coord
512 augmented_shape = self.storage_shape
513 while len(augmented_shape) < 4:
514 augmented_shape = [1] + augmented_shape
515
516 while len(augmented_coord) < 4:
517 augmented_coord = [0] + augmented_coord
518
519 assert len(augmented_coord) == len(augmented_shape)
520
521 if self.format == TensorFormat.NHWC:
522 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
523 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
524 stride_order = [4, 1, 3, 2, 0]
525
526 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200527 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100528 augmented_shape = augmented_shape[0:4] + [1]
529 augmented_coord = (
530 [augmented_coord[0], augmented_coord[3] // channel_divisor]
531 + augmented_coord[1:3]
532 + [augmented_coord[3] % channel_divisor]
533 )
534
535 if augmented_shape[1] == 0:
536 augmented_shape[1] = 1
537
538 else:
539 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
540 return None, None
541
542 strides = [0] * len(augmented_shape)
543 stride = self.element_size() * self.storage_compression_scale
544
545 if self.format != TensorFormat.NHCWB16:
546 for i in stride_order:
547 strides[i] = stride
548 stride *= augmented_shape[i]
549 else:
550 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100551 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200552 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100553 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200554 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100555 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
556
557 return strides, augmented_coord
558
559 def get_strides(self):
560 strides, _ = self.get_strides_and_coord()
561
562 return strides
563
Louis Verhaard3c07c972020-05-07 08:12:58 +0200564 def needs_dma(self):
565 return len(self.ops) == 1 and self.ops[0].type == "DMA"
566
567 def get_dma_src_tensor(self):
568 # For weight tensors that need DMA: returns the source tensor in Flash, else None
569 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
570 return self.ops[0].inputs[0] if self.needs_dma() else None
571
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200572 def find_npu_op(self):
573 # Returns the NPU operator that uses this tensor, excluding DMA operators.
574 for op in self.consumers():
575 if op.type == "DMA":
576 return op.outputs[0].find_npu_op()
577 if "npu_block_type" in op.attrs:
578 return op
579 return None
580
Tim Hall79d07d22020-04-27 18:20:16 +0100581 def compressed_stream_index_from_coord(self, coord):
582 assert self.format == TensorFormat.WeightsCompressed
583 assert len(self.compressed_values) > 0
584 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
585
586 depth = coord[-1]
587 brick_depth = self.brick_size[-1]
588 # Clamp position at final element index
589 if depth > self.shape[-1]:
590 depth = self.shape[-1]
591
592 # Always round up to next boundary
593 index = round_up_divide(depth, brick_depth)
594
595 # Check boundaries on all but last weight set (which may be shorter
596 # than the brick we divided it up into)
597 if index < len(self.weight_compressed_offsets) - 1:
598 # There are no half-way points in the weights
599 if (depth % brick_depth) != 0:
600 raise Exception("Offset into weights must be aligned to a brick")
601
602 return index
603
604 def size_of_compressed_stream(self, index):
605 assert 0 <= index < len(self.compressed_values)
606 return len(self.compressed_values[index])
607
608 def is_last_index_in_compressed_stream(self, index):
609 assert 0 <= index < len(self.compressed_values)
610 return index == len(self.compressed_values) - 1
611
612 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
613 address_offset = 0
614 coord = orig_coord
615
616 coord = coord[-len(self.storage_shape) :]
617
618 if self.sub_purpose == TensorSubPurpose.Standard:
619 for idx, c in enumerate(coord):
620 if is_top_box:
621 assert c > 0 and c <= self.shape[idx]
622 else:
623 assert c >= 0 and c < self.shape[idx]
624
625 if self.format == TensorFormat.WeightsCompressed:
626 if len(self.weight_compressed_offsets) == 0:
627 return 0
628
Louis Verhaard3c07c972020-05-07 08:12:58 +0200629 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100630 depth = orig_coord[-1]
631 brick_depth = self.brick_size[-1]
632 # Clamp position at final element index
633 if depth > self.shape[-1]:
634 depth = self.shape[-1]
635
636 # Always round up to next boundary
637 index = round_up_divide(depth, brick_depth)
638 index = index % 2
639
640 if len(self.compressed_values) <= 2:
641 if is_top_box and index == 0:
642 for cv in self.compressed_values:
643 address_offset += len(cv)
644 else:
645 address_offset = index * len(self.compressed_values[0])
646 else:
647 if is_top_box and index == 0:
648 address_offset = self.storage_shape[-1]
649 else:
650 address_offset = index * (self.storage_shape[-1] // 2)
651 else:
652 index = self.compressed_stream_index_from_coord(orig_coord)
653 assert index < len(self.weight_compressed_offsets)
654 address_offset = self.weight_compressed_offsets[index]
655 else:
656 if is_top_box:
657 coord = [c - 1 for c in coord]
658
659 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
660 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
661
662 strides, augmented_coord = self.get_strides_and_coord(coord)
663 if strides is None:
664 return None
665
666 if is_top_box:
667 address_offset += 1 * strides[-1] # one element
668
669 address_offset += np.dot(augmented_coord, strides)
670
671 assert address_offset >= 0
672 assert address_offset <= self.storage_size()
673 return address_offset
674
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200675 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
676 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
677 return True
678 return False
679
Tim Hall79d07d22020-04-27 18:20:16 +0100680 def __str__(self):
681 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
682
683 __repr__ = __str__