mean_op_mlu.cc 5.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

15
#include "paddle/fluid/framework/op_registry.h"
16 17 18 19 20 21 22
#include "paddle/fluid/operators/mlu/mlu_baseop.h"
#include "paddle/fluid/platform/device/mlu/device_context.h"
#include "paddle/fluid/platform/float16.h"

namespace paddle {
namespace operators {

23 24
using Tensor = framework::Tensor;

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
template <typename T>
class MeanMLUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto* input = context.Input<Tensor>("X");
    auto* output = context.Output<Tensor>("Out");

    const T* in_data = input->data<T>();
    T* out_data = output->mutable_data<T>(context.GetPlace());
    auto numel = input->numel();
    auto rank = input->dims().size();
    auto place = context.GetPlace();
    auto stream = context.template device_context<MLUDeviceContext>().stream();

    if (rank == 0) {  // scalar
F
fwenguang 已提交
40
      memory::Copy(place, out_data, place, in_data, numel * sizeof(T), stream);
41 42 43 44 45 46 47 48 49
      return;
    }

    std::vector<int> reduce_dims;
    reduce_dims.reserve(rank);
    for (decltype(rank) i = 0; i < rank; ++i) {
      reduce_dims.push_back(i);
    }

50 51 52 53
    MLUCnnlTensorDesc input_desc(*input, CNNL_LAYOUT_ARRAY,
                                 ToCnnlDataType(input->dtype()));
    MLUCnnlTensorDesc output_desc(*output, CNNL_LAYOUT_ARRAY,
                                  ToCnnlDataType(output->dtype()));
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

    MLUCnnlReduceDesc reduction_desc(
        reduce_dims, CNNL_REDUCE_AVG, ToCnnlDataType<T>(),
        CNNL_NOT_PROPAGATE_NAN, CNNL_REDUCE_NO_INDICES, CNNL_32BIT_INDICES);

    MLUCnnl::Reduce(context, true /*need_workspace*/, reduction_desc.get(),
                    nullptr, input_desc.get(),
                    reinterpret_cast<const void*>(in_data), 0 /*indices_size*/,
                    nullptr, nullptr, output_desc.get(),
                    reinterpret_cast<void*>(out_data));
  }
};

template <typename T>
class MeanMLUGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto output_grad = context.Input<Tensor>(framework::GradVarName("Out"));
    PADDLE_ENFORCE_EQ(output_grad->numel(), 1,
                      platform::errors::InvalidArgument(
                          "Mean Gradient Input Tensor len should be 1. But "
                          "received Out@Grad's elements num is %d.",
                          output_grad->numel()));
    auto input_grad = context.Output<Tensor>(framework::GradVarName("X"));
    input_grad->mutable_data<T>(context.GetPlace());

    auto in_data = output_grad->data<T>();
    auto numel = input_grad->numel();
    auto rank = input_grad->dims().size();
    auto out_data = input_grad->data<T>();
    auto place = context.GetPlace();
    auto stream = context.template device_context<MLUDeviceContext>().stream();

    if (rank == 0) {  // scalar
F
fwenguang 已提交
88
      memory::Copy(place, out_data, place, in_data, numel * sizeof(T), stream);
89 90 91 92
      return;
    }

    // means
93
    Tensor mean_var(output_grad->dtype());
94
    mean_var.mutable_data<T>(input_grad->dims(), context.GetPlace());
95 96
    MLUCnnlTensorDesc mean_var_desc(mean_var, CNNL_LAYOUT_ARRAY,
                                    ToCnnlDataType(mean_var.dtype()));
97 98 99 100
    auto value = static_cast<T>(1.0 / static_cast<float>(input_grad->numel()));
    MLUCnnl::Fill(context, value, mean_var_desc.get(), GetBasePtr(&mean_var));

    // means mul output_grad
101 102 103 104
    MLUCnnlTensorDesc in_desc(*output_grad, CNNL_LAYOUT_ARRAY,
                              ToCnnlDataType(output_grad->dtype()));
    MLUCnnlTensorDesc out_desc(*input_grad, CNNL_LAYOUT_ARRAY,
                               ToCnnlDataType(input_grad->dtype()));
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

    MLUCnnlOpTensorDesc op_tensor_desc(CNNL_OP_TENSOR_MUL, ToCnnlDataType<T>(),
                                       CNNL_NOT_PROPAGATE_NAN);

    MLUCnnl::OpTensor(context, op_tensor_desc.get(), in_desc.get(),
                      reinterpret_cast<const void*>(in_data),
                      mean_var_desc.get(), GetBasePtr(&mean_var),
                      out_desc.get(), reinterpret_cast<void*>(out_data),
                      ToCnnlDataType<T>());
  }
};
}  // namespace operators
}  // namespace paddle

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

REGISTER_OP_MLU_KERNEL(mean, ops::MeanMLUKernel<float>,
                       ops::MeanMLUKernel<plat::float16>);
REGISTER_OP_MLU_KERNEL(mean_grad, ops::MeanMLUGradKernel<float>,
                       ops::MeanMLUGradKernel<plat::float16>);