|
| 1 | +""" |
| 2 | +INTERNAL extension to synthesize a fhe compatible function from verilog code. |
| 3 | +""" |
| 4 | + |
| 5 | +from collections import Counter |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import concrete.fhe.dtypes as fhe_dtypes |
| 9 | +import concrete.fhe.tracing.typing as fhe_typing |
| 10 | +from concrete.fhe.dtypes.integer import Integer |
| 11 | +from concrete.fhe.extensions.synthesis.eval_context import EvalContext |
| 12 | +from concrete.fhe.extensions.synthesis.luts_to_fhe import tlu_circuit_to_mlir |
| 13 | +from concrete.fhe.extensions.synthesis.luts_to_graph import to_graph |
| 14 | +from concrete.fhe.extensions.synthesis.verilog_source import ( |
| 15 | + Ty, |
| 16 | + verilog_from_expression, |
| 17 | + verilog_from_tlu, |
| 18 | +) |
| 19 | +from concrete.fhe.extensions.synthesis.verilog_to_luts import yosys_lut_synthesis |
| 20 | +from concrete.fhe.values.value_description import ValueDescription |
| 21 | + |
| 22 | + |
| 23 | +class FheFunction: |
| 24 | + """Main class to synthesize verilog.""" |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + *, |
| 29 | + verilog, |
| 30 | + name, |
| 31 | + params=None, |
| 32 | + result_name="result", |
| 33 | + yosys_dot_file=False, |
| 34 | + verbose=False, |
| 35 | + ): |
| 36 | + assert params |
| 37 | + self.name = name |
| 38 | + self.verilog = verilog |
| 39 | + if verbose: |
| 40 | + print() |
| 41 | + print(f"Verilog, {name}:") |
| 42 | + print(verilog) |
| 43 | + print() |
| 44 | + if verbose: |
| 45 | + print("Synthesis") |
| 46 | + self.circuit = yosys_lut_synthesis( |
| 47 | + verilog, yosys_dot_file=yosys_dot_file, circuit_name=name |
| 48 | + ) |
| 49 | + if verbose: |
| 50 | + print() |
| 51 | + print(f"TLUs counts, {self.tlu_counts()}:") |
| 52 | + print() |
| 53 | + self.params = params |
| 54 | + self.result_name = result_name |
| 55 | + |
| 56 | + self.mlir = tlu_circuit_to_mlir(self.circuit, self.params, result_name, verbose) |
| 57 | + |
| 58 | + def __call__(self, **kwargs): |
| 59 | + """ |
| 60 | + Evaluate using mlir generation with a direct evaluation context. |
| 61 | +
|
| 62 | + This is useful for testing purpose. |
| 63 | + """ |
| 64 | + args = [] |
| 65 | + for name, type_ in self.params.items(): |
| 66 | + if name == "result": |
| 67 | + continue |
| 68 | + if isinstance(type_, list): |
| 69 | + val = EvalContext.Val( |
| 70 | + kwargs[name], EvalContext.Ty(type_[0].dtype.bit_width, is_tensor=True) |
| 71 | + ) |
| 72 | + else: |
| 73 | + val = EvalContext.Val(kwargs[name], EvalContext.Ty(type_.dtype.bit_width)) |
| 74 | + args.append(val) |
| 75 | + result_ty = self.params["result"] |
| 76 | + if isinstance(result_ty, list): |
| 77 | + eval_ty = EvalContext.Ty(result_ty, is_tensor=True) |
| 78 | + else: |
| 79 | + eval_ty = EvalContext.Ty(result_ty, is_tensor=False) |
| 80 | + result = self.mlir(EvalContext(), eval_ty, args) |
| 81 | + if isinstance(result_ty, list): |
| 82 | + return [r.value for r in result] |
| 83 | + else: |
| 84 | + return result.value |
| 85 | + |
| 86 | + def tlu_counts(self): |
| 87 | + """Count the number of tlus in the synthesized tracer keyed by input precision.""" |
| 88 | + counter = Counter() |
| 89 | + for node in self.circuit.nodes: |
| 90 | + if len(node.arguments) == 1: |
| 91 | + print(node) |
| 92 | + counter.update({len(node.arguments): 1}) |
| 93 | + return dict(sorted(counter.items())) |
| 94 | + |
| 95 | + def is_faster_than_1_tlu(self, reference_costs): |
| 96 | + """Verify that synthesis is faster than the original tlu.""" |
| 97 | + costs = 0 |
| 98 | + for node in self.circuit.nodes: |
| 99 | + zero_cost = len(node.arguments) <= 1 |
| 100 | + if zero_cost: |
| 101 | + # constant or inversion (converted to substraction) |
| 102 | + continue |
| 103 | + else: |
| 104 | + costs += reference_costs[len(node.arguments)] |
| 105 | + try: |
| 106 | + return costs <= reference_costs[self.params["a"].dtype.bit_width] |
| 107 | + except KeyError: |
| 108 | + return True |
| 109 | + |
| 110 | + def graph(self, *, filename=None, view=True, **kwargs): |
| 111 | + """Render the synthesized tracer as a graph.""" |
| 112 | + graph = to_graph(self.name, self.circuit.nodes) |
| 113 | + graph.render(filename=filename, view=view, cleanup=filename is None, **kwargs) |
| 114 | + |
| 115 | + |
| 116 | +def lut(table: 'list[int]', out_type: Optional[ValueDescription] = None, **kwargs): |
| 117 | + """Synthesize a lookup function from a table.""" |
| 118 | + # assert not signed # TODO signed case |
| 119 | + if isinstance(out_type, list): |
| 120 | + msg = "Multi-message output is not supported" |
| 121 | + raise TypeError(msg) |
| 122 | + if out_type: |
| 123 | + assert isinstance(out_type.dtype, Integer) |
| 124 | + v_out_type = Ty( |
| 125 | + bit_width=out_type.dtype.bit_width, |
| 126 | + is_signed=out_type.dtype.is_signed, |
| 127 | + ) |
| 128 | + verilog, v_out_type = verilog_from_tlu(table, signed_input=False, out_type=v_out_type) |
| 129 | + if "name" not in kwargs: |
| 130 | + kwargs.setdefault("name", "lut") |
| 131 | + if "params" not in kwargs: |
| 132 | + dtype = fhe_dtypes.Integer.that_can_represent(len(table) - 1) |
| 133 | + a_ty = getattr(fhe_typing, f"uint{dtype.bit_width}") |
| 134 | + assert a_ty |
| 135 | + kwargs["params"] = {"a": a_ty, "result": out_type} |
| 136 | + return FheFunction(verilog=verilog, **kwargs) |
| 137 | + |
| 138 | + |
| 139 | +def _uniformize_as_list(v): |
| 140 | + return v if isinstance(v, (list, tuple)) else [v] |
| 141 | + |
| 142 | + |
| 143 | +def verilog_expression( |
| 144 | + in_params: 'dict[str, ValueDescription]', expression: str, out_type: ValueDescription, **kwargs |
| 145 | +): |
| 146 | + """Synthesize a lookup function from a verilog function.""" |
| 147 | + result_name = "result" |
| 148 | + if result_name in in_params: |
| 149 | + result_name = f"{result_name}_{hash(expression)}" |
| 150 | + in_params = dict(in_params) |
| 151 | + in_params[result_name] = out_type |
| 152 | + verilog_params = { |
| 153 | + name: Ty( |
| 154 | + bit_width=sum(ty.dtype.bit_width for ty in _uniformize_as_list(type_list)), |
| 155 | + is_signed=any(ty.dtype.is_signed for ty in _uniformize_as_list(type_list)), |
| 156 | + ) |
| 157 | + for name, type_list in in_params.items() |
| 158 | + } |
| 159 | + verilog = verilog_from_expression(verilog_params, expression, result_name) |
| 160 | + if "name" not in kwargs: |
| 161 | + kwargs.setdefault("name", expression) |
| 162 | + return FheFunction(verilog=verilog, params=in_params, result_name=result_name, **kwargs) |
0 commit comments