blob: 2829f398edd16a103431e4a006fe445ff3bc39d4 [file] [log] [blame]
Johan Alfvén673683b2022-09-05 09:39:47 +02001# Copyright (C) 2020-2022 Arm Limited or its affiliates. All rights reserved.
Tim Hall79d07d22020-04-27 18:20:16 +01002#
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 Hallffe8e282021-06-24 18:29:53 +010019from collections import namedtuple
Louis Verhaard226ecaf2021-03-30 10:18:28 +020020from typing import List
21
Tim Halld8339a72021-05-27 18:49:40 +010022import numpy as np
23
Louis Verhaardaee5d752020-09-30 09:01:52 +020024from .operation import Op
Tim Halld8339a72021-05-27 18:49:40 +010025from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020026from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010027from .tensor import Tensor
Tim Halld8339a72021-05-27 18:49:40 +010028from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010029
30
31class LiveRange:
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020032 def __init__(self, tens, alignment):
Tim Hall79d07d22020-04-27 18:20:16 +010033 self.tensors = [] # Tensors that are assigned to the same LiveRange will be allocated to the same address
34 self.start_time = 99999999999
35 self.end_time = -1
36 self.size = 0
37 self.name = ""
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020038 self.alignment = alignment
Tim Halld8339a72021-05-27 18:49:40 +010039 self.mem_area = tens.mem_area if tens else MemArea.Unknown
Tim Hall79d07d22020-04-27 18:20:16 +010040
41 if tens:
42 self.add_tensor(tens)
43
44 def __str__(self):
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +010045 return (
46 f"<live_range.LiveRange: {self.start_time}-{self.end_time}, "
47 f"size={self.size}, '{self.name}' #:{len(self.tensors)}>"
48 )
Tim Hall79d07d22020-04-27 18:20:16 +010049
50 __repr__ = __str__
51
52 def add_tensor(self, tens):
53 if self.size == 0:
54 self.size = tens.storage_size()
55 self.name = tens.name # LiveRange will be named after the first tensor added
56 else:
57 assert (
58 self.size >= tens.storage_size()
59 ), "Tensors assigned to the same LiveRange need to fit the size of the LiveRange."
60
61 self.tensors.append(tens)
62
Tim Halld8339a72021-05-27 18:49:40 +010063 def mark_usage(self, op_time, op_length=1):
64 op_time_start = max(op_time, 0)
65 op_time_end = op_time + op_length
Rickard Bolinfd8b5002022-05-16 09:11:06 +000066 if op_time_end < op_time_start:
Tim Hall79d07d22020-04-27 18:20:16 +010067 return
Tim Hall79d07d22020-04-27 18:20:16 +010068
69 self.start_time = min(self.start_time, op_time_start)
70 self.end_time = max(self.end_time, op_time_end)
71
Tim Halld8339a72021-05-27 18:49:40 +010072 def set_buffer_size(self, buffer_size):
73 self.size = buffer_size
74 self.mem_area = MemArea.Sram
75
Tim Hall79d07d22020-04-27 18:20:16 +010076 def overlaps_ranges(self, other):
77 return max(self.start_time, other.start_time) < min(self.end_time, other.end_time)
78
79 def overlaps_address(self, other):
80 # Returns the first pair of tensors in this LiveRange and 'other' which have
81 # overlapping addresses
82 for tens in self.tensors:
83 for other_tens in other.tensors:
84 if max(tens.address, other_tens.address) < min(
85 tens.address + self.size, other_tens.address + other.size
86 ):
87 return True, tens, other_tens
88
89 return False, None, None
90
91 def __lt__(self, other):
92 if self.start_time != other.start_time:
93 return self.start_time < other.start_time
94 if self.end_time != other.end_time:
95 return self.end_time < other.end_time
96 if self.size != other.size:
97 return self.size < other.size
98 return self.name < other.name
99
100 def set_address(self, address):
Jacob Bohlin1a666972020-09-11 10:04:15 +0200101 # Set address of all tensors in LiveRange
Tim Hall79d07d22020-04-27 18:20:16 +0100102 for tens in self.tensors:
Jacob Bohlin1a666972020-09-11 10:04:15 +0200103 tens.address = address
104
105 return address
Tim Hall79d07d22020-04-27 18:20:16 +0100106
107 def get_alignment(self):
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200108 return self.alignment
Tim Hall79d07d22020-04-27 18:20:16 +0100109
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200110 def set_alignment(self, alignment):
111 self.alignment = max(self.alignment, alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100112
113
Tim Hall79d07d22020-04-27 18:20:16 +0100114class LiveRangeGraph:
115 def __init__(self):
Louis Verhaard226ecaf2021-03-30 10:18:28 +0200116 self.lrs: List[LiveRange] = [] # List of all created ranges
Tim Hall79d07d22020-04-27 18:20:16 +0100117 self.ranges = {} # tens -> range
Tim Hall79d07d22020-04-27 18:20:16 +0100118 self.processed_subgraphs = set()
119 self.current_time = 0
Tim Halld8339a72021-05-27 18:49:40 +0100120 self.end_time = None
Tim Hall79d07d22020-04-27 18:20:16 +0100121
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200122 def get_or_create_range(self, tens, alignment=Tensor.AllocationQuantum):
Jacob Bohlin1a666972020-09-11 10:04:15 +0200123 # Return the live range of the tensor (or any of its clones)
124 for existing_tensor, rng in self.ranges.items():
125 if tens.equivalent(existing_tensor):
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200126 rng.set_alignment(alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100127 return rng
128
129 # No live range found for the tensor, create a new one
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200130 rng = LiveRange(tens, alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100131 self.ranges[tens] = rng
Louis Verhaard226ecaf2021-03-30 10:18:28 +0200132 self.lrs.append(rng)
Tim Hall79d07d22020-04-27 18:20:16 +0100133 return rng
134
135 def fuse_ranges(self, in_tens, out_tens):
136 live_range = self.get_or_create_range(in_tens)
137 assert out_tens not in self.ranges, out_tens
138 live_range.add_tensor(out_tens)
139 self.ranges[out_tens] = live_range
140 return live_range
141
Tim Halld8339a72021-05-27 18:49:40 +0100142 def update_endtime(self):
Louis Verhaardcc34d5d2021-08-19 15:15:36 +0200143 self.end_time = self.current_time
Tim Halld8339a72021-05-27 18:49:40 +0100144 return self.end_time + 1
145
146 def get_temporal_memory_usage(self, target_mem_area):
Louis Verhaardcc34d5d2021-08-19 15:15:36 +0200147 usage = np.zeros(self.update_endtime(), dtype=np.int32)
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100148 for lr in self.lrs:
149 if lr.mem_area == target_mem_area:
Tim Halld8339a72021-05-27 18:49:40 +0100150 # End time is inclusive
erik.andersson@arm.comde6cb642022-02-02 14:03:15 +0100151 usage[lr.start_time : lr.end_time + 1] += lr.size
Tim Halld8339a72021-05-27 18:49:40 +0100152
153 return usage
154
Tim Hall79d07d22020-04-27 18:20:16 +0100155
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200156def tensor_should_be_ignored(tens, target_mem_area, target_mem_type_set):
Johan Alfvénfba0a7d2022-10-11 20:41:41 +0200157 if target_mem_area is None or target_mem_type_set is None:
158 return False
Patrik Gustavssona151f592020-10-16 13:59:52 +0200159 if tens.mem_area != target_mem_area or tens.mem_type not in target_mem_type_set:
160 return True
Patrik Gustavssona151f592020-10-16 13:59:52 +0200161 return False
162
163
Johan Alfvénfba0a7d2022-10-11 20:41:41 +0200164def _get_ifm_to_fuse(sched_op, target_mem_area=None, target_mem_type_set=None):
Tim Hallffe8e282021-06-24 18:29:53 +0100165 def _tensor_should_be_ignored(tens):
Johan Alfvén8d57aaa2022-02-04 11:19:17 +0100166 if tens.ifm_write_protected:
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200167 return True
168 return tensor_should_be_ignored(tens, target_mem_area, target_mem_type_set)
Tim Hallffe8e282021-06-24 18:29:53 +0100169
Johan Alfvénfba0a7d2022-10-11 20:41:41 +0200170 # Check if possible to merge ifm/ofm live ranges of elementwise op
171 ifm_tens = None
Jacob Bohlin98bfecd2021-06-21 17:22:20 +0200172 if sched_op.op_type.is_elementwise_op():
173 elem_op = sched_op.parent_op
Tim Hallffe8e282021-06-24 18:29:53 +0100174 if not _tensor_should_be_ignored(elem_op.ofm):
Jacob Bohlin98bfecd2021-06-21 17:22:20 +0200175 # Check if overwriting the inputs can be allowed
Tim Hallffe8e282021-06-24 18:29:53 +0100176 OpShapeTens = namedtuple("OpShapeTens", ["op_shape", "tens"])
177 outp = OpShapeTens(elem_op.ofm_shapes[0], elem_op.ofm)
178 inps = []
179 if elem_op.ifm is not None:
180 inps.append(OpShapeTens(elem_op.ifm_shapes[0], elem_op.ifm))
181 if elem_op.ifm2 is not None:
182 inps.append(OpShapeTens(elem_op.ifm_shapes[1], elem_op.ifm2))
Patrik Gustavssona151f592020-10-16 13:59:52 +0200183
Tim Hallffe8e282021-06-24 18:29:53 +0100184 # find an input tensor that can be overwritten by the output
185 for inp in inps:
186 if (
187 # check op input and output shapes allow overlapping
188 inp.op_shape == outp.op_shape
189 # check input tensor is valid
190 and inp.tens is not None
191 and inp.tens.shape != []
192 and not _tensor_should_be_ignored(inp.tens)
193 # check input and output tensors are compatible
194 and inp.tens.format == outp.tens.format
195 and inp.tens.dtype == outp.tens.dtype
196 # check input tensor only has one consumer
197 and len(inp.tens.consumer_list) == 1
198 # check output tensor only has one producer
199 and len(outp.tens.ops) == 1
200 ):
Johan Alfvénfba0a7d2022-10-11 20:41:41 +0200201 ifm_tens = inp.tens
Tim Hallffe8e282021-06-24 18:29:53 +0100202 break
Tim Hall79d07d22020-04-27 18:20:16 +0100203
Johan Alfvénfba0a7d2022-10-11 20:41:41 +0200204 return ifm_tens
205
206
207def ofm_can_reuse_ifm(sched_op, target_mem_area=None, target_mem_type_set=None):
208 ifm = _get_ifm_to_fuse(sched_op, target_mem_area, target_mem_type_set)
209 return ifm is not None
210
211
212def merge_elementwise_op_ranges(sg, sched_op, lr_graph, target_mem_area, target_mem_type_set):
213 ifm = _get_ifm_to_fuse(sched_op, target_mem_area, target_mem_type_set)
214 if ifm:
215 lr_graph.fuse_ranges(ifm, sched_op.parent_op.ofm)
216
Tim Hall79d07d22020-04-27 18:20:16 +0100217
218def extract_live_ranges_from_cascaded_passes(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200219 sg,
220 target_mem_area,
221 target_mem_type_set,
222 lr_graph=None,
223 cpu_tensor_alignment=Tensor.AllocationQuantum,
Tim Hall79d07d22020-04-27 18:20:16 +0100224):
Diego Russoea6111a2020-04-14 18:41:58 +0100225 if lr_graph is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100226 lr_graph = LiveRangeGraph()
227
228 if sg in lr_graph.processed_subgraphs:
229 # if subgraph has been processed already, return the lr_graph as is
230 return lr_graph
231
Tim Hall79d07d22020-04-27 18:20:16 +0100232 for cps in sg.cascaded_passes:
233 cps.time = lr_graph.current_time
234
235 time_for_pass = cps.time
236
Tim Hall79d07d22020-04-27 18:20:16 +0100237 for tens in cps.inputs:
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200238 if tensor_should_be_ignored(tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100239 continue
Tim Hallb9b515c2020-11-01 21:27:19 +0000240 rng = lr_graph.get_or_create_range(tens, cpu_tensor_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100241 rng.mark_usage(time_for_pass)
242
Fredrik Svedbergf3c7d552022-11-04 09:48:49 +0100243 op = cps.passes[0].ops[0] if cps.passes[0].ops else None
244 op_subgraph = op.attrs.get("subgraph", None) if op else None
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200245
Johan Alfvén673683b2022-09-05 09:39:47 +0200246 if op_subgraph is not None and MemType.Permanent_CPU not in target_mem_type_set:
Fredrik Svedbergf3c7d552022-11-04 09:48:49 +0100247 if op.type == Op.CustomNpuOp:
Johan Alfvén673683b2022-09-05 09:39:47 +0200248 # If the primary-op is an NpuOp that means this is where an Npu subgraph
249 # is called. Go into said subgraph and extract live ranges before continuing.
250 # Use default allocation alignment of 16 for Npu tensors
251 lr_graph = _extract_live_ranges_from_schedule(
252 op_subgraph, target_mem_area, target_mem_type_set, lr_graph
253 )
254 else:
255 # The op has one or more subgraphs in it (a typical op is the While op)
256 # Go into all subgraphs and extract live ranges before continuing.
257 for op_sg in op_subgraph:
258 lr_graph = extract_live_ranges_from_cascaded_passes(
259 op_sg, target_mem_area, target_mem_type_set, lr_graph, cpu_tensor_alignment
260 )
Tim Hall79d07d22020-04-27 18:20:16 +0100261 # Set the new time after handling the Npu subgraph
262 time_for_pass = lr_graph.current_time
263 cps.time = time_for_pass
264
Patrik Gustavssona151f592020-10-16 13:59:52 +0200265 for tens in cps.intermediates + cps.outputs:
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200266 if tensor_should_be_ignored(tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100267 continue
Tim Hallb9b515c2020-11-01 21:27:19 +0000268 rng = lr_graph.get_or_create_range(tens, cpu_tensor_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100269 rng.mark_usage(time_for_pass)
270
Tim Hall79d07d22020-04-27 18:20:16 +0100271 lr_graph.current_time += 2
272
273 end_time = 0
274 for rng in lr_graph.ranges.values():
275 # Find the maximum end time of all live-ranges in the graph
276 end_time = max(end_time, rng.end_time)
277
278 for tens in sg.output_tensors:
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200279 if tensor_should_be_ignored(tens, target_mem_area, target_mem_type_set):
Tim Hall79d07d22020-04-27 18:20:16 +0100280 continue
Tim Hallb9b515c2020-11-01 21:27:19 +0000281 rng = lr_graph.get_or_create_range(tens, cpu_tensor_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100282 rng.mark_usage(end_time)
283
284 # Add subgraph to set of processed subgraphs
285 lr_graph.processed_subgraphs.add(sg)
286 return lr_graph
Tim Halld8339a72021-05-27 18:49:40 +0100287
288
289def create_linear_live_range_graph(sg, target_mem_area, target_mem_type_set, lr_graph):
290 assert lr_graph is not None
291 sg_time = lr_graph.current_time
292 for ps in sg.passes:
293 for tens in ps.inputs + ps.outputs + ps.intermediates:
294 if tens.purpose == TensorPurpose.Weights or tensor_should_be_ignored(
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200295 tens, target_mem_area, target_mem_type_set
Tim Halld8339a72021-05-27 18:49:40 +0100296 ):
297 continue
Tim Halld8339a72021-05-27 18:49:40 +0100298 rng = lr_graph.get_or_create_range(tens)
299 rng.mark_usage(sg_time)
300
Jacob Bohlin98bfecd2021-06-21 17:22:20 +0200301 for _, op_info in sg.schedule.cost_map.items():
Tim Halld784af72021-06-08 21:25:57 +0100302 for tensor in [op_info.npu_weights_tensor, op_info.npu_scales_tensor]:
Fredrik Svedberg0ae28482021-10-27 13:58:03 +0200303 if tensor and not (tensor_should_be_ignored(tensor, target_mem_area, target_mem_type_set)):
Tim Halld784af72021-06-08 21:25:57 +0100304 rng = lr_graph.get_or_create_range(tensor)
305 rng.mark_usage(sg_time)
Tim Halld8339a72021-05-27 18:49:40 +0100306
307 lr_graph.current_time += 1
308 return lr_graph
309
310
311def _extract_live_ranges_from_schedule(sg, target_mem_area, target_mem_type_set, lr_graph):
312 time_for_cascade = {}
313 for sched_op in sg.sched_ops:
314 op_info = sg.schedule.cost_map[sched_op]
315 cascade = op_info.cascade
316 cascade_info = sg.schedule.cascades.get(cascade, None)
317
Johan Alfvén783d3642022-07-19 14:03:27 +0200318 if cascade_info is None:
319 # Op is not part of a cascade, check if the ifm can be overwritten by the ofm
320 merge_elementwise_op_ranges(sg, sched_op, lr_graph, target_mem_area, target_mem_type_set)
321
Tim Halld8339a72021-05-27 18:49:40 +0100322 time_to_set = time_for_cascade.get(cascade, lr_graph.current_time)
323
324 op_info.time_index = time_to_set
325
326 # Mark usage for all tensors related to this Pass
327 ps = sched_op.parent_ps
328 for tens in ps.inputs + ps.outputs + ps.intermediates:
329 if (
330 target_mem_area == MemArea.Sram
331 and cascade_info
332 and tens == ps.ifm_tensor
333 and sched_op in cascade_info.buffers
334 ):
335 # This tensor is a rolling buffer in a cascade and the size of the LiveRange needs to be modified
336 # for enabling temporal memory snapshots without modifying the original Tensor
337 rng = lr_graph.get_or_create_range(tens)
338 rng.set_buffer_size(cascade_info.buffers[sched_op].elements() * sched_op.ifm.dtype.size_in_bytes())
339 elif (
340 tens.purpose == TensorPurpose.Weights
341 or tens.purpose == TensorPurpose.FSBias
342 or tens.mem_type not in target_mem_type_set
343 or tens.mem_area != target_mem_area
344 ):
345 continue
346
347 else:
348 rng = lr_graph.get_or_create_range(tens)
349
350 rng.mark_usage(time_to_set)
351
Rickard Bolinfd8b5002022-05-16 09:11:06 +0000352 for idx, weight_tens in enumerate(op_info.buffered_weight_tensors):
353 if weight_tens.mem_type in target_mem_type_set and weight_tens.mem_area == target_mem_area:
354 rng = lr_graph.get_or_create_range(weight_tens)
355 start_time = time_to_set
356 length = 1
357 if weight_tens.pre_buffer:
358 start_time -= 1
359 length += 1
360 if len(op_info.buffered_weight_tensors) > 1:
361 last_idx = len(op_info.ofm_depth_slices) % len(op_info.buffered_weight_tensors)
362 # Double buffering: reduce end time of the buffer that is not used last
363 if last_idx != idx:
364 length -= 1
365 rng.mark_usage(start_time, length)
Tim Halld8339a72021-05-27 18:49:40 +0100366
367 if time_to_set == lr_graph.current_time:
368 lr_graph.current_time += 2
369
370 if cascade != 0:
371 time_for_cascade[cascade] = time_to_set
372
373 end_time = lr_graph.update_endtime()
374
375 for tens in sg.output_tensors:
376 if tens.mem_type not in target_mem_type_set or tens.mem_area != target_mem_area:
377 continue
378 rng = lr_graph.get_or_create_range(tens)
379 rng.mark_usage(end_time)
380
381 return lr_graph