nested_utils.py 5.46 KB
Newer Older
Dieterich Lawson's avatar
Dieterich Lawson committed
1
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# 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 set of utils for dealing with nested lists and tuples of Tensors."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Dieterich Lawson's avatar
Dieterich Lawson committed
22
import itertools
23
import tensorflow as tf
Dieterich Lawson's avatar
Dieterich Lawson committed
24

25
26
from tensorflow.python.util import nest

Dieterich Lawson's avatar
Dieterich Lawson committed
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
def map_nested(map_fn, nested):
  """Executes map_fn on every element in a (potentially) nested structure.

  Args:
    map_fn: A callable to execute on each element in 'nested'.
    nested: A potentially nested combination of sequence objects. Sequence
      objects include tuples, lists, namedtuples, and all subclasses of
      collections.Sequence except strings. See nest.is_sequence for details.
      For example [1, ('hello', 4.3)] is a nested structure containing elements
      1, 'hello', and 4.3.
  Returns:
    out_structure: A potentially nested combination of sequence objects with the
      same structure as the 'nested' input argument. out_structure
      contains the result of applying map_fn to each element in 'nested'. For
      example map_nested(lambda x: x+1, [1, (3, 4.3)]) returns [2, (4, 5.3)].
  """
  out = map(map_fn, nest.flatten(nested))
  return nest.pack_sequence_as(nested, out)


def tile_tensors(tensors, multiples):
  """Tiles a set of Tensors.

  Args:
    tensors: A potentially nested tuple or list of Tensors with rank
      greater than or equal to the length of 'multiples'. The Tensors do not
      need to have the same rank, but their rank must not be dynamic.
    multiples: A python list of ints indicating how to tile each Tensor
      in 'tensors'. Similar to the 'multiples' argument to tf.tile.
  Returns:
    tiled_tensors: A potentially nested tuple or list of Tensors with the same
      structure as the 'tensors' input argument. Contains the result of
      applying tf.tile to each Tensor in 'tensors'. When the rank of a Tensor
      in 'tensors' is greater than the length of multiples, multiples is padded
      at the end with 1s. For example when tiling a 4-dimensional Tensor with
      multiples [3, 4], multiples would be padded to [3, 4, 1, 1] before tiling.
  """
  def tile_fn(x):
Dieterich Lawson's avatar
Dieterich Lawson committed
66
    return tf.tile(x, multiples + [1] * (x.shape.ndims - len(multiples)))
67
68
69
70

  return map_nested(tile_fn, tensors)


Dieterich Lawson's avatar
Dieterich Lawson committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def where_tensors(condition, x_tensors, y_tensors):
  """Performs a tf.where operation on a two sets of Tensors.

  Args:
    condition: The condition tensor to use for the where operation.
    x_tensors: A potentially nested tuple or list of Tensors.
    y_tensors: A potentially nested tuple or list of Tensors. Must have the
    same structure as x_tensors.
  Returns:
    whered_tensors: A potentially nested tuple or list of Tensors with the
      same structure as the 'tensors' input argument. Contains the result of
      applying tf.where(condition, x, y) on each pair of elements in x_tensors
      and y_tensors.
  """
  flat_x = nest.flatten(x_tensors)
  flat_y = nest.flatten(y_tensors)
  result = [tf.where(condition, x, y) for x, y in
            itertools.izip(flat_x, flat_y)]

  return nest.pack_sequence_as(x_tensors, result)


93
94
95
96
97
98
99
100
101
102
103
104
105
106
def gather_tensors(tensors, indices):
  """Performs a tf.gather operation on a set of Tensors.

  Args:
    tensors: A potentially nested tuple or list of Tensors.
    indices: The indices to use for the gather operation.
  Returns:
    gathered_tensors: A potentially nested tuple or list of Tensors with the
      same structure as the 'tensors' input argument. Contains the result of
      applying tf.gather(x, indices) on each element x in 'tensors'.
  """
  return map_nested(lambda x: tf.gather(x, indices), tensors)


Dieterich Lawson's avatar
Dieterich Lawson committed
107
def tas_for_tensors(tensors, length, **kwargs):
108
109
110
111
112
113
  """Unstacks a set of Tensors into TensorArrays.

  Args:
    tensors: A potentially nested tuple or list of Tensors with length in the
      first dimension greater than or equal to the 'length' input argument.
    length: The desired length of the TensorArrays.
Dieterich Lawson's avatar
Dieterich Lawson committed
114
    **kwargs: Keyword args for TensorArray constructor.
115
116
117
118
119
120
  Returns:
    tensorarrays: A potentially nested tuple or list of TensorArrays with the
      same structure as 'tensors'. Contains the result of unstacking each Tensor
      in 'tensors'.
  """
  def map_fn(x):
Dieterich Lawson's avatar
Dieterich Lawson committed
121
122
    ta = tf.TensorArray(x.dtype, length,
                        name=x.name.split(':')[0] + '_ta', **kwargs)
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    return ta.unstack(x[:length, :])
  return map_nested(map_fn, tensors)


def read_tas(tas, index):
  """Performs a read operation on a set of TensorArrays.

  Args:
    tas: A potentially nested tuple or list of TensorArrays with length greater
      than 'index'.
    index: The location to read from.
  Returns:
    read_tensors: A potentially nested tuple or list of Tensors with the same
      structure as the 'tas' input argument. Contains the result of
      performing a read operation at 'index' on each TensorArray in 'tas'.
  """
  return map_nested(lambda ta: ta.read(index), tas)