Random numbers in CUDA

#1

Hi again,
just in an attempt to build a very simple Monte Carlo calculation that uses the GPU, I need to generate random numbers. What is the current best way to get a bunch of random numbers with the GPU? I tried things like

rand(CuArray,Float32,10)

but got funny results

MethodError: no method matching rand(::Type{CuArray}, ::Type{Float32}, ::Int64)
Closest candidates are:
  rand(!Matched::Random.AbstractRNG, ::Type{X}, ::Integer, !Matched::Integer...) where X at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Random/src/Random.jl:257
  rand(!Matched::Random.AbstractRNG, ::Any, ::Integer, !Matched::Integer...) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Random/src/Random.jl:248
  rand(::Type{X}, !Matched::Integer, ::Integer...) where X at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Random/src/Random.jl:258
  ...

Stacktrace:
 [1] top-level scope at In[18]:1

Thx,

Ferran.

#2

Why did you expect that to work? Doesn’t work with Base.Array either:

julia> using Random

julia> rand(Array, Float32, 10)
ERROR: MethodError: no method matching rand(::Type{Array}, ::Type{Float32}, ::Int64)

Either you can use the specific curand function (awaiting a constructor-based syntax):

julia> using CuArrays.CURAND

julia> curand(Float32, 10)
10-element CuArray{Float32,1}:

Or you can use the more idiomatic rand!:

julia> using Random

julia> a = CuArray{Float32}(undef, 10);

julia> rand!(a)
10-element CuArray{Float32,1}:
2 Likes
#3

Sorry, I expected that to work simply because it took it from elsewhere in the internet. But I also tried the

curand(Float32, 10)

version first (which actually seems the most obvious one), but failed :confused: Now I see that I was missing the

using CuArrays.CURAND

statement, while I explicitly had

using CuArrays

in my script. I somehow understood that, by issuing the latter, the former was implicitly loaded… but I was wrong.
I’m sorry to bother with all these basic questions, I just wanted to avoid all that when I asked about documentation in a previous post (and please do not misunderstand me, I mean no complain :slight_smile: ).

Best and thanks again,

Ferran

#4

It used to be that way with GPUArrays, but it’s an API that non of the other array types support so we got rid of it. I asked about it because some of the docstrings might still mention the old syntax.

We should fix that, since rand is always available: https://github.com/JuliaGPU/CuArrays.jl/issues/224