blob: bc0597f607a5d89e6bac10a6d76e2845412c9b35 [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):
417 shp = list(self.storage_shape)
418 if sub_purpose == TensorSubPurpose.DoubleBuffer:
419 assert len(shp) >= 2
420 shp[-1] = min(shp[-1], param_a * 2)
421 elif sub_purpose == TensorSubPurpose.RollingBufferX:
422 assert len(shp) == 4
423 shp[0] = 1
424 shp[2] = min(shp[2], param_a)
425 elif sub_purpose == TensorSubPurpose.RollingBufferY:
426 assert len(shp) == 4
427 shp[0] = 1
428 shp[1] = min(shp[1], param_a)
429 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
430 assert len(shp) == 4
431 shp[0] = 1
432 shp[2] = min(shp[2], param_a)
433 shp[1] = min(shp[1], param_b)
434 elif sub_purpose == TensorSubPurpose.Standard:
435 pass
436 else:
437 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
438 return shp
439
440 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
441 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
442 self.sub_purpose = sub_purpose
443 if sub_purpose == TensorSubPurpose.DoubleBuffer:
444 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
445
446 def bandwidth(self):
447 elems = shape_num_elements(self.bandwidth_shape)
448 if elems is None:
449 return 0
450 return elems * self.element_size() * self.bandwidth_compression_scale
451
452 def consumers(self):
453 return self.consumer_list
454
455 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
456 if self.sub_purpose in set(
457 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
458 ):
459 # build dummy coordinates that cover the entire buffer
460 start_coord = [0] * len(start_coord)
461 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
462
463 start = self.address_for_coordinate(start_coord, is_top_box=False)
464 end = self.address_for_coordinate(end_coord, is_top_box=True)
465 return MemoryRangeSet(self.mem_area, start, end)
466
467 def addresses_for_rolling_buffer(self, start_coord, end_coord):
468 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
469
470 if len(start_coord) < 4:
471 box_height0 = 1
472 box_width = 1
473
474 if len(start_coord) >= 2:
475 box_width = end_coord[-2] - start_coord[-2]
476
477 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
478
479 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
480 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
481
482 crossing_y = min(crossing_y, end_coord[1])
483 crossing_x = min(crossing_x, end_coord[2])
484
485 box_height0 = crossing_y - start_coord[1]
486 box_width = crossing_x - start_coord[2]
487
488 addresses = [None] * 4
489 addresses[0] = self.address_for_coordinate(start_coord)
490
491 if end_coord[2] > crossing_x:
492 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
493 raise Exception("Striping in vertical direction is not supported")
494 if end_coord[1] > crossing_y:
495 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
496 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
497 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
498
499 return box_height0, box_height0, box_width, addresses
500
501 def address_for_coordinate(self, coord, is_top_box=False):
502 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
503
504 def get_strides_and_coord(self, coord=None):
505 if coord is None:
506 coord = [0] * len(self.storage_shape)
507
508 augmented_coord = coord
509 augmented_shape = self.storage_shape
510 while len(augmented_shape) < 4:
511 augmented_shape = [1] + augmented_shape
512
513 while len(augmented_coord) < 4:
514 augmented_coord = [0] + augmented_coord
515
516 assert len(augmented_coord) == len(augmented_shape)
517
518 if self.format == TensorFormat.NHWC:
519 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
520 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
521 stride_order = [4, 1, 3, 2, 0]
522
523 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200524 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100525 augmented_shape = augmented_shape[0:4] + [1]
526 augmented_coord = (
527 [augmented_coord[0], augmented_coord[3] // channel_divisor]
528 + augmented_coord[1:3]
529 + [augmented_coord[3] % channel_divisor]
530 )
531
532 if augmented_shape[1] == 0:
533 augmented_shape[1] = 1
534
535 else:
536 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
537 return None, None
538
539 strides = [0] * len(augmented_shape)
540 stride = self.element_size() * self.storage_compression_scale
541
542 if self.format != TensorFormat.NHCWB16:
543 for i in stride_order:
544 strides[i] = stride
545 stride *= augmented_shape[i]
546 else:
547 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100548 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200549 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100550 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200551 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100552 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
553
554 return strides, augmented_coord
555
556 def get_strides(self):
557 strides, _ = self.get_strides_and_coord()
558
559 return strides
560
Louis Verhaard3c07c972020-05-07 08:12:58 +0200561 def needs_dma(self):
562 return len(self.ops) == 1 and self.ops[0].type == "DMA"
563
564 def get_dma_src_tensor(self):
565 # For weight tensors that need DMA: returns the source tensor in Flash, else None
566 # Note: for DMA ops, Pass.weight_tensor is referring to the SRAM weight tensor
567 return self.ops[0].inputs[0] if self.needs_dma() else None
568
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200569 def find_npu_op(self):
570 # Returns the NPU operator that uses this tensor, excluding DMA operators.
571 for op in self.consumers():
572 if op.type == "DMA":
573 return op.outputs[0].find_npu_op()
574 if "npu_block_type" in op.attrs:
575 return op
576 return None
577
Tim Hall79d07d22020-04-27 18:20:16 +0100578 def compressed_stream_index_from_coord(self, coord):
579 assert self.format == TensorFormat.WeightsCompressed
580 assert len(self.compressed_values) > 0
581 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
582
583 depth = coord[-1]
584 brick_depth = self.brick_size[-1]
585 # Clamp position at final element index
586 if depth > self.shape[-1]:
587 depth = self.shape[-1]
588
589 # Always round up to next boundary
590 index = round_up_divide(depth, brick_depth)
591
592 # Check boundaries on all but last weight set (which may be shorter
593 # than the brick we divided it up into)
594 if index < len(self.weight_compressed_offsets) - 1:
595 # There are no half-way points in the weights
596 if (depth % brick_depth) != 0:
597 raise Exception("Offset into weights must be aligned to a brick")
598
599 return index
600
601 def size_of_compressed_stream(self, index):
602 assert 0 <= index < len(self.compressed_values)
603 return len(self.compressed_values[index])
604
605 def is_last_index_in_compressed_stream(self, index):
606 assert 0 <= index < len(self.compressed_values)
607 return index == len(self.compressed_values) - 1
608
609 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
610 address_offset = 0
611 coord = orig_coord
612
613 coord = coord[-len(self.storage_shape) :]
614
615 if self.sub_purpose == TensorSubPurpose.Standard:
616 for idx, c in enumerate(coord):
617 if is_top_box:
618 assert c > 0 and c <= self.shape[idx]
619 else:
620 assert c >= 0 and c < self.shape[idx]
621
622 if self.format == TensorFormat.WeightsCompressed:
623 if len(self.weight_compressed_offsets) == 0:
624 return 0
625
Louis Verhaard3c07c972020-05-07 08:12:58 +0200626 if self.needs_dma() and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
Tim Hall79d07d22020-04-27 18:20:16 +0100627 depth = orig_coord[-1]
628 brick_depth = self.brick_size[-1]
629 # Clamp position at final element index
630 if depth > self.shape[-1]:
631 depth = self.shape[-1]
632
633 # Always round up to next boundary
634 index = round_up_divide(depth, brick_depth)
635 index = index % 2
636
637 if len(self.compressed_values) <= 2:
638 if is_top_box and index == 0:
639 for cv in self.compressed_values:
640 address_offset += len(cv)
641 else:
642 address_offset = index * len(self.compressed_values[0])
643 else:
644 if is_top_box and index == 0:
645 address_offset = self.storage_shape[-1]
646 else:
647 address_offset = index * (self.storage_shape[-1] // 2)
648 else:
649 index = self.compressed_stream_index_from_coord(orig_coord)
650 assert index < len(self.weight_compressed_offsets)
651 address_offset = self.weight_compressed_offsets[index]
652 else:
653 if is_top_box:
654 coord = [c - 1 for c in coord]
655
656 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
657 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
658
659 strides, augmented_coord = self.get_strides_and_coord(coord)
660 if strides is None:
661 return None
662
663 if is_top_box:
664 address_offset += 1 * strides[-1] # one element
665
666 address_offset += np.dot(augmented_coord, strides)
667
668 assert address_offset >= 0
669 assert address_offset <= self.storage_size()
670 return address_offset
671
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200672 def is_allocated_in_tensor_arena(self, scratch_tensor_mem_area):
673 if self.mem_area == scratch_tensor_mem_area and (self.mem_type in set((MemType.Scratch, MemType.Scratch_fast))):
674 return True
675 return False
676
Tim Hall79d07d22020-04-27 18:20:16 +0100677 def __str__(self):
678 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
679
680 __repr__ = __str__