blob: 09ee73e81ab2bb38035368877a198f9ef00143f3 [file] [log] [blame]
Tim Halld8339a72021-05-27 18:49:40 +01001# Copyright (C) 2021 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.
16#
17# Description:
18# Groups Operators in a schedule together to form Cascades.
Johan Alfvén255dad72022-07-16 18:27:05 +020019from collections import namedtuple
20
Tim Halld8339a72021-05-27 18:49:40 +010021from .numeric_util import round_up
22from .operation import NpuBlockType
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +010023from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010024from .shape4d import Shape4D
25
26non_cascadable_blocks = (
27 NpuBlockType.Default,
28 NpuBlockType.VectorProduct,
Tim Halld8339a72021-05-27 18:49:40 +010029 NpuBlockType.ReduceSum,
30)
31
32
33class CascadeInfo:
34 """Contains metadata about a cascade"""
35
36 def __init__(self, start, end, buffers, mem_usage: int):
37 self.start = start
38 self.end = end
39 self.buffers = buffers
40 self.mem_usage = mem_usage
41
42
43class BufferMap:
44 """Caches the buffers seen"""
45
46 def __init__(self):
47 self.buffer_map = {}
48
49 def get_buffer(self, producer, consumer, cost):
50 assert producer or consumer
51 key = (producer, consumer)
52 if key not in self.buffer_map:
53 # No cached buffer between these two SchedulerOperations
54 if consumer is None:
55 # There are either no consumers or multiple consumers - FeatureMap needs to be stored in full
56 buffer_shape = producer.ofm.shape
57 buffer_size = producer.ofm_size_in_bytes()
58 elif producer is None:
59 # First Op in subgraph or cascade - FeatureMap needs to be stored in full
60 buffer_shape = consumer.ifm.shape
61 buffer_size = consumer.ifm_size_in_bytes()
62 elif producer.requires_full_ofm or consumer.requires_full_ifm:
63 # FeatureMap needs to be stored in full
64 buffer_shape = max(producer.ofm.shape, consumer.ifm.shape)
65 buffer_size = max(producer.ofm_size_in_bytes(), consumer.ifm_size_in_bytes())
66 else:
67 # Use a rolling buffer
68 buffer_shape = rolling_buffer_shape(cost[producer].stripe, cost[consumer].stripe_input)
69 buffer_size = buffer_shape.elements() * producer.ofm.dtype.size_in_bytes()
70
71 self.buffer_map[key] = (buffer_shape, buffer_size)
72
73 return self.buffer_map[key]
74
75
76def rolling_buffer_shape(producer_stripe: Shape4D, consumer_stripe_input: Shape4D) -> Shape4D:
77 """Calculates the storage shape of the rolling buffer between two SchedulerOperations in a Cascade"""
78 buffer_height = round_up(producer_stripe.height + consumer_stripe_input.height, consumer_stripe_input.height)
79 # Rolling buffers have to conform to NHCWB16 format
80 return consumer_stripe_input.with_height(buffer_height).with_depth(round_up(producer_stripe.depth, 16))
81
82
83class CascadeBuilder:
84 """Class for grouping SchedulerOperations into cascades"""
85
86 def __init__(self, sched_ops, spilling, non_local_mem_usage=None):
87 self.sched_ops = sched_ops
88 self.no_cascade = 0
89 self.non_local_mem_usage = non_local_mem_usage if non_local_mem_usage else {}
90 self.spilling = spilling
91
92 def _is_cascadable(self, sched_op, cost) -> bool:
93 """Checks if 'sched_op' can be cascaded"""
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +010094
Tim Halld8339a72021-05-27 18:49:40 +010095 return (
96 sched_op.op_type.npu_block_type not in non_cascadable_blocks
97 and cost.stripe.height < sched_op.ofm.shape.height
Johan Alfvénab677b32022-05-09 13:02:24 +020098 and sched_op.parent_op.read_offsets[0] is None
99 and sched_op.parent_op.read_offsets[1] is None
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100100 and self.element_wise_cascading_conformity(sched_op)
Tim Halld8339a72021-05-27 18:49:40 +0100101 )
102
Johan Alfvén255dad72022-07-16 18:27:05 +0200103 def _is_mergeable(self, sched_op) -> bool:
104 # Code based on merge_elementwise_op_ranges from live_range.py
105
106 if not sched_op.op_type.is_elementwise_op():
107 return False
108
109 elem_op = sched_op.parent_op
110
111 # Check if overwriting the inputs can be allowed
112 OpShapeTens = namedtuple("OpShapeTens", ["op_shape", "tens"])
113 outp = OpShapeTens(elem_op.ofm_shapes[0], elem_op.ofm)
114
115 # check output tensor only has one producer
116 if len(outp.tens.ops) != 1:
117 return False
118
119 inps = []
120 if elem_op.ifm is not None:
121 inps.append(OpShapeTens(elem_op.ifm_shapes[0], elem_op.ifm))
122 if elem_op.ifm2 is not None:
123 inps.append(OpShapeTens(elem_op.ifm_shapes[1], elem_op.ifm2))
124
125 # find an input tensor that can be overwritten by the output
126 for inp in inps:
127 if (
128 # check op input and output shapes allow overlapping
129 inp.op_shape == outp.op_shape
130 # check input tensor is valid
131 and inp.tens is not None
132 and inp.tens.shape != []
133 # check input and output tensors are compatible
134 and inp.tens.format == outp.tens.format
135 and inp.tens.dtype == outp.tens.dtype
136 # check input tensor only has one consumer
137 and len(inp.tens.consumer_list) == 1
138 ):
139 return True
140
141 return False
142
Tim Halld8339a72021-05-27 18:49:40 +0100143 def _estimate_sram_usage(self, sched_op, cost) -> int:
144 """Estimate the SRAM required for the Op if all FeatureMaps are in SRAM"""
145 ifm2_size = sched_op.ifm2_size_in_bytes()
146 if sched_op.requires_full_ifm:
147 ifm_size = sched_op.ifm_size_in_bytes()
148 else:
149 ifm_size = (
150 cost.stripe_input.with_depth(round_up(cost.stripe_input.depth, 16)).elements()
151 * sched_op.ifm.dtype.size_in_bytes()
152 )
153 if sched_op.requires_full_ofm:
154 ofm_size = sched_op.ofm_size_in_bytes()
155 else:
156 ofm_size = (
157 cost.stripe.with_depth(round_up(cost.stripe.depth, 16)).elements() * sched_op.ofm.dtype.size_in_bytes()
158 )
159
Johan Alfvén255dad72022-07-16 18:27:05 +0200160 if self._is_mergeable(sched_op):
161 # ofm will use the ifm buffer to reduce SRAM usage, hence ofm_size = 0
162 ofm_size = 0
163
Tim Halld8339a72021-05-27 18:49:40 +0100164 return ifm_size + ifm2_size + ofm_size + self.non_local_mem_usage.get(sched_op, 0)
165
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100166 @staticmethod
167 def element_wise_cascading_conformity(sched_op):
168 """Check the inputs of the op to see if it's a candidate for cascading."""
169 # Cascading sub-operators of Softmax results in a crash when handling Sub and RescaleAdd ops
170
171 ifm = sched_op.parent_op.ifm
172 ifm2 = sched_op.parent_op.ifm2
173
174 if sched_op.op_type in [Op.RescaleAdd]:
175 return False
176
177 if sched_op.parent_op.type.is_binary_elementwise_op() and ifm and ifm2:
178 # We cannot rule out cascadability if at least one IFM is constant
179 return Op.Const in (ifm.ops[0], ifm2.ops[0])
180 else:
181 # Either one IFM is not variable or it is not a binary elementwise op - we cannot rule out cascadability
182 return True
183
Tim Halld8339a72021-05-27 18:49:40 +0100184 def build_cascades(self, ref_schedule, fallback_schedule, guiding_mem_limit):
185 ref_cost = ref_schedule.cost_map
186 fallback_cost = fallback_schedule.cost_map
187 cost = {}
188 cascade_map = {}
189 buffers = BufferMap()
190
191 # Peak memory usage so far - updated continously, unless dedicated SRAM where this is a hard limit
192 peak_sram_usage = guiding_mem_limit
193
194 idx = 0
195 while idx < len(self.sched_ops):
196 op = self.sched_ops[idx]
197 if op in cost:
198 # Already processed this Op
199 idx += 1
200 continue
201
202 if not self._is_cascadable(op, ref_cost[op]):
203 # Op is not a candidate for cascading - assign fallback cost
204 cost[op] = fallback_cost[op]
205 if not self.spilling:
206 peak_sram_usage = max(self._estimate_sram_usage(op, fallback_cost[op]), peak_sram_usage)
207 idx += 1
208 continue
209
210 # Propose a cascade starting with this Op
211 cascade_start = op.index
212 # Keep track of which Ops are in the proposed cascade as well as the best cascade so far
213 ops_in_cascade = [op]
214 ops_in_best_cascade = [op]
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000215 # Get the size of the weight buffer(s)
216 weight_buffer = sum(tens.storage_size() for tens in ref_cost[op].buffered_weight_tensors)
Tim Halld8339a72021-05-27 18:49:40 +0100217
218 # The first IFM needs to be stored in full
219 cascade_ifm_size = op.ifm_size_in_bytes() if not self.spilling else 0
220
221 # Add non-local memory usage
222 cascade_ifm_size += self.non_local_mem_usage.get(op, 0)
223
224 # Sum of all intermediate cascade buffers (including weight buffers)
225 cascade_buffers = weight_buffer
226 # Best cascade size - Initially it's the fallback cost of the first Op in the cascade
227 best_cascade_size = self._estimate_sram_usage(op, fallback_cost[op])
228
229 # Op is the producer of the OFM consumed by the next Op to consider
230 producer = op
231 while True:
232 dependants = producer.get_dependants()
233 if len(dependants) != 1:
234 # producer is either the last Op in the schedule or the start of a branch
235 break
236
237 current_op = dependants[0]
238 if (
239 current_op in cost
240 or current_op not in ref_cost
241 or not self._is_cascadable(current_op, ref_cost[current_op])
242 or producer.ofm.shape != current_op.ifm.shape
Louis Verhaard04bd3e92021-08-19 16:36:32 +0200243 or current_op.requires_full_ifm
244 or producer.requires_full_ofm
Tim Halld8339a72021-05-27 18:49:40 +0100245 ):
246 # Current op has already been processed or cannot be cascaded
247 break
248
Louis Verhaard37ba98c2022-03-16 09:56:45 +0100249 if producer.index + 1 != current_op.index:
250 # Cascading is possible, but requires reordering of operations in the schedule,
251 # this is currently not supported
252 break
253
Tim Halld8339a72021-05-27 18:49:40 +0100254 # Get the size of the FeatureMap buffers between current and neighbouring Ops
255 op_full_ifm = current_op.ifm_size_in_bytes()
256 op_full_ofm = current_op.ofm_size_in_bytes()
257 _, op_ifm_buffer = buffers.get_buffer(producer, current_op, ref_cost)
258
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000259 # Get the size of the weight buffer(s)
260 op_weight_buffer = sum(tens.storage_size() for tens in ref_cost[current_op].buffered_weight_tensors)
Tim Halld8339a72021-05-27 18:49:40 +0100261
262 # Calculate the uncascaded memory requirement for current Op
263 uncascaded_sram_usage = op_full_ifm + op_full_ofm + self.non_local_mem_usage.get(current_op, 0)
264
265 # Add current Op to cascade
266 ops_in_cascade.append(current_op)
267
268 # Increase the accumulated intermediate buffers in the cascade
269 cascade_buffers += op_ifm_buffer + op_weight_buffer
270
271 if self.spilling:
272 # For Dedicated SRAM only the intermediate buffers are in SRAM
273 if uncascaded_sram_usage < peak_sram_usage or cascade_buffers > peak_sram_usage:
274 # Cascade until an Op fits in its entirety or the accumulated buffers no longer fit
275 break
276 else:
277 # Any addition to the cascade that fits is the new best cascade for Dedicated SRAM
278 ops_in_best_cascade = [op for op in ops_in_cascade]
279 best_cascade_size = cascade_buffers
280
281 else:
282 # Calculate the total size of the current cascade
283 cascade_size = cascade_ifm_size + cascade_buffers + op_full_ofm
284
285 # Determine if cascading search should stop
286 if (
287 uncascaded_sram_usage < peak_sram_usage
288 and best_cascade_size < peak_sram_usage
289 or (cascade_ifm_size + cascade_buffers) > best_cascade_size
290 ):
291 # Both the existing cascade and current Op fits
292 break
293
Johan Alfvén255dad72022-07-16 18:27:05 +0200294 """
295 One of two conditions will update the best cascade:
296
297 - cascade_size < best_cascade_size or
298 - cascade_size < uncascaded_sram_usage
299
300 The last condition is illustrated below, showing an example where it is
301 better to choose a larger cascade_size (with more OPs) because it will
302 use less total SRAM usage.
303
304 For simplicity, all featuremaps have same size.
305
306 Cascade OP1-OP2, OP3 is standalone
307
308 -> |OP1| -> roll buffer -> |OP2| -> FM -> |OP3| -> FM
309 /
310 |OP0| -> FM
311 \
312 -> ....
313
314
315 best_cascade_size : FM + roll buffer + FM
316 uncascaded_sram_usage: FM + FM + FM
317
318 compared with:
319
320 Cascade OP1-OP3
321
322 -> |OP1| -> roll buffer -> |OP2| -> roll buffer -> |OP3| -> FM
323 /
324 |OP0| -> FM
325 \
326 -> ....
327
328
329 cascade_size : FM + roll buffer + roll buffer + FM
330
331
332 So, for this use case the comparison will be
333
334 (FM + roll buffer + roll buffer + FM) < (FM + roll buffer + FM) or
335 (FM + roll buffer + roll buffer + FM) < (FM + FM + FM)
336
337 hence, better to choose Cascade OP1-OP3 in this case.
338 """
339 if cascade_size < best_cascade_size or cascade_size < uncascaded_sram_usage:
Tim Halld8339a72021-05-27 18:49:40 +0100340 best_cascade_size = cascade_ifm_size + cascade_buffers + op_full_ofm
341 ops_in_best_cascade = [op for op in ops_in_cascade]
342
343 producer = current_op
344
345 if len(ops_in_best_cascade) > 1:
346 # A cascade was created - assign cascade and ref_cost to all of the Ops
347 cascade_end = cascade_start + (len(ops_in_best_cascade) - 1)
348 buffers_in_cascade = {}
349 prev_op = None
350 for cascaded_op in ops_in_best_cascade:
Louis Verhaard37ba98c2022-03-16 09:56:45 +0100351 assert cascade_start <= cascaded_op.index <= cascade_end
Tim Halld8339a72021-05-27 18:49:40 +0100352 cost[cascaded_op] = ref_cost[cascaded_op]
353 cost[cascaded_op].cascade = cascade_end
354 if prev_op:
355 rolling_buffer_shape, _ = buffers.get_buffer(prev_op, cascaded_op, ref_cost)
356 buffers_in_cascade[cascaded_op] = rolling_buffer_shape
357
358 prev_op = cascaded_op
359
360 # Create a CascadeInfo for the cascade
361 cascade_map[cascade_end] = CascadeInfo(
362 cascade_start, cascade_end, buffers_in_cascade, best_cascade_size
363 )
364 if not self.spilling:
365 # Update peak memory usage
366 peak_sram_usage = max(best_cascade_size, peak_sram_usage)
367 else:
368 # Assign fallback cost to the initial Op
369 cost[op] = fallback_cost[op]
370 if not self.spilling:
371 peak_sram_usage = max(self._estimate_sram_usage(op, fallback_cost[op]), peak_sram_usage)
372
erik.andersson@arm.com6b2a0b42022-03-22 15:35:30 +0100373 # Update costing and cascade information for the ref_schedule
Tim Halld8339a72021-05-27 18:49:40 +0100374 ref_schedule.cost_map = cost
375 ref_schedule.cascades = cascade_map
376 return ref_schedule