hierarchical_sigmoid_op.h 9.0 KB
Newer Older
Y
Yancey1989 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once
Q
Qiao Longfei 已提交
16

W
weixing02 已提交
17
#include <iostream>
18
#include <iterator>
Q
Qiao Longfei 已提交
19
#include <memory>
J
JiabinYang 已提交
20
#include <set>
21
#include <string>
W
weixing02 已提交
22
#include <vector>
Q
Qiao Longfei 已提交
23

J
JiabinYang 已提交
24
#include "paddle/fluid/framework/mixed_vector.h"
W
weixing02 已提交
25 26 27 28 29
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/clip_op.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/matrix_bit_code.h"
#include "paddle/fluid/platform/transform.h"
J
JiabinYang 已提交
30

31 32 33 34
#ifdef PADDLE_WITH_DISTRIBUTE
#include "paddle/fluid/operators/distributed/parameter_prefetch.h"
#endif

Y
Yancey1989 已提交
35 36 37
namespace paddle {
namespace operators {

Y
Yancey1989 已提交
38 39 40
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
Y
Yancey1989 已提交
41
using platform::Transform;
42
using framework::LoDTensor;
Y
Yancey1989 已提交
43

44
static std::vector<int64_t> PathToRows(const LoDTensor& path) {
J
JiabinYang 已提交
45
  std::set<int64_t> rows;
46
  const int64_t* paths = path.data<int64_t>();
J
JiabinYang 已提交
47
  for (int64_t i = 0; i < path.numel(); ++i) {
48
    int64_t row = paths[i];
J
JiabinYang 已提交
49 50
    if (row < 0) {
      continue;
J
JiabinYang 已提交
51
    }
J
JiabinYang 已提交
52
    rows.emplace(row);
J
JiabinYang 已提交
53
  }
J
JiabinYang 已提交
54
  return std::vector<int64_t>(rows.begin(), rows.end());
J
JiabinYang 已提交
55
}
Y
Yancey1989 已提交
56
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
57 58
class HierarchicalSigmoidOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
59
  void Compute(const framework::ExecutionContext& ctx) const override {
60 61 62 63 64 65 66 67 68 69 70
    auto& in = GET_DATA_SAFELY(ctx.Input<LoDTensor>("X"), "Input", "X",
                               "HierarchicalSigmoid");
    auto& w = GET_DATA_SAFELY(ctx.Input<LoDTensor>("W"), "Input", "W",
                              "HierarchicalSigmoid");
    auto* path = ctx.Input<LoDTensor>("PathTable");
    auto* code = ctx.Input<LoDTensor>("PathCode");
    auto& label = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Label"), "Input",
                                  "Label", "HierarchicalSigmoid");
    auto* bias = ctx.Input<LoDTensor>("Bias");
    auto* out = ctx.Output<LoDTensor>("Out");
    auto* pre_out = ctx.Output<LoDTensor>("PreOut");
Y
Yancey1989 已提交
71
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
72 73
    // for remote prefetch

74 75 76 77 78 79
    bool is_custom = false;
    if (path) {
      is_custom = true;
    }
    int64_t code_length =
        path ? path->dims()[1] : math::FindLastSet(num_classes - 1);
J
JiabinYang 已提交
80
    int64_t batch_size = in.dims()[0];
81
    LoDTensor sum;
W
weixing02 已提交
82
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
G
guosheng 已提交
83
    auto* pre_out_data = pre_out->mutable_data<T>(
Y
Yancey1989 已提交
84
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
W
weixing02 已提交
85
    auto pre_out_mat = EigenMatrix<T>::From(*pre_out);
G
guosheng 已提交
86 87
    // Not all class(leaf) nodes' path lengths equal code_length, thus init as
    // 0s can avoid out of path's loss.
88
    math::SetConstant<DeviceContext, T> zero;
W
weixing02 已提交
89
    zero(dev_ctx, pre_out, static_cast<T>(0.0));
Y
Yancey1989 已提交
90 91
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    math::RowwiseSum<DeviceContext, T> row_sum;
92 93 94

    std::unique_ptr<math::MatrixBitCodeFunctor<T>> bit_code;
    if (!is_custom) {
95 96
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(
          num_classes, label.template data<int64_t>()));
97
    } else {
98 99
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(
          *path, *code, label.template data<int64_t>()));
100
    }
Y
Yancey1989 已提交
101

Y
Yancey1989 已提交
102 103
    std::vector<int64_t> sum_dims({batch_size, 1UL});
    sum.mutable_data<T>(framework::make_ddim(sum_dims), ctx.GetPlace());
Y
Yancey1989 已提交
104
    auto sum_mat = EigenMatrix<T>::From(sum);
Y
Yancey1989 已提交
105
    out->mutable_data<T>(ctx.GetPlace());
106
    auto out_mat = framework::EigenMatrix<T>::From(*out);
Y
Yancey1989 已提交
107
    if (bias) {
108
      bit_code->Add(*bias, pre_out);
Y
Yancey1989 已提交
109
    }
J
JiabinYang 已提交
110
    bit_code->Mul(pre_out, w, in);
G
guosheng 已提交
111
    // clip to [-40, 40]
Y
Yancey1989 已提交
112 113
    Transform<DeviceContext> trans;
    trans(ctx.template device_context<DeviceContext>(), pre_out_data,
W
weixing02 已提交
114
          pre_out_data + pre_out->numel(), pre_out_data,
Y
Yancey1989 已提交
115
          ClipFunctor<T>(static_cast<T>(-40.0), static_cast<T>(40.0)));
116
    bit_code->Sum(*pre_out, out, static_cast<T>(-1));
G
guosheng 已提交
117
    // use softrelu to calculate cross entropy
Y
Yancey1989 已提交
118
    pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
W
weixing02 已提交
119
    row_sum(dev_ctx, *pre_out, &sum);
120 121 122 123
    // TODO(guosheng): Subtract the out of path's loss, since not all
    // class(leaf) nodes' path lengths equal code_length. But it won't break the
    // gradient check since both have the out of path's loss and will cancel out
    // each other.
Y
Yancey1989 已提交
124
    out_mat.device(place) = sum_mat + out_mat;
Y
Yancey1989 已提交
125
  }
