blob: 32eef3020b3c3dcc96a55600b68f07dbfddc254b [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# Contains the main sequencing of the compiler.
Diego Russoea6111a2020-04-14 18:41:58 +010018import time
19
Diego Russoe8a10452020-04-21 17:39:10 +010020from . import extract_npu_subgraphs
Tim Hall79d07d22020-04-27 18:20:16 +010021from . import graph_optimiser
Diego Russoe8a10452020-04-21 17:39:10 +010022from . import high_level_command_stream_generator
Tim Hall79d07d22020-04-27 18:20:16 +010023from . import insert_dma
Diego Russoe8a10452020-04-21 17:39:10 +010024from . import live_range
Louis Verhaard0b8268a2020-08-05 16:11:29 +020025from . import lut
Diego Russoe8a10452020-04-21 17:39:10 +010026from . import mark_tensors
27from . import npu_performance
28from . import npu_serialisation
Tim Hall79d07d22020-04-27 18:20:16 +010029from . import pass_packing
Diego Russoe8a10452020-04-21 17:39:10 +010030from . import register_command_stream_generator
Tim Hall79d07d22020-04-27 18:20:16 +010031from . import scheduler
32from . import tensor_allocation
Tim Hall79d07d22020-04-27 18:20:16 +010033from . import weight_compressor
Tim Halle6ccd872020-11-09 16:46:37 +000034from .debug_database import DebugDatabase
Patrik Gustavssonc0bb8992020-08-11 16:45:35 +020035from .errors import VelaError
Diego Russoe8a10452020-04-21 17:39:10 +010036from .nn_graph import PassPlacement
37from .nn_graph import TensorAllocator
Tim Halle6ccd872020-11-09 16:46:37 +000038from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010039from .rewrite_graph import verify_graph_health
Tim Halle6ccd872020-11-09 16:46:37 +000040from .rewrite_graph import visit_graph_post_order
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020041from .tensor import MemType
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020042from .tensor import Tensor
Tim Hall79d07d22020-04-27 18:20:16 +010043
44
45class CompilerOptions:
46 """Set of options to change compiler behaviour - verbosity, targets, turning off passes.
47
48Note the difference between ArchitectureFeatures and CompilerOptions
49- ArchitectureFeatures is for changing the Ethos-U55 and system architecture
50- CompilerOptions is for changing the behaviour of the compiler
51"""
52
53 def __init__(
54 self,
55 verbose_graph=False,
56 verbose_quantization=False,
57 verbose_packing=False,
58 verbose_tensor_purpose=False,
59 verbose_tensor_format=False,
60 verbose_allocation=False,
61 verbose_high_level_command_stream=False,
62 verbose_register_command_stream=False,
63 verbose_operators=False,
64 show_minimum_possible_allocation=False,
65 show_cpu_operations=False,
66 tensor_allocator=TensorAllocator.Greedy,
67 timing=False,
68 output_dir="outputs",
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020069 allocation_alignment=Tensor.AllocationQuantum,
Tim Hall79d07d22020-04-27 18:20:16 +010070 ):
71
72 self.verbose_graph = verbose_graph
73 self.verbose_quantization = verbose_quantization
74 self.verbose_packing = verbose_packing
75 self.verbose_tensor_purpose = verbose_tensor_purpose
76 self.verbose_tensor_format = verbose_tensor_format
77 self.verbose_allocation = verbose_allocation
78 self.verbose_high_level_command_stream = verbose_high_level_command_stream
79 self.verbose_register_command_stream = verbose_register_command_stream
80 self.verbose_operators = verbose_operators
81 self.show_minimum_possible_allocation = show_minimum_possible_allocation
82 self.show_cpu_operations = show_cpu_operations
83 self.tensor_allocator = tensor_allocator
84 self.timing = timing
85 self.output_dir = output_dir
Jacob Bohlin0628a8c2020-08-28 13:25:14 +020086 self.allocation_alignment = allocation_alignment
Tim Hall79d07d22020-04-27 18:20:16 +010087
88 def __str__(self):
89 return type(self).__name__ + ": " + str(self.__dict__)
90
91 __repr__ = __str__
92
93
Louis Verhaard0b9c9a32020-09-15 14:05:38 +020094def next_sram_factor(alloc_results):
95 # Bisects to find the max SRAM usage that successfully can be fitted with the tensor allocator.
96 # Returns tuple (factor, dry_test), with factor is None (stop) or 0 <= factor <= 1 (next SRAM factor to try),
97 # dry_test is True while still bisecting.
98 upper = 1.0
99 lower = 0.7
100 MAX_ITERATIONS = 8
101 if len(alloc_results) == 0:
102 # First iteration, try max SRAM, keep the result if it succeeds
103 return (upper, False)
104 elif len(alloc_results) == 1:
105 if alloc_results[0]:
106 # The allocator succeeded at first try; stop
107 return (None, False)
108 else:
109 # Start bisecting, try lowerbound SRAM
110 return (lower, True)
111 elif len(alloc_results) > MAX_ITERATIONS:
112 # Stop
113 return (None, False)
114 if not alloc_results[1]:
115 # Allocation at lower failed; search interval 0 - lower
116 upper = lower
117 lower = 0
118 best = lower
119 for success in alloc_results[2:]:
120 middle = (lower + upper) / 2
121 if success:
122 best = max(best, middle)
123 lower = middle
124 else:
125 upper = middle
126 if len(alloc_results) == MAX_ITERATIONS:
127 # Done bisecting; repeat the best match, but not as dry test
128 return (best, False)
129 # Next try; run only as dry test
130 return ((lower + upper) / 2, True)
131
132
Tim Halle6ccd872020-11-09 16:46:37 +0000133def _record_operator(op, arch):
134 if op.type != Op.Const:
135 DebugDatabase.add_source(op)
136
137
Tim Hall79d07d22020-04-27 18:20:16 +0100138def compiler_driver(nng, arch, options, scheduler_options):
139 assert verify_graph_health(nng)
Tim Halle6ccd872020-11-09 16:46:37 +0000140
141 # Pre-optimisation operator tracking
142 for sg in nng.subgraphs:
143 visit_graph_post_order(sg.output_tensors, arch, [], [_record_operator])
144
Tim Hall79d07d22020-04-27 18:20:16 +0100145 nng = graph_optimiser.optimise_graph_a(nng, arch, options.verbose_graph)
146 assert verify_graph_health(nng)
147
148 if options.verbose_quantization:
149 nng.print_graph_with_tensor_quantization()
150
151 nng = graph_optimiser.optimise_graph_b(nng, arch, options.verbose_graph)
152 assert verify_graph_health(nng)
153
154 nng = mark_tensors.mark_tensor_purpose(nng, arch, options.verbose_tensor_purpose)
155 assert verify_graph_health(nng)
156 nng = insert_dma.insert_dma_commands(nng, arch, options.verbose_graph)
157 assert verify_graph_health(nng)
158 pass_packing.pack_into_passes(nng, arch, options.verbose_packing)
159 assert verify_graph_health(nng)
160
161 extract_npu_subgraphs.extract_npu_subgraphs(nng, arch)
162
Tim Hall79d07d22020-04-27 18:20:16 +0100163 assert verify_graph_health(nng)
164 if options.timing:
165 start = time.time()
166
167 # Run the scheduler
168 scheduler.schedule_passes(nng, arch, scheduler_options)
169
170 if options.timing:
171 stop = time.time()
172 print("Scheduling took %f s" % (stop - start))
173 start = time.time()
174
175 # Update the compressed weights now that we have determined the
176 # block config, and calc and pack the scales and biases
177 weight_compressor.update_pass_weight_and_scale_tensors(nng, arch)
178
Tim Hall79d07d22020-04-27 18:20:16 +0100179 # LiveRanges for constant tensors for all Npu subgraphs
180 permanent_storage = arch.permanent_storage_mem_area
181 lr_graph_flash = live_range.LiveRangeGraph()
182
183 # Placeholders for scratch and flash tensors that are common for all Npu subgraphs
184 scratch_tens = None
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200185 scratch_fast_tens = None
Tim Hall79d07d22020-04-27 18:20:16 +0100186 flash_tens = None
187
188 # Calculate live ranges for all constant Npu tensors, in permanent storage
189 for sg in nng.subgraphs:
190 if sg.placement == PassPlacement.Npu:
191 lr_graph_flash = live_range.extract_live_ranges_from_cascaded_passes(
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200192 sg,
193 permanent_storage,
194 MemType.Permanent_NPU,
195 ignore_subgraph_input_output_tensors=True,
196 lr_graph=lr_graph_flash,
Tim Hall79d07d22020-04-27 18:20:16 +0100197 )
198
Tim Hall25f605c2020-05-18 18:04:26 +0100199 if len(nng.subgraphs) > 1:
200 # Allocate all Npu constant tensors to the first Npu subgraph since it is
201 # processed first during serialization into tensors
202 first_npu_sg = nng.subgraphs[1]
203 assert first_npu_sg.placement == PassPlacement.Npu
Tim Hall25f605c2020-05-18 18:04:26 +0100204 tensor_allocation.allocate_tensors(
205 nng,
206 first_npu_sg,
207 arch,
208 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200209 set((MemType.Permanent_NPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200210 tensor_allocator=TensorAllocator.LinearAlloc,
211 verbose_allocation=options.verbose_allocation,
212 show_minimum_possible_allocation=options.show_minimum_possible_allocation,
213 lr_graph=lr_graph_flash,
Tim Hall25f605c2020-05-18 18:04:26 +0100214 )
Tim Hall79d07d22020-04-27 18:20:16 +0100215
216 # Allocate all non-constant tensors to the root, i.e. Cpu, subgraph. This step
217 # will start at the root subgraph's input and traverse from top to bottom. When
218 # it comes across an Npu-op it will extract live ranges for it's corresponding
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200219 # Npu subgraph and add them to the root's live range graph.
220 # The non-constant tensors are stored either in arch.feature_map_storage_mem_area or
221 # arch.fast_storage_mem_area.
222 # When these memory areas are the same, all non-constant tensors are allocated together.
223 # Otherwise they are allocated separately.
224
Tim Hall79d07d22020-04-27 18:20:16 +0100225 root_sg = nng.get_root_subgraph()
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200226
227 alloc_list = []
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200228 feature_maps_in_fast_storage = arch.feature_map_storage_mem_area == arch.fast_storage_mem_area
229 if feature_maps_in_fast_storage:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200230 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))
231 alloc_list.append(mem_alloc_scratch)
232 else:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200233 mem_alloc_scratch_fast = (arch.fast_storage_mem_area, set((MemType.Scratch_fast,)))
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200234 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch,)))
235 # Order is important
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200236 alloc_list.append(mem_alloc_scratch_fast)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200237 alloc_list.append(mem_alloc_scratch)
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200238
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200239 for mem_area, mem_type_set in alloc_list:
240 if feature_maps_in_fast_storage or mem_area != arch.fast_storage_mem_area:
241 tensor_allocation.allocate_tensors(
242 nng,
243 root_sg,
244 arch,
245 mem_area,
246 mem_type_set,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200247 tensor_allocator=options.tensor_allocator,
248 verbose_allocation=options.verbose_allocation,
249 show_minimum_possible_allocation=options.show_minimum_possible_allocation,
250 allocation_alignment=options.allocation_alignment,
251 )
252 else:
253 # For the case where scratch_fast != scratch: attempt to place feature maps used between
254 # cascaded passes in fast storage. Bisection is used to find the max possible usage of SRAM.
255 alloc_results = []
256 while True:
257 assert len(alloc_results) < 10, "Infinite allocator loop"
258 sram_factor, dry_test = next_sram_factor(alloc_results)
259 if sram_factor is None:
260 break
261 # Try to move as many feature maps as possible to SRAM before allocating
262 sram_limit = sram_factor * arch.sram_size
263 for sg in nng.subgraphs:
264 scheduler.use_fast_storage_for_feature_maps(sg, sram_limit, arch)
265 alloc_success = tensor_allocation.allocate_tensors(
266 nng,
267 root_sg,
268 arch,
269 mem_area,
270 mem_type_set,
271 max_size=arch.sram_size,
272 dry_test=dry_test,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200273 tensor_allocator=options.tensor_allocator,
274 verbose_allocation=options.verbose_allocation,
275 show_minimum_possible_allocation=options.show_minimum_possible_allocation,
276 allocation_alignment=options.allocation_alignment,
277 )
278 if dry_test or not alloc_success:
279 for sg in nng.subgraphs:
280 scheduler.undo_use_fast_storage(sg, arch)
281 alloc_results.append(alloc_success)
282 if not alloc_results[-1]:
283 raise VelaError(
284 "Sram limit {} bytes, has been exceeded by the scratch fast tensor. "
285 "Increasing the value of --weight-estimation-scaling may help to resolve the issue. "
286 "See OPTIONS.md for more information.".format(arch.sram_size)
287 )
Tim Hall79d07d22020-04-27 18:20:16 +0100288
289 # Generate command streams and serialise Npu-ops into tensors
290 for sg in nng.subgraphs:
291 high_level_command_stream_generator.generate_high_level_command_stream(
292 nng, sg, arch, options.verbose_high_level_command_stream
293 )
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200294 lut.optimize_high_level_cmd_stream(sg, arch)
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100295 register_command_stream_generator.generate_register_command_stream_for_sg(
Tim Hall79d07d22020-04-27 18:20:16 +0100296 nng, sg, arch, options.verbose_register_command_stream
297 )
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200298 scratch_tens, scratch_fast_tens, flash_tens = npu_serialisation.serialise_npu_subgraph_into_tensors(
299 nng, sg, arch, scratch_tens, scratch_fast_tens, flash_tens
Tim Hall79d07d22020-04-27 18:20:16 +0100300 )
301
302 npu_serialisation.rewrite_npu_call_ops(nng, root_sg, arch)
303
Jacob Bohlin268394d2020-08-13 13:24:59 +0200304 # Set Scratch and Fast_scratch Tensor size
305 if scratch_tens is not None:
306 scratch_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch, 0)])
307 if scratch_fast_tens is not None:
308 scratch_fast_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch_fast, 0)])
309
Tim Hall79d07d22020-04-27 18:20:16 +0100310 # Allocate all Cpu constant tensors, this is done last because the Npu-ops
311 # have to be serialized into flash and scratch tensors first
312 tensor_allocation.allocate_tensors(
313 nng,
314 root_sg,
315 arch,
316 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200317 set((MemType.Permanent_CPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200318 tensor_allocator=TensorAllocator.LinearAlloc,
319 verbose_allocation=options.verbose_allocation,
320 show_minimum_possible_allocation=options.show_minimum_possible_allocation,
Jacob Bohlin0628a8c2020-08-28 13:25:14 +0200321 allocation_alignment=options.allocation_alignment,
Tim Hall79d07d22020-04-27 18:20:16 +0100322 )
323
324 npu_performance.calc_performance_for_network(nng, arch)