aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/kernels/cwise_op_clip.cc
blob: 49b90e855be64995966b41e2de57781f3e26277a (plain)
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
/* 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.
==============================================================================*/

#include "tensorflow/core/kernels/cwise_op_clip.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

// Basic coefficient-wise tenary operations.
// This is the case for example of the clip_by_value.
//   Device: E.g., CPUDevice, GPUDevice.
//   Functor: defined above. E.g., functor::clip.
template <typename Device, typename T>
class ClipOp : public OpKernel {
 public:
  explicit ClipOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}

  void Compute(OpKernelContext* ctx) override {
    const Tensor& in0 = ctx->input(0);
    const Tensor& in1 = ctx->input(1);
    const Tensor& in2 = ctx->input(2);
    OP_REQUIRES(ctx, (in0.shape() == in1.shape() ||
                      TensorShapeUtils::IsScalar(in1.shape())) &&
                     (in0.shape() == in2.shape() ||
                      TensorShapeUtils::IsScalar(in2.shape())),
                errors::InvalidArgument(
                    "clip_value_min and clip_value_max must be either of "
                    "the same shape as input, or a scalar. ",
                    "input shape: ", in0.shape().DebugString(),
                    "clip_value_min shape: ", in1.shape().DebugString(),
                    "clip_value_max shape: ", in2.shape().DebugString()));

    Tensor* out = nullptr;
    OP_REQUIRES_OK(
        ctx, ctx->forward_input_or_allocate_output({0}, 0, in0.shape(), &out));
    if (out->NumElements() == 0) return;  // Nothing to do for empty output

    auto in0_flat = in0.flat<T>();
    auto in1_flat = in1.flat<T>();
    auto in2_flat = in2.flat<T>();
    auto out_flat = out->flat<T>();
    const Device& d = ctx->eigen_device<Device>();

    if (in1.shape() == in2.shape()) {
      if (in0.shape() == in1.shape()) {
        functor::TernaryClipOp<Device, T>()(d, in0_flat, in1_flat, in2_flat,
                                            out_flat);
      } else {
        functor::UnaryClipOp<Device, T>()(d, in0_flat, in1_flat, in2_flat,
                                          out_flat);
      }
    } else {
      if (in0.shape() == in1.shape()) {
        functor::BinaryLeftClipOp<Device, T>()(d, in0_flat, in1_flat, in2_flat,
                                               out_flat);
      } else {
        functor::BinaryRightClipOp<Device, T>()(d, in0_flat, in1_flat, in2_flat,
                                                out_flat);
      }
    }
  }
};

namespace functor {
// Unary functor for clip [Tensor, Scalar, Scalar]
template <typename T>
struct UnaryClipFunc {
  UnaryClipFunc(const T& value_min, const T& value_max)
      : value_min(value_min), value_max(value_max) {}
  const T operator()(const T& value) const {
    return std::max(std::min(value, value_max), value_min);
  }
  T value_min;
  T value_max;
};
template <typename T>
struct UnaryClipOp<CPUDevice, T> {
  void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat& in0_flat,
                  typename TTypes<T>::ConstFlat& in1_flat,
                  typename TTypes<T>::ConstFlat& in2_flat,
                  typename TTypes<T>::Flat& out_flat) const {
    out_flat = in0_flat.unaryExpr(UnaryClipFunc<T>(in1_flat(0), in2_flat(0)));
  }
};

// Binary functor for clip [Tensor, Scalar, Tensor]
template <typename T>
struct BinaryRightClipFunc {
  explicit BinaryRightClipFunc(const T& value_min) : value_min(value_min) {}
  const T operator()(const T& value, const T& value_max) const {
    return std::max(std::min(value, value_max), value_min);
  }
  T value_min;
};
template <typename T>
struct BinaryRightClipOp<CPUDevice, T> {
  void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat& in0_flat,
                  typename TTypes<T>::ConstFlat& in1_flat,
                  typename TTypes<T>::ConstFlat& in2_flat,
                  typename TTypes<T>::Flat& out_flat) const {
    out_flat =
        in0_flat.binaryExpr(in2_flat, BinaryRightClipFunc<T>(in1_flat(0)));
  }
};

