/
building_block_factory.py
1880 lines (1591 loc) · 76.4 KB
/
building_block_factory.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
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A library of contruction functions for building block structures."""
import random
import string
from typing import List, Sequence, Tuple
import tensorflow as tf
from tensorflow_federated.proto.v0 import computation_pb2 as pb
from tensorflow_federated.python.common_libs import anonymous_tuple
from tensorflow_federated.python.common_libs import py_typecheck
from tensorflow_federated.python.common_libs import serialization_utils
from tensorflow_federated.python.core.api import computation_types
from tensorflow_federated.python.core.impl import type_utils
from tensorflow_federated.python.core.impl.compiler import building_blocks
from tensorflow_federated.python.core.impl.compiler import intrinsic_defs
from tensorflow_federated.python.core.impl.compiler import tensorflow_computation_factory
from tensorflow_federated.python.core.impl.compiler import transformation_utils
from tensorflow_federated.python.core.impl.types import placement_literals
from tensorflow_federated.python.core.impl.types import type_analysis
from tensorflow_federated.python.core.impl.types import type_conversions
from tensorflow_federated.python.core.impl.types import type_serialization
from tensorflow_federated.python.core.impl.utils import tensorflow_utils
def unique_name_generator(comp, prefix='_var'):
"""Yields a new unique name that does not exist in `comp`.
Args:
comp: The compuation building block to use as a reference.
prefix: The prefix to use when generating unique names. If `prefix` is
`None` or if `comp` contains any name with this prefix, then a unique
prefix will be generated from random lowercase ascii characters.
"""
if comp is not None:
names = transformation_utils.get_unique_names(comp)
else:
names = set()
while prefix is None or any(n.startswith(prefix) for n in names):
characters = string.ascii_lowercase
prefix = '_{}'.format(''.join(random.choice(characters) for _ in range(3)))
index = 1
while True:
yield '{}{}'.format(prefix, index)
index += 1
def create_compiled_empty_tuple():
"""Returns called graph representing the empty tuple.
Returns:
An instance of `building_blocks.Call`, calling a noarg function
which returns an empty tuple. This function is an instance of
`building_blocks.CompiledComputation`.
"""
proto = tensorflow_computation_factory.create_empty_tuple()
compiled = building_blocks.CompiledComputation(proto)
return building_blocks.Call(compiled, None)
def create_compiled_identity(type_signature, name=None):
"""Creates CompiledComputation representing identity function.
Args:
type_signature: Argument convertible to instance of `computation_types.Type`
via `computation_types.to_type`.
name: An optional string name to use as the name of the computation.
Returns:
An instance of `building_blocks.CompiledComputation`
representing the identity function taking an argument of type
`type_signature` and returning the same value.
Raises:
TypeError: If `type_signature` contains any types which cannot appear in
TensorFlow bindings.
"""
proto = tensorflow_computation_factory.create_identity(type_signature)
return building_blocks.CompiledComputation(proto, name)
class SelectionSpec(object):
"""Data class representing map from input tuple to selection of result.
Attributes:
tuple_index: The index of the source of the selection sequence in the
desired result of the generated TensorFlow. If this `SelectionSpec`
appears at index i of a list of `SelectionSpec`s, index j is the source
for the result of the generated function at index i.
selection_sequence: A list or tuple representing the selections to make from
`tuple_index`, so that the list `[0]` for example would represent the
output is the 0th element of `tuple_index`, while `[0, 0]` would represent
that the output is the 0th element of the 0th element of `tuple_index`.
"""
def __init__(self, tuple_index: int, selection_sequence: Sequence[int]):
self._tuple_index = tuple_index
self._selection_sequence = selection_sequence
@property
def tuple_index(self):
return self._tuple_index
@property
def selection_sequence(self):
return self._selection_sequence
def __str__(self):
return 'SelectionSequence(tuple_index={},selection_sequence={}'.format(
self._tuple_index, self._selection_sequence)
def __repr__(self):
return str(self)
def _extract_selections(parameter_value, output_spec):
results = []
for selection_spec in output_spec:
result_element = parameter_value[selection_spec.tuple_index]
for selection in selection_spec.selection_sequence:
py_typecheck.check_type(selection, int)
result_element = result_element[selection]
results.append(result_element)
return results
def construct_tensorflow_selecting_and_packing_outputs(
arg_type, output_structure: anonymous_tuple.AnonymousTuple):
"""Constructs TensorFlow selecting and packing elements from its input.
The result of this function can be called on a deduplicated
`building_blocks.Tuple` containing called graphs, thus preventing us from
embedding the same TensorFlow computation in the generated graphs, and
reducing the amount of work duplicated in the process of generating
TensorFlow.
The TensorFlow which results here will be a function which takes an argument
of type `arg_type`, returning a result specified by `output_structure`. Each
`SelectionSpec` nested inside of `output_structure` will represent a selection
from one of the arguments of the tuple `arg_type`, with the empty selection
being a possibility. The nested structure of `output_structure` will determine
how these selections are packed back into a result, IE, the result of the
function will be a nested tuple with the same structure as `output_structure`,
where the leaves of this structure (the `SelectionSpecs` of
`output_structure`) will be selections from the argument.
Args:
arg_type: `computation_types.Type` of the argument on which the constructed
function will be called. Should be an instance of
`computation_types.NamedTupleType`.
output_structure: `anonymous_tuple.AnonymousTuple` with `SelectionSpec` or
`anonymous_tupl.AnonymousTuple` elements, mapping from elements of the
nested argument tuple to the desired result of the generated computation.
`output_structure` must contain all the names desired on the output of the
computation.
Returns:
A `building_blocks.CompiledComputation` representing the specification
above.
Raises:
TypeError: If `arg_type` is not a `computation_types.NamedTupleType`, or
represents a type which cannot act as an input or output to a TensorFlow
computation in TFF, IE does not contain exclusively
`computation_types.SequenceType`, `computation_types.NamedTupleType` or
`computation_types.TensorType`.
"""
py_typecheck.check_type(output_structure, anonymous_tuple.AnonymousTuple)
def _check_output_structure(elem):
if isinstance(elem, anonymous_tuple.AnonymousTuple):
for x in elem:
_check_output_structure(x)
elif not isinstance(elem, SelectionSpec):
raise TypeError('output_structure can only contain nested anonymous '
'tuples and `SelectionSpecs`; encountered the value {} '
'of type {}.'.format(elem, type(elem)))
_check_output_structure(output_structure)
output_spec = anonymous_tuple.flatten(output_structure)
type_spec = computation_types.to_type(arg_type)
py_typecheck.check_type(type_spec, computation_types.NamedTupleType)
type_utils.check_tensorflow_compatible_type(type_spec)
with tf.Graph().as_default() as graph:
parameter_value, parameter_binding = tensorflow_utils.stamp_parameter_in_graph(
'x', type_spec, graph)
results = _extract_selections(parameter_value, output_spec)
repacked_result = anonymous_tuple.pack_sequence_as(output_structure, results)
result_type, result_binding = tensorflow_utils.capture_result_from_graph(
repacked_result, graph)
function_type = computation_types.FunctionType(type_spec, result_type)
serialized_function_type = type_serialization.serialize_type(function_type)
proto = pb.Computation(
type=serialized_function_type,
tensorflow=pb.TensorFlow(
graph_def=serialization_utils.pack_graph_def(graph.as_graph_def()),
parameter=parameter_binding,
result=result_binding))
return building_blocks.CompiledComputation(proto)
def create_tensorflow_constant(type_spec, scalar_value, name=None):
"""Creates called graph returning constant `scalar_value` of type `type_spec`.
`scalar_value` must be a scalar, and cannot be a float if any of the tensor
leaves of `type_spec` contain an integer data type. `type_spec` must contain
only named tuples and tensor types, but these can be arbitrarily nested.
Args:
type_spec: Value convertible to `computation_types.Type` via
`computation_types.to_type`, and whose resulting type tree can only
contain named tuples and tensors.
scalar_value: Scalar value to place in all the tensor leaves of `type_spec`.
name: An optional string name to use as the name of the computation.
Returns:
An instance of `building_blocks.Call`, whose argument is `None`
and whose function is a noarg
`building_blocks.CompiledComputation` which returns the
specified `scalar_value` packed into a TFF structure of type `type_spec.
Raises:
TypeError: If the type assumptions above are violated.
"""
proto = tensorflow_computation_factory.create_constant(
scalar_value, type_spec)
compiled = building_blocks.CompiledComputation(proto, name)
return building_blocks.Call(compiled, None)
def create_compiled_input_replication(type_signature, n_replicas):
"""Creates a compiled computation which replicates its argument.
Args:
type_signature: Value convertible to `computation_types.Type` via
`computation_types.to_type`. The type of the parameter of the constructed
computation.
n_replicas: Integer, the number of times the argument is intended to be
replicated.
Returns:
An instance of `building_blocks.CompiledComputation` encoding
a function taking a single argument fo type `type_signature` and returning
`n_replicas` identical copies of this argument.
Raises:
TypeError: If `type_signature` contains any types which cannot appear in
TensorFlow bindings, or if `n_replicas` is not an integer.
"""
proto = tensorflow_computation_factory.create_replicate_input(
type_signature, n_replicas)
return building_blocks.CompiledComputation(proto)
def create_tensorflow_to_broadcast_scalar(scalar_type, new_shape):
"""Creates TF function broadcasting scalar to shape `new_shape`.
Args:
scalar_type: Instance of `tf.DType`, the type of the scalar we are looking
to broadcast.
new_shape: Instance of `tf.TensorShape`, the shape we wish to broadcast to.
Must be fully defined.
Returns:
Instance of `building_blocks.CompiledComputation` representing
a function declaring a scalar parameter of dtype `scalar_type`, and
returning a tensor of this same dtype and shape `new_shape`, with the same
value in each entry as its scalar argument.
Raises:
TypeError: If the types of the arguments do not match the declared arg
types.
ValueError: If `new_shape` is not fully defined.
"""
proto = tensorflow_computation_factory.create_broadcast_scalar_to_shape(
scalar_type, new_shape)
return building_blocks.CompiledComputation(proto)
def create_tensorflow_binary_operator(operand_type, operator):
"""Creates a TensorFlow computation for the binary `operator`.
For `T` the `operand_type`, the type signature of the constructed operator
will be `(<T,T> -> U)`, where `U` is the result of applying `operator` to
a tuple of type `<T,T>`.
Notice that we have quite serious restrictions on `operand_type` here; not
only must it be compatible with stamping into a TensorFlow graph, but
additionally cannot contain a `computation_types.SequenceType`, as checked by
`type_utils.is_generic_op_compatible_type`.
Notice also that if `operand_type` is a `computation_types.NamedTupleType`,
`operator` will be applied pointwise. This places the burden on callers of
this function to construct the correct values to pass into the returned
function. For example, to divide `[2, 2]` by `2`, first the `int 2` must
be packed into the data structure `[x, x]`, before the division operator of
the appropriate type is called.
Args:
operand_type: The type of argument to the constructed binary operator. Must
be convertible to `computation_types.Type`.
operator: Callable taking two arguments specifying the operation to encode.
For example, `tf.add`, `tf.multiply`, `tf.divide`, ...
Returns:
Instance of `building_blocks.CompiledComputation` encoding
this binary operator.
Raises:
TypeError: If the type tree of `operand_type` contains any type which is
incompatible with the TFF generic operators, as checked by
`type_utils.is_generic_op_compatible_type`, or `operator` is not callable.
"""
proto = tensorflow_computation_factory.create_binary_operator(
operator, operand_type)
return building_blocks.CompiledComputation(proto)
def create_federated_getitem_call(arg, idx):
"""Creates computation building block passing getitem to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computation_types.FederatedType` with member of type
`computation_types.NamedTupleType` from which we wish to pick out item
`idx`.
idx: Index, instance of `int` or `slice` used to address the
`computation_types.NamedTupleType` underlying `arg`.
Returns:
Returns a `building_blocks.Call` with type signature
`computation_types.FederatedType` of same placement as `arg`, the result
of applying or mapping the appropriate `__getitem__` function, as defined
by `idx`.
"""
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(idx, (int, slice))
py_typecheck.check_type(arg.type_signature, computation_types.FederatedType)
py_typecheck.check_type(arg.type_signature.member,
computation_types.NamedTupleType)
getitem_comp = create_federated_getitem_comp(arg, idx)
return create_federated_map_or_apply(getitem_comp, arg)
def create_federated_getattr_call(arg, name):
"""Creates computation building block passing getattr to federated value.
Args:
arg: Instance of `building_blocks.ComputationBuildingBlock` of
`computation_types.FederatedType` with member of type
`computation_types.NamedTupleType` from which we wish to pick out item
`name`.
name: String name to address the `computation_types.NamedTupleType`
underlying `arg`.
Returns:
Returns a `building_blocks.Call` with type signature
`computation_types.FederatedType` of same placement as `arg`,
the result of applying or mapping the appropriate `__getattr__` function,
as defined by `name`.
"""
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(name, str)
py_typecheck.check_type(arg.type_signature, computation_types.FederatedType)
py_typecheck.check_type(arg.type_signature.member,
computation_types.NamedTupleType)
getattr_comp = create_federated_getattr_comp(arg, name)
return create_federated_map_or_apply(getattr_comp, arg)
def create_federated_setattr_call(federated_comp, name, value_comp):
"""Returns building block for `setattr(name, value_comp)` on `federated_comp`.
Creates an appropriate communication intrinsic (either `federated_map` or
`federated_apply`) as well as a `building_blocks.Lambda`
representing setting the `name` attribute of `federated_comp`'s `member` to
`value_comp`, and stitches these together in a call.
Notice that `federated_comp`'s `member` must actually define a `name`
attribute; this is enforced to avoid the need to worry about theplacement of a
previously undefined name.
Args:
federated_comp: Instance of `building_blocks.ComputationBuildingBlock` of
type `computation_types.FederatedType`, with member of type
`computation_types.NamedTupleType` whose attribute `name` we wish to set
to `value_comp`.
name: String name of the attribute we wish to overwrite in `federated_comp`.
value_comp: Instance of `building_blocks.ComputationBuildingBlock`, the
value to assign to `federated_comp`'s `member`'s `name` attribute.
Returns:
Instance of `building_blocks.ComputationBuildingBlock`
representing `federated_comp` with its `member`'s `name` attribute set to
`value`.
"""
py_typecheck.check_type(federated_comp,
building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(name, str)
py_typecheck.check_type(value_comp, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(federated_comp.type_signature,
computation_types.FederatedType)
py_typecheck.check_type(federated_comp.type_signature.member,
computation_types.NamedTupleType)
named_tuple_type_signature = federated_comp.type_signature.member
setattr_lambda = create_named_tuple_setattr_lambda(named_tuple_type_signature,
name, value_comp)
return create_federated_map_or_apply(setattr_lambda, federated_comp)
def create_named_tuple_setattr_lambda(named_tuple_signature, name, value_comp):
"""Creates a building block for replacing one attribute in a named tuple.
Returns an instance of `building_blocks.Lambda` which takes an
argument of type `computation_types.NamedTupleType` and returns a
`building_blocks.Tuple` which contains all the same elements as
the argument, except the attribute `name` now has value `value_comp`. The
Lambda constructed is the analogue of Python's `setattr` for the concrete
type `named_tuple_signature`.
Args:
named_tuple_signature: Instance of `computation_types.NamedTupleType`, the
type of the argument to the constructed `building_blocks.Lambda`.
name: String name of the attribute in the `named_tuple_signature` to replace
with `value_comp`. Must be present as a name in `named_tuple_signature;
otherwise we will raise an `AttributeError`.
value_comp: Instance of `building_blocks.ComputationBuildingBlock`, the
value to place as attribute `name` in the argument of the returned
function.
Returns:
An instance of `building_blocks.Block` of functional type
representing setting attribute `name` to value `value_comp` in its argument
of type `named_tuple_signature`.
Raises:
TypeError: If the types of the arguments don't match the assumptions above.
AttributeError: If `name` is not present as a named element in
`named_tuple_signature`
"""
py_typecheck.check_type(named_tuple_signature,
computation_types.NamedTupleType)
py_typecheck.check_type(name, str)
py_typecheck.check_type(value_comp, building_blocks.ComputationBuildingBlock)
value_comp_placeholder = building_blocks.Reference('value_comp_placeholder',
value_comp.type_signature)
lambda_arg = building_blocks.Reference('lambda_arg', named_tuple_signature)
if name not in dir(named_tuple_signature):
raise AttributeError(
'There is no such attribute as \'{name}\' in this federated tuple. '
'TFF does not allow for assigning to a nonexistent attribute. '
'If you want to assign to \'{name}\', you must create a new named '
'tuple containing this attribute.'.format(name=name))
elements = []
for idx, (key, element_type) in enumerate(
anonymous_tuple.to_elements(named_tuple_signature)):
if key == name:
if not type_utils.is_assignable_from(element_type,
value_comp.type_signature):
raise TypeError(
'`setattr` has attempted to set element {} of type {} with incompatible type {}'
.format(key, element_type, value_comp.type_signature))
elements.append((key, value_comp_placeholder))
else:
elements.append((key, building_blocks.Selection(lambda_arg, index=idx)))
return_tuple = building_blocks.Tuple(elements)
lambda_to_return = building_blocks.Lambda(lambda_arg.name,
named_tuple_signature, return_tuple)
symbols = ((value_comp_placeholder.name, value_comp),)
return building_blocks.Block(symbols, lambda_to_return)
def create_federated_getattr_comp(comp, name):
"""Function to construct computation for `federated_apply` of `__getattr__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `name` from its argument, of type `comp.type_signature.member`,
an instance of `computation_types.NamedTupleType`.
Args:
comp: Instance of `building_blocks.ComputationBuildingBlock` with type
signature `computation_types.FederatedType` whose `member` attribute is of
type `computation_types.NamedTupleType`.
name: String name of attribute to grab.
Returns:
Instance of `building_blocks.Lambda` which grabs attribute
according to `name` of its argument.
"""
py_typecheck.check_type(comp, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(comp.type_signature, computation_types.FederatedType)
py_typecheck.check_type(comp.type_signature.member,
computation_types.NamedTupleType)
py_typecheck.check_type(name, str)
element_names = [
x for x, _ in anonymous_tuple.iter_elements(comp.type_signature.member)
]
if name not in element_names:
raise ValueError(
'The federated value has no element of name `{}`. Value: {}'.format(
name, comp.formatted_representation()))
apply_input = building_blocks.Reference('x', comp.type_signature.member)
selected = building_blocks.Selection(apply_input, name=name)
apply_lambda = building_blocks.Lambda('x', apply_input.type_signature,
selected)
return apply_lambda
def create_federated_getitem_comp(comp, key):
"""Function to construct computation for `federated_apply` of `__getitem__`.
Creates a `building_blocks.ComputationBuildingBlock`
which selects `key` from its argument, of type `comp.type_signature.member`,
of type `computation_types.NamedTupleType`.
Args:
comp: Instance of `building_blocks.ComputationBuildingBlock` with type
signature `computation_types.FederatedType` whose `member` attribute is of
type `computation_types.NamedTupleType`.
key: Instance of `int` or `slice`, key used to grab elements from the member
of `comp`. implementation of slicing for `ValueImpl` objects with
`type_signature` `computation_types.NamedTupleType`.
Returns:
Instance of `building_blocks.Lambda` which grabs slice
according to `key` of its argument.
"""
py_typecheck.check_type(comp, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(comp.type_signature, computation_types.FederatedType)
py_typecheck.check_type(comp.type_signature.member,
computation_types.NamedTupleType)
py_typecheck.check_type(key, (int, slice))
apply_input = building_blocks.Reference('x', comp.type_signature.member)
if isinstance(key, int):
selected = building_blocks.Selection(apply_input, index=key)
else:
elems = anonymous_tuple.to_elements(comp.type_signature.member)
index_range = range(*key.indices(len(elems)))
elem_list = []
for k in index_range:
elem_list.append(
(elems[k][0], building_blocks.Selection(apply_input, index=k)))
selected = building_blocks.Tuple(elem_list)
apply_lambda = building_blocks.Lambda('x', apply_input.type_signature,
selected)
return apply_lambda
def create_computation_appending(comp1, comp2):
r"""Returns a block appending `comp2` to `comp1`.
Block
/ \
[comps=Tuple] Tuple
| |
[Comp, Comp] [Sel(0), ..., Sel(0), Sel(1)]
\ \ \
Sel(0) Sel(n) Ref(comps)
\ \
Ref(comps) Ref(comps)
Args:
comp1: A `building_blocks.ComputationBuildingBlock` with a `type_signature`
of type `computation_type.NamedTupleType`.
comp2: A `building_blocks.ComputationBuildingBlock` or a named computation
(a tuple pair of name, computation) representing a single element of an
`anonymous_tuple.AnonymousTuple`.
Returns:
A `building_blocks.Block`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(comp1, building_blocks.ComputationBuildingBlock)
if isinstance(comp2, building_blocks.ComputationBuildingBlock):
name2 = None
elif py_typecheck.is_name_value_pair(
comp2,
name_required=False,
value_type=building_blocks.ComputationBuildingBlock):
name2, comp2 = comp2
else:
raise TypeError('Unexpected tuple element: {}.'.format(comp2))
comps = building_blocks.Tuple((comp1, comp2))
ref = building_blocks.Reference('comps', comps.type_signature)
sel_0 = building_blocks.Selection(ref, index=0)
elements = []
named_type_signatures = anonymous_tuple.to_elements(comp1.type_signature)
for index, (name, _) in enumerate(named_type_signatures):
sel = building_blocks.Selection(sel_0, index=index)
elements.append((name, sel))
sel_1 = building_blocks.Selection(ref, index=1)
elements.append((name2, sel_1))
result = building_blocks.Tuple(elements)
symbols = ((ref.name, comps),)
return building_blocks.Block(symbols, result)
def create_federated_aggregate(value, zero, accumulate, merge, report):
r"""Creates a called federated aggregate.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp, Comp, Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
zero: A `building_blocks.ComputationBuildingBlock` to use as the initial
value.
accumulate: A `building_blocks.ComputationBuildingBlock` to use as the
accumulate function.
merge: A `building_blocks.ComputationBuildingBlock` to use as the merge
function.
report: A `building_blocks.ComputationBuildingBlock` to use as the report
function.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(zero, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(accumulate, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(merge, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(report, building_blocks.ComputationBuildingBlock)
# Its okay if the first argument of accumulate is assignable from the zero,
# without being the exact type. This occurs when accumulate has a type like
# (<int32[?], int32> -> int32[?]) but zero is int32[0].
zero_arg_type = accumulate.type_signature.parameter[0]
type_utils.check_assignable_from(zero_arg_type, zero.type_signature)
result_type = computation_types.FederatedType(report.type_signature.result,
placement_literals.SERVER)
intrinsic_type = computation_types.FunctionType((
type_conversions.type_to_non_all_equal(value.type_signature),
zero_arg_type,
accumulate.type_signature,
merge.type_signature,
report.type_signature,
), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_AGGREGATE.uri,
intrinsic_type)
values = building_blocks.Tuple((value, zero, accumulate, merge, report))
return building_blocks.Call(intrinsic, values)
def create_federated_apply(fn, arg):
r"""Creates a called federated apply.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(fn, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(fn.type_signature.result,
placement_literals.SERVER)
intrinsic_type = computation_types.FunctionType(
(fn.type_signature, arg.type_signature), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_APPLY.uri,
intrinsic_type)
values = building_blocks.Tuple((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_federated_broadcast(value):
r"""Creates a called federated broadcast.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(
value.type_signature.member, placement_literals.CLIENTS, all_equal=True)
intrinsic_type = computation_types.FunctionType(value.type_signature,
result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_BROADCAST.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_collect(value):
r"""Creates a called federated collect.
Call
/ \
Intrinsic Comp
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
type_signature = computation_types.SequenceType(value.type_signature.member)
result_type = computation_types.FederatedType(type_signature,
placement_literals.SERVER)
intrinsic_type = computation_types.FunctionType(
type_conversions.type_to_non_all_equal(value.type_signature), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_COLLECT.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_eval(
fn: building_blocks.ComputationBuildingBlock,
placement: placement_literals.PlacementLiteral,
) -> building_blocks.ComputationBuildingBlock:
r"""Creates a called federated eval.
Call
/ \
Intrinsic Comp
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
placement: A `placement_literals.PlacementLiteral` to use as the placement.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(fn, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(fn.type_signature, computation_types.FunctionType)
if placement is placement_literals.CLIENTS:
uri = intrinsic_defs.FEDERATED_EVAL_AT_CLIENTS.uri
all_equal = False
elif placement is placement_literals.SERVER:
uri = intrinsic_defs.FEDERATED_EVAL_AT_SERVER.uri
all_equal = True
else:
raise TypeError('Unsupported placement {}.'.format(placement))
result_type = computation_types.FederatedType(
fn.type_signature.result, placement, all_equal=all_equal)
intrinsic_type = computation_types.FunctionType(fn.type_signature,
result_type)
intrinsic = building_blocks.Intrinsic(uri, intrinsic_type)
return building_blocks.Call(intrinsic, fn)
def create_federated_map(fn, arg):
r"""Creates a called federated map.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(fn, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
parameter_type = computation_types.FederatedType(arg.type_signature.member,
placement_literals.CLIENTS)
result_type = computation_types.FederatedType(fn.type_signature.result,
placement_literals.CLIENTS)
intrinsic_type = computation_types.FunctionType(
(fn.type_signature, parameter_type), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_MAP.uri,
intrinsic_type)
values = building_blocks.Tuple((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_federated_map_all_equal(fn, arg):
r"""Creates a called federated map of equal values.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Note: The `fn` is required to be deterministic and therefore should contain no
`building_blocks.CompiledComputations`.
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(fn, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
parameter_type = computation_types.FederatedType(
arg.type_signature.member, placement_literals.CLIENTS, all_equal=True)
result_type = computation_types.FederatedType(
fn.type_signature.result, placement_literals.CLIENTS, all_equal=True)
intrinsic_type = computation_types.FunctionType(
(fn.type_signature, parameter_type), result_type)
intrinsic = building_blocks.Intrinsic(
intrinsic_defs.FEDERATED_MAP_ALL_EQUAL.uri, intrinsic_type)
values = building_blocks.Tuple((fn, arg))
return building_blocks.Call(intrinsic, values)
def create_federated_map_or_apply(fn, arg):
r"""Creates a called federated map or apply depending on `arg`s placement.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
fn: A `building_blocks.ComputationBuildingBlock` to use as the function.
arg: A `building_blocks.ComputationBuildingBlock` to use as the argument.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(fn, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(arg, building_blocks.ComputationBuildingBlock)
if arg.type_signature.placement is placement_literals.CLIENTS:
if arg.type_signature.all_equal:
return create_federated_map_all_equal(fn, arg)
else:
return create_federated_map(fn, arg)
elif arg.type_signature.placement is placement_literals.SERVER:
return create_federated_apply(fn, arg)
else:
raise TypeError('Unsupported placement {}.'.format(
arg.type_signature.placement))
def create_federated_mean(value, weight):
r"""Creates a called federated mean.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
weight: A `building_blocks.ComputationBuildingBlock` to use as the weight or
`None`.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
if weight is not None:
py_typecheck.check_type(weight, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(value.type_signature.member,
placement_literals.SERVER)
if weight is not None:
intrinsic_type = computation_types.FunctionType(
(type_conversions.type_to_non_all_equal(value.type_signature),
type_conversions.type_to_non_all_equal(weight.type_signature)),
result_type)
intrinsic = building_blocks.Intrinsic(
intrinsic_defs.FEDERATED_WEIGHTED_MEAN.uri, intrinsic_type)
values = building_blocks.Tuple((value, weight))
return building_blocks.Call(intrinsic, values)
else:
intrinsic_type = computation_types.FunctionType(
type_conversions.type_to_non_all_equal(value.type_signature),
result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_MEAN.uri,
intrinsic_type)
return building_blocks.Call(intrinsic, value)
def create_federated_reduce(value, zero, op):
r"""Creates a called federated reduce.
Call
/ \
Intrinsic Tuple
|
[Comp, Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
zero: A `building_blocks.ComputationBuildingBlock` to use as the initial
value.
op: A `building_blocks.ComputationBuildingBlock` to use as the op function.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(zero, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(op, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(op.type_signature.result,
placement_literals.SERVER)
intrinsic_type = computation_types.FunctionType((
type_conversions.type_to_non_all_equal(value.type_signature),
zero.type_signature,
op.type_signature,
), result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_REDUCE.uri,
intrinsic_type)
values = building_blocks.Tuple((value, zero, op))
return building_blocks.Call(intrinsic, values)
def create_federated_secure_sum(value, bitwidth):
r"""Creates a called secure sum.
Call
/ \
Intrinsic [Comp, Comp]
Args:
value: A `building_blocks.ComputationBuildingBlock` to use as the value.
bitwidth: A `building_blocks.ComputationBuildingBlock` to use as the
bitwidth value.
Returns:
A `building_blocks.Call`.
Raises:
TypeError: If any of the types do not match.
"""
py_typecheck.check_type(value, building_blocks.ComputationBuildingBlock)
py_typecheck.check_type(bitwidth, building_blocks.ComputationBuildingBlock)
result_type = computation_types.FederatedType(value.type_signature.member,
placement_literals.SERVER)
intrinsic_type = computation_types.FunctionType([
type_conversions.type_to_non_all_equal(value.type_signature),
bitwidth.type_signature,
], result_type)
intrinsic = building_blocks.Intrinsic(intrinsic_defs.FEDERATED_SECURE_SUM.uri,
intrinsic_type)
values = building_blocks.Tuple([value, bitwidth])