Y
Yancey1989 已提交
126 127
};

Y
Yancey1989 已提交
128
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
129 130
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
131
  void Compute(const framework::ExecutionContext& ctx) const override {
132 133 134 135 136 137 138
    auto& in = GET_DATA_SAFELY(ctx.Input<LoDTensor>("X"), "Input", "X",
                               "HierarchicalSigmoidGrad");
    auto& w = GET_DATA_SAFELY(ctx.Input<LoDTensor>("W"), "Input", "W",
                              "HierarchicalSigmoidGrad");
    auto* path = ctx.Input<LoDTensor>("PathTable");
    auto* code = ctx.Input<LoDTensor>("PathCode");
    auto* in_grad = ctx.Output<LoDTensor>(framework::GradVarName("X"));
J
JiabinYang 已提交
139 140 141
    bool is_sparse = ctx.Attr<bool>("is_sparse");
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    math::SetConstant<DeviceContext, T> zero;
142 143 144 145 146 147 148 149
    auto& label = GET_DATA_SAFELY(ctx.Input<LoDTensor>("Label"), "Input",
                                  "Label", "HierarchicalSigmoidGrad");
    auto& pre_out = GET_DATA_SAFELY(ctx.Input<LoDTensor>("PreOut"), "Input",
                                    "PreOut", "HierarchicalSigmoidGrad");
    auto& out_grad = GET_DATA_SAFELY(
        ctx.Input<LoDTensor>(framework::GradVarName("Out")), "Input",
        framework::GradVarName("Out"), "HierarchicalSigmoidGrad");
    LoDTensor pre_out_grad;
150

J
JiabinYang 已提交
151
    pre_out_grad.mutable_data<T>(pre_out.dims(), ctx.GetPlace());
152 153
    in_grad->mutable_data<T>(ctx.GetPlace());
    zero(dev_ctx, in_grad, static_cast<T>(0.0));
W
weixing02 已提交
154

Y
Yancey1989 已提交
155
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
156 157 158 159 160 161 162 163

    bool is_custom = false;
    if (path) {
      is_custom = true;
    }

    std::unique_ptr<math::MatrixBitCodeFunctor<T>> bit_code;
    if (!is_custom) {
164 165
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(
          num_classes, label.template data<int64_t>()));
166
    } else {
167 168
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(
          *path, *code, label.template data<int64_t>()));
