gaussian_random_op.cu 1.8 KB
Newer Older
D
dongzhihong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   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 16 17 18 19
#include <memory>
#include <random>
#include "paddle/platform/dynload/curand.h"
#include "paddle/platform/gpu_info.h"

D
dongzhihong 已提交
20 21
#include "paddle/framework/op_registry.h"

D
dongzhihong 已提交
22 23
namespace paddle {
namespace operators {
D
dongzhihong 已提交
24 25

template <typename T>
26
class GaussianRandomKernel : public framework::OpKernel {
D
dongzhihong 已提交
27
 public:
28
  void Compute(const framework::ExecutionContext& context) const override {
D
dongzhihong 已提交
29 30
    float mean = context.op_.GetAttr<float>("mean");
    float std = context.op_.GetAttr<float>("std");
31 32 33 34 35
    auto* tensor = context.Output<framework::Tensor>(0);
    T* data = tensor->mutable_data<T>(context.GetPlace());

    int seed = context.op_.GetAttr<int>("seed");
    if (seed == 0) {
36 37
      std::random_device rd;
      seed = rd();
38 39 40 41 42 43
    }
    curandGenerator_t g;
    PADDLE_ENFORCE(platform::dynload::curandCreateGenerator(
        &g, CURAND_RNG_PSEUDO_DEFAULT));
    PADDLE_ENFORCE(
        platform::dynload::curandSetPseudoRandomGeneratorSeed(g, seed));
Y
Yu Yang 已提交
44 45
    platform::dynload::curandGenerateNormal(
        g, data, framework::product(tensor->dims()), mean, std);
D
dongzhihong 已提交
46 47
  }
};
D
dongzhihong 已提交
48

D
dongzhihong 已提交
49 50 51
}  // namespace operators
}  // namespace paddle

52
namespace ops = paddle::operators;
53
REGISTER_OP_GPU_KERNEL(gaussian_random, ops::GaussianRandomKernel<float>);