blob: 3990164d361808a4fd84b9a36003e804a8d99ecb [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",
232 "mem_area",
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200233 "mem_type",
Tim Hall79d07d22020-04-27 18:20:16 +0100234 "format",
235 "purpose",
236 "sub_purpose",
237 "alignment",
238 "weight_transpose_depthwise",
239 "storage_compression_scale",
240 "bandwidth_compression_scale",
241 "compression_scale_for_worst_weight_stream",
242 "weight_compression_scales",
243 "weight_compression_config",
244 "storage_rounding_quantum",
245 "brick_size",
246 "address",
247 "quantization",
248 "weight_compressed_offsets",
249 "element_size_bytes",
Tim Hall79d07d22020-04-27 18:20:16 +0100250 "block_traversal",
Tim Hall79d07d22020-04-27 18:20:16 +0100251 "cpu_tensor",
252 "npu_tensor",
253 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200254 "resampling_mode",
Tim Hall79d07d22020-04-27 18:20:16 +0100255 )
256 AllocationQuantum = 16
257
258 def __init__(self, shape, dtype, name):
259 self.shape = shape
260 self.storage_shape = shape
261 self.bandwidth_shape = shape
262 self.dtype = dtype
263 self.name = name
264 self.equivalence_id = uuid.uuid4()
265
266 self.ops = []
267 self.consumer_list = []
268 # Below attributes are only set if a tensor has been cloned,
269 # either from Cpu -> Npu or vice versa. Needed for offline allocation
270 self.cpu_tensor = None # reference to the corresponding Cpu tensor
271 self.npu_tensor = None # reference to the corresponding Npu tensor
272
273 self.values = None
274 self.quant_values = None
275 self.compressed_values = None
276 self.mem_area = MemArea.Unknown
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200277 self.mem_type = MemType.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +0100278 self.format = TensorFormat.Unknown
279 self.purpose = TensorPurpose.Unknown
280 self.sub_purpose = TensorSubPurpose.Standard
281 self.alignment = Tensor.AllocationQuantum
282 self.weight_transpose_depthwise = False
283
284 self.storage_compression_scale = 1.0
285 self.bandwidth_compression_scale = 1.0
286 self.compression_scale_for_worst_weight_stream = 1.0
287 self.weight_compression_scales = None
288 self.weight_compression_config = None
289 self.weight_compressed_offsets = []
290 self.storage_rounding_quantum = (1, 1, 1, 1)
291 self.brick_size = (1, 1, 1, 1)
292 self.address = 0 # start address of tensor. will be filled in by tensor allocator
293 self.element_size_bytes = 0
294
295 # quantization parameters
296 self.quantization = None
Tim Hall79d07d22020-04-27 18:20:16 +0100297 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200298 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100299
300 def element_size(self):
301 if self.element_size_bytes == 0:
302 return self.dtype.size_in_bits() / 8
303 return self.element_size_bytes
304
305 def clone(self, suffix="_clone"):
306 res = Tensor(self.shape, self.dtype, self.name + suffix)
307 res.storage_shape = list(self.storage_shape)
308 res.bandwidth_shape = list(self.bandwidth_shape)
309
310 res.ops = []
311 res.consumer_list = []
312 res.equivalence_id = self.equivalence_id
313
314 res.values = self.values
315 res.quant_values = self.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100316 res.mem_area = self.mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200317 res.mem_type = self.mem_type
Tim Hall79d07d22020-04-27 18:20:16 +0100318 res.format = self.format
319 res.purpose = self.purpose
320 res.sub_purpose = self.sub_purpose
321 res.alignment = self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100322 res.bandwidth_compression_scale = self.bandwidth_compression_scale
Tim Hall79d07d22020-04-27 18:20:16 +0100323 res.storage_rounding_quantum = self.storage_rounding_quantum
Tim Hall79d07d22020-04-27 18:20:16 +0100324 res.address = 0
325
326 if self.quantization is not None:
327 res.quantization = self.quantization.clone()
328 else:
329 res.quantization = None
330
Dwight Lidmana9390f72020-05-13 12:00:08 +0200331 res.resampling_mode = self.resampling_mode
332
Louis Verhaard3c07c972020-05-07 08:12:58 +0200333 res.copy_compressed_weight_info(self)
Tim Hall79d07d22020-04-27 18:20:16 +0100334 return res
335
336 def clone_into_fast_storage(self, arch):
337 res = self.clone(suffix="_fast_storage")
338 res.mem_area = arch.fast_storage_mem_area
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200339 res.mem_type = MemType.Scratch_fast
Tim Hall79d07d22020-04-27 18:20:16 +0100340 return res
341
Louis Verhaard3c07c972020-05-07 08:12:58 +0200342 def copy_compressed_weight_info(self, src_tens):
343 # Copies compressed values + all related weight compression info from the given tensor
344 self.compressed_values = src_tens.compressed_values
345 self.storage_shape = src_tens.storage_shape
346 self.brick_size = src_tens.brick_size
347 self.weight_compression_scales = src_tens.weight_compression_scales
348 self.weight_compressed_offsets = src_tens.weight_compressed_offsets
349 self.weight_transpose_depthwise = src_tens.weight_transpose_depthwise
350 self.compression_scale_for_worst_weight_stream = src_tens.compression_scale_for_worst_weight_stream
351 self.storage_compression_scale = src_tens.storage_compression_scale
352 self.block_traversal = src_tens.block_traversal
353 self.weight_compression_config = src_tens.weight_compression_config
354
Tim Hall79d07d22020-04-27 18:20:16 +0100355 def set_format(self, fmt, arch):
356 self.format = fmt
357 shape_len = 0
358 try:
359 shape_len = len(self.shape)
360 except TypeError:
361 pass
362
363 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
364 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100365 self.brick_size = arch.brick_sizes[self.format]
366 self.brick_size = self.brick_size[-shape_len:]
367 if self.shape is None:
368 return
369
370 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
371 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
372
373 if fmt == TensorFormat.WeightsCompressed:
374 compression_ratio = 5 / 8
375 self.storage_compression_scale = compression_ratio
376 self.bandwidth_compression_scale = compression_ratio
377 self.compression_scale_for_worst_weight_stream = compression_ratio
378
379 def storage_elements(self):
380 elems = shape_num_elements(self.storage_shape)
381 if elems is None:
382 return 0
383 return elems
384
385 def elements(self):
386 elems = shape_num_elements(self.shape)
387 if elems is None:
388 return 0
389 return elems
390
391 def has_fully_defined_shape(self):
392 return shape_fully_defined(self.shape)
393
394 def storage_size(self):
395 raw_size = self.storage_elements() * self.element_size()
396 if raw_size == 0:
397 raw_size = 1 # force it to take up space
398 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
399 return rounded_size
400
401 def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
402 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
403 elems = shape_num_elements(alt_shape)
404 if elems is None:
405 return 0
406 if sub_purpose == TensorSubPurpose.DoubleBuffer:
407 raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream
408 else:
409 raw_size = elems * self.element_size() * self.storage_compression_scale
410 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
411 return rounded_size
412
413 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
414 shp = list(self.storage_shape)
415 if sub_purpose == TensorSubPurpose.DoubleBuffer:
416 assert len(shp) >= 2
417 shp[-1] = min(shp[-1], param_a * 2)
418 elif sub_purpose == TensorSubPurpose.RollingBufferX:
419 assert len(shp) == 4
420 shp[0] = 1
421 shp[2] = min(shp[2], param_a)
422 elif sub_purpose == TensorSubPurpose.RollingBufferY:
423 assert len(shp) == 4
424 shp[0] = 1
425 shp[1] = min(shp[1], param_a)
426 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
427 assert len(shp) == 4
428 shp[0] = 1
429 shp[2] = min(shp[2], param_a)
430 shp[1] = min(shp[1], param_b)
431 elif sub_purpose == TensorSubPurpose.Standard:
432 pass
433 else:
434 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
435 return shp
436
437 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
438 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
439 self.sub_purpose = sub_purpose
440 if sub_purpose == TensorSubPurpose.DoubleBuffer:
441 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
442
443 def bandwidth(self):
444 elems = shape_num_elements(self.bandwidth_shape)
445 if elems is None:
446 return 0
447 return elems * self.element_size() * self.bandwidth_compression_scale
448
449 def consumers(self):
450 return self.consumer_list
451
452 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
453 if self.sub_purpose in set(
454 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
455 ):
456 # build dummy coordinates that cover the entire buffer
457 start_coord = [0] * len(start_coord)
458 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
459
460 start = self.address_for_coordinate(start_coord, is_top_box=False)
461 end = self.address_for_coordinate(end_coord, is_top_box=True)
462 return MemoryRangeSet(self.mem_area, start, end)
463
464 def addresses_for_rolling_buffer(self, start_coord, end_coord):
465 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
466
467 if len(start_coord) < 4:
468 box_height0 = 1
469 box_width = 1
470
471 if len(start_coord) >= 2:
472 box_width = end_coord[-2] - start_coord[-2]
473
474 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
475
476 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
477 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
478
479 crossing_y = min(crossing_y, end_coord[1])
480 crossing_x = min(crossing_x, end_coord[2])
481
482 box_height0 = crossing_y - start_coord[1]
483 box_width = crossing_x - start_coord[2]
484
485 addresses = [None] * 4
486 addresses[0] = self.address_for_coordinate(start_coord)
487
488 if end_coord[2] > crossing_x:
489 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
490 raise Exception("Striping in vertical direction is not supported")
491 if end_coord[1] > crossing_y:
492 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
493 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
494 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
495
496 return box_height0, box_height0, box_width, addresses
497
498 def address_for_coordinate(self, coord, is_top_box=False):
499 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
500
501 def get_strides_and_coord(self, coord=None):
502 if coord is None:
503 coord = [0] * len(self.storage_shape)
504
505 augmented_coord = coord
506 augmented_shape = self.storage_shape
507 while len(augmented_shape) < 4:
508 augmented_shape = [1] + augmented_shape
509
510 while len(augmented_coord) < 4:
511 augmented_coord = [0] + augmented_coord
512
513 assert len(augmented_coord) == len(augmented_shape)
514
515 if self.format == TensorFormat.NHWC:
516 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
517 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
518 stride_order = [4, 1, 3, 2, 0]
519
520 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200521 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100522 augmented_shape = augmented_shape[0:4] + [1]
523 augmented_coord = (
524 [augmented_coord[0], augmented_coord[3] // channel_divisor]
525 + augmented_coord[1:3]
526 + [augmented_coord[3] % channel_divisor]
527 )
528
529 if augmented_shape[1] == 0:
530 augmented_shape[1] = 1
531
532 else:
533 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
534 return None, None
535
536 strides = [0] * len(augmented_shape)
537 stride = self.element_size() * self.storage_compression_scale
538
539 if self.format != TensorFormat.NHCWB16:
540 for i in stride_order:
541 strides[i] = stride
542 stride *= augmented_shape[i]
543 else:
544 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100545 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200546 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100547 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200548 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100549 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
550
551 return strides, augmented_coord
552
553 def get_strides(self):
554 strides, _ = self.get_strides_and_coord()
555
556 return strides
557
Louis Verhaard3c07c972020-05-07 08:12:58 +0200558 def needs_dma(self):
559 return len(self.ops) == 1 and self.ops[0].type == "DMA"
560
561 def get_dma_src_tensor(self):
562 # For weight tensors that need DMA: returns the source tensor in Flash, else None
563 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
564 return self.ops[0].inputs[0] if self.needs_dma() else None
565
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200566 def find_npu_op(self):
567 # Returns the NPU operator that uses this tensor, excluding DMA operators.
568 for op in self.consumers():
569 if op.type == "DMA":
570 return op.outputs[0].find_npu_op()
571 if "npu_block_type" in op.attrs:
572 return op
573 return None
574
Tim Hall79d07d22020-04-27 18:20:16 +0100575 def compressed_stream_index_from_coord(self, coord):
576 assert self.format == TensorFormat.WeightsCompressed
577 assert len(self.compressed_values) > 0
578 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
579
580 depth = coord[-1]
581 brick_depth = self.brick_size[-1]
582 # Clamp position at final element index
583 if depth > self.shape[-1]:
584 depth = self.shape[-1]
585
586 # Always round up to next boundary
587 index = round_up_divide(depth, brick_depth)
588
589 # Check boundaries on all but last weight set (which may be shorter
590 # than the brick we divided it up into)
591 if index < len(self.weight_compressed_offsets) - 1:
592 # There are no half-way points in the weights
593 if (depth % brick_depth) != 0:
594 raise Exception("Offset into weights must be aligned to a brick")
595
596 return index
597
598 def size_of_compressed_stream(self, index):
599 assert 0 <= index < len(self.compressed_values)
600 return len(self.compressed_values[index])
601
602 def is_last_index_in_compressed_stream(self, index):
603 assert 0 <= index < len(self.compressed_values)
604 return index == len(self.compressed_values) - 1
605
606 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
607 address_offset = 0
608 coord = orig_coord
609
610 coord = coord[-len(self.storage_shape) :]
611
612 if self.sub_purpose == TensorSubPurpose.Standard:
613 for idx, c in enumerate(coord):
614 if is_top_box:
615 assert c > 0 and c <= self.shape[idx]
616 else:
617 assert c >= 0 and c < self.shape[idx]
618
619 if self.format == TensorFormat.WeightsCompressed:
620 if len(self.weight_compressed_offsets) == 0:
621 return 0
622
Louis Verhaard3c07c972020-05-07 08:12:58 +0200623 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100624 depth = orig_coord[-1]
625 brick_depth = self.brick_size[-1]
626 # Clamp position at final element index
627 if depth > self.shape[-1]:
628 depth = self.shape[-1]
629
630 # Always round up to next boundary
631 index = round_up_divide(depth, brick_depth)
632 index = index % 2
633
634 if len(self.compressed_values) <= 2:
635 if is_top_box and index == 0:
636 for cv in self.compressed_values:
637 address_offset += len(cv)
638 else:
639 address_offset = index * len(self.compressed_values[0])
640 else:
641 if is_top_box and index == 0:
642 address_offset = self.storage_shape[-1]
643 else:
644 address_offset = index * (self.storage_shape[-1] // 2)
645 else:
646 index = self.compressed_stream_index_from_coord(orig_coord)
647 assert index < len(self.weight_compressed_offsets)
648 address_offset = self.weight_compressed_offsets[index]
649 else:
650 if is_top_box:
651 coord = [c - 1 for c in coord]
652
653 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
654 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
655
656 strides, augmented_coord = self.get_strides_and_coord(coord)
657 if strides is None:
658 return None
659
660 if is_top_box:
661 address_offset += 1 * strides[-1] # one element
662
663 address_offset += np.dot(augmented_coord, strides)
664
665 assert address_offset >= 0
666 assert address_offset <= self.storage_size()
667 return address_offset
668
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200669 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
670 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
671 return True
672 return False
673
Tim Hall79d07d22020-04-27 18:20:16 +0100674 def __str__(self):
675 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
676
677 __repr__ = __str__