blob: c07229fb1572f2516a494379ea0a6974ec3f08b4 [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
Louis Verhaarde8a5a782020-11-02 18:04:27 +010023from .api import NpuBlockTraversal
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010024from .architecture_features import Accelerator
25from .architecture_features import ArchitectureFeatures
Diego Russoe8a10452020-04-21 17:39:10 +010026from .data_type import DataType
Louis Verhaard7db78962020-05-25 15:05:26 +020027from .errors import UnsupportedFeatureError
Diego Russoe8a10452020-04-21 17:39:10 +010028from .nn_graph import SchedulingStrategy
29from .numeric_util import round_up
Patrik Gustavssond89c09e2020-07-08 11:27:12 +020030from .numeric_util import round_up_divide
Diego Russoe8a10452020-04-21 17:39:10 +010031from .operation import NpuBlockType
Louis Verhaardaee5d752020-09-30 09:01:52 +020032from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010033from .scaling import quantise_scale
34from .scaling import reduced_quantise_scale
Louis Verhaard9db529a2020-09-23 10:27:11 +020035from .tensor import create_equivalence_id
Diego Russoe8a10452020-04-21 17:39:10 +010036from .tensor import TensorBlockTraversal
37from .tensor import TensorFormat
38from .tensor import TensorPurpose
39from .tensor import TensorSubPurpose
Jacob Bohline843d332020-06-23 12:12:56 +020040from ethosu import mlw_codec
Diego Russoe8a10452020-04-21 17:39:10 +010041
Tim Hall79d07d22020-04-27 18:20:16 +010042
Louis Verhaard3c07c972020-05-07 08:12:58 +020043# Contains meta info for a weight compression. If two tensors have identical weight compression config,
44# then they also will have identical compressed weights.
45WeightCompressionConfig = namedtuple(
Louis Verhaard9db529a2020-09-23 10:27:11 +020046 "WeightCompressionConfig", ["npu_block_type", "ofm_block_depth", "ofm_depth_step", "dilation", "value_id"]
Louis Verhaard3c07c972020-05-07 08:12:58 +020047)
48
49
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010050def encode_weights(
51 accelerator: Accelerator,
52 weights_volume: np.ndarray,
53 dilation_xy: tuple,
54 ifm_bitdepth: int,
55 ofm_block_depth: int,
56 is_depthwise: bool,
Louis Verhaarde8a5a782020-11-02 18:04:27 +010057 block_traversal: NpuBlockTraversal,
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010058):
59 """
60 Public facing API to use the ethosu weight encoding.
61
62 :param accelerator: architecture_features.Accelerator enum to pick the correct ethosu accelerator
63 :param weights_volume: numpy.ndarray in OHWI layout with a shape of four
64 :param dilation_xy: a two element tuple of dilation attributes in x,y dimension
65 :param ifm_bitdepth: the bitdepth of input feature map
66 :param ofm_block_depth: the depth of blocks for ethosu processing
67 :param is_depthwise: a boolean indicating these weights are used for a depthwise traversal
Louis Verhaarde8a5a782020-11-02 18:04:27 +010068 :param block_traversal: indicates how these weights are traversed on sub-kernal basis
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010069 :return: a bytearray of compressed weights
70 """
71
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +000072 # Check arg types
73 assert isinstance(accelerator, Accelerator)
74 assert isinstance(weights_volume, np.ndarray)
75 assert isinstance(dilation_xy, tuple)
76 assert isinstance(ifm_bitdepth, int)
77 assert isinstance(ofm_block_depth, int)
78 assert isinstance(is_depthwise, bool)
Louis Verhaarde8a5a782020-11-02 18:04:27 +010079 assert isinstance(block_traversal, NpuBlockTraversal)
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +000080
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010081 # Checks for weight layout
82 assert len(weights_volume.shape) == 4, "weights ndarray should have a shape of 4"
83
84 # It cannot be both partkernel and depthwise
Louis Verhaarde8a5a782020-11-02 18:04:27 +010085 assert not (
86 is_depthwise and block_traversal == NpuBlockTraversal.PART_KERNEL_FIRST
87 ), "encode_weights :: partkernel and depthwise are mutually exclusive"
Manupa Karunaratned83d2e12020-07-20 12:05:32 +010088
89 # Check valid values for dilation
90 assert dilation_xy[0] in (1, 2), "encode_weights :: dilation x should be 1 or 2 not {}".format(dilation_xy[0])
91 assert dilation_xy[1] in (1, 2), "encode_weights :: dilation y should be 1 or 2 not {}".format(dilation_xy[1])
92
93 ifm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ifm_ublock
94 ofm_ublock = ArchitectureFeatures.accelerator_configs[accelerator].ofm_ublock
95 raw_stream = generate_brick(
96 ifm_ublock=ifm_ublock,
97 ofm_ublock=ofm_ublock,
98 brick_weights=weights_volume,
99 ofm_block_depth=ofm_block_depth,
100 is_depthwise=is_depthwise,
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100101 is_partkernel=block_traversal == NpuBlockTraversal.PART_KERNEL_FIRST,
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100102 ifm_bitdepth=ifm_bitdepth,
103 dilation=dilation_xy,
104 )
105 encoded_stream = encode(raw_stream)
106 return encoded_stream
107
108
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100109def encode_bias(bias: np.int64, scale: int, shift: int):
110 """
111 Public facing API to pack bias and scale values as required by the hardware
112 :param bias: 64bit signed number that includes 40bit signed bias
113 :param scale: 32bit scale value
114 :param shift: 6bit shift value
115 :return: packed 80bit [0(2-bits),shift(6-bits),scale(32-bits),bias(40-bits)]
116 """
Manupa Karunaratne8b24f2b2020-08-12 18:26:39 +0000117 # Check arg types
118 assert isinstance(bias, np.int64)
119 assert isinstance(scale, int)
120 assert isinstance(shift, int)
121
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100122 assert -(1 << (40 - 1)) <= bias < (1 << (40 - 1)) # signed 40-bit range
123 assert 0 <= scale < (1 << 32) # unsigned 32-bit range
124 assert 0 <= shift < (1 << 6) # unsigned 6-bit range
125
126 data = bytearray(10)
127 data[0] = (bias >> (0 * 8)) & 0xFF
128 data[1] = (bias >> (1 * 8)) & 0xFF
129 data[2] = (bias >> (2 * 8)) & 0xFF
130 data[3] = (bias >> (3 * 8)) & 0xFF
131 data[4] = (bias >> (4 * 8)) & 0xFF
132 data[5] = (scale >> (0 * 8)) & 0xFF
133 data[6] = (scale >> (1 * 8)) & 0xFF
134 data[7] = (scale >> (2 * 8)) & 0xFF
135 data[8] = (scale >> (3 * 8)) & 0xFF
136 data[9] = shift & 0x3F
137 return data
138
139
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200140def create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Louis Verhaard3c07c972020-05-07 08:12:58 +0200141 # Note: for an ofm block only its depth is used in weight compression.
142 # And block depth > ofm depth gives same result as block depth == ofm depth
143 block_depth = min(ofm_block_depth, tens.quant_values.shape[-1])
Louis Verhaard9db529a2020-09-23 10:27:11 +0200144 return WeightCompressionConfig(npu_block_type, block_depth, ofm_depth_step, dilation, tens.value_id)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200145
146
147def set_storage_shape(tens):
148 # Sets the storage shape depending on the tensor's sub purpose
149 if tens.sub_purpose == TensorSubPurpose.DoubleBuffer and len(tens.compressed_values) > 2:
150 offset = 2 * np.amax([len(x) for x in tens.compressed_values])
151 assert offset % 16 == 0
152 else:
153 offset = tens.weight_compressed_offsets[-1]
154 tens.storage_shape = [1, 1, 1, offset]
155
156
157class CompressedWeightCache:
158 # Contains weight compressions for all weight tensors in a graph
159 def __init__(self):
160 self.cache = {} # maps from WeightCompressionConfig to a tensor clone containing compressed weights
161
162 def get_tensor_with_same_compression(self, wcc):
163 return self.cache.get(wcc)
164
165 def add(self, tens):
166 # Adds the compressed weights from the tensor to the cache
167 wcc = tens.weight_compression_config
168 # Clone the tensor to make sure that nothing related to the weight compression is modified
169 tens_clone = tens.clone("_weights{}_{}".format(wcc.ofm_block_depth, wcc.ofm_depth_step))
170 self.cache[wcc] = tens_clone
171
172
Tim Hall79d07d22020-04-27 18:20:16 +0100173def encode(weight_stream):
Patrik Gustavsson5ff99442020-07-10 10:12:17 +0200174 if len(weight_stream) == 0:
175 return []
Tim Hall79d07d22020-04-27 18:20:16 +0100176 assert np.amin(weight_stream) >= -255
177 assert np.amax(weight_stream) <= 255
178
179 # Encode flattened signed weight stream
180 compressed = mlw_codec.encode(weight_stream)
181
182 # pad with 0xFF as needed so the length of the weight stream
183 # is a multiple of 16
Diego Russoea6111a2020-04-14 18:41:58 +0100184
Tim Hall79d07d22020-04-27 18:20:16 +0100185 while (len(compressed) % 16) != 0:
186 compressed.append(0xFF)
187
188 return compressed
189
190
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100191def generate_brick(
192 ifm_ublock, ofm_ublock, brick_weights, ofm_block_depth, is_depthwise, is_partkernel, ifm_bitdepth, dilation
193):
194
195 decomp_h = ArchitectureFeatures.SubKernelMax.height // dilation[0]
196 decomp_w = ArchitectureFeatures.SubKernelMax.width // dilation[1]
Tim Hallf7e810a2020-06-25 15:04:31 +0100197 # Expect weights formatted OHWI
198 ofm_depth = brick_weights.shape[-4]
199 ifm_depth = brick_weights.shape[-1]
200 kernel_width = brick_weights.shape[-2]
201 kernel_height = brick_weights.shape[-3]
Tim Hall79d07d22020-04-27 18:20:16 +0100202 # IFM block depth
203 if is_partkernel or (ifm_bitdepth == 16):
204 # IFM block depth is always 16 for part-kernel-first
205 ifm_block_depth = 16
206 elif ifm_bitdepth == 8:
207 ifm_block_depth = 32
208 else:
209 assert False
210
211 stream = []
212
213 # Top level striping - OFM blocks in the entire brick's depth
Louis Verhaard3c07c972020-05-07 08:12:58 +0200214 for ofm_block_z in range(0, ofm_depth, ofm_block_depth):
215 clipped_ofm_block_depth = min(ofm_block_depth, ofm_depth - ofm_block_z)
Tim Hall79d07d22020-04-27 18:20:16 +0100216 # IFM blocks required for the brick
217 for ifm_block_z in range(0, (1 if is_depthwise else ifm_depth), ifm_block_depth):
218 if is_depthwise:
219 clipped_ifm_block_depth = ifm_ublock.depth
220 else:
221 clipped_ifm_block_depth = (
222 min(ifm_block_depth, ifm_depth - ifm_block_z) if is_partkernel else ifm_block_depth
223 )
224 # Weight decomposition
225 # Subkernel Splitting (H)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200226 for subkernel_y in range(0, kernel_height, decomp_h):
227 sub_height = min(kernel_height - subkernel_y, decomp_h)
Tim Hall79d07d22020-04-27 18:20:16 +0100228 # Subkernel splitting (W)
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200229 for subkernel_x in range(0, kernel_width, decomp_w):
230 sub_width = min(kernel_width - subkernel_x, decomp_w)
Tim Hall79d07d22020-04-27 18:20:16 +0100231 subkernel_elements = sub_width * sub_height
232 # Part kernel first works across the kernel H/W and needs padding
233 if is_partkernel:
234 if ifm_bitdepth == 16 and subkernel_elements % 2 != 0:
235 subkernel_elements = int(math.ceil(subkernel_elements / 2) * 2)
236 elif ifm_bitdepth == 8 and subkernel_elements % 4 != 0:
237 subkernel_elements = int(math.ceil(subkernel_elements / 4) * 4)
238
239 # Depthwise Conv requires multiple of 4 kernel elements in its weight block
240 # this is different from normal conv which is considered "weights depth-first"
241 elif is_depthwise:
242 subkernel_elements = int(math.ceil(subkernel_elements / 4.0) * 4)
243
244 ifm_block_depth_outer = clipped_ifm_block_depth if is_partkernel else 1
245 ifm_block_depth_inner = 1 if is_partkernel else clipped_ifm_block_depth
246 # IFM Ublocks in IFM-block over depth for part-kernel-first mode
247 # For depth-first IFM Ublocks are traversed after subkernel elements so this loop is ignored.
248 for ifm_ublk_outer in range(0, ifm_block_depth_outer, ifm_ublock.depth):
249 # OFM Ublocks in OFM-block over depth
250 for ofm_ublk in range(0, clipped_ofm_block_depth, ofm_ublock.depth):
251 # HW Kernel element traversal - cannot be a H/W loop due to element
252 # padding requirement on depthwise/part-kernel configurations
253 for element in range(subkernel_elements):
254 kx = element % sub_width
255 ky = element // sub_width
256 # IFM Ublocks in IFM-block over depth (only 1 ublock if depthwise)
257 # In case of part-kernel-first IFM Ublock traversal have already been handled
258 # and this loop is ignored.
259 for ifm_ublk_inner in range(0, ifm_block_depth_inner, ifm_ublock.depth):
260 # Feed OFM ublock elements
261 for ofm_ublock_z in range(ofm_ublock.depth):
262 # Source IFM ublock elements (only 1 element deep if depthwise)
263 for ifm_ublock_z in range(1 if is_depthwise else ifm_ublock.depth):
264 # Source position within the current subkernel
265 wx = subkernel_x + kx
266 wy = subkernel_y + ky
267 # Source IFM/OFM slices
268 ifm_ublk = ifm_ublk_inner + ifm_ublk_outer
269 ifm_z = ifm_block_z + ifm_ublk + ifm_ublock_z
270 ofm_z = ofm_block_z + ofm_ublk + ofm_ublock_z
271 if (ifm_z >= ifm_depth) or (ofm_z >= ofm_depth) or (ky >= sub_height):
272 stream.append(0)
273 else:
Tim Hallf7e810a2020-06-25 15:04:31 +0100274 stream.append(brick_weights[ofm_z][wy][wx][ifm_z])
Tim Hall79d07d22020-04-27 18:20:16 +0100275 return stream
276
Jacob Bohline843d332020-06-23 12:12:56 +0200277
Tim Hallf7e810a2020-06-25 15:04:31 +0100278def core_deinterleave(hwio, core, ncores):
279 # Put weights back into OHWI
Jacob Bohline843d332020-06-23 12:12:56 +0200280 ohwi = np.transpose(hwio, (3, 0, 1, 2))
281 return ohwi[core : ohwi.shape[0] : ncores]
282
Tim Hall79d07d22020-04-27 18:20:16 +0100283
284# Compress the weights
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200285def compress_weights(arch, nng, tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation):
Tim Hall79d07d22020-04-27 18:20:16 +0100286 assert tens.purpose == TensorPurpose.Weights
Tim Hall79d07d22020-04-27 18:20:16 +0100287
Louis Verhaard3c07c972020-05-07 08:12:58 +0200288 # Check the weight cache
289 if nng.weight_cache is None:
290 nng.weight_cache = CompressedWeightCache()
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200291 wcc = create_weight_compression_config(tens, npu_block_type, ofm_block_depth, ofm_depth_step, dilation)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200292 tens.weight_compression_config = wcc
Louis Verhaard9db529a2020-09-23 10:27:11 +0200293 # Reassign equivalence id such that tensors with same weight compression get identical equivalence ids,
294 # but tensors with the same values but different compression get different equivalence ids
295 tens.equivalence_id = create_equivalence_id(wcc)
Louis Verhaard3c07c972020-05-07 08:12:58 +0200296 tens_cached = nng.weight_cache.get_tensor_with_same_compression(wcc)
297 if tens_cached is not None:
298 # Cache hit, copy weights from the cache
299 tens.copy_compressed_weight_info(tens_cached)
300 set_storage_shape(tens)
301 return
Louis Verhaard3c07c972020-05-07 08:12:58 +0200302 # No cache hit, perform the compression
Tim Hall79d07d22020-04-27 18:20:16 +0100303 assert tens.quantization is not None
304 assert tens.quantization.scale_f32 is not None
305 assert tens.quantization.zero_point is not None
306
307 zero_point = tens.quantization.zero_point
308 quant_buf = tens.quant_values.astype(np.int64)
309
310 # Early zero-point correction
311 weights = quant_buf - zero_point
312
313 if len(weights.shape) == 2:
314 weights = np.expand_dims(np.expand_dims(weights, axis=0), axis=0)
Tim Hall79d07d22020-04-27 18:20:16 +0100315
316 compression_scales = []
317 compressed_offsets = []
318 encoded_streams = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100319 encoded_streams_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100320 offset = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100321 max_single_buffer_len = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100322
323 ifm_bitdepth = tens.consumer_list[0].inputs[0].dtype.size_in_bits()
324 ifm_depth = weights.shape[-2]
325 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
326 tens.block_traversal = TensorBlockTraversal.DepthWise
327 if npu_block_type == NpuBlockType.ConvolutionMxN:
328 # Determine which block traversal strategy has better DPU utilization
Jacob Bohlinde2a57f2020-08-10 15:21:42 +0200329 kernel_size = weights.shape[0] * weights.shape[1]
330 depth_utilization = weights.shape[2] / round_up(weights.shape[2], 32 if ifm_bitdepth == 8 else 16)
331 part_kernel_utilization = (weights.shape[2] / round_up(weights.shape[2], 8)) * (
Tim Hall79d07d22020-04-27 18:20:16 +0100332 kernel_size / round_up(kernel_size, 4 if ifm_bitdepth == 8 else 2)
333 )
334 if part_kernel_utilization >= depth_utilization or ifm_depth <= 8:
335 # Part-kernel first is always better for ifm depths <= 8
336 tens.block_traversal = TensorBlockTraversal.PartKernelFirst
337 else:
338 tens.block_traversal = TensorBlockTraversal.DepthFirst
339
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100340 is_depthwise = tens.block_traversal == TensorBlockTraversal.DepthWise
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100341 if tens.block_traversal == TensorBlockTraversal.PartKernelFirst:
342 block_traversal = NpuBlockTraversal.PART_KERNEL_FIRST
343 else:
344 block_traversal = NpuBlockTraversal.DEPTH_FIRST
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100345
Louis Verhaardaee5d752020-09-30 09:01:52 +0200346 if tens.consumer_list[0].type == Op.Conv2DBackpropInputSwitchedBias:
Jacob Bohlincf7da102020-05-20 09:03:40 +0200347 # Transpose Convoluion, reverse weights in H and W axes
Tim Hallc30f4952020-06-15 20:47:35 +0100348 weights = np.flip(weights, axis=(0, 1))
Jacob Bohlincf7da102020-05-20 09:03:40 +0200349
Jacob Bohline843d332020-06-23 12:12:56 +0200350 # Calculate brick size
Jacob Bohlinde2a57f2020-08-10 15:21:42 +0200351 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 +0200352 elements_in_brick = np.prod(brick_size)
353
Tim Hall79d07d22020-04-27 18:20:16 +0100354 # Slice weight stream up depth-ways into bricks and compress
355 full_ofm_depth = quant_buf.shape[-1]
356 for idx in range(0, full_ofm_depth, ofm_depth_step):
357 # Get the weights necessary for this brick
358 count = min(full_ofm_depth - idx, ofm_depth_step)
359 brick_weights = weights[:, :, :, idx : idx + count]
360
Tim Hallf7e810a2020-06-25 15:04:31 +0100361 substream_offsets = [0]
362 encoded_stream = []
Tim Hallf7e810a2020-06-25 15:04:31 +0100363
364 # For each core, deinterleave weights from the larger volume
365 # and generate separate compressed streams.
366 for core in range(0, min(arch.ncores, full_ofm_depth)):
367 core_weights = core_deinterleave(brick_weights, core, arch.ncores)
Tim Hall62316762020-06-25 16:55:02 +0100368
369 block_depth = (ofm_block_depth + arch.ncores - 1 - core) // arch.ncores
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100370 encoded_substream = []
Tim Hall62316762020-06-25 16:55:02 +0100371 if block_depth != 0:
Manupa Karunaratned83d2e12020-07-20 12:05:32 +0100372 encoded_substream = encode_weights(
373 accelerator=arch.accelerator_config,
374 weights_volume=core_weights,
375 dilation_xy=dilation,
376 ifm_bitdepth=ifm_bitdepth,
377 ofm_block_depth=block_depth,
378 is_depthwise=is_depthwise,
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100379 block_traversal=block_traversal,
Jacob Bohline843d332020-06-23 12:12:56 +0200380 )
Jacob Bohline843d332020-06-23 12:12:56 +0200381 encoded_stream.extend(encoded_substream)
382 substream_offsets.append(len(encoded_stream))
Tim Hallf7e810a2020-06-25 15:04:31 +0100383
Jacob Bohline843d332020-06-23 12:12:56 +0200384 encoded_streams.append(encoded_stream)
385 encoded_streams_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100386
387 # Remember maximum encoded length for DoubleBuffering
388 max_single_buffer_len = max(max_single_buffer_len, len(encoded_stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100389
Tim Hall79d07d22020-04-27 18:20:16 +0100390 # Remember where we put it for linear addressing
391 compressed_offsets.append(offset)
Tim Hallf7e810a2020-06-25 15:04:31 +0100392 offset += len(encoded_stream)
Tim Hall79d07d22020-04-27 18:20:16 +0100393 assert offset % 16 == 0
394
395 # Compression scale tracking
Jacob Bohline843d332020-06-23 12:12:56 +0200396 compression_scales.append(len(encoded_stream) / elements_in_brick)
Tim Hall79d07d22020-04-27 18:20:16 +0100397
Tim Hallf7e810a2020-06-25 15:04:31 +0100398 # Track total length as last element of the offsets array
Tim Hall79d07d22020-04-27 18:20:16 +0100399 compressed_offsets.append(offset)
400
Tim Hall79d07d22020-04-27 18:20:16 +0100401 tens.weight_compression_scales = compression_scales
Tim Hall79d07d22020-04-27 18:20:16 +0100402 tens.weight_compressed_offsets = compressed_offsets
403 tens.compression_scale_for_worst_weight_stream = np.amax(compression_scales)
404 tens.storage_compression_scale = tens.bandwidth_compression_scale = np.average(compression_scales)
405 tens.compressed_values = encoded_streams
Tim Hallf7e810a2020-06-25 15:04:31 +0100406 tens.compressed_values_substream_offsets = encoded_streams_substream_offsets
Jacob Bohline843d332020-06-23 12:12:56 +0200407 tens.brick_size = brick_size
Louis Verhaard3c07c972020-05-07 08:12:58 +0200408 set_storage_shape(tens)
409 nng.weight_cache.add(tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100410
Jacob Bohline843d332020-06-23 12:12:56 +0200411
Tim Hallf7e810a2020-06-25 15:04:31 +0100412def calc_scales_and_pack_biases(tens, arch, ofm_depth_step, rescale_for_faf=False):
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100413 assert tens.purpose in [TensorPurpose.FeatureMap, TensorPurpose.FSBias]
Tim Hall79d07d22020-04-27 18:20:16 +0100414 assert tens.format == TensorFormat.NHWC
415 # the connected operator should expect a bias input unless it is a FullyConnected
Louis Verhaardaee5d752020-09-30 09:01:52 +0200416 assert tens.consumer_list[0].type.needs_bias()
Tim Hall79d07d22020-04-27 18:20:16 +0100417 # the input bias tensor is the same as that connected to the operator
Louis Verhaardaee5d752020-09-30 09:01:52 +0200418 bias_tens = tens.consumer_list[0].bias
Jacob Bohlincf7da102020-05-20 09:03:40 +0200419 assert tens is bias_tens
420
Tim Hall79d07d22020-04-27 18:20:16 +0100421 # the operator should only have a single output
422 assert len(tens.consumer_list[0].outputs) == 1
Tim Hall79d07d22020-04-27 18:20:16 +0100423 biases = tens.quant_values
424
425 first_consumer_op = tens.consumer_list[0]
426 ifm_dtype = first_consumer_op.inputs[0].dtype
427 ifm_scale = first_consumer_op.inputs[0].quantization.scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200428 ofm_scale = first_consumer_op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100429 weight_scales = first_consumer_op.inputs[1].quantization.scale_f32
430
431 # biases can have multiple consumers for rnn cells. if so, then check that they are all the same
432 for op in tens.consumer_list[1:]:
433 assert ifm_scale == op.inputs[0].quantization.scale_f32
Louis Verhaard98a34992020-09-01 10:39:04 +0200434 assert ofm_scale == op.get_output_quantization().scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100435 assert weight_scales == op.inputs[1].quantization.scale_f32
436
437 if not hasattr(weight_scales, "__iter__"):
438 # If weight_scales is not already an iterable make it into a list
439 weight_scales = [weight_scales]
440
441 # Convert scales to np.double (from np.float32) to conform to TensorFlow Lite which
442 # uses double during scaling calculations
443 # TensorFlow Lite casts the scales slightly differently for uint8 and int8
444 if not rescale_for_faf:
445 if ifm_dtype == DataType.uint8:
446 scales = [np.double(ifm_scale * weight_scale) / np.double(ofm_scale) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200447 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100448 scales = [
449 (np.double(ifm_scale) * np.double(weight_scale)) / np.double(ofm_scale)
450 for weight_scale in weight_scales
451 ]
452 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200453 raise UnsupportedFeatureError(
454 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
455 )
Tim Hall79d07d22020-04-27 18:20:16 +0100456 else:
457 if ifm_dtype == DataType.uint8:
458 scales = [np.double(ifm_scale * weight_scale * 0x3000) for weight_scale in weight_scales]
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200459 elif ifm_dtype == DataType.int8 or ifm_dtype == DataType.int16:
Tim Hall79d07d22020-04-27 18:20:16 +0100460 scales = [(np.double(ifm_scale * 0x3000) * np.double(weight_scale)) for weight_scale in weight_scales]
461 else:
Louis Verhaard7db78962020-05-25 15:05:26 +0200462 raise UnsupportedFeatureError(
463 "Compression of {} is not implemented; tensor: {}".format(ifm_dtype, tens.name)
464 )
Tim Hall79d07d22020-04-27 18:20:16 +0100465
466 # quantise all of the weight scales into (scale_factor, shift)
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200467 if ifm_dtype == DataType.int16:
468 quantised_scales = [reduced_quantise_scale(scale) for scale in scales]
469 else:
470 quantised_scales = [quantise_scale(scale) for scale in scales]
Tim Hall79d07d22020-04-27 18:20:16 +0100471
Tim Hall79d07d22020-04-27 18:20:16 +0100472 # pack the biases and scales
Tim Hall79d07d22020-04-27 18:20:16 +0100473 if len(quantised_scales) == 1:
474 # If only 1 quantised scale is used, repeat that value for the length of the biases
475 quantised_scales = [quantised_scales[0]] * len(biases)
476
477 assert len(quantised_scales) == len(biases)
Tim Hall79d07d22020-04-27 18:20:16 +0100478 tens.element_size_bytes = 10
Tim Hallf7e810a2020-06-25 15:04:31 +0100479 tens.compressed_values = []
480 tens.compressed_values_substream_offsets = []
Tim Hall79d07d22020-04-27 18:20:16 +0100481
Tim Hallf7e810a2020-06-25 15:04:31 +0100482 total_elements = len(quantised_scales)
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200483 alignment_bytes = 0
Tim Hallf7e810a2020-06-25 15:04:31 +0100484 for i in range(0, total_elements, ofm_depth_step):
485 # Extract streams from brick to generate substreams for each core
486 stream = bytearray()
487 substream_offsets = [0]
488 max_len = min(ofm_depth_step, total_elements - i)
489 for core in range(0, min(arch.ncores, max_len)):
Jacob Bohline843d332020-06-23 12:12:56 +0200490 core_scales = quantised_scales[i + core : i + core + max_len : arch.ncores]
491 core_biases = biases[i + core : i + core + max_len : arch.ncores]
Tim Hallf7e810a2020-06-25 15:04:31 +0100492 for j, core_bias in enumerate(core_biases):
Manupa Karunaratnebef228b2020-07-29 18:06:28 +0100493 stream.extend(encode_bias(np.int64(core_bias), *core_scales[j]))
Tim Hall79d07d22020-04-27 18:20:16 +0100494
Tim Hallf7e810a2020-06-25 15:04:31 +0100495 # Align to 16 for start for next substream
Jacob Bohline843d332020-06-23 12:12:56 +0200496 remainder = (len(stream)) % 16
Tim Hallf7e810a2020-06-25 15:04:31 +0100497 if remainder > 0:
Jacob Bohline843d332020-06-23 12:12:56 +0200498 stream.extend(bytearray(16 - remainder))
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200499 alignment_bytes += 16 - remainder
Tim Hall79d07d22020-04-27 18:20:16 +0100500
Jacob Bohline843d332020-06-23 12:12:56 +0200501 substream_offsets.append(len(stream))
Tim Hall79d07d22020-04-27 18:20:16 +0100502
Tim Hallf7e810a2020-06-25 15:04:31 +0100503 # Add to compressed values with their substream offset lists to the tensor
Jacob Bohline843d332020-06-23 12:12:56 +0200504 tens.compressed_values.append(stream)
505 tens.compressed_values_substream_offsets.append(substream_offsets)
Tim Hallf7e810a2020-06-25 15:04:31 +0100506
Patrik Gustavssond89c09e2020-07-08 11:27:12 +0200507 tens.storage_shape = [total_elements + round_up_divide(alignment_bytes, tens.element_size_bytes)]
Tim Hall79d07d22020-04-27 18:20:16 +0100508
Jacob Bohline843d332020-06-23 12:12:56 +0200509
Tim Hall79d07d22020-04-27 18:20:16 +0100510def update_pass_weight_and_scale_tensors(nng, arch):
Tim Hall79d07d22020-04-27 18:20:16 +0100511 for sg in nng.subgraphs:
512 for ps in sg.passes:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200513 tens = ps.weight_tensor
514 if tens is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200515 op = tens.find_npu_op()
Dwight Lidman940fdee2020-08-13 13:11:48 +0200516 if op is None:
517 continue
Louis Verhaard3c07c972020-05-07 08:12:58 +0200518 needs_dma = tens.needs_dma()
Tim Hall79d07d22020-04-27 18:20:16 +0100519 if ps.cascade.strategy == SchedulingStrategy.WeightStream and needs_dma:
520 ofm_depth_step = ps.block_config[-1]
521 else:
Louis Verhaard3c07c972020-05-07 08:12:58 +0200522 ofm_depth_step = tens.shape[-1]
Tim Hall79d07d22020-04-27 18:20:16 +0100523 compress_weights(
Louis Verhaardaee5d752020-09-30 09:01:52 +0200524 arch, nng, tens, op.type.npu_block_type, ps.block_config[-1], ofm_depth_step, op.get_dilation_h_w()
Tim Hall79d07d22020-04-27 18:20:16 +0100525 )
526 # Update source tensor
Louis Verhaard3c07c972020-05-07 08:12:58 +0200527 if needs_dma:
528 src_tens = tens.get_dma_src_tensor()
529 src_tens.shape = tens.shape
530 src_tens.quant_values = tens.quant_values
531 src_tens.copy_compressed_weight_info(tens)
532 set_storage_shape(src_tens)
Tim Hall79d07d22020-04-27 18:20:16 +0100533
Diego Russoea6111a2020-04-14 18:41:58 +0100534 if ps.scale_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100535 rescale_for_faf = False
Louis Verhaardaee5d752020-09-30 09:01:52 +0200536 activation_ops = set((Op.Sigmoid, Op.Tanh))
Tim Hall79d07d22020-04-27 18:20:16 +0100537 if (ps.ops[-1].type in activation_ops) and (ps.npu_block_type != NpuBlockType.ElementWise):
538 rescale_for_faf = True
Tim Hallf7e810a2020-06-25 15:04:31 +0100539 calc_scales_and_pack_biases(ps.scale_tensor, arch, ofm_depth_step, rescale_for_faf)
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100540 if ps.scale_tensor.ops[0].type == Op.DMA:
541 src_tens = ps.scale_tensor.get_dma_src_tensor()
542 src_tens.shape = ps.scale_tensor.shape
543 src_tens.quant_values = ps.scale_tensor.quant_values
544 src_tens.element_size_bytes = ps.scale_tensor.element_size_bytes
545 src_tens.copy_compressed_weight_info(ps.scale_tensor)