blob: 0b50eaa8fdf55219c34311205100b3bb3f2bcbc3 [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.
19from .numeric_util import round_up
20from .operation import NpuBlockType
21from .shape4d import Shape4D
22
23non_cascadable_blocks = (
24 NpuBlockType.Default,
25 NpuBlockType.VectorProduct,
26 NpuBlockType.ElementWise,
27 NpuBlockType.ReduceSum,
28)
29
30
31class CascadeInfo:
32 """Contains metadata about a cascade"""
33
34 def __init__(self, start, end, buffers, mem_usage: int):
35 self.start = start
36 self.end = end
37 self.buffers = buffers
38 self.mem_usage = mem_usage
39
40
41class BufferMap:
42 """Caches the buffers seen"""
43
44 def __init__(self):
45 self.buffer_map = {}
46
47 def get_buffer(self, producer, consumer, cost):
48 assert producer or consumer
49 key = (producer, consumer)
50 if key not in self.buffer_map:
51 # No cached buffer between these two SchedulerOperations
52 if consumer is None:
53 # There are either no consumers or multiple consumers - FeatureMap needs to be stored in full
54 buffer_shape = producer.ofm.shape
55 buffer_size = producer.ofm_size_in_bytes()
56 elif producer is None:
57 # First Op in subgraph or cascade - FeatureMap needs to be stored in full
58 buffer_shape = consumer.ifm.shape
59 buffer_size = consumer.ifm_size_in_bytes()
60 elif producer.requires_full_ofm or consumer.requires_full_ifm:
61 # FeatureMap needs to be stored in full
62 buffer_shape = max(producer.ofm.shape, consumer.ifm.shape)
63 buffer_size = max(producer.ofm_size_in_bytes(), consumer.ifm_size_in_bytes())
64 else:
65 # Use a rolling buffer
66 buffer_shape = rolling_buffer_shape(cost[producer].stripe, cost[consumer].stripe_input)
67 buffer_size = buffer_shape.elements() * producer.ofm.dtype.size_in_bytes()
68
69 self.buffer_map[key] = (buffer_shape, buffer_size)
70
71 return self.buffer_map[key]
72
73
74def rolling_buffer_shape(producer_stripe: Shape4D, consumer_stripe_input: Shape4D) -> Shape4D:
75 """Calculates the storage shape of the rolling buffer between two SchedulerOperations in a Cascade"""
76 buffer_height = round_up(producer_stripe.height + consumer_stripe_input.height, consumer_stripe_input.height)
77 # Rolling buffers have to conform to NHCWB16 format
78 return consumer_stripe_input.with_height(buffer_height).with_depth(round_up(producer_stripe.depth, 16))
79
80
81class CascadeBuilder:
82 """Class for grouping SchedulerOperations into cascades"""
83
84 def __init__(self, sched_ops, spilling, non_local_mem_usage=None):
85 self.sched_ops = sched_ops
86 self.no_cascade = 0
87 self.non_local_mem_usage = non_local_mem_usage if non_local_mem_usage else {}
88 self.spilling = spilling
89
90 def _is_cascadable(self, sched_op, cost) -> bool:
91 """Checks if 'sched_op' can be cascaded"""
92 return (
93 sched_op.op_type.npu_block_type not in non_cascadable_blocks
94 and cost.stripe.height < sched_op.ofm.shape.height
95 )
96
97 def _estimate_sram_usage(self, sched_op, cost) -> int:
98 """Estimate the SRAM required for the Op if all FeatureMaps are in SRAM"""
99 ifm2_size = sched_op.ifm2_size_in_bytes()
100 if sched_op.requires_full_ifm:
101 ifm_size = sched_op.ifm_size_in_bytes()
102 else:
103 ifm_size = (
104 cost.stripe_input.with_depth(round_up(cost.stripe_input.depth, 16)).elements()
105 * sched_op.ifm.dtype.size_in_bytes()
106 )
107 if sched_op.requires_full_ofm:
108 ofm_size = sched_op.ofm_size_in_bytes()
109 else:
110 ofm_size = (
111 cost.stripe.with_depth(round_up(cost.stripe.depth, 16)).elements() * sched_op.ofm.dtype.size_in_bytes()
112 )
113
114 return ifm_size + ifm2_size + ofm_size + self.non_local_mem_usage.get(sched_op, 0)
115
116 def build_cascades(self, ref_schedule, fallback_schedule, guiding_mem_limit):
117 ref_cost = ref_schedule.cost_map
118 fallback_cost = fallback_schedule.cost_map
119 cost = {}
120 cascade_map = {}
121 buffers = BufferMap()
122
123 # Peak memory usage so far - updated continously, unless dedicated SRAM where this is a hard limit
124 peak_sram_usage = guiding_mem_limit
125
126 idx = 0
127 while idx < len(self.sched_ops):
128 op = self.sched_ops[idx]
129 if op in cost:
130 # Already processed this Op
131 idx += 1
132 continue
133
134 if not self._is_cascadable(op, ref_cost[op]):
135 # Op is not a candidate for cascading - assign fallback cost
136 cost[op] = fallback_cost[op]
137 if not self.spilling:
138 peak_sram_usage = max(self._estimate_sram_usage(op, fallback_cost[op]), peak_sram_usage)
139 idx += 1
140 continue
141
142 # Propose a cascade starting with this Op
143 cascade_start = op.index
144 # Keep track of which Ops are in the proposed cascade as well as the best cascade so far
145 ops_in_cascade = [op]
146 ops_in_best_cascade = [op]
147 # Get the size of the weight buffer
148 weight_buffer = 0
149 if ref_cost[op].buffered_weight_tensor:
150 weight_buffer = ref_cost[op].buffered_weight_tensor.storage_size()
151
152 # The first IFM needs to be stored in full
153 cascade_ifm_size = op.ifm_size_in_bytes() if not self.spilling else 0
154
155 # Add non-local memory usage
156 cascade_ifm_size += self.non_local_mem_usage.get(op, 0)
157
158 # Sum of all intermediate cascade buffers (including weight buffers)
159 cascade_buffers = weight_buffer
160 # Best cascade size - Initially it's the fallback cost of the first Op in the cascade
161 best_cascade_size = self._estimate_sram_usage(op, fallback_cost[op])
162
163 # Op is the producer of the OFM consumed by the next Op to consider
164 producer = op
165 while True:
166 dependants = producer.get_dependants()
167 if len(dependants) != 1:
168 # producer is either the last Op in the schedule or the start of a branch
169 break
170
171 current_op = dependants[0]
172 if (
173 current_op in cost
174 or current_op not in ref_cost
175 or not self._is_cascadable(current_op, ref_cost[current_op])
176 or producer.ofm.shape != current_op.ifm.shape
Louis Verhaard04bd3e92021-08-19 16:36:32 +0200177 or current_op.requires_full_ifm
178 or producer.requires_full_ofm
Tim Halld8339a72021-05-27 18:49:40 +0100179 ):
180 # Current op has already been processed or cannot be cascaded
181 break
182
183 # Get the size of the FeatureMap buffers between current and neighbouring Ops
184 op_full_ifm = current_op.ifm_size_in_bytes()
185 op_full_ofm = current_op.ofm_size_in_bytes()
186 _, op_ifm_buffer = buffers.get_buffer(producer, current_op, ref_cost)
187
188 # Get the size of the weight buffer
189 op_weight_buffer = 0
190 if ref_cost[current_op].buffered_weight_tensor:
191 op_weight_buffer = ref_cost[current_op].buffered_weight_tensor.storage_size()
192
193 # Calculate the uncascaded memory requirement for current Op
194 uncascaded_sram_usage = op_full_ifm + op_full_ofm + self.non_local_mem_usage.get(current_op, 0)
195
196 # Add current Op to cascade
197 ops_in_cascade.append(current_op)
198
199 # Increase the accumulated intermediate buffers in the cascade
200 cascade_buffers += op_ifm_buffer + op_weight_buffer
201
202 if self.spilling:
203 # For Dedicated SRAM only the intermediate buffers are in SRAM
204 if uncascaded_sram_usage < peak_sram_usage or cascade_buffers > peak_sram_usage:
205 # Cascade until an Op fits in its entirety or the accumulated buffers no longer fit
206 break
207 else:
208 # Any addition to the cascade that fits is the new best cascade for Dedicated SRAM
209 ops_in_best_cascade = [op for op in ops_in_cascade]
210 best_cascade_size = cascade_buffers
211
212 else:
213 # Calculate the total size of the current cascade
214 cascade_size = cascade_ifm_size + cascade_buffers + op_full_ofm
215
216 # Determine if cascading search should stop
217 if (
218 uncascaded_sram_usage < peak_sram_usage
219 and best_cascade_size < peak_sram_usage
220 or (cascade_ifm_size + cascade_buffers) > best_cascade_size
221 ):
222 # Both the existing cascade and current Op fits
223 break
224
225 # Determine if current cascade is the best so far
226 if cascade_size < best_cascade_size:
227 best_cascade_size = cascade_ifm_size + cascade_buffers + op_full_ofm
228 ops_in_best_cascade = [op for op in ops_in_cascade]
229
230 producer = current_op
231
232 if len(ops_in_best_cascade) > 1:
233 # A cascade was created - assign cascade and ref_cost to all of the Ops
234 cascade_end = cascade_start + (len(ops_in_best_cascade) - 1)
235 buffers_in_cascade = {}
236 prev_op = None
237 for cascaded_op in ops_in_best_cascade:
238 cost[cascaded_op] = ref_cost[cascaded_op]
239 cost[cascaded_op].cascade = cascade_end
240 if prev_op:
241 rolling_buffer_shape, _ = buffers.get_buffer(prev_op, cascaded_op, ref_cost)
242 buffers_in_cascade[cascaded_op] = rolling_buffer_shape
243
244 prev_op = cascaded_op
245
246 # Create a CascadeInfo for the cascade
247 cascade_map[cascade_end] = CascadeInfo(
248 cascade_start, cascade_end, buffers_in_cascade, best_cascade_size
249 )
250 if not self.spilling:
251 # Update peak memory usage
252 peak_sram_usage = max(best_cascade_size, peak_sram_usage)
253 else:
254 # Assign fallback cost to the initial Op
255 cost[op] = fallback_cost[op]
256 if not self.spilling:
257 peak_sram_usage = max(self._estimate_sram_usage(op, fallback_cost[op]), peak_sram_usage)
258
259 # Update costing and cascde information for the ref_schedule
260 ref_schedule.cost_map = cost
261 ref_schedule.cascades = cascade_map
262 return ref_schedule