Repository navigation
Expand file tree
/
Copy pathfunction.py
More file actions
1942 lines (1656 loc) · 76.4 KB
/
Copy pathfunction.py
File metadata and controls
1942 lines (1656 loc) · 76.4 KB
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
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
# pylint: disable=unidiomatic-typecheck
"""Defun decorator for defining graph-mode functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import threading
import types as types_lib
import weakref
import numpy as np
import six
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import function_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.eager import execute
from tensorflow.python.eager import tape
from tensorflow.python.eager.graph_only_ops import graph_placeholder
from tensorflow.python.framework import c_api_util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import device as pydev
from tensorflow.python.framework import dtypes as dtypes_module
from tensorflow.python.framework import error_interpolation
from tensorflow.python.framework import errors
from tensorflow.python.framework import func_graph as func_graph_module
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_spec
from tensorflow.python.ops import custom_gradient
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import gradients_util
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
from tensorflow.python.util import function_utils
from tensorflow.python.util import memory
from tensorflow.python.util import nest
from tensorflow.python.util import tf_decorator
from tensorflow.python.util import tf_inspect
FORWARD_FUNCTION_ATTRIBUTE_NAME = "forward_function_name"
BACKWARD_FUNCTION_ATTRIBUTE_NAME = "backward_function_name"
CacheKey = collections.namedtuple("CacheKey", [
"input_signature", "parent_graph", "device_functions", "colocation_stack",
"uses_xla"
])
def is_same_structure(structure1,
structure2,
check_values=False):
"""Check two structures for equality, optionally of types and of values."""
try:
nest.assert_same_structure(structure1, structure2)
except (ValueError, TypeError):
return False
if check_values:
flattened1 = nest.flatten(structure1)
flattened2 = nest.flatten(structure2)
# First check the types to avoid AttributeErrors.
if any(type(f1) != type(f2) for f1, f2 in zip(flattened1, flattened2)):
return False
return flattened1 == flattened2
return True
def _parse_func_attrs(attributes):
"""Convert the keyword arguments into function_def attributes.
Currently only support primitive types: bool, int, float and string.
Args:
attributes: the dictionary of attributes.
Returns:
A dict of attributes where the key is the name of attribute and the value
is the AttrValue proto.
Raises:
ValueError: If the kwargs contains unwhitelisted name or unsupported value
types.
"""
attrs = {}
for key, value in attributes.items():
if isinstance(value, attr_value_pb2.AttrValue):
attrs[key] = value
# bool type check has to happen before int since bool is a subclass of int.
elif isinstance(value, bool):
attrs[key] = attr_value_pb2.AttrValue(b=value)
elif isinstance(value, int):
attrs[key] = attr_value_pb2.AttrValue(i=value)
elif isinstance(value, float):
attrs[key] = attr_value_pb2.AttrValue(f=value)
elif isinstance(value, (str, bytes, six.text_type)):
attrs[key] = attr_value_pb2.AttrValue(s=compat.as_bytes(value))
else:
raise ValueError("Unsupported attribute type for %s with type %s" %
(key, type(value)))
return attrs
class _InterpolateFunctionError(object):
"""Context Manager that interpolates the exception from 'top_level_func'."""
def __init__(self, top_level_func):
self._func = top_level_func
def __enter__(self):
pass
def __exit__(self, typ, exc, tb):
if not exc or not isinstance(exc, errors.OpError):
return False
message = compat.as_text(exc.message)
_, tags = error_interpolation.parse_message(message)
g = None
func_stack = []
# pylint: disable=protected-access
for t in tags:
if t.type == "function_node":
if t.name == compat.as_str(self._func.name):
g = self._func._graph
elif g:
next_func = g._get_function(t.name)
if next_func is not None and isinstance(next_func,
_EagerDefinedFunction):
g = next_func._graph
if g:
func_stack.append(g.name)
else:
func_stack.append("<unknown>")
# pylint: enable=protected-access
if g:
message = error_interpolation.interpolate(message, g)
message += "\n\nFunction call stack:\n"
message += " -> ".join(func_stack)
message += "\n"
exc._message = message # pylint: disable=protected-access
return False
def _forward_name(n):
"""The name of a generated forward defun named n."""
return "__forward_%s_%s" % (n, ops.uid())
def _backward_name(n):
"""The name of a generated backward defun named n."""
return "__backward_%s_%s" % (n, ops.uid())
def _inference_name(n):
"""The name of a forward-but-no-gradient defun named n."""
return "__inference_%s_%s" % (n, ops.uid())
# TODO(apassos) get rid of this by splitting framework.function._DefinedFunction
# so it doesn't have the definition-generating logic and is just a container for
# an already-defined function.
class _EagerDefinedFunction(object):
"""Callable with the interface of `framework.function._DefinedFunction`.
`_EagerDefinedFunction` encapsulates a function definition and its properties,
and it provides a method for calling the encapsulated function. Some Ops
take functions as attributes, which have type `func`; an instance of this
class may be provided as the value of these `func` attributes.
"""
def __init__(self, name, graph, inputs, outputs, attrs):
"""Initializes an eager defined function.
Args:
name: str, the name for the created function.
graph: Graph, the graph containing the operations in the function
inputs: the tensors in the graph to be used as inputs to the function
outputs: the tensors in the graph which will be outputs to the function
attrs: dict mapping names of attributes to their AttrValue values
"""
input_ops = set(arg.op for arg in inputs)
operations = [op for op in graph.get_operations() if op not in input_ops]
fn = pywrap_tensorflow.TF_GraphToFunction_wrapper(
graph._c_graph, # pylint: disable=protected-access
compat.as_str(name),
False,
[o._c_op for o in operations], # pylint: disable=protected-access
[t._as_tf_output() for t in inputs], # pylint: disable=protected-access
[t._as_tf_output() for t in outputs], # pylint: disable=protected-access
[],
[t._as_c_op for o in graph.control_outputs],
[], # control_output_names
None,
compat.as_str(""))
for name, attr_value in attrs.items():
serialized = attr_value.SerializeToString()
# TODO(iga): this creates and deletes a new TF_Status for every attr.
# It might be worth creating a convenient way to re-use status.
pywrap_tensorflow.TF_FunctionSetAttrValueProto(
fn, compat.as_str(name), serialized)
# TODO(apassos) avoid creating a FunctionDef (specially to grab the
# signature, but also in general it's nice not to depend on it.
with c_api_util.tf_buffer() as buffer_:
pywrap_tensorflow.TF_FunctionToFunctionDef(fn, buffer_)
proto_data = pywrap_tensorflow.TF_GetBuffer(buffer_)
function_def = function_pb2.FunctionDef()
function_def.ParseFromString(compat.as_bytes(proto_data))
with ops.init_scope():
if context.executing_eagerly():
context.add_function(fn)
self.definition = function_def
self.name = compat.as_bytes(function_def.signature.name)
self.signature = function_def.signature
self._num_outputs = len(self.signature.output_arg)
self._output_types = [o.type for o in self.signature.output_arg]
self._output_shapes = [o.shape for o in outputs]
self._func_graph_outputs = outputs
self.grad_func_name = None
self.python_grad_func = None
self._c_func = c_api_util.ScopedTFFunction(fn)
self._grad_func = None
self._graph = graph
self._stateful_ops = tuple(op for op in operations if op.op_def.is_stateful)
def add_to_graph(self, g=None):
# pylint: disable=protected-access
if not g and context.executing_eagerly():
context.context().add_function_def(self.definition)
else:
if self.name not in g._functions:
g._add_function(self)
for f in self._graph._functions.values():
if f.name not in g._functions:
g._add_function(f)
# pylint: enable=protected-access
@property
def stateful_ops(self):
return self._stateful_ops
def call(self, ctx, args):
"""Calls this function with `args` as inputs.
`ConcreteFunction` execution respects device annotations only if the
function won't be compiled with xla.
Args:
ctx: a Context object
args: a list of arguments to supply this function with.
Returns:
The outputs of the function call.
Raises:
ValueError: if the number of arguments is incorrect.
"""
if len(args) != len(self.signature.input_arg):
raise ValueError(
"Arguments and signature arguments do not match: %s %s " %
(len(args), len(list(self.signature.input_arg))))
function_call_options = ctx.get_function_call_options()
if function_call_options.config_proto_serialized is None:
config = function_utils.get_disabled_rewriter_config()
else:
config = function_call_options.config_proto_serialized
executor_type = function_call_options.executor_type or ""
executing_eagerly = ctx.executing_eagerly()
if executing_eagerly:
with _InterpolateFunctionError(self):
outputs = execute.execute(
str(self.signature.name),
num_outputs=self._num_outputs,
inputs=args,
attrs=("executor_type", executor_type,
"config_proto", config),
ctx=ctx)
# Replace empty list with None
outputs = outputs or None
elif self._graph._xla_compile: # pylint: disable=protected-access
g = ops.get_default_graph()
self.add_to_graph(g)
signature = self.signature
op = g.create_op(
signature.name,
[ops.internal_convert_to_tensor(x, ctx=ctx) for x in args],
tuple(dtypes_module.DType(x.type) for x in signature.output_arg),
op_def=signature,
name="FunctionCall",
compute_shapes=False)
outputs = op.outputs
if not outputs:
return op
if isinstance(outputs, (ops.Tensor, type(None))):
outputs = [outputs]
else:
outputs = list(outputs)
else:
# TODO(akshayka): Either remove this if the FunctionLibraryRuntime
# creates `PartitionedCallOp` kernels by default, or remove the previous
# branch if a TPU kernel is registered for `PartitionedCall`.
with _InterpolateFunctionError(self):
outputs = functional_ops.partitioned_call(
args=args,
f=self,
tout=self._output_types,
executing_eagerly=executing_eagerly,
config=config,
executor_type=executor_type)
if executing_eagerly:
return outputs
else:
for i, shape in enumerate(self._output_shapes):
outputs[i].set_shape(shape)
for i, func_graph_output in enumerate(self._func_graph_outputs):
custom_gradient.copy_handle_data(func_graph_output, outputs[i])
return outputs
class ConcreteFunction(object):
"""Callable object encapsulating a function definition and its gradient.
`ConcreteFunction` is a callable that encapsulates a function definition and
is differentiable under `tf.GradientTape` objects.
"""
def __init__(self, func_graph, attrs=None, signature=None):
"""Initialize a `ConcreteFunction`.
Args:
func_graph: An instance of FuncGraph: the function body to wrap.
attrs: (optional) dict mapping names of attributes to their AttrValue
values. Attributes in `attrs` will be included in this function's
definition.
signature: a nested sequence of `TensorSpec` objects specifying the input
signature of this function.
Raises:
ValueError: If number of input_placeholders is not equal to the number
of function inputs.
"""
self._arg_keywords = None
self._num_positional_args = None
self._func_graph = func_graph
self._captured_inputs = list(self._func_graph.captures.keys())
self._num_outputs = len(self._func_graph.outputs)
self._output_shapes = tuple(
output.shape for output in self._func_graph.outputs)
self._attrs = _parse_func_attrs(attrs or {})
self._inference_function = _EagerDefinedFunction(
_inference_name(self._func_graph.name), self._func_graph,
self._func_graph.inputs, self._func_graph.outputs, self._attrs)
self._backward_graph_function = None
self._signature = signature
self._gradient_name = None
def __call__(self, *args, **kwargs):
"""Executes the wrapped function.
Args:
*args: Tensors or Variables. Positional arguments are only accepted when
they correspond one-to-one with arguments of the traced Python function.
**kwargs: Tensors or Variables specified by name. When
`get_concrete_function` was called to create this `ConcreteFunction`,
each Tensor input was given a name, defaulting to the name of the Python
function's argument but possibly overridden by the `name=` argument to
`tf.TensorSpec`. These names become the argument names for the concrete
function.
Returns:
The result of applying the TF function on the given Tensors.
Raises:
AssertionError: If this `ConcreteFunction` was not created through
`get_concrete_function`.
ValueError: If arguments contains anything other than Tensors or
Variables.
TypeError: For invalid positional/keyword argument combinations.
"""
if self._arg_keywords is None or self._num_positional_args is None:
if self._signature is not None:
if kwargs:
raise NotImplementedError(
"Keyword arguments not supported when calling a "
"wrap_function-decorated function.")
return self._call_flat(args)
raise AssertionError(
"Tried to call a concrete function obtained from an internal API "
"through the public interface. Use get_concrete_function instead.")
if len(args) > self._num_positional_args:
raise TypeError(
("Expected at most {} positional arguments ({}), got {}. When "
"calling a concrete function, positional arguments may not be bound "
"to Tensors within nested structures.").format(
self._num_positional_args,
self._arg_keywords[:self._num_positional_args],
args))
args = list(args)
for keyword in self._arg_keywords[len(args):]:
try:
args.append(kwargs.pop(compat.as_str(keyword)))
except KeyError:
specified_keywords = (list(self._arg_keywords[:len(args)])
+ list(kwargs.keys()))
raise TypeError(
"Expected argument names {} but got values for {}. Missing: {}."
.format(
list(self._arg_keywords),
specified_keywords,
list(set(self._arg_keywords) - set(specified_keywords))))
if kwargs:
positional_arg_keywords = set(self._arg_keywords[:len(args)])
for unused_key in kwargs:
if unused_key in positional_arg_keywords:
raise TypeError("Got two values for keyword '{}'.".format(unused_key))
raise TypeError("Keyword arguments {} unknown. Expected {}.".format(
list(kwargs.keys()), list(self._arg_keywords)))
return self._call_flat(args)
def _filtered_call(self, args, kwargs):
"""Executes the function, filtering arguments from the Python function.
Objects aside from Tensors and Variables are ignored.
Args:
args: Canonicalized positional arguments of the Python function.
kwargs: Canonicalized keyword arguments of the Python function.
Returns:
The result of applying the function on the Tensors/Variables contained in
`args` and `kwargs`.
"""
return self._call_flat(
(t for t in nest.flatten((args, kwargs))
if isinstance(t, (ops.Tensor,
resource_variable_ops.ResourceVariable))))
def _call_flat(self, args):
"""Executes the wrapped function.
Args:
args: a list of Tensors or Variables.
Returns:
The result of applying the TF function to `args`.
Raises:
ValueError: If `args` contains anything other than Tensors or Variables.
"""
ctx = context.context()
tape.variables_accessed(self._func_graph.variables)
tensor_inputs = []
variables_used = set([])
for i, arg in enumerate(args):
if isinstance(arg, resource_variable_ops.ResourceVariable):
# We can pass a variable more than once, and in this case we need to
# pass its handle only once.
if arg.handle in variables_used:
continue
if arg.trainable:
tape.variable_accessed(arg)
tensor_inputs.append(arg.handle)
variables_used.add(arg.handle)
elif isinstance(arg, ops.Tensor):
tensor_inputs.append(arg)
elif (self._signature is not None and
isinstance(self._signature[i], tensor_spec.TensorSpec)):
tensor_inputs.append(
ops.convert_to_tensor(arg, self._signature[i].dtype))
else:
raise ValueError("All inputs to `ConcreteFunction`s must be Tensors; "
"on invocation of %s, the %d-th input (%s) was not a "
"Tensor." % (self._func_graph.name, i, str(arg)))
args = tensor_inputs + self._captured_inputs
if (tape.should_record(tensor_inputs) or
tape.should_record(self._captured_inputs)):
if context.executing_eagerly():
return self._eager_backprop_call(args)
else:
return self._backprop_call_with_delayed_rewrite(args)
# Only need to override the gradient in graph mode and when we have outputs.
if context.executing_eagerly() or not self.outputs:
outputs = self._inference_function.call(ctx, args)
else:
self._register_gradient()
with ops.get_default_graph().gradient_override_map(
{"PartitionedCall": self._gradient_name,
"StatefulPartitionedCall": self._gradient_name}):
outputs = self._inference_function.call(ctx, args)
return self._build_call_outputs(outputs)
def _register_gradient(self):
"""Registers the gradient for this `ConcreteFunction`.
The gradient rewrites an inference call op to a forward call op, but does
not modify a pre-existing forward call op. It then computes the gradient
from the output's gradients and the side outputs of the forward op.
"""
if self._gradient_name:
return
self._gradient_name = "PartitionedCall-%s" % ops.uid()
@ops.RegisterGradient(self._gradient_name)
def _registered_grad_fn(op, *doutputs): # pylint: disable=unused-variable
return self._grad_fn(op, *doutputs)
def _grad_fn(self, op, *doutputs):
"""Gradients of this function."""
if self._backward_graph_function is None:
self._construct_backprop_function()
# pylint: disable=protected-access
self._forward_function.add_to_graph(op.graph)
num_inference_outputs = self._inference_function._num_outputs
# Rewrite an inference call op to be a forward call op
if op.get_attr("f").name.encode() == self._inference_function.name:
op._set_func_attr("f", self._forward_function.name)
op._set_type_list_attr("Tout", self._forward_function._output_types)
op._add_outputs(
self._forward_function._output_types[num_inference_outputs:],
self._forward_function._output_shapes[num_inference_outputs:])
for i in range(num_inference_outputs, len(op.outputs)):
func_graph_output = self._forward_function._func_graph_outputs[i]
custom_gradient.copy_handle_data(func_graph_output, op.outputs[i])
# pylint: enable=protected-access
# Compute the gradients using the side outputs
side_outputs = op.outputs[num_inference_outputs:]
args = list(doutputs[:num_inference_outputs]) + list(side_outputs)
return self._backward_graph_function._call_flat( # pylint: disable=protected-access
(a for a in args if a is not None))
@property
def name(self):
"""`ConcreteFunction` name."""
return self._inference_function.name
@property
def graph(self):
"""Returns the graph from which this function was constructed."""
return self._func_graph
@property
def inputs(self):
"""Returns tensors in `self.graph` corresponding to arguments."""
return self._func_graph.inputs
@property
def structured_input_signature(self):
"""Returns structured signature of the original function."""
return self._func_graph.structured_input_signature
@property
def outputs(self):
"""Returns tensors in `self.graph` corresponding to returned tensors."""
return self._func_graph.outputs
@property
def structured_outputs(self):
"""Returns outputs in `self.graph` as returned by the original function."""
return self._func_graph.structured_outputs
@property
def captured_inputs(self):
"""Returns external Tensors captured by this function.
self.__call__(*args) passes `args + self.captured_inputs` to the function.
"""
return self._captured_inputs
@property
def function_def(self):
"""Returns a `FunctionDef` object representing this function."""
return self._inference_function.definition
@property
def output_shapes(self):
"""The function's output shapes."""
# TODO(ebrevdo): Should we only keep the output shapes associated
# with len(self._python_returns) outputs?
# TODO(akshayka): Consider removing this.
outputs_list = nest.flatten(self._func_graph.structured_outputs)
j = 0
for i, o in enumerate(outputs_list):
if o is not None:
if isinstance(o, ops.IndexedSlices):
# Extract the shape of the `IndexedSlices` object's `values` field.
outputs_list[i] = self._output_shapes[j] # the `values` shape
if o.dense_shape is not None:
j += 3 # skip over shapes for `values`, `indices`, `dense_shape`
else:
j += 2 # skip over shapes for `values`, `indices`
else:
outputs_list[i] = self._output_shapes[j]
j += 1
return nest.pack_sequence_as(self._func_graph.structured_outputs,
outputs_list)
@property
def output_dtypes(self):
# TODO(akshayka): Consider removing this.
return nest.map_structure(lambda x: x.dtype if x is not None else None,
self._func_graph.structured_outputs)
def add_to_graph(self, g=None, register_gradient_functions=False):
"""Registers the function, adds it to the graph g or default graph."""
# If we are not executing eagerly, adds the function to default graph if no
# graph is specified.
# In case of eager execution, function definition gets added to context
# during construction itself.
# TODO(allel/shivaniagrawal): rename this to register to reflect the
# method's functionality better. Remove register_gradient_functions argument
# and figure out if these needs to be registered.
if not context.executing_eagerly() and not g:
g = ops.get_default_graph()
self._inference_function.add_to_graph(g) # pylint: disable=protected-access
# pylint: disable=protected-access
if register_gradient_functions:
# There are two situations for the actual call of a defun:
# 1. If none of the input args are resource variables or watch by any
# tape, and it will run the _inference_function of concrete_func for
# forward pass, the gradient will be generated by standard mechanism.
# 2. Otherwise, defun will create two functions, one for forward pass,
# and the backward pass will be created via tape.
# When registering the function, we register both cases.
if self._backward_graph_function is None:
self._construct_backprop_function()
forward_function = self._forward_function
backward_function = self._backward_graph_function._inference_function
# pylint: enable=protected-access
forward_function.add_to_graph(g)
backward_function.add_to_graph(g)
def _construct_backprop_function(self):
"""Constructs the backprop function object for this function."""
backwards_graph = func_graph_module.FuncGraph(
_backward_name(self._func_graph.name))
forward_function_name = _forward_name(self._func_graph.name)
outputs = [x for x in self._func_graph.outputs
if gradients_util.IsTrainable(x)]
with backwards_graph.as_default():
gradients_wrt_outputs = [
graph_placeholder(x.dtype, x.shape) for x in outputs
]
gradients_wrt_inputs = gradients_util._GradientsHelper( # pylint: disable=protected-access
outputs,
self._func_graph.inputs,
grad_ys=gradients_wrt_outputs,
src_graph=self._func_graph)
backwards_graph_captures = list(backwards_graph.captures.keys())
backward_function_attr = _parse_func_attrs(
{FORWARD_FUNCTION_ATTRIBUTE_NAME: forward_function_name})
backward_function_attr.update(self._attrs)
# The ordering of `backwards_graph.inputs` is important: inputs of
# `self._backward_graph_function` correspond to outputs of
# `self._forward_function`.
backwards_graph.inputs = gradients_wrt_outputs + list(
backwards_graph.captures.values())
# Clear captures, since we pass them in as inputs.
backwards_graph.captures = {}
backwards_graph.outputs.extend(
grad
for grad in nest.flatten(gradients_wrt_inputs, expand_composites=True)
if grad is not None)
backwards_graph.structured_outputs = gradients_wrt_inputs
self._backward_graph_function = ConcreteFunction(
backwards_graph, attrs=backward_function_attr)
forward_function_attr = _parse_func_attrs({
BACKWARD_FUNCTION_ATTRIBUTE_NAME:
self._backward_graph_function._inference_function.name}) # pylint: disable=protected-access
forward_function_attr.update(self._attrs)
self._forward_function = _EagerDefinedFunction(
forward_function_name, self._func_graph, self._func_graph.inputs,
self._func_graph.outputs + backwards_graph_captures,
forward_function_attr)
def _eager_backprop_call(self, args):
"""Calls the forward function and records the result on a tape.
This method fully constructs the forward and backward functions before
calling the function and recording them on the tape.
(Only records results on a tape if the function has outputs).
Args:
args: All inputs to the function, including resolved captured inputs
Returns:
The call output.
"""
if self._backward_graph_function is None:
self._construct_backprop_function()
ctx = context.context()
self._register_gradient()
with ops.get_default_graph().gradient_override_map(
{"PartitionedCall": self._gradient_name,
"StatefulPartitionedCall": self._gradient_name}):
outputs = self._forward_function.call(ctx, args)
if isinstance(outputs, ops.Operation) or outputs is None:
return outputs
# `real_outputs` are the actual outputs of the inference graph function;
# `side_outputs` are the intermediate Tensors that were added as outputs to
# the forward graph function so that we can compute its gradient.
real_outputs = outputs[:self._num_outputs]
skip_positions = [i for i, t in enumerate(real_outputs)
if not gradients_util.IsTrainable(t)]
side_outputs = outputs[self._num_outputs:]
def backward_function(*args):
args = [a for i, a in enumerate(args)
if a is not None and i not in skip_positions]
return self._backward_graph_function._call_flat( # pylint: disable=protected-access
list(args) + side_outputs)
tape.record_operation(self._forward_function.signature.name, real_outputs,
args, backward_function)
return self._build_call_outputs(real_outputs)
def _backprop_call_with_delayed_rewrite(self, args):
"""Calls the inference function and records the result on a tape.
The recorded backwards function will construct the backwards graph and
rewrite the inference function to the forward function. This only happens
if the recorded backwards function ends up being used to compute gradients.
This approach avoids constructing unnecessary graphs, but it only works if
we are calling this function when not executing eagerly.
(Only records results on a tape if the function has outputs)
Args:
args: All inputs to the function, including resolved captured inputs
Returns:
The call output.
"""
ctx = context.context()
self._register_gradient()
with ops.get_default_graph().gradient_override_map(
{"PartitionedCall": self._gradient_name,
"StatefulPartitionedCall": self._gradient_name}):
outputs = self._inference_function.call(ctx, args)
if isinstance(outputs, ops.Operation) or outputs is None:
return outputs
call_op = outputs[0].op
def backward_function(*args):
return self._grad_fn(call_op, *args)
tape.record_operation(self._inference_function.signature.name, outputs,
args, backward_function)
return self._build_call_outputs(outputs)
def _build_call_outputs(self, result):
"""Maps the fdef output list to actual output structure.
Args:
result: Output lists defined by FunctionDef.
Returns:
The actual call output.
"""
if self._func_graph.structured_outputs is None:
return result
# Use `nest.flatten` instead of `func_graph_module.flatten` in order to
# preserve any IndexedSlices in `self._func_graph.structured_outputs`.
outputs_list = nest.flatten(self._func_graph.structured_outputs)
j = 0
for i, o in enumerate(outputs_list):
if o is not None:
if isinstance(o, ops.IndexedSlices):
# Repack Tensors for IndexedSlices.
if o.dense_shape is not None:
outputs_list[i] = ops.IndexedSlices(
values=result[j],
indices=result[j + 1],
dense_shape=result[j + 2])
j += 3
else:
outputs_list[i] = ops.IndexedSlices(
values=result[j], indices=result[j + 1])
j += 2
else:
outputs_list[i] = result[j]
j += 1
ret = nest.pack_sequence_as(self._func_graph.structured_outputs,
outputs_list)
return ret
pywrap_tensorflow.RegisterType("Tensor", ops.Tensor)
pywrap_tensorflow.RegisterType("IndexedSlices", ops.IndexedSlices)
def _deterministic_dict_values(dictionary):
return tuple(dictionary[key] for key in sorted(dictionary))
class FunctionSpec(object):
"""Specification of how to bind arguments to a function."""
@staticmethod
def from_function_and_signature(python_function, input_signature):
"""Create a FunctionSpec instance given a python function and signature."""
if isinstance(python_function, functools.partial):
python_function_to_inspect = python_function.func
args_to_prepend = python_function.args or tuple()
kwargs_to_include = python_function.keywords or {}
if input_signature is not None:
# TODO(b/124441704): Add support for input_signature + partial.
raise NotImplementedError(
"Missing support for input_signature when using partial functions.")
else:
python_function_to_inspect = python_function
args_to_prepend = tuple()
kwargs_to_include = {}
fullargspec = tf_inspect.getfullargspec(python_function_to_inspect)
is_method = tf_inspect.ismethod(python_function_to_inspect)
return FunctionSpec(fullargspec, is_method, args_to_prepend,
kwargs_to_include, input_signature)
def __init__(self, fullargspec, is_method, args_to_prepend, kwargs_to_include,
input_signature):
self._fullargspec = fullargspec
self._is_method = is_method
self._args_to_prepend = args_to_prepend
self._kwargs_to_include = kwargs_to_include
self._default_values = fullargspec.defaults
if self._is_method:
# Remove `self`: default arguments shouldn't be matched to it.
args = fullargspec.args[1:]
else:
args = fullargspec.args
# A cache mapping from argument name to index, for canonicalizing
# arguments that are called in a keyword-like fashion.
self._args_to_indices = {arg: i for i, arg in enumerate(args)}
self.arg_names = args
self.vararg_name = fullargspec.varargs
# A cache mapping from arg index to default value, for canonicalization.
offset = len(args) - len(fullargspec.defaults or [])
self._arg_indices_to_default_values = {
offset + index: default
for index, default in enumerate(fullargspec.defaults or [])
}
self._default_values_start_index = offset
if input_signature is None:
self._input_signature = None
else:
if fullargspec.varkw is not None or fullargspec.kwonlyargs:
raise ValueError("Cannot define a TensorFlow function from a Python "
"function with keyword arguments when "
"input_signature is provided.")
if not isinstance(input_signature, (tuple, list)):
raise TypeError("input_signature must be either a tuple or a "
"list, received " + str(type(input_signature)))
self._input_signature = tuple(input_signature)
self._flat_input_signature = tuple(nest.flatten(input_signature))
@property
def fullargspec(self):
return self._fullargspec
@property
def is_method(self):
return self._is_method
@property
def args_to_prepend(self):
return self._args_to_prepend
@property
def kwargs_to_include(self):
return self._kwargs_to_include
@property
def input_signature(self):
return self._input_signature
@property
def flat_input_signature(self):
return self._flat_input_signature
def canonicalize_function_inputs(self, *args, **kwargs):
"""Canonicalizes `args` and `kwargs`.
Canonicalize the inputs to the Python function using a `FunctionSpec`
instance. In particular, we parse the varags and kwargs that the
original function was called with into a tuple corresponding to the
Python function's positional (named) arguments and a dictionary
corresponding to its kwargs.
Args:
*args: The varargs this object was called with.
**kwargs: The keyword args this function was called with.
Returns:
A canonicalized ordering of the inputs representened by a tuple in the
form (args, kwargs). Here: `args` is a full list of bound arguments, and
`kwargs` contains only true keyword arguments, as opposed to named
arguments called in a keyword-like fashion.
Raises:
ValueError: If a keyword in `kwargs` cannot be matched with a positional
argument when an input signature is specified, or when the inputs
do not conform to the input signature.
"""
if self._input_signature is not None:
if len(args) > len(self._input_signature):
raise TypeError(
"When input_signature is provided, only pass arguments "
"covered by it. Received %d argument(s)." % len(args))
for arg in six.iterkeys(kwargs):
index = self._args_to_indices.get(arg, None)
if index is None:
raise TypeError(
"Function got an unexpected keyword argument %s" % arg)
if index >= len(self._input_signature):
raise TypeError(
"When input_signature is provided, only pass arguments "
"covered by it. Received argument %s." % arg)
args = self._args_to_prepend + args
kwargs = dict(kwargs, **self._kwargs_to_include)
if not kwargs:
if self._default_values:
inputs = args + self._default_values[
len(args) - self._default_values_start_index:]
else:
inputs = args
else:
# Maps from index of arg to its corresponding value, according to `args`
# and `kwargs`; seeded with the default values for the named args that
# aren't in `args`.
arg_indices_to_values = {
index: default for index, default in six.iteritems(
self._arg_indices_to_default_values) if index >= len(args)
}
consumed_args = []
for arg, value in six.iteritems(kwargs):
index = self._args_to_indices.get(arg, None)
if index is not None:
arg_indices_to_values[index] = value
consumed_args.append(arg)
elif self._input_signature is not None:
raise ValueError("Cannot define a TensorFlow function from a Python "
"function with keyword arguments when "
"input_signature is provided.")
for arg in consumed_args:
# After this loop, `kwargs` will only contain true keyword arguments, as
# opposed to named arguments called in a keyword-like fashion.
kwargs.pop(arg)
inputs = args + _deterministic_dict_values(arg_indices_to_values)