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 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
    auto* params = ctx.Input<framework::Tensor>("Parameters");
Y
Yancey1989 已提交
36 37
    auto* label = ctx.Input<framework::Tensor>("Label");
    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 43
    int64_t code_length = math::FindLastSet(num_classes - 1);
    int64_t batch_size = in->dims()[0];
    auto* ids = label->data<int64_t>();
Y
Yancey1989 已提交
44
    framework::Tensor pre_out;
Y
Yancey1989 已提交
45 46 47
    framework::Tensor sum;
    auto pre_out_data = pre_out.mutable_data<T>(
        framework::make_ddim({batch_size, code_length}), ctx.GetPlace());
Y
Yancey1989 已提交
48 49
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);

Y
Yancey1989 已提交
50 51 52 53 54
    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 已提交
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

Y
Yancey1989 已提交
61
    if (bias) {
Y
Yancey1989 已提交
62
      bit_code.Add(num_classes, ids, pre_out, *bias);
Y
Yancey1989 已提交
63
    }
Y
Yancey1989 已提交
64 65 66
    for (int i = 0; i < in->dims()[0]; ++i) {
      bit_code.Mul(num_classes, ids, pre_out, params->Slice(i, i + 1),
                   in->Slice(i, i + 1));
Y
Yancey1989 已提交
67 68
    }
    // clip the matrix with (-40, 40)
Y
Yancey1989 已提交
69 70 71 72 73
    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)));
    bit_code.Sum(num_classes, ids, 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 91 92
    auto* in = ctx.Input<framework::Tensor>("X");
    auto* in_grad = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    auto* params =
        ctx.Output<framework::Tensor>(framework::GradVarName("Parameters"));
Y
Yancey1989 已提交
93
    auto* bias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
Y
Yancey1989 已提交
94
    auto* label = ctx.Input<framework::Tensor>("Label");
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];
Y
Yancey1989 已提交
98 99

    framework::Tensor pre_out;
Y
Yancey1989 已提交
100 101 102 103
    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 已提交
104
    auto pre_out_mat = EigenMatrix<T>::From(pre_out);
Y
Yancey1989 已提交
105
    auto* ids = label->data<int64_t>();
Y
Yancey1989 已提交
106 107

    // init pre_out matrix with {1.0}
Y
Yancey1989 已提交
108 109 110
    math::SetConstant<DeviceContext, T> one;
    math::MatrixBitCodeFunctor<T> bit_code;
    one(device_ctx, &pre_out, static_cast<T>(1.0));
Y
Yancey1989 已提交
111 112 113 114
    // 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 已提交
115
    bit_code.Sub(num_classes, ids, pre_out);
Y
Yancey1989 已提交
116 117

    if (bias) {
Y
Yancey1989 已提交
118
      bit_code.AddGrad(num_classes, ids, pre_out, *bias);
Y
Yancey1989 已提交
119 120
    }

Y
Yancey1989 已提交
121 122 123 124 125 126 127
    for (int i = 0; i < in_grad->dims()[0]; ++i) {
      auto p_sliced = params->Slice(i, i + 1);
      auto in_sliced = in->Slice(i, i + 1);
      auto in_grad_sliced = in_grad->Slice(i, i + 1);
      bit_code.MulGradWeight(num_classes, ids, pre_out, p_sliced, in_sliced);
      bit_code.MulGradError(num_classes, ids, pre_out, p_sliced,
                            in_grad_sliced);
Y
Yancey1989 已提交
128 129
    }
  }
Y
Yancey1989 已提交
130 131 132 133
};

}  // namespace operators
}  // namespace paddle