Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GPUArrays out-of-place random methods #325

Merged
merged 1 commit into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/random.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
using Random

Random.rand!(A::oneWrappedArray) = Random.rand!(GPUArrays.default_rng(oneArray), A)
Random.randn!(A::oneWrappedArray) = Random.randn!(GPUArrays.default_rng(oneArray), A)
gpuarrays_rng() = GPUArrays.default_rng(oneArray)

# GPUArrays in-place
Random.rand!(A::oneWrappedArray) = Random.rand!(gpuarrays_rng(), A)
Random.randn!(A::oneWrappedArray) = Random.randn!(gpuarrays_rng(), A)

# GPUArrays out-of-place
rand(T::Type, dims::Dims) = Random.rand!(oneArray{T}(undef, dims...))
randn(T::Type, dims::Dims; kwargs...) = Random.randn!(oneArray{T}(undef, dims...); kwargs...)

# support all dimension specifications
rand(T::Type, dim1::Integer, dims::Integer...) = Random.rand!(oneArray{T}(undef, dim1, dims...))
randn(T::Type, dim1::Integer, dims::Integer...; kwargs...) = Random.randn!(oneArray{T}(undef, dim1, dims...); kwargs...)

# untyped out-of-place
rand(dim1::Integer, dims::Integer...) = Random.rand!(oneArray{Float32}(undef, dim1, dims...))
randn(dim1::Integer, dims::Integer...; kwargs...) = Random.randn!(oneArray{Float32}(undef, dim1, dims...); kwargs...)

# seeding
seed!(seed=Base.rand(UInt64)) = Random.seed!(gpuarrays_rng(), seed)
39 changes: 39 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Random

@testset "rand" begin

# in-place
for (f,T) in ((rand!,Float16),
(rand!,Float32),
(randn!,Float16),
(randn!,Float32)),
d in (2, (2,2), (2,2,2), 3, (3,3), (3,3,3))
A = oneArray{T}(undef, d)
fill!(A, T(0))
f(A)
@test !iszero(collect(A))
end

# out-of-place, with implicit type
for (f,T) in ((oneAPI.rand,Float32), (oneAPI.randn,Float32)),
args in ((2,), (2, 2), (3,), (3, 3))
A = f(args...)
@test eltype(A) == T
end

# out-of-place, with type specified
for (f,T) in ((oneAPI.rand,Float32), (oneAPI.randn,Float32),
(rand,Float32), (randn,Float32)),
args in ((T, 2), (T, 2, 2), (T, (2, 2)), (T, 3), (T, 3, 3), (T, (3, 3)))
A = f(args...)
@test eltype(A) == T
end

## seeding
oneAPI.seed!(1)
a = oneAPI.rand(Int32, 1)
oneAPI.seed!(1)
b = oneAPI.rand(Int32, 1)
@test iszero(collect(a) - collect(b))

end # testset