blob: d289209661d5cfdeaf9519861b812dd7d356a1b1 [file] [log] [blame]
wilisa0146c94772023-02-08 09:56:14 +00001# SPDX-FileCopyrightText: Copyright 2020-2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
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.
Rickard Bolinbc6ee582022-11-04 08:24:29 +000016#
Tim Hall79d07d22020-04-27 18:20:16 +010017# Description:
18# Contains the main sequencing of the compiler.
Diego Russoea6111a2020-04-14 18:41:58 +010019import time
20
Diego Russoe8a10452020-04-21 17:39:10 +010021from . import extract_npu_subgraphs
Tim Hall79d07d22020-04-27 18:20:16 +010022from . import graph_optimiser
Diego Russoe8a10452020-04-21 17:39:10 +010023from . import high_level_command_stream_generator
Louis Verhaard1e170182020-11-26 11:42:04 +010024from . import high_level_command_to_npu_op
Diego Russoe8a10452020-04-21 17:39:10 +010025from . import live_range
Louis Verhaard0b8268a2020-08-05 16:11:29 +020026from . import lut
Diego Russoe8a10452020-04-21 17:39:10 +010027from . import mark_tensors
28from . import npu_performance
29from . import npu_serialisation
Tim Hall79d07d22020-04-27 18:20:16 +010030from . import pass_packing
31from . import scheduler
32from . import tensor_allocation
Tim Halle6ccd872020-11-09 16:46:37 +000033from .debug_database import DebugDatabase
Diego Russoe8a10452020-04-21 17:39:10 +010034from .nn_graph import PassPlacement
35from .nn_graph import TensorAllocator
Tim Halle6ccd872020-11-09 16:46:37 +000036from .operation import Op
Diego Russoea6111a2020-04-14 18:41:58 +010037from .rewrite_graph import verify_graph_health
Tim Halle6ccd872020-11-09 16:46:37 +000038from .rewrite_graph import visit_graph_post_order
Tim Halld8339a72021-05-27 18:49:40 +010039from .scheduler import OptimizationStrategy
40from .tensor import MemArea
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
Jonas Ohlssond8575072022-03-30 10:30:25 +020048 Note the difference between ArchitectureFeatures and CompilerOptions
49 - ArchitectureFeatures is for changing the Ethos-U and system architecture
50 - CompilerOptions is for changing the behaviour of the compiler"""
Tim Hall79d07d22020-04-27 18:20:16 +010051
52 def __init__(
53 self,
54 verbose_graph=False,
55 verbose_quantization=False,
56 verbose_packing=False,
57 verbose_tensor_purpose=False,
58 verbose_tensor_format=False,
59 verbose_allocation=False,
60 verbose_high_level_command_stream=False,
61 verbose_register_command_stream=False,
62 verbose_operators=False,
Fredrik Svedbergf5c07c42021-04-23 14:36:42 +020063 verbose_weights=False,
Tim Hallc1be0872022-03-03 17:50:52 +000064 verbose_performance=False,
Tim Hall79d07d22020-04-27 18:20:16 +010065 show_cpu_operations=False,
66 tensor_allocator=TensorAllocator.Greedy,
67 timing=False,
wilisa0146c94772023-02-08 09:56:14 +000068 force_symmetric_int_weights=False,
Tim Hall79d07d22020-04-27 18:20:16 +010069 output_dir="outputs",
Tim Hallb9b515c2020-11-01 21:27:19 +000070 cpu_tensor_alignment=Tensor.AllocationQuantum,
Tim Hallcda4fcb2022-05-19 12:36:58 +010071 hillclimb_max_iterations=None,
Tim Hall79d07d22020-04-27 18:20:16 +010072 ):
73
74 self.verbose_graph = verbose_graph
75 self.verbose_quantization = verbose_quantization
76 self.verbose_packing = verbose_packing
77 self.verbose_tensor_purpose = verbose_tensor_purpose
78 self.verbose_tensor_format = verbose_tensor_format
79 self.verbose_allocation = verbose_allocation
80 self.verbose_high_level_command_stream = verbose_high_level_command_stream
81 self.verbose_register_command_stream = verbose_register_command_stream
82 self.verbose_operators = verbose_operators
Fredrik Svedbergf5c07c42021-04-23 14:36:42 +020083 self.verbose_weights = verbose_weights
Tim Hallc1be0872022-03-03 17:50:52 +000084 self.verbose_performance = verbose_performance
Tim Hall79d07d22020-04-27 18:20:16 +010085 self.show_cpu_operations = show_cpu_operations
86 self.tensor_allocator = tensor_allocator
87 self.timing = timing
wilisa0146c94772023-02-08 09:56:14 +000088 self.force_symmetric_int_weights = force_symmetric_int_weights
Tim Hall79d07d22020-04-27 18:20:16 +010089 self.output_dir = output_dir
Tim Hallb9b515c2020-11-01 21:27:19 +000090 self.cpu_tensor_alignment = cpu_tensor_alignment
Tim Hallcda4fcb2022-05-19 12:36:58 +010091 self.hillclimb_max_iterations = hillclimb_max_iterations
Tim Hall79d07d22020-04-27 18:20:16 +010092
93 def __str__(self):
94 return type(self).__name__ + ": " + str(self.__dict__)
95
96 __repr__ = __str__
97
98
Louis Verhaard0b9c9a32020-09-15 14:05:38 +020099def next_sram_factor(alloc_results):
100 # Bisects to find the max SRAM usage that successfully can be fitted with the tensor allocator.
101 # Returns tuple (factor, dry_test), with factor is None (stop) or 0 <= factor <= 1 (next SRAM factor to try),
102 # dry_test is True while still bisecting.
103 upper = 1.0
104 lower = 0.7
105 MAX_ITERATIONS = 8
106 if len(alloc_results) == 0:
107 # First iteration, try max SRAM, keep the result if it succeeds
108 return (upper, False)
109 elif len(alloc_results) == 1:
110 if alloc_results[0]:
111 # The allocator succeeded at first try; stop
112 return (None, False)
113 else:
114 # Start bisecting, try lowerbound SRAM
115 return (lower, True)
116 elif len(alloc_results) > MAX_ITERATIONS:
117 # Stop
118 return (None, False)
119 if not alloc_results[1]:
120 # Allocation at lower failed; search interval 0 - lower
121 upper = lower
122 lower = 0
123 best = lower
124 for success in alloc_results[2:]:
125 middle = (lower + upper) / 2
126 if success:
127 best = max(best, middle)
128 lower = middle
129 else:
130 upper = middle
131 if len(alloc_results) == MAX_ITERATIONS:
132 # Done bisecting; repeat the best match, but not as dry test
133 return (best, False)
134 # Next try; run only as dry test
135 return ((lower + upper) / 2, True)
136
137
Tim Halle6ccd872020-11-09 16:46:37 +0000138def _record_operator(op, arch):
wilisa0179a89042022-11-02 17:18:43 +0000139 if op.type not in (Op.Const, Op.Placeholder):
Tim Halle6ccd872020-11-09 16:46:37 +0000140 DebugDatabase.add_source(op)
141
142
Tim Halld8339a72021-05-27 18:49:40 +0100143def _check_schedule(nng, arch, scheduler_options):
144 # check sram usage for optimisation strategy
145 sram_usage = nng.get_root_subgraph().memory_used.get(MemArea.Sram)
146 if sram_usage is not None and scheduler_options.optimization_strategy == OptimizationStrategy.Performance:
147 if sram_usage > scheduler_options.optimization_sram_limit:
148 print(
149 f"Warning: SRAM target for arena memory area exceeded."
150 f" Target = {scheduler_options.optimization_sram_limit} Bytes,"
151 f" Actual = {sram_usage} Bytes"
152 )
153
154
wilisa0189a8cdd2022-08-22 16:13:06 +0000155def compiler_driver(nng, arch, options, scheduler_options, network_type, output_basename):
Tim Hall79d07d22020-04-27 18:20:16 +0100156 assert verify_graph_health(nng)
Tim Halle6ccd872020-11-09 16:46:37 +0000157
158 # Pre-optimisation operator tracking
159 for sg in nng.subgraphs:
160 visit_graph_post_order(sg.output_tensors, arch, [], [_record_operator])
161
wilisa0146c94772023-02-08 09:56:14 +0000162 nng = graph_optimiser.optimise_graph(
163 nng, arch, network_type, options.verbose_graph, options.force_symmetric_int_weights
164 )
Tim Hall79d07d22020-04-27 18:20:16 +0100165 assert verify_graph_health(nng)
166
167 if options.verbose_quantization:
168 nng.print_graph_with_tensor_quantization()
169
Tim Hall79d07d22020-04-27 18:20:16 +0100170 nng = mark_tensors.mark_tensor_purpose(nng, arch, options.verbose_tensor_purpose)
171 assert verify_graph_health(nng)
Tim Hall79d07d22020-04-27 18:20:16 +0100172 pass_packing.pack_into_passes(nng, arch, options.verbose_packing)
173 assert verify_graph_health(nng)
174
175 extract_npu_subgraphs.extract_npu_subgraphs(nng, arch)
176
Tim Hall79d07d22020-04-27 18:20:16 +0100177 assert verify_graph_health(nng)
178 if options.timing:
179 start = time.time()
180
181 # Run the scheduler
Tim Halld8339a72021-05-27 18:49:40 +0100182 scheduler.schedule_passes(nng, arch, options, scheduler_options)
183 _check_schedule(nng, arch, scheduler_options)
Tim Hall79d07d22020-04-27 18:20:16 +0100184
185 if options.timing:
186 stop = time.time()
187 print("Scheduling took %f s" % (stop - start))
188 start = time.time()
189
Tim Hall79d07d22020-04-27 18:20:16 +0100190 # LiveRanges for constant tensors for all Npu subgraphs
191 permanent_storage = arch.permanent_storage_mem_area
192 lr_graph_flash = live_range.LiveRangeGraph()
193
194 # Placeholders for scratch and flash tensors that are common for all Npu subgraphs
195 scratch_tens = None
Patrik Gustavsson3ab94522020-06-29 17:36:55 +0200196 scratch_fast_tens = None
Tim Hall79d07d22020-04-27 18:20:16 +0100197 flash_tens = None
198
Dwight Lidman62cdfe52021-10-11 16:39:10 +0200199 # Create list of NPU subgraphs with same order as the list of all subgraphs
200 npu_subgraphs = [sg for sg in nng.subgraphs if sg.placement == PassPlacement.Npu]
Tim Hall79d07d22020-04-27 18:20:16 +0100201
Dwight Lidman62cdfe52021-10-11 16:39:10 +0200202 # Calculate live ranges for all constant Npu tensors, in permanent storage
203 for sg in npu_subgraphs:
204 lr_graph_flash = live_range.create_linear_live_range_graph(
Jonas Ohlssond8575072022-03-30 10:30:25 +0200205 sg,
206 permanent_storage,
207 MemType.Permanent_NPU,
208 lr_graph=lr_graph_flash,
Dwight Lidman62cdfe52021-10-11 16:39:10 +0200209 )
210
211 if npu_subgraphs:
Tim Hall25f605c2020-05-18 18:04:26 +0100212 # Allocate all Npu constant tensors to the first Npu subgraph since it is
213 # processed first during serialization into tensors
Dwight Lidman62cdfe52021-10-11 16:39:10 +0200214 first_npu_sg = npu_subgraphs[0]
Tim Hall25f605c2020-05-18 18:04:26 +0100215 tensor_allocation.allocate_tensors(
216 nng,
217 first_npu_sg,
218 arch,
219 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200220 set((MemType.Permanent_NPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200221 tensor_allocator=TensorAllocator.LinearAlloc,
222 verbose_allocation=options.verbose_allocation,
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200223 lr_graph=lr_graph_flash,
Tim Hall25f605c2020-05-18 18:04:26 +0100224 )
Tim Hall79d07d22020-04-27 18:20:16 +0100225
Tim Hall79d07d22020-04-27 18:20:16 +0100226 root_sg = nng.get_root_subgraph()
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200227
Tim Hall79d07d22020-04-27 18:20:16 +0100228 # Generate command streams and serialise Npu-ops into tensors
Dwight Lidman62cdfe52021-10-11 16:39:10 +0200229 for sg in npu_subgraphs:
230 high_level_command_stream_generator.generate_high_level_command_stream_for_schedule(
231 nng, sg, arch, options.verbose_high_level_command_stream
232 )
233 lut.optimize_high_level_cmd_stream(sg, arch)
234 high_level_command_to_npu_op.generate_register_command_stream_for_sg(
235 nng, sg, arch, options.verbose_register_command_stream
236 )
237 scratch_tens, scratch_fast_tens, flash_tens = npu_serialisation.serialise_npu_subgraph_into_tensors(
238 sg, arch, scratch_tens, scratch_fast_tens, flash_tens
239 )
Tim Hall79d07d22020-04-27 18:20:16 +0100240
Johan Alfvén673683b2022-09-05 09:39:47 +0200241 # Create list of CPU subgraphs with same order as the list of all subgraphs
242 cpu_subgraphs = [sg for sg in nng.subgraphs if sg.placement == PassPlacement.Cpu]
243 for sg in cpu_subgraphs:
244 npu_serialisation.rewrite_npu_call_ops(sg, arch)
Tim Hall79d07d22020-04-27 18:20:16 +0100245
Jacob Bohlin268394d2020-08-13 13:24:59 +0200246 # Set Scratch and Fast_scratch Tensor size
247 if scratch_tens is not None:
248 scratch_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch, 0)])
249 if scratch_fast_tens is not None:
250 scratch_fast_tens.set_all_shapes([root_sg.memory_used_per_type.get(MemType.Scratch_fast, 0)])
251
Tim Hall79d07d22020-04-27 18:20:16 +0100252 # Allocate all Cpu constant tensors, this is done last because the Npu-ops
253 # have to be serialized into flash and scratch tensors first
254 tensor_allocation.allocate_tensors(
255 nng,
256 root_sg,
257 arch,
258 permanent_storage,
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200259 set((MemType.Permanent_CPU,)),
Louis Verhaard0b9c9a32020-09-15 14:05:38 +0200260 tensor_allocator=TensorAllocator.LinearAlloc,
261 verbose_allocation=options.verbose_allocation,
Tim Hallb9b515c2020-11-01 21:27:19 +0000262 cpu_tensor_alignment=options.cpu_tensor_alignment,
Tim Hall79d07d22020-04-27 18:20:16 +0100263 )
264
wilisa0189a8cdd2022-08-22 16:13:06 +0000265 npu_performance.calc_new_performance_for_network(
266 nng, arch, network_type, options.verbose_performance, output_basename
267 )