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.
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}:
3 Likes
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 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 ).
Best and thanks again,
Ferran
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: Mimic Base exports · Issue #224 · JuliaGPU/CuArrays.jl · GitHub
1 Like