-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
torch_wrapper.py
90 lines (71 loc) · 2.8 KB
/
torch_wrapper.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
import functools
import numpy as np
import torch
HANDLED_FUNCTIONS = {}
def implements(torch_function):
"""Register a torch function override for ScalarTensor"""
@functools.wraps(torch_function)
def decorator(func):
HANDLED_FUNCTIONS[torch_function] = func
return func
return decorator
class PaillierTensor(object):
def __init__(self, paillier_array):
if type(paillier_array) == list:
self._paillier_np_array = np.array(paillier_array)
elif type(paillier_array) == np.ndarray:
self._paillier_np_array = paillier_array
else:
raise TypeError(f"{type(paillier_array)} is not supported.")
def __repr__(self):
return "PaillierTensor"
def decypt(self, sk):
return torch.Tensor(
np.vectorize(lambda x: sk.decrypt2float(x))(self._paillier_np_array)
)
def tensor(self, sk=None):
if sk is not None:
return self.decypt(sk)
else:
return torch.zeros(self._paillier_np_array.shape)
def numpy(self):
return self._paillier_np_array
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
if func not in HANDLED_FUNCTIONS or not all(
issubclass(t, (torch.Tensor, PaillierTensor)) for t in types
):
return NotImplemented
return HANDLED_FUNCTIONS[func](*args, **kwargs)
@implements(torch.add)
def add(input, other):
if type(other) in [int, float]:
return PaillierTensor(input._paillier_np_array + other)
elif type(other) in [torch.Tensor, PaillierTensor]:
return PaillierTensor(input._paillier_np_array + other.numpy())
else:
raise NotImplementedError(f"{type(other)} is not supported.")
@implements(torch.sub)
def sub(input, other):
if type(other) in [int, float]:
return PaillierTensor(input._paillier_np_array + (-1 * other))
elif type(other) in [torch.Tensor, PaillierTensor]:
return PaillierTensor(input._paillier_np_array + (-1 * other.numpy()))
else:
raise NotImplementedError(f"{type(other)} is not supported.")
@implements(torch.mul)
def mul(input, other):
if type(other) in [int, float]:
return PaillierTensor(input._paillier_np_array * other)
elif type(other) in [torch.Tensor, PaillierTensor]:
return PaillierTensor(input._paillier_np_array * other.numpy())
else:
raise NotImplementedError(f"{type(other)} is not supported.")
def __add__(self, other):
return torch.add(self, other)
def __sub__(self, other):
return torch.sub(self, other)
def __mul__(self, other):
return torch.mul(self, other)