/
beaver.py
213 lines (157 loc) · 6.86 KB
/
beaver.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
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import crypten
import crypten.communicator as comm
import torch
from crypten.common.util import count_wraps
from crypten.config import cfg
class IgnoreEncodings:
"""Context Manager to ignore tensor encodings"""
def __init__(self, list_of_tensors):
self.list_of_tensors = list_of_tensors
self.encodings_cache = [tensor.encoder.scale for tensor in list_of_tensors]
def __enter__(self):
for tensor in self.list_of_tensors:
tensor.encoder._scale = 1
def __exit__(self, exc_type, exc_value, exc_traceback):
for i, tensor in enumerate(self.list_of_tensors):
tensor.encoder._scale = self.encodings_cache[i]
def __beaver_protocol(op, x, y, *args, **kwargs):
"""Performs Beaver protocol for additively secret-shared tensors x and y
1. Obtain uniformly random sharings [a],[b] and [c] = [a * b]
2. Additively hide [x] and [y] with appropriately sized [a] and [b]
3. Open ([epsilon] = [x] - [a]) and ([delta] = [y] - [b])
4. Return [z] = [c] + (epsilon * [b]) + ([a] * delta) + (epsilon * delta)
"""
assert op in {
"mul",
"matmul",
"conv1d",
"conv2d",
"conv_transpose1d",
"conv_transpose2d",
}
if x.device != y.device:
raise ValueError(f"x lives on device {x.device} but y on device {y.device}")
provider = crypten.mpc.get_default_provider()
a, b, c = provider.generate_additive_triple(
x.size(), y.size(), op, device=x.device, *args, **kwargs
)
from .arithmetic import ArithmeticSharedTensor
if cfg.mpc.active_security:
"""
Reference: "Multiparty Computation from Somewhat Homomorphic Encryption"
Link: https://eprint.iacr.org/2011/535.pdf
"""
f, g, h = provider.generate_additive_triple(
x.size(), y.size(), op, device=x.device, *args, **kwargs
)
t = ArithmeticSharedTensor.PRSS(a.size(), device=x.device)
t_plain_text = t.get_plain_text()
rho = (t_plain_text * a - f).get_plain_text()
sigma = (b - g).get_plain_text()
triples_check = t_plain_text * c - h - sigma * f - rho * g - rho * sigma
triples_check = triples_check.get_plain_text()
if torch.any(triples_check != 0):
raise ValueError("Beaver Triples verification failed!")
# Vectorized reveal to reduce rounds of communication
with IgnoreEncodings([a, b, x, y]):
epsilon, delta = ArithmeticSharedTensor.reveal_batch([x - a, y - b])
# z = c + (a * delta) + (epsilon * b) + epsilon * delta
c._tensor += getattr(torch, op)(epsilon, b._tensor, *args, **kwargs)
c._tensor += getattr(torch, op)(a._tensor, delta, *args, **kwargs)
c += getattr(torch, op)(epsilon, delta, *args, **kwargs)
return c
def mul(x, y):
return __beaver_protocol("mul", x, y)
def matmul(x, y):
return __beaver_protocol("matmul", x, y)
def conv1d(x, y, **kwargs):
return __beaver_protocol("conv1d", x, y, **kwargs)
def conv2d(x, y, **kwargs):
return __beaver_protocol("conv2d", x, y, **kwargs)
def conv_transpose1d(x, y, **kwargs):
return __beaver_protocol("conv_transpose1d", x, y, **kwargs)
def conv_transpose2d(x, y, **kwargs):
return __beaver_protocol("conv_transpose2d", x, y, **kwargs)
def square(x):
"""Computes the square of `x` for additively secret-shared tensor `x`
1. Obtain uniformly random sharings [r] and [r2] = [r * r]
2. Additively hide [x] with appropriately sized [r]
3. Open ([epsilon] = [x] - [r])
4. Return z = [r2] + 2 * epsilon * [r] + epsilon ** 2
"""
provider = crypten.mpc.get_default_provider()
r, r2 = provider.square(x.size(), device=x.device)
with IgnoreEncodings([x, r]):
epsilon = (x - r).reveal()
return r2 + 2 * r * epsilon + epsilon * epsilon
def wraps(x):
"""Privately computes the number of wraparounds for a set a shares
To do so, we note that:
[theta_x] = theta_z + [beta_xr] - [theta_r] - [eta_xr]
Where [theta_i] is the wraps for a variable i
[beta_ij] is the differential wraps for variables i and j
[eta_ij] is the plaintext wraps for variables i and j
Note: Since [eta_xr] = 0 with probability 1 - |x| / Q for modulus Q, we
can make the assumption that [eta_xr] = 0 with high probability.
"""
provider = crypten.mpc.get_default_provider()
r, theta_r = provider.wrap_rng(x.size(), device=x.device)
beta_xr = theta_r.clone()
beta_xr._tensor = count_wraps([x._tensor, r._tensor])
with IgnoreEncodings([x, r]):
z = x + r
theta_z = comm.get().gather(z._tensor, 0)
theta_x = beta_xr - theta_r
# TODO: Incorporate eta_xr
if x.rank == 0:
theta_z = count_wraps(theta_z)
theta_x._tensor += theta_z
return theta_x
def truncate(x, y):
"""Protocol to divide an ArithmeticSharedTensor `x` by a constant integer `y`"""
wrap_count = wraps(x)
x.share = x.share.div_(y, rounding_mode="trunc")
# NOTE: The multiplication here must be split into two parts
# to avoid long out-of-bounds when y <= 2 since (2 ** 63) is
# larger than the largest long integer.
correction = wrap_count * 4 * (int(2**62) // y)
x.share -= correction.share
return x
def AND(x, y):
"""
Performs Beaver protocol for binary secret-shared tensors x and y
1. Obtain uniformly random sharings [a],[b] and [c] = [a & b]
2. XOR hide [x] and [y] with appropriately sized [a] and [b]
3. Open ([epsilon] = [x] ^ [a]) and ([delta] = [y] ^ [b])
4. Return [c] ^ (epsilon & [b]) ^ ([a] & delta) ^ (epsilon & delta)
"""
from .binary import BinarySharedTensor
provider = crypten.mpc.get_default_provider()
a, b, c = provider.generate_binary_triple(x.size(), y.size(), device=x.device)
# Stack to vectorize reveal
eps_del = BinarySharedTensor.reveal_batch([x ^ a, y ^ b])
epsilon = eps_del[0]
delta = eps_del[1]
return (b & epsilon) ^ (a & delta) ^ (epsilon & delta) ^ c
def B2A_single_bit(xB):
"""Converts a single-bit BinarySharedTensor xB into an
ArithmeticSharedTensor. This is done by:
1. Generate ArithmeticSharedTensor [rA] and BinarySharedTensor =rB= with
a common 1-bit value r.
2. Hide xB with rB and open xB ^ rB
3. If xB ^ rB = 0, then return [rA], otherwise return 1 - [rA]
Note: This is an arithmetic xor of a single bit.
"""
if comm.get().get_world_size() < 2:
from .arithmetic import ArithmeticSharedTensor
return ArithmeticSharedTensor(xB._tensor, precision=0, src=0)
provider = crypten.mpc.get_default_provider()
rA, rB = provider.B2A_rng(xB.size(), device=xB.device)
z = (xB ^ rB).reveal()
rA = rA * (1 - 2 * z) + z
return rA