blob: 7f66579ea643e71fbbdd1bb517ee5b5ddf89976e [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# Wrapping function to do tensor address allocation. That is, assigning addresses to tensors based on what has been
18# worked out from the allowable overlaps that are calculated by the live range analysis.
Tim Hall79d07d22020-04-27 18:20:16 +010019import math
Tim Hall79d07d22020-04-27 18:20:16 +010020
Diego Russoea6111a2020-04-14 18:41:58 +010021import numpy as np
22
23from . import live_range
24from . import numeric_util
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020025from .errors import AllocationError
Tim Hall79d07d22020-04-27 18:20:16 +010026from .greedy_allocation import allocate_live_ranges as greedy_allocate_live_ranges
Louis Verhaard9bfe0f82020-12-03 12:26:25 +010027from .live_range import LiveRangeGraph
Diego Russoe8a10452020-04-21 17:39:10 +010028from .nn_graph import TensorAllocator
29from .tensor import MemArea
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020030from .tensor import MemType
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020031from .tensor import Tensor
Louis Verhaard0b8268a2020-08-05 16:11:29 +020032from .tensor import TensorPurpose
Louis Verhaard9bfe0f82020-12-03 12:26:25 +010033from ethosu import tensor_allocator
Tim Hall79d07d22020-04-27 18:20:16 +010034
35
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020036def linear_allocate_live_ranges(live_ranges, alloc_granularity=Tensor.AllocationQuantum):
Louis Verhaard3c07c972020-05-07 08:12:58 +020037 # Allocates using increasing addresses. Duplicate constant tensors will be allocated to the same address
Tim Hall79d07d22020-04-27 18:20:16 +010038 total_sz = 0
39 allocated_tensors = []
40
Louis Verhaard3c07c972020-05-07 08:12:58 +020041 # just assign increasing addresses, except for duplicates
Tim Hall79d07d22020-04-27 18:20:16 +010042 for tens, lr in live_ranges.ranges.items():
43 if tens in allocated_tensors:
44 continue
45
Louis Verhaard3c07c972020-05-07 08:12:58 +020046 address = total_sz
47 if tens.weight_compression_config is not None:
48 for allocated_tens in allocated_tensors:
49 if allocated_tens.weight_compression_config == tens.weight_compression_config:
50 address = allocated_tens.address
51 break
Louis Verhaard0b8268a2020-08-05 16:11:29 +020052 if tens.purpose == TensorPurpose.LUT:
53 for allocated_tens in allocated_tensors:
54 if allocated_tens.equivalent(tens):
55 address = allocated_tens.address
56 break
Louis Verhaard3c07c972020-05-07 08:12:58 +020057 lr.set_address(address)
Tim Hall79d07d22020-04-27 18:20:16 +010058 allocated_tensors += lr.tensors
Louis Verhaard3c07c972020-05-07 08:12:58 +020059 if address == total_sz:
60 total_sz += numeric_util.round_up(int(math.ceil(lr.size)), alloc_granularity)
Tim Hall79d07d22020-04-27 18:20:16 +010061
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020062 verify_alignment(live_ranges, alloc_granularity)
Tim Hall79d07d22020-04-27 18:20:16 +010063 return total_sz
64
65
Louis Verhaard9bfe0f82020-12-03 12:26:25 +010066def search_allocate_live_ranges(live_ranges: LiveRangeGraph, alloc_granularity: int) -> int:
67 # Allocates using the search-based allocator (implemented in C++)
68 input = []
69 lrs = []
70 lr_set = set()
71 for lr in live_ranges.ranges.values():
72 lr_set.add((lr.start_time, lr.end_time, lr))
73 lr_list = sorted(lr_set)
74 # Create a single array of ints containing start/end/size of the live ranges
75 for start, end, lr in lr_list:
76 input += [start, end, numeric_util.round_up(lr.size, alloc_granularity)]
77 lrs.append(lr)
78 addresses = tensor_allocator.allocate(input, 0)
79 # The result is a list containing the allocated addresses
80 total_sz = 0
81 for lr, address in zip(lrs, addresses):
82 total_sz = max(total_sz, address + lr.size)
83 lr.set_address(address)
84 verify_allocation(live_ranges, alloc_granularity)
85 return total_sz
86
87
88def verify_alignment(live_ranges: LiveRangeGraph, alignment: int):
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020089 for lr in live_ranges.ranges.values():
90 for tens in lr.tensors:
91 if not all(op and op.run_on_npu for op in tens.ops + tens.consumer_list):
92 # This is a CPU tensor, verify alignment
93 if tens.address % alignment != 0:
Michael McGeagh7a6f8432020-12-02 15:29:22 +000094 raise AllocationError(f"Tensor '{tens.name}' not aligned to {alignment} bytes")
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020095
96
Louis Verhaard9bfe0f82020-12-03 12:26:25 +010097def verify_allocation(live_ranges: LiveRangeGraph, alignment: int):
98 lrs = list(live_ranges.ranges.values())
99 for n in lrs:
100 verify_alignment(live_ranges, alignment)
101
102 for m in lrs:
103 if n != m and n.overlaps_ranges(m):
104 overlap, tens_n, tens_m = n.overlaps_address(m)
105 if overlap and not (tens_n.equivalent(tens_m) and tens_n.address == tens_m.address):
106 raise AllocationError(
Michael McGeagh7a6f8432020-12-02 15:29:22 +0000107 f"Overlapping buffers: {n.name}: {tens_n.address} -> {tens_n.address + n.size}"
108 f" and {m.name}: {tens_m.address} -> {tens_m.address + m.size}"
Louis Verhaard9bfe0f82020-12-03 12:26:25 +0100109 )
110
111
Tim Hall79d07d22020-04-27 18:20:16 +0100112def mark_sram_used_for_cascaded_passes(sg, lrs):
113 end_pos = max(ps.time for ps in sg.cascaded_passes) + 2
114 mem_usage = np.zeros(end_pos, dtype=np.int64)
115
116 for tens, rng in lrs.ranges.items():
117 storage_size = tens.storage_size()
118 mem_usage[rng.start_time : rng.end_time] += storage_size
119
120 for cps in sg.cascaded_passes:
121 sram_used = max(mem_usage[cps.time], mem_usage[cps.time + 1])
122 cps.sram_used = sram_used
123 for ps in cps.passes:
124 ps.sram_used = sram_used
125
126
Tim Hallb9b515c2020-11-01 21:27:19 +0000127def print_allocation(lrs, mem_area, mem_type_set, sg, verbose_allocation):
Tim Hall79d07d22020-04-27 18:20:16 +0100128 if verbose_allocation:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200129 if mem_type_set == set((MemType.Permanent_NPU,)) or mem_type_set == set((MemType.Permanent_CPU,)):
Tim Hall79d07d22020-04-27 18:20:16 +0100130 print("allocation for", mem_area, "- constant tensors in", sg.placement.name, "subgraph(s)")
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200131 else:
132 print("allocation for", mem_area, "- non-constant tensors in Cpu and Npu subgraphs")
Louis Verhaard1356c2a2020-09-16 10:25:28 +0200133 mem_usage = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100134 for start_time, start, end, name, end_time in sorted(
135 (
136 lr.start_time,
137 tens.address,
138 tens.address + int(math.ceil(tens.storage_size())),
139 tens.name + " " + str(tens.purpose),
140 lr.end_time,
141 )
142 for tens, lr in lrs.ranges.items()
143 ):
144 name = name.replace("\x00", "")
145 print("%9d: %#12x - %#12x: %3d - %3d %s" % ((end - start), start, end, start_time, end_time, name))
Louis Verhaard1356c2a2020-09-16 10:25:28 +0200146 mem_usage = max(mem_usage, end)
147 print("Memory usage: {} ({:#x}) bytes / {:.1f} KB".format(mem_usage, mem_usage, mem_usage / 1024))
Tim Hall79d07d22020-04-27 18:20:16 +0100148 print()
149
Tim Hall79d07d22020-04-27 18:20:16 +0100150
151def allocate_tensors(
152 nng,
153 sg,
154 arch,
155 mem_area,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200156 mem_type_set,
Tim Hall79d07d22020-04-27 18:20:16 +0100157 tensor_allocator=TensorAllocator.Greedy,
158 verbose_allocation=False,
Tim Hall79d07d22020-04-27 18:20:16 +0100159 lr_graph=None,
Tim Hallb9b515c2020-11-01 21:27:19 +0000160 cpu_tensor_alignment=Tensor.AllocationQuantum,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200161 max_size=None,
162 dry_test=False,
Tim Hall79d07d22020-04-27 18:20:16 +0100163):
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200164 # Allocates addresses to tensors, returns False if tensors could not be fit within max_size
Tim Hall79d07d22020-04-27 18:20:16 +0100165 ignore_subgraph_input_output_tensors = False
166 lrs = live_range.extract_live_ranges_from_cascaded_passes(
167 sg,
168 mem_area,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200169 mem_type_set,
Tim Hall79d07d22020-04-27 18:20:16 +0100170 ignore_subgraph_input_output_tensors=ignore_subgraph_input_output_tensors,
171 lr_graph=lr_graph,
Tim Hallb9b515c2020-11-01 21:27:19 +0000172 cpu_tensor_alignment=cpu_tensor_alignment,
Tim Hall79d07d22020-04-27 18:20:16 +0100173 )
174
175 if lrs.ranges:
176 tens_alloc = tensor_allocator
177 if tens_alloc == TensorAllocator.Greedy:
Tim Hallb9b515c2020-11-01 21:27:19 +0000178 total_sz = greedy_allocate_live_ranges(sg, arch, lrs, mem_area, cpu_tensor_alignment, verbose_allocation)
Louis Verhaard9bfe0f82020-12-03 12:26:25 +0100179 verify_allocation(lrs, cpu_tensor_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100180 elif tens_alloc == TensorAllocator.LinearAlloc:
Tim Hallb9b515c2020-11-01 21:27:19 +0000181 total_sz = linear_allocate_live_ranges(lrs, cpu_tensor_alignment)
Louis Verhaard9bfe0f82020-12-03 12:26:25 +0100182 elif tens_alloc == TensorAllocator.Search:
183 total_sz = search_allocate_live_ranges(lrs, cpu_tensor_alignment)
Tim Hall79d07d22020-04-27 18:20:16 +0100184 else:
185 assert 0
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200186 alloc_ok = max_size is None or total_sz <= max_size
187 if dry_test or not alloc_ok:
188 # Dry test or allocation failed; undo allocation
189 for lr in lrs.ranges.values():
190 lr.set_address(None)
191 return alloc_ok
Tim Hall79d07d22020-04-27 18:20:16 +0100192
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200193 if sg.memory_used.get(mem_area, 0) == 0:
194 sg.memory_used[mem_area] = total_sz
195 else:
196 sg.memory_used[mem_area] += total_sz
197
198 # Keep track of how much should be used for scratch or permanent storage for NPU
199 for mem_type in mem_type_set:
200 if sg.memory_used_per_type.get(mem_type, 0) == 0:
201 sg.memory_used_per_type[mem_type] = total_sz
202 else:
203 sg.memory_used_per_type[mem_type] += total_sz
Tim Hall79d07d22020-04-27 18:20:16 +0100204
205 nng.total_size[mem_area] = nng.total_size.get(mem_area, 0) + sum(tens.storage_size() for tens in lrs.ranges)
206 nng.total_elements[mem_area] = nng.total_elements.get(mem_area, 0) + sum(tens.elements() for tens in lrs.ranges)
207
Tim Hallb9b515c2020-11-01 21:27:19 +0000208 print_allocation(lrs, mem_area, mem_type_set, sg, verbose_allocation)
Tim Hall79d07d22020-04-27 18:20:16 +0100209
210 if mem_area == MemArea.Sram:
211 # Mark Sram usage for all subgraphs
212 for sg_ in nng.subgraphs:
213 mark_sram_used_for_cascaded_passes(sg_, lrs)
214
215 if sg == nng.get_root_subgraph():
216 nng.memory_used = sg.memory_used
217 for mem_area in nng.total_elements.keys():
218 try:
219 nng.bits_per_element[mem_area] = nng.total_size[mem_area] * 8 / nng.total_elements[mem_area]
220 except ZeroDivisionError:
221 nng.bits_per_element[mem_area] = 0.0
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200222 return True