-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathTensor.py
389 lines (329 loc) · 12.9 KB
/
Tensor.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
# built-in dependencies
from typing import Union, List
import multiprocessing
from contextlib import closing
# 3rd party dependencies
from tqdm import tqdm
# project dependencies
from lightphe.models.Homomorphic import Homomorphic
from lightphe.commons import phe_utils
from lightphe.models.Ciphertext import Ciphertext
from lightphe.models.Algorithm import Algorithm
from lightphe.commons.logger import Logger
logger = Logger(module="lightphe/models/Tensor.py")
# pylint: disable=too-few-public-methods, no-else-return
class Fraction:
"""
Class to store fractional values
"""
def __init__(
self,
dividend: Union[int, tuple, list],
abs_dividend: Union[int, tuple, list],
divisor: Union[int, tuple, list],
sign: int = 1,
):
self.dividend = dividend
self.divisor = divisor
self.sign = sign
self.abs_dividend = abs_dividend
def __str__(self):
"""
Print Fraction Class Object
"""
sign = "-" if self.sign == -1 else "+"
return f"Fraction({sign}{self.abs_dividend} / {self.divisor})"
def __repr__(self):
"""
Print Fraction Class Object
"""
return self.__str__()
class EncryptedTensor:
"""
Class to store encrypted tensor objects
"""
def __init__(
self,
fractions: List[Fraction],
cs: Homomorphic,
precision: int = 5,
):
"""
Initialization method
Args:
fractions (list): list of fractions storing individual encrypted tensor items
cs (cryptosystem): built cryptosystem
precision (int): precision of the tensor
"""
self.fractions = fractions
self.cs = cs
self.precision = precision
def __str__(self):
"""
Print encrypted tensor object
"""
results = []
for i in self.fractions:
results.append(f"{i}")
return ", ".join(results)
def __repr__(self):
"""
Print encrypted tensor object
"""
return self.__str__()
def __matmul__(self, other: Union["EncryptedTensor", list]):
"""
Perform dot product of two encrypted tensors
"""
if not (
(isinstance(other, EncryptedTensor) and isinstance(self, list))
or (isinstance(other, list) and isinstance(self, EncryptedTensor))
):
raise ValueError(
"Dot product can be run for EncryptedTensor and List of float / int"
)
encrypted_tensor = self.__mul__(other=other)
if len(encrypted_tensor.fractions) == 0:
raise ValueError("Dot product cannot be calculated for empty tensor")
divisor = cast_ciphertext(
cs=self.cs, value=encrypted_tensor.fractions[0].divisor
)
if len(encrypted_tensor.fractions) > 10000:
# parallelize the sum operation
num_workers = min(
len(encrypted_tensor.fractions), multiprocessing.cpu_count()
)
chunks = chunkify(encrypted_tensor.fractions, num_workers)
with closing(multiprocessing.Pool(num_workers)) as pool:
funclist = []
for chunk in chunks:
f = pool.apply_async(sum_fractions_chunk, (chunk, self.cs))
funclist.append(f)
partial_sums = []
for f in tqdm(funclist, desc="Summing up fractions", disable=True):
result = f.get(timeout=10)
partial_sums.append(result)
# map reduce
total_sum = partial_sums[0]
for partial in partial_sums[1:]:
total_sum += partial
fraction = Fraction(
dividend=total_sum.value,
abs_dividend=total_sum.value,
divisor=divisor.value,
sign=1,
)
else:
# serial implementation
sum_dividend = cast_ciphertext(
cs=self.cs, value=encrypted_tensor.fractions[0].abs_dividend
)
divisor = cast_ciphertext(
cs=self.cs, value=encrypted_tensor.fractions[0].divisor
)
if len(encrypted_tensor.fractions) > 1:
for fraction in encrypted_tensor.fractions[1:]:
sum_dividend += cast_ciphertext(
value=fraction.abs_dividend, cs=self.cs
)
fraction = Fraction(
dividend=sum_dividend.value,
abs_dividend=sum_dividend.value,
divisor=divisor.value,
sign=1,
)
return EncryptedTensor(fractions=[fraction], cs=self.cs)
def __mul__(
self, other: Union["EncryptedTensor", int, float, list]
) -> "EncryptedTensor":
"""
Perform homomorphic element-wise multipliction on tensors
or multiplication of an encrypted tensor with a constant
Args:
other: encrypted tensor or constant
Returns:
encrypted tensor
"""
if isinstance(other, EncryptedTensor):
if isinstance(other, EncryptedTensor) and len(self.fractions) != len(
other.fractions
):
raise ValueError(
"Tensor sizes must be equal in homomorphic multiplication"
)
fractions = []
for i, alpha_tensor in enumerate(self.fractions):
beta_tensor = other.fractions[i]
current_dividend = self.cs.multiply(
ciphertext1=alpha_tensor.dividend, ciphertext2=beta_tensor.dividend
)
current_abs_dividend = self.cs.multiply(
ciphertext1=alpha_tensor.abs_dividend,
ciphertext2=beta_tensor.abs_dividend,
)
current_divisor = self.cs.multiply(
ciphertext1=alpha_tensor.divisor, ciphertext2=beta_tensor.divisor
)
fraction = Fraction(
dividend=current_dividend,
abs_dividend=current_abs_dividend,
divisor=current_divisor,
sign=alpha_tensor.sign * beta_tensor.sign,
)
fractions.append(fraction)
return EncryptedTensor(fractions=fractions, cs=self.cs)
elif isinstance(other, list):
# perform element-wise multiplication of encrypted tensor with plain tensor
if len(self.fractions) != len(other):
raise ValueError(
"Tensor sizes must be equal in homomorphic multiplication"
)
if any(i < 0 for i in other) or any(
fraction.sign < 0 for fraction in self.fractions
):
raise ValueError(
"all items in the plain and encrypted tensor must be positive"
" to perform element wise multiplication"
)
dividends = []
divisor = None
for alpha, beta in zip(self.fractions, other):
c_abs_dividend, c_divisor = phe_utils.fractionize(
value=(
abs(beta) % self.cs.plaintext_modulo
if abs(beta) > self.cs.plaintext_modulo
else abs(beta)
),
modulo=self.cs.plaintext_modulo,
precision=self.precision,
)
dividend = (
cast_ciphertext(cs=self.cs, value=alpha.abs_dividend)
* c_abs_dividend
)
if divisor is None:
divisor = (
cast_ciphertext(cs=self.cs, value=alpha.divisor) * c_divisor
)
# dividends.append(dividend)
dividends.append(
Fraction(
dividend=dividend.value,
abs_dividend=dividend.value,
divisor=divisor.value,
sign=1,
)
)
return EncryptedTensor(fractions=dividends, cs=self.cs)
elif isinstance(other, (int, float)):
constant_sign = 1 if other >= 0 else -1
other = abs(other)
if isinstance(other, float):
other = phe_utils.normalize_input(
value=other, modulo=self.cs.plaintext_modulo
)
fractions = []
for alpha_tensor in self.fractions:
dividend = self.cs.multiply_by_contant(
ciphertext=alpha_tensor.dividend, constant=other
)
abs_dividend = self.cs.multiply_by_contant(
ciphertext=alpha_tensor.abs_dividend, constant=other
)
# notice that divisor is alpha tensor's divisor instead of addition
fraction = Fraction(
dividend=dividend,
abs_dividend=abs_dividend,
divisor=alpha_tensor.divisor,
sign=constant_sign * alpha_tensor.sign,
)
fractions.append(fraction)
return EncryptedTensor(fractions=fractions, cs=self.cs)
else:
raise ValueError(
"Encrypted tensor can be multiplied by an encrypted tensor or constant"
)
def __rmul__(
self, multiplier: Union[int, float, "EncryptedTensor"]
) -> "EncryptedTensor":
"""
Perform multiplication of encrypted tensor with a constant or plain tensor (element-wise)
Args:
multiplier: scalar value
Returns:
encrypted tensor
"""
return self.__mul__(other=multiplier)
def __add__(self, other: "EncryptedTensor") -> "EncryptedTensor":
"""
Perform homomorphic addition
Args:
other: encrypted tensor
Returns:
encrypted tensor
"""
if len(self.fractions) != len(other.fractions):
raise ValueError("Fraction sizes must be equal")
current_tensors = []
for i, alpha_tensor in enumerate(self.fractions):
beta_tensor = other.fractions[i]
current_dividend = self.cs.add(
ciphertext1=alpha_tensor.dividend, ciphertext2=beta_tensor.dividend
)
current_abs_dividend = self.cs.add(
ciphertext1=alpha_tensor.abs_dividend,
ciphertext2=beta_tensor.abs_dividend,
)
# notice that divisor is alpha tensor's divisor instead of addition
if alpha_tensor.sign == -1 and beta_tensor.sign == -1:
current_tensor = Fraction(
dividend=current_dividend,
abs_dividend=current_abs_dividend,
divisor=alpha_tensor.divisor,
sign=-1,
)
else:
# if one is positive and one is negative, then i cannot know
# the result is positive or negative. trust mod calculations.
if alpha_tensor.sign != beta_tensor.sign:
logger.warn(
f"{i}-th items of the vectors have different signs, and result's sign "
"cannot be determined in PHE. Result will be shown for positive for this anyway."
)
current_tensor = Fraction(
dividend=current_dividend,
abs_dividend=current_dividend,
divisor=alpha_tensor.divisor,
sign=1,
)
current_tensors.append(current_tensor)
return EncryptedTensor(fractions=current_tensors, cs=self.cs)
def cast_ciphertext(cs: Homomorphic, value: int) -> Ciphertext:
"""Cast an integer value to a Ciphertext object."""
class_name = cs.__class__.__name__
algorithm_name = getattr(Algorithm, class_name, None)
assert algorithm_name is not None, f"Algorithm name not found for {class_name}"
return Ciphertext(
algorithm_name=algorithm_name,
keys=cs.keys,
value=value,
form=cs.keys.get("form"),
curve=cs.keys.get("curve"),
)
def chunkify(lst: list, n: int):
"""Split list into n approximately equal chunks."""
avg = len(lst) // n
remainder = len(lst) % n
chunks = []
start = 0
for i in range(n):
end = start + avg + (1 if i < remainder else 0)
chunks.append(lst[start:end])
start = end
return chunks
def sum_fractions_chunk(fractions_chunk: list, cs: Homomorphic):
"""Compute the sum of a chunk of fractions in parallel."""
result = cast_ciphertext(cs=cs, value=fractions_chunk[0].abs_dividend)
for fraction in fractions_chunk[1:]:
result += cast_ciphertext(cs=cs, value=fraction.abs_dividend)
return result