dropout_op_mlu.cc 7.3 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 42 43 44 45 46
/* 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);

    if (!is_test) {
      // exec dropout op for training only.
      int seed_data = 0;
      if (seed_tensor) {
        if (platform::is_mlu_place(seed_tensor->place())) {
47 48 49 50 51
          memory::Copy(platform::CPUPlace(),
                       &seed_data,
                       seed_tensor->place(),
                       seed_tensor->data<int>(),
                       sizeof(int));
Q
qipengh 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64
        } 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);
65 66 67 68
        MLUCnnl::Fill(ctx,
                      CNNL_POINTER_MODE_HOST,
                      &value_t,
                      out_desc.get(),
Q
qipengh 已提交
69
                      GetBasePtr(out));
70 71 72 73
        MLUCnnl::Fill(ctx,
                      CNNL_POINTER_MODE_HOST,
                      &value_t,
                      mask_desc.get(),
Q
qipengh 已提交
74 75 76 77 78 79 80 81 82
                      GetBasePtr(mask));
        return;
      }

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

      const float prob = is_upscale ? dropout_prob : 0.0f;
83 84 85 86 87 88 89 90 91 92
      MLUCnnl::FusedDropout(ctx,
                            mlu_gen_random->get(),
                            x_desc.get(),
                            GetBasePtr(x),
                            prob,
                            GetBasePtr(&(mlu_gen_random->get_state())),
                            mask_desc.get(),
                            GetBasePtr(mask),
                            out_desc.get(),
                            GetBasePtr(out));
Q
qipengh 已提交
93 94 95 96
    } else {
      // exec dropout op for inference only.
      if (is_upscale) {
        framework::TensorCopy(
97 98 99 100
            *x,
            ctx.GetPlace(),
            ctx.template device_context<platform::MLUDeviceContext>(),
            out);
Q
qipengh 已提交
101
      } else {
102
        auto scale = static_cast<T>(1.0f - dropout_prob);
Q
qipengh 已提交
103 104 105
        Tensor scale_tensor(x->dtype());
        scale_tensor.mutable_data<T>({1}, ctx.GetPlace());
        MLUCnnlTensorDesc scale_desc(scale_tensor);
106 107 108 109
        MLUCnnl::Fill(ctx,
                      CNNL_POINTER_MODE_HOST,
                      &scale,
                      scale_desc.get(),
Q
qipengh 已提交
110 111 112
                      GetBasePtr(&scale_tensor));

        auto data_type = ToCnnlDataType<T>();
113 114 115 116 117 118 119 120 121 122 123
        MLUCnnlOpTensorDesc op_tensor_desc(
            CNNL_OP_TENSOR_MUL, data_type, CNNL_NOT_PROPAGATE_NAN);
        MLUCnnl::OpTensor(ctx,
                          op_tensor_desc.get(),
                          x_desc.get(),
                          GetBasePtr(x),
                          scale_desc.get(),
                          GetBasePtr(&scale_tensor),
                          out_desc.get(),
                          GetBasePtr(out),
                          data_type);
Q
qipengh 已提交
124 125 126 127 128 129 130 131 132
      }
    }
  }
};

template <typename T>
class DropoutGradMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
133 134
    PADDLE_ENFORCE_EQ(!ctx.Attr<bool>("is_test"),
                      true,
Q
qipengh 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147
                      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);
148 149 150 151
      MLUCnnl::Fill(ctx,
                    CNNL_POINTER_MODE_HOST,
                    &value_t,
                    grad_x_desc.get(),
Q
qipengh 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
                    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()));

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

    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);
179 180 181 182 183 184 185 186 187 188 189 190
    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 已提交
191 192 193 194 195 196 197 198 199
  }
};

}  // namespace operators
}  // namespace paddle

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

200 201
REGISTER_OP_MLU_KERNEL(dropout,
                       ops::DropoutMLUKernel<float>,
Q
qipengh 已提交
202 203
                       ops::DropoutMLUKernel<plat::float16>);

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