hierarchical_sigmoid_op.h 5.3 KB
Newer Older
Y
Yancey1989 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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
#include "paddle/framework/op_registry.h"
Y
Yancey1989 已提交
17
#include "paddle/operators/clip_op.h"
Y
Yancey1989 已提交
18
#include "paddle/operators/math/math_function.h"
Y
Yancey1989 已提交
19
#include "paddle/operators/math/matrix_bit_code.h"
Y
Yancey1989 已提交
20
#include "paddle/platform/transform.h"
Y
Yancey1989 已提交
21 22 23 24

namespace paddle {
namespace operators {

Y
Yancey1989 已提交
25 26 27
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
Y
Yancey1989 已提交
28
using platform::Transform;
Y
Yancey1989 已提交
29

Y
Yancey1989 已提交
30
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
31 32
class HierarchicalSigmoidOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
33
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
34
    auto* in = ctx.Input<framework::Tensor>("X");
Y
Yancey1989 已提交
35 36
    auto* w = ctx.Input<framework::Tensor>("W");
    auto* ids = ctx.Input<framework::Tensor>("Ids");
Y
Yancey1989 已提交
37
    auto* bias = ctx.Input<framework::Tensor>("Bias");
Y
Yancey1989 已提交
38
    auto* out = ctx.Output<framework::Tensor>("Out");
Y
Yancey1989 已提交
39
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
Y
Yancey1989 已提交
40

Y
Yancey1989 已提交
41 42
    int64_t code_length = math::FindLastSet(num_classes - 1);
    int64_t batch_size = in->dims()[0];
Y
Yancey1989 已提交
43
    framework::Tensor pre_out;
Y
Yancey1989 已提交
44 45 46
    framework::Tensor sum;
    auto pre_out_data = pre_out.mutable_data<T>(
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
Y
Yancey1989 已提交
47 48
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);

Y
Yancey1989 已提交
49 50 51
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto& device_ctx = ctx.template device_context<DeviceContext>();
    math::RowwiseSum<DeviceContext, T> row_sum;
Y
Yancey1989 已提交
52
    math::MatrixBitCodeFunctor<T> bit_code(num_classes, ids->data<int64_t>());
Y
Yancey1989 已提交
53

Y
Yancey1989 已提交
54 55
    std::vector<int64_t> sum_dims({batch_size, 1UL});
    sum.mutable_data<T>(framework::make_ddim(sum_dims), ctx.GetPlace());
Y
Yancey1989 已提交
56
    auto sum_mat = EigenMatrix<T>::From(sum);
Y
Yancey1989 已提交
57
    out->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
58
    auto out_mat = framework::EigenVector<T>::Flatten(*out);
Y
Yancey1989 已提交
59
    if (bias) {
Y
Yancey1989 已提交
60
      bit_code.Add(pre_out, *bias);
Y
Yancey1989 已提交
61
    }
Y
Yancey1989 已提交
62 63 64
    for (int64_t i = 0; i < batch_size; ++i) {
      auto w_i = w->Slice(i, i + 1);
      bit_code.Mul(pre_out, w_i, *in);
Y
Yancey1989 已提交
65 66
    }
    // clip the matrix with (-40, 40)
Y
Yancey1989 已提交
67 68 69 70
    Transform<DeviceContext> trans;
    trans(ctx.template device_context<DeviceContext>(), pre_out_data,
          pre_out_data + pre_out.numel(), pre_out_data,
          ClipFunctor<T>(static_cast<T>(-40.0), static_cast<T>(40.0)));
Y
Yancey1989 已提交
71
    bit_code.Sum(pre_out, *out, static_cast<T>(-1));
Y
Yancey1989 已提交
72
    // softrelu with threshold is 40.0
Y
Yancey1989 已提交
73 74 75
    trans(ctx.template device_context<DeviceContext>(), pre_out_data,
          pre_out_data + pre_out.numel(), pre_out_data,
          ClipFunctor<T>(static_cast<T>(-40.0), static_cast<T>(40.0)));
Y
Yancey1989 已提交
76
    pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
Y
Yancey1989 已提交
77
    row_sum(device_ctx, pre_out, &sum);
Y
Yancey1989 已提交
78
    out_mat.device(place) = sum_mat + out_mat;
Y
Yancey1989 已提交
79
  }
Y
Yancey1989 已提交
80 81
};

Y
Yancey1989 已提交
82
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
83 84
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
85
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
86 87
    auto* in = ctx.Input<framework::Tensor>("X");
    auto* in_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
Y
Yancey1989 已提交
88
    auto* w = ctx.Output<framework::Tensor>(framework::GradVarName("W"));
Y
Yancey1989 已提交
89
    auto* bias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
Y
Yancey1989 已提交
90
    auto* ids = ctx.Input<framework::Tensor>("Ids");
Y
Yancey1989 已提交
91
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
Y
Yancey1989 已提交
92 93
    int64_t code_length = math::FindLastSet(num_classes - 1);
    int64_t batch_size = in->dims()[0];
Y
Yancey1989 已提交
94 95

    framework::Tensor pre_out;
Y
Yancey1989 已提交
96 97 98 99
    pre_out.mutable_data<T>(framework::make_ddim({batch_size, code_length}),
                            ctx.GetPlace());
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto& device_ctx = ctx.template device_context<DeviceContext>();
Y
Yancey1989 已提交
100 101
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);
    // init pre_out matrix with {1.0}
Y
Yancey1989 已提交
102
    math::SetConstant<DeviceContext, T> one;
Y
Yancey1989 已提交
103
    math::MatrixBitCodeFunctor<T> bit_code(num_classes, ids->data<int64_t>());
Y
Yancey1989 已提交
104
    one(device_ctx, &pre_out, static_cast<T>(1.0));
Y
Yancey1989 已提交
105 106 107 108
    // softrelu derivative
    pre_out_mat.device(place) =
        pre_out_mat * (static_cast<T>(1.0) - static_cast<T>(1.0) / pre_out_mat);

Y
Yancey1989 已提交
109
    bit_code.Sub(pre_out);
Y
Yancey1989 已提交
110 111

    if (bias) {
Y
Yancey1989 已提交
112
      bias->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
113
      bit_code.AddGrad(pre_out, *bias);
Y
Yancey1989 已提交
114
    }
Y
Yancey1989 已提交
115 116
    in_grad->mutable_data<T>(ctx.GetPlace());
    w->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
117 118 119 120 121 122
    for (int i = 0; i < batch_size; ++i) {
      auto w_i = w->Slice(i, i + 1);
      // auto in_i = in->Slice(i, i + 1);
      // auto in_grad_i = in_grad->Slice(i, i + 1);
      bit_code.MulGradWeight(pre_out, w_i, *in);
      bit_code.MulGradError(pre_out, w_i, *in_grad);
Y
Yancey1989 已提交
123 124
    }
  }
Y
Yancey1989 已提交
125 126 127 128
};

}  // namespace operators
}  // namespace paddle