gaussian_random.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "ultra_infer/function/gaussian_random.h"
  15. #include <memory>
  16. #include <random>
  17. #include <utility>
  18. namespace ultra_infer {
  19. namespace function {
  20. template <typename T>
  21. void GaussianRandomKernel(const std::vector<int64_t> &shape, float mean,
  22. float std, int seed, FDTensor *out) {
  23. std::normal_distribution<T> dist(mean, std);
  24. out->Allocate(shape, TypeToDataType<T>::dtype);
  25. int64_t size = out->Numel();
  26. T *data = reinterpret_cast<T *>(out->Data());
  27. std::mt19937_64 engine;
  28. engine.seed(seed);
  29. for (int64_t i = 0; i < size; ++i) {
  30. data[i] = dist(engine);
  31. }
  32. }
  33. void GaussianRandom(const std::vector<int64_t> &shape, FDTensor *out,
  34. FDDataType dtype, float mean, float std, int seed) {
  35. FD_VISIT_FLOAT_TYPES(dtype, "GaussianRandomKernel", [&]() {
  36. GaussianRandomKernel<data_t>(shape, mean, std, seed, out);
  37. });
  38. }
  39. } // namespace function
  40. } // namespace ultra_infer