blob: 8426705af7f0d265651dd1415d4d54b1e915f389 [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# Compresses and pads the weigths. It also calculates the scales and packs with the biases.
Tim Hall79d07d22020-04-27 18:20:16 +010018import math
Tim Hall79d07d22020-04-27 18:20:16 +010019from collections import namedtuple
Diego Russoea6111a2020-04-14 18:41:58 +010020
21import numpy as np
Tim Hall79d07d22020-04-27 18:20:16 +010022
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010023from .architecture_features import Accelerator
24from .architecture_features import ArchitectureFeatures
Diego Russoe8a10452020-04-21 17:39:10 +010025from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020026from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010027from .nn_graph import SchedulingStrategy
28from .numeric_util import round_up
Patrik Gustavssond89c09e2020-07-08 11:27:12 +020029from .numeric_util import round_up_divide
Diego Russoe8a10452020-04-21 17:39:10 +010030from .operation import NpuBlockType
31from .scaling import quantise_scale
32from .scaling import reduced_quantise_scale
Louis Verhaard9db529a2020-09-23 10:27:11 +020033from .tensor import create_equivalence_id
Diego Russoe8a10452020-04-21 17:39:10 +010034from .tensor import TensorBlockTraversal
35from .tensor import TensorFormat
36from .tensor import TensorPurpose
37from .tensor import TensorSubPurpose
Jacob Bohline843d332020-06-23 12:12:56 +020038from ethosu import mlw_codec
Diego Russoe8a10452020-04-21 17:39:10 +010039
Tim Hall79d07d22020-04-27 18:20:16 +010040
Louis Verhaard3c07c972020-05-07 08:12:58 +020041# Contains meta info for a weight compression. If two tensors have identical weight compression config,
42# then they also will have identical compressed weights.
43WeightCompressionConfig = namedtuple(
Louis Verhaard9db529a2020-09-23 10:27:11 +020044 "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "value_id"]
Louis Verhaard3c07c972020-05-07 08:12:58 +020045)
46
47
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010048def encode_weights(
49 accelerator: Accelerator,
50 weights_volume: np.ndarray,
51 dilation_xy: tuple,
52 ifm_bitdepth: int,
53 ofm_block_depth: int,
54 is_depthwise: bool,
55 is_partkernel: bool,
56):
57 """
58 Public facing API to use the ethosu weight encoding.
59
60 :param accelerator: architecture_features.Accelerator enum to pick the correct ethosu accelerator
61 :param weights_volume: numpy.ndarray in OHWI layout with a shape of four
62 :param dilation_xy: a two element tuple of dilation attributes in x,y dimension
63 :param ifm_bitdepth: the bitdepth of input feature map
64 :param ofm_block_depth: the depth of blocks for ethosu processing
65 :param is_depthwise: a boolean indicating these weights are used for a depthwise traversal
66 :param is_partkernel: a boolean indicating these weights are traversed on sub-kernal basis
67 :return: a bytearray of compressed weights
68 """
69
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +000070 # Check arg types
71 assert isinstance(accelerator, Accelerator)
72 assert isinstance(weights_volume, np.ndarray)
73 assert isinstance(dilation_xy, tuple)
74 assert isinstance(ifm_bitdepth, int)
75 assert isinstance(ofm_block_depth, int)
76 assert isinstance(is_depthwise, bool)
77 assert isinstance(is_partkernel, bool)
78
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010079 # Checks for weight layout
80 assert len(weights_volume.shape) == 4, "weights ndarray should have a shape of 4"
81
82 # It cannot be both partkernel and depthwise
83 assert not (is_depthwise and is_partkernel), "encode_weights :: partkernel and depthwise are mutually exclusive"
84
85 # Check valid values for dilation
86 assert dilation_xy[0] in (1, 2), "encode_weights :: dilation x should be 1 or 2 not {}".format(dilation_xy[0])
87 assert dilation_xy[1] in (1, 2), "encode_weights :: dilation y should be 1 or 2 not {}".format(dilation_xy[1])
88
89 ifm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ifm_ublock
90 ofm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ofm_ublock
91 raw_stream = generate_brick(
92 ifm_ublock=ifm_ublock,
93 ofm_ublock=ofm_ublock,
94 brick_weights=weights_volume,
95 ofm_block_depth=ofm_block_depth,
96 is_depthwise=is_depthwise,
97 is_partkernel=is_partkernel,
98 ifm_bitdepth=ifm_bitdepth,
99 dilation=dilation_xy,
100 )
101 encoded_stream = encode(raw_stream)
102 return encoded_stream
103
104
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100105def encode_bias(bias: np.int64, scale: int, shift: int):
106 """
107 Public facing API to pack bias and scale values as required by the hardware
108 :param bias: 64bit signed number that includes 40bit signed bias
109 :param scale: 32bit scale value
110 :param shift: 6bit shift value
111 :return: packed 80bit [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
112 """
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +0000113 # Check arg types
114 assert isinstance(bias, np.int64)
115 assert isinstance(scale, int)
116 assert isinstance(shift, int)
117
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100118 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
119 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
120 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
121
122 data = bytearray(10)
123 data[0] = (bias >> (0 * 8)) & 0xFF
124 data[1] = (bias >> (1 * 8)) & 0xFF
125 data[2] = (bias >> (2 * 8)) & 0xFF
126 data[3] = (bias >> (3 * 8)) & 0xFF
127 data[4] = (bias >> (4 * 8)) & 0xFF
128 data[5] = (scale >> (0 * 8)) & 0xFF
129 data[6] = (scale >> (1 * 8)) & 0xFF
130 data[7] = (scale >> (2 * 8)) & 0xFF
131 data[8] = (scale >> (3 * 8)) & 0xFF
132 data[9] = shift & 0x3F
133 return data
134
135
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200136def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Louis Verhaard3c07c972020-05-07 08:12:58 +0200137 # Note: for an ofm block only its depth is used in weight compression.
138 # And block depth > ofm depth gives same result as block depth == ofm depth
139 block_depth = min(ofm_block_depth, tens.quant_values.shape[-1])
Louis Verhaard9db529a2020-09-23 10:27:11 +0200140 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, tens.value_id)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200141
142
143def set_storage_shape(tens):
144 # Sets the storage shape depending on the tensor's sub purpose
145 if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(tens.compressed_values) > 2:
146 offset = 2 * np.amax([len(x) for x in tens.compressed_values])
147 assert offset % 16 == 0
148 else:
149 offset = tens.weight_compressed_offsets[-1]
150 tens.storage_shape = [1, 1, 1, offset]
151
152
153class CompressedWeightCache:
154 # Contains weight compressions for all weight tensors in a graph
155 def __init__(self):
156 self.cache = {} # maps from WeightCompressionConfig to a tensor clone containing compressed weights
157
158 def get_tensor_with_same_compression(self, wcc):
159 return self.cache.get(wcc)
160
161 def add(self, tens):
162 # Adds the compressed weights from the tensor to the cache
163 wcc = tens.weight_compression_config
164 # Clone the tensor to make sure that nothing related to the weight compression is modified
165 tens_clone = tens.clone("_weights{}_{}".format(wcc.ofm_block_depth, wcc.ofm_depth_step))
166 self.cache[wcc] = tens_clone
167
168
Tim Hall79d07d22020-04-27 18:20:16 +0100169def encode(weight_stream):
Patrik Gustavsson5ff99442020-07-10 10:12:17 +0200170 if len(weight_stream) == 0:
171 return []
Tim Hall79d07d22020-04-27 18:20:16 +0100172 assert np.amin(weight_stream) >= -255
173 assert np.amax(weight_stream) <= 255
174
175 # Encode flattened signed weight stream
176 compressed = mlw_codec.encode(weight_stream)
177
178 # pad with 0xFF as needed so the length of the weight stream
179 # is a multiple of 16
Diego Russoea6111a2020-04-14 18:41:58 +0100180
Tim Hall79d07d22020-04-27 18:20:16 +0100181 while (len(compressed) % 16) != 0:
182 compressed.append(0xFF)
183
184 return compressed
185
186
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100187def generate_brick(
188 ifm_ublock, ofm_ublock, brick_weights, ofm_block_depth, is_depthwise, is_partkernel, ifm_bitdepth, dilation
189):
190
191 decomp_h = ArchitectureFeatures.SubKernelMax.height // dilation[0]
192 decomp_w = ArchitectureFeatures.SubKernelMax.width // dilation[1]
Tim Hallf7e810a2020-06-25 15:04:31 +0100193 # Expect weights formatted OHWI
194 ofm_depth = brick_weights.shape[-4]
195 ifm_depth = brick_weights.shape[-1]
196 kernel_width = brick_weights.shape[-2]
197 kernel_height = brick_weights.shape[-3]
Tim Hall79d07d22020-04-27 18:20:16 +0100198 # IFM block depth
199 if is_partkernel or (ifm_bitdepth == 16):
200 # IFM block depth is always 16 for part-kernel-first
201 ifm_block_depth = 16
202 elif ifm_bitdepth == 8:
203 ifm_block_depth = 32
204 else:
205 assert False
206
207 stream = []
208
209 # Top level striping - OFM blocks in the entire brick's depth
Louis Verhaard3c07c972020-05-07 08:12:58 +0200210 for ofm_block_z in range(0, ofm_depth, ofm_block_depth):
211 clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z)
Tim Hall79d07d22020-04-27 18:20:16 +0100212 # IFM blocks required for the brick
213 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
214 if is_depthwise:
215 clipped_ifm_block_depth = ifm_ublock.depth
216 else:
217 clipped_ifm_block_depth = (
218 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
219 )
220 # Weight decomposition
221 # Subkernel Splitting (H)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200222 for subkernel_y in range(0, kernel_height, decomp_h):
223 sub_height = min(kernel_height - subkernel_y, decomp_h)
Tim Hall79d07d22020-04-27 18:20:16 +0100224 # Subkernel splitting (W)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200225 for subkernel_x in range(0, kernel_width, decomp_w):
226 sub_width = min(kernel_width - subkernel_x, decomp_w)
Tim Hall79d07d22020-04-27 18:20:16 +0100227 subkernel_elements = sub_width * sub_height
228 # Part kernel first works across the kernel H/W and needs padding
229 if is_partkernel:
230 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
231 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
232 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
233 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
234
235 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
236 # this is different from normal conv which is considered "weights depth-first"
237 elif is_depthwise:
238 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
239
240 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
241 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
242 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
243 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
244 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
245 # OFM Ublocks in OFM-block over depth
246 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
247 # HW Kernel element traversal - cannot be a H/W loop due to element
248 # padding requirement on depthwise/part-kernel configurations
249 for element in range(subkernel_elements):
250 kx = element % sub_width
251 ky = element // sub_width
252 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
253 # In case of part-kernel-first IFM Ublock traversal have already been handled
254 # and this loop is ignored.
255 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
256 # Feed OFM ublock elements
257 for ofm_ublock_z in range(ofm_ublock.depth):
258 # Source IFM ublock elements (only 1 element deep if depthwise)
259 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
260 # Source position within the current subkernel
261 wx = subkernel_x + kx
262 wy = subkernel_y + ky
263 # Source IFM/OFM slices
264 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
265 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
266 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
267 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
268 stream.append(0)
269 else:
Tim Hallf7e810a2020-06-25 15:04:31 +0100270 stream.append(brick_weights[ofm_z][wy][wx][ifm_z])
Tim Hall79d07d22020-04-27 18:20:16 +0100271 return stream
272
Jacob Bohline843d332020-06-23 12:12:56 +0200273
Tim Hallf7e810a2020-06-25 15:04:31 +0100274def core_deinterleave(hwio, core, ncores):
275 # Put weights back into OHWI
Jacob Bohline843d332020-06-23 12:12:56 +0200276 ohwi = np.transpose(hwio, (3, 0, 1, 2))
277 return ohwi[core : ohwi.shape[0] : ncores]
278
Tim Hall79d07d22020-04-27 18:20:16 +0100279
280# Compress the weights
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200281def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Tim Hall79d07d22020-04-27 18:20:16 +0100282 assert tens.purpose == TensorPurpose.Weights
Tim Hall79d07d22020-04-27 18:20:16 +0100283
Louis Verhaard3c07c972020-05-07 08:12:58 +0200284 # Check the weight cache
285 if nng.weight_cache is None:
286 nng.weight_cache = CompressedWeightCache()
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200287 wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200288 tens.weight_compression_config = wcc
Louis Verhaard9db529a2020-09-23 10:27:11 +0200289 # Reassign equivalence id such that tensors with same weight compression get identical equivalence ids,
290 # but tensors with the same values but different compression get different equivalence ids
291 tens.equivalence_id = create_equivalence_id(wcc)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200292 tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc)
293 if tens_cached is not None:
294 # Cache hit, copy weights from the cache
295 tens.copy_compressed_weight_info(tens_cached)
296 set_storage_shape(tens)
297 return
Louis Verhaard3c07c972020-05-07 08:12:58 +0200298 # No cache hit, perform the compression
Tim Hall79d07d22020-04-27 18:20:16 +0100299 assert tens.quantization is not None
300 assert tens.quantization.scale_f32 is not None
301 assert tens.quantization.zero_point is not None
302
303 zero_point = tens.quantization.zero_point
304 quant_buf = tens.quant_values.astype(np.int64)
305
306 # Early zero-point correction
307 weights = quant_buf - zero_point
308
309 if len(weights.shape) == 2:
310 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
Tim Hall79d07d22020-04-27 18:20:16 +0100311
312 compression_scales = []
313 compressed_offsets = []
314 encoded_streams = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100315 encoded_streams_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100316 offset = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100317 max_single_buffer_len = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100318
319 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
320 ifm_depth = weights.shape[-2]
321 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
322 tens.block_traversal = TensorBlockTraversal.DepthWise
323 if npu_block_type == NpuBlockType.ConvolutionMxN:
324 # Determine which block traversal strategy has better DPU utilization
Jacob Bohlinde2a57f2020-08-10 15:21:42 +0200325 kernel_size = weights.shape[0] * weights.shape[1]
326 depth_utilization = weights.shape[2] / round_up(weights.shape[2], 32 if ifm_bitdepth == 8 else 16)
327 part_kernel_utilization = (weights.shape[2] / round_up(weights.shape[2], 8)) * (
Tim Hall79d07d22020-04-27 18:20:16 +0100328 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
329 )
330 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
331 # Part-kernel first is always better for ifm depths <= 8
332 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
333 else:
334 tens.block_traversal = TensorBlockTraversal.DepthFirst
335
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100336 is_depthwise = tens.block_traversal == TensorBlockTraversal.DepthWise
337 is_partkernel = tens.block_traversal == TensorBlockTraversal.PartKernelFirst
338
Jacob Bohlincf7da102020-05-20 09:03:40 +0200339 if tens.consumer_list[0].type == "Conv2DBackpropInputSwitchedBias":
340 # Transpose Convoluion, reverse weights in H and W axes
Tim Hallc30f4952020-06-15 20:47:35 +0100341 weights = np.flip(weights, axis=(0, 1))
Jacob Bohlincf7da102020-05-20 09:03:40 +0200342
Jacob Bohline843d332020-06-23 12:12:56 +0200343 # Calculate brick size
Jacob Bohlinde2a57f2020-08-10 15:21:42 +0200344 brick_size = (weights.shape[0], weights.shape[1], weights.shape[2], min(tens.shape[-1], ofm_depth_step))
Jacob Bohline843d332020-06-23 12:12:56 +0200345 elements_in_brick = np.prod(brick_size)
346
Tim Hall79d07d22020-04-27 18:20:16 +0100347 # Slice weight stream up depth-ways into bricks and compress
348 full_ofm_depth = quant_buf.shape[-1]
349 for idx in range(0, full_ofm_depth, ofm_depth_step):
350 # Get the weights necessary for this brick
351 count = min(full_ofm_depth - idx, ofm_depth_step)
352 brick_weights = weights[:, :, :, idx : idx + count]
353
Tim Hallf7e810a2020-06-25 15:04:31 +0100354 substream_offsets = [0]
355 encoded_stream = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100356
357 # For each core, deinterleave weights from the larger volume
358 # and generate separate compressed streams.
359 for core in range(0, min(arch.ncores, full_ofm_depth)):
360 core_weights = core_deinterleave(brick_weights, core, arch.ncores)
Tim Hall62316762020-06-25 16:55:02 +0100361
362 block_depth = (ofm_block_depth + arch.ncores - 1 - core) // arch.ncores
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100363 encoded_substream = []
Tim Hall62316762020-06-25 16:55:02 +0100364 if block_depth != 0:
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100365 encoded_substream = encode_weights(
366 accelerator=arch.accelerator_config,
367 weights_volume=core_weights,
368 dilation_xy=dilation,
369 ifm_bitdepth=ifm_bitdepth,
370 ofm_block_depth=block_depth,
371 is_depthwise=is_depthwise,
372 is_partkernel=is_partkernel,
Jacob Bohline843d332020-06-23 12:12:56 +0200373 )
Jacob Bohline843d332020-06-23 12:12:56 +0200374 encoded_stream.extend(encoded_substream)
375 substream_offsets.append(len(encoded_stream))
Tim Hallf7e810a2020-06-25 15:04:31 +0100376
Jacob Bohline843d332020-06-23 12:12:56 +0200377 encoded_streams.append(encoded_stream)
378 encoded_streams_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100379
380 # Remember maximum encoded length for DoubleBuffering
381 max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100382
Tim Hall79d07d22020-04-27 18:20:16 +0100383 # Remember where we put it for linear addressing
384 compressed_offsets.append(offset)
Tim Hallf7e810a2020-06-25 15:04:31 +0100385 offset += len(encoded_stream)
Tim Hall79d07d22020-04-27 18:20:16 +0100386 assert offset % 16 == 0
387
388 # Compression scale tracking
Jacob Bohline843d332020-06-23 12:12:56 +0200389 compression_scales.append(len(encoded_stream) / elements_in_brick)
Tim Hall79d07d22020-04-27 18:20:16 +0100390
Tim Hallf7e810a2020-06-25 15:04:31 +0100391 # Track total length as last element of the offsets array
Tim Hall79d07d22020-04-27 18:20:16 +0100392 compressed_offsets.append(offset)
393
Tim Hall79d07d22020-04-27 18:20:16 +0100394 tens.weight_compression_scales = compression_scales
Tim Hall79d07d22020-04-27 18:20:16 +0100395 tens.weight_compressed_offsets = compressed_offsets
396 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
397 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
398 tens.compressed_values = encoded_streams
Tim Hallf7e810a2020-06-25 15:04:31 +0100399 tens.compressed_values_substream_offsets = encoded_streams_substream_offsets
Jacob Bohline843d332020-06-23 12:12:56 +0200400 tens.brick_size = brick_size
Louis Verhaard3c07c972020-05-07 08:12:58 +0200401 set_storage_shape(tens)
402 nng.weight_cache.add(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100403
Jacob Bohline843d332020-06-23 12:12:56 +0200404
Tim Hallf7e810a2020-06-25 15:04:31 +0100405def calc_scales_and_pack_biases(tens, arch, ofm_depth_step, rescale_for_faf=False):
Tim Hall79d07d22020-04-27 18:20:16 +0100406 assert tens.purpose == TensorPurpose.FeatureMap
407 assert tens.format == TensorFormat.NHWC
408 # the connected operator should expect a bias input unless it is a FullyConnected
409 assert "Bias" in tens.consumer_list[0].type or tens.consumer_list[0].type.startswith("FullyConnected")
410 # the input bias tensor is the same as that connected to the operator
Jacob Bohlincf7da102020-05-20 09:03:40 +0200411 _, _, bias_tens, _ = tens.consumer_list[0].get_ifm_weights_biases_ofm()
412 assert tens is bias_tens
413
Tim Hall79d07d22020-04-27 18:20:16 +0100414 # the operator should only have a single output
415 assert len(tens.consumer_list[0].outputs) == 1
Tim Hall79d07d22020-04-27 18:20:16 +0100416 biases = tens.quant_values
417
418 first_consumer_op = tens.consumer_list[0]
419 ifm_dtype = first_consumer_op.inputs[0].dtype
420 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200421 ofm_scale = first_consumer_op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100422 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
423
424 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
425 for op in tens.consumer_list[1:]:
426 assert ifm_scale == op.inputs[0].quantization.scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200427 assert ofm_scale == op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100428 assert weight_scales == op.inputs[1].quantization.scale_f32
429
430 if not hasattr(weight_scales, "__iter__"):
431 # If weight_scales is not already an iterable make it into a list
432 weight_scales = [weight_scales]
433
434 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
435 # uses double during scaling calculations
436 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
437 if not rescale_for_faf:
438 if ifm_dtype == DataType.uint8:
439 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200440 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100441 scales = [
442 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
443 for weight_scale in weight_scales
444 ]
445 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200446 raise UnsupportedFeatureError(
447 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
448 )
Tim Hall79d07d22020-04-27 18:20:16 +0100449 else:
450 if ifm_dtype == DataType.uint8:
451 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200452 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100453 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
454 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200455 raise UnsupportedFeatureError(
456 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
457 )
Tim Hall79d07d22020-04-27 18:20:16 +0100458
459 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200460 if ifm_dtype == DataType.int16:
461 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
462 else:
463 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100464
Tim Hall79d07d22020-04-27 18:20:16 +0100465 # pack the biases and scales
Tim Hall79d07d22020-04-27 18:20:16 +0100466 if len(quantised_scales) == 1:
467 # If only 1 quantised scale is used, repeat that value for the length of the biases
468 quantised_scales = [quantised_scales[0]] * len(biases)
469
470 assert len(quantised_scales) == len(biases)
Tim Hall79d07d22020-04-27 18:20:16 +0100471 tens.element_size_bytes = 10
Tim Hallf7e810a2020-06-25 15:04:31 +0100472 tens.compressed_values = []
473 tens.compressed_values_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100474
Tim Hallf7e810a2020-06-25 15:04:31 +0100475 total_elements = len(quantised_scales)
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200476 alignment_bytes = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100477 for i in range(0, total_elements, ofm_depth_step):
478 # Extract streams from brick to generate substreams for each core
479 stream = bytearray()
480 substream_offsets = [0]
481 max_len = min(ofm_depth_step, total_elements - i)
482 for core in range(0, min(arch.ncores, max_len)):
Jacob Bohline843d332020-06-23 12:12:56 +0200483 core_scales = quantised_scales[i + core : i + core + max_len : arch.ncores]
484 core_biases = biases[i + core : i + core + max_len : arch.ncores]
Tim Hallf7e810a2020-06-25 15:04:31 +0100485 for j, core_bias in enumerate(core_biases):
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100486 stream.extend(encode_bias(np.int64(core_bias), *core_scales[j]))
Tim Hall79d07d22020-04-27 18:20:16 +0100487
Tim Hallf7e810a2020-06-25 15:04:31 +0100488 # Align to 16 for start for next substream
Jacob Bohline843d332020-06-23 12:12:56 +0200489 remainder = (len(stream)) % 16
Tim Hallf7e810a2020-06-25 15:04:31 +0100490 if remainder > 0:
Jacob Bohline843d332020-06-23 12:12:56 +0200491 stream.extend(bytearray(16 - remainder))
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200492 alignment_bytes += 16 - remainder
Tim Hall79d07d22020-04-27 18:20:16 +0100493
Jacob Bohline843d332020-06-23 12:12:56 +0200494 substream_offsets.append(len(stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100495
Tim Hallf7e810a2020-06-25 15:04:31 +0100496 # Add to compressed values with their substream offset lists to the tensor
Jacob Bohline843d332020-06-23 12:12:56 +0200497 tens.compressed_values.append(stream)
498 tens.compressed_values_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100499
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200500 tens.storage_shape = [total_elements + round_up_divide(alignment_bytes, tens.element_size_bytes)]
Tim Hall79d07d22020-04-27 18:20:16 +0100501
Jacob Bohline843d332020-06-23 12:12:56 +0200502
Tim Hall79d07d22020-04-27 18:20:16 +0100503def update_pass_weight_and_scale_tensors(nng, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100504 for sg in nng.subgraphs:
505 for ps in sg.passes:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200506 tens = ps.weight_tensor
507 if tens is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200508 op = tens.find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200509 if op is None:
510 continue
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200511 npu_usage_of_tensor = op.attrs["npu_block_type"]
Louis Verhaard3c07c972020-05-07 08:12:58 +0200512 needs_dma = tens.needs_dma()
Tim Hall79d07d22020-04-27 18:20:16 +0100513 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
514 ofm_depth_step = ps.block_config[-1]
515 else:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200516 ofm_depth_step = tens.shape[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100517 compress_weights(
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200518 arch, nng, tens, npu_usage_of_tensor, ps.block_config[-1], ofm_depth_step, op.get_dilation_h_w()
Tim Hall79d07d22020-04-27 18:20:16 +0100519 )
520 # Update source tensor
Louis Verhaard3c07c972020-05-07 08:12:58 +0200521 if needs_dma:
522 src_tens = tens.get_dma_src_tensor()
523 src_tens.shape = tens.shape
524 src_tens.quant_values = tens.quant_values
525 src_tens.copy_compressed_weight_info(tens)
526 set_storage_shape(src_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100527
Diego Russoea6111a2020-04-14 18:41:58 +0100528 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100529 rescale_for_faf = False
530 activation_ops = set(("Sigmoid", "Tanh"))
531 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
532 rescale_for_faf = True
Tim Hallf7e810a2020-06-25 15:04:31 +0100533 calc_scales_and_pack_biases(ps.scale_tensor, arch, ofm_depth_step, rescale_for_faf)