dropout_op_mlu.cc 7.4 KB
Newer Older
Q
qipengh 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/* Copyright (c) 2022 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. */

#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/mlu/mlu_baseop.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename T>
class DropoutMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<Tensor>("X");
    auto* out = ctx.Output<Tensor>("Out");
    auto dropout_prob = ctx.Attr<float>("dropout_prob");
    auto is_test = ctx.Attr<bool>("is_test");
    auto* seed_tensor =
        ctx.HasInput("Seed") ? ctx.Input<Tensor>("Seed") : nullptr;
    auto dropout_implementation =
        ctx.Attr<std::string>("dropout_implementation");

    const bool is_upscale = (dropout_implementation == "upscale_in_train");

    out->mutable_data<T>(ctx.GetPlace());
    MLUCnnlTensorDesc x_desc(*x);
    MLUCnnlTensorDesc out_desc(*out);

42 43 44 45 46 47 48 49 50 51 52
    if (is_test && is_upscale) {
      // dropout op for inference: out = input.
      framework::TensorCopy(
          *x,
          ctx.GetPlace(),
          ctx.template device_context<platform::MLUDeviceContext>(),
          out);
      return;
    } else if (!is_test) {
      // dropout op for training: out = input * mask / ( 1.0 - dropout_prob ) or
      // out = input * mask.
Q
qipengh 已提交
53 54 55
      int seed_data = 0;
      if (seed_tensor) {
        if (platform::is_mlu_place(seed_tensor->place())) {
56 57 58 59 60
          memory::Copy(platform::CPUPlace(),
                       &seed_data,
                       seed_tensor->place(),
                       seed_tensor->data<int>(),
                       sizeof(int));
Q
qipengh 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73
        } else {
          seed_data = *(seed_tensor->data<int>());
        }
      } else {
        seed_data = ctx.Attr<bool>("fix_seed") ? ctx.Attr<int>("seed") : 0;
      }

      auto* mask = ctx.Output<Tensor>("Mask");
      mask->mutable_data<uint8_t>(ctx.GetPlace());
      MLUCnnlTensorDesc mask_desc(*mask);
      // Special case when dropout_prob is 1.0
      if (dropout_prob == 1.0f) {
        auto value_t = static_cast<T>(0.0f);
74 75 76 77
        MLUCnnl::Fill(ctx,
                      CNNL_POINTER_MODE_HOST,
                      &value_t,
                      out_desc.get(),
Q
qipengh 已提交
78
                      GetBasePtr(out));
79 80 81 82
        MLUCnnl::Fill(ctx,
                      CNNL_POINTER_MODE_HOST,
                      &value_t,
                      mask_desc.get(),
Q
qipengh 已提交
83 84 85 86 87 88 89 90
                      GetBasePtr(mask));
        return;
      }

      // create mlu random generator
      const int device_id = ctx.GetPlace().GetDeviceId();
      auto mlu_gen_random = GetMLURandomGenerator(ctx, device_id, seed_data);

91
      // compute out = input * mask / ( 1.0 - dropout_prob )
92 93 94 95
      MLUCnnl::FusedDropout(ctx,
                            mlu_gen_random->get(),
                            x_desc.get(),
                            GetBasePtr(x),
96
                            dropout_prob,
97 98 99 100 101
                            GetBasePtr(&(mlu_gen_random->get_state())),
                            mask_desc.get(),
                            GetBasePtr(mask),
                            out_desc.get(),
                            GetBasePtr(out));
102

Q
qipengh 已提交
103
      if (is_upscale) {
104
        return;
Q
qipengh 已提交
105 106
      }
    }
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

    // In downgrade_in_infer mode, need to multiply (1.0f - dropout_prob).
    Tensor scale_tensor(x->dtype());
    Tensor bias_tensor(x->dtype());
    scale_tensor.mutable_data<T>({1}, ctx.GetPlace());
    bias_tensor.mutable_data<T>({1}, ctx.GetPlace());
    MLUCnnlTensorDesc scale_desc(scale_tensor);
    MLUCnnlTensorDesc bias_desc(bias_tensor);
    FillMLUTensorWithHostValue(
        ctx, static_cast<T>(1.0f - dropout_prob), &scale_tensor);
    FillMLUTensorWithHostValue(ctx, static_cast<T>(0.0f), &bias_tensor);

    MLUCnnl::Scale(ctx,
                   0,
                   is_test ? x_desc.get() : out_desc.get(),
                   is_test ? GetBasePtr(x) : GetBasePtr(out),
                   scale_desc.get(),
                   GetBasePtr(&scale_tensor),
                   bias_desc.get(),
                   GetBasePtr(&bias_tensor),
                   out_desc.get(),
                   GetBasePtr(out));
