blob: 95af1ccb05583bdc7d6d30144881d9aadc18feb3 [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
24from .range_set import AccessDirection
25from .range_set import MemoryAccessSet
Louis Verhaard0b8268a2020-08-05 16:11:29 +020026from .range_set import MemoryRangeSet
27from .tensor import MemArea
28from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010029
30
31class Box:
32 def __init__(self, start_coord, end_coord):
33 self.start_coord = list(start_coord)
34 self.end_coord = list(end_coord)
35 assert len(self.start_coord) == len(end_coord)
36 for i in range(len(self.start_coord)):
37 assert self.start_coord[i] <= self.end_coord[i]
38
39 def transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +010040 self,
41 strides,
42 skirt,
43 ifm_shape,
44 npu_block_type,
45 concat_axis=0,
46 concat_offset=0,
47 split_offset=None,
48 k_height=1,
49 upscaling_factor=1,
Tim Hall79d07d22020-04-27 18:20:16 +010050 ):
51 new_start_coord = list(self.start_coord)
52 new_end_coord = list(self.end_coord)
53
54 new_start_coord[concat_axis] -= concat_offset
55 new_end_coord[concat_axis] -= concat_offset
56
Diego Russoea6111a2020-04-14 18:41:58 +010057 if split_offset is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010058 for idx in range(len(split_offset)):
59 new_start_coord[idx] += split_offset[idx]
60 new_end_coord[idx] += split_offset[idx]
61
Fredrik Svedberga0c36242020-06-03 15:43:31 +020062 if split_offset is None and npu_block_type in set(
63 (NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct, NpuBlockType.ReduceSum)
64 ):
65 # these types of operations do a "dot product" or sum over the entire IFM
Tim Hall79d07d22020-04-27 18:20:16 +010066 new_start_coord[-1] = 0
67 new_end_coord[-1] = ifm_shape[-1]
68
Louis Verhaarde0ef2732020-06-03 08:56:44 +020069 if npu_block_type == NpuBlockType.ElementWise and min(len(new_end_coord), len(ifm_shape)) >= 1:
70 new_end_coord[-1] = min(new_end_coord[-1], ifm_shape[-1])
Tim Hall79d07d22020-04-27 18:20:16 +010071 if min(len(new_end_coord), len(ifm_shape)) >= 2:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020072 new_end_coord[-2] = min(new_end_coord[-2], ifm_shape[-2] * upscaling_factor)
Tim Hall79d07d22020-04-27 18:20:16 +010073 if min(len(new_end_coord), len(ifm_shape)) >= 3:
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020074 original_end_coord = list(new_end_coord)
75 new_end_coord[-3] = min(new_end_coord[-3], ifm_shape[-3] * upscaling_factor)
Tim Hall79d07d22020-04-27 18:20:16 +010076
77 pad_top = 0
78 pad_bottom = 0
79 if strides is not None and skirt is not None:
80 if len(new_start_coord) >= 2:
81 stride = strides[2]
82 new_start_coord[-2] = max(new_start_coord[-2] * stride - skirt[1], 0)
83 new_end_coord[-2] = min(new_end_coord[-2] * stride + skirt[3], ifm_shape[-2])
84
85 if len(new_start_coord) >= 3:
86 stride = strides[1]
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020087 skirt_top_remainder = skirt[0] % upscaling_factor
Tim Hall79d07d22020-04-27 18:20:16 +010088
89 total_stride = stride * (new_end_coord[-3] - new_start_coord[-3] - 1)
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020090 new_start_coord[-3] = new_start_coord[-3] * stride - skirt[0] + skirt_top_remainder
Tim Hall79d07d22020-04-27 18:20:16 +010091
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020092 pad_top = max(0, 0 - new_start_coord[-3]) + skirt_top_remainder
Tim Hall79d07d22020-04-27 18:20:16 +010093 new_start_coord[-3] = max(new_start_coord[-3], 0)
94
95 while len(ifm_shape) < 3:
96 ifm_shape = [1] + ifm_shape
Jacob Bohlin9b64ba02020-07-07 17:15:22 +020097
98 if (new_end_coord[-3] * stride + skirt[2]) > (ifm_shape[-3] * upscaling_factor):
Tim Hall79d07d22020-04-27 18:20:16 +010099 # pad_bottom is calculated based the diff between the end position of the weight kernel,
100 # after last stride and the ifm height.
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200101 if upscaling_factor != 1 and original_end_coord[-3] > ifm_shape[-3] * upscaling_factor:
102 # Special case for Transpose Convolution with VALID padding.
103 pad_bottom = original_end_coord[-3] - (ifm_shape[-3] * upscaling_factor)
104 else:
105 k_start = new_start_coord[-3] - pad_top
106 pad_bottom = max(0, k_start + total_stride + k_height - (ifm_shape[-3] * upscaling_factor))
Tim Hall79d07d22020-04-27 18:20:16 +0100107
Jacob Bohlin9b64ba02020-07-07 17:15:22 +0200108 # Adjust for upscaling
109 new_start_coord[-3] = max(new_start_coord[-3] // upscaling_factor, 0)
110 new_end_coord[-3] = new_end_coord[-3] * stride + skirt[2] + (skirt[2] % upscaling_factor)
111 new_end_coord[-3] = min(new_end_coord[-3] // upscaling_factor, ifm_shape[-3])
Tim Hall79d07d22020-04-27 18:20:16 +0100112
113 return Box(new_start_coord, new_end_coord), pad_top, pad_bottom
114
115 def make_weight_box(weight_shape, npu_block_type, oc_range_start=None, oc_range_end=None, weights_transposed=False):
116 start = [0] * len(weight_shape)
117 end = list(weight_shape)
118 if oc_range_start is not None and oc_range_end is not None:
119 if npu_block_type == NpuBlockType.ConvolutionDepthWise:
120 # input range is output range divided by channel multiplier
121 if weights_transposed:
122 start[-1] = oc_range_start // weight_shape[-2]
123 end[-1] = oc_range_end // weight_shape[-2]
124 else:
125 start[-2] = oc_range_start // weight_shape[-1]
126 end[-2] = oc_range_end // weight_shape[-1]
127 else:
128 start[-1] = oc_range_start
129 end[-1] = oc_range_end
130 for i in range(len(end)):
131 assert 0 <= start[i] < weight_shape[i]
132 assert 0 < end[i] <= weight_shape[i]
133
134 return Box(start, end)
135
136 def get_size_shape(self):
137 return [int(self.end_coord[i] - self.start_coord[i]) for i in range(len(self.end_coord))]
138
139 def get_size(self):
140 return int(np.prod(self.get_size_shape()))
141
142 def __str__(self):
143 return "<Box %s - %s>" % (self.start_coord, self.end_coord)
144
145 __repr__ = __str__
146
147
148class CommandType(IntEnum):
149 NpuStripe = 0
150 DMA = 1
151 Size = 2
152
153
154class Command:
155 def get_ofm_y_range_for_pass(self, ps_requested):
156 return None
157
158 def is_npu_pass_command(self):
159 return False
160
161 def get_memory_accesses(self):
162 return None
163
164 def get_operation_count(self):
165 # returns numpy array of (DPU blocks, dma_ops). Should line up with the CommandType enum
166 return np.array((0, 0))
167
168
169class NpuStripe(Command):
170 def __init__(
171 self,
172 ps,
173 block_config,
174 is_first,
175 is_last,
176 is_first_h_stripe,
177 is_last_h_stripe,
178 ifm_tensor,
179 ifm_box,
180 ofm_tensor,
181 ofm_box,
182 weight_tensor=None,
183 weight_box=None,
184 scale_tensor=None,
185 concat_axis=0,
186 concat_offset=0,
187 ifm2_tensor=None,
188 ifm2_box=None,
189 pad_top=0,
190 pad_bottom=0,
191 ):
192 self.cmdtype = CommandType.NpuStripe
193 self.ps = ps
194 self.block_config = block_config
195 self.is_first = is_first
196 self.is_last = is_last
197 self.is_first_h_stripe = is_first_h_stripe
198 self.is_last_h_stripe = is_last_h_stripe
199 self.ifm_tensor = ifm_tensor
200 self.ifm_box = ifm_box
201 self.ifm2_tensor = ifm2_tensor
202 self.ifm2_box = ifm2_box
203 self.ofm_tensor = ofm_tensor
204 self.ofm_box = ofm_box
205 self.weight_tensor = weight_tensor
206 self.scale_tensor = scale_tensor
207 self.weight_box = weight_box
208 self.concat_axis = concat_axis
209 self.concat_offset = concat_offset
210 self.pad_top = pad_top
211 self.pad_bottom = pad_bottom
212 for i in range(len(self.ofm_box.end_coord)):
213 assert self.ofm_box.end_coord[i] <= self.ofm_tensor.shape[i]
214
215 def get_memory_accesses(self):
216 res = MemoryAccessSet()
217 if self.ifm_tensor is not None and self.ifm_tensor.shape != []:
218 res.add(
219 self.ifm_tensor.get_address_ranges_for_coordinates(self.ifm_box.start_coord, self.ifm_box.end_coord),
220 AccessDirection.Read,
221 )
222 if self.ifm2_tensor is not None and self.ifm2_tensor.shape != []:
223 res.add(
224 self.ifm2_tensor.get_address_ranges_for_coordinates(self.ifm2_box.start_coord, self.ifm2_box.end_coord),
225 AccessDirection.Read,
226 )
227 if self.ofm_tensor is not None:
228 res.add(
229 self.ofm_tensor.get_address_ranges_for_coordinates(self.ofm_box.start_coord, self.ofm_box.end_coord),
230 AccessDirection.Write,
231 )
232 if self.weight_tensor is not None:
233 res.add(
234 self.weight_tensor.get_address_ranges_for_coordinates(
235 self.weight_box.start_coord, self.weight_box.end_coord
236 ),
237 AccessDirection.Read,
238 )
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200239 # Add read access to SHRAM by any LUT-s
240 for tens in self.ps.intermediates:
241 if tens.purpose == TensorPurpose.LUT and tens.mem_area == MemArea.Shram:
242 res.add(
243 MemoryRangeSet(tens.mem_area, tens.address, tens.address + tens.storage_size()),
244 AccessDirection.Read,
245 )
Tim Hall79d07d22020-04-27 18:20:16 +0100246 return res
247
248 def is_npu_pass_command(self):
249 return True
250
251 def __str__(self):
252 return "<NPUStripe: ps=%s, ifm_box=%s, ifm2_box=%s, ofm_box=%s, weight_box=%s, block_config=%s>" % (
253 self.ps.name,
254 self.ifm_box,
255 self.ifm2_box,
256 self.ofm_box,
257 self.weight_box,
258 self.block_config,
259 )
260
261 __repr__ = __str__
262
263 def get_ofm_y_range_for_pass(self, ps_requested):
264 if ps_requested != self.ps:
265 return None
266 if len(self.ofm_box.start_coord) >= 3:
267 return (self.ofm_box.start_coord[-3], self.ofm_box.end_coord[-3])
268 return None
269
270 def get_block_dimensions(self):
271 ofm_box = self.ofm_box
272 block_config = self.block_config
273
274 out_height = 1
275 out_width = 1
276 out_depth = ofm_box.end_coord[-1] - ofm_box.start_coord[-1]
277 if len(ofm_box.end_coord) >= 4:
278 out_width = ofm_box.end_coord[-2] - ofm_box.start_coord[-2]
279 out_height = ofm_box.end_coord[-3] - ofm_box.start_coord[-3]
280
281 assert out_height >= 0
282 assert out_width >= 0
283 assert out_depth >= 0
284 return (
285 round_up_divide(out_height, block_config[0]),
286 round_up_divide(out_width, block_config[1]),
287 round_up_divide(out_depth, block_config[3]),
288 )
289
290 def get_operation_count(self):
291 # returns numpy array of (DPU blocks, dma_ops)
292 return np.array((self.get_n_blocks(), 0))
293
294 def get_n_blocks(self):
295 h, w, d = self.get_block_dimensions()
296 res = h * w * d
297 assert res >= 0
298 return res
299
300 def get_single_block_command(self, block_idx):
301 block_cfg = (self.block_config[0], self.block_config[1], self.block_config[3])
302 dims = self.get_block_dimensions()
303 strides = dims[1] * dims[2], dims[2], 1
304 coord = []
305 idx_left = block_idx
306 for s in strides:
307 c = idx_left // s
308 idx_left -= c * s
309 coord.append(c)
310
311 assert idx_left == 0
312
313 # put in dummy height/widths in case we're dealing with FC layers
314 ofm_start = list(self.ofm_box.start_coord)
315 ofm_end = list(self.ofm_box.end_coord)
316
317 # cut out a nice block shape
318 for idx in (-1, -2, -3):
319 if len(ofm_start) >= -idx:
320 ofm_start[idx] += block_cfg[idx] * coord[idx]
321 ofm_end[idx] = min(ofm_end[idx], ofm_start[idx] + block_cfg[idx])
322
323 ps = self.ps
324 strides = None
325 skirt = None
326 if ps.primary_op is not None:
327 strides = ps.primary_op.attrs.get("strides", None)
328 skirt = ps.primary_op.attrs.get("skirt", None)
329 npu_block_type = ps.npu_block_type
330
331 ofm_box = Box(ofm_start, ofm_end)
332 ifm_box, _, _ = ofm_box.transform_with_strides_and_skirt(
333 strides, skirt, self.ifm_tensor.shape, npu_block_type, self.concat_axis, self.concat_offset
334 )
335
336 weight_box = None
337 if self.weight_tensor is not None:
338 weight_oc_start = ofm_start[-1]
339 weight_oc_end = ofm_end[-1]
340 if self.concat_axis - len(self.weight_tensor.shape) == -1:
341 weight_oc_start -= self.concat_offset
342 weight_oc_end -= self.concat_offset
343
344 weight_box = Box.make_weight_box(
345 self.weight_tensor.shape,
346 npu_block_type,
347 weight_oc_start,
348 weight_oc_end,
349 self.weight_tensor.weight_transpose_depthwise,
350 )
351
352 return NpuStripe(
353 self.ps,
354 self.block_config,
355 self.is_first,
356 self.is_last,
357 self.is_first_h_stripe,
358 self.is_last_h_stripe,
359 self.ifm_tensor,
360 ifm_box,
361 self.ofm_tensor,
362 ofm_box,
363 self.weight_tensor,
364 weight_box,
365 self.scale_tensor,
366 self.concat_axis,
367 self.concat_offset,
368 )
369
370
371class DMA(Command):
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200372 def __init__(self, ps, in_tensor, out_tensor, box):
Tim Hall79d07d22020-04-27 18:20:16 +0100373 self.cmdtype = CommandType.DMA
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200374 self.ps = ps
Tim Hall79d07d22020-04-27 18:20:16 +0100375 self.in_tensor = in_tensor
376 self.out_tensor = out_tensor
377 self.box = box
378
379 def __str__(self):
380 return "<DMA: in=%s, out=%s, box=%s>" % (self.in_tensor.name, self.out_tensor.name, self.box)
381
382 __repr__ = __str__
383
384 def get_memory_accesses(self):
385 res = MemoryAccessSet()
386
387 res.add(
388 self.in_tensor.get_address_ranges_for_coordinates(self.box.start_coord, self.box.end_coord),
389 AccessDirection.Read,
390 )
391 res.add(
392 self.out_tensor.get_address_ranges_for_coordinates(self.box.start_coord, self.box.end_coord),
393 AccessDirection.Write,
394 )
395 return res
396
397 def get_operation_count(self):
398 # returns numpy array of (DPU blocks, dma_ops)
399 return np.array((0, 1))