Home | History | Annotate | Download | only in kernels
      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 #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
     22 #include "tensorflow/core/framework/numeric_op.h"
     23 #include "tensorflow/core/framework/op_kernel.h"
     24 #include "tensorflow/core/framework/register_types.h"
     25 #include "tensorflow/core/framework/tensor.h"
     26 
     27 namespace tensorflow {
     28 
     29 typedef Eigen::ThreadPoolDevice CPUDevice;
     30 
     31 template <typename T>
     32 class L2LossOp<CPUDevice, T> : public OpKernel {
     33  public:
     34   explicit L2LossOp(OpKernelConstruction* context) : OpKernel(context) {}
     35 
     36   void Compute(OpKernelContext* context) override {
     37     // The input tensor can be of any number of dimensions, even though it's
     38     // 2D in most typical applications.
     39     const Tensor& input = context->input(0);
     40     // The output is a single number.
     41     Tensor* output = nullptr;
     42     OP_REQUIRES_OK(context,
     43                    context->allocate_output(0, TensorShape({}), &output));
     44     const CPUDevice& d = context->eigen_device<CPUDevice>();
     45     output->scalar<T>().device(d) =
     46         (input.flat<T>().square() * static_cast<T>(0.5)).sum();
     47   }
     48 };
     49 
     50 #define REGISTER_KERNEL(T)                                      \
     51   REGISTER_KERNEL_BUILDER(                                      \
     52       Name("L2Loss").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
     53       L2LossOp<CPUDevice, T>);
     54 
     55 REGISTER_KERNEL(float);
     56 REGISTER_KERNEL(double);
     57 REGISTER_KERNEL(Eigen::half);
     58 #undef REGISTER_KERNEL
     59 
     60 }  // namespace tensorflow
     61