blob: a5372d735330a3437d7ac9900bdff7dfbc4f9af1 [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# Contains classes that hold commands for the high-level command stream (one command per DMA or NPU stripe).
Diego Russoea6111a2020-04-14 18:41:58 +010018from enum import IntEnum
19
Tim Hall79d07d22020-04-27 18:20:16 +010020import numpy as np
Diego Russoea6111a2020-04-14 18:41:58 +010021
Tim Hall79d07d22020-04-27 18:20:16 +010022from .numeric_util import round_up_divide
Diego Russoe8a10452020-04-21 17:39:10 +010023from .operation import NpuBlockType
Andreas Nevalainen897cc142020-10-28 15:42:08 +010024from .operation import Op
Diego Russoe8a10452020-04-21 17:39:10 +010025from .range_set import AccessDirection
26from .range_set import MemoryAccessSet
Louis Verhaard0b8268a2020-08-05 16:11:29 +020027from .range_set import MemoryRangeSet
28from .tensor import MemArea
29from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010030
31
32class Box:
33 def __init__(self, start_coord, end_coord):
34 self.start_coord = list(start_coord)
35 self.end_coord = list(end_coord)
36 assert len(self.start_coord) == len(end_coord)
37 for i in range(len(self.start_coord)):
38 assert self.start_coord[i] <= self.end_coord[i]
39
40 def transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +010041 self,
42 strides,
43 skirt,
44 ifm_shape,
45 npu_block_type,
46 concat_axis=0,
47 concat_offset=0,
48 split_offset=None,
49 k_height=1,
50 upscaling_factor=1,
Tim Hall79d07d22020-04-27 18:20:16 +010051 ):
52 new_start_coord = list(self.start_coord)
53 new_end_coord = list(self.end_coord)
54
55 new_start_coord[concat_axis] -= concat_offset
56 new_end_coord[concat_axis] -= concat_offset
57
Diego Russoea6111a2020-04-14 18:41:58 +010058 if split_offset is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010059 for idx in range(len(split_offset)):
60 new_start_coord[idx] += split_offset[idx]
61 new_end_coord[idx] += split_offset[idx]
62
Fredrik Svedberga0c36242020-06-03 15:43:31 +020063 if split_offset is None and npu_block_type in set(
64 (NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct, NpuBlockType.ReduceSum)
65 ):
66 # these types of operations do a "dot product" or sum over the entire IFM
Tim Hall79d07d22020-04-27 18:20:16 +010067 new_start_coord[-1] = 0
68 new_end_coord[-1] = ifm_shape[-1]
69
Louis Verhaarde0ef2732020-06-03 08:56:44 +020070 if npu_block_type == NpuBlockType.ElementWise and min(len(new_end_coord), len(ifm_shape)) >= 1:
71 new_end_coord[-1] = min(new_end_coord[-1], ifm_shape[-1])
Tim Hall79d07d22020-04-27 18:20:16 +010072 if min(len(new_end_coord), len(ifm_shape)) >= 2:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020073 new_end_coord[-2] = min(new_end_coord[-2], ifm_shape[-2] * upscaling_factor)
Tim Hall79d07d22020-04-27 18:20:16 +010074 if min(len(new_end_coord), len(ifm_shape)) >= 3:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020075 original_end_coord = list(new_end_coord)
76 new_end_coord[-3] = min(new_end_coord[-3], ifm_shape[-3] * upscaling_factor)
Tim Hall79d07d22020-04-27 18:20:16 +010077
78 pad_top = 0
79 pad_bottom = 0
80 if strides is not None and skirt is not None:
81 if len(new_start_coord) >= 2:
82 stride = strides[2]
83 new_start_coord[-2] = max(new_start_coord[-2] * stride - skirt[1], 0)
84 new_end_coord[-2] = min(new_end_coord[-2] * stride + skirt[3], ifm_shape[-2])
85
86 if len(new_start_coord) >= 3:
87 stride = strides[1]
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020088 skirt_top_remainder = skirt[0] % upscaling_factor
Tim Hall79d07d22020-04-27 18:20:16 +010089
90 total_stride = stride * (new_end_coord[-3] - new_start_coord[-3] - 1)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020091 new_start_coord[-3] = new_start_coord[-3] * stride - skirt[0] + skirt_top_remainder
Tim Hall79d07d22020-04-27 18:20:16 +010092
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020093 pad_top = max(0, 0 - new_start_coord[-3]) + skirt_top_remainder
Tim Hall79d07d22020-04-27 18:20:16 +010094 new_start_coord[-3] = max(new_start_coord[-3], 0)
95
96 while len(ifm_shape) < 3:
97 ifm_shape = [1] + ifm_shape
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020098
99 if (new_end_coord[-3] * stride + skirt[2]) > (ifm_shape[-3] * upscaling_factor):
Tim Hall79d07d22020-04-27 18:20:16 +0100100 # pad_bottom is calculated based the diff between the end position of the weight kernel,
101 # after last stride and the ifm height.
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200102 if upscaling_factor != 1 and original_end_coord[-3] > ifm_shape[-3] * upscaling_factor:
103 # Special case for Transpose Convolution with VALID padding.
104 pad_bottom = original_end_coord[-3] - (ifm_shape[-3] * upscaling_factor)
105 else:
106 k_start = new_start_coord[-3] - pad_top
107 pad_bottom = max(0, k_start + total_stride + k_height - (ifm_shape[-3] * upscaling_factor))
Tim Hall79d07d22020-04-27 18:20:16 +0100108
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200109 # Adjust for upscaling
110 new_start_coord[-3] = max(new_start_coord[-3] // upscaling_factor, 0)
111 new_end_coord[-3] = new_end_coord[-3] * stride + skirt[2] + (skirt[2] % upscaling_factor)
112 new_end_coord[-3] = min(new_end_coord[-3] // upscaling_factor, ifm_shape[-3])
Tim Hall79d07d22020-04-27 18:20:16 +0100113
114 return Box(new_start_coord, new_end_coord), pad_top, pad_bottom
115
116 def make_weight_box(weight_shape, npu_block_type, oc_range_start=None, oc_range_end=None, weights_transposed=False):
117 start = [0] * len(weight_shape)
118 end = list(weight_shape)
119 if oc_range_start is not None and oc_range_end is not None:
120 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
121 # input range is output range divided by channel multiplier
122 if weights_transposed:
123 start[-1] = oc_range_start // weight_shape[-2]
124 end[-1] = oc_range_end // weight_shape[-2]
125 else:
126 start[-2] = oc_range_start // weight_shape[-1]
127 end[-2] = oc_range_end // weight_shape[-1]
128 else:
129 start[-1] = oc_range_start
130 end[-1] = oc_range_end
131 for i in range(len(end)):
132 assert 0 <= start[i] < weight_shape[i]
133 assert 0 < end[i] <= weight_shape[i]
134
135 return Box(start, end)
136
137 def get_size_shape(self):
138 return [int(self.end_coord[i] - self.start_coord[i]) for i in range(len(self.end_coord))]
139
140 def get_size(self):
141 return int(np.prod(self.get_size_shape()))
142
143 def __str__(self):
144 return "<Box %s - %s>" % (self.start_coord, self.end_coord)
145
146 __repr__ = __str__
147
148
149class CommandType(IntEnum):
150 NpuStripe = 0
151 DMA = 1
152 Size = 2
153
154
155class Command:
156 def get_ofm_y_range_for_pass(self, ps_requested):
157 return None
158
159 def is_npu_pass_command(self):
160 return False
161
162 def get_memory_accesses(self):
163 return None
164
165 def get_operation_count(self):
166 # returns numpy array of (DPU blocks, dma_ops). Should line up with the CommandType enum
167 return np.array((0, 0))
168
169
170class NpuStripe(Command):
171 def __init__(
172 self,
173 ps,
174 block_config,
175 is_first,
176 is_last,
177 is_first_h_stripe,
178 is_last_h_stripe,
179 ifm_tensor,
180 ifm_box,
181 ofm_tensor,
182 ofm_box,
183 weight_tensor=None,
184 weight_box=None,
185 scale_tensor=None,
186 concat_axis=0,
187 concat_offset=0,
188 ifm2_tensor=None,
189 ifm2_box=None,
190 pad_top=0,
191 pad_bottom=0,
192 ):
193 self.cmdtype = CommandType.NpuStripe
194 self.ps = ps
195 self.block_config = block_config
196 self.is_first = is_first
197 self.is_last = is_last
198 self.is_first_h_stripe = is_first_h_stripe
199 self.is_last_h_stripe = is_last_h_stripe
200 self.ifm_tensor = ifm_tensor
201 self.ifm_box = ifm_box
202 self.ifm2_tensor = ifm2_tensor
203 self.ifm2_box = ifm2_box
204 self.ofm_tensor = ofm_tensor
205 self.ofm_box = ofm_box
206 self.weight_tensor = weight_tensor
207 self.scale_tensor = scale_tensor
208 self.weight_box = weight_box
209 self.concat_axis = concat_axis
210 self.concat_offset = concat_offset
211 self.pad_top = pad_top
212 self.pad_bottom = pad_bottom
213 for i in range(len(self.ofm_box.end_coord)):
214 assert self.ofm_box.end_coord[i] <= self.ofm_tensor.shape[i]
215
216 def get_memory_accesses(self):
217 res = MemoryAccessSet()
218 if self.ifm_tensor is not None and self.ifm_tensor.shape != []:
219 res.add(
220 self.ifm_tensor.get_address_ranges_for_coordinates(self.ifm_box.start_coord, self.ifm_box.end_coord),
221 AccessDirection.Read,
222 )
223 if self.ifm2_tensor is not None and self.ifm2_tensor.shape != []:
224 res.add(
225 self.ifm2_tensor.get_address_ranges_for_coordinates(self.ifm2_box.start_coord, self.ifm2_box.end_coord),
226 AccessDirection.Read,
227 )
228 if self.ofm_tensor is not None:
229 res.add(
230 self.ofm_tensor.get_address_ranges_for_coordinates(self.ofm_box.start_coord, self.ofm_box.end_coord),
231 AccessDirection.Write,
232 )
233 if self.weight_tensor is not None:
234 res.add(
235 self.weight_tensor.get_address_ranges_for_coordinates(
236 self.weight_box.start_coord, self.weight_box.end_coord
237 ),
238 AccessDirection.Read,
239 )
Andreas Nevalainen897cc142020-10-28 15:42:08 +0100240 if self.scale_tensor is not None and self.scale_tensor.ops[0].type == Op.DMA:
241 res.add(
242 self.scale_tensor.get_address_ranges_for_coordinates([0], self.scale_tensor.shape),
243 AccessDirection.Read,
244 )
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200245 # Add read access to SHRAM by any LUT-s
246 for tens in self.ps.intermediates:
247 if tens.purpose == TensorPurpose.LUT and tens.mem_area == MemArea.Shram:
248 res.add(
249 MemoryRangeSet(tens.mem_area, tens.address, tens.address + tens.storage_size()),
250 AccessDirection.Read,
251 )
Louis Verhaard814cfbb2020-08-21 14:06:25 +0200252 # Add write access to SHRAM, needed when LUTs can overwrite accumulator banks
253 res.add(
254 self.ps.shared_buffer.get_shram_memory_access_range(), AccessDirection.Write,
255 )
Tim Hall79d07d22020-04-27 18:20:16 +0100256 return res
257
258 def is_npu_pass_command(self):
259 return True
260
261 def __str__(self):
262 return "<NPUStripe: ps=%s, ifm_box=%s, ifm2_box=%s, ofm_box=%s, weight_box=%s, block_config=%s>" % (
263 self.ps.name,
264 self.ifm_box,
265 self.ifm2_box,
266 self.ofm_box,
267 self.weight_box,
268 self.block_config,
269 )
270
271 __repr__ = __str__
272
273 def get_ofm_y_range_for_pass(self, ps_requested):
274 if ps_requested != self.ps:
275 return None
276 if len(self.ofm_box.start_coord) >= 3:
277 return (self.ofm_box.start_coord[-3], self.ofm_box.end_coord[-3])
278 return None
279
280 def get_block_dimensions(self):
281 ofm_box = self.ofm_box
282 block_config = self.block_config
283
284 out_height = 1
285 out_width = 1
286 out_depth = ofm_box.end_coord[-1] - ofm_box.start_coord[-1]
287 if len(ofm_box.end_coord) >= 4:
288 out_width = ofm_box.end_coord[-2] - ofm_box.start_coord[-2]
289 out_height = ofm_box.end_coord[-3] - ofm_box.start_coord[-3]
290
291 assert out_height >= 0
292 assert out_width >= 0
293 assert out_depth >= 0
294 return (
295 round_up_divide(out_height, block_config[0]),
296 round_up_divide(out_width, block_config[1]),
297 round_up_divide(out_depth, block_config[3]),
298 )
299
300 def get_operation_count(self):
301 # returns numpy array of (DPU blocks, dma_ops)
302 return np.array((self.get_n_blocks(), 0))
303
304 def get_n_blocks(self):
305 h, w, d = self.get_block_dimensions()
306 res = h * w * d
307 assert res >= 0
308 return res
309
310 def get_single_block_command(self, block_idx):
311 block_cfg = (self.block_config[0], self.block_config[1], self.block_config[3])
312 dims = self.get_block_dimensions()
313 strides = dims[1] * dims[2], dims[2], 1
314 coord = []
315 idx_left = block_idx
316 for s in strides:
317 c = idx_left // s
318 idx_left -= c * s
319 coord.append(c)
320
321 assert idx_left == 0
322
323 # put in dummy height/widths in case we're dealing with FC layers
324 ofm_start = list(self.ofm_box.start_coord)
325 ofm_end = list(self.ofm_box.end_coord)
326
327 # cut out a nice block shape
328 for idx in (-1, -2, -3):
329 if len(ofm_start) >= -idx:
330 ofm_start[idx] += block_cfg[idx] * coord[idx]
331 ofm_end[idx] = min(ofm_end[idx], ofm_start[idx] + block_cfg[idx])
332
333 ps = self.ps
334 strides = None
335 skirt = None
336 if ps.primary_op is not None:
337 strides = ps.primary_op.attrs.get("strides", None)
338 skirt = ps.primary_op.attrs.get("skirt", None)
339 npu_block_type = ps.npu_block_type
340
341 ofm_box = Box(ofm_start, ofm_end)
342 ifm_box, _, _ = ofm_box.transform_with_strides_and_skirt(
343 strides, skirt, self.ifm_tensor.shape, npu_block_type, self.concat_axis, self.concat_offset
344 )
345
346 weight_box = None
347 if self.weight_tensor is not None:
348 weight_oc_start = ofm_start[-1]
349 weight_oc_end = ofm_end[-1]
350 if self.concat_axis - len(self.weight_tensor.shape) == -1:
351 weight_oc_start -= self.concat_offset
352 weight_oc_end -= self.concat_offset
353
354 weight_box = Box.make_weight_box(
355 self.weight_tensor.shape,
356 npu_block_type,
357 weight_oc_start,
358 weight_oc_end,
359 self.weight_tensor.weight_transpose_depthwise,
360 )
361
362 return NpuStripe(
363 self.ps,
364 self.block_config,
365 self.is_first,
366 self.is_last,
367 self.is_first_h_stripe,
368 self.is_last_h_stripe,
369 self.ifm_tensor,
370 ifm_box,
371 self.ofm_tensor,
372 ofm_box,
373 self.weight_tensor,
374 weight_box,
375 self.scale_tensor,
376 self.concat_axis,
377 self.concat_offset,
378 )
379
380
381class DMA(Command):
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200382 def __init__(self, ps, in_tensor, out_tensor, box):
Tim Hall79d07d22020-04-27 18:20:16 +0100383 self.cmdtype = CommandType.DMA
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200384 self.ps = ps
Tim Hall79d07d22020-04-27 18:20:16 +0100385 self.in_tensor = in_tensor
386 self.out_tensor = out_tensor
387 self.box = box
388
389 def __str__(self):
390 return "<DMA: in=%s, out=%s, box=%s>" % (self.in_tensor.name, self.out_tensor.name, self.box)
391
392 __repr__ = __str__
393
394 def get_memory_accesses(self):
395 res = MemoryAccessSet()
396
397 res.add(
398 self.in_tensor.get_address_ranges_for_coordinates(self.box.start_coord, self.box.end_coord),
399 AccessDirection.Read,
400 )
401 res.add(
402 self.out_tensor.get_address_ranges_for_coordinates(self.box.start_coord, self.box.end_coord),
403 AccessDirection.Write,
404 )
405 return res
406
407 def get_operation_count(self):
408 # returns numpy array of (DPU blocks, dma_ops)
409 return np.array((0, 1))