/
control_flow_ops.py
3767 lines (3205 loc) · 142 KB
/
control_flow_ops.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
# Copyright 2015 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.
# ==============================================================================
"""Control Flow Operations.
See the [autograph](https://www.tensorflow.org/guide/autograph) guide.
"""
# pylint: disable=g-bad-name
import abc
import collections
import functools
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.protobuf import control_flow_pb2
from tensorflow.python.eager import context
from tensorflow.python.framework import composite_tensor
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import indexed_slices
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework import type_spec
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_util as util
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_control_flow_ops
from tensorflow.python.ops import gen_functional_ops
from tensorflow.python.ops import gen_logging_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import tensor_array_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import,undefined-variable
from tensorflow.python.ops.gen_control_flow_ops import *
# pylint: enable=wildcard-import
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
from tensorflow.python.util import deprecation
from tensorflow.python.util import dispatch
from tensorflow.python.util import nest
from tensorflow.python.util import tf_should_use
from tensorflow.python.util import variable_utils
from tensorflow.python.util.lazy_loader import LazyLoader
from tensorflow.python.util.tf_export import tf_export
# This is to avoid a circular dependency:
# cond_v2 -> gradients_util -> control_flow_ops
cond_v2 = LazyLoader("cond_v2", globals(),
"tensorflow.python.ops.cond_v2")
# This is to avoid circular dependencies:
# while_v2 -> control_flow_ops
# while_v2 -> gradients_util -> control_flow_ops
while_v2 = LazyLoader("while_v2", globals(),
"tensorflow.python.ops.while_v2")
# def_function also uses cond
def_function = LazyLoader(
"def_function", globals(),
"tensorflow.python.eager.def_function")
# We override the 'tuple' for a control flow op, so we keep python's
# existing 'tuple' for later use in this module.
_basetuple = tuple
def _summarize_eager(tensor, summarize=None):
"""Returns a summarized string representation of eager `tensor`.
Args:
tensor: EagerTensor to summarize
summarize: Include these many first elements of `array`
"""
# Emulate the behavior of Tensor::SummarizeValue()
if summarize is None:
summarize = 3
elif summarize < 0:
summarize = array_ops.size(tensor)
# reshape((-1,)) is the fastest way to get a flat array view
if tensor._rank(): # pylint: disable=protected-access
flat = tensor.numpy().reshape((-1,))
lst = [str(x) for x in flat[:summarize]]
if len(lst) < flat.size:
lst.append("...")
else:
# tensor.numpy() returns a scalar for zero dimensional arrays
if gen_math_ops.not_equal(summarize, 0):
lst = [str(tensor.numpy())]
else:
lst = []
return ", ".join(lst)
# pylint: disable=protected-access
# Assert and Print are special symbols in python, so we must
# use an upper-case version of them.
@tf_export("debugging.Assert", "Assert")
@dispatch.add_dispatch_support
@tf_should_use.should_use_result
def Assert(condition, data, summarize=None, name=None):
"""Asserts that the given condition is true.
If `condition` evaluates to false, print the list of tensors in `data`.
`summarize` determines how many entries of the tensors to print.
Args:
condition: The condition to evaluate.
data: The tensors to print out when condition is false.
summarize: Print this many entries of each tensor.
name: A name for this operation (optional).
Returns:
assert_op: An `Operation` that, when executed, raises a
`tf.errors.InvalidArgumentError` if `condition` is not true.
@compatibility(eager)
returns None
@end_compatibility
Raises:
@compatibility(TF1)
When in TF V1 mode (that is, outside `tf.function`) Assert needs a control
dependency on the output to ensure the assertion executes:
```python
# Ensure maximum element of x is smaller or equal to 1
assert_op = tf.Assert(tf.less_equal(tf.reduce_max(x), 1.), [x])
with tf.control_dependencies([assert_op]):
... code using x ...
```
@end_compatibility
"""
if context.executing_eagerly():
if not condition:
xs = ops.convert_n_to_tensor(data)
data_str = [_summarize_eager(x, summarize) for x in xs]
raise errors.InvalidArgumentError(
node_def=None,
op=None,
message="Expected '%s' to be true. Summarized data: %s" %
(condition, "\n".join(data_str)))
return
with ops.name_scope(name, "Assert", [condition, data]) as name:
xs = ops.convert_n_to_tensor(data)
if all(x.dtype in {dtypes.string, dtypes.int32} for x in xs):
# As a simple heuristic, we assume that string and int32 are
# on host to avoid the need to use cond. If it is not case,
# we will pay the price copying the tensor to host memory.
return gen_logging_ops._assert(condition, data, summarize, name="Assert")
else:
condition = ops.convert_to_tensor(condition, name="Condition")
def true_assert():
return gen_logging_ops._assert(
condition, data, summarize, name="Assert")
guarded_assert = cond(condition, no_op, true_assert, name="AssertGuard")
if context.executing_eagerly():
return
return guarded_assert.op
def _Identity(tensor, name=None):
"""Return a tensor with the same shape and contents as the input tensor.
Args:
tensor: A Tensor.
name: A name for this operation (optional).
Returns:
A Tensor with the same type and value as the input Tensor.
"""
tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True)
# TODO(b/246438937): Remove this when we expand ResourceVariables into
# dt_resource tensors.
tensor = variable_utils.convert_variables_to_tensors(tensor)
if isinstance(tensor, ops.Tensor):
if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access
return gen_array_ops.ref_identity(tensor, name=name)
else:
return array_ops.identity(tensor, name=name)
elif isinstance(tensor, composite_tensor.CompositeTensor):
return nest.map_structure(_Identity, tensor, expand_composites=True)
else:
raise TypeError("'tensor' must be a Tensor or CompositeTensor. "
f"Received: {type(tensor)}.")
def _NextIteration(tensor, name=None):
tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True)
if isinstance(tensor, ops.Tensor):
if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access
return ref_next_iteration(tensor, name=name)
else:
return next_iteration(tensor, name=name)
elif isinstance(tensor, composite_tensor.CompositeTensor):
return nest.map_structure(_NextIteration, tensor, expand_composites=True)
else:
raise TypeError("'tensor' must be a Tensor or CompositeTensor. "
f"Received: {type(tensor)}.")
def _Enter(tensor,
frame_name,
is_constant=False,
parallel_iterations=10,
use_ref=True,
use_input_shape=True,
name=None):
"""Creates or finds a child frame, and makes `tensor` available to it.
The unique `frame_name` is used by the `Executor` to identify frames. If
`is_constant` is true, `tensor` is a constant in the child frame; otherwise
it may be changed in the child frame. At most `parallel_iterations`
iterations are run in parallel in the child frame.
Args:
tensor: The tensor to be made available to the child frame.
frame_name: The name of the child frame.
is_constant: If true, the output is constant within the child frame.
parallel_iterations: The number of iterations allowed to run in parallel.
use_ref: If true, use ref_enter if tensor is of ref type.
use_input_shape: If true, set the result's shape based on tensor's shape.
name: A name for this operation (optional).
Returns:
The same tensor as `tensor`.
Raises:
ValueError: If any tensor in `tensor` has a less specific shape
than its corresponding shape in `shape_invariant`.
"""
tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True)
if isinstance(tensor, ops.Tensor):
if tensor.dtype._is_ref_dtype and use_ref: # pylint: disable=protected-access
result = gen_control_flow_ops.ref_enter(
tensor, frame_name, is_constant, parallel_iterations, name=name)
else:
result = gen_control_flow_ops.enter(
tensor, frame_name, is_constant, parallel_iterations, name=name)
if use_input_shape:
result.set_shape(tensor.get_shape())
return result
elif isinstance(tensor, composite_tensor.CompositeTensor):
def enter_component(t):
return _Enter(t, frame_name, is_constant, parallel_iterations, use_ref,
use_input_shape)
return nest.map_structure(enter_component, tensor, expand_composites=True)
else:
raise TypeError("'tensor' must be a Tensor or CompositeTensor. "
f"Received: {type(tensor)}.")
def exit(tensor, name=None): # pylint: disable=redefined-builtin
"""Exits the current frame to its parent frame.
Exit makes its input `tensor` available to the parent frame.
Args:
tensor: The tensor to be made available to the parent frame.
name: A name for this operation (optional).
Returns:
The same tensor as `tensor`.
"""
tensor = ops.internal_convert_to_tensor_or_composite(tensor, as_ref=True)
if isinstance(tensor, ops.Tensor):
if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access
return gen_control_flow_ops.ref_exit(tensor, name)
else:
return gen_control_flow_ops._exit(tensor, name)
elif isinstance(tensor, composite_tensor.CompositeTensor):
return nest.map_structure(exit, tensor, expand_composites=True)
else:
raise TypeError("'tensor' must be a Tensor or CompositeTensor. "
f"Received: {type(tensor)}.")
def switch(data, pred, dtype=None, name=None):
"""Forwards `data` to an output determined by `pred`.
If `pred` is false, the `data` input is forwarded to the first output.
Otherwise, the data goes to the second output.
This op handles `Tensor`s and `IndexedSlices`.
Args:
data: The tensor to be forwarded to the appropriate output.
pred: A scalar that specifies which output port will receive data.
dtype: Optional element type for the returned tensor. If missing, the type
is inferred from the type of `value`.
name: A name for this operation (optional).
Returns:
`(output_false, output_true)`: If `pred` is true, data will be forwarded
to `output_true`, otherwise it goes to `output_false`.
"""
with ops.name_scope(name, "Switch", [data, pred]) as name:
data = ops.internal_convert_to_tensor_or_composite(
data, dtype=dtype, name="data", as_ref=True)
pred = ops.convert_to_tensor(pred, name="pred")
if isinstance(data, ops.Tensor):
return gen_control_flow_ops.switch(data, pred, name=name)
else:
if not isinstance(data, composite_tensor.CompositeTensor):
raise TypeError(
"'data' must be a Tensor or CompositeTensor. "
f"Received: {type(data)}.")
tensors = nest.flatten(data, expand_composites=True)
mapped = [gen_control_flow_ops.switch(tensor, pred) for tensor in tensors]
mapped_f, mapped_t = zip(*mapped)
return (nest.pack_sequence_as(data, mapped_f, expand_composites=True),
nest.pack_sequence_as(data, mapped_t, expand_composites=True))
def _SwitchRefOrTensor(data, pred, name="Switch"):
"""Forwards `data` to an output determined by `pred`.
If `pred` is false, the `data` input is forwarded to the first output.
Otherwise, the data goes to the second output.
This op handles `Tensor`s and `IndexedSlices`.
Args:
data: The tensor to be forwarded to the appropriate output.
pred: A scalar that specifies which output port will receive data.
name: A name for this operation (optional).
Returns:
`(output_false, output_true)`: If `pred` is true, data will be forwarded to
`output_true`, otherwise it goes to `output_false`.
Raises:
TypeError: if data is not a Tensor or IndexedSlices
"""
data = ops.convert_to_tensor_or_composite(data, name="data")
# NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below
# addresses the following scenario.
#
# Assume you execute Optimizer.apply_gradients() in a branch of a cond().
#
# 1. The update op is created inside a `with ops.colocate(var):` block
#
# 2. Some tensor `data` is captured and a switch is created in a
# `with ops.colocate_with(data):` block.
#
# with ops.colocate_with(var):
# with ops.colocate_with(data):
# op = ...
#
# var and data may be pinned to different devices, so we want to ops
# created within ops.colocate_with(data) to ignore the existing stack.
with ops.colocate_with(data, ignore_existing=True):
if isinstance(data, ops.Tensor):
if data.dtype._is_ref_dtype: # pylint: disable=protected-access
return ref_switch(data, pred, name=name)
return switch(data, pred, name=name)
def merge(inputs, name=None):
"""Returns the value of an available element of `inputs`.
This op tests each of the tensors in `inputs` in turn to determine if any of
them is available. If it finds an available tensor, it returns it and its
index in `inputs`.
It is an error if more than one tensor in `inputs` is available. If no tensor
in `inputs` is available, the returned tensor and index are not set.
This op handles both `Tensor`s and `IndexedSlices`. If inputs has a mix of
`Tensor`s and `IndexedSlices`, all inputs are converted to IndexedSlices
before merging.
Args:
inputs: The input tensors, at most one of which is available.
name: A name for this operation (optional).
Returns:
A tuple containing the chosen input tensor and its index in `inputs`.
Raises:
ValueError: If any of the inputs is None, or inputs are IndexedSlices and
some but not all have a dense_shape property.
"""
if any(inp is None for inp in inputs):
raise ValueError("At least one of the merge inputs is None: %s" % inputs)
with ops.name_scope(name, "Merge", inputs) as name:
inputs = [
ops.internal_convert_to_tensor_or_composite(inp, as_ref=True)
for inp in inputs
]
if all(isinstance(v, ops.Tensor) for v in inputs):
if all(v.dtype._is_ref_dtype for v in inputs): # pylint: disable=protected-access
return gen_control_flow_ops.ref_merge(inputs, name)
else:
return gen_control_flow_ops.merge(inputs, name)
else:
# If there is a mix of tensors and indexed slices, then convert the
# tensors to indexed slices.
if all(
isinstance(v, (indexed_slices.IndexedSlices, ops.Tensor))
for v in inputs):
inputs = math_ops._as_indexed_slices_list(inputs, optimize=False)
for v in inputs:
if not isinstance(v, composite_tensor.CompositeTensor):
raise TypeError("Type %s not supported" % type(v))
for v in inputs[1:]:
nest.assert_same_structure(inputs[0], v, expand_composites=True)
flat_inputs = [nest.flatten(v, expand_composites=True) for v in inputs]
merged_results = [
gen_control_flow_ops.merge(component)
for component in zip(*flat_inputs)
]
flat_merged = [tensor for (tensor, _) in merged_results]
chosen_index = merged_results[0][1]
merged_inputs = nest.pack_sequence_as(
inputs[0], flat_merged, expand_composites=True)
return (merged_inputs, chosen_index)
def _convert_tensorarray_to_flow(tensor_or_tensor_array):
if isinstance(tensor_or_tensor_array, tensor_array_ops.TensorArray):
return tensor_or_tensor_array.flow
else:
return tensor_or_tensor_array
def _convert_flow_to_tensorarray(tensor_or_tensor_array, tensor_or_flow):
if isinstance(tensor_or_tensor_array, tensor_array_ops.TensorArray):
return tensor_array_ops.build_ta_with_new_flow(tensor_or_tensor_array,
tensor_or_flow)
else:
return tensor_or_flow
def _convert_to_tensor_or_composite_or_tensorarray(var):
if isinstance(var, tensor_array_ops.TensorArray):
return var
return ops.convert_to_tensor_or_composite(var)
# TODO(xjun): replace this with is_subtype_of after it is landed.
def _ShapeLessThanOrEqual(shape1, shape2):
if shape2.dims is None:
return True
if shape1.ndims != shape2.ndims:
return False
for dim1, dim2 in zip(shape1.dims, shape2.dims):
if dim2.value is not None and dim1.value != dim2.value:
return False
return True
def _shape_invariant_to_type_spec(var, shape=None):
"""Converts a shape invariant to a TypeSpec.
If `var` is a TensorArray, it will first be converted to its flow.
Args:
var: The tensor, tensor array or composite tensor whose shape is described
by the shape invariant.
shape: A `TypeSpec` or `TensorShape`. If `shape` is already a `TypeSpec`,
then it is simply returned as-is.
Returns:
A `TypeSpec` for `var`, consistent with the given shape.
Raises:
TypeError: If `shape` is a TypeSpec and not compatible with `var`.
TypeError: If `shape` is not None, a TypeSpec, or a TensorShape.
TypeError: If `shape` is a TensorShape, `var` is a CompositeTensor, and
`var` doesn't implement the `_shape_invariant_to_type_spec` method.
"""
var = _convert_tensorarray_to_flow(var)
if shape is None:
return type_spec.type_spec_from_value(var)
elif isinstance(shape, type_spec.TypeSpec):
if not shape.is_compatible_with(var):
raise TypeError("TypeSpec %r is not compatible with %r" % (shape, var))
return shape
elif not isinstance(shape, tensor_shape.TensorShape):
raise TypeError(
"'shape' must be one of TypeSpec, TensorShape or None. "
f"Received: {type(shape)}")
if isinstance(var, ops.Tensor):
return tensor_spec.TensorSpec(shape, var.dtype)
else:
try:
return var._shape_invariant_to_type_spec(shape) # pylint: disable=protected-access
except NotImplementedError as e:
raise TypeError(
f"To describe or constrain a {type(var).__name__}, use a "
f"{type(var._type_spec).__name__} instead of a TensorShape.") from e # pylint: disable=protected-access
def _EnforceShapeInvariant(merge_var, next_var):
"""Check if the shapes of the loops variables are invariants.
Args:
merge_var: The tensor representing the initial values of the loop
variables.
next_var: The tensor representing the values of the loop variables
after one loop iteration.
Raises:
ValueError: If any tensor in `merge_var` has a more specific shape than
its corresponding tensor in `next_var`.
"""
if isinstance(merge_var, ops.Tensor):
m_shape = merge_var.get_shape()
n_shape = next_var.get_shape()
if not _ShapeLessThanOrEqual(n_shape, m_shape):
enter = merge_var.op.inputs[0].op
assert util.IsLoopEnter(enter)
input_t = enter.inputs[0]
raise ValueError(
"Input tensor '%s' enters the loop with shape %s, but has shape %s "
"after one iteration. To allow the shape to vary across iterations, "
"use the `shape_invariants` argument of tf.while_loop to specify a "
"less-specific shape." % (input_t.name, input_t.shape, n_shape))
else:
raise TypeError("'merge_var' must be a Tensor. "
f"Received: {type(merge_var)}.")
def _AddNextAndBackEdge(m, v, enforce_shape_invariant=True):
"""Add NextIteration and back edge from v to m."""
if isinstance(m, ops.Tensor):
v = ops.convert_to_tensor(v)
v = _NextIteration(v)
if enforce_shape_invariant:
# Make sure the shapes of loop outputs are correct. We do this before
# calling _update_input, which will raise a less-helpful error message if
# the types don't match.
# TODO(skyewm): call this for other cases below (needs testing)
_EnforceShapeInvariant(m, v)
m.op._update_input(1, v) # pylint: disable=protected-access
elif isinstance(m, composite_tensor.CompositeTensor):
# pylint: disable=protected-access
def update_component(m_component, v_component):
m_component.op._update_input(1, v_component)
if isinstance(m, indexed_slices.IndexedSlices):
v = math_ops._as_indexed_slices(v, optimize=False)
# pylint: enable=protected-access
v = _NextIteration(v)
return nest.map_structure(update_component, m, v, expand_composites=True)
else:
raise TypeError("'m' must be a Tensor or CompositeTensor. "
f"Received: {type(m)}.")
return v
class ControlFlowContext(metaclass=abc.ABCMeta):
"""The base class for control flow context.
The usage pattern is a sequence of (Enter, Exit) followed by a final
ExitResult.
We maintain the following state for control flow contexts during graph
construction:
1. graph has _control_flow_context: the current context used to
construct new nodes. Changed by ctxt.Enter() and ctxt.Exit()
2. op has _control_flow_context: the context to which the op belongs.
Set at the time the op is created. Immutable.
3. A ControlFlowContext has _outer_context: the context in which this
context is created. Set at the time a context is created. Immutable.
4. A ControlFlowContext has _context_stack.
Pushed and popped by ctxt.Enter() and ctxt.Exit()
"""
def __init__(self, values_def=None, import_scope=None):
self._nested_contexts = []
self._outer_context = ops.get_default_graph()._get_control_flow_context()
if self._outer_context:
self._outer_context._nested_contexts.append(self) # pylint: disable=protected-access
self._context_stack = []
if values_def:
self._init_values_from_proto(values_def, import_scope=import_scope)
else:
# The names of tensors that have been already seen in this context.
self._values = set()
# The keys are the names of tensors referenced by but external to this
# context. Each value is the Tensor that should be used by this context to
# access the key value (e.g. a switch output guarding a cond input value).
self._external_values = {}
def _init_values_from_proto(self, values_def, import_scope=None):
"""Initializes values and external_values from `ValuesDef` protocol buffer.
Args:
values_def: `ValuesDef` protocol buffer.
import_scope: Optional `string`. Name scope to add.
"""
assert isinstance(values_def, control_flow_pb2.ValuesDef)
self._values = set(
ops.prepend_name_scope(value, import_scope)
for value in values_def.values)
g = ops.get_default_graph()
self._external_values = {}
for k, v in values_def.external_values.items():
k = ops.prepend_name_scope(k, import_scope)
self._external_values[k] = g.as_graph_element(
ops.prepend_name_scope(v, import_scope))
op_names = set([
op.split(":")[0]
for op in self._values - set(self._external_values.keys())
])
for op in op_names:
# pylint: disable=protected-access
g.as_graph_element(op)._set_control_flow_context(self)
# pylint: enable=protected-access
@property
def name(self):
return self._name
@property
def outer_context(self):
"""Return the context containing this context."""
return self._outer_context
@property
def grad_state(self):
raise NotImplementedError("Abstract method")
@property
def back_prop(self):
raise NotImplementedError("Abstract method")
@abc.abstractmethod
def to_control_flow_context_def(self, context_def, export_scope=None):
"""Serializes this into `context_def`.
Args:
context_def: a `ControlFlowContextDef` protocol buffer.
export_scope: Optional `string`. Name scope to remove.
"""
raise NotImplementedError("Abstract method")
def _to_values_def(self, export_scope=None):
"""Converts the values to a `ValuesDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `ValuesDef` protocol buffer.
"""
values_def = control_flow_pb2.ValuesDef()
values_def.values.extend(
[ops.strip_name_scope(v, export_scope) for v in sorted(self._values)])
for k, v in self._external_values.items():
k = ops.strip_name_scope(k, export_scope)
values_def.external_values[k] = ops.strip_name_scope(v.name, export_scope)
return values_def
def AddName(self, name):
self._values.add(name)
# pylint: disable=protected-access
def Enter(self):
"""Enter this control flow context."""
graph = ops.get_default_graph()
self._context_stack.append(graph._get_control_flow_context())
graph._set_control_flow_context(self)
def Exit(self):
"""Exit this control flow context."""
graph = ops.get_default_graph()
last_context = self._context_stack.pop()
graph._set_control_flow_context(last_context)
def EnterGradientColocation(self, op, gradient_uid):
"""Start building a gradient colocated with an op."""
if self._outer_context:
self._outer_context.EnterGradientColocation(op, gradient_uid)
def ExitGradientColocation(self, op, gradient_uid):
"""Start building a gradient colocated with an op."""
if self._outer_context:
self._outer_context.ExitGradientColocation(op, gradient_uid)
def ExitResult(self, result):
"""Make a list of tensors available in the outer context."""
if self._outer_context:
def fn(x):
self._outer_context.AddName(x.name)
return x
nest.map_structure(fn, result, expand_composites=True)
def GetWhileContext(self):
"""Return the while context containing this context."""
if self._outer_context:
return self._outer_context.GetWhileContext()
return None
def _RemoveExternalControlEdges(self, op):
"""Remove any external control dependency on this op."""
while_ctxt = self.GetWhileContext()
# A control input of `op` is internal if it is in the same while
# loop context as the enclosing while loop context of self.
if while_ctxt is None:
internal_control_inputs, external_control_inputs = op.control_inputs, []
else:
internal_control_inputs, external_control_inputs = [], []
for x in op.control_inputs:
ctxt = util.GetOutputContext(x)
if ctxt is not None and ctxt.GetWhileContext() == while_ctxt:
internal_control_inputs.append(x)
else:
external_control_inputs.append(x)
if len(internal_control_inputs) != len(op.control_inputs):
# TODO(mdan): perhaps there should be a replace_control_inputs()
op._remove_all_control_inputs()
op._add_control_inputs(internal_control_inputs)
return internal_control_inputs, external_control_inputs
# pylint: enable=protected-access
def AddInnerOp(self, op):
"""Notifies a scope about an operator added to an inner scope."""
if self._outer_context:
self._outer_context.AddInnerOp(op)
def GetControlPivot(self):
"""Returns the pivot node for this context, or None."""
return None
def IsWhileContext(self):
return False
def IsCondContext(self):
return False
def IsXLAContext(self):
return False
def __str__(self):
return self.name
class CondContext(ControlFlowContext):
"""The context for the conditional construct."""
def __init__(self,
pred=None,
pivot=None,
branch=None,
name="cond_text",
context_def=None,
import_scope=None):
"""Creates a `CondContext`.
Args:
pred: The `boolean` tensor for the conditional predicate.
pivot: The predicate tensor in this branch.
branch: 0 or 1 representing this branch.
name: Name of the `CondContext` python object.
context_def: Optional `ContextDef` protocol buffer to initialize the
`CondContext` object from.
import_scope: Optional `string`. Name scope to add. Only used when
initialing from protocol buffer.
"""
self._name = ops.get_default_graph().unique_name(name)
if context_def:
self._init_from_proto(context_def, import_scope=import_scope)
else:
# Initializes the default fields.
ControlFlowContext.__init__(self)
self._pred = pred # The boolean tensor for the cond predicate
self._pivot = pivot # The predicate tensor in this branch
self._branch = branch # 0 or 1 representing this branch
# Values considered to have been already seen in this context. pred is not
# included in this context.
self._values.add(pred.name)
self._external_values[pred.name] = pred
self._values.add(pivot.name)
pivot.op._set_control_flow_context(self) # pylint: disable=protected-access
def _init_from_proto(self, context_def, import_scope=None):
"""Creates a new `CondContext` from protocol buffer.
Args:
context_def: `CondContextDef` protocol buffer.
import_scope: Optional `string`. Name scope to add.
"""
assert isinstance(context_def, control_flow_pb2.CondContextDef)
# Create from context_def.
g = ops.get_default_graph()
self._name = ops.prepend_name_scope(context_def.context_name, import_scope)
self._pred = g.as_graph_element(
ops.prepend_name_scope(context_def.pred_name, import_scope))
self._pivot = g.as_graph_element(
ops.prepend_name_scope(context_def.pivot_name, import_scope))
self._branch = context_def.branch
super(CondContext, self).__init__(
values_def=context_def.values_def, import_scope=import_scope)
@property
def pred(self):
return self._pred
@property
def pivot(self):
return self._pivot
@property
def branch(self):
return self._branch
@property
def grad_state(self):
if self.GetWhileContext():
return self.GetWhileContext().grad_state
return None
@property
def back_prop(self):
if self.GetWhileContext():
self.GetWhileContext().back_prop
return False
def GetControlPivot(self):
return self._pivot
def to_proto(self, export_scope=None):
"""Converts a `CondContext` to a `CondContextDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `CondContextDef` protocol buffer.
"""
if (export_scope is None or self.name.startswith(export_scope)):
context_def = control_flow_pb2.CondContextDef()
context_def.context_name = ops.strip_name_scope(self.name, export_scope)
context_def.pred_name = ops.strip_name_scope(self._pred.name,
export_scope)
context_def.pivot_name = ops.strip_name_scope(self._pivot.name,
export_scope)
context_def.branch = self._branch
context_def.values_def.MergeFrom(
super(CondContext, self)._to_values_def(export_scope))
for nested in self._nested_contexts:
nested_def = context_def.nested_contexts.add()
nested.to_control_flow_context_def(nested_def)
return context_def
else:
return None
@staticmethod
def from_proto(context_def, import_scope=None):
"""Returns a `CondContext` object created from `context_def`."""
ret = CondContext(context_def=context_def, import_scope=import_scope)
ret.Enter()
for nested_def in context_def.nested_contexts:
from_control_flow_context_def(nested_def, import_scope=import_scope)
ret.Exit()
return ret
def to_control_flow_context_def(self, context_def, export_scope=None):
context_def.cond_ctxt.CopyFrom(self.to_proto(export_scope=export_scope))
def AddValue(self, val):
"""Add `val` to the current context and its outer context recursively."""
if val.name in self._values:
# Use the real value if it comes from outer context. This is needed in
# particular for nested conds.
result = self._external_values.get(val.name)
result = val if result is None else result
else:
result = val
self._values.add(val.name)
if self._outer_context:
result = self._outer_context.AddValue(val)
self._values.add(result.name)
self._external_values[result.name] = result
with ops.control_dependencies(None):
result = _SwitchRefOrTensor(result, self._pred)[self._branch]
if self._outer_context:
self._outer_context.AddInnerOp(result.op)
result.op.graph.prevent_fetching(result.op)
# pylint: disable=protected-access
result.op._set_control_flow_context(self)
# pylint: enable=protected-access
# Mark Switch output as seen by this context and any outer contexts,
# just like what we do for normal op outputs in _AddOpInternal() below.
ctxt = self
while ctxt is not None:
# pylint: disable=protected-access
ctxt._values.add(result.name)
ctxt = ctxt._outer_context
# pylint: enable=protected-access
self._external_values[val.name] = result
return result
def AddOp(self, op):
self._AddOpInternal(op)
def _AddOpInternal(self, op):
"""Add `op` to the current context."""
if not op.inputs:
# If we're in a while loop, remove any control inputs from outside the
# loop.
self._RemoveExternalControlEdges(op)
if not any(
util.OpInContext(input_op, self) for input_op in op.control_inputs):
# pylint: disable=protected-access
op._add_control_input(self._pivot.op)
# pylint: enable=protected-access
else:
# Make each input to 'op' available in this CondContext. If an input is
# already part of this context there's nothing to do, but if it's
# external, AddValue() will handle adding the appropriate Switch node and
# other bookkeeping.
for index in range(len(op.inputs)):
x = op.inputs[index]
if op.type == "Merge" and x.op.type == "NextIteration":
# Edge case: if we're importing a while loop inside this CondContext,
# AddValue() will not correctly handle the NextIteration inputs to
# Merge node. The problem is that the NextIteration should also be
# part of this context, but if we're importing it won't have been
# processed and added to the context yet, so AddValue() will try to
# add a Switch which results in an invalid graph. Instead, we use the
# NextIteration input as-is here, and it will eventually be added to
# the context via AddOp().
real_x = x
else:
real_x = self.AddValue(x)
if real_x != x:
# pylint: disable=protected-access
op._update_input(index, real_x)
# pylint: enable=protected-access
# Remove any external control dependency on this op.
self._RemoveExternalControlEdges(op)
# pylint: disable=protected-access
if op.graph._is_function(op.type) or op.type == "SymbolicGradient":
op._add_control_input(self._pivot.op)
# pylint: enable=protected-access
# Mark op's outputs as seen by this context and any outer contexts.
output_names = [x.name for x in op.outputs]
ctxt = self
while ctxt is not None:
# pylint: disable=protected-access
ctxt._values.update(output_names)
ctxt = ctxt._outer_context
# pylint: enable=protected-access
if self._outer_context or not util.IsLoopExit(op):
op.graph.prevent_fetching(op)
if self._outer_context:
self._outer_context.AddInnerOp(op)
def _ProcessOutputTensor(self, val):
"""Process an output tensor of a conditional branch."""
real_val = val
if val.name not in self._values:
# Handle the special case of lambda: x
self._values.add(val.name)
if self._outer_context:
real_val = self._outer_context.AddValue(val)
self._values.add(real_val.name)