// Binary functor for clip [Tensor, Tensor, Scalar]
template <typename T>
struct BinaryLeftClipFunc {
  explicit BinaryLeftClipFunc(const T& value_max) : value_max(value_max) {}
  const T operator()(const T& value, const T& value_min) const {
    return std::max(std::min(value, value_max), value_min);
  }
  T value_max;
};
template <typename T>
struct BinaryLeftClipOp<CPUDevice, T> {
  void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat& in0_flat,
                  typename TTypes<T>::ConstFlat& in1_flat,
                  typename TTypes<T>::ConstFlat& in2_flat,
                  typename TTypes<T>::Flat& out_flat) const {
    out_flat =
        in0_flat.binaryExpr(in1_flat, BinaryLeftClipFunc<T>(in2_flat(0)));
  }
};

// Ternary functor for clip [Tensor, Tensor, Tensor]
template <typename T>
struct TernaryClipOp<CPUDevice, T> {
  void operator()(const CPUDevice& d, typename TTypes<T>::ConstFlat& in0_flat,
                  typename TTypes<T>::ConstFlat& in1_flat,
                  typename TTypes<T>::ConstFlat& in2_flat,
                  typename TTypes<T>::Flat& out_flat) const {
    out_flat.device(d) = in0_flat.cwiseMin(in2_flat).cwiseMax(in1_flat);
  }
};

#define INSTANTIATE_CPU(T)                         \
  template struct UnaryClipOp<CPUDevice, T>;       \
  template struct BinaryRightClipOp<CPUDevice, T>; \
  template struct BinaryLeftClipOp<CPUDevice, T>;  \
  template struct TernaryClipOp<CPUDevice, T>;
INSTANTIATE_CPU(Eigen::half);
INSTANTIATE_CPU(float);
INSTANTIATE_CPU(double);
INSTANTIATE_CPU(int8);
INSTANTIATE_CPU(int16);
INSTANTIATE_CPU(int32);
INSTANTIATE_CPU(int64);
INSTANTIATE_CPU(uint8);
INSTANTIATE_CPU(uint16);
#undef INSTANTIATE_CPU
}  // namespace functor

#define REGISTER_CPU_KERNEL(type)                                       \
  REGISTER_KERNEL_BUILDER(                                              \
      Name("ClipByValue").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      ClipOp<CPUDevice, type>);

REGISTER_CPU_KERNEL(Eigen::half);
REGISTER_CPU_KERNEL(float);
REGISTER_CPU_KERNEL(double);
REGISTER_CPU_KERNEL(int8);
REGISTER_CPU_KERNEL(int16);
REGISTER_CPU_KERNEL(int32);
REGISTER_CPU_KERNEL(int64);
REGISTER_CPU_KERNEL(uint8);
REGISTER_CPU_KERNEL(uint16);
#undef REGISTER_CPU_KERNEL

#if GOOGLE_CUDA

#define REGISTER_GPU_KERNEL(type)                                       \
  REGISTER_KERNEL_BUILDER(                                              \
      Name("ClipByValue").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      ClipOp<GPUDevice, type>);
REGISTER_GPU_KERNEL(Eigen::half);
REGISTER_GPU_KERNEL(float);
REGISTER_GPU_KERNEL(double);
REGISTER_GPU_KERNEL(int8);
REGISTER_GPU_KERNEL(int16);
REGISTER_GPU_KERNEL(int64);
REGISTER_GPU_KERNEL(uint8);
REGISTER_GPU_KERNEL(uint16);

// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("ClipByValue")
                            .Device(DEVICE_GPU)
                            .HostMemory("t")
                            .HostMemory("clip_value_min")
                            .HostMemory("clip_value_max")
                            .HostMemory("output")
                            .TypeConstraint<int32>("T"),
                        ClipOp<CPUDevice, int32>);

#undef REGISTER_GPU_KERNEL
#endif

}  // namespace tensorflow