blob: a2b20e474134743680c7c37dbab3ca7d1fa2f8a5 [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
Tim Hallc8a73862020-10-27 12:43:14 +000049- ArchitectureFeatures is for changing the Ethos-U and system architecture
Tim Hall79d07d22020-04-27 18:20:16 +010050- 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,
Tim Hall79d07d22020-04-27 18:20:16 +010064 show_cpu_operations=False,
65 tensor_allocator=TensorAllocator.Greedy,
66 timing=False,
67 output_dir="outputs",
Tim Hallb9b515c2020-11-01 21:27:19 +000068 cpu_tensor_alignment=Tensor.AllocationQuantum,
Tim Hall79d07d22020-04-27 18:20:16 +010069 ):
70
71 self.verbose_graph = verbose_graph
72 self.verbose_quantization = verbose_quantization
73 self.verbose_packing = verbose_packing
74 self.verbose_tensor_purpose = verbose_tensor_purpose
75 self.verbose_tensor_format = verbose_tensor_format
76 self.verbose_allocation = verbose_allocation
77 self.verbose_high_level_command_stream = verbose_high_level_command_stream
78 self.verbose_register_command_stream = verbose_register_command_stream
79 self.verbose_operators = verbose_operators
Tim Hall79d07d22020-04-27 18:20:16 +010080 self.show_cpu_operations = show_cpu_operations
81 self.tensor_allocator = tensor_allocator
82 self.timing = timing
83 self.output_dir = output_dir
Tim Hallb9b515c2020-11-01 21:27:19 +000084 self.cpu_tensor_alignment = cpu_tensor_alignment
Tim Hall79d07d22020-04-27 18:20:16 +010085
86 def __str__(self):
87 return type(self).__name__ + ": " + str(self.__dict__)
88
89 __repr__ = __str__
90
91
Louis Verhaard0b9c9a32020-09-15 14:05:38 +020092def next_sram_factor(alloc_results):
93 # Bisects to find the max SRAM usage that successfully can be fitted with the tensor allocator.
94 # Returns tuple (factor, dry_test), with factor is None (stop) or 0 <= factor <= 1 (next SRAM factor to try),
95 # dry_test is True while still bisecting.
96 upper = 1.0
97 lower = 0.7
98 MAX_ITERATIONS = 8
99 if len(alloc_results) == 0:
100 # First iteration, try max SRAM, keep the result if it succeeds
101 return (upper, False)
102 elif len(alloc_results) == 1:
103 if alloc_results[0]:
104 # The allocator succeeded at first try; stop
105 return (None, False)
106 else:
107 # Start bisecting, try lowerbound SRAM
108 return (lower, True)
109 elif len(alloc_results) > MAX_ITERATIONS:
110 # Stop
111 return (None, False)
112 if not alloc_results[1]:
113 # Allocation at lower failed; search interval 0 - lower
114 upper = lower
115 lower = 0
116 best = lower
117 for success in alloc_results[2:]:
118 middle = (lower + upper) / 2
119 if success:
120 best = max(best, middle)
121 lower = middle
122 else:
123 upper = middle
124 if len(alloc_results) == MAX_ITERATIONS:
125 # Done bisecting; repeat the best match, but not as dry test
126 return (best, False)
127 # Next try; run only as dry test
128 return ((lower + upper) / 2, True)
129
130
Tim Halle6ccd872020-11-09 16:46:37 +0000131def _record_operator(op, arch):
132 if op.type != Op.Const:
133 DebugDatabase.add_source(op)
134
135
Tim Hall79d07d22020-04-27 18:20:16 +0100136def compiler_driver(nng, arch, options, scheduler_options):
137 assert verify_graph_health(nng)
Tim Halle6ccd872020-11-09 16:46:37 +0000138
139 # Pre-optimisation operator tracking
140 for sg in nng.subgraphs:
141 visit_graph_post_order(sg.output_tensors, arch, [], [_record_operator])
142
Tim Hall79d07d22020-04-27 18:20:16 +0100143 nng = graph_optimiser.optimise_graph_a(nng, arch, options.verbose_graph)
144 assert verify_graph_health(nng)
145
146 if options.verbose_quantization:
147 nng.print_graph_with_tensor_quantization()
148
149 nng = graph_optimiser.optimise_graph_b(nng, arch, options.verbose_graph)
150 assert verify_graph_health(nng)
151
152 nng = mark_tensors.mark_tensor_purpose(nng, arch, options.verbose_tensor_purpose)
153 assert verify_graph_health(nng)
154 nng = insert_dma.insert_dma_commands(nng, arch, options.verbose_graph)
155 assert verify_graph_health(nng)
156 pass_packing.pack_into_passes(nng, arch, options.verbose_packing)
157 assert verify_graph_health(nng)
158
159 extract_npu_subgraphs.extract_npu_subgraphs(nng, arch)
160
Tim Hall79d07d22020-04-27 18:20:16 +0100161 assert verify_graph_health(nng)
162 if options.timing:
163 start = time.time()
164
165 # Run the scheduler
166 scheduler.schedule_passes(nng, arch, scheduler_options)
167
168 if options.timing:
169 stop = time.time()
170 print("Scheduling took %f s" % (stop - start))
171 start = time.time()
172
173 # Update the compressed weights now that we have determined the
174 # block config, and calc and pack the scales and biases
175 weight_compressor.update_pass_weight_and_scale_tensors(nng, arch)
176
Tim Hall79d07d22020-04-27 18:20:16 +0100177 # LiveRanges for constant tensors for all Npu subgraphs
178 permanent_storage = arch.permanent_storage_mem_area
179 lr_graph_flash = live_range.LiveRangeGraph()
180
181 # Placeholders for scratch and flash tensors that are common for all Npu subgraphs
182 scratch_tens = None
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200183 scratch_fast_tens = None
Tim Hall79d07d22020-04-27 18:20:16 +0100184 flash_tens = None
185
186 # Calculate live ranges for all constant Npu tensors, in permanent storage
187 for sg in nng.subgraphs:
188 if sg.placement == PassPlacement.Npu:
189 lr_graph_flash = live_range.extract_live_ranges_from_cascaded_passes(
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200190 sg,
191 permanent_storage,
192 MemType.Permanent_NPU,
193 ignore_subgraph_input_output_tensors=True,
194 lr_graph=lr_graph_flash,
Tim Hall79d07d22020-04-27 18:20:16 +0100195 )
196
Tim Hall25f605c2020-05-18 18:04:26 +0100197 if len(nng.subgraphs) > 1:
198 # Allocate all Npu constant tensors to the first Npu subgraph since it is
199 # processed first during serialization into tensors
200 first_npu_sg = nng.subgraphs[1]
201 assert first_npu_sg.placement == PassPlacement.Npu
Tim Hall25f605c2020-05-18 18:04:26 +0100202 tensor_allocation.allocate_tensors(
203 nng,
204 first_npu_sg,
205 arch,
206 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200207 set((MemType.Permanent_NPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200208 tensor_allocator=TensorAllocator.LinearAlloc,
209 verbose_allocation=options.verbose_allocation,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200210 lr_graph=lr_graph_flash,
Tim Hall25f605c2020-05-18 18:04:26 +0100211 )
Tim Hall79d07d22020-04-27 18:20:16 +0100212
213 # Allocate all non-constant tensors to the root, i.e. Cpu, subgraph. This step
214 # will start at the root subgraph's input and traverse from top to bottom. When
215 # it comes across an Npu-op it will extract live ranges for it's corresponding
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200216 # Npu subgraph and add them to the root's live range graph.
217 # The non-constant tensors are stored either in arch.feature_map_storage_mem_area or
218 # arch.fast_storage_mem_area.
219 # When these memory areas are the same, all non-constant tensors are allocated together.
220 # Otherwise they are allocated separately.
221
Tim Hall79d07d22020-04-27 18:20:16 +0100222 root_sg = nng.get_root_subgraph()
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200223
224 alloc_list = []
Tim Hall1bd531d2020-11-01 20:59:36 +0000225 if arch.is_spilling_enabled():
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200226 mem_alloc_scratch_fast = (arch.fast_storage_mem_area, set((MemType.Scratch_fast,)))
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200227 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch,)))
228 # Order is important
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200229 alloc_list.append(mem_alloc_scratch_fast)
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200230 alloc_list.append(mem_alloc_scratch)
Tim Hall1bd531d2020-11-01 20:59:36 +0000231 else:
232 mem_alloc_scratch = (arch.feature_map_storage_mem_area, set((MemType.Scratch, MemType.Scratch_fast)))
233 alloc_list.append(mem_alloc_scratch)
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200234
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200235 for mem_area, mem_type_set in alloc_list:
Tim Hall1bd531d2020-11-01 20:59:36 +0000236 if arch.is_spilling_enabled() and mem_area == arch.fast_storage_mem_area:
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200237 # For the case where scratch_fast != scratch: attempt to place feature maps used between
238 # cascaded passes in fast storage. Bisection is used to find the max possible usage of SRAM.
239 alloc_results = []
240 while True:
241 assert len(alloc_results) < 10, "Infinite allocator loop"
242 sram_factor, dry_test = next_sram_factor(alloc_results)
243 if sram_factor is None:
244 break
245 # Try to move as many feature maps as possible to SRAM before allocating
246 sram_limit = sram_factor * arch.sram_size
247 for sg in nng.subgraphs:
248 scheduler.use_fast_storage_for_feature_maps(sg, sram_limit, arch)
249 alloc_success = tensor_allocation.allocate_tensors(
250 nng,
251 root_sg,
252 arch,
253 mem_area,
254 mem_type_set,
255 max_size=arch.sram_size,
256 dry_test=dry_test,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200257 tensor_allocator=options.tensor_allocator,
258 verbose_allocation=options.verbose_allocation,
Tim Hallb9b515c2020-11-01 21:27:19 +0000259 cpu_tensor_alignment=options.cpu_tensor_alignment,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200260 )
261 if dry_test or not alloc_success:
262 for sg in nng.subgraphs:
263 scheduler.undo_use_fast_storage(sg, arch)
264 alloc_results.append(alloc_success)
265 if not alloc_results[-1]:
266 raise VelaError(
267 "Sram limit {} bytes, has been exceeded by the scratch fast tensor. "
268 "Increasing the value of --weight-estimation-scaling may help to resolve the issue. "
269 "See OPTIONS.md for more information.".format(arch.sram_size)
270 )
Tim Hall1bd531d2020-11-01 20:59:36 +0000271 else:
272 tensor_allocation.allocate_tensors(
273 nng,
274 root_sg,
275 arch,
276 mem_area,
277 mem_type_set,
278 tensor_allocator=options.tensor_allocator,
279 verbose_allocation=options.verbose_allocation,
Tim Hallb9b515c2020-11-01 21:27:19 +0000280 cpu_tensor_alignment=options.cpu_tensor_alignment,
Tim Hall1bd531d2020-11-01 20:59:36 +0000281 )
Tim Hall79d07d22020-04-27 18:20:16 +0100282
283 # Generate command streams and serialise Npu-ops into tensors
284 for sg in nng.subgraphs:
285 high_level_command_stream_generator.generate_high_level_command_stream(
286 nng, sg, arch, options.verbose_high_level_command_stream
287 )
Louis Verhaard0b8268a2020-08-05 16:11:29 +0200288 lut.optimize_high_level_cmd_stream(sg, arch)
Louis Verhaarde8a5a782020-11-02 18:04:27 +0100289 register_command_stream_generator.generate_register_command_stream_for_sg(
Tim Hall79d07d22020-04-27 18:20:16 +0100290 nng, sg, arch, options.verbose_register_command_stream
291 )
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200292 scratch_tens, scratch_fast_tens, flash_tens = npu_serialisation.serialise_npu_subgraph_into_tensors(
293 nng, sg, arch, scratch_tens, scratch_fast_tens, flash_tens
Tim Hall79d07d22020-04-27 18:20:16 +0100294 )
295
296 npu_serialisation.rewrite_npu_call_ops(nng, root_sg, arch)
297
Jacob Bohlin268394d2020-08-13 13:24:59 +0200298 # Set Scratch and Fast_scratch Tensor size
299 if scratch_tens is not None:
300 scratch_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch, 0)])
301 if scratch_fast_tens is not None:
302 scratch_fast_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch_fast, 0)])
303
Tim Hall79d07d22020-04-27 18:20:16 +0100304 # Allocate all Cpu constant tensors, this is done last because the Npu-ops
305 # have to be serialized into flash and scratch tensors first
306 tensor_allocation.allocate_tensors(
307 nng,
308 root_sg,
309 arch,
310 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200311 set((MemType.Permanent_CPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200312 tensor_allocator=TensorAllocator.LinearAlloc,
313 verbose_allocation=options.verbose_allocation,
Tim Hallb9b515c2020-11-01 21:27:19 +0000314 cpu_tensor_alignment=options.cpu_tensor_alignment,
Tim Hall79d07d22020-04-27 18:20:16 +0100315 )
316
317 npu_performance.calc_performance_for_network(nng, arch)