blob: a29cafe078d6e09802cbf436e14969849f6922e0 [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.
Diego Russoe8a10452020-04-21 17:39:10 +010019from .nn_graph import PassPlacement
Louis Verhaardaee5d752020-09-30 09:01:52 +020020from .operation import Op
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020021from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010022from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010023
24
25class LiveRange:
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020026 def __init__(self, tens, alignment):
Tim Hall79d07d22020-04-27 18:20:16 +010027 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 = ""
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020032 self.alignment = alignment
Tim Hall79d07d22020-04-27 18:20:16 +010033
34 if tens:
35 self.add_tensor(tens)
36
37 def __str__(self):
38 return "<live_range.LiveRange: '%s' start_time=%s, end_time=%s>" % (self.name, self.start_time, self.end_time)
39
40 __repr__ = __str__
41
42 def add_tensor(self, tens):
43 if self.size == 0:
44 self.size = tens.storage_size()
45 self.name = tens.name # LiveRange will be named after the first tensor added
46 else:
47 assert (
48 self.size >= tens.storage_size()
49 ), "Tensors assigned to the same LiveRange need to fit the size of the LiveRange."
50
51 self.tensors.append(tens)
52
53 def mark_usage(self, op_time):
54 if op_time == -1:
55 return
56 op_time_start = op_time
57 op_time_end = op_time + 1
58
59 self.start_time = min(self.start_time, op_time_start)
60 self.end_time = max(self.end_time, op_time_end)
61
62 def overlaps_ranges(self, other):
63 return max(self.start_time, other.start_time) < min(self.end_time, other.end_time)
64
65 def overlaps_address(self, other):
66 # Returns the first pair of tensors in this LiveRange and 'other' which have
67 # overlapping addresses
68 for tens in self.tensors:
69 for other_tens in other.tensors:
70 if max(tens.address, other_tens.address) < min(
71 tens.address + self.size, other_tens.address + other.size
72 ):
73 return True, tens, other_tens
74
75 return False, None, None
76
77 def __lt__(self, other):
78 if self.start_time != other.start_time:
79 return self.start_time < other.start_time
80 if self.end_time != other.end_time:
81 return self.end_time < other.end_time
82 if self.size != other.size:
83 return self.size < other.size
84 return self.name < other.name
85
86 def set_address(self, address):
Jacob Bohlin1a666972020-09-11 10:04:15 +020087 # Set address of all tensors in LiveRange
Tim Hall79d07d22020-04-27 18:20:16 +010088 for tens in self.tensors:
Jacob Bohlin1a666972020-09-11 10:04:15 +020089 tens.address = address
90
91 return address
Tim Hall79d07d22020-04-27 18:20:16 +010092
93 def get_alignment(self):
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020094 return self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +010095
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020096 def set_alignment(self, alignment):
97 self.alignment = max(self.alignment, alignment)
Tim Hall79d07d22020-04-27 18:20:16 +010098
99
Tim Hall79d07d22020-04-27 18:20:16 +0100100class LiveRangeGraph:
101 def __init__(self):
102 self.ranges = {} # tens -> range
Tim Hall79d07d22020-04-27 18:20:16 +0100103 self.ignore_tensors = set()
104 self.processed_subgraphs = set()
105 self.current_time = 0
106
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200107 def get_or_create_range(self, tens, alignment=Tensor.AllocationQuantum):
Jacob Bohlin1a666972020-09-11 10:04:15 +0200108 # Return the live range of the tensor (or any of its clones)
109 for existing_tensor, rng in self.ranges.items():
110 if tens.equivalent(existing_tensor):
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200111 rng.set_alignment(alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100112 return rng
113
114 # No live range found for the tensor, create a new one
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200115 rng = LiveRange(tens, alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100116 self.ranges[tens] = rng
117 return rng
118
119 def fuse_ranges(self, in_tens, out_tens):
120 live_range = self.get_or_create_range(in_tens)
121 assert out_tens not in self.ranges, out_tens
122 live_range.add_tensor(out_tens)
123 self.ranges[out_tens] = live_range
124 return live_range
125
126
Patrik Gustavssona151f592020-10-16 13:59:52 +0200127def tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
128 if tens.mem_area != target_mem_area or tens.mem_type not in target_mem_type_set:
129 return True
130 if tens in lr_graph.ignore_tensors:
131 return True
132 if tens.name.endswith("reshape_shape_npu"):
133 # Reshape tensor, no need to allocate
134 lr_graph.ignore_tensors.add(tens)
135 return True
136 return False
137
138
139# Tries merging of ifm/ofm live ranges for memory only ops and elementwise ops
140def merge_op_ranges(sg, lr_graph, target_mem_area, target_mem_type_set):
141 for ps in sg.passes:
142 if ps.placement == PassPlacement.MemoryOnly:
143 # For memory only passes, e.g. Reshape. Add input and output tensor to the same LiveRange
144 input_tensor = ps.inputs[0]
145 output_tensor = ps.outputs[0]
146 if not tensor_should_be_ignored(lr_graph, input_tensor, target_mem_area, target_mem_type_set) and not (
147 tensor_should_be_ignored(lr_graph, output_tensor, target_mem_area, target_mem_type_set)
148 ):
149 lr_graph.fuse_ranges(input_tensor, output_tensor)
150 elif ps.is_element_wise:
151 merge_elementwise_op_ranges(ps, lr_graph, target_mem_area, target_mem_type_set)
152
153
154# Tries to merge ifm/ofm live of elementwise op
155def merge_elementwise_op_ranges(ps, lr_graph, target_mem_area, target_mem_type_set):
156 elem_op = None
157 for op in ps.ops:
158 if op.type.is_elementwise_op():
159 assert elem_op is None
160 elem_op = op
161
162 if elem_op is not None and not tensor_should_be_ignored(
163 lr_graph, elem_op.ofm, target_mem_area, target_mem_type_set
164 ):
165 # Check if overwriting the inputs can be allowed
166 if elem_op.type not in (Op.SHL, Op.SHR):
167 inps = []
168 if (
169 elem_op.ifm is not None
170 and elem_op.ifm.shape != []
171 and elem_op.ifm.mem_area == target_mem_area
172 and elem_op.ifm.mem_type in target_mem_type_set
173 ):
174 inps.append(elem_op.ifm)
175 if (
176 elem_op.ifm2 is not None
177 and elem_op.ifm2.shape != []
178 and elem_op.ifm2.mem_area == target_mem_area
179 and elem_op.ifm.mem_type in target_mem_type_set
180 ):
181 inps.append(elem_op.ifm2)
182
183 if len(inps) > 0:
184 for inp in inps:
185 # check input format, dtype, broadcasting or if there are more input consumers
186 if (
187 inp.format == elem_op.ofm.format
188 and inp.dtype == elem_op.ofm.dtype
189 and inp.shape == elem_op.ofm.shape
190 and (len(inp.consumer_list) == 1 and len(inp.ops) == 1)
191 ):
192 lr_graph.fuse_ranges(inp, elem_op.ofm)
193 break
194
195
Tim Hall79d07d22020-04-27 18:20:16 +0100196def extract_live_ranges_from_passes(
197 sg,
198 target_mem_area,
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100199 target_mem_type_set=set((MemType.Scratch, MemType.Scratch_fast)),
Tim Hall79d07d22020-04-27 18:20:16 +0100200 ignore_subgraph_input_output_tensors=False,
201):
202 lr_graph = LiveRangeGraph()
203
204 if ignore_subgraph_input_output_tensors:
205 lr_graph.ignore_tensors.update(sg.input_tensors)
206 lr_graph.ignore_tensors.update(sg.output_tensors)
207
Patrik Gustavssona151f592020-10-16 13:59:52 +0200208 # Try to merge live ranges of operations in the NPU subgraphs
Tim Hall79d07d22020-04-27 18:20:16 +0100209 if sg.placement == PassPlacement.Npu:
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100210 merge_op_ranges(sg, lr_graph, target_mem_area, target_mem_type_set)
Tim Hall79d07d22020-04-27 18:20:16 +0100211
212 for idx, ps in enumerate(sg.passes):
213 ps.time = 2 * idx
214
215 time_for_pass = ps.time
216
Patrik Gustavssona151f592020-10-16 13:59:52 +0200217 for tens in ps.inputs + ps.intermediates + ps.outputs:
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100218 if tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100219 continue
220 rng = lr_graph.get_or_create_range(tens)
221 rng.mark_usage(time_for_pass)
222
Tim Hall79d07d22020-04-27 18:20:16 +0100223 end_time = len(sg.passes) * 2
224 for tens in sg.output_tensors:
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100225 if tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100226 continue
227 rng = lr_graph.get_or_create_range(tens)
228 rng.mark_usage(end_time)
229
230 return lr_graph
231
232
233def extract_live_ranges_from_cascaded_passes(
234 sg,
235 target_mem_area,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200236 target_mem_type_set,
Tim Hall79d07d22020-04-27 18:20:16 +0100237 ignore_subgraph_input_output_tensors=False,
238 lr_graph=None,
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200239 allocation_alignment=Tensor.AllocationQuantum,
Tim Hall79d07d22020-04-27 18:20:16 +0100240):
Diego Russoea6111a2020-04-14 18:41:58 +0100241 if lr_graph is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100242 lr_graph = LiveRangeGraph()
243
244 if sg in lr_graph.processed_subgraphs:
245 # if subgraph has been processed already, return the lr_graph as is
246 return lr_graph
247
248 if ignore_subgraph_input_output_tensors:
249 lr_graph.ignore_tensors.update(sg.input_tensors)
250 lr_graph.ignore_tensors.update(sg.output_tensors)
251
Patrik Gustavssona151f592020-10-16 13:59:52 +0200252 # Try to merge live ranges of operations in the NPU subgraphs
Tim Hall79d07d22020-04-27 18:20:16 +0100253 if sg.placement == PassPlacement.Npu:
Patrik Gustavssona151f592020-10-16 13:59:52 +0200254 merge_op_ranges(sg, lr_graph, target_mem_area, target_mem_type_set)
Tim Hall79d07d22020-04-27 18:20:16 +0100255
256 for cps in sg.cascaded_passes:
257 cps.time = lr_graph.current_time
258
259 time_for_pass = cps.time
260
Tim Hall79d07d22020-04-27 18:20:16 +0100261 for tens in cps.inputs:
Patrik Gustavssona151f592020-10-16 13:59:52 +0200262 if tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100263 continue
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200264 rng = lr_graph.get_or_create_range(tens, allocation_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100265 rng.mark_usage(time_for_pass)
266
267 cps_primary_op = cps.passes[0].primary_op
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200268
Louis Verhaardaee5d752020-09-30 09:01:52 +0200269 if (
270 cps_primary_op
271 and cps_primary_op.type == Op.CustomNpuOp
272 and MemType.Permanent_CPU not in target_mem_type_set
273 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100274 # If the primary-op is an NpuOp that means this is where an Npu subgraph
275 # is called. Go into said subgraph and extract live ranges before continuing.
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200276 # Use default allocation alignment of 16 for Npu tensors
Tim Hall79d07d22020-04-27 18:20:16 +0100277 npu_sg = cps_primary_op.attrs["subgraph"]
278 lr_graph = extract_live_ranges_from_cascaded_passes(
Patrik Gustavssonfad90c22020-11-03 13:07:40 +0100279 npu_sg, target_mem_area, target_mem_type_set, False, lr_graph,
Tim Hall79d07d22020-04-27 18:20:16 +0100280 )
281 # Set the new time after handling the Npu subgraph
282 time_for_pass = lr_graph.current_time
283 cps.time = time_for_pass
284
Patrik Gustavssona151f592020-10-16 13:59:52 +0200285 for tens in cps.intermediates + cps.outputs:
286 if tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100287 continue
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200288 rng = lr_graph.get_or_create_range(tens, allocation_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100289 rng.mark_usage(time_for_pass)
290
Tim Hall79d07d22020-04-27 18:20:16 +0100291 lr_graph.current_time += 2
292
293 end_time = 0
294 for rng in lr_graph.ranges.values():
295 # Find the maximum end time of all live-ranges in the graph
296 end_time = max(end_time, rng.end_time)
297
298 for tens in sg.output_tensors:
Patrik Gustavssona151f592020-10-16 13:59:52 +0200299 if tensor_should_be_ignored(lr_graph, tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100300 continue
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200301 rng = lr_graph.get_or_create_range(tens, allocation_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100302 rng.mark_usage(end_time)
303
304 # Add subgraph to set of processed subgraphs
305 lr_graph.processed_subgraphs.add(sg)
306 return lr_graph