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:
SparseSoftmaxOp(OpKernelConstruction * context)40   explicit SparseSoftmaxOp(OpKernelConstruction *context) : OpKernel(context) {}
41 
Compute(OpKernelContext * context)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 
66     const int64 nnz = indices_t->dim_size(0);
67     const int rank = static_cast<int>(indices_t->dim_size(1));
68     SparseTensor st;
69     OP_REQUIRES_OK(
70         context, SparseTensor::Create(
71                      tensor::DeepCopy(*indices_t), tensor::DeepCopy(*values_t),
72                      TensorShape(shape_t->flat<int64>()), &st));
73 
74     Tensor *output_values = nullptr;
75     OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({nnz}),
76                                                      &output_values));
77     typename TTypes<T>::Flat output_flat = output_values->flat<T>();
78 
79     Tensor tmp_t;
80     OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::value,
81                                                    TensorShape({}), &tmp_t));
82     typename TTypes<T>::Scalar tmp_scalar = tmp_t.scalar<T>();
83 
84     gtl::InlinedVector<int64, 4> dims(rank);
85     std::iota(dims.begin(), dims.end(), 0);
86     // { 0, ..., rank-1 }.
87     const ArraySlice<int64> kReorderDims(dims);
88     // All but the last dim -- the class dimension to be max-reduced along.
89     const ArraySlice<int64> kGroupByDims = kReorderDims.subspan(0, rank - 1);
90     st.Reorder<T>(kReorderDims);
91     int count = 0;
92 
93     // The SparseTensor has logical shape [..., b, c], where the
94     // innermost size-"c" dimension is the class dimension to be max-reduced.
95     // Therefore we group by the first (rank - 1) dimensions.
96     const Device &device = context->eigen_device<Device>();
97     for (const auto &g : st.group(kGroupByDims)) {
98       const auto group_vals = g.values<T>();
99       const int group_size = group_vals.size();
100 
101       // Shifts by max, exponentiates, then renormalizes.
102       tmp_scalar.device(context->eigen_device<Device>()) = group_vals.maximum();
103       const T group_max = tmp_scalar();
104 
105       Eigen::Tensor<T, 1, Eigen::RowMajor> tmp(group_size);
106       tmp.device(device) = (group_vals - tmp.constant(group_max)).exp();
107 
108       tmp_scalar.device(device) = tmp.sum().inverse();
109       tmp.device(device) = tmp * tmp.constant(tmp_scalar());
110 
111       // Assigns back to output[count, count + group_size).
112       Eigen::TensorMap<Eigen::Tensor<T, 1, Eigen::RowMajor>> output_part(
113           output_flat.data() + count, group_size);
114       output_part.device(device) = tmp;
115 
116       count += group_size;
117     }
118   }
119 };
120 
121 #define REGISTER_KERNEL(T)                                             \
122   REGISTER_KERNEL_BUILDER(                                             \
123       Name("SparseSoftmax").Device(DEVICE_CPU).TypeConstraint<T>("T"), \
124       SparseSoftmaxOp<CPUDevice, T>)
125 
126 REGISTER_KERNEL(float);
127 REGISTER_KERNEL(double);
128 #undef REGISTER_KERNEL
129 
130 }  // namespace tensorflow
131