169
    }
170

Y
Use mkl  
Yu Yang 已提交
171
    // softrelu derivative
J
JiabinYang 已提交
172

Y
Use mkl  
Yu Yang 已提交
173
    auto blas = math::GetBlas<DeviceContext, T>(ctx);
174

Y
Use mkl  
Yu Yang 已提交
175
    auto* pre_out_grad_data = pre_out_grad.data<T>();
176
    auto* pre_out_data = pre_out.template data<T>();
Y
Use mkl  
Yu Yang 已提交
177 178 179 180 181 182
    auto n = pre_out.numel();
    blas.VEXP(n, pre_out_data, pre_out_grad_data);
    blas.VINV(n, pre_out_grad_data, pre_out_grad_data);
    for (int64_t i = 0; i < n; ++i) {
      pre_out_grad_data[i] = 1.0 - pre_out_grad_data[i];
    }
183
    bit_code->Sub(&pre_out_grad);  // the gradient of clip(w * x + b)
184
    auto* out_grad_data = out_grad.template data<T>();
Y
Use mkl  
Yu Yang 已提交
185 186 187 188 189 190 191

    int64_t dim0 = pre_out_grad.dims()[0];
    int64_t dim1 = pre_out_grad.dims()[1];
    for (int64_t i = 0; i < dim0; ++i) {
      T tmp = out_grad_data[i];
      blas.SCAL(dim1, tmp, pre_out_grad_data + i * dim1);
    }
G
guosheng 已提交
192 193
    // TODO(guosheng): multiply pre_out_grad with subgradient of clipping to
    // be consistent with the clipping in forward.
194
    auto* bias_grad = ctx.Output<LoDTensor>(framework::GradVarName("Bias"));
195 196 197 198 199
    if (bias_grad) {
      bias_grad->mutable_data<T>(ctx.GetPlace());
      zero(dev_ctx, bias_grad, static_cast<T>(0.0));
      bit_code->AddGrad(pre_out_grad, bias_grad);
    }
J
JiabinYang 已提交
200
    if (!is_sparse) {
201
      auto* w_grad = ctx.Output<LoDTensor>(framework::GradVarName("W"));
J
JiabinYang 已提交
202 203
      w_grad->mutable_data<T>(ctx.GetPlace());
      zero(dev_ctx, w_grad, static_cast<T>(0.0));
J
JiabinYang 已提交
204
      bit_code->MulGradWeight(pre_out_grad, w_grad, in);
J
JiabinYang 已提交
205
    } else {
206 207
      PADDLE_ENFORCE(path != nullptr,
                     "Sparse mode should not be used without custom tree!");
J
JiabinYang 已提交
208
      framework::Vector<int64_t> real_rows = PathToRows(*path);
J
JiabinYang 已提交
209 210 211
      auto* w_grad =
          ctx.Output<framework::SelectedRows>(framework::GradVarName("W"));
      w_grad->set_rows(real_rows);
212
      // Build a map of id -> row_index to speed up finding the index of one id
J
JiabinYang 已提交
213
      w_grad->set_height(w.dims()[0]);
J
JiabinYang 已提交
214
      auto* w_grad_value = w_grad->mutable_value();
J
JiabinYang 已提交
215
      framework::DDim temp_dim(w.dims());
216
      temp_dim[0] = real_rows.size();
J
JiabinYang 已提交
217 218
      w_grad_value->mutable_data<T>(temp_dim, ctx.GetPlace());
      zero(dev_ctx, w_grad_value, static_cast<T>(0.0));
J
JiabinYang 已提交
219
      bit_code->MulGradWeight(pre_out_grad, w_grad, in);
J
JiabinYang 已提交
220
    }
J
JiabinYang 已提交
221
    bit_code->MulGradError(pre_out_grad, w, in_grad);
Y
Yancey1989 已提交
222
  }
Y
Yancey1989 已提交
223 224 225 226
};

}  // namespace operators
}  // namespace paddle