1 | /* Copyright 2015 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 | // See docs in ../ops/nn_ops.cc. |
17 | |
18 | #define EIGEN_USE_THREADS |
19 | |
20 | #include "tensorflow/core/kernels/l2loss_op.h" |
21 | |
22 | #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" |
23 | #include "tensorflow/core/framework/numeric_op.h" |
24 | #include "tensorflow/core/framework/op_kernel.h" |
25 | #include "tensorflow/core/framework/register_types.h" |
26 | #include "tensorflow/core/framework/tensor.h" |
27 | |
28 | namespace tensorflow { |
29 | |
30 | typedef Eigen::ThreadPoolDevice CPUDevice; |
31 | |
32 | template <typename T> |
33 | class L2LossOp<CPUDevice, T> : public OpKernel { |
34 | public: |
35 | explicit L2LossOp(OpKernelConstruction* context) : OpKernel(context) {} |
36 | |
37 | void Compute(OpKernelContext* context) override { |
38 | // The input tensor can be of any number of dimensions, even though it's |
39 | // 2D in most typical applications. |
40 | const Tensor& input = context->input(0); |
41 | // The output is a single number. |
42 | Tensor* output = nullptr; |
43 | OP_REQUIRES_OK(context, |
44 | context->allocate_output(0, TensorShape({}), &output)); |
45 | const CPUDevice& d = context->eigen_device<CPUDevice>(); |
46 | output->scalar<T>().device(d) = |
47 | (input.flat<T>().square() * static_cast<T>(0.5)).sum(); |
48 | } |
49 | }; |
50 | |
51 | #define REGISTER_KERNEL(T) \ |
52 | REGISTER_KERNEL_BUILDER( \ |
53 | Name("L2Loss").Device(DEVICE_CPU).TypeConstraint<T>("T"), \ |
54 | L2LossOp<CPUDevice, T>); |
55 | |
56 | REGISTER_KERNEL(float); |
57 | REGISTER_KERNEL(double); |
58 | REGISTER_KERNEL(Eigen::half); |
59 | #ifdef INTEL_MKL |
60 | // Since Eigen backend does not support bfloat16 ops, we are selectively |
61 | // enabling them for MKL backend. |
62 | REGISTER_KERNEL(bfloat16); |
63 | #endif // INTEL_MKL |
64 | #undef REGISTER_KERNEL |
65 | |
66 | } // namespace tensorflow |
67 | |