Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2016 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/sparse_ops.cc.
     17 
     18 #define EIGEN_USE_THREADS
     19 
     20 #include <numeric>
     21 
     22 #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
     23 #include "tensorflow/core/framework/op_kernel.h"
     24 #include "tensorflow/core/framework/register_types.h"
     25 #include "tensorflow/core/framework/tensor.h"
     26 #include "tensorflow/core/framework/tensor_util.h"
     27 #include "tensorflow/core/framework/types.h"
     28 #include "tensorflow/core/util/sparse/sparse_tensor.h"
     29 
     30 using tensorflow::gtl::ArraySlice;
     31 using tensorflow::sparse::SparseTensor;
     32 
     33 namespace tensorflow {
     34 
     35 using CPUDevice = Eigen::ThreadPoolDevice;
     36 
     37 template <typename Device, typename T>
     38 class SparseSoftmaxOp : public OpKernel {
     39  public:
     40   explicit SparseSoftmaxOp(OpKernelConstruction *context) : OpKernel(context) {}
     41 
     42   void Compute(OpKernelContext *context) override {
     43     const Tensor *indices_t, *values_t, *shape_t;
     44     OP_REQUIRES_OK(context, context->input("sp_indices", &indices_t));
     45     OP_REQUIRES_OK(context, context->input("sp_values", &values_t));
     46     OP_REQUIRES_OK(context, context->input("sp_shape", &shape_t));
     47 
     48     // Validations.
     49     OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices_t->shape()),
     50                 errors::InvalidArgument(
     51                     "Input sp_indices should be a matrix but received shape: ",
     52                     indices_t->shape().DebugString()));
     53     OP_REQUIRES(context,
     54                 TensorShapeUtils::IsVector(values_t->shape()) &&
     55                     TensorShapeUtils::IsVector(shape_t->shape()),
     56                 errors::InvalidArgument(
     57                     "Inputs sp_values and sp_shape should be vectors "
     58                     "but received shapes: ",
     59                     values_t->shape().DebugString(), " and ",
     60                     shape_t->shape().DebugString()));
     61     OP_REQUIRES(context, shape_t->NumElements() >= 2,
     62                 errors::InvalidArgument(
     63                     "Input should have rank >= 2, but received shape: ",
     64                     shape_t->SummarizeValue(3)));
     65     OP_REQUIRES(context,
     66                 indices_t->dim_size(0) < std::numeric_limits<int>::max(),
     67                 errors::InvalidArgument(
     68                     "Number of non-zero elements exceeds int32 range"));
     69 
     70     const int nnz = static_cast<int>(indices_t->dim_size(0));
     71     const int rank = static_cast<int>(indices_t->dim_size(1));
     72     SparseTensor st(tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),
     73                     TensorShape(shape_t->flat<int64>()));
     74 
     75     Tensor *output_values = nullptr;
     76     OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({nnz}),
     77                                                      &output_values));
     78     typename TTypes<T>::Flat output_flat = output_values->flat<T>();
     79 
     80     Tensor tmp_t;
     81     OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
     82                                                    TensorShape({}), &tmp_t));
     83     typename TTypes<T>::Scalar tmp_scalar = tmp_t.scalar<T>();
     84 
     85     gtl::InlinedVector<int64, 4> dims(rank);
     86     std::iota(dims.begin(), dims.end(), 0);
     87     // { 0, ..., rank-1 }.
     88     const ArraySlice<int64> kReorderDims(dims);
     89     // All but the last dim -- the class dimension to be max-reduced along.
     90     const ArraySlice<int64> kGroupByDims(kReorderDims, 0, rank - 1);
     91     st.Reorder<T>(kReorderDims);
     92     int count = 0;
     93 
     94     // The SparseTensor has logical shape [..., b, c], where the
     95     // innermost size-"c" dimension is the class dimension to be max-reduced.
     96     // Therefore we group by the first (rank - 1) dimensions.
     97     const Device &device = context->eigen_device<Device>();
     98     for (const auto &g : st.group(kGroupByDims)) {
     99       const auto group_vals = g.values<T>();
    100       const int group_size = group_vals.size();
    101 
    102       // Shifts by max, exponentiates, then renormalizes.
    103       tmp_scalar.device(context->eigen_device<Device>()) = group_vals.maximum();
    104       const T group_max = tmp_scalar();
    105 
    106       Eigen::Tensor<T, 1, Eigen::RowMajor> tmp(group_size);
    107       tmp.device(device) = (group_vals - tmp.constant(group_max)).exp();
    108 
    109       tmp_scalar.device(device) = tmp.sum().inverse();
    110       tmp.device(device) = tmp * tmp.constant(tmp_scalar());
    111 
    112       // Assigns back to output[count, count + group_size).
    113       Eigen::TensorMap<Eigen::Tensor<T, 1, Eigen::RowMajor>> output_part(
    114           output_flat.data() + count, group_size);
    115       output_part.device(device) = tmp;
    116 
    117       count += group_size;
    118     }
    119   }
    120 };
    121 
    122 #define REGISTER_KERNEL(T)                                             \
    123   REGISTER_KERNEL_BUILDER(                                             \
    124       Name("SparseSoftmax").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
    125       SparseSoftmaxOp<CPUDevice, T>)
    126 
    127 REGISTER_KERNEL(float);
    128 REGISTER_KERNEL(double);
    129 #undef REGISTER_KERNEL
    130 
    131 }  // namespace tensorflow
    132