hierarchical_sigmoid_op.h 5.6 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 52 53
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    auto& device_ctx = ctx.template device_context<DeviceContext>();
    math::RowwiseSum<DeviceContext, T> row_sum;
    math::MatrixBitCodeFunctor<T> bit_code;

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

Y
Yancey1989 已提交
60
    if (bias) {
Y
Yancey1989 已提交
61
      bit_code.Add(num_classes, ids->data<int64_t>(), pre_out, *bias);
Y
Yancey1989 已提交
62
    }
Y
Yancey1989 已提交
63
    for (int i = 0; i < in->dims()[0]; ++i) {
Y
Yancey1989 已提交
64 65
      bit_code.Mul(num_classes, ids->data<int64_t>(), pre_out,
                   w->Slice(i, i + 1), in->Slice(i, i + 1));
Y
Yancey1989 已提交
66 67
    }
    // clip the matrix with (-40, 40)
Y
Yancey1989 已提交
68 69 70 71
    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 已提交
72 73
    bit_code.Sum(num_classes, ids->data<int64_t>(), pre_out, *out,
                 static_cast<T>(-1));
Y
Yancey1989 已提交
74
    // softrelu with threshold is 40.0
Y
Yancey1989 已提交
75 76 77
    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 已提交
78
    pre_out_mat.device(place) = (static_cast<T>(1.0) + pre_out_mat.exp()).log();
Y
Yancey1989 已提交
79 80

    row_sum(device_ctx, pre_out, &sum);
Y
Yancey1989 已提交
81
    out_mat.device(place) = sum_mat + out_mat;
Y
Yancey1989 已提交
82
  }
Y
Yancey1989 已提交
83 84
};

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

    framework::Tensor pre_out;
Y
Yancey1989 已提交
99 100 101 102
    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 已提交
103 104
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);
    // init pre_out matrix with {1.0}
Y
Yancey1989 已提交
105 106 107
    math::SetConstant<DeviceContext, T> one;
    math::MatrixBitCodeFunctor<T> bit_code;
    one(device_ctx, &pre_out, static_cast<T>(1.0));
Y
Yancey1989 已提交
108 109 110 111
    // 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 已提交
112
    bit_code.Sub(num_classes, ids->data<int64_t>(), pre_out);
Y
Yancey1989 已提交
113 114

    if (bias) {
Y
Yancey1989 已提交
115 116
      bias->mutable_data<T>(ctx.GetPlace());
      bit_code.AddGrad(num_classes, ids->data<int64_t>(), pre_out, *bias);
Y
Yancey1989 已提交
117
    }
Y
Yancey1989 已提交
118 119
    in_grad->mutable_data<T>(ctx.GetPlace());
    w->mutable_data<T>(ctx.GetPlace());
Y
Yancey1989 已提交
120
    for (int i = 0; i < in_grad->dims()[0]; ++i) {
Y
Yancey1989 已提交
121
      auto p_sliced = w->Slice(i, i + 1);
Y
Yancey1989 已提交
122 123
      auto in_sliced = in->Slice(i, i + 1);
      auto in_grad_sliced = in_grad->Slice(i, i + 1);
Y
Yancey1989 已提交
124 125 126 127
      bit_code.MulGradWeight(num_classes, ids->data<int64_t>(), pre_out,
                             p_sliced, in_sliced);
      bit_code.MulGradError(num_classes, ids->data<int64_t>(), pre_out,
                            p_sliced, in_grad_sliced);
Y
Yancey1989 已提交
128 129
    }
  }
Y
Yancey1989 已提交
130 131 132 133
};

}  // namespace operators
}  // namespace paddle