blob: 160cf630587568edd463b082c4be3176f66ca5d6 [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
29class MemArea(enum.IntFlag):
30 Unknown = 0
31 Sram = 1
32 Dram = 2
33 OnChipFlash = 3
34 OffChipFlash = 4
35 Size = OffChipFlash + 1
36
37 def display_name(self):
38 return ("Unknown", "SRAM", "DRAM", "On-chip Flash", "Off-chip Flash", "Size")[self.value]
39
40 def identifier_name(self):
41 return ("unknown", "sram", "dram", "on_chip_flash", "off_chip_flash", "size")[self.value]
42
43 def all():
44 return (MemArea.Sram, MemArea.Dram, MemArea.OnChipFlash, MemArea.OffChipFlash)
45
46 def __str__(self):
47 return self.name
48
49
50class TensorPurpose(enum.IntFlag):
51 Unknown = 0
52 Weights = 1
53 FeatureMap = 2
54 Scratch = 3
55 Size = 4
56
57 def display_name(self):
58 return ("Unknown", "Weights", "FeatureMap", "Scratch", "Size")[self.value]
59
60 def identifier_name(self):
61 return ("unknown", "weights", "feature_map", "scratch", "size")[self.value]
62
63 def all():
64 return (TensorPurpose.Weights, TensorPurpose.FeatureMap)
65
66
67class TensorSubPurpose(enum.Enum):
68 Standard = 0
69 DoubleBuffer = 1
70 RollingBufferX = 2
71 RollingBufferY = 3
72 RollingBufferXY = 4
73
74 def display_name(self):
75 return ("Standard", "Double Buffer", "Rolling Buffer X", "Rolling Buffer Y", "Rolling Buffer XY")[self.value]
76
77 def identifier_name(self):
78 return ("standard", "double_buffer", "rolling_buffer_x", "rolling_buffer_y", "rolling_buffer_xy")[self.value]
79
80 def all():
81 return (
82 TensorSubPurpose.Standard,
83 TensorSubPurpose.DoubleBuffer,
84 TensorSubPurpose.RollingBufferX,
85 TensorSubPurpose.RollingBufferY,
86 TensorSubPurpose.RollingBufferXY,
87 )
88
89
90class TensorFormat(enum.Flag):
91 Unknown = 0
92 WeightsCompressed = 1
93 NHWC = 2
94 NHCWB16 = 3
95
96 def __str__(self):
97 return self.name
98
99
100class TensorBlockTraversal(enum.Enum):
101 Default = 0
102 DepthWise = 1
103 DepthFirst = 2
104 PartKernelFirst = 3
105
106
107def shape_num_elements(shp):
108 elems = 1
109 if shp is None:
110 return None
111 for d in shp:
112 if d is None:
113 return None
114 elems *= d
115 return elems
116
117
118def shape_fully_defined(shp):
119 if shp is None:
120 return False
121 for d in shp:
122 if d is None:
123 return False
124 return True
125
126
127def shape_round_to_quantum(shp, quantum):
128 new_shp = list(shp)
129
130 # Traverse backwards using length of shape since there may be more rounding quantums than shape elements
131 for i in range(-1, -len(shp) - 1, -1):
132 if new_shp[i] is not None:
133 new_shp[i] = numeric_util.round_up(new_shp[i], quantum[i])
134 return new_shp
135
136
137class QuantizationParameters:
138 __slots__ = "min", "max", "num_bits", "narrow_range", "scale_f32", "zero_point", "quant_min", "quant_max"
139
140 def __init__(self, min=None, max=None, num_bits=None, narrow_range=None):
141 self.min = min
142 self.max = max
143
144 self.num_bits = num_bits
145 self.narrow_range = narrow_range
146
147 self.scale_f32 = None
148 self.zero_point = None
149 self.quant_min = None
150 self.quant_max = None
151
152 def __str__(self):
153 return "<nng.QuantizationParameters min=%s max=%s, num_bits=%s, scale=%s, zero_point=%s>" % (
154 self.min,
155 self.max,
156 self.num_bits,
157 self.scale_f32,
158 self.zero_point,
159 )
160
161 __repr__ = __str__
162
163 def clone(self):
164 res = QuantizationParameters()
165 res.min = self.min
166 res.max = self.max
167
168 res.num_bits = self.num_bits
169 res.narrow_range = self.narrow_range
170
171 res.scale_f32 = self.scale_f32
172 res.zero_point = self.zero_point
173 res.quant_min = self.quant_min
174 res.quant_max = self.quant_max
175 return res
176
177 def dequantize(self, values):
178 if self.zero_point.size == 1 and self.scale_f32.size == 1:
179 # same scale is used for all values
180 res = (values.astype(np.float64) - self.zero_point) * self.scale_f32
181 else:
182 # a different scale is used for different sets of values
183 values_as_float = values.astype(np.float64)
184
185 # this is not compatible with the format of depthwise weights,
186 # where input is at index 3 (Output, Kh, Kw, Input)
187 # return the quantized values
188 return np.ndarray((values_as_float.shape))
189
190 shape = values_as_float.shape[0]
191 assert self.zero_point.size == self.scale_f32.size == shape
192 res = np.ndarray(values_as_float.shape)
193 for i in range(shape):
194 res[i] = (values_as_float[i] - self.zero_point[i]) * self.scale_f32[i]
195
196 return res
197
198
199class Tensor:
200 __slots__ = (
201 "shape",
202 "storage_shape",
203 "bandwidth_shape",
204 "dtype",
205 "name",
206 "ops",
207 "consumer_list",
208 "values",
209 "quant_values",
210 "compressed_values",
211 "mem_area",
212 "format",
213 "purpose",
214 "sub_purpose",
215 "alignment",
216 "weight_transpose_depthwise",
217 "storage_compression_scale",
218 "bandwidth_compression_scale",
219 "compression_scale_for_worst_weight_stream",
220 "weight_compression_scales",
221 "weight_compression_config",
222 "storage_rounding_quantum",
223 "brick_size",
224 "address",
225 "quantization",
226 "weight_compressed_offsets",
227 "element_size_bytes",
228 "reshaped",
229 "block_traversal",
230 "offset",
231 "cpu_tensor",
232 "npu_tensor",
233 "equivalence_id",
Dwight Lidmana9390f72020-05-13 12:00:08 +0200234 "resampling_mode",
Tim Hall79d07d22020-04-27 18:20:16 +0100235 )
236 AllocationQuantum = 16
237
238 def __init__(self, shape, dtype, name):
239 self.shape = shape
240 self.storage_shape = shape
241 self.bandwidth_shape = shape
242 self.dtype = dtype
243 self.name = name
244 self.equivalence_id = uuid.uuid4()
245
246 self.ops = []
247 self.consumer_list = []
248 # Below attributes are only set if a tensor has been cloned,
249 # either from Cpu -> Npu or vice versa. Needed for offline allocation
250 self.cpu_tensor = None # reference to the corresponding Cpu tensor
251 self.npu_tensor = None # reference to the corresponding Npu tensor
252
253 self.values = None
254 self.quant_values = None
255 self.compressed_values = None
256 self.mem_area = MemArea.Unknown
257 self.format = TensorFormat.Unknown
258 self.purpose = TensorPurpose.Unknown
259 self.sub_purpose = TensorSubPurpose.Standard
260 self.alignment = Tensor.AllocationQuantum
261 self.weight_transpose_depthwise = False
262
263 self.storage_compression_scale = 1.0
264 self.bandwidth_compression_scale = 1.0
265 self.compression_scale_for_worst_weight_stream = 1.0
266 self.weight_compression_scales = None
267 self.weight_compression_config = None
268 self.weight_compressed_offsets = []
269 self.storage_rounding_quantum = (1, 1, 1, 1)
270 self.brick_size = (1, 1, 1, 1)
271 self.address = 0 # start address of tensor. will be filled in by tensor allocator
272 self.element_size_bytes = 0
273
274 # quantization parameters
275 self.quantization = None
276
277 self.reshaped = False
278 self.block_traversal = TensorBlockTraversal.Default
Dwight Lidmana9390f72020-05-13 12:00:08 +0200279 self.resampling_mode = resampling_mode.NONE
Tim Hall79d07d22020-04-27 18:20:16 +0100280
281 def element_size(self):
282 if self.element_size_bytes == 0:
283 return self.dtype.size_in_bits() / 8
284 return self.element_size_bytes
285
286 def clone(self, suffix="_clone"):
287 res = Tensor(self.shape, self.dtype, self.name + suffix)
288 res.storage_shape = list(self.storage_shape)
289 res.bandwidth_shape = list(self.bandwidth_shape)
290
291 res.ops = []
292 res.consumer_list = []
293 res.equivalence_id = self.equivalence_id
294
295 res.values = self.values
296 res.quant_values = self.quant_values
297 res.compressed_values = self.compressed_values
298 res.mem_area = self.mem_area
299 res.format = self.format
300 res.purpose = self.purpose
301 res.sub_purpose = self.sub_purpose
302 res.alignment = self.alignment
303 res.weight_transpose_depthwise = self.weight_transpose_depthwise
304
305 res.storage_compression_scale = self.storage_compression_scale
306 res.bandwidth_compression_scale = self.bandwidth_compression_scale
307 res.compression_scale_for_worst_weight_stream = self.compression_scale_for_worst_weight_stream
308 res.weight_compression_scales = self.weight_compression_scales
309 res.storage_rounding_quantum = self.storage_rounding_quantum
310 res.brick_size = self.brick_size
311 res.address = 0
312
313 if self.quantization is not None:
314 res.quantization = self.quantization.clone()
315 else:
316 res.quantization = None
317
Dwight Lidmana9390f72020-05-13 12:00:08 +0200318 res.resampling_mode = self.resampling_mode
319
Tim Hall79d07d22020-04-27 18:20:16 +0100320 return res
321
322 def clone_into_fast_storage(self, arch):
323 res = self.clone(suffix="_fast_storage")
324 res.mem_area = arch.fast_storage_mem_area
325 return res
326
327 def set_format(self, fmt, arch):
328 self.format = fmt
329 shape_len = 0
330 try:
331 shape_len = len(self.shape)
332 except TypeError:
333 pass
334
335 self.storage_rounding_quantum = arch.storage_rounding_quantums[self.format]
336 self.storage_rounding_quantum = self.storage_rounding_quantum[-shape_len:]
Tim Hall79d07d22020-04-27 18:20:16 +0100337 self.brick_size = arch.brick_sizes[self.format]
338 self.brick_size = self.brick_size[-shape_len:]
339 if self.shape is None:
340 return
341
342 self.bandwidth_shape = shape_round_to_quantum(self.shape, self.brick_size)
343 self.storage_shape = shape_round_to_quantum(self.shape, self.storage_rounding_quantum)
344
345 if fmt == TensorFormat.WeightsCompressed:
346 compression_ratio = 5 / 8
347 self.storage_compression_scale = compression_ratio
348 self.bandwidth_compression_scale = compression_ratio
349 self.compression_scale_for_worst_weight_stream = compression_ratio
350
351 def storage_elements(self):
352 elems = shape_num_elements(self.storage_shape)
353 if elems is None:
354 return 0
355 return elems
356
357 def elements(self):
358 elems = shape_num_elements(self.shape)
359 if elems is None:
360 return 0
361 return elems
362
363 def has_fully_defined_shape(self):
364 return shape_fully_defined(self.shape)
365
366 def storage_size(self):
367 raw_size = self.storage_elements() * self.element_size()
368 if raw_size == 0:
369 raw_size = 1 # force it to take up space
370 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
371 return rounded_size
372
373 def storage_size_for_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
374 alt_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
375 elems = shape_num_elements(alt_shape)
376 if elems is None:
377 return 0
378 if sub_purpose == TensorSubPurpose.DoubleBuffer:
379 raw_size = elems * self.element_size() * self.compression_scale_for_worst_weight_stream
380 else:
381 raw_size = elems * self.element_size() * self.storage_compression_scale
382 rounded_size = numeric_util.round_up(numeric_util.round_up_to_int(raw_size), self.alignment)
383 return rounded_size
384
385 def storage_shape_for_sub_purpose(self, sub_purpose, param_a, param_b):
386 shp = list(self.storage_shape)
387 if sub_purpose == TensorSubPurpose.DoubleBuffer:
388 assert len(shp) >= 2
389 shp[-1] = min(shp[-1], param_a * 2)
390 elif sub_purpose == TensorSubPurpose.RollingBufferX:
391 assert len(shp) == 4
392 shp[0] = 1
393 shp[2] = min(shp[2], param_a)
394 elif sub_purpose == TensorSubPurpose.RollingBufferY:
395 assert len(shp) == 4
396 shp[0] = 1
397 shp[1] = min(shp[1], param_a)
398 elif sub_purpose == TensorSubPurpose.RollingBufferXY:
399 assert len(shp) == 4
400 shp[0] = 1
401 shp[2] = min(shp[2], param_a)
402 shp[1] = min(shp[1], param_b)
403 elif sub_purpose == TensorSubPurpose.Standard:
404 pass
405 else:
406 assert 0, "did not expect new sub purpose %s" % (sub_purpose,)
407 return shp
408
409 def set_new_sub_purpose(self, sub_purpose, param_a=None, param_b=None):
410 self.storage_shape = self.storage_shape_for_sub_purpose(sub_purpose, param_a, param_b)
411 self.sub_purpose = sub_purpose
412 if sub_purpose == TensorSubPurpose.DoubleBuffer:
413 self.storage_compression_scale = self.compression_scale_for_worst_weight_stream
414
415 def bandwidth(self):
416 elems = shape_num_elements(self.bandwidth_shape)
417 if elems is None:
418 return 0
419 return elems * self.element_size() * self.bandwidth_compression_scale
420
421 def consumers(self):
422 return self.consumer_list
423
424 def get_address_ranges_for_coordinates(self, start_coord, end_coord):
425 if self.sub_purpose in set(
426 (TensorSubPurpose.RollingBufferX, TensorSubPurpose.RollingBufferY, TensorSubPurpose.RollingBufferXY)
427 ):
428 # build dummy coordinates that cover the entire buffer
429 start_coord = [0] * len(start_coord)
430 end_coord = [min(self.storage_shape[i], self.shape[i]) for i in range(len(end_coord))]
431
432 start = self.address_for_coordinate(start_coord, is_top_box=False)
433 end = self.address_for_coordinate(end_coord, is_top_box=True)
434 return MemoryRangeSet(self.mem_area, start, end)
435
436 def addresses_for_rolling_buffer(self, start_coord, end_coord):
437 # returns ( box_height0, box_height1, box_width, [address_tl, address_tr, address_bl, address_br] )
438
439 if len(start_coord) < 4:
440 box_height0 = 1
441 box_width = 1
442
443 if len(start_coord) >= 2:
444 box_width = end_coord[-2] - start_coord[-2]
445
446 return box_height0, box_height0, box_width, [self.address_for_coordinate(start_coord), None, None, None]
447
448 crossing_y = numeric_util.round_up(start_coord[1] + 1, self.storage_shape[1])
449 crossing_x = numeric_util.round_up(start_coord[2] + 1, self.storage_shape[2])
450
451 crossing_y = min(crossing_y, end_coord[1])
452 crossing_x = min(crossing_x, end_coord[2])
453
454 box_height0 = crossing_y - start_coord[1]
455 box_width = crossing_x - start_coord[2]
456
457 addresses = [None] * 4
458 addresses[0] = self.address_for_coordinate(start_coord)
459
460 if end_coord[2] > crossing_x:
461 addresses[1] = self.address_for_coordinate([start_coord[0], start_coord[1], crossing_x, start_coord[3]])
462 raise Exception("Striping in vertical direction is not supported")
463 if end_coord[1] > crossing_y:
464 addresses[2] = self.address_for_coordinate([start_coord[0], crossing_y, start_coord[2], start_coord[3]])
465 if end_coord[1] > crossing_y and end_coord[2] > crossing_x:
466 addresses[3] = self.address_for_coordinate([start_coord[0], crossing_y, crossing_x, start_coord[3]])
467
468 return box_height0, box_height0, box_width, addresses
469
470 def address_for_coordinate(self, coord, is_top_box=False):
471 return self.address + self.address_offset_for_coordinate(coord, is_top_box)
472
473 def get_strides_and_coord(self, coord=None):
474 if coord is None:
475 coord = [0] * len(self.storage_shape)
476
477 augmented_coord = coord
478 augmented_shape = self.storage_shape
479 while len(augmented_shape) < 4:
480 augmented_shape = [1] + augmented_shape
481
482 while len(augmented_coord) < 4:
483 augmented_coord = [0] + augmented_coord
484
485 assert len(augmented_coord) == len(augmented_shape)
486
487 if self.format == TensorFormat.NHWC:
488 augmented_shape = [augmented_shape[0], augmented_shape[3]] + augmented_shape[1:3] + [1]
489 augmented_coord = [augmented_coord[0], augmented_coord[3]] + augmented_coord[1:3] + [0]
490 stride_order = [4, 1, 3, 2, 0]
491
492 elif self.format == TensorFormat.NHCWB16:
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200493 channel_divisor = 16
Tim Hall79d07d22020-04-27 18:20:16 +0100494 augmented_shape = augmented_shape[0:4] + [1]
495 augmented_coord = (
496 [augmented_coord[0], augmented_coord[3] // channel_divisor]
497 + augmented_coord[1:3]
498 + [augmented_coord[3] % channel_divisor]
499 )
500
501 if augmented_shape[1] == 0:
502 augmented_shape[1] = 1
503
504 else:
505 assert self.format in set((TensorFormat.Unknown, TensorFormat.WeightsCompressed))
506 return None, None
507
508 strides = [0] * len(augmented_shape)
509 stride = self.element_size() * self.storage_compression_scale
510
511 if self.format != TensorFormat.NHCWB16:
512 for i in stride_order:
513 strides[i] = stride
514 stride *= augmented_shape[i]
515 else:
516 assert len(strides) == 5
Tim Hall79d07d22020-04-27 18:20:16 +0100517 strides[4] = stride
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200518 strides[3] = 16 * stride # STRIDE_X
Tim Hall79d07d22020-04-27 18:20:16 +0100519 strides[1] = strides[3] * augmented_shape[2] # STRIDE_C
Patrik Gustavsson2213e902020-05-05 17:49:35 +0200520 strides[2] = augmented_shape[2] * augmented_shape[3] * stride # STRIDE_Y
Tim Hall79d07d22020-04-27 18:20:16 +0100521 strides[0] = strides[2] * augmented_shape[1] # STRIDE_N
522
523 return strides, augmented_coord
524
525 def get_strides(self):
526 strides, _ = self.get_strides_and_coord()
527
528 return strides
529
530 def compressed_stream_index_from_coord(self, coord):
531 assert self.format == TensorFormat.WeightsCompressed
532 assert len(self.compressed_values) > 0
533 assert len(self.compressed_values) + 1 == len(self.weight_compressed_offsets)
534
535 depth = coord[-1]
536 brick_depth = self.brick_size[-1]
537 # Clamp position at final element index
538 if depth > self.shape[-1]:
539 depth = self.shape[-1]
540
541 # Always round up to next boundary
542 index = round_up_divide(depth, brick_depth)
543
544 # Check boundaries on all but last weight set (which may be shorter
545 # than the brick we divided it up into)
546 if index < len(self.weight_compressed_offsets) - 1:
547 # There are no half-way points in the weights
548 if (depth % brick_depth) != 0:
549 raise Exception("Offset into weights must be aligned to a brick")
550
551 return index
552
553 def size_of_compressed_stream(self, index):
554 assert 0 <= index < len(self.compressed_values)
555 return len(self.compressed_values[index])
556
557 def is_last_index_in_compressed_stream(self, index):
558 assert 0 <= index < len(self.compressed_values)
559 return index == len(self.compressed_values) - 1
560
561 def address_offset_for_coordinate(self, orig_coord, is_top_box=False):
562 address_offset = 0
563 coord = orig_coord
564
565 coord = coord[-len(self.storage_shape) :]
566
567 if self.sub_purpose == TensorSubPurpose.Standard:
568 for idx, c in enumerate(coord):
569 if is_top_box:
570 assert c > 0 and c <= self.shape[idx]
571 else:
572 assert c >= 0 and c < self.shape[idx]
573
574 if self.format == TensorFormat.WeightsCompressed:
575 if len(self.weight_compressed_offsets) == 0:
576 return 0
577
578 if len(self.ops) == 1 and self.ops[0].type == "DMA" and self.sub_purpose == TensorSubPurpose.DoubleBuffer:
579 depth = orig_coord[-1]
580 brick_depth = self.brick_size[-1]
581 # Clamp position at final element index
582 if depth > self.shape[-1]:
583 depth = self.shape[-1]
584
585 # Always round up to next boundary
586 index = round_up_divide(depth, brick_depth)
587 index = index % 2
588
589 if len(self.compressed_values) <= 2:
590 if is_top_box and index == 0:
591 for cv in self.compressed_values:
592 address_offset += len(cv)
593 else:
594 address_offset = index * len(self.compressed_values[0])
595 else:
596 if is_top_box and index == 0:
597 address_offset = self.storage_shape[-1]
598 else:
599 address_offset = index * (self.storage_shape[-1] // 2)
600 else:
601 index = self.compressed_stream_index_from_coord(orig_coord)
602 assert index < len(self.weight_compressed_offsets)
603 address_offset = self.weight_compressed_offsets[index]
604 else:
605 if is_top_box:
606 coord = [c - 1 for c in coord]
607
608 # handle wraparound for partial buffers. make sure to do this after subtracting top box:
609 coord = [c % self.storage_shape[idx] for idx, c in enumerate(coord)]
610
611 strides, augmented_coord = self.get_strides_and_coord(coord)
612 if strides is None:
613 return None
614
615 if is_top_box:
616 address_offset += 1 * strides[-1] # one element
617
618 address_offset += np.dot(augmented_coord, strides)
619
620 assert address_offset >= 0
621 assert address_offset <= self.storage_size()
622 return address_offset
623
624 def __str__(self):
625 return "<nng.Tensor '%s' shape=%s dtype=%s>" % (self.name, self.shape, self.dtype)
626
627 __repr__ = __str__