blob: d5a6341b8e6b13e4fd141bfdb097fce4b350f8f9 [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# Generate a high-level command stream from a scheduled subgraph with CascadedPasses.
18#
19# Also used during scheduling to work out allowable IFM/OFM overlap, this functionality can be accessed using
20# calc_allowed_ofm_ifm_overlap_for_cascaded_pass().
Diego Russoe8a10452020-04-21 17:39:10 +010021from .high_level_command_stream import Box
22from .high_level_command_stream import DMA
23from .high_level_command_stream import NpuStripe
24from .nn_graph import PassPlacement
25from .nn_graph import SchedulingStrategy
Charles Xu89a6bbf2020-08-11 12:31:58 +020026from .numeric_util import round_up_divide
Tim Hall79d07d22020-04-27 18:20:16 +010027from .operation import NpuBlockType
Charles Xu78792222020-05-13 10:15:26 +020028from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010029
30
Charles Xu78792222020-05-13 10:15:26 +020031def dma_if_necessary(ps, box, tensor):
Louis Verhaard3c07c972020-05-07 08:12:58 +020032 if tensor.needs_dma():
Charles Xu78792222020-05-13 10:15:26 +020033 dma_op = tensor.ops[0]
Tim Hall79d07d22020-04-27 18:20:16 +010034 in_tensor = dma_op.inputs[0]
Louis Verhaard0b8268a2020-08-05 16:11:29 +020035 yield DMA(ps, in_tensor, tensor, box)
Tim Hall79d07d22020-04-27 18:20:16 +010036
Tim Hallc30f4952020-06-15 20:47:35 +010037
Charles Xu600351a2020-05-18 08:54:47 +020038def match_tensor(source, derived):
39 if source == derived:
40 return True
41 ops = derived.ops
Tim Hallc30f4952020-06-15 20:47:35 +010042 return ops != [] and len(ops) == 1 and ops[0].type == "SplitSliceRead" and source == ops[0].inputs[0]
43
Tim Hall79d07d22020-04-27 18:20:16 +010044
45def generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx):
46 is_first = idx == 0
47 is_last = idx == len(passes) - 1
48 ps = passes[idx]
49 block_config = block_configs[idx]
Charles Xu600351a2020-05-18 08:54:47 +020050 npu_block_type = ps.npu_block_type
51 split_offsets = [None, None] # offset for [ifm, ifm2]
52
53 ifm_idx = 0
54 for op in ps.ops:
55 if op.type == "SplitSliceRead":
56 split_offsets[ifm_idx] = op.attrs["split_start"]
57 ps.primary_op.attrs["fused_memory_function"] = op.type
58 ifm_idx += 1
59
60 if len(ps.inputs) == 2 and npu_block_type == NpuBlockType.ElementWise:
61 # Ensure correct imf and ifm2 order
Tim Hallc30f4952020-06-15 20:47:35 +010062 if match_tensor(ps.inputs[0], ps.primary_op.inputs[1]) and match_tensor(ps.inputs[1], ps.primary_op.inputs[0]):
Charles Xu600351a2020-05-18 08:54:47 +020063 ps.ifm_tensor, ps.ifm2_tensor = ps.ifm2_tensor, ps.ifm_tensor
64 split_offsets[0], split_offsets[1] = split_offsets[1], split_offsets[0]
Tim Hall79d07d22020-04-27 18:20:16 +010065
66 ifm_tensor = ps.ifm_tensor
67 ifm2_tensor = ps.ifm2_tensor
68 ofm_tensor = ps.ofm_tensor
69 weight_tensor = ps.weight_tensor
70 scale_tensor = ps.scale_tensor
71
72 ofm_start = [0] * len(ofm_tensor.shape)
73 ofm_end = list(ofm_tensor.shape)
74
75 strides = None
76 skirt = None
Jacob Bohlin611fcdf2020-06-11 15:09:57 +020077 upscaling = 1
Tim Hall79d07d22020-04-27 18:20:16 +010078 if ps.primary_op is not None:
79 strides = ps.primary_op.attrs.get("strides", None)
80 skirt = ps.primary_op.attrs.get("skirt", None)
Charles Xu89a6bbf2020-08-11 12:31:58 +020081 if ps.primary_op.type == "Conv2DBackpropInputSwitchedBias":
Jacob Bohlin611fcdf2020-06-11 15:09:57 +020082 upscaling = ofm_tensor.shape[-3] // ifm_tensor.shape[-3]
Charles Xu89a6bbf2020-08-11 12:31:58 +020083 elif ps.primary_op.type == "ResizeBilinear":
84 upscaling = round_up_divide(ofm_tensor.shape[-3], ifm_tensor.shape[-3])
Tim Hall79d07d22020-04-27 18:20:16 +010085
Tim Hall79d07d22020-04-27 18:20:16 +010086 concat_axis = 0
87 concat_offset = 0
88
Tim Hall79d07d22020-04-27 18:20:16 +010089 # Fusable activation functions
90 activation_ops = set(("Sigmoid", "Tanh", "Relu", "Relu6", "ReluN1To1"))
91
92 for op in ps.ops:
93 if op.type == "ConcatSliceWrite":
94 concat_axis = op.attrs["concat_axis"]
95 concat_start = op.attrs["concat_start"]
96 concat_end = op.attrs["concat_end"]
97
98 ofm_start[concat_axis] = concat_start
99 ofm_end[concat_axis] = concat_end
100 concat_offset = concat_start
101 ps.primary_op.attrs["fused_memory_function"] = op.type
102 elif op.type in activation_ops:
103 ps.primary_op.attrs["fused_activation_function"] = op.type
104
Tim Hall79d07d22020-04-27 18:20:16 +0100105 if strat == SchedulingStrategy.WeightStream:
106 ofm_step = block_config[-1]
107 ofm_stop = ofm_end[-1]
Louis Verhaard3c07c972020-05-07 08:12:58 +0200108 if weight_tensor is None or not weight_tensor.needs_dma():
Tim Hall79d07d22020-04-27 18:20:16 +0100109 ofm_step = ofm_stop
110 for start in range(ofm_start[-1], ofm_stop, ofm_step):
111 end = min(start + ofm_step, ofm_stop)
112 ofm_start[-1] = start
113 ofm_end[-1] = end
114 ofm_box = Box(ofm_start, ofm_end)
115 ifm_box = None
116 ifm2_box = None
117
118 if ifm_tensor.shape != []:
119 ifm_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100120 strides,
121 skirt,
122 ifm_tensor.shape,
123 npu_block_type,
124 concat_axis,
125 concat_offset,
126 split_offsets[0],
127 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100128 )
129 else:
130 ifm_box = Box([], [])
131 if ifm2_tensor is not None and ifm2_tensor.shape != []:
132 ifm2_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100133 strides,
134 skirt,
135 ifm2_tensor.shape,
136 npu_block_type,
137 concat_axis,
138 concat_offset,
139 split_offsets[1],
140 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100141 )
142 else:
143 ifm2_box = Box([], [])
144
Charles Xu78792222020-05-13 10:15:26 +0200145 for intermediate in ps.intermediates:
Tim Hallc30f4952020-06-15 20:47:35 +0100146 if (
147 intermediate is not None
148 and intermediate.shape != []
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200149 and intermediate.purpose in (TensorPurpose.FeatureMap, TensorPurpose.LUT)
Tim Hallc30f4952020-06-15 20:47:35 +0100150 ):
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200151 if intermediate.purpose is TensorPurpose.FeatureMap:
152 intermediate_box, _, _ = ofm_box.transform_with_strides_and_skirt(
153 strides,
154 skirt,
155 intermediate.shape,
156 npu_block_type,
157 concat_axis,
158 concat_offset,
159 split_offsets[0],
160 upscaling,
161 )
162 else:
163 intermediate_box = Box([0] * len(intermediate.shape), list(intermediate.shape))
Charles Xu78792222020-05-13 10:15:26 +0200164 yield from dma_if_necessary(ps, intermediate_box, intermediate)
165
Tim Hall79d07d22020-04-27 18:20:16 +0100166 weight_box = None
167 if weight_tensor is not None:
168 weight_oc_start = start
169 weight_oc_end = end
170 if concat_axis - len(weight_tensor.shape) == -1:
171 weight_oc_start -= concat_offset
172 weight_oc_end -= concat_offset
173
174 weight_box = Box.make_weight_box(
175 weight_tensor.shape,
176 npu_block_type,
177 weight_oc_start,
178 weight_oc_end,
179 weight_tensor.weight_transpose_depthwise,
180 )
Charles Xu78792222020-05-13 10:15:26 +0200181 yield from dma_if_necessary(ps, weight_box, weight_tensor)
Tim Hall79d07d22020-04-27 18:20:16 +0100182
183 yield NpuStripe(
184 ps,
185 block_config,
186 is_first,
187 is_last,
188 True,
189 True,
190 ifm_tensor,
191 ifm_box,
192 ofm_tensor,
193 ofm_box,
194 weight_tensor,
195 weight_box,
196 scale_tensor,
197 concat_axis,
198 concat_offset,
199 ifm2_tensor=ifm2_tensor,
200 ifm2_box=ifm2_box,
201 )
202
203 elif strat == SchedulingStrategy.IfmStream:
204 y_step = block_config[0]
205 y_start = 0
206 y_dim = 1
207 if len(ofm_tensor.shape) >= 3:
208 y_start = ofm_start[-3]
209 y_dim = ofm_end[-3]
210 if idx > 0:
211 ifm_y_present = 0
212 prev_pass = passes[idx - 1]
213 prev_pass_gen = generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx - 1)
214 else:
215 ifm_y_present = 1
216 if len(ifm_tensor.shape) >= 3:
217 ifm_y_present = ifm_tensor.shape[-3]
218 prev_pass_gen = []
219 prev_pass = None
220
221 if len(passes) == 1:
222 # no cascading, can just issue one big stripe
223 # but only if we've done allocation and OFM does not overlap IFM
Charles Xu04ce34c2020-06-23 12:42:28 +0200224 if ifm_tensor.address is not None and ofm_tensor.address is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100225 if (
226 ifm_tensor.address + ifm_tensor.storage_size() <= ofm_tensor.address
227 or ofm_tensor.address + ofm_tensor.storage_size() <= ifm_tensor.address
228 ):
229 y_step = y_dim
230
231 weight_box = None
232
233 for start in range(y_start, y_dim, y_step):
234 end = min(start + y_step, y_dim)
235 if len(ofm_tensor.shape) >= 3:
236 ofm_start[-3] = start
237 ofm_end[-3] = end
238 ofm_box = Box(ofm_start, ofm_end)
239
240 k_height = 1
Charles Xu89a6bbf2020-08-11 12:31:58 +0200241 if npu_block_type in (NpuBlockType.Pooling, NpuBlockType.ReduceSum):
Tim Hall79d07d22020-04-27 18:20:16 +0100242 if ps.primary_op is not None:
243 k_height = ps.primary_op.attrs["ksize"][1]
244 else:
245 if weight_tensor is not None:
246 k_height = weight_tensor.shape[0]
247
248 ifm_box, pad_top, pad_bottom = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100249 strides,
250 skirt,
251 ifm_tensor.shape,
252 npu_block_type,
253 concat_axis,
254 concat_offset,
255 split_offsets[0],
256 k_height,
257 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100258 )
259
Charles Xu78792222020-05-13 10:15:26 +0200260 for intermediate in ps.intermediates:
Tim Hallc30f4952020-06-15 20:47:35 +0100261 if (
262 intermediate is not None
263 and intermediate.shape != []
264 and intermediate.purpose == TensorPurpose.FeatureMap
265 ):
Charles Xu78792222020-05-13 10:15:26 +0200266 intermediate_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100267 strides,
268 skirt,
269 intermediate.shape,
270 npu_block_type,
271 concat_axis,
272 concat_offset,
273 split_offsets[0],
274 upscaling,
Charles Xu78792222020-05-13 10:15:26 +0200275 )
276 yield from dma_if_necessary(ps, intermediate_box, intermediate)
277
Tim Hall79d07d22020-04-27 18:20:16 +0100278 ifm_y_needed = 1
279 if len(ifm_box.end_coord) >= 3:
280 ifm_y_needed = ifm_box.end_coord[-3]
281 if ifm_y_present < ifm_y_needed:
282 for prev_cmd in prev_pass_gen:
283 yield prev_cmd
284 rng = prev_cmd.get_ofm_y_range_for_pass(prev_pass)
285 if rng is not None:
286 ifm_y_present = max(ifm_y_present, rng[1])
287 if ifm_y_present >= ifm_y_needed:
288 break
289
290 if weight_tensor is not None and weight_box is None:
291 weight_box = Box.make_weight_box(
292 weight_tensor.shape, npu_block_type, weights_transposed=weight_tensor.weight_transpose_depthwise
293 )
Charles Xu78792222020-05-13 10:15:26 +0200294 yield from dma_if_necessary(ps, weight_box, weight_tensor)
Tim Hall79d07d22020-04-27 18:20:16 +0100295
296 # Check if first/last stripe in pass
297 is_first_h_stripe = start == y_start
298 is_last_h_stripe = (start + y_step) >= y_dim
299
300 stripe = NpuStripe(
301 ps,
302 block_config,
303 is_first,
304 is_last,
305 is_first_h_stripe,
306 is_last_h_stripe,
307 ifm_tensor,
308 ifm_box,
309 ofm_tensor,
310 ofm_box,
311 weight_tensor,
312 weight_box,
313 scale_tensor,
314 concat_axis,
315 concat_offset,
316 None,
317 None,
318 pad_top,
319 pad_bottom,
320 )
321 yield stripe
322 else:
323 assert 0, "unknown scheduling strategy"
324
325
326def generate_high_level_command_stream_for_pass_list(strat, passes, block_configs):
327 if strat == SchedulingStrategy.WeightStream:
328 for idx in range(len(passes)):
329 yield from generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx)
330 elif strat == SchedulingStrategy.IfmStream:
331 yield from generate_high_level_command_stream_for_pass(strat, passes, block_configs, len(passes) - 1)
332 else:
333 assert 0, "Unknown streaming strategy"
334
335
336def generate_high_level_command_stream_for_cascaded_pass(cps):
337 yield from generate_high_level_command_stream_for_pass_list(
338 cps.strategy, cps.passes, [ps.block_config for ps in cps.passes]
339 )
340
341
342def generate_high_level_command_stream(nng, sg, arch, verbose_high_level_command_stream):
343 res = []
344 for cps in sg.cascaded_passes:
345 if cps.placement == PassPlacement.Npu:
346 res += list(generate_high_level_command_stream_for_cascaded_pass(cps))
347
348 sg.high_level_command_stream = res
349 if verbose_high_level_command_stream:
350 sg.print_high_level_command_stream()
351
352
353def calc_allowed_ofm_ifm_overlap_for_pass_list(strat, passes, block_configs):
354 highest_ofm_write = 0
355 if not passes[0].ifm_tensor or not passes[-1].ofm_tensor:
356 return 0
357
358 ifm_read = passes[0].ifm_tensor.storage_size
359 min_overlap = 999999999999999999999
360 ofm_size = passes[-1].ofm_tensor.storage_size()
361 if strat == SchedulingStrategy.WeightStream:
362 return 0
363 for cmd in generate_high_level_command_stream_for_pass_list(strat, passes, block_configs):
364 if cmd.is_npu_pass_command():
365 if cmd.is_first:
366 ifm_read = cmd.ifm_tensor.address_offset_for_coordinate(cmd.ifm_box.start_coord, is_top_box=False)
367 if ifm_read is None:
368 return 0
369 if cmd.is_last:
370 write_offset = cmd.ofm_tensor.address_offset_for_coordinate(cmd.ofm_box.end_coord, is_top_box=True)
371 if write_offset is None:
372 return 0
373 highest_ofm_write = max(write_offset, highest_ofm_write)
374
375 if cmd.is_first or cmd.is_last:
376 overlap_required = max(highest_ofm_write - min(ifm_read, ofm_size), 0)
377 can_overwrite = ofm_size - overlap_required
378 min_overlap = min(min_overlap, can_overwrite)
379
380 if cmd.is_first:
381 ifm_read = cmd.ifm_tensor.address_offset_for_coordinate(cmd.ifm_box.end_coord, is_top_box=True)
382
383 min_overlap = max(min_overlap, 0)
384 return min_overlap
385
386
387def calc_allowed_ofm_ifm_overlap_for_cascaded_pass(cps):
388 return calc_allowed_ofm_ifm_overlap_for_pass_list(cps.strategy, cps.passes, [ps.block_config for ps in cps.passes])