hierarchical_sigmoid_op.h 9.2 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
W
weixing02 已提交
16
#include <iostream>
J
JiabinYang 已提交
17
#include <set>
W
weixing02 已提交
18
#include <vector>
J
JiabinYang 已提交
19
#include "paddle/fluid/framework/mixed_vector.h"
W
weixing02 已提交
20 21
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/clip_op.h"
J
JiabinYang 已提交
22
#include "paddle/fluid/operators/detail/safe_ref.h"
W
weixing02 已提交
23 24 25
#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 已提交
26

Y
Yancey1989 已提交
27 28 29
namespace paddle {
namespace operators {

Y
Yancey1989 已提交
30 31 32
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
Y
Yancey1989 已提交
33
using platform::Transform;
Y
Yancey1989 已提交
34

J
JiabinYang 已提交
35 36 37 38 39 40
static std::vector<int64_t> PathToRows(const framework::LoDTensor& path) {
  std::set<int64_t> rows;
  for (int64_t i = 0; i < path.numel(); ++i) {
    int64_t row = path.data<int64_t>()[i];
    if (row < 0) {
      continue;
J
JiabinYang 已提交
41
    }
J
JiabinYang 已提交
42
    rows.emplace(row);
J
JiabinYang 已提交
43
  }
J
JiabinYang 已提交
44
  return std::vector<int64_t>(rows.begin(), rows.end());
J
JiabinYang 已提交
45
}
Y
Yancey1989 已提交
46
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
47 48
class HierarchicalSigmoidOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
49
  void Compute(const framework::ExecutionContext& ctx) const override {
50 51
    auto& in = detail::Ref(ctx.Input<framework::LoDTensor>("X"));
    auto& w = detail::Ref(ctx.Input<framework::LoDTensor>("W"));
J
JiabinYang 已提交
52
    auto* path = ctx.Input<framework::LoDTensor>("PTable");
J
JiabinYang 已提交
53
    auto* code = ctx.Input<framework::LoDTensor>("PathCode");
54
    auto& label = detail::Ref(ctx.Input<framework::LoDTensor>("Label"));
J
JiabinYang 已提交
55 56 57
    auto* bias = ctx.Input<framework::LoDTensor>("Bias");
    auto* out = ctx.Output<framework::LoDTensor>("Out");
    auto* pre_out = ctx.Output<framework::LoDTensor>("PreOut");
Y
Yancey1989 已提交
58
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
59 60 61 62 63 64
    bool is_custom = false;
    if (path) {
      is_custom = true;
    }
    int64_t code_length =
        path ? path->dims()[1] : math::FindLastSet(num_classes - 1);
J
JiabinYang 已提交
65
    int64_t batch_size = in.dims()[0];
J
JiabinYang 已提交
66
    framework::LoDTensor sum;
W
weixing02 已提交
67
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
G
guosheng 已提交
68
    auto* pre_out_data = pre_out->mutable_data<T>(
Y
Yancey1989 已提交
69
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
W
weixing02 已提交
70
    auto pre_out_mat = EigenMatrix<T>::From(*pre_out);
G
guosheng 已提交
71 72
    // Not all class(leaf) nodes' path lengths equal code_length, thus init as
    // 0s can avoid out of path's loss.
73
    math::SetConstant<DeviceContext, T> zero;
W
weixing02 已提交
74
    zero(dev_ctx, pre_out, static_cast<T>(0.0));
Y
Yancey1989 已提交
75 76
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    math::RowwiseSum<DeviceContext, T> row_sum;
77 78 79 80

    std::unique_ptr<math::MatrixBitCodeFunctor<T>> bit_code;
    if (!is_custom) {
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(num_classes,
J
JiabinYang 已提交
81
                                                       label.data<int64_t>()));
82
    } else {
J
JiabinYang 已提交
83 84
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(*path, *code,
                                                       label.data<int64_t>()));
85
    }
Y
Yancey1989 已提交
86

Y
Yancey1989 已提交
87 88
    std::vector<int64_t> sum_dims({batch_size, 1UL});
    sum.mutable_data<T>(framework::make_ddim(sum_dims), ctx.GetPlace());
Y
Yancey1989 已提交
89
    auto sum_mat = EigenMatrix<T>::From(sum);
Y
Yancey1989 已提交
90
    out->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
91
    auto out_mat = framework::EigenVector<T>::Flatten(*out);
Y
Yancey1989 已提交
92
    if (bias) {
93
      bit_code->Add(*bias, pre_out);
Y
Yancey1989 已提交
94
    }
J
JiabinYang 已提交
95
    bit_code->Mul(pre_out, w, in);
G
guosheng 已提交
96
    // clip to [-40, 40]
Y
Yancey1989 已提交
97 98
    Transform<DeviceContext> trans;
    trans(ctx.template device_context<DeviceContext>(), pre_out_data,
W
weixing02 已提交
99
          pre_out_data + pre_out->numel(), pre_out_data,
Y
Yancey1989 已提交
100
          ClipFunctor<T>(static_cast<T>(-40.0), static_cast<T>(40.0)));
101
    bit_code->Sum(*pre_out, out, static_cast<T>(-1));
G
guosheng 已提交
102
    // use softrelu to calculate cross entropy
Y
Yancey1989 已提交
103
    pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
W
weixing02 已提交
104
    row_sum(dev_ctx, *pre_out, &sum);
105 106 107 108
    // 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 已提交
109
    out_mat.device(place) = sum_mat + out_mat;
Y
Yancey1989 已提交
110
  }
Y
Yancey1989 已提交
111 112
};

