1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5 //
6 // This Source Code Form is subject to the terms of the Mozilla
7 // Public License v. 2.0. If a copy of the MPL was not distributed
8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
10 #define EIGEN_TEST_NO_LONGDOUBLE
11 #define EIGEN_TEST_NO_COMPLEX
12 #define EIGEN_TEST_FUNC cxx11_tensor_random_cuda
13 #define EIGEN_DEFAULT_DENSE_INDEX_TYPE int
14 #define EIGEN_USE_GPU
15
16 #include "main.h"
17 #include <Eigen/CXX11/Tensor>
18
19
test_cuda_random_uniform()20 void test_cuda_random_uniform()
21 {
22 Tensor<float, 2> out(72,97);
23 out.setZero();
24
25 std::size_t out_bytes = out.size() * sizeof(float);
26
27 float* d_out;
28 cudaMalloc((void**)(&d_out), out_bytes);
29
30 Eigen::CudaStreamDevice stream;
31 Eigen::GpuDevice gpu_device(&stream);
32
33 Eigen::TensorMap<Eigen::Tensor<float, 2> > gpu_out(d_out, 72,97);
34
35 gpu_out.device(gpu_device) = gpu_out.random();
36
37 assert(cudaMemcpyAsync(out.data(), d_out, out_bytes, cudaMemcpyDeviceToHost, gpu_device.stream()) == cudaSuccess);
38 assert(cudaStreamSynchronize(gpu_device.stream()) == cudaSuccess);
39
40 // For now we just check thes code doesn't crash.
41 // TODO: come up with a valid test of randomness
42 }
43
44
test_cuda_random_normal()45 void test_cuda_random_normal()
46 {
47 Tensor<float, 2> out(72,97);
48 out.setZero();
49
50 std::size_t out_bytes = out.size() * sizeof(float);
51
52 float* d_out;
53 cudaMalloc((void**)(&d_out), out_bytes);
54
55 Eigen::CudaStreamDevice stream;
56 Eigen::GpuDevice gpu_device(&stream);
57
58 Eigen::TensorMap<Eigen::Tensor<float, 2> > gpu_out(d_out, 72,97);
59
60 Eigen::internal::NormalRandomGenerator<float> gen(true);
61 gpu_out.device(gpu_device) = gpu_out.random(gen);
62
63 assert(cudaMemcpyAsync(out.data(), d_out, out_bytes, cudaMemcpyDeviceToHost, gpu_device.stream()) == cudaSuccess);
64 assert(cudaStreamSynchronize(gpu_device.stream()) == cudaSuccess);
65 }
66
test_complex()67 static void test_complex()
68 {
69 Tensor<std::complex<float>, 1> vec(6);
70 vec.setRandom();
71
72 // Fixme: we should check that the generated numbers follow a uniform
73 // distribution instead.
74 for (int i = 1; i < 6; ++i) {
75 VERIFY_IS_NOT_EQUAL(vec(i), vec(i-1));
76 }
77 }
78
79
test_cxx11_tensor_random_cuda()80 void test_cxx11_tensor_random_cuda()
81 {
82 CALL_SUBTEST(test_cuda_random_uniform());
83 CALL_SUBTEST(test_cuda_random_normal());
84 CALL_SUBTEST(test_complex());
85 }
86