Q
qipengh 已提交
129 130 131 132 133 134 135
  }
};

template <typename T>
class DropoutGradMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
136 137
    PADDLE_ENFORCE_EQ(!ctx.Attr<bool>("is_test"),
                      true,
Q
qipengh 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150
                      platform::errors::InvalidArgument(
                          "GradOp is only callable when is_test is false"));
    auto* grad_x = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* grad_out = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* mask = ctx.Input<Tensor>("Mask");
    auto dropout_prob = ctx.Attr<float>("dropout_prob");
    auto dropout_impl = ctx.Attr<std::string>("dropout_implementation");

    grad_x->mutable_data<T>(ctx.GetPlace());
    MLUCnnlTensorDesc grad_x_desc(*grad_x);

    if (dropout_prob == 1.) {
      auto value_t = static_cast<T>(0.0f);
151 152 153 154
      MLUCnnl::Fill(ctx,
                    CNNL_POINTER_MODE_HOST,
                    &value_t,
                    grad_x_desc.get(),
Q
qipengh 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
                    GetBasePtr(grad_x));
      return;
    }

    // cast mask from uint8 to float32/float16
    Tensor cast_mask(grad_x->dtype());
    cast_mask.Resize(mask->dims());
    cast_mask.mutable_data<T>(ctx.GetPlace());

    MLUCnnlTensorDesc mask_desc(*mask);
    MLUCnnlTensorDesc cast_mask_desc(cast_mask);
    cnnlCastDataType_t cast_type =
        GetCastDataType(framework::TransToProtoVarType(mask->dtype()),
                        framework::TransToProtoVarType(cast_mask.dtype()));

170 171 172 173 174 175
    MLUCnnl::Cast(ctx,
                  cast_type,
                  mask_desc.get(),
                  GetBasePtr(mask),
                  cast_mask_desc.get(),
                  GetBasePtr(&cast_mask));
Q
qipengh 已提交
176 177 178 179 180 181

    const bool is_upscale = (dropout_impl == "upscale_in_train");
    const float scale = is_upscale ? (1.0f / (1.0f - dropout_prob)) : (1.0f);

    auto data_type = ToCnnlDataType<T>();
    MLUCnnlTensorDesc grad_out_desc(*grad_out);
182 183 184 185 186 187 188 189 190 191 192 193
    MLUCnnlOpTensorDesc op_tensor_desc(
        CNNL_OP_TENSOR_MUL, data_type, CNNL_NOT_PROPAGATE_NAN);
    MLUCnnl::OpTensor(ctx,
                      op_tensor_desc.get(),
                      cast_mask_desc.get(),
                      GetBasePtr(&cast_mask),
                      grad_out_desc.get(),
                      GetBasePtr(grad_out),
                      grad_x_desc.get(),
                      GetBasePtr(grad_x),
                      data_type,
                      scale);
Q
qipengh 已提交
194 195 196 197 198 199 200 201 202
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

203 204
REGISTER_OP_MLU_KERNEL(dropout,
                       ops::DropoutMLUKernel<float>,
Q
qipengh 已提交
205 206
                       ops::DropoutMLUKernel<plat::float16>);

207 208
REGISTER_OP_MLU_KERNEL(dropout_grad,
                       ops::DropoutGradMLUKernel<float>,
Q
qipengh 已提交
209
                       ops::DropoutGradMLUKernel<plat::float16>);