Y
Yancey1989 已提交
113
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
114 115
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
116
  void Compute(const framework::ExecutionContext& ctx) const override {
117 118
    auto& in = detail::Ref(ctx.Input<framework::LoDTensor>("X"));
    auto& w = detail::Ref(ctx.Input<framework::LoDTensor>("W"));
J
JiabinYang 已提交
119
    auto* path = ctx.Input<framework::LoDTensor>("PTable");
J
JiabinYang 已提交
120
    auto* code = ctx.Input<framework::LoDTensor>("PathCode");
J
JiabinYang 已提交
121
    auto* bias = ctx.Input<framework::LoDTensor>("Bias");
J
JiabinYang 已提交
122 123 124 125 126
    auto* in_grad =
        ctx.Output<framework::LoDTensor>(framework::GradVarName("X"));
    bool is_sparse = ctx.Attr<bool>("is_sparse");
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    math::SetConstant<DeviceContext, T> zero;
127 128 129
    auto& label = detail::Ref(ctx.Input<framework::LoDTensor>("Label"));
    auto& pre_out = detail::Ref(ctx.Input<framework::LoDTensor>("PreOut"));
    auto& out_grad = detail::Ref(
J
JiabinYang 已提交
130
        ctx.Input<framework::LoDTensor>(framework::GradVarName("Out")));
J
JiabinYang 已提交
131
    framework::LoDTensor pre_out_grad;
132

J
JiabinYang 已提交
133
    pre_out_grad.mutable_data<T>(pre_out.dims(), ctx.GetPlace());
134 135
    in_grad->mutable_data<T>(ctx.GetPlace());
    zero(dev_ctx, in_grad, static_cast<T>(0.0));
W
weixing02 已提交
136

Y
Yancey1989 已提交
137
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
138 139 140 141 142 143 144 145 146

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

    std::unique_ptr<math::MatrixBitCodeFunctor<T>> bit_code;
    if (!is_custom) {
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(num_classes,
J
JiabinYang 已提交
147
                                                       label.data<int64_t>()));
148
    } else {
J
JiabinYang 已提交
149 150
      bit_code.reset(new math::MatrixBitCodeFunctor<T>(*path, *code,
                                                       label.data<int64_t>()));
151
    }
152

Y
Use mkl  
Yu Yang 已提交
153
    // softrelu derivative
J
JiabinYang 已提交
154

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

Y
Use mkl  
Yu Yang 已提交
157 158 159 160 161 162 163 164
    auto* pre_out_grad_data = pre_out_grad.data<T>();
    auto* pre_out_data = pre_out.data<T>();
    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];
    }
165
    bit_code->Sub(&pre_out_grad);  // the gradient of clip(w * x + b)
Y
Use mkl  
Yu Yang 已提交
166 167 168 169 170 171 172 173
    auto* out_grad_data = out_grad.data<T>();

    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 已提交
174 175
    // TODO(guosheng): multiply pre_out_grad with subgradient of clipping to
    // be consistent with the clipping in forward.
J
JiabinYang 已提交
176

J
JiabinYang 已提交
177
    if (!is_sparse) {
J
JiabinYang 已提交
178 179 180 181 182 183 184
      auto* bias_grad =
          ctx.Output<framework::LoDTensor>(framework::GradVarName("Bias"));
      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 已提交
185 186 187 188
      auto* w_grad =
          ctx.Output<framework::LoDTensor>(framework::GradVarName("W"));
      w_grad->mutable_data<T>(ctx.GetPlace());
      zero(dev_ctx, w_grad, static_cast<T>(0.0));
J
JiabinYang 已提交
189
      bit_code->MulGradWeight(pre_out_grad, w_grad, in);
J
JiabinYang 已提交
190
    } else {
J
JiabinYang 已提交
191
      framework::Vector<int64_t> real_rows = PathToRows(*path);
J
JiabinYang 已提交
192 193 194
      auto* w_grad =
          ctx.Output<framework::SelectedRows>(framework::GradVarName("W"));
      w_grad->set_rows(real_rows);
195
      // Build a map of id -> row_index to speed up finding the index of one id
J
JiabinYang 已提交
196
      w_grad->set_height(w.dims()[0]);
J
JiabinYang 已提交
197
      auto* w_grad_value = w_grad->mutable_value();
J
JiabinYang 已提交
198
      framework::DDim temp_dim(w.dims());
J
JiabinYang 已提交
199 200 201 202
      set(temp_dim, 0, real_rows.size());

      w_grad_value->mutable_data<T>(temp_dim, ctx.GetPlace());
      zero(dev_ctx, w_grad_value, static_cast<T>(0.0));
J
JiabinYang 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
      auto* bias_grad =
          ctx.Output<framework::SelectedRows>(framework::GradVarName("Bias"));
      if (bias_grad) {
        bias_grad->set_rows(real_rows);
        // build ids -> rows index map
        bias_grad->SyncIndex();
        bias_grad->set_height(bias->dims()[0]);
        auto* bias_grad_value = bias_grad->mutable_value();
        std::vector<int64_t> dims = {static_cast<int64_t>(real_rows.size()),
                                     bias->dims()[1]};
        bias_grad_value->mutable_data<T>(framework::make_ddim(dims),
                                         ctx.GetPlace());
        zero(dev_ctx, bias_grad_value, static_cast<T>(0.0));
        bit_code->AddGrad(pre_out_grad, bias_grad);
      }
J
JiabinYang 已提交
218
      bit_code->MulGradWeight(pre_out_grad, w_grad, in);
J
JiabinYang 已提交
219
    }
J
JiabinYang 已提交
220
    bit_code->MulGradError(pre_out_grad, w, in_grad);
Y
Yancey1989 已提交
221
  }
Y
Yancey1989 已提交
222 223 224 225
};

}  // namespace operators
}  // namespace paddle