blob: 6aa88d86f90c5df720e831159dd8725e0612ebd8 [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
Tim Hall79d07d22020-04-27 18:20:16 +010026from .operation import NpuBlockType
Charles Xu78792222020-05-13 10:15:26 +020027from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010028
29
Charles Xu78792222020-05-13 10:15:26 +020030def dma_if_necessary(ps, box, tensor):
Louis Verhaard3c07c972020-05-07 08:12:58 +020031 if tensor.needs_dma():
Charles Xu78792222020-05-13 10:15:26 +020032 dma_op = tensor.ops[0]
Tim Hall79d07d22020-04-27 18:20:16 +010033 in_tensor = dma_op.inputs[0]
Charles Xu78792222020-05-13 10:15:26 +020034 yield DMA(in_tensor, tensor, box)
Tim Hall79d07d22020-04-27 18:20:16 +010035
Tim Hallc30f4952020-06-15 20:47:35 +010036
Charles Xu600351a2020-05-18 08:54:47 +020037def match_tensor(source, derived):
38 if source == derived:
39 return True
40 ops = derived.ops
Tim Hallc30f4952020-06-15 20:47:35 +010041 return ops != [] and len(ops) == 1 and ops[0].type == "SplitSliceRead" and source == ops[0].inputs[0]
42
Tim Hall79d07d22020-04-27 18:20:16 +010043
44def generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx):
45 is_first = idx == 0
46 is_last = idx == len(passes) - 1
47 ps = passes[idx]
48 block_config = block_configs[idx]
Charles Xu600351a2020-05-18 08:54:47 +020049 npu_block_type = ps.npu_block_type
50 split_offsets = [None, None] # offset for [ifm, ifm2]
51
52 ifm_idx = 0
53 for op in ps.ops:
54 if op.type == "SplitSliceRead":
55 split_offsets[ifm_idx] = op.attrs["split_start"]
56 ps.primary_op.attrs["fused_memory_function"] = op.type
57 ifm_idx += 1
58
59 if len(ps.inputs) == 2 and npu_block_type == NpuBlockType.ElementWise:
60 # Ensure correct imf and ifm2 order
Tim Hallc30f4952020-06-15 20:47:35 +010061 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 +020062 ps.ifm_tensor, ps.ifm2_tensor = ps.ifm2_tensor, ps.ifm_tensor
63 split_offsets[0], split_offsets[1] = split_offsets[1], split_offsets[0]
Tim Hall79d07d22020-04-27 18:20:16 +010064
65 ifm_tensor = ps.ifm_tensor
66 ifm2_tensor = ps.ifm2_tensor
67 ofm_tensor = ps.ofm_tensor
68 weight_tensor = ps.weight_tensor
69 scale_tensor = ps.scale_tensor
70
71 ofm_start = [0] * len(ofm_tensor.shape)
72 ofm_end = list(ofm_tensor.shape)
73
74 strides = None
75 skirt = None
Jacob Bohlin611fcdf2020-06-11 15:09:57 +020076 upscaling = 1
Tim Hall79d07d22020-04-27 18:20:16 +010077 if ps.primary_op is not None:
78 strides = ps.primary_op.attrs.get("strides", None)
79 skirt = ps.primary_op.attrs.get("skirt", None)
Jacob Bohlin611fcdf2020-06-11 15:09:57 +020080 if ps.primary_op.type in set(("Conv2DBackpropInputSwitchedBias", "ResizeBilinear")):
81 upscaling = ofm_tensor.shape[-3] // ifm_tensor.shape[-3]
Tim Hall79d07d22020-04-27 18:20:16 +010082
Tim Hall79d07d22020-04-27 18:20:16 +010083 concat_axis = 0
84 concat_offset = 0
85
Tim Hall79d07d22020-04-27 18:20:16 +010086 # Fusable activation functions
87 activation_ops = set(("Sigmoid", "Tanh", "Relu", "Relu6", "ReluN1To1"))
88
89 for op in ps.ops:
90 if op.type == "ConcatSliceWrite":
91 concat_axis = op.attrs["concat_axis"]
92 concat_start = op.attrs["concat_start"]
93 concat_end = op.attrs["concat_end"]
94
95 ofm_start[concat_axis] = concat_start
96 ofm_end[concat_axis] = concat_end
97 concat_offset = concat_start
98 ps.primary_op.attrs["fused_memory_function"] = op.type
99 elif op.type in activation_ops:
100 ps.primary_op.attrs["fused_activation_function"] = op.type
101
Tim Hall79d07d22020-04-27 18:20:16 +0100102 if strat == SchedulingStrategy.WeightStream:
103 ofm_step = block_config[-1]
104 ofm_stop = ofm_end[-1]
Louis Verhaard3c07c972020-05-07 08:12:58 +0200105 if weight_tensor is None or not weight_tensor.needs_dma():
Tim Hall79d07d22020-04-27 18:20:16 +0100106 ofm_step = ofm_stop
107 for start in range(ofm_start[-1], ofm_stop, ofm_step):
108 end = min(start + ofm_step, ofm_stop)
109 ofm_start[-1] = start
110 ofm_end[-1] = end
111 ofm_box = Box(ofm_start, ofm_end)
112 ifm_box = None
113 ifm2_box = None
114
115 if ifm_tensor.shape != []:
116 ifm_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100117 strides,
118 skirt,
119 ifm_tensor.shape,
120 npu_block_type,
121 concat_axis,
122 concat_offset,
123 split_offsets[0],
124 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100125 )
126 else:
127 ifm_box = Box([], [])
128 if ifm2_tensor is not None and ifm2_tensor.shape != []:
129 ifm2_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100130 strides,
131 skirt,
132 ifm2_tensor.shape,
133 npu_block_type,
134 concat_axis,
135 concat_offset,
136 split_offsets[1],
137 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100138 )
139 else:
140 ifm2_box = Box([], [])
141
Charles Xu78792222020-05-13 10:15:26 +0200142 for intermediate in ps.intermediates:
Tim Hallc30f4952020-06-15 20:47:35 +0100143 if (
144 intermediate is not None
145 and intermediate.shape != []
146 and intermediate.purpose == TensorPurpose.FeatureMap
147 ):
Charles Xu78792222020-05-13 10:15:26 +0200148 intermediate_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100149 strides,
150 skirt,
151 intermediate.shape,
152 npu_block_type,
153 concat_axis,
154 concat_offset,
155 split_offsets[0],
156 upscaling,
Charles Xu78792222020-05-13 10:15:26 +0200157 )
158 yield from dma_if_necessary(ps, intermediate_box, intermediate)
159
Tim Hall79d07d22020-04-27 18:20:16 +0100160 weight_box = None
161 if weight_tensor is not None:
162 weight_oc_start = start
163 weight_oc_end = end
164 if concat_axis - len(weight_tensor.shape) == -1:
165 weight_oc_start -= concat_offset
166 weight_oc_end -= concat_offset
167
168 weight_box = Box.make_weight_box(
169 weight_tensor.shape,
170 npu_block_type,
171 weight_oc_start,
172 weight_oc_end,
173 weight_tensor.weight_transpose_depthwise,
174 )
Charles Xu78792222020-05-13 10:15:26 +0200175 yield from dma_if_necessary(ps, weight_box, weight_tensor)
Tim Hall79d07d22020-04-27 18:20:16 +0100176
177 yield NpuStripe(
178 ps,
179 block_config,
180 is_first,
181 is_last,
182 True,
183 True,
184 ifm_tensor,
185 ifm_box,
186 ofm_tensor,
187 ofm_box,
188 weight_tensor,
189 weight_box,
190 scale_tensor,
191 concat_axis,
192 concat_offset,
193 ifm2_tensor=ifm2_tensor,
194 ifm2_box=ifm2_box,
195 )
196
197 elif strat == SchedulingStrategy.IfmStream:
198 y_step = block_config[0]
199 y_start = 0
200 y_dim = 1
201 if len(ofm_tensor.shape) >= 3:
202 y_start = ofm_start[-3]
203 y_dim = ofm_end[-3]
204 if idx > 0:
205 ifm_y_present = 0
206 prev_pass = passes[idx - 1]
207 prev_pass_gen = generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx - 1)
208 else:
209 ifm_y_present = 1
210 if len(ifm_tensor.shape) >= 3:
211 ifm_y_present = ifm_tensor.shape[-3]
212 prev_pass_gen = []
213 prev_pass = None
214
215 if len(passes) == 1:
216 # no cascading, can just issue one big stripe
217 # but only if we've done allocation and OFM does not overlap IFM
Charles Xu04ce34c2020-06-23 12:42:28 +0200218 if ifm_tensor.address is not None and ofm_tensor.address is not None:
Tim Hall79d07d22020-04-27 18:20:16 +0100219 if (
220 ifm_tensor.address + ifm_tensor.storage_size() <= ofm_tensor.address
221 or ofm_tensor.address + ofm_tensor.storage_size() <= ifm_tensor.address
222 ):
223 y_step = y_dim
224
225 weight_box = None
226
227 for start in range(y_start, y_dim, y_step):
228 end = min(start + y_step, y_dim)
229 if len(ofm_tensor.shape) >= 3:
230 ofm_start[-3] = start
231 ofm_end[-3] = end
232 ofm_box = Box(ofm_start, ofm_end)
233
234 k_height = 1
235 if npu_block_type == NpuBlockType.Pooling:
236 if ps.primary_op is not None:
237 k_height = ps.primary_op.attrs["ksize"][1]
238 else:
239 if weight_tensor is not None:
240 k_height = weight_tensor.shape[0]
241
242 ifm_box, pad_top, pad_bottom = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100243 strides,
244 skirt,
245 ifm_tensor.shape,
246 npu_block_type,
247 concat_axis,
248 concat_offset,
249 split_offsets[0],
250 k_height,
251 upscaling,
Tim Hall79d07d22020-04-27 18:20:16 +0100252 )
253
Charles Xu78792222020-05-13 10:15:26 +0200254 for intermediate in ps.intermediates:
Tim Hallc30f4952020-06-15 20:47:35 +0100255 if (
256 intermediate is not None
257 and intermediate.shape != []
258 and intermediate.purpose == TensorPurpose.FeatureMap
259 ):
Charles Xu78792222020-05-13 10:15:26 +0200260 intermediate_box, _, _ = ofm_box.transform_with_strides_and_skirt(
Tim Hallc30f4952020-06-15 20:47:35 +0100261 strides,
262 skirt,
263 intermediate.shape,
264 npu_block_type,
265 concat_axis,
266 concat_offset,
267 split_offsets[0],
268 upscaling,
Charles Xu78792222020-05-13 10:15:26 +0200269 )
270 yield from dma_if_necessary(ps, intermediate_box, intermediate)
271
Tim Hall79d07d22020-04-27 18:20:16 +0100272 ifm_y_needed = 1
273 if len(ifm_box.end_coord) >= 3:
274 ifm_y_needed = ifm_box.end_coord[-3]
275 if ifm_y_present < ifm_y_needed:
276 for prev_cmd in prev_pass_gen:
277 yield prev_cmd
278 rng = prev_cmd.get_ofm_y_range_for_pass(prev_pass)
279 if rng is not None:
280 ifm_y_present = max(ifm_y_present, rng[1])
281 if ifm_y_present >= ifm_y_needed:
282 break
283
284 if weight_tensor is not None and weight_box is None:
285 weight_box = Box.make_weight_box(
286 weight_tensor.shape, npu_block_type, weights_transposed=weight_tensor.weight_transpose_depthwise
287 )
Charles Xu78792222020-05-13 10:15:26 +0200288 yield from dma_if_necessary(ps, weight_box, weight_tensor)
Tim Hall79d07d22020-04-27 18:20:16 +0100289
290 # Check if first/last stripe in pass
291 is_first_h_stripe = start == y_start
292 is_last_h_stripe = (start + y_step) >= y_dim
293
294 stripe = NpuStripe(
295 ps,
296 block_config,
297 is_first,
298 is_last,
299 is_first_h_stripe,
300 is_last_h_stripe,
301 ifm_tensor,
302 ifm_box,
303 ofm_tensor,
304 ofm_box,
305 weight_tensor,
306 weight_box,
307 scale_tensor,
308 concat_axis,
309 concat_offset,
310 None,
311 None,
312 pad_top,
313 pad_bottom,
314 )
315 yield stripe
316 else:
317 assert 0, "unknown scheduling strategy"
318
319
320def generate_high_level_command_stream_for_pass_list(strat, passes, block_configs):
321 if strat == SchedulingStrategy.WeightStream:
322 for idx in range(len(passes)):
323 yield from generate_high_level_command_stream_for_pass(strat, passes, block_configs, idx)
324 elif strat == SchedulingStrategy.IfmStream:
325 yield from generate_high_level_command_stream_for_pass(strat, passes, block_configs, len(passes) - 1)
326 else:
327 assert 0, "Unknown streaming strategy"
328
329
330def generate_high_level_command_stream_for_cascaded_pass(cps):
331 yield from generate_high_level_command_stream_for_pass_list(
332 cps.strategy, cps.passes, [ps.block_config for ps in cps.passes]
333 )
334
335
336def generate_high_level_command_stream(nng, sg, arch, verbose_high_level_command_stream):
337 res = []
338 for cps in sg.cascaded_passes:
339 if cps.placement == PassPlacement.Npu:
340 res += list(generate_high_level_command_stream_for_cascaded_pass(cps))
341
342 sg.high_level_command_stream = res
343 if verbose_high_level_command_stream:
344 sg.print_high_level_command_stream()
345
346
347def calc_allowed_ofm_ifm_overlap_for_pass_list(strat, passes, block_configs):
348 highest_ofm_write = 0
349 if not passes[0].ifm_tensor or not passes[-1].ofm_tensor:
350 return 0
351
352 ifm_read = passes[0].ifm_tensor.storage_size
353 min_overlap = 999999999999999999999
354 ofm_size = passes[-1].ofm_tensor.storage_size()
355 if strat == SchedulingStrategy.WeightStream:
356 return 0
357 for cmd in generate_high_level_command_stream_for_pass_list(strat, passes, block_configs):
358 if cmd.is_npu_pass_command():
359 if cmd.is_first:
360 ifm_read = cmd.ifm_tensor.address_offset_for_coordinate(cmd.ifm_box.start_coord, is_top_box=False)
361 if ifm_read is None:
362 return 0
363 if cmd.is_last:
364 write_offset = cmd.ofm_tensor.address_offset_for_coordinate(cmd.ofm_box.end_coord, is_top_box=True)
365 if write_offset is None:
366 return 0
367 highest_ofm_write = max(write_offset, highest_ofm_write)
368
369 if cmd.is_first or cmd.is_last:
370 overlap_required = max(highest_ofm_write - min(ifm_read, ofm_size), 0)
371 can_overwrite = ofm_size - overlap_required
372 min_overlap = min(min_overlap, can_overwrite)
373
374 if cmd.is_first:
375 ifm_read = cmd.ifm_tensor.address_offset_for_coordinate(cmd.ifm_box.end_coord, is_top_box=True)
376
377 min_overlap = max(min_overlap, 0)
378 return min_overlap
379
380
381def calc_allowed_ofm_ifm_overlap_for_cascaded_pass(cps):
382 return calc_allowed_ofm_ifm_overlap_for_pass_list(cps.strategy, cps.passes, [ps.block_config for ps in cps.passes])