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