hierarchical_sigmoid_op.h 5.4 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 17 18 19 20 21 22
#include <iostream>
#include <vector>
#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"
Y
Yancey1989 已提交
23 24 25
namespace paddle {
namespace operators {

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

Y
Yancey1989 已提交
31
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
32 33
class HierarchicalSigmoidOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
34
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
35
    auto* in = ctx.Input<framework::Tensor>("X");
Y
Yancey1989 已提交
36 37
    auto* w = ctx.Input<framework::Tensor>("W");
    auto* ids = ctx.Input<framework::Tensor>("Ids");
Y
Yancey1989 已提交
38
    auto* bias = ctx.Input<framework::Tensor>("Bias");
Y
Yancey1989 已提交
39
    auto* out = ctx.Output<framework::Tensor>("Out");
W
weixing02 已提交
40
    auto* pre_out = ctx.Output<framework::Tensor>("PreOut");
Y
Yancey1989 已提交
41
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
Y
Yancey1989 已提交
42 43 44
    int64_t code_length = math::FindLastSet(num_classes - 1);
    int64_t batch_size = in->dims()[0];
    framework::Tensor sum;
W
weixing02 已提交
45 46 47
    math::SetConstant<DeviceContext, T> zero;
    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    auto pre_out_data = pre_out->mutable_data<T>(
Y
Yancey1989 已提交
48
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
W
weixing02 已提交
49 50
    auto pre_out_mat = EigenMatrix<T>::From(*pre_out);
    zero(dev_ctx, pre_out, static_cast<T>(0.0));
Y
Yancey1989 已提交
51 52
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
    math::RowwiseSum<DeviceContext, T> row_sum;
Y
Yancey1989 已提交
53
    math::MatrixBitCodeFunctor<T> bit_code(num_classes, ids->data<int64_t>());
Y
Yancey1989 已提交
54

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

Y
Yancey1989 已提交
80
template <typename DeviceContext, typename T>
Y
Yancey1989 已提交
81 82
class HierarchicalSigmoidGradOpKernel : public framework::OpKernel<T> {
 public:
Y
Yancey1989 已提交
83
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yancey1989 已提交
84
    auto* in = ctx.Input<framework::Tensor>("X");
W
weixing02 已提交
85
    auto* w = ctx.Input<framework::Tensor>("W");
Y
Yancey1989 已提交
86
    auto* in_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
W
weixing02 已提交
87 88 89
    auto* w_grad = ctx.Output<framework::Tensor>(framework::GradVarName("W"));
    auto* bias_grad =
        ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
Y
Yancey1989 已提交
90
    auto* ids = ctx.Input<framework::Tensor>("Ids");
W
weixing02 已提交
91 92 93 94
    auto* pre_out = ctx.Input<framework::Tensor>("PreOut");
    auto* out_grad =
        ctx.Input<framework::Tensor>(framework::GradVarName("Out"));

Y
Yancey1989 已提交
95
    size_t num_classes = static_cast<size_t>(ctx.Attr<int>("num_classes"));
Y
Yancey1989 已提交
96 97
    int64_t code_length = math::FindLastSet(num_classes - 1);
    int64_t batch_size = in->dims()[0];
W
weixing02 已提交
98 99 100
    framework::Tensor pre_out_grad;
    pre_out_grad.mutable_data<T>(
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
Y
Yancey1989 已提交
101
    auto& place = *ctx.template device_context<DeviceContext>().eigen_device();
W
weixing02 已提交
102 103
    auto pre_out_mat = EigenMatrix<T>::From(*pre_out);
    auto pre_out_grad_mat = EigenMatrix<T>::From(pre_out_grad);
Y
Yancey1989 已提交
104
    math::MatrixBitCodeFunctor<T> bit_code(num_classes, ids->data<int64_t>());
Y
Yancey1989 已提交
105
    // softrelu derivative
W
weixing02 已提交
106 107 108 109 110 111 112 113
    bit_code.OutGrad(&pre_out_grad, *out_grad);
    pre_out_grad_mat.device(place) =
        pre_out_grad_mat *
        (static_cast<T>(1.0) - static_cast<T>(1.0) / pre_out_mat.exp());
    bit_code.Sub(&pre_out_grad);
    if (bias_grad) {
      bias_grad->mutable_data<T>(ctx.GetPlace());
      bit_code.AddGrad(pre_out_grad, bias_grad);
Y
Yancey1989 已提交
114
    }
Y
Yancey1989 已提交
115
    in_grad->mutable_data<T>(ctx.GetPlace());
W
weixing02 已提交
116 117 118
    w_grad->mutable_data<T>(ctx.GetPlace());
    bit_code.MulGradWeight(pre_out_grad, w_grad, *in);
    bit_code.MulGradError(pre_out_grad, *w, in_grad);
Y
Yancey1989 已提交
119
  }
Y
Yancey1989 已提交
120 121 122 123
};

}  // namespace operators
}  // namespace paddle