blob: 23ab67d9299230c499ec11d54797c082ce17365a [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# Build a live range graph for tensors in one or more subgraphs. Used for tensor allocation as well as in the scheduler.
18# Can work with either a pass packed subgraph or a scheduled subgraph.
Tim Hall79d07d22020-04-27 18:20:16 +010019from .high_level_command_stream_generator import calc_allowed_ofm_ifm_overlap_for_cascaded_pass
Diego Russoe8a10452020-04-21 17:39:10 +010020from .nn_graph import PassPlacement
21from .tensor import MemArea
22from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010023
24
25class LiveRange:
26 def __init__(self, tens):
27 self.tensors = [] # Tensors that are assigned to the same LiveRange will be allocated to the same address
28 self.start_time = 99999999999
29 self.end_time = -1
30 self.size = 0
31 self.name = ""
32
33 if tens:
34 self.add_tensor(tens)
35
36 def __str__(self):
37 return "<live_range.LiveRange: '%s' start_time=%s, end_time=%s>" % (self.name, self.start_time, self.end_time)
38
39 __repr__ = __str__
40
41 def add_tensor(self, tens):
42 if self.size == 0:
43 self.size = tens.storage_size()
44 self.name = tens.name # LiveRange will be named after the first tensor added
45 else:
46 assert (
47 self.size >= tens.storage_size()
48 ), "Tensors assigned to the same LiveRange need to fit the size of the LiveRange."
49
50 self.tensors.append(tens)
51
52 def mark_usage(self, op_time):
53 if op_time == -1:
54 return
55 op_time_start = op_time
56 op_time_end = op_time + 1
57
58 self.start_time = min(self.start_time, op_time_start)
59 self.end_time = max(self.end_time, op_time_end)
60
61 def overlaps_ranges(self, other):
62 return max(self.start_time, other.start_time) < min(self.end_time, other.end_time)
63
64 def overlaps_address(self, other):
65 # Returns the first pair of tensors in this LiveRange and 'other' which have
66 # overlapping addresses
67 for tens in self.tensors:
68 for other_tens in other.tensors:
69 if max(tens.address, other_tens.address) < min(
70 tens.address + self.size, other_tens.address + other.size
71 ):
72 return True, tens, other_tens
73
74 return False, None, None
75
76 def __lt__(self, other):
77 if self.start_time != other.start_time:
78 return self.start_time < other.start_time
79 if self.end_time != other.end_time:
80 return self.end_time < other.end_time
81 if self.size != other.size:
82 return self.size < other.size
83 return self.name < other.name
84
85 def set_address(self, address):
86 # Set address of all unaddressed tensors in LiveRange
87 for tens in self.tensors:
88 if tens.address == 0:
89 tens.address = address
90 # Also need to set the address to the tensor's cpu/npu clones
Diego Russoea6111a2020-04-14 18:41:58 +010091 if tens.cpu_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010092 tens.cpu_tensor.address = address
Diego Russoea6111a2020-04-14 18:41:58 +010093 if tens.npu_tensor is not None:
Tim Hall79d07d22020-04-27 18:20:16 +010094 tens.npu_tensor.address = address
95
96 def get_alignment(self):
97 # Get max alignment of LiveRange's tensors
98 if self.tensors:
99 alignment = 0
100 for tens in self.tensors:
101 alignment = max(alignment, tens.alignment)
102
103 return alignment
104
105 return Tensor.AllocationQuantum
106
107
108def merge_memory_op_ranges(sg, lr_graph, tensor_should_be_ignored, target_mem_area):
109 for ps in sg.passes:
110 if ps.placement == PassPlacement.MemoryOnly:
111 # For memory only passes, e.g. Reshape. Add input and output tensor to the same LiveRange
112 input_tensor = ps.inputs[0]
113 output_tensor = ps.outputs[0]
114 # If the input or output tensor is tied to a Cpu tensor, i.e. a subgraph input
115 # or output, fuse the live-range with the Cpu tensors' live-range instead.
Diego Russoea6111a2020-04-14 18:41:58 +0100116 input_tensor = input_tensor.cpu_tensor if input_tensor.cpu_tensor is not None else input_tensor
117 output_tensor = output_tensor.cpu_tensor if output_tensor.cpu_tensor is not None else output_tensor
Tim Hall79d07d22020-04-27 18:20:16 +0100118 if not tensor_should_be_ignored(input_tensor, target_mem_area) and not tensor_should_be_ignored(
119 output_tensor, target_mem_area
120 ):
121 lr_graph.fuse_ranges(input_tensor, output_tensor)
122
123
124class LiveRangeGraph:
125 def __init__(self):
126 self.ranges = {} # tens -> range
127 self.allowed_overlaps = {} # (tens,tens) -> overlap_int
128 self.ignore_tensors = set()
129 self.processed_subgraphs = set()
130 self.current_time = 0
131
132 def get_or_create_range(self, tens):
133 for rng in self.ranges.values():
134 # Return the live range of the tensor (or it's cpu/npu clone)
135 if any(tensor in rng.tensors for tensor in [tens, tens.npu_tensor, tens.cpu_tensor]):
136 return rng
137
138 # No live range found for the tensor, create a new one
139 rng = LiveRange(tens)
140 self.ranges[tens] = rng
141 return rng
142
143 def fuse_ranges(self, in_tens, out_tens):
144 live_range = self.get_or_create_range(in_tens)
145 assert out_tens not in self.ranges, out_tens
146 live_range.add_tensor(out_tens)
147 self.ranges[out_tens] = live_range
148 return live_range
149
150
151def extract_live_ranges_from_passes(
152 sg,
153 target_mem_area,
154 mark_output_tensors_overlapping_with_input_tensors=False,
155 ignore_subgraph_input_output_tensors=False,
156):
157 lr_graph = LiveRangeGraph()
158
159 if ignore_subgraph_input_output_tensors:
160 lr_graph.ignore_tensors.update(sg.input_tensors)
161 lr_graph.ignore_tensors.update(sg.output_tensors)
162
163 def tensor_should_be_ignored(tens, target_mem_area):
164 if tens.mem_area != target_mem_area:
165 return True
166 if tens in lr_graph.ignore_tensors:
167 return True
168 if tens.name.endswith("reshape_shape_npu"):
169 # Reshape tensor, no need to allocate
170 lr_graph.ignore_tensors.add(tens)
171 return True
172 return False
173
174 # Merge only memory operations in the NPU subgraphs
175 if sg.placement == PassPlacement.Npu:
176 merge_memory_op_ranges(sg, lr_graph, tensor_should_be_ignored, target_mem_area)
177
178 for idx, ps in enumerate(sg.passes):
179 ps.time = 2 * idx
180
181 time_for_pass = ps.time
182
183 for tens in ps.inputs:
184 if tensor_should_be_ignored(tens, target_mem_area):
185 continue
186 rng = lr_graph.get_or_create_range(tens)
187 rng.mark_usage(time_for_pass)
188
189 for tens in ps.intermediates:
190 if tensor_should_be_ignored(tens, target_mem_area):
191 continue
192 rng = lr_graph.get_or_create_range(tens)
193 rng.mark_usage(time_for_pass)
194
195 for tens in ps.outputs:
196 if tensor_should_be_ignored(tens, target_mem_area):
197 continue
198 rng = lr_graph.get_or_create_range(tens)
199 output_time = time_for_pass
200 if not mark_output_tensors_overlapping_with_input_tensors and ps.is_element_wise:
201 output_time += 1
202 rng.mark_usage(output_time)
203
204 end_time = len(sg.passes) * 2
205 for tens in sg.output_tensors:
206 if tensor_should_be_ignored(tens, target_mem_area):
207 continue
208 rng = lr_graph.get_or_create_range(tens)
209 rng.mark_usage(end_time)
210
211 return lr_graph
212
213
214def extract_live_ranges_from_cascaded_passes(
215 sg,
216 target_mem_area,
217 mark_output_tensors_overlapping_with_input_tensors=False,
218 use_ifm_ofm_overlap=True,
219 ignore_subgraph_input_output_tensors=False,
220 lr_graph=None,
221):
Diego Russoea6111a2020-04-14 18:41:58 +0100222 if lr_graph is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100223 lr_graph = LiveRangeGraph()
224
225 if sg in lr_graph.processed_subgraphs:
226 # if subgraph has been processed already, return the lr_graph as is
227 return lr_graph
228
229 if ignore_subgraph_input_output_tensors:
230 lr_graph.ignore_tensors.update(sg.input_tensors)
231 lr_graph.ignore_tensors.update(sg.output_tensors)
232
233 def tensor_should_be_ignored(tens, target_mem_area):
234 if tens.mem_area != target_mem_area:
235 return True
236 if tens in lr_graph.ignore_tensors:
237 return True
238 if tens.name.endswith("reshape_shape_npu"):
239 # Reshape tensor, no need to allocate
240 lr_graph.ignore_tensors.add(tens)
241 return True
242 return False
243
244 # Merge only memory operations in the NPU subgraphs
245 if sg.placement == PassPlacement.Npu:
246 merge_memory_op_ranges(sg, lr_graph, tensor_should_be_ignored, target_mem_area)
247
248 for cps in sg.cascaded_passes:
249 cps.time = lr_graph.current_time
250
251 time_for_pass = cps.time
252
253 is_element_wise = cps.is_element_wise
254
255 for tens in cps.inputs:
256 if tensor_should_be_ignored(tens, target_mem_area):
257 continue
258 rng = lr_graph.get_or_create_range(tens)
259 rng.mark_usage(time_for_pass)
260
261 cps_primary_op = cps.passes[0].primary_op
262 if cps_primary_op and cps_primary_op.type == "NpuOp" and target_mem_area in set((MemArea.Sram, MemArea.Dram)):
263 # If the primary-op is an NpuOp that means this is where an Npu subgraph
264 # is called. Go into said subgraph and extract live ranges before continuing.
265 npu_sg = cps_primary_op.attrs["subgraph"]
266 lr_graph = extract_live_ranges_from_cascaded_passes(
267 npu_sg,
268 target_mem_area,
269 mark_output_tensors_overlapping_with_input_tensors,
270 use_ifm_ofm_overlap,
271 False,
272 lr_graph,
273 )
274 # Set the new time after handling the Npu subgraph
275 time_for_pass = lr_graph.current_time
276 cps.time = time_for_pass
277
278 for tens in cps.intermediates:
279 if tensor_should_be_ignored(tens, target_mem_area):
280 continue
281 rng = lr_graph.get_or_create_range(tens)
282 rng.mark_usage(time_for_pass)
283
284 for tens in cps.outputs:
285 if tensor_should_be_ignored(tens, target_mem_area):
286 continue
287 rng = lr_graph.get_or_create_range(tens)
288 output_time = time_for_pass
289 if not mark_output_tensors_overlapping_with_input_tensors and is_element_wise:
290 output_time += 1
291 rng.mark_usage(output_time)
292
293 if use_ifm_ofm_overlap:
294 # fill allowed overlap for ifm and ofm tensor
295 ifm_tensor = cps.passes[0].ifm_tensor
296 ofm_tensor = cps.passes[-1].ofm_tensor
297 if (
298 ifm_tensor is not None
299 and ofm_tensor is not None
300 and not tensor_should_be_ignored(ifm_tensor, target_mem_area)
301 and not tensor_should_be_ignored(ofm_tensor, target_mem_area)
302 ):
303 lr_graph.allowed_overlaps[(ifm_tensor, ofm_tensor)] = calc_allowed_ofm_ifm_overlap_for_cascaded_pass(
304 cps
305 )
306
307 lr_graph.current_time += 2
308
309 end_time = 0
310 for rng in lr_graph.ranges.values():
311 # Find the maximum end time of all live-ranges in the graph
312 end_time = max(end_time, rng.end_time)
313
314 for tens in sg.output_tensors:
315 if tensor_should_be_ignored(tens, target_mem_area):
316 continue
317 rng = lr_graph.get_or_create_range(tens)
318 rng.mark_usage(end_time)
319
320 # Add subgraph to set of processed subgraphs
321 lr_graph.processed_subgraphs.add(sg)
322 return lr_graph