1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15
16"""Operations for automatic batching and unbatching."""
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21from tensorflow.python.eager import function
22from tensorflow.python.framework import ops
23from tensorflow.python.framework import tensor_spec
24from tensorflow.python.ops import gen_batch_ops
25# pylint: disable=wildcard-import
26from tensorflow.python.ops.gen_batch_ops import *
27# pylint: enable=wildcard-import
28from tensorflow.python.util.tf_export import tf_export
29
30
31@tf_export("nondifferentiable_batch_function")
32def batch_function(num_batch_threads,
33                   max_batch_size,
34                   batch_timeout_micros,
35                   allowed_batch_sizes=None,
36                   max_enqueued_batches=10,
37                   autograph=True,
38                   enable_large_batch_splitting=True):
39  """Batches the computation done by the decorated function.
40
41  So, for example, in the following code
42
43  ```python
44  @batch_function(1, 2, 3)
45  def layer(a):
46    return tf.matmul(a, a)
47
48  b = layer(w)
49  ```
50
51  if more than one session.run call is simultaneously trying to compute `b`
52  the values of `w` will be gathered, non-deterministically concatenated
53  along the first axis, and only one thread will run the computation. See the
54  documentation of the `Batch` op for more details.
55
56  Assumes that all arguments of the decorated function are Tensors which will
57  be batched along their first dimension.
58
59  SparseTensor is not supported. The return value of the decorated function
60  must be a Tensor or a list/tuple of Tensors.
61
62  Args:
63    num_batch_threads: Number of scheduling threads for processing batches
64     of work. Determines the number of batches processed in parallel.
65    max_batch_size: Batch sizes will never be bigger than this.
66    batch_timeout_micros: Maximum number of microseconds to wait before
67     outputting an incomplete batch.
68    allowed_batch_sizes: Optional list of allowed batch sizes. If left empty,
69     does nothing. Otherwise, supplies a list of batch sizes, causing the op
70     to pad batches up to one of those sizes. The entries must increase
71     monotonically, and the final entry must equal max_batch_size.
72    max_enqueued_batches: The maximum depth of the batch queue. Defaults to 10.
73    autograph: Whether to use autograph to compile python and eager style code
74     for efficient graph-mode execution.
75    enable_large_batch_splitting: The value of this option doesn't affect
76     processing output given the same input; it affects implementation details
77     as stated below: 1. Improve batching efficiency by eliminating unnecessary
78     adding. 2.`max_batch_size` specifies the limit of input and
79     `allowed_batch_sizes` specifies the limit of a task to be processed. API
80     user can give an input of size 128 when 'max_execution_batch_size'
81     is 32 -> implementation can split input of 128 into 4 x 32, schedule
82     concurrent processing, and then return concatenated results corresponding
83     to 128.
84
85  Returns:
86    The decorated function will return the unbatched computation output Tensors.
87  """
88
89  def decorator(fn):  # pylint: disable=missing-docstring
90
91    def decorated(*args):  # pylint: disable=missing-docstring
92
93      @function.defun(autograph=autograph)
94      def computation(*computation_args):
95        return fn(*computation_args)
96
97      computation = computation.get_concrete_function(
98          *[tensor_spec.TensorSpec(dtype=x.dtype, shape=x.shape, name=str(i))
99            for i, x in enumerate(args)])
100
101      with ops.name_scope("batch") as name:
102        for a in args:
103          if not isinstance(a, ops.Tensor):
104            raise ValueError("All arguments to functions decorated with "
105                             "`batch_function`  are supposed to be Tensors; "
106                             "found %s" % repr(a))
107        return gen_batch_ops.batch_function(
108            num_batch_threads=num_batch_threads,
109            max_batch_size=max_batch_size,
110            batch_timeout_micros=batch_timeout_micros,
111            allowed_batch_sizes=allowed_batch_sizes,
112            max_enqueued_batches=max_enqueued_batches,
113            shared_name=name,
114            enable_large_batch_splitting=enable_large_batch_splitting,
115            f=computation,
116            in_tensors=list(args),
117            captured_tensors=computation.captured_inputs,
118            Tout=[o.dtype for o in computation.outputs])
119
120    return decorated
121
122  return decorator
123