Skip to content

Commit 46bb486

Browse files
authored
☢️ Libero backend for rad-hard PolarFire line of FPGAs (#1240)
* Initial implementation of Libero backend for PolarFire line of FPGAs * Fix writing of overflow and saturation modes in fixpt * Fix strategy choices * Use FIFOs for top function arguments * Fix FIFO write * Incomplete support for compile() * Full support for local compile() * Fix formatting * Delete build_lib.sh
1 parent 78627c9 commit 46bb486

33 files changed

+5244
-0
lines changed

hls4ml/backends/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from hls4ml.backends.backend import Backend, get_available_backends, get_backend, register_backend # noqa: F401
22
from hls4ml.backends.fpga.fpga_backend import FPGABackend # noqa: F401
3+
from hls4ml.backends.libero.libero_backend import LiberoBackend
34
from hls4ml.backends.oneapi.oneapi_backend import OneAPIBackend
45
from hls4ml.backends.plugin_loader import load_backend_plugins
56
from hls4ml.backends.quartus.quartus_backend import QuartusBackend
@@ -21,6 +22,7 @@ def _register_builtin_backends():
2122
register_backend('Catapult', CatapultBackend)
2223
register_backend('SymbolicExpression', SymbolicExpressionBackend)
2324
register_backend('oneAPI', OneAPIBackend)
25+
register_backend('Libero', LiberoBackend)
2426

2527

2628
_register_builtin_backends()

hls4ml/backends/libero/__init__.py

Whitespace-only changes.
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
import os
2+
import subprocess
3+
import sys
4+
from pathlib import Path
5+
6+
from hls4ml.backends import FPGABackend
7+
from hls4ml.model.attributes import ChoiceAttribute
8+
from hls4ml.model.flow import register_flow
9+
from hls4ml.model.layers import Dense, Layer
10+
from hls4ml.model.optimizer import layer_optimizer
11+
from hls4ml.model.types import StructWrapperVariable
12+
from hls4ml.report import parse_libero_report
13+
14+
15+
class LiberoBackend(FPGABackend):
16+
def __init__(self):
17+
super().__init__(name='Libero')
18+
self._register_layer_attributes()
19+
self._register_flows()
20+
21+
def _register_layer_attributes(self):
22+
strategy_layers = [
23+
Dense,
24+
]
25+
26+
for layer in strategy_layers:
27+
attrs = self.attribute_map.get(layer, [])
28+
attrs.append(
29+
ChoiceAttribute(
30+
'strategy',
31+
choices=['latency', 'resource'],
32+
default='latency',
33+
)
34+
)
35+
self.attribute_map[layer] = attrs
36+
37+
def _register_flows(self):
38+
initializers = self._get_layer_initializers()
39+
init_flow = register_flow('init_layers', initializers, requires=['optimize'], backend=self.name)
40+
41+
libero_types = [
42+
'libero:transform_types',
43+
'libero:set_pipeline_style',
44+
]
45+
libero_types_flow = register_flow('specific_types', libero_types, requires=[init_flow], backend=self.name)
46+
47+
template_flow = register_flow('apply_templates', self._get_layer_templates, requires=[init_flow], backend=self.name)
48+
49+
writer_passes = ['make_stamp', 'libero:write_hls']
50+
self._writer_flow = register_flow('write', writer_passes, requires=['libero:ip'], backend=self.name)
51+
52+
ip_flow_requirements = [
53+
'optimize',
54+
init_flow,
55+
libero_types_flow,
56+
template_flow,
57+
]
58+
59+
self._default_flow = register_flow('ip', None, requires=ip_flow_requirements, backend=self.name)
60+
61+
def get_default_flow(self):
62+
return self._default_flow
63+
64+
def get_writer_flow(self):
65+
return self._writer_flow
66+
67+
def create_initial_config(
68+
self,
69+
fpga_family='PolarFire',
70+
part='MPF300',
71+
board='hw_only',
72+
clock_period=5,
73+
io_type='io_parallel',
74+
smarthls_path=None,
75+
namespace=None,
76+
write_weights_txt=True,
77+
write_tar=False,
78+
**_,
79+
):
80+
"""Create initial configuration of the Libero backend.
81+
82+
Args:
83+
fpga_family (str, optional): The FPGA family to be used. Defaults to 'PolarFire'.
84+
part (str, optional): The FPGA part to be used. Defaults to 'MPF300'.
85+
board (str, optional): The target board. Defaults to 'hw_only'.
86+
clock_period (int, optional): The clock period. Defaults to 5.
87+
io_type (str, optional): Type of implementation used. One of
88+
'io_parallel' or 'io_stream'. Defaults to 'io_parallel'.
89+
smarthls_path (str, optional): Path to SmartHLS installation (part of Libero installation).
90+
For example: /opt/microchip/Libero_SoC_v2024.2/SmartHLS-2024.2/SmartHLS
91+
If None, installation path will be inferred from the location of ``shls`` binary. Defaults to None.
92+
namespace (str, optional): If defined, place all generated code within a namespace. Defaults to None.
93+
write_weights_txt (bool, optional): If True, writes weights to .txt files which speeds up compilation.
94+
Defaults to True.
95+
write_tar (bool, optional): If True, compresses the output directory into a .tar.gz file. Defaults to False.
96+
97+
Returns:
98+
dict: initial configuration.
99+
"""
100+
101+
config = {}
102+
103+
config['FPGAFamily'] = fpga_family if fpga_family is not None else 'PolarFire'
104+
config['Part'] = part if part is not None else 'MPF300'
105+
config['Board'] = board if board is not None else 'hw_only'
106+
config['ClockPeriod'] = clock_period if clock_period is not None else 5
107+
config['IOType'] = io_type if io_type is not None else 'io_parallel'
108+
config['SmartHLSPath'] = self._find_smarthls_path(smarthls_path)
109+
config['HLSConfig'] = {}
110+
config['WriterConfig'] = {
111+
'Namespace': namespace,
112+
'WriteWeightsTxt': write_weights_txt,
113+
'WriteTar': write_tar,
114+
}
115+
116+
return config
117+
118+
def _find_smarthls_path(self, smarthls_path):
119+
if smarthls_path is None:
120+
shls_path = subprocess.check_output(['which', 'shls']).decode('utf-8').strip()
121+
smarthls_path = Path(shls_path).parent.parent
122+
else:
123+
if not isinstance(smarthls_path, Path):
124+
smarthls_path = Path(smarthls_path)
125+
126+
return smarthls_path
127+
128+
def _run_shls_cmd(self, cmd_name, cwd, skip=True):
129+
if skip:
130+
flag = '-s'
131+
else:
132+
flag = '-a'
133+
ret_val = subprocess.run(
134+
['shls', flag, cmd_name],
135+
shell=False,
136+
check=True,
137+
stdout=sys.stdout,
138+
stderr=sys.stderr,
139+
cwd=cwd,
140+
)
141+
return ret_val
142+
143+
def compile(self, model):
144+
"""Compile the generated project that can be linked into Python runtime.
145+
146+
Args:
147+
model (ModelGraph): Model to compile.
148+
149+
Raises:
150+
Exception: If the project failed to compile
151+
152+
Returns:
153+
string: Returns the name of the compiled library.
154+
"""
155+
156+
lib_name = None
157+
158+
# This is a bit hacky, we can't change the Makefile used to run the regular build(), so we have to swap the file
159+
# to do the compile(). Alternative was to use environment variables.
160+
out_dir = model.config.get_output_dir()
161+
162+
makefile_path = os.path.join(out_dir, 'Makefile')
163+
os.rename(makefile_path, makefile_path + '.build')
164+
os.rename(makefile_path + '.compile', makefile_path)
165+
ret_val = self._run_shls_cmd('sw_compile', out_dir, skip=True)
166+
os.rename(makefile_path, makefile_path + '.compile')
167+
os.rename(makefile_path + '.build', makefile_path)
168+
169+
if ret_val.returncode != 0:
170+
print(ret_val.stdout)
171+
raise Exception(f'Failed to compile project "{model.config.get_project_name()}"')
172+
lib_name = f'{out_dir}/hls_output/.hls/{model.config.get_project_name()}.sw_binary'
173+
174+
return lib_name
175+
176+
def build(
177+
self,
178+
model,
179+
reset=False,
180+
skip_preqs=True,
181+
sw_compile=True,
182+
hw=True,
183+
cosim=False,
184+
rtl_synth=False,
185+
fpga=False,
186+
**kwargs,
187+
):
188+
"""Build the model using Libero suite and SmartHLS compiler. Additional arguments passed to the function in form of
189+
`<arg>=True` will be passed as an argument to the `shls` command. See SmartHLS user guide for list of possible
190+
command line options.
191+
192+
Args:
193+
model (ModelGraph): Model to build
194+
reset (bool, optional): Clean up any existing files. Defaults to False.
195+
skip_preqs(bool, optional): Skip any prerequisite step that is outdated. Defaults to False.
196+
sw_compile (bool, optional): Compile the generated HLS in software. Defaults to True.
197+
hw (bool, optional): Compile the software to hardware, producing a set of Verilog HDL files. Defaults to True.
198+
cosim (bool, optional): Run co-simulation. Defaults to False.
199+
rtl_synth (bool, optional): Run RTL synthesis for resource results. This will take less time than `fpga`.
200+
Defaults to False.
201+
fpga (bool, optional): Synthesize the generated hardware to target FPGA. This runs RTL synthesis and
202+
place-and-route for resource and timing results. Defaults to False.
203+
204+
Raises:
205+
Exception: Raised if the `shls` command has not been found
206+
CalledProcessError: Raised if SmartHLS returns non-zero code for any of the commands executed
207+
208+
Returns:
209+
dict: Detailed report produced by SmartHLS.
210+
"""
211+
if 'linux' in sys.platform:
212+
found = os.system('command -v shls > /dev/null')
213+
if found != 0:
214+
raise Exception('Libero/SmartHLS installation not found. Make sure "shls" is on PATH.')
215+
216+
cwd = model.config.get_output_dir()
217+
218+
if reset:
219+
self._run_shls_cmd('clean', cwd, skip_preqs)
220+
if sw_compile:
221+
self._run_shls_cmd('sw_compile', cwd, skip_preqs)
222+
if hw:
223+
self._run_shls_cmd('hw', cwd, skip_preqs)
224+
if cosim:
225+
self._run_shls_cmd('cosim', cwd, skip_preqs)
226+
if rtl_synth:
227+
self._run_shls_cmd('rtl_synth', cwd, skip_preqs)
228+
if fpga:
229+
self._run_shls_cmd('fpga', cwd, skip_preqs)
230+
231+
for arg_name, arg_val in kwargs.items():
232+
if arg_val:
233+
self._run_shls_cmd(arg_name, cwd, skip_preqs)
234+
235+
return parse_libero_report(model.config.get_output_dir())
236+
237+
@layer_optimizer(Layer)
238+
def init_base_layer(self, layer):
239+
reuse_factor = layer.model.config.get_reuse_factor(layer)
240+
layer.set_attr('reuse_factor', reuse_factor)
241+
if layer.name in layer.model.inputs + layer.model.outputs:
242+
for out_name, out_var in layer.variables.items():
243+
new_out_var = StructWrapperVariable(out_var)
244+
layer.set_attr(out_name, new_out_var)
245+
246+
@layer_optimizer(Dense)
247+
def init_dense(self, layer):
248+
if layer.model.config.is_resource_strategy(layer):
249+
n_in, n_out = self.get_layer_mult_size(layer)
250+
self.set_target_reuse_factor(layer)
251+
self.set_closest_reuse_factor(layer, n_in, n_out)
252+
layer.set_attr('strategy', 'resource')
253+
else:
254+
layer.set_attr('strategy', 'latency')

0 commit comments

Comments
 (0)