truncated_gaussian_random_op_npu.cc 4.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2021 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 <memory>
#include <string>
17

18
#include "paddle/fluid/framework/convert_utils.h"
19
#include "paddle/fluid/operators/truncated_gaussian_random_op.h"
20
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
21 22 23 24 25 26 27 28 29 30 31 32

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename DeviceContext, typename T>
class TruncatedGaussianRandomNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    // TODO(zhiqiu): support dynamic shape and call ParameterizedTruncatedNormal
    std::vector<int> shape = ctx.Attr<std::vector<int>>("shape");
33
    Tensor shape_tensor(experimental::DataType::INT32);
34 35
    shape_tensor.mutable_data<int32_t>({static_cast<int>(shape.size())},
                                       ctx.GetPlace());
36 37
    paddle::framework::TensorFromVector(
        shape, ctx.device_context(), &shape_tensor);
38
    float mean = ctx.Attr<float>("mean");
39
    Tensor mean_tensor(experimental::DataType::FLOAT32);
40
    mean_tensor.mutable_data<float>({1}, ctx.GetPlace());
41
    FillNpuTensorWithConstant<float>(&mean_tensor, mean);
42 43

    float std = ctx.Attr<float>("std");
44
    Tensor std_tensor(experimental::DataType::FLOAT32);
45
    std_tensor.mutable_data<float>({1}, ctx.GetPlace());
46
    FillNpuTensorWithConstant<float>(&std_tensor, std);
47 48 49

    int32_t seed_var = ctx.Attr<int32_t>("seed");

50
    Tensor min_tensor(experimental::DataType::FLOAT32);
51 52
    min_tensor.mutable_data<float>({1}, ctx.GetPlace());
    float min_value = mean - std * 2.0;
53
    FillNpuTensorWithConstant<float>(&min_tensor, min_value);
54

55
    Tensor max_tensor(experimental::DataType::FLOAT32);
56 57
    max_tensor.mutable_data<float>({1}, ctx.GetPlace());
    float max_value = mean + std * 2.0;
58
    FillNpuTensorWithConstant<float>(&max_tensor, max_value);
59 60 61 62 63 64

    auto* out = ctx.Output<framework::Tensor>("Out");
    out->mutable_data<T>(ctx.GetPlace());
    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
L
Leo Chen 已提交
65
    const auto& runner = NpuOpRunner(
66
        "ParameterizedTruncatedNormal",
67 68
        {shape_tensor, mean_tensor, std_tensor, min_tensor, max_tensor},
        {*out},
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
        {{"seed", seed_var}});
    runner.Run(stream);
  }
};

// NOTE(zhiqiu): actually, this is cpu version kernel, and we need to make the
// above
// npu version work in the future.
template <typename T>
class NPUTruncatedGaussianRandomKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    float mean = context.Attr<float>("mean");
    float std = context.Attr<float>("std");
    auto* tensor = context.Output<framework::Tensor>("Out");
    tensor->mutable_data<T>(context.GetPlace());

86
    Tensor cpu_tensor(tensor->dtype());
87 88
    cpu_tensor.Resize(tensor->dims());
    T* cpu_data = cpu_tensor.mutable_data<T>(platform::CPUPlace());
89 90
    std::uniform_real_distribution<T> dist(std::numeric_limits<float>::min(),
                                           1.0);
91 92 93 94 95 96 97 98 99
    TruncatedNormal<T> truncated_normal(mean, std);
    int64_t size = tensor->numel();

    unsigned int seed = static_cast<unsigned int>(context.Attr<int>("seed"));
    auto engine = framework::GetCPURandomEngine(seed);
    for (int64_t i = 0; i < size; ++i) {
      cpu_data[i] = truncated_normal(dist(*engine));
    }
    framework::TensorCopy(
100 101 102 103
        cpu_tensor,
        context.GetPlace(),
        context.template device_context<platform::DeviceContext>(),
        tensor);
104 105 106 107 108 109 110 111 112 113 114 115
    context.template device_context<paddle::platform::NPUDeviceContext>()
        .Wait();
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_NPU_KERNEL(truncated_gaussian_random,
                       ops::NPUTruncatedGaussianRandomKernel<float>);