gaussian_random_op.cu 1.9 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
  void Compute(const framework::ExecutionContext& context) const override {
    T mean = static_cast<T>(context.op_.GetAttr<T>("mean"));
    T std = static_cast<T>(context.op_.GetAttr<T>("std"));
    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) {
      seed = std::random_device()();
    }
    curandGenerator_t g;
    PADDLE_ENFORCE(platform::dynload::curandCreateGenerator(
        &g, CURAND_RNG_PSEUDO_DEFAULT));
    PADDLE_ENFORCE(
        platform::dynload::curandSetPseudoRandomGeneratorSeed(g, seed));
    // auto g = const_cast<platform::GPUDeviceContext*>(ctx)->RandGenerator();
    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 53
namespace ops = paddle::operators;
REGISTER_OP_GPU_KERNEL(gaussian_random, ops::GaussianRandomKernel<float>);