/
circuit.py
626 lines (500 loc) · 19.2 KB
/
circuit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
"""
Declaration of `Circuit` class.
"""
# pylint: disable=import-error,no-member,no-name-in-module
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
from concrete.compiler import (
CompilationContext,
Parameter,
SimulatedValueDecrypter,
SimulatedValueExporter,
)
from mlir.ir import Module as MlirModule
from ..internal.utils import assert_that
from ..representation import Graph
from .client import Client
from .configuration import Configuration
from .keys import Keys
from .server import Server
from .utils import validate_input_args
from .value import Value
# pylint: enable=import-error,no-member,no-name-in-module
class Circuit:
"""
Circuit class, to combine computation graph, mlir, client and server into a single object.
"""
configuration: Configuration
graph: Graph
mlir_module: MlirModule
compilation_context: CompilationContext
client: Client
server: Server
simulator: Server
def __init__(
self,
graph: Graph,
mlir: MlirModule,
compilation_context: CompilationContext,
configuration: Optional[Configuration] = None,
):
self.configuration = configuration if configuration is not None else Configuration()
self.graph = graph
self.mlir_module = mlir
self.compilation_context = compilation_context
if self.configuration.fhe_simulation:
self.enable_fhe_simulation()
if self.configuration.fhe_execution:
self.enable_fhe_execution()
def __str__(self):
return self.graph.format()
def draw(
self,
*,
horizontal: bool = False,
save_to: Optional[Union[Path, str]] = None,
show: bool = False,
) -> Path:
"""
Draw the graph of the circuit.
That this function requires the python `pygraphviz` package
which itself requires the installation of `graphviz` packages
(see https://pygraphviz.github.io/documentation/stable/install.html)
Args:
horizontal (bool, default = False):
whether to draw horizontally
save_to (Optional[Path], default = None):
path to save the drawing
a temporary file will be used if it's None
show (bool, default = False):
whether to show the drawing using matplotlib
Returns:
Path:
path to the drawing
"""
return self.graph.draw(horizontal=horizontal, save_to=save_to, show=show)
@property
def mlir(self) -> str:
"""Textual representation of the MLIR module.
Returns:
str: textual representation of the MLIR module
"""
return str(self.mlir_module).strip()
def enable_fhe_simulation(self):
"""
Enable FHE simulation.
"""
if not hasattr(self, "simulator"):
self.simulator = Server.create(
self.mlir_module,
self.configuration,
is_simulated=True,
compilation_context=self.compilation_context,
)
def enable_fhe_execution(self):
"""
Enable FHE execution.
"""
if not hasattr(self, "server"):
self.server = Server.create(
self.mlir_module, self.configuration, compilation_context=self.compilation_context
)
keyset_cache_directory = None
if self.configuration.use_insecure_key_cache:
assert_that(self.configuration.enable_unsafe_features)
assert_that(self.configuration.insecure_key_cache_location is not None)
keyset_cache_directory = self.configuration.insecure_key_cache_location
self.client = Client(self.server.client_specs, keyset_cache_directory)
def simulate(self, *args: Any) -> Any:
"""
Simulate execution of the circuit.
Args:
*args (Any):
inputs to the circuit
Returns:
Any:
result of the simulation
"""
if not hasattr(self, "simulator"): # pragma: no cover
self.enable_fhe_simulation()
ordered_validated_args = validate_input_args(self.simulator.client_specs, *args)
exporter = SimulatedValueExporter.new(self.simulator.client_specs.client_parameters)
exported = [
None
if arg is None
else Value(
exporter.export_tensor(position, arg.flatten().tolist(), list(arg.shape))
if isinstance(arg, np.ndarray) and arg.shape != ()
else exporter.export_scalar(position, int(arg))
)
for position, arg in enumerate(ordered_validated_args)
]
results = self.simulator.run(*exported)
if not isinstance(results, tuple):
results = (results,)
decrypter = SimulatedValueDecrypter.new(self.simulator.client_specs.client_parameters)
decrypted = tuple(
decrypter.decrypt(position, result.inner) for position, result in enumerate(results)
)
return decrypted if len(decrypted) != 1 else decrypted[0]
@property
def keys(self) -> Keys:
"""
Get the keys of the circuit.
"""
if not hasattr(self, "client"): # pragma: no cover
self.enable_fhe_execution()
return self.client.keys
@keys.setter
def keys(self, new_keys: Keys):
"""
Set the keys of the circuit.
"""
if not hasattr(self, "client"): # pragma: no cover
self.enable_fhe_execution()
self.client.keys = new_keys
def keygen(
self, force: bool = False, seed: Optional[int] = None, encryption_seed: Optional[int] = None
):
"""
Generate keys required for homomorphic evaluation.
Args:
force (bool, default = False):
whether to generate new keys even if keys are already generated
seed (Optional[int], default = None):
seed for private keys randomness
encryption_seed (Optional[int], default = None):
seed for encryption randomness
"""
if not hasattr(self, "client"): # pragma: no cover
self.enable_fhe_execution()
self.client.keygen(force, seed, encryption_seed)
def encrypt(
self,
*args: Optional[Union[int, np.ndarray, List]],
) -> Optional[Union[Value, Tuple[Optional[Value], ...]]]:
"""
Encrypt argument(s) to for evaluation.
Args:
*args (Optional[Union[int, numpy.ndarray, List]]):
argument(s) for evaluation
Returns:
Optional[Union[Value, Tuple[Optional[Value], ...]]]:
encrypted argument(s) for evaluation
"""
if not hasattr(self, "client"): # pragma: no cover
self.enable_fhe_execution()
return self.client.encrypt(*args)
def run(
self,
*args: Optional[Union[Value, Tuple[Optional[Value], ...]]],
) -> Union[Value, Tuple[Value, ...]]:
"""
Evaluate the circuit.
Args:
*args (Value):
argument(s) for evaluation
Returns:
Union[Value, Tuple[Value, ...]]:
result(s) of evaluation
"""
if not hasattr(self, "server"): # pragma: no cover
self.enable_fhe_execution()
self.keygen(force=False)
return self.server.run(*args, evaluation_keys=self.client.evaluation_keys)
def decrypt(
self,
*results: Union[Value, Tuple[Value, ...]],
) -> Optional[Union[int, np.ndarray, Tuple[Optional[Union[int, np.ndarray]], ...]]]:
"""
Decrypt result(s) of evaluation.
Args:
*results (Union[Value, Tuple[Value, ...]]):
result(s) of evaluation
Returns:
Optional[Union[int, np.ndarray, Tuple[Optional[Union[int, np.ndarray]], ...]]]:
decrypted result(s) of evaluation
"""
if not hasattr(self, "client"): # pragma: no cover
self.enable_fhe_execution()
return self.client.decrypt(*results)
def encrypt_run_decrypt(self, *args: Any) -> Any:
"""
Encrypt inputs, run the circuit, and decrypt the outputs in one go.
Args:
*args (Union[int, numpy.ndarray]):
inputs to the circuit
Returns:
Union[int, np.ndarray, Tuple[Union[int, np.ndarray], ...]]:
clear result of homomorphic evaluation
"""
return self.decrypt(self.run(self.encrypt(*args)))
def cleanup(self):
"""
Cleanup the temporary library output directory.
"""
if hasattr(self, "server"): # pragma: no cover
self.server.cleanup()
# Properties
def _property(self, name: str) -> Any:
"""
Get a property of the circuit by name.
Args:
name (str):
name of the property
Returns:
Any:
statistic
"""
if hasattr(self, "simulator"):
return getattr(self.simulator, name) # pragma: no cover
if not hasattr(self, "server"):
self.enable_fhe_execution() # pragma: no cover
return getattr(self.server, name)
@property
def size_of_secret_keys(self) -> int:
"""
Get size of the secret keys of the circuit.
"""
return self._property("size_of_secret_keys") # pragma: no cover
@property
def size_of_bootstrap_keys(self) -> int:
"""
Get size of the bootstrap keys of the circuit.
"""
return self._property("size_of_bootstrap_keys") # pragma: no cover
@property
def size_of_keyswitch_keys(self) -> int:
"""
Get size of the key switch keys of the circuit.
"""
return self._property("size_of_keyswitch_keys") # pragma: no cover
@property
def size_of_inputs(self) -> int:
"""
Get size of the inputs of the circuit.
"""
return self._property("size_of_inputs")() # pragma: no cover
@property
def size_of_outputs(self) -> int:
"""
Get size of the outputs of the circuit.
"""
return self._property("size_of_outputs")() # pragma: no cover
@property
def p_error(self) -> int:
"""
Get probability of error for each simple TLU (on a scalar).
"""
return self._property("p_error") # pragma: no cover
@property
def global_p_error(self) -> int:
"""
Get the probability of having at least one simple TLU error during the entire execution.
"""
return self._property("global_p_error") # pragma: no cover
@property
def complexity(self) -> float:
"""
Get complexity of the circuit.
"""
return self._property("complexity") # pragma: no cover
@property
def memory_usage_per_location(self) -> Dict[str, int]:
"""
Get the memory usage of operations in the circuit per location.
"""
return self._property("memory_usage_per_location")() # pragma: no cover
# Programmable Bootstrap Statistics
@property
def programmable_bootstrap_count(self) -> int:
"""
Get the number of programmable bootstraps in the circuit.
"""
return self._property("programmable_bootstrap_count")() # pragma: no cover
@property
def programmable_bootstrap_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of programmable bootstraps per bit width in the circuit.
"""
return self._property("programmable_bootstrap_count_per_parameter")() # pragma: no cover
@property
def programmable_bootstrap_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of programmable bootstraps per tag in the circuit.
"""
return self._property("programmable_bootstrap_count_per_tag")() # pragma: no cover
@property
def programmable_bootstrap_count_per_tag_per_parameter(self) -> Dict[str, Dict[int, int]]:
"""
Get the number of programmable bootstraps per tag per bit width in the circuit.
"""
return self._property(
"programmable_bootstrap_count_per_tag_per_parameter"
)() # pragma: no cover
# Key Switch Statistics
@property
def key_switch_count(self) -> int:
"""
Get the number of key switches in the circuit.
"""
return self._property("key_switch_count")() # pragma: no cover
@property
def key_switch_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of key switches per parameter in the circuit.
"""
return self._property("key_switch_count_per_parameter")() # pragma: no cover
@property
def key_switch_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of key switches per tag in the circuit.
"""
return self._property("key_switch_count_per_tag")() # pragma: no cover
@property
def key_switch_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of key switches per tag per parameter in the circuit.
"""
return self._property("key_switch_count_per_tag_per_parameter")() # pragma: no cover
# Packing Key Switch Statistics
@property
def packing_key_switch_count(self) -> int:
"""
Get the number of packing key switches in the circuit.
"""
return self._property("packing_key_switch_count")() # pragma: no cover
@property
def packing_key_switch_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of packing key switches per parameter in the circuit.
"""
return self._property("packing_key_switch_count_per_parameter")() # pragma: no cover
@property
def packing_key_switch_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of packing key switches per tag in the circuit.
"""
return self._property("packing_key_switch_count_per_tag")() # pragma: no cover
@property
def packing_key_switch_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of packing key switches per tag per parameter in the circuit.
"""
return self._property(
"packing_key_switch_count_per_tag_per_parameter"
)() # pragma: no cover
# Clear Addition Statistics
@property
def clear_addition_count(self) -> int:
"""
Get the number of clear additions in the circuit.
"""
return self._property("clear_addition_count")() # pragma: no cover
@property
def clear_addition_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of clear additions per parameter in the circuit.
"""
return self._property("clear_addition_count_per_parameter")() # pragma: no cover
@property
def clear_addition_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of clear additions per tag in the circuit.
"""
return self._property("clear_addition_count_per_tag")() # pragma: no cover
@property
def clear_addition_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of clear additions per tag per parameter in the circuit.
"""
return self._property("clear_addition_count_per_tag_per_parameter")() # pragma: no cover
# Encrypted Addition Statistics
@property
def encrypted_addition_count(self) -> int:
"""
Get the number of encrypted additions in the circuit.
"""
return self._property("encrypted_addition_count")() # pragma: no cover
@property
def encrypted_addition_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of encrypted additions per parameter in the circuit.
"""
return self._property("encrypted_addition_count_per_parameter")() # pragma: no cover
@property
def encrypted_addition_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of encrypted additions per tag in the circuit.
"""
return self._property("encrypted_addition_count_per_tag")() # pragma: no cover
@property
def encrypted_addition_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of encrypted additions per tag per parameter in the circuit.
"""
return self._property(
"encrypted_addition_count_per_tag_per_parameter"
)() # pragma: no cover
# Clear Multiplication Statistics
@property
def clear_multiplication_count(self) -> int:
"""
Get the number of clear multiplications in the circuit.
"""
return self._property("clear_multiplication_count")() # pragma: no cover
@property
def clear_multiplication_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of clear multiplications per parameter in the circuit.
"""
return self._property("clear_multiplication_count_per_parameter")() # pragma: no cover
@property
def clear_multiplication_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of clear multiplications per tag in the circuit.
"""
return self._property("clear_multiplication_count_per_tag")() # pragma: no cover
@property
def clear_multiplication_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of clear multiplications per tag per parameter in the circuit.
"""
return self._property(
"clear_multiplication_count_per_tag_per_parameter"
)() # pragma: no cover
# Encrypted Negation Statistics
@property
def encrypted_negation_count(self) -> int:
"""
Get the number of encrypted negations in the circuit.
"""
return self._property("encrypted_negation_count")() # pragma: no cover
@property
def encrypted_negation_count_per_parameter(self) -> Dict[Parameter, int]:
"""
Get the number of encrypted negations per parameter in the circuit.
"""
return self._property("encrypted_negation_count_per_parameter")() # pragma: no cover
@property
def encrypted_negation_count_per_tag(self) -> Dict[str, int]:
"""
Get the number of encrypted negations per tag in the circuit.
"""
return self._property("encrypted_negation_count_per_tag")() # pragma: no cover
@property
def encrypted_negation_count_per_tag_per_parameter(self) -> Dict[str, Dict[Parameter, int]]:
"""
Get the number of encrypted negations per tag per parameter in the circuit.
"""
return self._property(
"encrypted_negation_count_per_tag_per_parameter"
)() # pragma: no cover
# All Statistics
@property
def statistics(self) -> Dict:
"""
Get all statistics of the circuit.
"""
return self._property("statistics") # pragma: no cover