/
pond.py
4516 lines (3346 loc) · 131 KB
/
pond.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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=protected-access
"""Implementation of the Pond protocol.
Pond is a vectorized two-party secret sharing protocol similar to SPDZ with a
generalized implementation of Beaver triples that are produced by a third-party
helper."""
from __future__ import absolute_import
import abc
import logging
import random
import sys
from functools import reduce
from functools import wraps
from math import ceil
from math import log2
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
import numpy as np
import tensorflow as tf
from ...config import get_config
from ...config import tensorflow_supports_int64
from ...player import Player
from ...queue.fifo import AbstractFIFOQueue
from ...queue.fifo import TFFIFOQueue
from ...tensor import factories
from ...tensor import fixed64
from ...tensor import fixed100
from ...tensor import int64factory
from ...tensor import int100factory
from ...tensor.factory import AbstractConstant
from ...tensor.factory import AbstractFactory
from ...tensor.factory import AbstractTensor
from ...tensor.factory import AbstractVariable
from ...tensor.fixed import FixedpointConfig
from ...tensor.fixed import _validate_fixedpoint_config
from ...tensor.helpers import inverse
from ..protocol import Protocol
from ..protocol import TFEPrivateTensor
from ..protocol import TFEPrivateVariable
from ..protocol import TFEPublicTensor
from ..protocol import TFEPublicVariable
from ..protocol import TFETensor
from ..protocol import TFETensorBone
from ..protocol import memoize
from ..protocol import nodes
from .triple_sources import BaseTripleSource
from .triple_sources import OnlineTripleSource
TFEData = Union[np.ndarray, tf.Tensor]
TFEInputter = Callable[[], Union[List[tf.Tensor], tf.Tensor]]
TF_INT_TYPES = [tf.int8, tf.int16, tf.int32, tf.int64]
TripleSourceOrPlayer = Union[BaseTripleSource, Player]
_THISMODULE = sys.modules[__name__]
class Pond(Protocol):
"""Pond is similar to SPDZ except it has been vectorized plus a few more
optimizations.
Pond works with 2 parties for computation and one crypto producer for
triples.
:param Player server_0: The "alice" of MPC.
:param Player server_1: The "bob" of MPC.
:param Player triple_source: the entity responsible for producing triples in
`Pond` protocol. The valid values can be of type `TripleSource` or
`Player`. If a `Player` is passed, it will be the host that is used as an
`OnlineTripleSource` producer.
:param AbstractFactory tensor_factory: Which backing type of tensor you would
like to use, e.g. `int100` or `int64`
:param Player fixedpoint_config: Parameters for fixed-point precision tensors
""" # noqa:E501
def __init__(
self,
server_0=None,
server_1=None,
triple_source: Optional[TripleSourceOrPlayer] = None,
tensor_factory: Optional[AbstractFactory] = None,
fixedpoint_config: Optional[FixedpointConfig] = None,
) -> None:
config = get_config()
self.server_0 = config.get_player(server_0 if server_0 else "server0")
self.server_1 = config.get_player(server_1 if server_1 else "server1")
if triple_source is None:
crypto_producer = config.get_player("server2")
crypto_producer = config.get_player(
crypto_producer if crypto_producer else "crypto-producer"
)
self.triple_source = OnlineTripleSource(crypto_producer)
else:
if isinstance(triple_source, Player):
self.triple_source = OnlineTripleSource(triple_source)
else:
assert isinstance(triple_source, BaseTripleSource)
self.triple_source = triple_source
if tensor_factory is None:
if tensorflow_supports_int64():
tensor_factory = int64factory
else:
logging.warning(
"Falling back to using int100 tensors due to lack of int64 "
"support. Performance may be improved by installing a version of "
"TensorFlow supporting this (1.13+ or custom build)."
)
tensor_factory = int100factory
if fixedpoint_config is None:
if tensor_factory is int64factory:
fixedpoint_config = fixed64
elif tensor_factory is int100factory:
fixedpoint_config = fixed100
else:
raise ValueError(
(
"Don't know how to pick fixedpoint configuration "
"for tensor type {}"
).format(tensor_factory)
)
_validate_fixedpoint_config(fixedpoint_config, tensor_factory)
self.fixedpoint_config = fixedpoint_config
self.tensor_factory = tensor_factory
def define_constant(
self,
value: np.ndarray,
apply_scaling: bool = True,
name: Optional[str] = None,
factory: Optional[AbstractFactory] = None,
):
"""
define_constant(value, apply_scaling, name, factory) -> PondConstant
Define a constant to use in computation.
.. code-block:: python
x = prot.define_constant(np.array([1,2,3,4]), apply_scaling=False)
:See: tf.constant
:param np.ndarray value: The value to define as a constant.
:param bool apply_scaling: Whether or not to scale the value.
:param str name: What name to give to this node in the graph.
:param AbstractFactory factory: Which tensor type to represent this value
with.
"""
assert isinstance(value, np.ndarray), type(value)
factory = factory or self.tensor_factory
v = self._encode(value, apply_scaling)
with tf.name_scope("constant{}".format("-" + name if name else "")):
with tf.device(self.server_0.device_name):
x_on_0 = factory.constant(v)
with tf.device(self.server_1.device_name):
x_on_1 = factory.constant(v)
return PondConstant(self, x_on_0, x_on_1, apply_scaling)
# def define_public_tensor(
# self,
# initial_value,
# apply_scaling: bool = True,
# name: Optional[str] = None,
# factory: Optional[AbstractFactory] = None,
# ):
# assert isinstance(
# initial_value, (np.ndarray, tf.Tensor, PondPublicTensor)
# ), type(initial_value)
# factory = factory or self.tensor_factory
# with tf.name_scope("public-var{}".format("-" + name if name else "")):
# if isinstance(initial_value, np.ndarray):
# v = self._encode(initial_value, apply_scaling)
# v_on_0, v_on_1 = v, v
# elif isinstance(initial_value, tf.Tensor):
# inttype = factory.native_type
# v = self._encode(initial_value, apply_scaling, tf_int_type=inttype)
# v_on_0, v_on_1 = v, v
# elif isinstance(initial_value, PondPublicTensor):
# v_on_0, v_on_1 = initial_value.unwrapped
# else:
# raise TypeError(
# ("Don't know how to turn {} into a " "public variable").format(
# type(initial_value)
# )
# )
# with tf.device(self.server_0.device_name):
# x_on_0 = factory.tensor(v_on_0)
# with tf.device(self.server_1.device_name):
# x_on_1 = factory.tensor(v_on_1)
# x = PondPublicTensor(self, x_on_0, x_on_1, apply_scaling)
# return x
def define_public_variable(
self,
initial_value,
apply_scaling: bool = True,
name: Optional[str] = None,
factory: Optional[AbstractFactory] = None,
):
"""Define a public variable.
This is like defining a variable in tensorflow except it creates one that
can be used by the protocol.
For most cases, you can think of this as the same as the one from
TensorFlow and you don't generally need to consider the difference.
For those curious, under the hood, the major difference is that this
function will pin your data to a specific device which will be used to
optimize the graph later on.
:see: tf.Variable
:param Union[np.ndarray,tf.Tensor,PondPublicTensor] initial_value: The
initial value.
:param bool apply_scaling: Whether or not to scale the value.
:param str name: What name to give to this node in the graph.
:param AbstractFactory factory: Which tensor type to represent this value
with.
"""
assert isinstance(
initial_value, (np.ndarray, tf.Tensor, PondPublicTensor)
), type(initial_value)
factory = factory or self.tensor_factory
with tf.name_scope("public-var{}".format("-" + name if name else "")):
if isinstance(initial_value, np.ndarray):
v = self._encode(initial_value, apply_scaling)
v_on_0, v_on_1 = v, v
elif isinstance(initial_value, tf.Tensor):
inttype = factory.native_type
v = self._encode(initial_value, apply_scaling, tf_int_type=inttype)
v_on_0, v_on_1 = v, v
elif isinstance(initial_value, PondPublicTensor):
v_on_0, v_on_1 = initial_value.unwrapped
else:
raise TypeError(
("Don't know how to turn {} into a " "public variable").format(
type(initial_value)
)
)
with tf.device(self.server_0.device_name):
x_on_0 = factory.variable(v_on_0)
with tf.device(self.server_1.device_name):
x_on_1 = factory.variable(v_on_1)
x = PondPublicVariable(self, x_on_0, x_on_1, apply_scaling)
return x
def define_private_variable(
self,
initial_value,
apply_scaling: bool = True,
share_type: str = None,
name: Optional[str] = None,
factory: Optional[AbstractFactory] = None,
):
"""Define a private variable.
This will take the passed value and construct shares that will be split up
between those involved in the computation.
For example, in a two party architecture, this will split the value into
two sets of shares and transfer them between each party in a secure manner.
:see tf.Variable
:param Union[np.ndarray,tf.Tensor,PondPublicTensor] initial_value: The
initial value.
:param bool apply_scaling: Whether or not to scale the value.
:param str name: What name to give to this node in the graph.
:param AbstractFactory factory: Which tensor type to represent this value
with.
"""
init_val_types = (np.ndarray, tf.Tensor, PondPublicTensor, PondPrivateTensor)
assert isinstance(initial_value, init_val_types), type(initial_value)
factory = factory or self.tensor_factory
suffix = "-" + name if name else ""
with tf.name_scope("private-var{}".format(suffix)):
if isinstance(initial_value, np.ndarray):
v = factory.tensor(self._encode(initial_value, apply_scaling))
v0, v1 = self._share(v)
elif isinstance(initial_value, tf.Tensor):
v = factory.tensor(
self._encode(
initial_value,
apply_scaling,
tf_int_type=factory.native_type,
)
)
v0, v1 = self._share(v)
elif isinstance(initial_value, PondPublicTensor):
v_on_0, _ = initial_value.unwrapped
with tf.device(self.server_0.device_name):
# NOTE[Morten]
# we can alternatively avoid transfer of v1 from server0 and server1
# by having the crypto producer (pre-)generate sharings of zero
v0, v1 = self._share(v_on_0)
elif isinstance(initial_value, PondPrivateTensor):
v0, v1 = initial_value.unwrapped
else:
raise TypeError(
("Don't know how to turn {} " "into private variable").format(
type(initial_value)
)
)
with tf.device(self.server_0.device_name):
x0 = factory.variable(v0)
with tf.device(self.server_1.device_name):
x1 = factory.variable(v1)
x = PondPrivateVariable(self, x0, x1, apply_scaling)
return x
def fifo_queue(self, capacity, shape, shared_name):
return AdditiveFIFOQueue(
protocol=self,
server_0=self.server_0,
server_1=self.server_1,
capacity=capacity,
dtype=self.tensor_factory,
shape=shape,
shared_name=shared_name,
)
def define_public_input(
self,
player: Union[str, Player],
inputter_fn: TFEInputter,
apply_scaling: bool = True,
name: Optional[str] = None,
):
"""Define a public input.
This represents a `public` input owned by the specified player into the
graph.
:param Union[str,Player] player: Which player owns this input.
:param bool apply_scaling: Whether or not to scale the value.
:param str name: What name to give to this node in the graph.
"""
if isinstance(player, str):
player = get_config().get_player(player)
assert isinstance(player, Player)
factory = self.tensor_factory
suffix = "-" + name if name else ""
def helper(v: tf.Tensor) -> "PondPublicTensor":
assert (
v.shape.is_fully_defined()
), "Shape of input '{}' on '{}' is not fully defined".format(
name if name else "", player.name
)
enc = self._encode(v, apply_scaling, tf_int_type=factory.native_type)
w = factory.tensor(enc)
return PondPublicTensor(self, w, w, apply_scaling)
with tf.name_scope("public-input{}".format(suffix)):
with tf.device(player.device_name):
inputs = inputter_fn()
if isinstance(inputs, tf.Tensor):
# single input -> single output
v = inputs
return helper(v)
if isinstance(inputs, (list, tuple)):
# multiple inputs -> multiple outputs
return [helper(v) for v in inputs]
raise TypeError(
("Don't know how to handle inputs " "of type {}").format(
type(inputs)
)
)
def local_computation(self, player_name=None, **kwargs):
"""Annotate a function `compute_func` for local computation.
This decorator can be used to pin a function's code to a specific player's
device for remote execution. This is useful when defining player-specific
handlers for e.g. providing model weights, or input and output tensors.
The decorator can handle global functions, normal object methods, or
classmethods. If wrapping a method, it's presumed that the method's object
has an attribute named `player_name`, or that the user will provide the
`player_name` later on as a kwarg to the `compute_func`.
Example:
```
@tfe.local_computation('input-provider')
def provide_input():
return tf.random.normal((3, 3))
@tfe.local_computation
def receive_output(logits):
return tf.print(tf.argmax(logits, axis=-1))
x = provide_input()
y = model(x)
receive_op = receive_output(y, player_name='output-receiver')
with tfe.Session():
sess.run(receive_op)
```
Arguments:
player_name: Name of the player who should execute the function.
kwargs: Keyword arguments to use when encoding or encrypting
inputs/outputs to compute_func: see tfe.define_local_computation for
details.
Returns:
The compute_func, but decorated for remote execution.
"""
if callable(player_name):
# The user has called us as a standard decorator:
#
# @tfe.local_computation
# def provide_input():
# return tf.zeros((2, 2))
actual_compute_func = player_name
player_name = None
else:
# The user has called us as a function, maybe with non-default args:
#
# @tfe.local_computation('input-provider')
# def provide_input():
# return tf.zeros((2, 2))
actual_compute_func = None
def decorator(compute_func):
@wraps(compute_func)
def compute_func_wrapper(*compute_func_args, **compute_func_kwargs):
# Assume player_name was passed to decorator. If not, try to recover.
actual_player_name = player_name
if actual_player_name is None:
# Maybe user has passed player_name to compute_func as a kwarg
actual_player_name = compute_func_kwargs.get("player_name", None)
if actual_player_name is None:
# Assume compute_func is a method and its instance has some
# attribute `player_name`
if compute_func_args:
parent_instance = compute_func_args[0]
actual_player_name = getattr(
parent_instance, "player_name", None
)
if actual_player_name is None:
# Fallback to error
raise ValueError(
"'player_name' not provided. Please provide "
"'player_name' as a keyword argument to this "
"function, or as an argument to the "
"tfe.local_computation decorator."
)
return self.define_local_computation(
actual_player_name,
compute_func,
arguments=compute_func_args,
**kwargs,
)
return compute_func_wrapper
if actual_compute_func is None:
# User has not yet passed a compute_func, so we'll expect them to
# pass it outside of this function's scope (e.g. as a decorator).
return decorator
# User has already passed a compute_func, so return the decorated version.
return decorator(actual_compute_func)
def define_local_computation(
self,
player,
computation_fn,
arguments=None,
apply_scaling=True,
name_scope=None,
masked=False,
factory=None,
):
"""
Define a local computation that happens on plaintext tensors.
:param player: Who performs the computation and gets to see the values in
plaintext.
:param apply_scaling: Whether or not to scale the outputs.
:param name_scope: Optional name to give to this node in the graph.
:param masked: Whether or not to produce masked outputs.
:param factory: Backing tensor type to use for outputs.
""" # noqa:E501
factory = factory or self.tensor_factory
if isinstance(player, str):
player = get_config().get_player(player)
assert isinstance(player, Player)
def share_output(v: tf.Tensor):
assert (
v.shape.is_fully_defined()
), "Shape of return value '{}' on '{}' not fully defined".format(
name_scope if name_scope else "", player.name
)
enc = self._encode(v, apply_scaling, tf_int_type=factory.native_type)
w = factory.tensor(enc)
x = self._share_and_wrap(w, apply_scaling)
if not masked:
return x
with tf.name_scope("local_mask"):
a0 = factory.sample_uniform(v.shape)
a1 = factory.sample_uniform(v.shape)
a = a0 + a1
alpha = w - a
return PondMaskedTensor(self, x, a, a0, a1, alpha, alpha, apply_scaling)
def reconstruct_input(x):
if not isinstance(x, (AbstractTensor, PondTensor)):
return x
if isinstance(x, PondPublicTensor):
w, _ = x.unwrapped
v = self._decode(w, x.is_scaled)
return v
if isinstance(x, PondPrivateTensor):
x0, x1 = x.unwrapped
w = self._reconstruct(x0, x1)
v = self._decode(w, x.is_scaled)
return v
if isinstance(x, PondMaskedTensor):
x0, x1 = x.unmasked.unwrapped
w = self._reconstruct(x0, x1)
v = self._decode(w, x.is_scaled)
return v
raise TypeError(
("Don't know how to process input argument " "of type {}").format(
type(x)
)
)
with tf.name_scope(name_scope if name_scope else "local-computation"):
with tf.device(player.device_name):
if arguments is None:
inputs = []
else:
if not isinstance(arguments, (list, tuple)):
arguments = [arguments]
inputs = [reconstruct_input(x) for x in arguments]
outputs = computation_fn(*inputs)
if outputs is None:
return None
if isinstance(outputs, tf.Tensor):
return share_output(outputs)
if isinstance(outputs, (list, tuple)):
return [share_output(output) for output in outputs]
raise TypeError(
"Don't know how to handle results of "
"type {}".format(type(outputs))
)
def define_private_input(
self,
player,
inputter_fn,
apply_scaling: bool = True,
name_scope: Optional[str] = None,
masked: bool = False,
factory: Optional[AbstractFactory] = None,
):
"""
Define a private input.
This represents a `private` input owned by the specified player into the
graph.
:param Union[str,Player] player: Which player owns this input.
:param bool apply_scaling: Whether or not to scale the value.
:param str name_scope: What name to give to this node in the graph.
:param bool masked: Whether or not to mask the input.
:param AbstractFactory factory: Which backing type to use for this input
(e.g. `int100` or `int64`).
"""
return self.define_local_computation(
player=player,
computation_fn=inputter_fn,
arguments=[],
apply_scaling=apply_scaling,
name_scope=name_scope if name_scope else "private-input",
masked=masked,
factory=factory,
)
def define_output(
self,
player,
arguments,
outputter_fn,
name_scope=None,
):
"""
Define an output for this graph.
:param player: Which player this output will be sent to.
"""
return self.define_local_computation(
player=player,
computation_fn=outputter_fn,
arguments=arguments,
name_scope=name_scope if name_scope else "output",
)
def from_bone(self, tensor_bone):
factory = factories[tensor_bone.factory]
if isinstance(tensor_bone, PondPublicTensorBone):
with tf.device(self.server_0.device_name):
value_0 = factory.tensor(tensor_bone.values[0]).identity()
with tf.device(self.server_1.device_name):
value_1 = factory.tensor(tensor_bone.values[1]).identity()
return PondPublicTensor(
self, value_0, value_1, is_scaled=tensor_bone.is_scaled
)
elif isinstance(tensor_bone, PondPrivateTensorBone):
with tf.device(self.server_0.device_name):
value_0 = factory.tensor(tensor_bone.values[0]).identity()
with tf.device(self.server_1.device_name):
value_1 = factory.tensor(tensor_bone.values[1]).identity()
return PondPrivateTensor(
self, value_0, value_1, is_scaled=tensor_bone.is_scaled
)
elif isinstance(tensor_bone, PondMaskedTensorBone):
with tf.device(self.server_0.device_name):
a0 = factory.tensor(tensor_bone.a0).identity()
alpha_on_0 = factory.tensor(tensor_bone.alpha_on_0).identity()
with tf.device(self.server_1.device_name):
a1 = factory.tensor(tensor_bone.a1).identity()
alpha_on_1 = factory.tensor(tensor_bone.alpha_on_1).identity()
with tf.device(self.triple_source.producer.device_name):
a = factory.tensor(tensor_bone.a).identity()
return PondMaskedTensor(
self,
self.from_bone(tensor_bone.unmasked),
a,
a0,
a1,
alpha_on_0,
alpha_on_1,
is_scaled=tensor_bone.is_scaled,
)
else:
raise TypeError(
"Don't know how to handle type {}".format(type(tensor_bone))
)
def _encode(
self,
rationals: Union[tf.Tensor, np.ndarray],
apply_scaling: bool,
tf_int_type=None,
) -> Union[tf.Tensor, np.ndarray]:
"""
Encode tensor of rational numbers into tensor of ring elements. Output is
of same type as input to allow function to be used for constants.
"""
with tf.name_scope("encode"):
if isinstance(rationals, np.ndarray):
if apply_scaling:
# First converting to float64, otherwise the scaling
# would not work as expected for input np array of type int32
scaled = rationals.astype(np.float64)
scaled = scaled * self.fixedpoint_config.scaling_factor
else:
scaled = rationals
integers = np.array(scaled).astype(np.int64)
elif isinstance(rationals, tf.Tensor):
tf_int_type = tf_int_type or (
scaled.dtype
if scaled.dtype in TF_INT_TYPES
else self.tensor_factory.native_type
)
assert tf_int_type in TF_INT_TYPES
if apply_scaling:
# First converting to float64, otherwise the scaling
# would not work as expected for input np array of type int32
scaled = tf.cast(rationals, tf.float64)
scaled = scaled * self.fixedpoint_config.scaling_factor
else:
scaled = rationals
integers = tf.cast(scaled, dtype=tf_int_type)
else:
# give it a last try
try:
scaled = np.array(rationals)
if apply_scaling:
# First converting to float64, otherwise the scaling
# would not work as expected for input np array of type int32
scaled = scaled.astype(np.float64)
scaled = np.array(
scaled * self.fixedpoint_config.scaling_factor
)
integers = scaled.astype(np.int64)
except: # noqa:E722
raise TypeError(
"Don't know how to encode {}".format(type(rationals))
)
return integers
@memoize
def _decode(
self,
elements: AbstractTensor,
is_scaled: bool,
) -> Union[tf.Tensor, np.ndarray]:
"""Decode tensor of ring elements into tensor of rational numbers."""
with tf.name_scope("decode"):
bound = self.fixedpoint_config.bound_single_precision
scaled = (elements + bound).to_native() - bound
if not is_scaled:
return scaled
return scaled / self.fixedpoint_config.scaling_factor
def _share(
self,
secret: AbstractTensor,
) -> Tuple[AbstractTensor, AbstractTensor]:
"""Secret-share an AbstractTensor.
Args:
secret: `AbstractTensor`, the tensor to share.
Returns:
A pair of `AbstractTensor`, the shares.
"""
with tf.name_scope("share"):
share0 = secret.factory.sample_uniform(secret.shape)
share1 = secret - share0
# randomized swap to distribute load between two servers wrt who gets
# the seed
if random.random() < 0.5:
share0, share1 = share1, share0
return share0, share1
def _share_and_wrap(
self,
secret: AbstractTensor,
is_scaled: bool,
) -> "PondPrivateTensor":
s0, s1 = self._share(secret)
return PondPrivateTensor(self, s0, s1, is_scaled)
def _reconstruct(self, share0, share1):
with tf.name_scope("reconstruct"):
return share0 + share1
@memoize
def assign(
self,
variable: Union["PondPrivateVariable", "PondPublicVariable"],
value,
) -> tf.Operation:
"""See tf.assign."""
if isinstance(variable, PondPrivateVariable):
assert isinstance(value, PondPrivateTensor), type(value)
assert variable.is_scaled == value.is_scaled, (
"Scaling must match: {}, {}"
).format(variable.is_scaled, value.is_scaled)
var0, var1 = variable.variable0, variable.variable1
val0, val1 = value.share0, value.share1
with tf.name_scope("assign"):
with tf.device(self.server_0.device_name):
var0.assign(val0)
with tf.device(self.server_1.device_name):
var1.assign(val1)
elif isinstance(variable, PondPublicVariable):
assert isinstance(value, PondPublicTensor), type(value)
assert (
variable.is_scaled == value.is_scaled
), "Scaling must match: {}, {}".format(
variable.is_scaled,
value.is_scaled,
)
var0, var1 = variable.variable_on_0, variable.variable_on_1
val0, val1 = value.value_on_0, value.value_on_1
with tf.name_scope("assign"):
with tf.device(self.server_0.device_name):
var0.assign(val0)
with tf.device(self.server_1.device_name):
var1.assign(val1)
else:
raise TypeError(
("Don't know how to handle variable " "of type {}").format(
type(variable)
)
)
@memoize
def add(self, x, y):
"""
add(x, y) -> PondTensor
Adds two tensors `x` and `y`.
:param PondTensor x: The first operand.
:param PondTensor y: The second operand.
"""
x, y = self.lift(x, y)
return self.dispatch("add", x, y)
# pylint: disable=inconsistent-return-statements
def lift(self, x, y=None, apply_scaling: Optional[bool] = None):
"""
lift(x, y=None, apply_scaling=None) -> PondTensor(s)
Convenience method for working with mixed typed tensors in programs:
combining any of the Pond objects together with e.g. ints and floats
will automatically lift the latter into Pond objects.
:param int,float,PondTensor x: Python object to lift.
:param int,float,PondTensor y: Second Python object to lift, optional.
:param bool apply_scaling: Whether to apply scaling to the input object(s).
"""
if y is None:
if isinstance(x, (int, float)):
return self.define_constant(np.array(x))
if isinstance(x, PondTensor):
return x
raise TypeError("Don't know how to lift {}".format(type(x)))
if isinstance(x, (int, float)):
if isinstance(y, (int, float)):
x = self.define_constant(np.array(x))
y = self.define_constant(np.array(y))
return x, y
if isinstance(y, PondTensor):
x = self.define_constant(
np.array(x),
apply_scaling=apply_scaling or y.is_scaled,
factory=y.backing_dtype,
)
return x, y
raise TypeError(
("Don't know how to lift " "{}, {}").format(type(x), type(y))
)
if isinstance(x, PondTensor):
if isinstance(y, (int, float)):
y = self.define_constant(
np.array(y),
apply_scaling=apply_scaling or x.is_scaled,
factory=x.backing_dtype,
)
return x, y
if isinstance(y, PondTensor):
return x, y
raise TypeError(("Don't know how to lift " "{}, {}").format(type(x), type(y)))
# pylint: enable=inconsistent-return-statements
@memoize
def add_n(self, tensors):
# TODO(Morten) we could optimize by doing lazy reductions, potentially
# segmenting as needed
return reduce(lambda x, y: x + y, tensors)
@memoize
def reduce_sum(self, x, axis=None, keepdims=None):
x = self.lift(x)
return self.dispatch("reduce_sum", x, axis=axis, keepdims=keepdims)
def sum(self, x, axis=None, keepdims=None):
return self.reduce_sum(x, axis, keepdims)
@memoize
def cumsum(self, x, axis=0, exclusive=False, reverse=False):
return self.dispatch(
"cumsum",
x,
axis=axis,
exclusive=exclusive,
reverse=reverse,
)
@memoize
def sub(self, x, y):
x, y = self.lift(x, y)
return self.dispatch("sub", x, y)
def mask(self, x):
"""Convert to a PondMaskedTensor."""
if isinstance(x, (list, tuple)):
# apply recursively
return [self.mask(xi) for xi in x]
node_key = ("mask", x)
x_masked = nodes.get(node_key, None)
if x_masked is not None:
return x_masked
if isinstance(x, PondPrivateTensor):
x_masked = _mask_private(self, x)
else:
raise TypeError("Don't know how to mask {}".format(type(x)))
nodes[node_key] = x_masked
return x_masked
@memoize
def mul(self, x, y):
x, y = self.lift(x, y)
return self.dispatch("mul", x, y)
@memoize
def square(self, x):