dropout_op_xpu.cc 6.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
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. */
H
hong 已提交
11

12 13
#include <memory>
#include <string>
H
hong 已提交
14
#include "paddle/fluid/framework/op_registry.h"
15
#include "paddle/fluid/platform/device/device_wrapper.h"
16 17 18 19
namespace paddle {
namespace operators {

#ifdef PADDLE_WITH_XPU
20

H
hong 已提交
21
using Tensor = framework::Tensor;
22 23
template <typename DeviceContext, typename T>
class DropoutXPUKernel : public framework::OpKernel<T> {
24 25
  using XPUTyp = typename XPUTypeTrait<T>::Type;

26 27 28 29 30 31 32 33 34
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* x = context.Input<Tensor>("X");
    auto* y = context.Output<Tensor>("Out");
    const auto* x_data = x->data<T>();
    auto* y_data = y->mutable_data<T>(context.GetPlace());
    float dropout_prob = context.Attr<float>("dropout_prob");
    auto dropout_implementation =
        context.Attr<std::string>("dropout_implementation");
35 36
    auto& dev_ctx = context.template device_context<DeviceContext>();

37 38 39
    auto* seed =
        context.HasInput("Seed") ? context.Input<Tensor>("Seed") : nullptr;

40 41
    int is_upscale = (dropout_implementation == "upscale_in_train");

42
    if (!context.Attr<bool>("is_test")) {
43 44
      int seed_data = 0;
      if (seed) {
45 46 47 48 49 50 51
        if (platform::is_xpu_place(seed->place())) {
          memory::Copy(platform::CPUPlace(), &seed_data, seed->place(),
                       seed->data<int>(), sizeof(int));
        } else {
          seed_data = *(seed->data<int>());
        }

52
      } else {
53 54
        seed_data =
            context.Attr<bool>("fix_seed") ? context.Attr<int>("seed") : 0;
55
      }
56

57 58
      auto* mask = context.Output<Tensor>("Mask");
      auto* mask_data = mask->mutable_data<T>(context.GetPlace());
59 60 61 62 63
      // Special case when dropout_prob is 1.0
      if (dropout_prob == 1.0f) {
        int r = xpu::constant(dev_ctx.x_context(),
                              reinterpret_cast<XPUTyp*>(y_data), y->numel(),
                              XPUTyp(0));
64
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "constant");
65 66 67
        r = xpu::constant(dev_ctx.x_context(),
                          reinterpret_cast<XPUTyp*>(mask_data), mask->numel(),
                          XPUTyp(0));
68
        PADDLE_ENFORCE_XDNN_SUCCESS(r, "constant");
69
        return;
70
      }
71 72 73
      int r = xpu::dropout(dev_ctx.x_context(),
                           reinterpret_cast<const XPUTyp*>(x->data<T>()),
                           reinterpret_cast<XPUTyp*>(y->data<T>()),
74
                           reinterpret_cast<XPUTyp*>(mask_data), seed_data,
75
                           mask->numel(), is_upscale, dropout_prob);
76
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "dropout");
77 78 79 80 81 82
    } else {
      float scale =
          (is_upscale) ? (1.0) : (static_cast<float>(1.0f - dropout_prob));
      int r = xpu::scale(
          dev_ctx.x_context(), reinterpret_cast<const XPUTyp*>(x_data),
          reinterpret_cast<XPUTyp*>(y_data), x->numel(), false, scale, 0.0f);
83
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "scale");
84 85 86 87 88
    }
  }
};
template <typename DeviceContext, typename T>
class DropoutGradXPUKernel : public framework::OpKernel<T> {
89
  using XPUType = typename XPUTypeTrait<T>::Type;
90

91 92
 public:
  void Compute(const framework::ExecutionContext& context) const override {
X
xiaoting 已提交
93 94 95
    PADDLE_ENFORCE_EQ(!context.Attr<bool>("is_test"), true,
                      platform::errors::InvalidArgument(
                          "GradOp is only callable when is_test is false"));
96 97 98 99 100
    auto* grad_x = context.Output<Tensor>(framework::GradVarName("X"));
    auto* grad_y = context.Input<Tensor>(framework::GradVarName("Out"));
    auto* mask = context.Input<Tensor>("Mask");
    grad_x->mutable_data<T>(context.GetPlace());
    auto& dev_ctx = context.template device_context<DeviceContext>();
101 102 103 104
    auto& dropout_implementation =
        context.Attr<std::string>("dropout_implementation");
    float dropout_prob = context.Attr<float>("dropout_prob");
    const T* mask_data = mask->data<T>();
105 106 107 108 109 110 111

    if (dropout_implementation != "upscale_in_train") {
      int r = xpu::mul(dev_ctx.x_context(),
                       reinterpret_cast<const XPUType*>(grad_y->data<T>()),
                       reinterpret_cast<const XPUType*>(mask_data),
                       reinterpret_cast<XPUType*>(grad_x->data<T>()),
                       grad_y->numel());
112
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "mul");
113 114 115
      return;
    }

116
    auto version = platform::get_xpu_version(context.GetPlace().GetDeviceId());
117
    if (version == phi::backends::xpu::XPUVersion::XPU1) {
118 119
      xpu::ctx_guard RAII_GUARD(dev_ctx.x_context());
      XPUType* mask_new = RAII_GUARD.alloc_l3_or_gm<XPUType>(mask->numel());
120 121 122
      float scale =
          (dropout_prob == 1.0f) ? (1.0f) : (1.0f / (1.0f - dropout_prob));
      int r = xpu::scale(dev_ctx.x_context(),
123 124 125
                         reinterpret_cast<const XPUType*>(mask->data<T>()),
                         reinterpret_cast<XPUType*>(mask_new), mask->numel(),
                         false, scale, 0.0f);
126
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "scale");
127 128 129 130 131
      r = xpu::mul(dev_ctx.x_context(),
                   reinterpret_cast<const XPUType*>(grad_y->data<T>()),
                   reinterpret_cast<const XPUType*>(mask_new),
                   reinterpret_cast<XPUType*>(grad_x->data<T>()),
                   grad_y->numel());
132
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "mul");
133 134 135 136 137 138 139
    } else {
      int r =
          xpu::dropout_grad(dev_ctx.x_context(),
                            reinterpret_cast<const XPUType*>(mask->data<T>()),
                            reinterpret_cast<const XPUType*>(grad_y->data<T>()),
                            reinterpret_cast<XPUType*>(grad_x->data<T>()),
                            dropout_prob, grad_y->numel());
140
      PADDLE_ENFORCE_XDNN_SUCCESS(r, "dropout_grad");
141
    }
142 143 144 145 146
  }
};
}  // namespace operators
}  // namespace paddle
namespace ops = paddle::operators;
147
namespace plat = paddle::platform;
148
REGISTER_OP_XPU_KERNEL(
149 150
    dropout, ops::DropoutXPUKernel<paddle::platform::XPUDeviceContext, float>,
    ops::DropoutXPUKernel<paddle::platform::XPUDeviceContext, plat::float16>);
151 152
REGISTER_OP_XPU_KERNEL(
    dropout_grad,
153 154 155
    ops::DropoutGradXPUKernel<paddle::platform::XPUDeviceContext, float>,
    ops::DropoutGradXPUKernel<paddle::platform::XPUDeviceContext,
                              plat::float16>);
156
#endif