/* 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 #include #include #include "paddle/fluid/framework/mixed_vector.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/clip_op.h" #include "paddle/fluid/operators/detail/safe_ref.h" #include "paddle/fluid/operators/math/math_function.h" #include "paddle/fluid/operators/math/matrix_bit_code.h" #include "paddle/fluid/platform/transform.h" namespace paddle { namespace operators { template using EigenMatrix = framework::EigenMatrix; using platform::Transform; static std::vector PathToRows(const framework::LoDTensor& path) { std::set rows; for (int64_t i = 0; i < path.numel(); ++i) { int64_t row = path.data()[i]; if (row < 0) { continue; } rows.emplace(row); } return std::vector(rows.begin(), rows.end()); } template class HierarchicalSigmoidOpKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const override { auto& in = detail::Ref(ctx.Input("X")); auto& w = detail::Ref(ctx.Input("W")); auto* path = ctx.Input("PTable"); auto* code = ctx.Input("PathCode"); auto& label = detail::Ref(ctx.Input("Label")); auto* bias = ctx.Input("Bias"); auto* out = ctx.Output("Out"); auto* pre_out = ctx.Output("PreOut"); size_t num_classes = static_cast(ctx.Attr("num_classes")); bool is_custom = false; if (path) { is_custom = true; } int64_t code_length = path ? path->dims()[1] : math::FindLastSet(num_classes - 1); int64_t batch_size = in.dims()[0]; framework::LoDTensor sum; auto& dev_ctx = ctx.template device_context(); auto* pre_out_data = pre_out->mutable_data( framework::make_ddim({batch_size, code_length}), ctx.GetPlace()); auto pre_out_mat = EigenMatrix::From(*pre_out); // Not all class(leaf) nodes' path lengths equal code_length, thus init as // 0s can avoid out of path's loss. math::SetConstant zero; zero(dev_ctx, pre_out, static_cast(0.0)); auto& place = *ctx.template device_context().eigen_device(); math::RowwiseSum row_sum; std::unique_ptr> bit_code; if (!is_custom) { bit_code.reset(new math::MatrixBitCodeFunctor(num_classes, label.data())); } else { bit_code.reset(new math::MatrixBitCodeFunctor(*path, *code, label.data())); } std::vector sum_dims({batch_size, 1UL}); sum.mutable_data(framework::make_ddim(sum_dims), ctx.GetPlace()); auto sum_mat = EigenMatrix::From(sum); out->mutable_data(ctx.GetPlace()); auto out_mat = framework::EigenVector::Flatten(*out); if (bias) { bit_code->Add(*bias, pre_out); } bit_code->Mul(pre_out, w, in); // clip to [-40, 40] Transform trans; trans(ctx.template device_context(), pre_out_data, pre_out_data + pre_out->numel(), pre_out_data, ClipFunctor(static_cast(-40.0), static_cast(40.0))); bit_code->Sum(*pre_out, out, static_cast(-1)); // use softrelu to calculate cross entropy pre_out_mat.device(place) = (static_cast(1.0) + pre_out_mat.exp()).log(); row_sum(dev_ctx, *pre_out, &sum); // 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. out_mat.device(place) = sum_mat + out_mat; } }; template class HierarchicalSigmoidGradOpKernel : public framework::OpKernel { public: void Compute(const framework::ExecutionContext& ctx) const override { auto& in = detail::Ref(ctx.Input("X")); auto& w = detail::Ref(ctx.Input("W")); auto* path = ctx.Input("PTable"); auto* code = ctx.Input("PathCode"); auto* bias = ctx.Input("Bias"); auto* in_grad = ctx.Output(framework::GradVarName("X")); bool is_sparse = ctx.Attr("is_sparse"); auto& dev_ctx = ctx.template device_context(); math::SetConstant zero; auto& label = detail::Ref(ctx.Input("Label")); auto& pre_out = detail::Ref(ctx.Input("PreOut")); auto& out_grad = detail::Ref( ctx.Input(framework::GradVarName("Out"))); framework::LoDTensor pre_out_grad; pre_out_grad.mutable_data(pre_out.dims(), ctx.GetPlace()); in_grad->mutable_data(ctx.GetPlace()); zero(dev_ctx, in_grad, static_cast(0.0)); size_t num_classes = static_cast(ctx.Attr("num_classes")); bool is_custom = false; if (path) { is_custom = true; } std::unique_ptr> bit_code; if (!is_custom) { bit_code.reset(new math::MatrixBitCodeFunctor(num_classes, label.data())); } else { bit_code.reset(new math::MatrixBitCodeFunctor(*path, *code, label.data())); } // softrelu derivative auto blas = math::GetBlas(ctx); auto* pre_out_grad_data = pre_out_grad.data(); auto* pre_out_data = pre_out.data(); 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]; } bit_code->Sub(&pre_out_grad); // the gradient of clip(w * x + b) auto* out_grad_data = out_grad.data(); 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); } // TODO(guosheng): multiply pre_out_grad with subgradient of clipping to // be consistent with the clipping in forward. if (!is_sparse) { auto* bias_grad = ctx.Output(framework::GradVarName("Bias")); if (bias_grad) { bias_grad->mutable_data(ctx.GetPlace()); zero(dev_ctx, bias_grad, static_cast(0.0)); bit_code->AddGrad(pre_out_grad, bias_grad); } auto* w_grad = ctx.Output(framework::GradVarName("W")); w_grad->mutable_data(ctx.GetPlace()); zero(dev_ctx, w_grad, static_cast(0.0)); bit_code->MulGradWeight(pre_out_grad, w_grad, in); } else { framework::Vector real_rows = PathToRows(*path); auto* w_grad = ctx.Output(framework::GradVarName("W")); w_grad->set_rows(real_rows); // Build a map of id -> row_index to speed up finding the index of one id w_grad->set_height(w.dims()[0]); auto* w_grad_value = w_grad->mutable_value(); framework::DDim temp_dim(w.dims()); set(temp_dim, 0, real_rows.size()); w_grad_value->mutable_data(temp_dim, ctx.GetPlace()); zero(dev_ctx, w_grad_value, static_cast(0.0)); auto* bias_grad = ctx.Output(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 dims = {static_cast(real_rows.size()), bias->dims()[1]}; bias_grad_value->mutable_data(framework::make_ddim(dims), ctx.GetPlace()); zero(dev_ctx, bias_grad_value, static_cast(0.0)); bit_code->AddGrad(pre_out_grad, bias_grad); } bit_code->MulGradWeight(pre_out_grad, w_grad, in); } bit_code->MulGradError(pre_out_grad, w, in_grad); } }; } // namespace operators } // namespace paddle