|
| 1 | +import re |
| 2 | + |
| 3 | +from sympy.core import S |
| 4 | +from sympy.core.numbers import Integer |
| 5 | +from sympy.printing.cxx import CXX11CodePrinter |
| 6 | + |
| 7 | +from hls4ml.backends.template import FunctionCallTemplate, LayerConfigTemplate |
| 8 | +from hls4ml.model.layers import SymbolicExpression |
| 9 | + |
| 10 | +# Expression templates |
| 11 | + |
| 12 | +expr_function_template = 'y[{y_index}] = {expr_str};' |
| 13 | + |
| 14 | +expr_include_list = ['hls_math.h', 'nnet_utils/nnet_math.h'] |
| 15 | + |
| 16 | +built_in_luts = ['sin_lut', 'cos_lut'] |
| 17 | + |
| 18 | + |
| 19 | +class HLSCodePrinter(CXX11CodePrinter): |
| 20 | + _ns = 'hls::' |
| 21 | + |
| 22 | + def __init__(self, layer, lut_functions, use_built_in_luts=False, settings=None): |
| 23 | + if lut_functions is not None: |
| 24 | + if use_built_in_luts: |
| 25 | + # Check if user's LUTs override built-in LUTs |
| 26 | + for lut_name in lut_functions.keys(): |
| 27 | + if lut_name in built_in_luts: |
| 28 | + print(f'WARNING: User-specified LUT function {lut_name} overrides built-in LUT function.') |
| 29 | + |
| 30 | + if settings is None: |
| 31 | + settings = {'user_functions': lut_functions} |
| 32 | + else: |
| 33 | + user_functions = settings.get('user_functions', {}) |
| 34 | + user_functions.update(lut_functions) |
| 35 | + settings['user_functions'] = user_functions |
| 36 | + |
| 37 | + super().__init__(settings) |
| 38 | + self.layer = layer |
| 39 | + self.use_built_in_luts = use_built_in_luts |
| 40 | + |
| 41 | + for k in ( |
| 42 | + 'Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma' |
| 43 | + ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh ' |
| 44 | + 'atanh erf erfc loggamma gamma ceiling floor' |
| 45 | + ).split(): |
| 46 | + setattr(HLSCodePrinter, '_print_%s' % k, HLSCodePrinter._print_math) |
| 47 | + |
| 48 | + def _symbol_to_array(self, name): |
| 49 | + return re.sub(r'([a-zA-Z]+)(\d+)', r'\1[\2]', name) |
| 50 | + |
| 51 | + def _wrap_with_type_name(self, expr_str): |
| 52 | + type_name = self.layer.types['result_t'].name |
| 53 | + return f'{type_name}({expr_str})' |
| 54 | + |
| 55 | + def _print_Integer(self, expr): |
| 56 | + int_str = super()._print_Integer(expr) |
| 57 | + return self._wrap_with_type_name(int_str) |
| 58 | + |
| 59 | + def _print_Float(self, flt): |
| 60 | + float_str = super()._print_Float(flt) |
| 61 | + return self._wrap_with_type_name(float_str) |
| 62 | + |
| 63 | + def _print_Rational(self, expr): |
| 64 | + p, q = int(expr.p), int(expr.q) |
| 65 | + p_q_str = f'{p}.0/{q}.0' |
| 66 | + return self._wrap_with_type_name(p_q_str) |
| 67 | + |
| 68 | + def _print_Pow(self, expr): |
| 69 | + type_name = self.layer.types['result_t'].name |
| 70 | + type_precision = self.layer.types['result_t'].precision |
| 71 | + if isinstance(expr.exp, Integer): |
| 72 | + l_brac, r_brac = ('(', ')') if len(expr.base.args) > 1 else ('', '') |
| 73 | + if expr.exp > 1: |
| 74 | + return ( |
| 75 | + '(' |
| 76 | + + '*'.join([l_brac + self._symbol_to_array(self._print(expr.base)) + r_brac for _ in range(expr.exp)]) |
| 77 | + + ')' |
| 78 | + ) |
| 79 | + elif expr.exp == -1: # 1/x |
| 80 | + base = l_brac + self._symbol_to_array(self._print(expr.base)) + r_brac |
| 81 | + return f'hls::recip<{type_precision.width}, {type_precision.integer}>(({type_name}){base})' |
| 82 | + else: |
| 83 | + return super()._print_Pow(expr) |
| 84 | + else: |
| 85 | + base = self._print(expr.base) |
| 86 | + if expr.exp == 0.5: |
| 87 | + return f'{self._ns}sqrt<{type_precision.width}, {type_precision.integer}>(({type_name})({base}))' |
| 88 | + elif expr.exp == S.One / 3: |
| 89 | + return f'{self._ns}cbrt<{type_precision.width}, {type_precision.integer}>(({type_name})({base}))' |
| 90 | + else: |
| 91 | + exp = self._print(expr.exp) |
| 92 | + return f'{self._ns}pow<{type_precision.width}, {type_precision.integer}>(({type_name})({base}), {exp})' |
| 93 | + |
| 94 | + def _print_math(self, expr): |
| 95 | + name = self.known_functions[expr.__class__.__name__] |
| 96 | + if not isinstance(name, str): |
| 97 | + for cb, fname in name: |
| 98 | + if cb(*expr.args): |
| 99 | + name = fname |
| 100 | + break |
| 101 | + else: |
| 102 | + raise ValueError("No matching printer") |
| 103 | + |
| 104 | + # Setting precision of math functions required some rethinking |
| 105 | + # Doing e.g., hls::pow<x.width, x.iwidth>(x, y) passes C sim, but fails synthesis, need to use hls::pow<16,6>(x,y) |
| 106 | + type_name = self.layer.types['result_t'].name |
| 107 | + type_precision = self.layer.types['result_t'].precision |
| 108 | + template = f'<{type_precision.width}, {type_precision.integer}>' |
| 109 | + cast = f'({type_name})' |
| 110 | + args = ', '.join(map(lambda arg: self._print(arg), expr.args)) |
| 111 | + |
| 112 | + if self.use_built_in_luts and name + '_lut' in built_in_luts: |
| 113 | + ns = 'nnet::' |
| 114 | + name = name + '_lut' |
| 115 | + template = f'<{type_name}>' |
| 116 | + else: |
| 117 | + ns = self._ns |
| 118 | + |
| 119 | + return f'{ns}{name}{template}({cast}({args}))' |
| 120 | + |
| 121 | + def _print_Symbol(self, expr): |
| 122 | + name = super()._print_Symbol(expr) |
| 123 | + return self._symbol_to_array(name) |
| 124 | + |
| 125 | + |
| 126 | +class ExpressionFunctionTemplate(FunctionCallTemplate): |
| 127 | + def __init__(self): |
| 128 | + super().__init__(SymbolicExpression, include_header=expr_include_list) |
| 129 | + self.template = expr_function_template |
| 130 | + |
| 131 | + def format(self, node): |
| 132 | + params = self._default_function_params(node) |
| 133 | + |
| 134 | + lut_functions = {lut_fun.name: lut_fun.name for lut_fun in params['lut_functions']} |
| 135 | + printer = HLSCodePrinter(node, lut_functions=lut_functions, use_built_in_luts=node.attributes['use_built_in_luts']) |
| 136 | + |
| 137 | + fn_templates = [] |
| 138 | + for i, expr in enumerate(node.attributes['expression']): |
| 139 | + params['expr_str'] = printer.doprint(expr) |
| 140 | + params['y_index'] = str(i) |
| 141 | + fn_templates.append(self.template.format(**params)) |
| 142 | + |
| 143 | + return fn_templates |
| 144 | + |
| 145 | + |
| 146 | +class ExpressionConfigTemplate(LayerConfigTemplate): |
| 147 | + def __init__(self): |
| 148 | + super().__init__(SymbolicExpression) |
| 149 | + |
| 150 | + def format(self, node): |
| 151 | + params = self._default_config_params(node) |
| 152 | + |
| 153 | + lut_defs = [] |
| 154 | + for lut_fun in params['lut_functions']: |
| 155 | + type_name = params['result_t'].name |
| 156 | + if lut_fun.math_func in ['sinpi', 'cospi', 'sin', 'cos', 'asin', 'acos', 'atan', 'atan2']: |
| 157 | + # We have return type overrides for these functions |
| 158 | + namespace = 'nnet::' |
| 159 | + else: |
| 160 | + namespace = 'hls::' |
| 161 | + lut_def = ( |
| 162 | + f'nnet::lookup_table<{type_name}, ' |
| 163 | + f'{lut_fun.table_size}, ' |
| 164 | + f'{namespace}' |
| 165 | + f'{lut_fun.math_func}> ' |
| 166 | + f'{lut_fun.name}' |
| 167 | + f'({lut_fun.range_start}, ' |
| 168 | + f'{lut_fun.range_end});' |
| 169 | + ) |
| 170 | + lut_defs.append(lut_def) |
| 171 | + |
| 172 | + return '\n'.join(lut_defs) |
0 commit comments