From 20eea2c9ab6d9f994d1a57cf167344570365f4fc Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 16 Mar 2026 01:06:06 +0000 Subject: [PATCH 01/20] on-device rand! with three options for stateless counter-based RNG --- prototype/rand/Project.toml | 6 ++ prototype/rand/test_rand.jl | 74 +++++++++++++++++++ src/AcceleratedKernels.jl | 1 + src/rand/philox.jl | 37 ++++++++++ src/rand/rand.jl | 137 ++++++++++++++++++++++++++++++++++++ src/rand/splitmix64.jl | 26 +++++++ src/rand/threefry.jl | 49 +++++++++++++ src/rand/utilities.jl | 36 ++++++++++ test/rand.jl | 132 ++++++++++++++++++++++++++++++++++ test/runtests.jl | 1 + 10 files changed, 499 insertions(+) create mode 100644 prototype/rand/Project.toml create mode 100644 prototype/rand/test_rand.jl create mode 100644 src/rand/philox.jl create mode 100644 src/rand/rand.jl create mode 100644 src/rand/splitmix64.jl create mode 100644 src/rand/threefry.jl create mode 100644 src/rand/utilities.jl create mode 100644 test/rand.jl diff --git a/prototype/rand/Project.toml b/prototype/rand/Project.toml new file mode 100644 index 00000000..7e92c899 --- /dev/null +++ b/prototype/rand/Project.toml @@ -0,0 +1,6 @@ +[deps] +AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" +BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" +CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +PProf = "e4faabce-9ead-11e9-39d9-4379958e3056" +Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/prototype/rand/test_rand.jl b/prototype/rand/test_rand.jl new file mode 100644 index 00000000..329214dc --- /dev/null +++ b/prototype/rand/test_rand.jl @@ -0,0 +1,74 @@ +using BenchmarkTools +using CUDA + +import AcceleratedKernels as AK + + +const N = 100_000_000 +const GPU_BLOCK_SIZE = 256 + +const RNG_SPLITMIX = AK.CounterRNG(0x12345678; alg=AK.SplitMix64()) +const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox()) +const RNG_THREEFRY = AK.CounterRNG(0x12345678; alg=AK.Threefry()) + +x_cuda = CuArray{Float32}(undef, N) +x_splitmix = CuArray{Float32}(undef, N) +x_philox = CuArray{Float32}(undef, N) +x_threefry = CuArray{Float32}(undef, N) +x_cpu = Vector{Float32}(undef, N) + + +function run_cuda_rand!(x) + CUDA.rand!(x) + CUDA.synchronize() + return x +end + + +function run_ak_rand_gpu!(rng, x) + AK.rand!(rng, x; block_size=GPU_BLOCK_SIZE) + AK.synchronize(AK.get_backend(x)) + return x +end + + +function run_ak_rand_cpu!(rng, x) + AK.rand!(rng, x) + return x +end + + +# Julia base rand() gives [0, 1) and so does EVERYTHING ELSE EVER! but CuRAND gives (0, 1] ... +is_unit_interval(v) = all(x -> 0.0f0 <= x <= 1.0f0, v) + +# warmup compile +run_cuda_rand!(x_cuda) +run_ak_rand_gpu!(RNG_SPLITMIX, x_splitmix) +run_ak_rand_gpu!(RNG_PHILOX, x_philox) +run_ak_rand_gpu!(RNG_THREEFRY, x_threefry) +run_ak_rand_cpu!(RNG_SPLITMIX, x_cpu) + +@assert is_unit_interval(Array(x_cuda)) +@assert is_unit_interval(Array(x_splitmix)) +@assert is_unit_interval(Array(x_philox)) +@assert is_unit_interval(Array(x_threefry)) +@assert is_unit_interval(x_cpu) + +println("N = ", N) +println("CPU threads: ", Threads.nthreads()) + +println("\nCUDA.rand! benchmark (CuArray{Float32}, in-place)") +display(@benchmark run_cuda_rand!($x_cuda)) + +println("\nAK.rand! SplitMix64 benchmark (GPU, CuArray{Float32})") +display(@benchmark run_ak_rand_gpu!($RNG_SPLITMIX, $x_splitmix)) + +println("\nAK.rand! Philox benchmark (GPU, CuArray{Float32})") +display(@benchmark run_ak_rand_gpu!($RNG_PHILOX, $x_philox)) + +println("\nAK.rand! Threefry benchmark (GPU, CuArray{Float32})") +display(@benchmark run_ak_rand_gpu!($RNG_THREEFRY, $x_threefry)) + +println("\nAK.rand! benchmark (CPU, Vector{Float32}, SplitMix64)") +display(@benchmark run_ak_rand_cpu!($RNG_SPLITMIX, $x_cpu)) + diff --git a/src/AcceleratedKernels.jl b/src/AcceleratedKernels.jl index d662c2a5..06a401ae 100644 --- a/src/AcceleratedKernels.jl +++ b/src/AcceleratedKernels.jl @@ -31,6 +31,7 @@ include("map.jl") include("sort/sort.jl") include("reduce/reduce.jl") include("accumulate/accumulate.jl") +include("rand/rand.jl") include("searchsorted.jl") include("predicates.jl") include("arithmetics.jl") diff --git a/src/rand/philox.jl b/src/rand/philox.jl new file mode 100644 index 00000000..2b32d95e --- /dev/null +++ b/src/rand/philox.jl @@ -0,0 +1,37 @@ +struct Philox <: CounterRNGAlgorithm end + + +# Philox magic numbers +const PHILOX_M0 = UInt32(0xD256D193) +const PHILOX_W0 = UInt32(0x9E3779B9) +const PHILOX_ROUNDS = 10 + + +# Each round destroys x0 with multiplication, addition, and XORs +@inline function _philox2x32_round(x0::UInt32, x1::UInt32, k0::UInt32) + lo = PHILOX_M0 * x0 + hi = _mulhi_u32(PHILOX_M0, x0) + y0 = xor(xor(hi, k0), x1) + y1 = lo + return y0, y1 +end + + +""" + rand_uint32(rng::CounterRNG{<:Unsigned, Philox}, counter::UInt64) -> UInt32 +""" +@inline function rand_uint32(rng::CounterRNG{<:Unsigned, Philox}, counter::UInt64)::UInt32 + x0 = _u32_lo(counter) + x1 = _u32_hi(counter) + + seed = UInt64(rng.seed) + k0 = _u32_lo(seed) + x1 = xor(x1, _u32_hi(seed)) + + @inbounds for _ in 1:PHILOX_ROUNDS + x0, x1 = _philox2x32_round(x0, x1, k0) + k0 += PHILOX_W0 + end + + return x0 +end diff --git a/src/rand/rand.jl b/src/rand/rand.jl new file mode 100644 index 00000000..07952e1d --- /dev/null +++ b/src/rand/rand.jl @@ -0,0 +1,137 @@ +""" + abstract type AbstractCounterRNG end + abstract type CounterRNGAlgorithm end + +RNG interface for counter-based random generation with AcceleratedKernels. +""" + +abstract type AbstractCounterRNG end +abstract type CounterRNGAlgorithm end + + +""" + CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=SplitMix64()) + +Stateless counter-based RNG configuration for [`rand!`](@ref). + +`CounterRNG` is immutable and does not hold mutable thread-local or global state. Each generated +value is a pure function of: +- `seed` +- logical linear element index +- algorithm (`alg`) + +The default algorithm is `Philox()`. +""" +struct CounterRNG{K <: Unsigned, A <: CounterRNGAlgorithm} <: AbstractCounterRNG + seed::K + alg::A +end + + +function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) + @argcheck seed >= 0 + CounterRNG(UInt64(seed), alg) +end + + + + +# Shared helpers +include("utilities.jl") + +# Algorithm-specific integer generators +include("splitmix64.jl") +include("philox.jl") +include("threefry.jl") + + + + + +function _rand_fill_threads!( + rng::AbstractCounterRNG, + x::AbstractArray{Float32}; + max_tasks::Int, + min_elems::Int, +) + task_partition(length(x), max_tasks, min_elems) do irange + @inbounds for i in irange + counter = _counter_from_index(i) + x[i] = uint32_to_unit_float32(rand_uint32(rng, counter)) + end + end + return x +end + + +@kernel inbounds=true cpu=false unsafe_indices=true function _rand_fill_kernel!( + rng, + x, +) + i = @index(Global, Linear) + if i <= length(x) + counter = _counter_from_index(i) + x[i] = uint32_to_unit_float32(rand_uint32(rng, counter)) + end +end + + +function _rand_fill_gpu!( + rng::AbstractCounterRNG, + x::AbstractArray{Float32}, + backend::Backend; + block_size::Int, +) + @argcheck block_size > 0 + len = length(x) + len == 0 && return x + + blocks = div(len, block_size, RoundUp) + kernel! = _rand_fill_kernel!(backend, block_size) + kernel!(rng, x, ndrange=(blocks * block_size,)) + return x +end + + +""" + rand!( + rng::AbstractCounterRNG, + x::AbstractArray{Float32}, + backend::Backend=get_backend(x); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + + # Implementation choice + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, + ) + +Fill `x` in-place with pseudo-random `Float32` values in `[0, 1)` using a stateless counter-based +RNG. For `x[i]`, the counter is exactly `UInt64(i - 1)` in linear indexing order. + +The float conversion is mantissa-based: uniform over the produced mantissa grid, not over all +representable `Float32` values in `[0, 1)`. +""" +function rand!( + rng::AbstractCounterRNG, + x::AbstractArray{Float32}, + backend::Backend=get_backend(x); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) + if use_gpu_algorithm(backend, prefer_threads) + _rand_fill_gpu!(rng, x, backend; block_size) + else + _rand_fill_threads!(rng, x; max_tasks, min_elems) + end +end diff --git a/src/rand/splitmix64.jl b/src/rand/splitmix64.jl new file mode 100644 index 00000000..165f72f6 --- /dev/null +++ b/src/rand/splitmix64.jl @@ -0,0 +1,26 @@ +struct SplitMix64 <: CounterRNGAlgorithm end + +# SplitMix64 magic numbers +const SPLITMIX64_INCREMENT = UInt64(0x9e3779b97f4a7c15) +const SPLITMIX64_MIX_A = UInt64(0xbf58476d1ce4e5b9) +const SPLITMIX64_MIX_B = UInt64(0x94d049bb133111eb) + + +@inline function _splitmix64_mix(x::UInt64)::UInt64 + x = xor(x, x >> 30) + x *= SPLITMIX64_MIX_A + x = xor(x, x >> 27) + x *= SPLITMIX64_MIX_B + x = xor(x, x >> 31) + return x +end + + +""" + rand_uint32(rng::CounterRNG{<:Unsigned, SplitMix64}, counter::UInt64) -> UInt32 +""" +@inline function rand_uint32(rng::CounterRNG{<:Unsigned, SplitMix64}, counter::UInt64)::UInt32 + seed = UInt64(rng.seed) + mixed = _splitmix64_mix(counter + seed + SPLITMIX64_INCREMENT) + return UInt32(mixed >> 32) +end diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl new file mode 100644 index 00000000..0a65dc36 --- /dev/null +++ b/src/rand/threefry.jl @@ -0,0 +1,49 @@ +struct Threefry <: CounterRNGAlgorithm end + +# Threefry magic numbers +const THREEFRY_PARITY = UInt32(0x1BD11BDA) +const THREEFRY_ROTATIONS = ( + UInt32(13), UInt32(15), UInt32(26), UInt32(6), + UInt32(17), UInt32(29), UInt32(16), UInt32(24), +) +const THREEFRY_ROUNDS = 20 + + +@inline function _threefry_key_word(k0::UInt32, k1::UInt32, k2::UInt32, idx::Int)::UInt32 + idx == 0 && return k0 + idx == 1 && return k1 + return k2 +end + + +""" + rand_uint32(rng::CounterRNG{<:Unsigned, Threefry}, counter::UInt64) -> UInt32 +""" +@inline function rand_uint32(rng::CounterRNG{<:Unsigned, Threefry}, counter::UInt64)::UInt32 + x0 = _u32_lo(counter) + x1 = _u32_hi(counter) + + seed = UInt64(rng.seed) + k0 = _u32_lo(seed) + k1 = _u32_hi(seed) + k2 = xor(THREEFRY_PARITY, xor(k0, k1)) + + x0 += k0 + x1 += k1 + + @inbounds for round in 0:(THREEFRY_ROUNDS - 1) + rot = THREEFRY_ROTATIONS[(round & 0x7) + 1] + x0 += x1 + x1 = xor(_rotl32(x1, rot), x0) + + if (round & 0x3) == 3 + s = (round >>> 2) + 1 + i0 = s % 3 + i1 = (s + 1) % 3 + x0 += _threefry_key_word(k0, k1, k2, i0) + x1 += _threefry_key_word(k0, k1, k2, i1) + UInt32(s) + end + end + + return x0 +end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl new file mode 100644 index 00000000..35b72f0d --- /dev/null +++ b/src/rand/utilities.jl @@ -0,0 +1,36 @@ +# lo: rightmost 32 bits, hi: leftmost 32 bits +@inline _u32_lo(x::UInt64)::UInt32 = UInt32(x & UInt64(0xffffffff)) +@inline _u32_hi(x::UInt64)::UInt32 = UInt32(x >> 32) + +# leftmost 32 bits of a*b cast to UInt64s +@inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) + + +@inline function _rotl32(x::UInt32, r::UInt32)::UInt32 + return (x << r) | (x >> (UInt32(32) - r)) +end + + +@inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) + + +@inline function rand_uint32(::AbstractCounterRNG, ::UInt64)::UInt32 + # Unrecognised AbstractCounterRNG + throw(ArgumentError("No rand_uint32 implementation for this RNG type")) +end + + + +""" + uint32_to_unit_float32(u::UInt32) -> Float32 + +Convert a random `UInt32` to `Float32` in `[0, 1)` by mantissa construction. +""" +@inline function uint32_to_unit_float32(u::UInt32)::Float32 + # Keep 23 random bits for the mantissa (drop 9 rightmost bits from the UInt32) + # and combine with the bit pattern of 1.0f0 (sign=0, exponent=127). + bits = UInt32(0x3f800000) | (u >> 9) + + # Interpret as 1.mantissa, then subtract 1 for [0, 1) + return reinterpret(Float32, bits) - 1.0f0 +end diff --git a/test/rand.jl b/test/rand.jl new file mode 100644 index 00000000..7fefdff1 --- /dev/null +++ b/test/rand.jl @@ -0,0 +1,132 @@ +function _is_unit_interval(v) + for x in v + if isnan(x) || x < 0.0f0 || x >= 1.0f0 + return false + end + end + return true +end + +function _rand_fill_reference!(rng, x::AbstractArray{Float32}) + @inbounds for i in eachindex(x) + counter = UInt64(i - one(i)) + x[i] = AK.uint32_to_unit_float32(AK.rand_uint32(rng, counter)) + end + return x +end + +@testset "rand" begin + @test AK.CounterRNG{AK.SplitMix64}(0x1) isa AK.CounterRNG{AK.SplitMix64, UInt64} + @test AK.CounterRNG{AK.Philox}(UInt32(0x1)) isa AK.CounterRNG{AK.Philox, UInt32} + @test AK.CounterRNG{AK.Threefry, UInt16}(123) isa AK.CounterRNG{AK.Threefry, UInt16} + @test_throws ArgumentError AK.CounterRNG{AK.SplitMix64, UInt8}(300) + + rng_algs = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) + + for alg in rng_algs + rng_alg = AK.CounterRNG(0x123456789abcdef; alg) + @test AK.rand_uint32(rng_alg, UInt64(0)) == AK.rand_uint32(rng_alg, UInt64(0)) + @test AK.rand_uint32(rng_alg, UInt64(1)) != AK.rand_uint32(rng_alg, UInt64(0)) + + vals_alg = [AK.rand_uint32(rng_alg, UInt64(i)) for i in 0:1023] + @test length(unique(vals_alg)) == length(vals_alg) + + x_alg = array_from_host(zeros(Float32, 2048)) + AK.rand!(rng_alg, x_alg; prefer_threads, block_size=64) + @test _is_unit_interval(Array(x_alg)) + end + + rng = AK.CounterRNG(0x123456789abcdef) + + @test AK.rand_uint32(rng, UInt64(0)) == AK.rand_uint32(rng, UInt64(0)) + @test AK.rand_uint32(rng, UInt64(1)) != AK.rand_uint32(rng, UInt64(0)) + @test AK.rand_uint32(rng, UInt64(17)) != AK.rand_uint32(rng, UInt64(18)) + + vals = [AK.rand_uint32(rng, UInt64(i)) for i in 0:2047] + @test length(unique(vals)) == length(vals) + + for u in ( + UInt32(0x00000000), + UInt32(0x00000001), + UInt32(0x7fffffff), + UInt32(0x80000000), + UInt32(0xffffffff), + ) + x = AK.uint32_to_unit_float32(u) + @test !isnan(x) + @test 0.0f0 <= x < 1.0f0 + end + + lengths = (0, 1, 31, 32, 33, 1024, 1025) + for len in lengths + x = array_from_host(zeros(Float32, len)) + AK.rand!(rng, x; prefer_threads, block_size=64) + xh = Array(x) + + ref = zeros(Float32, len) + _rand_fill_reference!(rng, ref) + + @test xh == ref + @test _is_unit_interval(xh) + end + + x1 = array_from_host(zeros(Float32, 4096)) + x2 = array_from_host(zeros(Float32, 4096)) + AK.rand!(rng, x1; prefer_threads, block_size=64) + AK.rand!(rng, x2; prefer_threads, block_size=257) + @test Array(x1) == Array(x2) + + rng2 = AK.CounterRNG(rng.seed + UInt64(1)) + x3 = array_from_host(zeros(Float32, 4096)) + AK.rand!(rng2, x3; prefer_threads, block_size=64) + @test Array(x3) != Array(x1) + + xnd = array_from_host(zeros(Float32, 7, 11, 5)) + AK.rand!(rng, xnd; prefer_threads, block_size=128) + xndh = Array(xnd) + refnd = zeros(Float32, 7, 11, 5) + _rand_fill_reference!(rng, refnd) + @test xndh == refnd + + if IS_CPU_BACKEND + base = zeros(Float32, 64) + view_x = @view base[2:2:end] + AK.rand!( + rng, + view_x; + max_tasks=Threads.nthreads(), + min_elems=1, + prefer_threads=true, + ) + + ref_view = zeros(Float32, length(view_x)) + _rand_fill_reference!(rng, ref_view) + @test collect(view_x) == ref_view + end + + nstats = 200_000 + xstats = array_from_host(zeros(Float32, nstats)) + AK.rand!(rng, xstats; prefer_threads, block_size=256) + xh = Array(xstats) + + @test _is_unit_interval(xh) + + m = sum(xh) / nstats + v = sum((x - m)^2 for x in xh) / nstats + @test abs(m - 0.5) < 0.01 + @test abs(v - (1 / 12)) < 0.01 + + nbins = 16 + counts = zeros(Int, nbins) + for x in xh + ibin = Int(floor(x * nbins)) + 1 + ibin = min(ibin, nbins) + counts[ibin] += 1 + end + expected = nstats / nbins + max_rel_dev = maximum(abs(c - expected) / expected for c in counts) + @test max_rel_dev < 0.1 + + x64 = array_from_host(zeros(Float64, 16)) + @test_throws MethodError AK.rand!(rng, x64; prefer_threads) +end diff --git a/test/runtests.jl b/test/runtests.jl index 716fd8e0..a2707b6b 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -69,6 +69,7 @@ end include("partition.jl") include("looping.jl") include("map.jl") +include("rand.jl") include("sort.jl") include("reduce.jl") include("accumulate.jl") From 3c3e81a6ca8f48ccd2b8d93180b50af9691c1b74 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 16 Mar 2026 16:51:00 +0000 Subject: [PATCH 02/20] add convenience for AK.rand!(X), and single UInt64 seed construction for fresh fills with simple calls. determinism obviously remains if an rng is passed --- src/rand/philox.jl | 33 ++++++- src/rand/rand.jl | 89 ++++++++++++++---- src/rand/splitmix64.jl | 23 ++++- src/rand/threefry.jl | 33 ++++++- src/rand/utilities.jl | 63 ++++++++++++- test/rand.jl | 204 +++++++++++++++++++++++++++++------------ 6 files changed, 357 insertions(+), 88 deletions(-) diff --git a/src/rand/philox.jl b/src/rand/philox.jl index 2b32d95e..8137f645 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -18,9 +18,12 @@ end """ - rand_uint32(rng::CounterRNG{<:Unsigned, Philox}, counter::UInt64) -> UInt32 + _philox2x32_block(rng::CounterRNG{<:Philox}, counter::UInt64) """ -@inline function rand_uint32(rng::CounterRNG{<:Unsigned, Philox}, counter::UInt64)::UInt32 +@inline function _philox2x32_block( + rng::CounterRNG{<:Philox}, + counter::UInt64, +)::Tuple{UInt32, UInt32} x0 = _u32_lo(counter) x1 = _u32_hi(counter) @@ -33,5 +36,31 @@ end k0 += PHILOX_W0 end + return x0, x1 +end + + +""" + rand_uint(rng::CounterRNG{<:Philox}, counter::UInt64, UInt32) -> UInt32 +""" +@inline function rand_uint( + rng::CounterRNG{<:Philox}, + counter::UInt64, + ::Type{UInt32}, +)::UInt32 + x0, _ = _philox2x32_block(rng, counter) return x0 end + + +""" + rand_uint(rng::CounterRNG{<:Philox}, counter::UInt64, UInt64) -> UInt64 +""" +@inline function rand_uint( + rng::CounterRNG{<:Philox}, + counter::UInt64, + ::Type{UInt64}, +)::UInt64 + x0, x1 = _philox2x32_block(rng, counter) + return _u64_from_u32(x0, x1) +end diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 07952e1d..0e294520 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -10,7 +10,7 @@ abstract type CounterRNGAlgorithm end """ - CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=SplitMix64()) + CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) Stateless counter-based RNG configuration for [`rand!`](@ref). @@ -21,13 +21,20 @@ value is a pure function of: - algorithm (`alg`) The default algorithm is `Philox()`. + +`seed` may be any non-negative `Integer`. It is normalised to `UInt64` internally. """ -struct CounterRNG{K <: Unsigned, A <: CounterRNGAlgorithm} <: AbstractCounterRNG - seed::K +struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG + seed::UInt64 alg::A end +function CounterRNG(seed::Unsigned; alg::CounterRNGAlgorithm=Philox()) + CounterRNG(UInt64(seed), alg) +end + + function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) @argcheck seed >= 0 CounterRNG(UInt64(seed), alg) @@ -35,6 +42,20 @@ end +""" + CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64()) + +Create a stateless counter-based RNG with an automatically generated seed. + +The seed is sampled exactly once at construction using `rand(UInt64)`. Reusing this same +`CounterRNG` instance is deterministic for fixed seed, algorithm, array shape, and eltype. +""" +function CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64()) + CounterRNG(Base.rand(UInt64); alg) +end + + + # Shared helpers include("utilities.jl") @@ -50,14 +71,14 @@ include("threefry.jl") function _rand_fill_threads!( rng::AbstractCounterRNG, - x::AbstractArray{Float32}; + x::AbstractArray{T}; max_tasks::Int, min_elems::Int, -) +) where {T <: ALLOWED_RAND_SCALARS} task_partition(length(x), max_tasks, min_elems) do irange @inbounds for i in irange counter = _counter_from_index(i) - x[i] = uint32_to_unit_float32(rand_uint32(rng, counter)) + x[i] = rand_scalar(rng, counter, T) end end return x @@ -71,17 +92,17 @@ end i = @index(Global, Linear) if i <= length(x) counter = _counter_from_index(i) - x[i] = uint32_to_unit_float32(rand_uint32(rng, counter)) + x[i] = rand_scalar(rng, counter, eltype(x)) end end function _rand_fill_gpu!( rng::AbstractCounterRNG, - x::AbstractArray{Float32}, + x::AbstractArray{T}, backend::Backend; block_size::Int, -) +) where {T <: ALLOWED_RAND_SCALARS} @argcheck block_size > 0 len = length(x) len == 0 && return x @@ -96,7 +117,7 @@ end """ rand!( rng::AbstractCounterRNG, - x::AbstractArray{Float32}, + x::AbstractArray{T}, backend::Backend=get_backend(x); # CPU settings @@ -110,15 +131,23 @@ end block_size::Int=256, ) -Fill `x` in-place with pseudo-random `Float32` values in `[0, 1)` using a stateless counter-based -RNG. For `x[i]`, the counter is exactly `UInt64(i - 1)` in linear indexing order. +Fill `x` in-place with pseudo-random values using a stateless counter-based RNG. For `x[i]`, the +counter is exactly `UInt64(i - 1)` in linear indexing order. -The float conversion is mantissa-based: uniform over the produced mantissa grid, not over all -representable `Float32` values in `[0, 1)`. +Supported scalar element types are: +- `UInt32`, `UInt64` +- `Int32`, `Int64` +- `Float32`, `Float64` + +Semantics: +- Unsigned integers: raw random bit patterns of requested width. +- Signed integers: corresponding unsigned patterns reinterpreted as signed. +- Floats: mantissa-based conversion from `UInt32`/`UInt64` into `[0, 1)`, uniform over the + produced mantissa grid (not over all representable floats). """ function rand!( rng::AbstractCounterRNG, - x::AbstractArray{Float32}, + x::AbstractArray{T}, backend::Backend=get_backend(x); # CPU settings @@ -128,10 +157,34 @@ function rand!( # GPU settings block_size::Int=256, -) +) where T + + @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" + if use_gpu_algorithm(backend, prefer_threads) - _rand_fill_gpu!(rng, x, backend; block_size) + return _rand_fill_gpu!(rng, x, backend; block_size) else - _rand_fill_threads!(rng, x; max_tasks, min_elems) + return _rand_fill_threads!(rng, x; max_tasks, min_elems) end end + + +""" + rand!( + x::AbstractArray{T}, + args...; + kwargs..., + ) + +Convenience overload that creates a fresh `CounterRNG()` and fills `x`. + +Each call to `rand!(x, ...)` auto-seeds a new RNG once using `rand(UInt64)`, so repeated calls +produce different outputs unless an explicit `CounterRNG` is provided. +""" +function rand!( + x::AbstractArray, + args...; + kwargs..., +) + return rand!(CounterRNG(), x, args...; kwargs...) +end diff --git a/src/rand/splitmix64.jl b/src/rand/splitmix64.jl index 165f72f6..0b94f310 100644 --- a/src/rand/splitmix64.jl +++ b/src/rand/splitmix64.jl @@ -17,10 +17,25 @@ end """ - rand_uint32(rng::CounterRNG{<:Unsigned, SplitMix64}, counter::UInt64) -> UInt32 + rand_uint(rng::CounterRNG{<:SplitMix64}, counter::UInt64, UInt64) -> UInt64 """ -@inline function rand_uint32(rng::CounterRNG{<:Unsigned, SplitMix64}, counter::UInt64)::UInt32 +@inline function rand_uint( + rng::CounterRNG{<:SplitMix64}, + counter::UInt64, + ::Type{UInt64}, +)::UInt64 seed = UInt64(rng.seed) - mixed = _splitmix64_mix(counter + seed + SPLITMIX64_INCREMENT) - return UInt32(mixed >> 32) + return _splitmix64_mix(counter + seed + SPLITMIX64_INCREMENT) +end + + +""" + rand_uint(rng::CounterRNG{<:SplitMix64}, counter::UInt64, UInt32) -> UInt32 +""" +@inline function rand_uint( + rng::CounterRNG{<:SplitMix64}, + counter::UInt64, + ::Type{UInt32}, +)::UInt32 + return _u32_hi(rand_uint(rng, counter, UInt64)) end diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl index 0a65dc36..4b1e5af2 100644 --- a/src/rand/threefry.jl +++ b/src/rand/threefry.jl @@ -17,9 +17,12 @@ end """ - rand_uint32(rng::CounterRNG{<:Unsigned, Threefry}, counter::UInt64) -> UInt32 + _threefry2x32_block(rng::CounterRNG{<:Threefry}, counter::UInt64) """ -@inline function rand_uint32(rng::CounterRNG{<:Unsigned, Threefry}, counter::UInt64)::UInt32 +@inline function _threefry2x32_block( + rng::CounterRNG{<:Threefry}, + counter::UInt64, +)::Tuple{UInt32, UInt32} x0 = _u32_lo(counter) x1 = _u32_hi(counter) @@ -45,5 +48,31 @@ end end end + return x0, x1 +end + + +""" + rand_uint(rng::CounterRNG{<:Threefry}, counter::UInt64, UInt32) -> UInt32 +""" +@inline function rand_uint( + rng::CounterRNG{<:Threefry}, + counter::UInt64, + ::Type{UInt32}, +)::UInt32 + x0, _ = _threefry2x32_block(rng, counter) return x0 end + + +""" + rand_uint(rng::CounterRNG{<:Threefry}, counter::UInt64, UInt64) -> UInt64 +""" +@inline function rand_uint( + rng::CounterRNG{<:Threefry}, + counter::UInt64, + ::Type{UInt64}, +)::UInt64 + x0, x1 = _threefry2x32_block(rng, counter) + return _u64_from_u32(x0, x1) +end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 35b72f0d..1f27c950 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -1,6 +1,7 @@ # lo: rightmost 32 bits, hi: leftmost 32 bits @inline _u32_lo(x::UInt64)::UInt32 = UInt32(x & UInt64(0xffffffff)) @inline _u32_hi(x::UInt64)::UInt32 = UInt32(x >> 32) +@inline _u64_from_u32(lo::UInt32, hi::UInt32)::UInt64 = (UInt64(hi) << 32) | UInt64(lo) # leftmost 32 bits of a*b cast to UInt64s @inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) @@ -14,9 +15,50 @@ end @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) -@inline function rand_uint32(::AbstractCounterRNG, ::UInt64)::UInt32 - # Unrecognised AbstractCounterRNG - throw(ArgumentError("No rand_uint32 implementation for this RNG type")) +""" + ALLOWED_RAND_SCALARS + +Internal scalar eltypes currently supported by [`rand!`](@ref). +""" +const ALLOWED_RAND_SCALARS = Union{ + UInt32, UInt64, + Int32, Int64, + Float32, Float64, +} + + +@inline function rand_uint(::AbstractCounterRNG, ::UInt64, ::Type{U})::U where {U <: Union{UInt32, UInt64}} + throw(ArgumentError("No rand_uint implementation for this RNG type")) +end + + +@inline raw_uint_type(::Type{UInt32}) = UInt32 +@inline raw_uint_type(::Type{Int32}) = UInt32 +@inline raw_uint_type(::Type{Float32}) = UInt32 +@inline raw_uint_type(::Type{UInt64}) = UInt64 +@inline raw_uint_type(::Type{Int64}) = UInt64 +@inline raw_uint_type(::Type{Float64}) = UInt64 + + +@inline from_uint(::Type{UInt32}, u::UInt32)::UInt32 = u +@inline from_uint(::Type{UInt64}, u::UInt64)::UInt64 = u +@inline from_uint(::Type{Int32}, u::UInt32)::Int32 = reinterpret(Int32, u) +@inline from_uint(::Type{Int64}, u::UInt64)::Int64 = reinterpret(Int64, u) +@inline from_uint(::Type{Float32}, u::UInt32)::Float32 = uint32_to_unit_float32(u) +@inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) + + +@inline function rand_scalar(rng::AbstractCounterRNG, counter::UInt64, ::Type{T})::T where {T <: ALLOWED_RAND_SCALARS} + U = raw_uint_type(T) + u = rand_uint(rng, counter, U) + return from_uint(T, u) +end + + +@inline function rand_scalar(::AbstractCounterRNG, ::UInt64, ::Type{T}) where {T} + throw(ArgumentError( + "Unsupported random scalar type $(T). Supported: UInt32, UInt64, Int32, Int64, Float32, Float64." + )) end @@ -34,3 +76,18 @@ Convert a random `UInt32` to `Float32` in `[0, 1)` by mantissa construction. # Interpret as 1.mantissa, then subtract 1 for [0, 1) return reinterpret(Float32, bits) - 1.0f0 end + + +""" + uint64_to_unit_float64(u::UInt64) -> Float64 + +Convert a random `UInt64` to `Float64` in `[0, 1)` by mantissa construction. +""" +@inline function uint64_to_unit_float64(u::UInt64)::Float64 + # Keep 52 random bits for the mantissa (drop 12 rightmost bits from the UInt64) + # and combine with the bit pattern of 1.0 (sign=0, exponent=1023). + bits = UInt64(0x3ff0000000000000) | (u >> 12) + + # Interpret as 1.mantissa, then subtract 1 for [0, 1) + return reinterpret(Float64, bits) - 1.0 +end diff --git a/test/rand.jl b/test/rand.jl index 7fefdff1..339a2cbe 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,49 +1,100 @@ function _is_unit_interval(v) for x in v - if isnan(x) || x < 0.0f0 || x >= 1.0f0 + if isnan(x) || x < zero(x) || x >= one(x) return false end end return true end -function _rand_fill_reference!(rng, x::AbstractArray{Float32}) +function _rand_fill_reference!(rng, x::AbstractArray{T}) where {T <: AK.ALLOWED_RAND_SCALARS} @inbounds for i in eachindex(x) counter = UInt64(i - one(i)) - x[i] = AK.uint32_to_unit_float32(AK.rand_uint32(rng, counter)) + x[i] = AK.rand_scalar(rng, counter, T) end return x end @testset "rand" begin - @test AK.CounterRNG{AK.SplitMix64}(0x1) isa AK.CounterRNG{AK.SplitMix64, UInt64} - @test AK.CounterRNG{AK.Philox}(UInt32(0x1)) isa AK.CounterRNG{AK.Philox, UInt32} - @test AK.CounterRNG{AK.Threefry, UInt16}(123) isa AK.CounterRNG{AK.Threefry, UInt16} - @test_throws ArgumentError AK.CounterRNG{AK.SplitMix64, UInt8}(300) + @test AK.CounterRNG(0x1; alg=AK.SplitMix64()) isa AK.CounterRNG{AK.SplitMix64} + @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} + @test AK.CounterRNG(UInt16(123); alg=AK.Threefry()) isa AK.CounterRNG{AK.Threefry} + @test AK.CounterRNG(UInt32(300)).seed == UInt64(300) + @test_throws ArgumentError AK.CounterRNG(-1) + + Random.seed!(0x1234) + expected_auto_seed = rand(UInt64) + Random.seed!(0x1234) + rng_auto = AK.CounterRNG() + @test rng_auto.seed == expected_auto_seed + @test rng_auto.alg isa AK.SplitMix64 + + xauto1 = array_from_host(zeros(Float32, 1024)) + xauto2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(rng_auto, xauto1; prefer_threads, block_size=64) + AK.rand!(rng_auto, xauto2; prefer_threads, block_size=257) + @test Array(xauto1) == Array(xauto2) + + Random.seed!(0xabcdef) + seed1 = rand(UInt64) + seed2 = rand(UInt64) + ref1 = array_from_host(zeros(Float32, 1024)) + ref2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(AK.CounterRNG(seed1; alg=AK.SplitMix64()), ref1; prefer_threads, block_size=64) + AK.rand!(AK.CounterRNG(seed2; alg=AK.SplitMix64()), ref2; prefer_threads, block_size=64) + + Random.seed!(0xabcdef) + xconv1 = array_from_host(zeros(Float32, 1024)) + xconv2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(xconv1; prefer_threads, block_size=64) + AK.rand!(xconv2; prefer_threads, block_size=64) + @test Array(xconv1) == Array(ref1) + @test Array(xconv2) == Array(ref2) rng_algs = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) + scalar_types = (UInt32, UInt64, Int32, Int64, Float32, Float64) for alg in rng_algs rng_alg = AK.CounterRNG(0x123456789abcdef; alg) - @test AK.rand_uint32(rng_alg, UInt64(0)) == AK.rand_uint32(rng_alg, UInt64(0)) - @test AK.rand_uint32(rng_alg, UInt64(1)) != AK.rand_uint32(rng_alg, UInt64(0)) + for U in (UInt32, UInt64) + @test AK.rand_uint(rng_alg, UInt64(0), U) == AK.rand_uint(rng_alg, UInt64(0), U) + @test AK.rand_uint(rng_alg, UInt64(1), U) != AK.rand_uint(rng_alg, UInt64(0), U) - vals_alg = [AK.rand_uint32(rng_alg, UInt64(i)) for i in 0:1023] - @test length(unique(vals_alg)) == length(vals_alg) + vals_alg = [AK.rand_uint(rng_alg, UInt64(i), U) for i in 0:1023] + @test length(unique(vals_alg)) > 900 + end - x_alg = array_from_host(zeros(Float32, 2048)) - AK.rand!(rng_alg, x_alg; prefer_threads, block_size=64) - @test _is_unit_interval(Array(x_alg)) + for T in scalar_types + x_alg = array_from_host(zeros(T, 2048)) + AK.rand!(rng_alg, x_alg; prefer_threads, block_size=64) + x_alg_h = Array(x_alg) + ref_alg = zeros(T, 2048) + _rand_fill_reference!(rng_alg, ref_alg) + @test x_alg_h == ref_alg + if T <: AbstractFloat + @test _is_unit_interval(x_alg_h) + end + end end rng = AK.CounterRNG(0x123456789abcdef) - @test AK.rand_uint32(rng, UInt64(0)) == AK.rand_uint32(rng, UInt64(0)) - @test AK.rand_uint32(rng, UInt64(1)) != AK.rand_uint32(rng, UInt64(0)) - @test AK.rand_uint32(rng, UInt64(17)) != AK.rand_uint32(rng, UInt64(18)) + @test AK.from_uint(UInt32, UInt32(0xdeadbeef)) == UInt32(0xdeadbeef) + @test AK.from_uint(UInt64, UInt64(0x0123456789abcdef)) == UInt64(0x0123456789abcdef) + @test AK.from_uint(Int32, UInt32(0xdeadbeef)) == reinterpret(Int32, UInt32(0xdeadbeef)) + @test AK.from_uint(Int64, UInt64(0x0123456789abcdef)) == reinterpret(Int64, UInt64(0x0123456789abcdef)) + + @test AK.rand_uint(rng, UInt64(0), UInt32) == AK.rand_uint(rng, UInt64(0), UInt32) + @test AK.rand_uint(rng, UInt64(1), UInt32) != AK.rand_uint(rng, UInt64(0), UInt32) + @test AK.rand_uint(rng, UInt64(17), UInt32) != AK.rand_uint(rng, UInt64(18), UInt32) + @test AK.rand_uint(rng, UInt64(0), UInt64) == AK.rand_uint(rng, UInt64(0), UInt64) + @test AK.rand_uint(rng, UInt64(1), UInt64) != AK.rand_uint(rng, UInt64(0), UInt64) + @test AK.rand_uint(rng, UInt64(17), UInt64) != AK.rand_uint(rng, UInt64(18), UInt64) - vals = [AK.rand_uint32(rng, UInt64(i)) for i in 0:2047] - @test length(unique(vals)) == length(vals) + vals_u32 = [AK.rand_uint(rng, UInt64(i), UInt32) for i in 0:2047] + vals_u64 = [AK.rand_uint(rng, UInt64(i), UInt64) for i in 0:2047] + @test length(unique(vals_u32)) > 1800 + @test length(unique(vals_u64)) > 2000 for u in ( UInt32(0x00000000), @@ -57,51 +108,85 @@ end @test 0.0f0 <= x < 1.0f0 end - lengths = (0, 1, 31, 32, 33, 1024, 1025) - for len in lengths - x = array_from_host(zeros(Float32, len)) - AK.rand!(rng, x; prefer_threads, block_size=64) - xh = Array(x) - - ref = zeros(Float32, len) - _rand_fill_reference!(rng, ref) + for u in ( + UInt64(0x0000000000000000), + UInt64(0x0000000000000001), + UInt64(0x7fffffffffffffff), + UInt64(0x8000000000000000), + UInt64(0xffffffffffffffff), + ) + x = AK.uint64_to_unit_float64(u) + @test !isnan(x) + @test 0.0 <= x < 1.0 + end - @test xh == ref - @test _is_unit_interval(xh) + for T in scalar_types + s0 = AK.rand_scalar(rng, UInt64(0), T) + s1 = AK.rand_scalar(rng, UInt64(1), T) + @test s0 isa T + @test s1 isa T + @test s0 != s1 + if T <: AbstractFloat + @test zero(T) <= s0 < one(T) + @test zero(T) <= s1 < one(T) + end end - x1 = array_from_host(zeros(Float32, 4096)) - x2 = array_from_host(zeros(Float32, 4096)) - AK.rand!(rng, x1; prefer_threads, block_size=64) - AK.rand!(rng, x2; prefer_threads, block_size=257) - @test Array(x1) == Array(x2) + @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) - rng2 = AK.CounterRNG(rng.seed + UInt64(1)) - x3 = array_from_host(zeros(Float32, 4096)) - AK.rand!(rng2, x3; prefer_threads, block_size=64) - @test Array(x3) != Array(x1) + lengths = (0, 1, 31, 32, 33, 1024, 1025) + for T in scalar_types + for len in lengths + x = array_from_host(zeros(T, len)) + AK.rand!(rng, x; prefer_threads, block_size=64) + xh = Array(x) + + ref = zeros(T, len) + _rand_fill_reference!(rng, ref) + + @test xh == ref + if T <: AbstractFloat + @test _is_unit_interval(xh) + end + end + end - xnd = array_from_host(zeros(Float32, 7, 11, 5)) - AK.rand!(rng, xnd; prefer_threads, block_size=128) - xndh = Array(xnd) - refnd = zeros(Float32, 7, 11, 5) - _rand_fill_reference!(rng, refnd) - @test xndh == refnd + rng2 = AK.CounterRNG(rng.seed + UInt64(1)) + for T in scalar_types + x1 = array_from_host(zeros(T, 4096)) + x2 = array_from_host(zeros(T, 4096)) + AK.rand!(rng, x1; prefer_threads, block_size=64) + AK.rand!(rng, x2; prefer_threads, block_size=257) + @test Array(x1) == Array(x2) + + x3 = array_from_host(zeros(T, 4096)) + AK.rand!(rng2, x3; prefer_threads, block_size=64) + @test Array(x3) != Array(x1) + + xnd = array_from_host(zeros(T, 7, 11, 5)) + AK.rand!(rng, xnd; prefer_threads, block_size=128) + xndh = Array(xnd) + refnd = zeros(T, 7, 11, 5) + _rand_fill_reference!(rng, refnd) + @test xndh == refnd + end if IS_CPU_BACKEND - base = zeros(Float32, 64) - view_x = @view base[2:2:end] - AK.rand!( - rng, - view_x; - max_tasks=Threads.nthreads(), - min_elems=1, - prefer_threads=true, - ) - - ref_view = zeros(Float32, length(view_x)) - _rand_fill_reference!(rng, ref_view) - @test collect(view_x) == ref_view + for T in scalar_types + base = zeros(T, 64) + view_x = @view base[2:2:end] + AK.rand!( + rng, + view_x; + max_tasks=Threads.nthreads(), + min_elems=1, + prefer_threads=true, + ) + + ref_view = zeros(T, length(view_x)) + _rand_fill_reference!(rng, ref_view) + @test collect(view_x) == ref_view + end end nstats = 200_000 @@ -127,6 +212,7 @@ end max_rel_dev = maximum(abs(c - expected) / expected for c in counts) @test max_rel_dev < 0.1 - x64 = array_from_host(zeros(Float64, 16)) - @test_throws MethodError AK.rand!(rng, x64; prefer_threads) + x16 = array_from_host(zeros(UInt16, 16)) + @test_throws ArgumentError AK.rand!(x16; prefer_threads) + @test_throws ArgumentError AK.rand!(rng, x16; prefer_threads) end From f590d5eabcb5a616776cb13913c3b72eba2e1428 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 16 Mar 2026 17:42:43 +0000 Subject: [PATCH 03/20] just use foreachindex for the kernel now that it is simple enough --- src/rand/rand.jl | 86 +++++++++---------------------------------- src/rand/utilities.jl | 27 ++++++++++---- 2 files changed, 36 insertions(+), 77 deletions(-) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 0e294520..23ef8017 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -23,6 +23,13 @@ value is a pure function of: The default algorithm is `Philox()`. `seed` may be any non-negative `Integer`. It is normalised to `UInt64` internally. + +Constructors: +- `CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox())` + Uses an explicit non-negative seed. +- `CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64())` + Auto-seeds once using `rand(UInt64)`. Reusing the same `CounterRNG` instance is deterministic + for fixed seed, algorithm, array shape, and eltype. """ struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG seed::UInt64 @@ -30,26 +37,12 @@ struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG end -function CounterRNG(seed::Unsigned; alg::CounterRNGAlgorithm=Philox()) - CounterRNG(UInt64(seed), alg) -end - - function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) - @argcheck seed >= 0 + @argcheck seed >= 0 "Seed must be a positive integer" CounterRNG(UInt64(seed), alg) end - -""" - CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64()) - -Create a stateless counter-based RNG with an automatically generated seed. - -The seed is sampled exactly once at construction using `rand(UInt64)`. Reusing this same -`CounterRNG` instance is deterministic for fixed seed, algorithm, array shape, and eltype. -""" function CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64()) CounterRNG(Base.rand(UInt64); alg) end @@ -65,55 +58,6 @@ include("splitmix64.jl") include("philox.jl") include("threefry.jl") - - - - -function _rand_fill_threads!( - rng::AbstractCounterRNG, - x::AbstractArray{T}; - max_tasks::Int, - min_elems::Int, -) where {T <: ALLOWED_RAND_SCALARS} - task_partition(length(x), max_tasks, min_elems) do irange - @inbounds for i in irange - counter = _counter_from_index(i) - x[i] = rand_scalar(rng, counter, T) - end - end - return x -end - - -@kernel inbounds=true cpu=false unsafe_indices=true function _rand_fill_kernel!( - rng, - x, -) - i = @index(Global, Linear) - if i <= length(x) - counter = _counter_from_index(i) - x[i] = rand_scalar(rng, counter, eltype(x)) - end -end - - -function _rand_fill_gpu!( - rng::AbstractCounterRNG, - x::AbstractArray{T}, - backend::Backend; - block_size::Int, -) where {T <: ALLOWED_RAND_SCALARS} - @argcheck block_size > 0 - len = length(x) - len == 0 && return x - - blocks = div(len, block_size, RoundUp) - kernel! = _rand_fill_kernel!(backend, block_size) - kernel!(rng, x, ndrange=(blocks * block_size,)) - return x -end - - """ rand!( rng::AbstractCounterRNG, @@ -160,12 +104,16 @@ function rand!( ) where T @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" - - if use_gpu_algorithm(backend, prefer_threads) - return _rand_fill_gpu!(rng, x, backend; block_size) - else - return _rand_fill_threads!(rng, x; max_tasks, min_elems) + foreachindex( + 1:length(x), backend; + max_tasks, + min_elems, + prefer_threads, + block_size, + ) do i + @inbounds x[i] = rand_scalar(rng, _counter_from_index(i), T) end + return x end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 1f27c950..c22a863d 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -27,11 +27,6 @@ const ALLOWED_RAND_SCALARS = Union{ } -@inline function rand_uint(::AbstractCounterRNG, ::UInt64, ::Type{U})::U where {U <: Union{UInt32, UInt64}} - throw(ArgumentError("No rand_uint implementation for this RNG type")) -end - - @inline raw_uint_type(::Type{UInt32}) = UInt32 @inline raw_uint_type(::Type{Int32}) = UInt32 @inline raw_uint_type(::Type{Float32}) = UInt32 @@ -48,9 +43,24 @@ end @inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) -@inline function rand_scalar(rng::AbstractCounterRNG, counter::UInt64, ::Type{T})::T where {T <: ALLOWED_RAND_SCALARS} - U = raw_uint_type(T) - u = rand_uint(rng, counter, U) +@inline function rand_uint( + rng::AbstractCounterRNG, + ::UInt64, + ::Type{UIntType} +)::UIntType where {UIntType <: Union{UInt32, UInt64}} + throw(ArgumentError("No rand_uint implementation for RNG: $rng")) +end + + +@inline function rand_scalar( + rng::AbstractCounterRNG, + counter::UInt64, + ::Type{T} +)::T where {T <: ALLOWED_RAND_SCALARS} + + UIntType = raw_uint_type(T) + u = rand_uint(rng, counter, UIntType) + return from_uint(T, u) end @@ -63,6 +73,7 @@ end + """ uint32_to_unit_float32(u::UInt32) -> Float32 From 9e471d6c3144704e036bd98bf16705181426b85a Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 16 Mar 2026 18:34:24 +0000 Subject: [PATCH 04/20] finalise tests and docs --- docs/make.jl | 1 + docs/src/api/rand.md | 48 ++++++ src/rand/philox.jl | 15 +- src/rand/rand.jl | 18 +- src/rand/splitmix64.jl | 8 +- src/rand/threefry.jl | 14 +- src/rand/utilities.jl | 36 ++-- test/rand.jl | 362 ++++++++++++++++++++--------------------- 8 files changed, 256 insertions(+), 246 deletions(-) create mode 100644 docs/src/api/rand.md diff --git a/docs/make.jl b/docs/make.jl index 58b4632e..5e794a2b 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -23,6 +23,7 @@ makedocs(; "Using Different Backends" => "api/using_backends.md", "General Loops" => "api/foreachindex.md", "Map" => "api/map.md", + "Random Number Generation" => "api/rand.md", "Sorting" => "api/sort.md", "Reduce" => "api/reduce.md", "MapReduce" => "api/mapreduce.md", diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md new file mode 100644 index 00000000..2fa468f1 --- /dev/null +++ b/docs/src/api/rand.md @@ -0,0 +1,48 @@ +### Random Number Generation + +Counter-based random generation for CPU and GPU backends with deterministic behavior for fixed +`seed`, algorithm, array shape, and eltype. + +Use an explicit `CounterRNG(seed; alg=...)` when reproducibility matters. For convenience, +`AK.rand!(x)` creates a fresh `CounterRNG()` on each call using one auto-seeded `Base.rand(UInt64)` +draw, so repeated calls usually produce different outputs. + +Supported output element types: +- `UInt32`, `UInt64` +- `Int32`, `Int64` +- `Float32`, `Float64` + +The core of the random number generation produces a `UInt` of the requested scalar width. +That `UInt` is then either: +- Unsigned integers: returned as-is +- Signed integers: reinterpreted as a signed integer bit pattern. +- Floats: mantissa construction into a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)). + +Algorithms currently available: +- `SplitMix64` ([read more](https://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64)) +- `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) +- `Threefry` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) + +`Philox` is the default algorithm for `CounterRNG()`, as it is more thoroughly +statistically tested and measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an RTX +5060 (advertised 448 GB/s), i.e. effectively memory-bound throughput. + +Examples: +```julia +import AcceleratedKernels as AK +using oneAPI + +# Reproducible +rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) +x = oneArray{Float32}(undef, 1024) +AK.rand!(rng, x) + +# Convenience (fresh auto-seeded RNG on each call) +y = oneArray{Float32}(undef, 1024) +AK.rand!(y) +``` + +```@docs +AcceleratedKernels.CounterRNG +AcceleratedKernels.rand! +``` diff --git a/src/rand/philox.jl b/src/rand/philox.jl index 8137f645..bdebc8e5 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -7,7 +7,6 @@ const PHILOX_W0 = UInt32(0x9E3779B9) const PHILOX_ROUNDS = 10 -# Each round destroys x0 with multiplication, addition, and XORs @inline function _philox2x32_round(x0::UInt32, x1::UInt32, k0::UInt32) lo = PHILOX_M0 * x0 hi = _mulhi_u32(PHILOX_M0, x0) @@ -17,9 +16,7 @@ const PHILOX_ROUNDS = 10 end -""" - _philox2x32_block(rng::CounterRNG{<:Philox}, counter::UInt64) -""" +# Evaluate one Philox block at `counter`, returning two 32-bit lanes `(x0, x1)` @inline function _philox2x32_block( rng::CounterRNG{<:Philox}, counter::UInt64, @@ -40,9 +37,7 @@ end end -""" - rand_uint(rng::CounterRNG{<:Philox}, counter::UInt64, UInt32) -> UInt32 -""" +# Return lane 0 from the single Philox block at `counter` @inline function rand_uint( rng::CounterRNG{<:Philox}, counter::UInt64, @@ -53,14 +48,12 @@ end end -""" - rand_uint(rng::CounterRNG{<:Philox}, counter::UInt64, UInt64) -> UInt64 -""" +# Build UInt64 from the two lanes `(x0, x1)` of the same Philox block at `counter` @inline function rand_uint( rng::CounterRNG{<:Philox}, counter::UInt64, ::Type{UInt64}, )::UInt64 x0, x1 = _philox2x32_block(rng, counter) - return _u64_from_u32(x0, x1) + return _u64_from_u32s(x0, x1) end diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 23ef8017..e62ba962 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -38,12 +38,12 @@ end function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) - @argcheck seed >= 0 "Seed must be a positive integer" + @argcheck seed >= 0 "Seed must be a non-negative integer" CounterRNG(UInt64(seed), alg) end -function CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64()) +function CounterRNG(; alg::CounterRNGAlgorithm=Philox()) CounterRNG(Base.rand(UInt64); alg) end @@ -115,20 +115,6 @@ function rand!( end return x end - - -""" - rand!( - x::AbstractArray{T}, - args...; - kwargs..., - ) - -Convenience overload that creates a fresh `CounterRNG()` and fills `x`. - -Each call to `rand!(x, ...)` auto-seeds a new RNG once using `rand(UInt64)`, so repeated calls -produce different outputs unless an explicit `CounterRNG` is provided. -""" function rand!( x::AbstractArray, args...; diff --git a/src/rand/splitmix64.jl b/src/rand/splitmix64.jl index 0b94f310..d169b738 100644 --- a/src/rand/splitmix64.jl +++ b/src/rand/splitmix64.jl @@ -16,9 +16,7 @@ const SPLITMIX64_MIX_B = UInt64(0x94d049bb133111eb) end -""" - rand_uint(rng::CounterRNG{<:SplitMix64}, counter::UInt64, UInt64) -> UInt64 -""" +# Natural SplitMix64 output path: compute 64 random bits directly from one counter @inline function rand_uint( rng::CounterRNG{<:SplitMix64}, counter::UInt64, @@ -29,9 +27,7 @@ end end -""" - rand_uint(rng::CounterRNG{<:SplitMix64}, counter::UInt64, UInt32) -> UInt32 -""" +# UInt32 path is derived from the high 32 bits of the UInt64 SplitMix output @inline function rand_uint( rng::CounterRNG{<:SplitMix64}, counter::UInt64, diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl index 4b1e5af2..7326f404 100644 --- a/src/rand/threefry.jl +++ b/src/rand/threefry.jl @@ -16,9 +16,7 @@ const THREEFRY_ROUNDS = 20 end -""" - _threefry2x32_block(rng::CounterRNG{<:Threefry}, counter::UInt64) -""" +# Evaluate one Threefry block at `counter`, returning two 32-bit lanes `(x0, x1)` @inline function _threefry2x32_block( rng::CounterRNG{<:Threefry}, counter::UInt64, @@ -52,9 +50,7 @@ end end -""" - rand_uint(rng::CounterRNG{<:Threefry}, counter::UInt64, UInt32) -> UInt32 -""" +# Return lane 0 from the single Threefry block at `counter` @inline function rand_uint( rng::CounterRNG{<:Threefry}, counter::UInt64, @@ -65,14 +61,12 @@ end end -""" - rand_uint(rng::CounterRNG{<:Threefry}, counter::UInt64, UInt64) -> UInt64 -""" +# Build UInt64 from the two lanes `(x0, x1)` of the same Threefry block at `counter` @inline function rand_uint( rng::CounterRNG{<:Threefry}, counter::UInt64, ::Type{UInt64}, )::UInt64 x0, x1 = _threefry2x32_block(rng, counter) - return _u64_from_u32(x0, x1) + return _u64_from_u32s(x0, x1) end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index c22a863d..2623c9d2 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -1,25 +1,19 @@ # lo: rightmost 32 bits, hi: leftmost 32 bits @inline _u32_lo(x::UInt64)::UInt32 = UInt32(x & UInt64(0xffffffff)) @inline _u32_hi(x::UInt64)::UInt32 = UInt32(x >> 32) -@inline _u64_from_u32(lo::UInt32, hi::UInt32)::UInt64 = (UInt64(hi) << 32) | UInt64(lo) +@inline _u64_from_u32s(lo::UInt32, hi::UInt32)::UInt64 = (UInt64(hi) << 32) | UInt64(lo) # leftmost 32 bits of a*b cast to UInt64s @inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) - -@inline function _rotl32(x::UInt32, r::UInt32)::UInt32 - return (x << r) | (x >> (UInt32(32) - r)) -end +# 32-bit rotate left by r positions +@inline _rotl32(x::UInt32, r::UInt32)::UInt32 = (x << r) | (x >> (UInt32(32) - r)) @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) -""" - ALLOWED_RAND_SCALARS - -Internal scalar eltypes currently supported by [`rand!`](@ref). -""" +# Internal scalar eltypes currently supported by rand!. const ALLOWED_RAND_SCALARS = Union{ UInt32, UInt64, Int32, Int64, @@ -43,6 +37,10 @@ const ALLOWED_RAND_SCALARS = Union{ @inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) +#= +Every RNG algorithm implements rand_uint(rng, counter, UInt32/UInt64). +This fallback provides a clear failure for unsupported RNG types. +=# @inline function rand_uint( rng::AbstractCounterRNG, ::UInt64, @@ -52,6 +50,12 @@ const ALLOWED_RAND_SCALARS = Union{ end +#= +Shared scalar generation: +1) map requested scalar type to corresponding raw UInt width +2) fill the UInt with random bits +3) convert bits into requested scalar representation +=# @inline function rand_scalar( rng::AbstractCounterRNG, counter::UInt64, @@ -74,11 +78,7 @@ end -""" - uint32_to_unit_float32(u::UInt32) -> Float32 - -Convert a random `UInt32` to `Float32` in `[0, 1)` by mantissa construction. -""" +# Convert random UInt32 bits to Float32 in [0, 1) by mantissa construction. @inline function uint32_to_unit_float32(u::UInt32)::Float32 # Keep 23 random bits for the mantissa (drop 9 rightmost bits from the UInt32) # and combine with the bit pattern of 1.0f0 (sign=0, exponent=127). @@ -89,11 +89,7 @@ Convert a random `UInt32` to `Float32` in `[0, 1)` by mantissa construction. end -""" - uint64_to_unit_float64(u::UInt64) -> Float64 - -Convert a random `UInt64` to `Float64` in `[0, 1)` by mantissa construction. -""" +# Convert random UInt64 bits to Float64 in [0, 1) by mantissa construction. @inline function uint64_to_unit_float64(u::UInt64)::Float64 # Keep 52 random bits for the mantissa (drop 12 rightmost bits from the UInt64) # and combine with the bit pattern of 1.0 (sign=0, exponent=1023). diff --git a/test/rand.jl b/test/rand.jl index 339a2cbe..e3f0bb60 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,218 +1,214 @@ -function _is_unit_interval(v) - for x in v - if isnan(x) || x < zero(x) || x >= one(x) - return false - end - end - return true -end +const RAND_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) +const RAND_SCALAR_TYPES = (UInt32, UInt64, Int32, Int64, Float32, Float64) + + +_is_unit_interval(v) = all(x -> !isnan(x) && zero(x) <= x < one(x), v) + function _rand_fill_reference!(rng, x::AbstractArray{T}) where {T <: AK.ALLOWED_RAND_SCALARS} @inbounds for i in eachindex(x) - counter = UInt64(i - one(i)) - x[i] = AK.rand_scalar(rng, counter, T) + x[i] = AK.rand_scalar(rng, UInt64(i - one(i)), T) end return x end -@testset "rand" begin - @test AK.CounterRNG(0x1; alg=AK.SplitMix64()) isa AK.CounterRNG{AK.SplitMix64} - @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} - @test AK.CounterRNG(UInt16(123); alg=AK.Threefry()) isa AK.CounterRNG{AK.Threefry} - @test AK.CounterRNG(UInt32(300)).seed == UInt64(300) - @test_throws ArgumentError AK.CounterRNG(-1) - - Random.seed!(0x1234) - expected_auto_seed = rand(UInt64) - Random.seed!(0x1234) - rng_auto = AK.CounterRNG() - @test rng_auto.seed == expected_auto_seed - @test rng_auto.alg isa AK.SplitMix64 - - xauto1 = array_from_host(zeros(Float32, 1024)) - xauto2 = array_from_host(zeros(Float32, 1024)) - AK.rand!(rng_auto, xauto1; prefer_threads, block_size=64) - AK.rand!(rng_auto, xauto2; prefer_threads, block_size=257) - @test Array(xauto1) == Array(xauto2) - - Random.seed!(0xabcdef) - seed1 = rand(UInt64) - seed2 = rand(UInt64) - ref1 = array_from_host(zeros(Float32, 1024)) - ref2 = array_from_host(zeros(Float32, 1024)) - AK.rand!(AK.CounterRNG(seed1; alg=AK.SplitMix64()), ref1; prefer_threads, block_size=64) - AK.rand!(AK.CounterRNG(seed2; alg=AK.SplitMix64()), ref2; prefer_threads, block_size=64) - - Random.seed!(0xabcdef) - xconv1 = array_from_host(zeros(Float32, 1024)) - xconv2 = array_from_host(zeros(Float32, 1024)) - AK.rand!(xconv1; prefer_threads, block_size=64) - AK.rand!(xconv2; prefer_threads, block_size=64) - @test Array(xconv1) == Array(ref1) - @test Array(xconv2) == Array(ref2) - - rng_algs = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) - scalar_types = (UInt32, UInt64, Int32, Int64, Float32, Float64) - - for alg in rng_algs - rng_alg = AK.CounterRNG(0x123456789abcdef; alg) - for U in (UInt32, UInt64) - @test AK.rand_uint(rng_alg, UInt64(0), U) == AK.rand_uint(rng_alg, UInt64(0), U) - @test AK.rand_uint(rng_alg, UInt64(1), U) != AK.rand_uint(rng_alg, UInt64(0), U) - - vals_alg = [AK.rand_uint(rng_alg, UInt64(i), U) for i in 0:1023] - @test length(unique(vals_alg)) > 900 - end - for T in scalar_types - x_alg = array_from_host(zeros(T, 2048)) - AK.rand!(rng_alg, x_alg; prefer_threads, block_size=64) - x_alg_h = Array(x_alg) - ref_alg = zeros(T, 2048) - _rand_fill_reference!(rng_alg, ref_alg) - @test x_alg_h == ref_alg - if T <: AbstractFloat - @test _is_unit_interval(x_alg_h) - end - end - end +function _assert_rand_matches_reference!(rng, x; kwargs...) + AK.rand!(rng, x; kwargs...) + ref = zeros(eltype(x), size(x)) + _rand_fill_reference!(rng, ref) + @test Array(x) == ref + return x +end - rng = AK.CounterRNG(0x123456789abcdef) - - @test AK.from_uint(UInt32, UInt32(0xdeadbeef)) == UInt32(0xdeadbeef) - @test AK.from_uint(UInt64, UInt64(0x0123456789abcdef)) == UInt64(0x0123456789abcdef) - @test AK.from_uint(Int32, UInt32(0xdeadbeef)) == reinterpret(Int32, UInt32(0xdeadbeef)) - @test AK.from_uint(Int64, UInt64(0x0123456789abcdef)) == reinterpret(Int64, UInt64(0x0123456789abcdef)) - - @test AK.rand_uint(rng, UInt64(0), UInt32) == AK.rand_uint(rng, UInt64(0), UInt32) - @test AK.rand_uint(rng, UInt64(1), UInt32) != AK.rand_uint(rng, UInt64(0), UInt32) - @test AK.rand_uint(rng, UInt64(17), UInt32) != AK.rand_uint(rng, UInt64(18), UInt32) - @test AK.rand_uint(rng, UInt64(0), UInt64) == AK.rand_uint(rng, UInt64(0), UInt64) - @test AK.rand_uint(rng, UInt64(1), UInt64) != AK.rand_uint(rng, UInt64(0), UInt64) - @test AK.rand_uint(rng, UInt64(17), UInt64) != AK.rand_uint(rng, UInt64(18), UInt64) - - vals_u32 = [AK.rand_uint(rng, UInt64(i), UInt32) for i in 0:2047] - vals_u64 = [AK.rand_uint(rng, UInt64(i), UInt64) for i in 0:2047] - @test length(unique(vals_u32)) > 1800 - @test length(unique(vals_u64)) > 2000 - - for u in ( - UInt32(0x00000000), - UInt32(0x00000001), - UInt32(0x7fffffff), - UInt32(0x80000000), - UInt32(0xffffffff), - ) - x = AK.uint32_to_unit_float32(u) - @test !isnan(x) - @test 0.0f0 <= x < 1.0f0 + +@testset "rand" begin + @testset "constructors" begin + @test AK.CounterRNG(0x1; alg=AK.SplitMix64()) isa AK.CounterRNG{AK.SplitMix64} + @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} + @test AK.CounterRNG(UInt16(123); alg=AK.Threefry()) isa AK.CounterRNG{AK.Threefry} + @test AK.CounterRNG(UInt32(300)).seed == UInt64(300) + @test_throws ArgumentError AK.CounterRNG(-1) + + Random.seed!(0x1234) + expected_seed = rand(UInt64) + Random.seed!(0x1234) + rng_auto = AK.CounterRNG() + @test rng_auto.seed == expected_seed + @test rng_auto.alg isa AK.Philox + + x1 = array_from_host(zeros(Float32, 1024)) + x2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(rng_auto, x1; prefer_threads, block_size=64) + AK.rand!(rng_auto, x2; prefer_threads, block_size=257) + @test Array(x1) == Array(x2) end - for u in ( - UInt64(0x0000000000000000), - UInt64(0x0000000000000001), - UInt64(0x7fffffffffffffff), - UInt64(0x8000000000000000), - UInt64(0xffffffffffffffff), - ) - x = AK.uint64_to_unit_float64(u) - @test !isnan(x) - @test 0.0 <= x < 1.0 + + @testset "bit helpers" begin + hi = UInt32(0b10101010101010101010101010101010) + lo = UInt32(0b01010101010101010101010101010101) + word = UInt64(hi) << 32 | UInt64(lo) + + @test AK._u32_hi(word) == hi + @test AK._u32_lo(word) == lo + @test AK._u64_from_u32s(lo, hi) == word + @test AK._mulhi_u32(0xffffffff % UInt32, 0xffffffff % UInt32) == 0xfffffffe % UInt32 + @test AK._rotl32(0b10000000000000000000000000000001 % UInt32, UInt32(1)) == 0b11 % UInt32 + @test AK._counter_from_index(1) == UInt64(0) + @test AK._counter_from_index(17) == UInt64(16) + + @test AK.raw_uint_type(UInt32) === UInt32 + @test AK.raw_uint_type(Int32) === UInt32 + @test AK.raw_uint_type(Float32) === UInt32 + @test AK.raw_uint_type(UInt64) === UInt64 + @test AK.raw_uint_type(Int64) === UInt64 + @test AK.raw_uint_type(Float64) === UInt64 + + @test AK.from_uint(UInt32, 0b1010 % UInt32) == 0b1010 % UInt32 + @test AK.from_uint(UInt64, 0b1010 % UInt64) == 0b1010 % UInt64 + @test AK.from_uint(Int32, 0b11111111111111111111111111111111 % UInt32) == Int32(-1) + @test AK.from_uint( + Int64, 0b1111111111111111111111111111111111111111111111111111111111111111 % UInt64 + ) == Int64(-1) + + @test AK.uint32_to_unit_float32(UInt32(0)) == 0.0f0 + @test AK.uint64_to_unit_float64(UInt64(0)) == 0.0 + @test 0.0f0 <= AK.uint32_to_unit_float32(typemax(UInt32)) < 1.0f0 + @test 0.0 <= AK.uint64_to_unit_float64(typemax(UInt64)) < 1.0 end - for T in scalar_types - s0 = AK.rand_scalar(rng, UInt64(0), T) - s1 = AK.rand_scalar(rng, UInt64(1), T) - @test s0 isa T - @test s1 isa T - @test s0 != s1 - if T <: AbstractFloat - @test zero(T) <= s0 < one(T) - @test zero(T) <= s1 < one(T) + + @testset "rand_uint" begin + for alg in RAND_ALGS + rng = AK.CounterRNG(0x123456789abcdef; alg) + for U in (UInt32, UInt64) + @test AK.rand_uint(rng, UInt64(0), U) == AK.rand_uint(rng, UInt64(0), U) + @test AK.rand_uint(rng, UInt64(1), U) != AK.rand_uint(rng, UInt64(0), U) + + vals = [AK.rand_uint(rng, UInt64(i), U) for i in 0:511] + @test length(unique(vals)) > 460 + end + end + + rng_splitmix = AK.CounterRNG(0x31415926; alg=AK.SplitMix64()) + for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) + @test AK.rand_uint(rng_splitmix, c, UInt32) == AK._u32_hi( + AK.rand_uint(rng_splitmix, c, UInt64) + ) end - end - @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) + for alg in (AK.Philox(), AK.Threefry()) + rng = AK.CounterRNG(0xabcdef1234567890; alg) + for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) + @test AK._u32_lo(AK.rand_uint(rng, c, UInt64)) == AK.rand_uint(rng, c, UInt32) + end + end + end - lengths = (0, 1, 31, 32, 33, 1024, 1025) - for T in scalar_types - for len in lengths - x = array_from_host(zeros(T, len)) - AK.rand!(rng, x; prefer_threads, block_size=64) - xh = Array(x) - ref = zeros(T, len) - _rand_fill_reference!(rng, ref) + @testset "rand_scalar" begin + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) - @test xh == ref + for T in RAND_SCALAR_TYPES + s0 = AK.rand_scalar(rng, UInt64(0), T) + s1 = AK.rand_scalar(rng, UInt64(1), T) + @test s0 isa T + @test s1 isa T + @test s0 != s1 if T <: AbstractFloat - @test _is_unit_interval(xh) + @test zero(T) <= s0 < one(T) + @test zero(T) <= s1 < one(T) end end + + c = UInt64(42) + @test AK.rand_scalar(rng, c, Int32) == reinterpret(Int32, AK.rand_uint(rng, c, UInt32)) + @test AK.rand_scalar(rng, c, Int64) == reinterpret(Int64, AK.rand_uint(rng, c, UInt64)) + @test AK.rand_scalar(rng, c, Float32) == AK.uint32_to_unit_float32( + AK.rand_uint(rng, c, UInt32) + ) + @test AK.rand_scalar(rng, c, Float64) == AK.uint64_to_unit_float64( + AK.rand_uint(rng, c, UInt64) + ) + @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) end - rng2 = AK.CounterRNG(rng.seed + UInt64(1)) - for T in scalar_types - x1 = array_from_host(zeros(T, 4096)) - x2 = array_from_host(zeros(T, 4096)) - AK.rand!(rng, x1; prefer_threads, block_size=64) - AK.rand!(rng, x2; prefer_threads, block_size=257) - @test Array(x1) == Array(x2) - x3 = array_from_host(zeros(T, 4096)) - AK.rand!(rng2, x3; prefer_threads, block_size=64) - @test Array(x3) != Array(x1) + @testset "rand! explicit rng" begin + lengths = (0, 1, 31, 32, 33, 257, 1024) + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) - xnd = array_from_host(zeros(T, 7, 11, 5)) - AK.rand!(rng, xnd; prefer_threads, block_size=128) - xndh = Array(xnd) - refnd = zeros(T, 7, 11, 5) - _rand_fill_reference!(rng, refnd) - @test xndh == refnd - end + for T in RAND_SCALAR_TYPES + for len in lengths + x = array_from_host(zeros(T, len)) + _assert_rand_matches_reference!(rng, x; prefer_threads, block_size=64) + if T <: AbstractFloat + @test _is_unit_interval(Array(x)) + end + end + end - if IS_CPU_BACKEND - for T in scalar_types - base = zeros(T, 64) - view_x = @view base[2:2:end] - AK.rand!( - rng, - view_x; - max_tasks=Threads.nthreads(), - min_elems=1, - prefer_threads=true, - ) + for T in RAND_SCALAR_TYPES + x1 = array_from_host(zeros(T, 2048)) + x2 = array_from_host(zeros(T, 2048)) + AK.rand!(rng, x1; prefer_threads, block_size=64) + AK.rand!(rng, x2; prefer_threads, block_size=257) + @test Array(x1) == Array(x2) + end + + rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) + for T in RAND_SCALAR_TYPES + x1 = array_from_host(zeros(T, 2048)) + x2 = array_from_host(zeros(T, 2048)) + AK.rand!(rng, x1; prefer_threads, block_size=64) + AK.rand!(rng2, x2; prefer_threads, block_size=64) + @test Array(x1) != Array(x2) + end - ref_view = zeros(T, length(view_x)) - _rand_fill_reference!(rng, ref_view) - @test collect(view_x) == ref_view + for T in (Float32, UInt64) + xnd = array_from_host(zeros(T, 7, 11, 5)) + _assert_rand_matches_reference!(rng, xnd; prefer_threads, block_size=128) + end + + if IS_CPU_BACKEND + for T in RAND_SCALAR_TYPES + base = zeros(T, 64) + view_x = @view base[2:2:end] + AK.rand!( + rng, view_x; + max_tasks=Threads.nthreads(), + min_elems=1, + prefer_threads=true + ) + ref_view = zeros(T, length(view_x)) + _rand_fill_reference!(rng, ref_view) + @test collect(view_x) == ref_view + end end end - nstats = 200_000 - xstats = array_from_host(zeros(Float32, nstats)) - AK.rand!(rng, xstats; prefer_threads, block_size=256) - xh = Array(xstats) - @test _is_unit_interval(xh) + @testset "rand! convenience" begin + Random.seed!(0xabcdef) + seed1 = rand(UInt64) + seed2 = rand(UInt64) - m = sum(xh) / nstats - v = sum((x - m)^2 for x in xh) / nstats - @test abs(m - 0.5) < 0.01 - @test abs(v - (1 / 12)) < 0.01 + ref1 = array_from_host(zeros(Float32, 1024)) + ref2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(AK.CounterRNG(seed1; alg=AK.Philox()), ref1; prefer_threads, block_size=64) + AK.rand!(AK.CounterRNG(seed2; alg=AK.Philox()), ref2; prefer_threads, block_size=64) - nbins = 16 - counts = zeros(Int, nbins) - for x in xh - ibin = Int(floor(x * nbins)) + 1 - ibin = min(ibin, nbins) - counts[ibin] += 1 - end - expected = nstats / nbins - max_rel_dev = maximum(abs(c - expected) / expected for c in counts) - @test max_rel_dev < 0.1 + Random.seed!(0xabcdef) + x1 = array_from_host(zeros(Float32, 1024)) + x2 = array_from_host(zeros(Float32, 1024)) + AK.rand!(x1; prefer_threads, block_size=64) + AK.rand!(x2; prefer_threads, block_size=64) + @test Array(x1) == Array(ref1) + @test Array(x2) == Array(ref2) - x16 = array_from_host(zeros(UInt16, 16)) - @test_throws ArgumentError AK.rand!(x16; prefer_threads) - @test_throws ArgumentError AK.rand!(rng, x16; prefer_threads) + x_bad = array_from_host(zeros(UInt16, 16)) + @test_throws ArgumentError AK.rand!(x_bad; prefer_threads) + @test_throws ArgumentError AK.rand!(AK.CounterRNG(0x1), x_bad; prefer_threads) + end end From 65caf10021c371500fc785e927da4ef00ee645f8 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 17 Mar 2026 00:16:49 +0000 Subject: [PATCH 05/20] ensure deteminism in convenience tests by avoiding race causing intermittent test failure. fence Float64 tests to CPU-only to avoid breaking CI on Metal and oneAPI --- Project.toml | 4 +++- src/AcceleratedKernels.jl | 1 + src/rand/rand.jl | 16 ++++++------- test/rand.jl | 48 +++++++++++++++++++++++---------------- 4 files changed, 41 insertions(+), 28 deletions(-) diff --git a/Project.toml b/Project.toml index 2fccea8b..60ddf3ab 100644 --- a/Project.toml +++ b/Project.toml @@ -1,13 +1,14 @@ name = "AcceleratedKernels" uuid = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" -authors = ["Andrei-Leonard Nicusan and contributors"] version = "0.4.3" +authors = ["Andrei-Leonard Nicusan and contributors"] [deps] ArgCheck = "dce04be8-c92d-5529-be00-80e4d2c0e197" GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" UnsafeAtomics = "013be700-e6cd-48c3-b4a1-df204f14c38f" [weakdeps] @@ -21,6 +22,7 @@ ArgCheck = "2" GPUArraysCore = "0.2.0" KernelAbstractions = "0.9.34" Markdown = "1" +Random = "1.11.0" UnsafeAtomics = "0.3.0" julia = "1.10" oneAPI = "1, 2" diff --git a/src/AcceleratedKernels.jl b/src/AcceleratedKernels.jl index 06a401ae..7262cbed 100644 --- a/src/AcceleratedKernels.jl +++ b/src/AcceleratedKernels.jl @@ -15,6 +15,7 @@ using ArgCheck: @argcheck using GPUArraysCore: AnyGPUArray, @allowscalar using KernelAbstractions using KernelAbstractions: @context +using Random import UnsafeAtomics diff --git a/src/rand/rand.jl b/src/rand/rand.jl index e62ba962..20a2fe8f 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -27,8 +27,8 @@ The default algorithm is `Philox()`. Constructors: - `CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox())` Uses an explicit non-negative seed. -- `CounterRNG(; alg::CounterRNGAlgorithm=SplitMix64())` - Auto-seeds once using `rand(UInt64)`. Reusing the same `CounterRNG` instance is deterministic +- `CounterRNG(; alg::CounterRNGAlgorithm=Philox())` + Auto-seeds once using `Random.rand(Random.default_rng(), UInt64)`. Reusing the same `CounterRNG` instance is deterministic for fixed seed, algorithm, array shape, and eltype. """ struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG @@ -44,7 +44,7 @@ end function CounterRNG(; alg::CounterRNGAlgorithm=Philox()) - CounterRNG(Base.rand(UInt64); alg) + CounterRNG(Random.rand(Random.default_rng(), UInt64); alg) end @@ -58,6 +58,9 @@ include("splitmix64.jl") include("philox.jl") include("threefry.jl") + + + """ rand!( rng::AbstractCounterRNG, @@ -83,11 +86,6 @@ Supported scalar element types are: - `Int32`, `Int64` - `Float32`, `Float64` -Semantics: -- Unsigned integers: raw random bit patterns of requested width. -- Signed integers: corresponding unsigned patterns reinterpreted as signed. -- Floats: mantissa-based conversion from `UInt32`/`UInt64` into `[0, 1)`, uniform over the - produced mantissa grid (not over all representable floats). """ function rand!( rng::AbstractCounterRNG, @@ -115,6 +113,8 @@ function rand!( end return x end + + function rand!( x::AbstractArray, args...; diff --git a/test/rand.jl b/test/rand.jl index e3f0bb60..1084637c 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,5 +1,9 @@ const RAND_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) -const RAND_SCALAR_TYPES = (UInt32, UInt64, Int32, Int64, Float32, Float64) +const RAND_SCALAR_TYPES_ALL = (UInt32, UInt64, Int32, Int64, Float32, Float64) +const RAND_SCALAR_TYPES_BACKEND = IS_CPU_BACKEND ? + RAND_SCALAR_TYPES_ALL : + (UInt32, UInt64, Int32, Int64, Float32) +const RUN_FLOAT64_RAND_TESTS = IS_CPU_BACKEND _is_unit_interval(v) = all(x -> !isnan(x) && zero(x) <= x < one(x), v) @@ -31,7 +35,7 @@ end @test_throws ArgumentError AK.CounterRNG(-1) Random.seed!(0x1234) - expected_seed = rand(UInt64) + expected_seed = Random.rand(Random.default_rng(), UInt64) Random.seed!(0x1234) rng_auto = AK.CounterRNG() @test rng_auto.seed == expected_seed @@ -63,7 +67,9 @@ end @test AK.raw_uint_type(Float32) === UInt32 @test AK.raw_uint_type(UInt64) === UInt64 @test AK.raw_uint_type(Int64) === UInt64 - @test AK.raw_uint_type(Float64) === UInt64 + if RUN_FLOAT64_RAND_TESTS + @test AK.raw_uint_type(Float64) === UInt64 + end @test AK.from_uint(UInt32, 0b1010 % UInt32) == 0b1010 % UInt32 @test AK.from_uint(UInt64, 0b1010 % UInt64) == 0b1010 % UInt64 @@ -73,9 +79,11 @@ end ) == Int64(-1) @test AK.uint32_to_unit_float32(UInt32(0)) == 0.0f0 - @test AK.uint64_to_unit_float64(UInt64(0)) == 0.0 @test 0.0f0 <= AK.uint32_to_unit_float32(typemax(UInt32)) < 1.0f0 - @test 0.0 <= AK.uint64_to_unit_float64(typemax(UInt64)) < 1.0 + if RUN_FLOAT64_RAND_TESTS + @test AK.uint64_to_unit_float64(UInt64(0)) == 0.0 + @test 0.0 <= AK.uint64_to_unit_float64(typemax(UInt64)) < 1.0 + end end @@ -110,7 +118,7 @@ end @testset "rand_scalar" begin rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) - for T in RAND_SCALAR_TYPES + for T in RAND_SCALAR_TYPES_BACKEND s0 = AK.rand_scalar(rng, UInt64(0), T) s1 = AK.rand_scalar(rng, UInt64(1), T) @test s0 isa T @@ -128,9 +136,11 @@ end @test AK.rand_scalar(rng, c, Float32) == AK.uint32_to_unit_float32( AK.rand_uint(rng, c, UInt32) ) - @test AK.rand_scalar(rng, c, Float64) == AK.uint64_to_unit_float64( - AK.rand_uint(rng, c, UInt64) - ) + if RUN_FLOAT64_RAND_TESTS + @test AK.rand_scalar(rng, c, Float64) == AK.uint64_to_unit_float64( + AK.rand_uint(rng, c, UInt64) + ) + end @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) end @@ -139,7 +149,7 @@ end lengths = (0, 1, 31, 32, 33, 257, 1024) rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) - for T in RAND_SCALAR_TYPES + for T in RAND_SCALAR_TYPES_BACKEND for len in lengths x = array_from_host(zeros(T, len)) _assert_rand_matches_reference!(rng, x; prefer_threads, block_size=64) @@ -149,7 +159,7 @@ end end end - for T in RAND_SCALAR_TYPES + for T in RAND_SCALAR_TYPES_BACKEND x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) AK.rand!(rng, x1; prefer_threads, block_size=64) @@ -158,7 +168,7 @@ end end rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) - for T in RAND_SCALAR_TYPES + for T in RAND_SCALAR_TYPES_BACKEND x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) AK.rand!(rng, x1; prefer_threads, block_size=64) @@ -172,7 +182,7 @@ end end if IS_CPU_BACKEND - for T in RAND_SCALAR_TYPES + for T in RAND_SCALAR_TYPES_BACKEND base = zeros(T, 64) view_x = @view base[2:2:end] AK.rand!( @@ -190,18 +200,18 @@ end @testset "rand! convenience" begin - Random.seed!(0xabcdef) - seed1 = rand(UInt64) - seed2 = rand(UInt64) - ref1 = array_from_host(zeros(Float32, 1024)) ref2 = array_from_host(zeros(Float32, 1024)) + x1 = array_from_host(zeros(Float32, 1024)) + x2 = array_from_host(zeros(Float32, 1024)) + + Random.seed!(0xabcdef) + seed1 = Random.rand(Random.default_rng(), UInt64) AK.rand!(AK.CounterRNG(seed1; alg=AK.Philox()), ref1; prefer_threads, block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) AK.rand!(AK.CounterRNG(seed2; alg=AK.Philox()), ref2; prefer_threads, block_size=64) Random.seed!(0xabcdef) - x1 = array_from_host(zeros(Float32, 1024)) - x2 = array_from_host(zeros(Float32, 1024)) AK.rand!(x1; prefer_threads, block_size=64) AK.rand!(x2; prefer_threads, block_size=64) @test Array(x1) == Array(ref1) From 3d1e0c05b2e6c5f6ddc2008ba3de5e1c6de37453 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 17 Mar 2026 00:25:28 +0000 Subject: [PATCH 06/20] fix Random dep for use with julia v1.10 --- Project.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Project.toml b/Project.toml index 60ddf3ab..4a3a6b34 100644 --- a/Project.toml +++ b/Project.toml @@ -22,7 +22,7 @@ ArgCheck = "2" GPUArraysCore = "0.2.0" KernelAbstractions = "0.9.34" Markdown = "1" -Random = "1.11.0" +Random = "1" UnsafeAtomics = "0.3.0" julia = "1.10" oneAPI = "1, 2" From 48cd247b86a55b5fc4c896c151f6bb3f128e47d2 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 17 Mar 2026 21:28:32 +0000 Subject: [PATCH 07/20] add Bool scalar support with isodd() on a UInt32 --- docs/src/api/rand.md | 6 ++++-- src/rand/rand.jl | 8 ++++++++ src/rand/utilities.jl | 5 ++++- test/rand.jl | 17 +++++++++++++---- 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 2fa468f1..d9ffc713 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -4,19 +4,21 @@ Counter-based random generation for CPU and GPU backends with deterministic beha `seed`, algorithm, array shape, and eltype. Use an explicit `CounterRNG(seed; alg=...)` when reproducibility matters. For convenience, -`AK.rand!(x)` creates a fresh `CounterRNG()` on each call using one auto-seeded `Base.rand(UInt64)` -draw, so repeated calls usually produce different outputs. +`AK.rand!(x)` creates a fresh `CounterRNG()` on each call using one auto-seeded +`Base.rand(Random.default_rng(), UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. Supported output element types: - `UInt32`, `UInt64` - `Int32`, `Int64` - `Float32`, `Float64` +- `Bool` The core of the random number generation produces a `UInt` of the requested scalar width. That `UInt` is then either: - Unsigned integers: returned as-is - Signed integers: reinterpreted as a signed integer bit pattern. - Floats: mantissa construction into a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)). +- Bool: `true` if the `UInt` draw is odd (`isodd(u)`), otherwise `false`. Algorithms currently available: - `SplitMix64` ([read more](https://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64)) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 20a2fe8f..fdd70763 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -85,6 +85,14 @@ Supported scalar element types are: - `UInt32`, `UInt64` - `Int32`, `Int64` - `Float32`, `Float64` +- `Bool` + +Semantics: +- Unsigned integers: raw random bit patterns of requested width. +- Signed integers: corresponding unsigned patterns reinterpreted as signed. +- Floats: mantissa-based conversion from `UInt32`/`UInt64` into `[0, 1)`, uniform over the + produced mantissa grid (not over all representable floats). +- Bool: `true` if the raw `UInt` draw is odd (`isodd(u)`), otherwise `false`. """ function rand!( diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 2623c9d2..c9f2cc5d 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -18,6 +18,7 @@ const ALLOWED_RAND_SCALARS = Union{ UInt32, UInt64, Int32, Int64, Float32, Float64, + Bool } @@ -27,6 +28,7 @@ const ALLOWED_RAND_SCALARS = Union{ @inline raw_uint_type(::Type{UInt64}) = UInt64 @inline raw_uint_type(::Type{Int64}) = UInt64 @inline raw_uint_type(::Type{Float64}) = UInt64 +@inline raw_uint_type(::Type{Bool}) = UInt32 @inline from_uint(::Type{UInt32}, u::UInt32)::UInt32 = u @@ -35,6 +37,7 @@ const ALLOWED_RAND_SCALARS = Union{ @inline from_uint(::Type{Int64}, u::UInt64)::Int64 = reinterpret(Int64, u) @inline from_uint(::Type{Float32}, u::UInt32)::Float32 = uint32_to_unit_float32(u) @inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) +@inline from_uint(::Type{Bool}, u::UInt32)::Bool = isodd(u) #= @@ -71,7 +74,7 @@ end @inline function rand_scalar(::AbstractCounterRNG, ::UInt64, ::Type{T}) where {T} throw(ArgumentError( - "Unsupported random scalar type $(T). Supported: UInt32, UInt64, Int32, Int64, Float32, Float64." + "Unsupported random scalar type $(T). Supported: $(ALLOWED_RAND_SCALARS)" )) end diff --git a/test/rand.jl b/test/rand.jl index 1084637c..a9d0c462 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,8 +1,8 @@ const RAND_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) -const RAND_SCALAR_TYPES_ALL = (UInt32, UInt64, Int32, Int64, Float32, Float64) +const RAND_SCALAR_TYPES_ALL = (UInt32, UInt64, Int32, Int64, Float32, Float64, Bool) const RAND_SCALAR_TYPES_BACKEND = IS_CPU_BACKEND ? RAND_SCALAR_TYPES_ALL : - (UInt32, UInt64, Int32, Int64, Float32) + (UInt32, UInt64, Int32, Int64, Float32, Bool) const RUN_FLOAT64_RAND_TESTS = IS_CPU_BACKEND @@ -67,6 +67,7 @@ end @test AK.raw_uint_type(Float32) === UInt32 @test AK.raw_uint_type(UInt64) === UInt64 @test AK.raw_uint_type(Int64) === UInt64 + @test AK.raw_uint_type(Bool) === UInt32 if RUN_FLOAT64_RAND_TESTS @test AK.raw_uint_type(Float64) === UInt64 end @@ -77,6 +78,8 @@ end @test AK.from_uint( Int64, 0b1111111111111111111111111111111111111111111111111111111111111111 % UInt64 ) == Int64(-1) + @test AK.from_uint(Bool, UInt32(0)) == false + @test AK.from_uint(Bool, UInt32(1)) == true @test AK.uint32_to_unit_float32(UInt32(0)) == 0.0f0 @test 0.0f0 <= AK.uint32_to_unit_float32(typemax(UInt32)) < 1.0f0 @@ -123,7 +126,9 @@ end s1 = AK.rand_scalar(rng, UInt64(1), T) @test s0 isa T @test s1 isa T - @test s0 != s1 + if T !== Bool + @test s0 != s1 + end if T <: AbstractFloat @test zero(T) <= s0 < one(T) @test zero(T) <= s1 < one(T) @@ -136,11 +141,15 @@ end @test AK.rand_scalar(rng, c, Float32) == AK.uint32_to_unit_float32( AK.rand_uint(rng, c, UInt32) ) + @test AK.rand_scalar(rng, c, Bool) == isodd(AK.rand_uint(rng, c, UInt32)) if RUN_FLOAT64_RAND_TESTS @test AK.rand_scalar(rng, c, Float64) == AK.uint64_to_unit_float64( AK.rand_uint(rng, c, UInt64) ) end + bools = [AK.rand_scalar(rng, UInt64(i), Bool) for i in 0:511] + @test any(identity, bools) + @test any(!, bools) @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) end @@ -176,7 +185,7 @@ end @test Array(x1) != Array(x2) end - for T in (Float32, UInt64) + for T in (Float32, UInt64, Bool) xnd = array_from_host(zeros(T, 7, 11, 5)) _assert_rand_matches_reference!(rng, xnd; prefer_threads, block_size=128) end From 68e03c3b98f5a703a422a03e0ab2e2e88f1ec53c Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 17 Mar 2026 22:04:13 +0000 Subject: [PATCH 08/20] add support for Float16, UInt8, UInt16, Int8, Int16 (was bored) --- Project.toml | 2 +- docs/src/api/rand.md | 16 ++++++++-------- src/rand/rand.jl | 6 +++--- src/rand/utilities.jl | 27 ++++++++++++++++++++++++--- test/rand.jl | 40 ++++++++++++++++++++++++++++++++++------ 5 files changed, 70 insertions(+), 21 deletions(-) diff --git a/Project.toml b/Project.toml index 4a3a6b34..b0c601d9 100644 --- a/Project.toml +++ b/Project.toml @@ -1,7 +1,7 @@ name = "AcceleratedKernels" uuid = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" -version = "0.4.3" authors = ["Andrei-Leonard Nicusan and contributors"] +version = "0.4.3" [deps] ArgCheck = "dce04be8-c92d-5529-be00-80e4d2c0e197" diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index d9ffc713..93ed339a 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -5,18 +5,18 @@ Counter-based random generation for CPU and GPU backends with deterministic beha Use an explicit `CounterRNG(seed; alg=...)` when reproducibility matters. For convenience, `AK.rand!(x)` creates a fresh `CounterRNG()` on each call using one auto-seeded -`Base.rand(Random.default_rng(), UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. +`Random.rand(Random.default_rng(), UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. -Supported output element types: -- `UInt32`, `UInt64` -- `Int32`, `Int64` -- `Float32`, `Float64` +Supported element types: +- `UInt8`, `UInt16`, `UInt32`, `UInt64` +- `Int8`, `Int16`, `Int32`, `Int64` +- `Float16`, `Float32`, `Float64` - `Bool` -The core of the random number generation produces a `UInt` of the requested scalar width. +The core of the random number generation produces either a `UInt32` or `UInt64` depending on the width of the requested element type. That `UInt` is then either: -- Unsigned integers: returned as-is -- Signed integers: reinterpreted as a signed integer bit pattern. +- Unsigned integers: returned as-is or truncated if necessary. +- Signed integers: reinterpreted as a signed integer bit pattern and truncated if necessary. - Floats: mantissa construction into a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)). - Bool: `true` if the `UInt` draw is odd (`isodd(u)`), otherwise `false`. diff --git a/src/rand/rand.jl b/src/rand/rand.jl index fdd70763..dc48f03c 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -82,9 +82,9 @@ Fill `x` in-place with pseudo-random values using a stateless counter-based RNG. counter is exactly `UInt64(i - 1)` in linear indexing order. Supported scalar element types are: -- `UInt32`, `UInt64` -- `Int32`, `Int64` -- `Float32`, `Float64` +- `UInt8`, `UInt16`, `UInt32`, `UInt64` +- `Int8`, `Int16`, `Int32`, `Int64` +- `Float16`, `Float32`, `Float64` - `Bool` Semantics: diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index c9f2cc5d..3d5dab7c 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -15,15 +15,20 @@ # Internal scalar eltypes currently supported by rand!. const ALLOWED_RAND_SCALARS = Union{ - UInt32, UInt64, - Int32, Int64, - Float32, Float64, + UInt8, UInt16, UInt32, UInt64, + Int8, Int16, Int32, Int64, + Float16, Float32, Float64, Bool } +@inline raw_uint_type(::Type{UInt8}) = UInt32 +@inline raw_uint_type(::Type{UInt16}) = UInt32 @inline raw_uint_type(::Type{UInt32}) = UInt32 +@inline raw_uint_type(::Type{Int8}) = UInt32 +@inline raw_uint_type(::Type{Int16}) = UInt32 @inline raw_uint_type(::Type{Int32}) = UInt32 +@inline raw_uint_type(::Type{Float16}) = UInt32 @inline raw_uint_type(::Type{Float32}) = UInt32 @inline raw_uint_type(::Type{UInt64}) = UInt64 @inline raw_uint_type(::Type{Int64}) = UInt64 @@ -31,10 +36,15 @@ const ALLOWED_RAND_SCALARS = Union{ @inline raw_uint_type(::Type{Bool}) = UInt32 +@inline from_uint(::Type{UInt8}, u::UInt32)::UInt8 = trunc(UInt8, u >> 24) +@inline from_uint(::Type{UInt16}, u::UInt32)::UInt16 = trunc(UInt16, u >> 16) @inline from_uint(::Type{UInt32}, u::UInt32)::UInt32 = u @inline from_uint(::Type{UInt64}, u::UInt64)::UInt64 = u +@inline from_uint(::Type{Int8}, u::UInt32)::Int8 = reinterpret(Int8, trunc(UInt8, u >> 24)) +@inline from_uint(::Type{Int16}, u::UInt32)::Int16 = reinterpret(Int16, trunc(UInt16, u >> 16)) @inline from_uint(::Type{Int32}, u::UInt32)::Int32 = reinterpret(Int32, u) @inline from_uint(::Type{Int64}, u::UInt64)::Int64 = reinterpret(Int64, u) +@inline from_uint(::Type{Float16}, u::UInt32)::Float16 = uint32_to_unit_float16(u) @inline from_uint(::Type{Float32}, u::UInt32)::Float32 = uint32_to_unit_float32(u) @inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) @inline from_uint(::Type{Bool}, u::UInt32)::Bool = isodd(u) @@ -81,6 +91,17 @@ end +# Convert random UInt32 bits to Float16 in [0, 1) by mantissa construction. +@inline function uint32_to_unit_float16(u::UInt32)::Float16 + # Keep 10 random bits for the mantissa (drop 22 rightmost bits from the UInt32) + # and combine with the bit pattern of Float16(1.0) (sign=0, exponent=15). + bits = UInt16(0x3c00) | UInt16(u >> 22) + + # Interpret as 1.mantissa, then subtract 1 for [0, 1) + return reinterpret(Float16, bits) - Float16(1) +end + + # Convert random UInt32 bits to Float32 in [0, 1) by mantissa construction. @inline function uint32_to_unit_float32(u::UInt32)::Float32 # Keep 23 random bits for the mantissa (drop 9 rightmost bits from the UInt32) diff --git a/test/rand.jl b/test/rand.jl index a9d0c462..9e03e59f 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,8 +1,13 @@ const RAND_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) -const RAND_SCALAR_TYPES_ALL = (UInt32, UInt64, Int32, Int64, Float32, Float64, Bool) +const RAND_SCALAR_TYPES_ALL = ( + UInt8, UInt16, UInt32, UInt64, + Int8, Int16, Int32, Int64, + Float16, Float32, Float64, + Bool, +) const RAND_SCALAR_TYPES_BACKEND = IS_CPU_BACKEND ? RAND_SCALAR_TYPES_ALL : - (UInt32, UInt64, Int32, Int64, Float32, Bool) + (UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float16, Float32, Bool) const RUN_FLOAT64_RAND_TESTS = IS_CPU_BACKEND @@ -62,8 +67,13 @@ end @test AK._counter_from_index(1) == UInt64(0) @test AK._counter_from_index(17) == UInt64(16) + @test AK.raw_uint_type(UInt8) === UInt32 + @test AK.raw_uint_type(UInt16) === UInt32 @test AK.raw_uint_type(UInt32) === UInt32 + @test AK.raw_uint_type(Int8) === UInt32 + @test AK.raw_uint_type(Int16) === UInt32 @test AK.raw_uint_type(Int32) === UInt32 + @test AK.raw_uint_type(Float16) === UInt32 @test AK.raw_uint_type(Float32) === UInt32 @test AK.raw_uint_type(UInt64) === UInt64 @test AK.raw_uint_type(Int64) === UInt64 @@ -72,15 +82,22 @@ end @test AK.raw_uint_type(Float64) === UInt64 end + @test AK.from_uint(UInt8, UInt32(0xabcdef01)) == UInt8(0xab) + @test AK.from_uint(UInt16, UInt32(0xabcdef01)) == UInt16(0xabcd) @test AK.from_uint(UInt32, 0b1010 % UInt32) == 0b1010 % UInt32 @test AK.from_uint(UInt64, 0b1010 % UInt64) == 0b1010 % UInt64 + @test AK.from_uint(Int8, UInt32(0xff000000)) == Int8(-1) + @test AK.from_uint(Int16, UInt32(0xffff0000)) == Int16(-1) @test AK.from_uint(Int32, 0b11111111111111111111111111111111 % UInt32) == Int32(-1) @test AK.from_uint( Int64, 0b1111111111111111111111111111111111111111111111111111111111111111 % UInt64 ) == Int64(-1) + @test AK.from_uint(Float16, UInt32(0)) == Float16(0) @test AK.from_uint(Bool, UInt32(0)) == false @test AK.from_uint(Bool, UInt32(1)) == true + @test AK.uint32_to_unit_float16(UInt32(0)) == Float16(0) + @test Float16(0) <= AK.uint32_to_unit_float16(typemax(UInt32)) < Float16(1) @test AK.uint32_to_unit_float32(UInt32(0)) == 0.0f0 @test 0.0f0 <= AK.uint32_to_unit_float32(typemax(UInt32)) < 1.0f0 if RUN_FLOAT64_RAND_TESTS @@ -126,7 +143,7 @@ end s1 = AK.rand_scalar(rng, UInt64(1), T) @test s0 isa T @test s1 isa T - if T !== Bool + if !(T in (Bool, Float16, UInt8, UInt16, Int8, Int16)) @test s0 != s1 end if T <: AbstractFloat @@ -136,8 +153,19 @@ end end c = UInt64(42) + @test AK.rand_scalar(rng, c, UInt8) == trunc(UInt8, AK.rand_uint(rng, c, UInt32) >> 24) + @test AK.rand_scalar(rng, c, UInt16) == trunc(UInt16, AK.rand_uint(rng, c, UInt32) >> 16) + @test AK.rand_scalar( + rng, c, Int8 + ) == reinterpret(Int8, trunc(UInt8, AK.rand_uint(rng, c, UInt32) >> 24)) + @test AK.rand_scalar( + rng, c, Int16 + ) == reinterpret(Int16, trunc(UInt16, AK.rand_uint(rng, c, UInt32) >> 16)) @test AK.rand_scalar(rng, c, Int32) == reinterpret(Int32, AK.rand_uint(rng, c, UInt32)) @test AK.rand_scalar(rng, c, Int64) == reinterpret(Int64, AK.rand_uint(rng, c, UInt64)) + @test AK.rand_scalar(rng, c, Float16) == AK.uint32_to_unit_float16( + AK.rand_uint(rng, c, UInt32) + ) @test AK.rand_scalar(rng, c, Float32) == AK.uint32_to_unit_float32( AK.rand_uint(rng, c, UInt32) ) @@ -150,7 +178,7 @@ end bools = [AK.rand_scalar(rng, UInt64(i), Bool) for i in 0:511] @test any(identity, bools) @test any(!, bools) - @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt16) + @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt128) end @@ -185,7 +213,7 @@ end @test Array(x1) != Array(x2) end - for T in (Float32, UInt64, Bool) + for T in (Float16, Float32, UInt64, Bool) xnd = array_from_host(zeros(T, 7, 11, 5)) _assert_rand_matches_reference!(rng, xnd; prefer_threads, block_size=128) end @@ -226,7 +254,7 @@ end @test Array(x1) == Array(ref1) @test Array(x2) == Array(ref2) - x_bad = array_from_host(zeros(UInt16, 16)) + x_bad = zeros(UInt128, 16) @test_throws ArgumentError AK.rand!(x_bad; prefer_threads) @test_throws ArgumentError AK.rand!(AK.CounterRNG(0x1), x_bad; prefer_threads) end From 8677d84d4b15592a31cf5a3e73587fe7c77b454b Mon Sep 17 00:00:00 2001 From: fjbarter Date: Wed, 18 Mar 2026 16:29:00 +0000 Subject: [PATCH 09/20] Add more faithful seed-key mapping for Philox, and improve thoroughness of docs --- docs/src/api/rand.md | 20 ++++++++++++++++++-- src/rand/philox.jl | 4 +--- src/rand/rand.jl | 2 +- src/rand/{splitmix64.jl => splitmix.jl} | 6 ++++++ 4 files changed, 26 insertions(+), 6 deletions(-) rename src/rand/{splitmix64.jl => splitmix.jl} (82%) diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 93ed339a..997e407f 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -25,8 +25,24 @@ Algorithms currently available: - `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) - `Threefry` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) -`Philox` is the default algorithm for `CounterRNG()`, as it is more thoroughly -statistically tested and measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an RTX +Statistical-testing note: +- Published/reference versions of `SplitMix64`, `Philox`, and `Threefry` are reported to pass + TestU01 BigCrush. +- These results refer to specific constructions and test setups; wrapper choices (such as + seed/key mapping conventions) can change bitwise output streams. +- These generators are not intended to be cryptographically secure. + +Philox keying note: +- AK uses `Philox2x32` internally (one 32-bit Philox key word). +- Users can pass any non-negative `Integer` seed; AK normalises to `UInt64` then derives the + 32-bit Philox key via a SplitMix-based mapping. +- This is a deliberate wrapper choice for ease of use (simple `seed` API with deterministic + streams), not a change to the Philox round function itself. +- Therefore, AK Philox streams are deterministic and high-quality, but not guaranteed to be + bit-for-bit identical to a raw Random123 Philox stream unless the same seed-to-key mapping and + counter convention are used. + +`Philox` is the default algorithm for `CounterRNG()`, as it is very thorough and very fast; it has been measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an Nvidia GeForce RTX 5060 (advertised 448 GB/s), i.e. effectively memory-bound throughput. Examples: diff --git a/src/rand/philox.jl b/src/rand/philox.jl index bdebc8e5..37149f1a 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -24,9 +24,7 @@ end x0 = _u32_lo(counter) x1 = _u32_hi(counter) - seed = UInt64(rng.seed) - k0 = _u32_lo(seed) - x1 = xor(x1, _u32_hi(seed)) + k0 = splitmix32_from_u64(UInt64(rng.seed)) @inbounds for _ in 1:PHILOX_ROUNDS x0, x1 = _philox2x32_round(x0, x1, k0) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index dc48f03c..d1fcb42e 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -54,7 +54,7 @@ end include("utilities.jl") # Algorithm-specific integer generators -include("splitmix64.jl") +include("splitmix.jl") include("philox.jl") include("threefry.jl") diff --git a/src/rand/splitmix64.jl b/src/rand/splitmix.jl similarity index 82% rename from src/rand/splitmix64.jl rename to src/rand/splitmix.jl index d169b738..8d7992b0 100644 --- a/src/rand/splitmix64.jl +++ b/src/rand/splitmix.jl @@ -16,6 +16,12 @@ const SPLITMIX64_MIX_B = UInt64(0x94d049bb133111eb) end +# Derive a 32-bit seed word from a 64-bit seed using SplitMix64 mixing. +@inline function splitmix32_from_u64(seed::UInt64)::UInt32 + return _u32_hi(_splitmix64_mix(seed + SPLITMIX64_INCREMENT)) +end + + # Natural SplitMix64 output path: compute 64 random bits directly from one counter @inline function rand_uint( rng::CounterRNG{<:SplitMix64}, From d687e2a84ab7816422273aea86b2a59b626177d8 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 23 Mar 2026 01:40:44 +0000 Subject: [PATCH 10/20] streaming rng by now including an offset, incremented by length(x) when AK.rand!(x) is called. This gives stream-like behaviour without any on-device state but still faster than CURAND. Add RNGTest in prototyping for BigCrush and SmallCrush (Philox, SM64, and Threefry all now confirmed to pass in the AK implementation) --- docs/src/api/rand.md | 52 ++++++-- prototype/RNGTest/Project.toml | 3 + prototype/RNGTest/README.md | 33 +++++ prototype/RNGTest/run_bigcrush.jl | 26 ++++ prototype/RNGTest/run_smallcrush.jl | 23 ++++ prototype/RNGTest/stream.jl | 80 ++++++++++++ prototype/rand/Project.toml | 1 + src/rand/philox.jl | 14 +- src/rand/rand.jl | 95 ++++++++++---- src/rand/splitmix.jl | 9 +- src/rand/threefry.jl | 13 +- src/rand/utilities.jl | 24 ++-- test/rand.jl | 195 ++++++++++++++++++++++------ 13 files changed, 459 insertions(+), 109 deletions(-) create mode 100644 prototype/RNGTest/Project.toml create mode 100644 prototype/RNGTest/README.md create mode 100644 prototype/RNGTest/run_bigcrush.jl create mode 100644 prototype/RNGTest/run_smallcrush.jl create mode 100644 prototype/RNGTest/stream.jl diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 997e407f..5c5596ec 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -1,11 +1,35 @@ ### Random Number Generation -Counter-based random generation for CPU and GPU backends with deterministic behavior for fixed -`seed`, algorithm, array shape, and eltype. +Counter-based random generation for CPU and GPU backends with deterministic stream behavior for +fixed `seed`, algorithm, and call sequence. -Use an explicit `CounterRNG(seed; alg=...)` when reproducibility matters. For convenience, -`AK.rand!(x)` creates a fresh `CounterRNG()` on each call using one auto-seeded -`Random.rand(Random.default_rng(), UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. +`CounterRNG` carries an internal `offset` (starting at `0`) that advances by `length(v)` on each +`AK.rand!(rng, v)` call. This means chunked fills are stream-consistent: +- filling `100` then `100` elements yields the same `200` values as one `200`-element fill. +- calls that share the same `CounterRNG` instance concurrently are not thread-safe. +- call `AK.reset!(rng)` to rewind a mutable offset-bearing RNG back to offset `0x0`. + +`AK.rand!` also accepts custom `AbstractCounterRNG` implementations: +- if they have a mutable `offset` field, streaming advancement is applied +- if they have no `offset` field, each call behaves statelessly from counter `0` +- if they have an immutable `offset` field, that offset is used as a fixed start and is not advanced + +Use an explicit `CounterRNG` when reproducibility is required. For +convenience, +`AK.rand!(v)` creates a fresh `CounterRNG()` on each call using one auto-seeded +`Base.rand(UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. + +`AK.reset!(rng)` rewinds offset to `0x0` for mutable RNGs that have an `offset` field. + +Custom RNGs: +- Define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm`. +- Define an RNG type `MyRNG <: AK.AbstractCounterRNG{MyAlg}` with fields `seed` and `alg`. +- Add a mutable `offset::UInt64` field if you want stream advancement across calls; omit it for stateless calls from counter `0`. +- Implement typed `rand_uint` methods: + - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` + - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` + +Both widths should be implemented so `AK.rand!` supports all integer/float output types without falling back or error. Supported element types: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -26,10 +50,7 @@ Algorithms currently available: - `Threefry` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) Statistical-testing note: -- Published/reference versions of `SplitMix64`, `Philox`, and `Threefry` are reported to pass - TestU01 BigCrush. -- These results refer to specific constructions and test setups; wrapper choices (such as - seed/key mapping conventions) can change bitwise output streams. +- In this repository, `SplitMix64`, `Philox`, and `Threefry` have passed TestU01 BigCrush - These generators are not intended to be cryptographically secure. Philox keying note: @@ -42,7 +63,7 @@ Philox keying note: bit-for-bit identical to a raw Random123 Philox stream unless the same seed-to-key mapping and counter convention are used. -`Philox` is the default algorithm for `CounterRNG()`, as it is very thorough and very fast; it has been measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an Nvidia GeForce RTX +`Philox` is the default algorithm for `CounterRNG()` because it is thorough and very fast; it has been measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an Nvidia GeForce RTX 5060 (advertised 448 GB/s), i.e. effectively memory-bound throughput. Examples: @@ -52,8 +73,14 @@ using oneAPI # Reproducible rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) -x = oneArray{Float32}(undef, 1024) -AK.rand!(rng, x) +v = oneArray{Float32}(undef, 1024) +AK.rand!(rng, v) + +# Stream-consistent chunking +v1 = oneArray{Float32}(undef, 100) +v2 = oneArray{Float32}(undef, 100) +AK.rand!(rng, v1) +AK.rand!(rng, v2) # Convenience (fresh auto-seeded RNG on each call) y = oneArray{Float32}(undef, 1024) @@ -62,5 +89,6 @@ AK.rand!(y) ```@docs AcceleratedKernels.CounterRNG +AcceleratedKernels.reset! AcceleratedKernels.rand! ``` diff --git a/prototype/RNGTest/Project.toml b/prototype/RNGTest/Project.toml new file mode 100644 index 00000000..7536db29 --- /dev/null +++ b/prototype/RNGTest/Project.toml @@ -0,0 +1,3 @@ +[deps] +AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" +RNGTest = "97cc5700-e6cb-5ca1-8fb2-7f6b45264ecd" diff --git a/prototype/RNGTest/README.md b/prototype/RNGTest/README.md new file mode 100644 index 00000000..2bc6a7b6 --- /dev/null +++ b/prototype/RNGTest/README.md @@ -0,0 +1,33 @@ +# AK + RNGTest SmallCrush Prototype + +This folder provides a chunked random stream generator based on `AcceleratedKernels.jl` that can be fed into `RNGTest.jl`. + +The stream is deterministic and effectively unbounded: +- each refill generates `chunk` random `UInt64` values with `AK.rand!` +- each refill advances one persistent `CounterRNG` stream offset +- this is a practical chunked stream for RNGTest callback mode + +`RNGTest.jl` (in this local checkout) expects a callback returning `Float64` in `[0,1]`, so `UInt64` words are mapped to `Float64` via top-53-bit scaling. + +Current status in this harness: `SplitMix64`, `Philox`, and `Threefry` all pass BigCrush using `run_bigcrush.jl`. + +## Run SmallCrush + +From this directory: + +```powershell +julia --project=. run_smallcrush.jl +``` + +## Run BigCrush + +```powershell +julia --project=. run_bigcrush.jl +``` + +Notes: +- Configure `ALG`, `SEED`, and `CHUNK` at the top of + `run_smallcrush.jl` / `run_bigcrush.jl`. +- The stream refills directly into host scratch using `AK.rand!` on CPU. +- `chunk` controls refill amortization and memory usage. +- `chunk=100000000` means ~800 MB host scratch (`UInt64`). diff --git a/prototype/RNGTest/run_bigcrush.jl b/prototype/RNGTest/run_bigcrush.jl new file mode 100644 index 00000000..a1298a02 --- /dev/null +++ b/prototype/RNGTest/run_bigcrush.jl @@ -0,0 +1,26 @@ +using RNGTest + +include("stream.jl") + + +const ALG = :philox +const SEED = 0x1234 +const CHUNK = 10_000_000 +const HOST_SCRATCH = Vector{UInt64}(undef, CHUNK) + + +stream = AKUInt64Stream( + HOST_SCRATCH; + seed=SEED, + alg=ALG, + start_counter=UInt64(0), +) +gen = make_rngtest_generator!(stream) +genname = "AK_Vector_$(ALG)_seed$(SEED)" + +println("Beginning BigCrush. This may take hours...") + +RNGTest.bigcrushTestU01(gen, genname) + +println("refills: ", stream.refill_count) +println("numbers consumed (approx): ", (stream.refill_count - 1) * stream.chunk + (stream.idx - 1)) diff --git a/prototype/RNGTest/run_smallcrush.jl b/prototype/RNGTest/run_smallcrush.jl new file mode 100644 index 00000000..db1251cb --- /dev/null +++ b/prototype/RNGTest/run_smallcrush.jl @@ -0,0 +1,23 @@ +using RNGTest + +include("stream.jl") + + +const ALG = :philox +const SEED = 0x1234 +const CHUNK = 100_000_000 +const HOST_SCRATCH = Vector{UInt64}(undef, CHUNK) + + +stream = AKUInt64Stream( + HOST_SCRATCH; + seed=SEED, + alg=ALG, + start_counter=UInt64(0), +) +gen = make_rngtest_generator!(stream) +genname = "AK_Vector_$(ALG)_seed$(SEED)" + +println("Beginning SmallCrush...") + +RNGTest.smallcrushTestU01(gen, genname) diff --git a/prototype/RNGTest/stream.jl b/prototype/RNGTest/stream.jl new file mode 100644 index 00000000..ba65ce9c --- /dev/null +++ b/prototype/RNGTest/stream.jl @@ -0,0 +1,80 @@ +import AcceleratedKernels as AK + + +function make_rng(seed::Integer, alg::Symbol; offset::Integer=0) + if alg === :philox + return AK.CounterRNG(seed; alg=AK.Philox(), offset=offset) + elseif alg === :threefry + return AK.CounterRNG(seed; alg=AK.Threefry(), offset=offset) + elseif alg === :splitmix64 + return AK.CounterRNG(seed; alg=AK.SplitMix64(), offset=offset) + end + throw(ArgumentError("alg must be :philox, :threefry, or :splitmix64; got $alg")) +end + + +mutable struct AKUInt64Stream{R <: AK.AbstractCounterRNG} + rng::R + chunk::Int + idx::Int + host_scratch::Vector{UInt64} + refill_count::Int +end + + +function AKUInt64Stream( + host_scratch::Vector{UInt64}; + seed::Integer=0x1234, + alg::Symbol=:philox, + start_counter::UInt64=0x0000000000000000, +) + chunk = length(host_scratch) + chunk > 0 || throw(ArgumentError("host_scratch must be non-empty")) + rng = make_rng(seed, alg; offset=start_counter) + + return AKUInt64Stream( + rng, + chunk, + chunk + 1, + host_scratch, + 0, + ) +end + + +@inline _u01_from_u64(u::UInt64)::Float64 = Float64(u >>> 11) * 0x1.0p-53 + + +function _fill_chunk!(s::AKUInt64Stream) + AK.rand!(s.rng, s.host_scratch) + return nothing +end + + +function refill!(s::AKUInt64Stream) + _fill_chunk!(s) + s.idx = 1 + s.refill_count += 1 + return s +end + + +function next_u64!(s::AKUInt64Stream)::UInt64 + if s.idx > s.chunk + refill!(s) + end + @inbounds u = s.host_scratch[s.idx] + s.idx += 1 + return u +end + + +@inline next_float64!(s::AKUInt64Stream)::Float64 = _u01_from_u64(next_u64!(s)) + + +function make_rngtest_generator!(s::AKUInt64Stream) + if s.idx > s.chunk + refill!(s) + end + return () -> next_float64!(s) +end diff --git a/prototype/rand/Project.toml b/prototype/rand/Project.toml index 7e92c899..7757b4d8 100644 --- a/prototype/rand/Project.toml +++ b/prototype/rand/Project.toml @@ -2,5 +2,6 @@ AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" +Cthulhu = "f68482b8-f384-11e8-15f7-abe071a5a75f" PProf = "e4faabce-9ead-11e9-39d9-4379958e3056" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/src/rand/philox.jl b/src/rand/philox.jl index 37149f1a..61e5f97b 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -18,13 +18,13 @@ end # Evaluate one Philox block at `counter`, returning two 32-bit lanes `(x0, x1)` @inline function _philox2x32_block( - rng::CounterRNG{<:Philox}, + seed::UInt64, counter::UInt64, )::Tuple{UInt32, UInt32} x0 = _u32_lo(counter) x1 = _u32_hi(counter) - k0 = splitmix32_from_u64(UInt64(rng.seed)) + k0 = splitmix32_from_u64(seed) @inbounds for _ in 1:PHILOX_ROUNDS x0, x1 = _philox2x32_round(x0, x1, k0) @@ -37,21 +37,23 @@ end # Return lane 0 from the single Philox block at `counter` @inline function rand_uint( - rng::CounterRNG{<:Philox}, + seed::UInt64, + alg::Philox, counter::UInt64, ::Type{UInt32}, )::UInt32 - x0, _ = _philox2x32_block(rng, counter) + x0, _ = _philox2x32_block(seed, counter) return x0 end # Build UInt64 from the two lanes `(x0, x1)` of the same Philox block at `counter` @inline function rand_uint( - rng::CounterRNG{<:Philox}, + seed::UInt64, + alg::Philox, counter::UInt64, ::Type{UInt64}, )::UInt64 - x0, x1 = _philox2x32_block(rng, counter) + x0, x1 = _philox2x32_block(seed, counter) return _u64_from_u32s(x0, x1) end diff --git a/src/rand/rand.jl b/src/rand/rand.jl index d1fcb42e..229a8991 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -1,50 +1,73 @@ """ - abstract type AbstractCounterRNG end abstract type CounterRNGAlgorithm end + abstract type AbstractCounterRNG{A <: CounterRNGAlgorithm} end RNG interface for counter-based random generation with AcceleratedKernels. """ -abstract type AbstractCounterRNG end abstract type CounterRNGAlgorithm end +abstract type AbstractCounterRNG{A <: CounterRNGAlgorithm} end """ CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) -Stateless counter-based RNG configuration for [`rand!`](@ref). +Counter-based RNG for [`rand!`](@ref). -`CounterRNG` is immutable and does not hold mutable thread-local or global state. Each generated -value is a pure function of: +`CounterRNG` stores: - `seed` -- logical linear element index - algorithm (`alg`) +- stream `offset` The default algorithm is `Philox()`. `seed` may be any non-negative `Integer`. It is normalised to `UInt64` internally. +`offset` is initialised to `0` by default and advances by `length(v)` after each [`rand!`](@ref) +call. Constructors: -- `CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox())` - Uses an explicit non-negative seed. -- `CounterRNG(; alg::CounterRNGAlgorithm=Philox())` - Auto-seeds once using `Random.rand(Random.default_rng(), UInt64)`. Reusing the same `CounterRNG` instance is deterministic - for fixed seed, algorithm, array shape, and eltype. +- `CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0)` + Uses an explicit non-negative seed and offset. +- `CounterRNG(; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0)` + Auto-seeds once using `Base.rand(UInt64)`, with default `offset == 0`. """ -struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG +mutable struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG{A} seed::UInt64 alg::A + offset::UInt64 end -function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) +function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0) @argcheck seed >= 0 "Seed must be a non-negative integer" - CounterRNG(UInt64(seed), alg) + @argcheck offset >= 0 "Offset must be a non-negative integer" + CounterRNG(UInt64(seed), alg, UInt64(offset)) end -function CounterRNG(; alg::CounterRNGAlgorithm=Philox()) - CounterRNG(Random.rand(Random.default_rng(), UInt64); alg) +function CounterRNG(; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0) + CounterRNG(Base.rand(UInt64); alg, offset) +end + + +CounterRNG(seed::Integer, alg::CounterRNGAlgorithm) = CounterRNG(seed; alg) + + +""" + reset!(rng::AbstractCounterRNG) + +Reset `rng.offset` to `0x0` for RNGs that support mutable stream offsets. + +This requires `rng` to: +- have an `offset` field +- be mutable +""" +@inline function reset!(rng::AbstractCounterRNG) + @argcheck hasfield(typeof(rng), :offset) "reset! requires an `offset` field" + @argcheck ismutabletype(typeof(rng)) "reset! requires a mutable RNG type" + + rng.offset = UInt64(0) + return rng end @@ -64,8 +87,8 @@ include("threefry.jl") """ rand!( rng::AbstractCounterRNG, - x::AbstractArray{T}, - backend::Backend=get_backend(x); + v::AbstractArray{T}, + backend::Backend=get_backend(v); # CPU settings max_tasks::Int=Threads.nthreads(), @@ -78,8 +101,13 @@ include("threefry.jl") block_size::Int=256, ) -Fill `x` in-place with pseudo-random values using a stateless counter-based RNG. For `x[i]`, the -counter is exactly `UInt64(i - 1)` in linear indexing order. +Fill `v` in-place with pseudo-random values using a counter-based RNG stream. For `v[i]`, the +counter is `start_offset + UInt64(i - 1)` in linear indexing order, where `start_offset` is: +- `rng.offset` if `rng` has an `offset` field +- `0` otherwise + +After filling `v`, `rng.offset` advances by `length(v)` only when `rng` has a mutable `offset` +field. Supported scalar element types are: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -97,8 +125,8 @@ Semantics: """ function rand!( rng::AbstractCounterRNG, - x::AbstractArray{T}, - backend::Backend=get_backend(x); + v::AbstractArray{T}, + backend::Backend=get_backend(v); # CPU settings max_tasks::Int=Threads.nthreads(), @@ -110,23 +138,36 @@ function rand!( ) where T @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" + + initial_offset = hasfield(typeof(rng), :offset) ? UInt64(getproperty(rng, :offset)) : UInt64(0) + + # local isbits captures from potentially mutable rng object + seed, alg = rng.seed, rng.alg + foreachindex( - 1:length(x), backend; + v, backend; max_tasks, min_elems, prefer_threads, block_size, ) do i - @inbounds x[i] = rand_scalar(rng, _counter_from_index(i), T) + @inbounds v[i] = rand_scalar(seed, alg, initial_offset + _counter_from_index(i), T) + end + + if hasfield(typeof(rng), :offset) && ismutabletype(typeof(rng)) + # XXX: maybe should be atomic add? would only be needed if AK.rand! were called + # concurrently on the same rng... ?? + rng.offset = initial_offset + UInt64(length(v)) end - return x + + v end function rand!( - x::AbstractArray, + v::AbstractArray, args...; kwargs..., ) - return rand!(CounterRNG(), x, args...; kwargs...) + return rand!(CounterRNG(), v, args...; kwargs...) end diff --git a/src/rand/splitmix.jl b/src/rand/splitmix.jl index 8d7992b0..cc474be1 100644 --- a/src/rand/splitmix.jl +++ b/src/rand/splitmix.jl @@ -24,20 +24,21 @@ end # Natural SplitMix64 output path: compute 64 random bits directly from one counter @inline function rand_uint( - rng::CounterRNG{<:SplitMix64}, + seed::UInt64, + alg::SplitMix64, counter::UInt64, ::Type{UInt64}, )::UInt64 - seed = UInt64(rng.seed) return _splitmix64_mix(counter + seed + SPLITMIX64_INCREMENT) end # UInt32 path is derived from the high 32 bits of the UInt64 SplitMix output @inline function rand_uint( - rng::CounterRNG{<:SplitMix64}, + seed::UInt64, + alg::SplitMix64, counter::UInt64, ::Type{UInt32}, )::UInt32 - return _u32_hi(rand_uint(rng, counter, UInt64)) + return _u32_hi(rand_uint(seed, alg, counter, UInt64)) end diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl index 7326f404..2006886d 100644 --- a/src/rand/threefry.jl +++ b/src/rand/threefry.jl @@ -18,13 +18,12 @@ end # Evaluate one Threefry block at `counter`, returning two 32-bit lanes `(x0, x1)` @inline function _threefry2x32_block( - rng::CounterRNG{<:Threefry}, + seed::UInt64, counter::UInt64, )::Tuple{UInt32, UInt32} x0 = _u32_lo(counter) x1 = _u32_hi(counter) - seed = UInt64(rng.seed) k0 = _u32_lo(seed) k1 = _u32_hi(seed) k2 = xor(THREEFRY_PARITY, xor(k0, k1)) @@ -52,21 +51,23 @@ end # Return lane 0 from the single Threefry block at `counter` @inline function rand_uint( - rng::CounterRNG{<:Threefry}, + seed::UInt64, + alg::Threefry, counter::UInt64, ::Type{UInt32}, )::UInt32 - x0, _ = _threefry2x32_block(rng, counter) + x0, _ = _threefry2x32_block(seed, counter) return x0 end # Build UInt64 from the two lanes `(x0, x1)` of the same Threefry block at `counter` @inline function rand_uint( - rng::CounterRNG{<:Threefry}, + seed::UInt64, + alg::Threefry, counter::UInt64, ::Type{UInt64}, )::UInt64 - x0, x1 = _threefry2x32_block(rng, counter) + x0, x1 = _threefry2x32_block(seed, counter) return _u64_from_u32s(x0, x1) end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 3d5dab7c..bc3da2f1 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -51,15 +51,16 @@ const ALLOWED_RAND_SCALARS = Union{ #= -Every RNG algorithm implements rand_uint(rng, counter, UInt32/UInt64). -This fallback provides a clear failure for unsupported RNG types. +Every RNG algorithm implements rand_uint(seed, alg, counter, UInt32/UInt64). +This is the fallback for unsupported RNG algorithms. =# @inline function rand_uint( - rng::AbstractCounterRNG, + ::UInt64, + alg::CounterRNGAlgorithm, ::UInt64, ::Type{UIntType} )::UIntType where {UIntType <: Union{UInt32, UInt64}} - throw(ArgumentError("No rand_uint implementation for RNG: $rng")) + throw(ArgumentError("No rand_uint implementation for RNG algorithm: $(typeof(alg))")) end @@ -70,27 +71,26 @@ Shared scalar generation: 3) convert bits into requested scalar representation =# @inline function rand_scalar( - rng::AbstractCounterRNG, + seed::UInt64, + alg::CounterRNGAlgorithm, counter::UInt64, ::Type{T} )::T where {T <: ALLOWED_RAND_SCALARS} UIntType = raw_uint_type(T) - u = rand_uint(rng, counter, UIntType) + u = rand_uint(seed, alg, counter, UIntType) return from_uint(T, u) end -@inline function rand_scalar(::AbstractCounterRNG, ::UInt64, ::Type{T}) where {T} +@inline function rand_scalar(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} throw(ArgumentError( "Unsupported random scalar type $(T). Supported: $(ALLOWED_RAND_SCALARS)" )) end - - # Convert random UInt32 bits to Float16 in [0, 1) by mantissa construction. @inline function uint32_to_unit_float16(u::UInt32)::Float16 # Keep 10 random bits for the mantissa (drop 22 rightmost bits from the UInt32) @@ -98,7 +98,7 @@ end bits = UInt16(0x3c00) | UInt16(u >> 22) # Interpret as 1.mantissa, then subtract 1 for [0, 1) - return reinterpret(Float16, bits) - Float16(1) + reinterpret(Float16, bits) - Float16(1) end @@ -109,7 +109,7 @@ end bits = UInt32(0x3f800000) | (u >> 9) # Interpret as 1.mantissa, then subtract 1 for [0, 1) - return reinterpret(Float32, bits) - 1.0f0 + reinterpret(Float32, bits) - 1.0f0 end @@ -120,5 +120,5 @@ end bits = UInt64(0x3ff0000000000000) | (u >> 12) # Interpret as 1.mantissa, then subtract 1 for [0, 1) - return reinterpret(Float64, bits) - 1.0 + reinterpret(Float64, bits) - 1.0 end diff --git a/test/rand.jl b/test/rand.jl index 9e03e59f..b7ef1673 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -7,25 +7,31 @@ const RAND_SCALAR_TYPES_ALL = ( ) const RAND_SCALAR_TYPES_BACKEND = IS_CPU_BACKEND ? RAND_SCALAR_TYPES_ALL : - (UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float16, Float32, Bool) + (UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Bool) +const RUN_FLOAT16_RAND_TESTS = IS_CPU_BACKEND const RUN_FLOAT64_RAND_TESTS = IS_CPU_BACKEND _is_unit_interval(v) = all(x -> !isnan(x) && zero(x) <= x < one(x), v) -function _rand_fill_reference!(rng, x::AbstractArray{T}) where {T <: AK.ALLOWED_RAND_SCALARS} +function _rand_fill_reference!( + rng, + x::AbstractArray{T}; + counter_offset::UInt64=UInt64(0), +) where {T <: AK.ALLOWED_RAND_SCALARS} @inbounds for i in eachindex(x) - x[i] = AK.rand_scalar(rng, UInt64(i - one(i)), T) + x[i] = AK.rand_scalar(rng.seed, rng.alg, counter_offset + UInt64(i - one(i)), T) end return x end function _assert_rand_matches_reference!(rng, x; kwargs...) + counter_offset = rng.offset AK.rand!(rng, x; kwargs...) ref = zeros(eltype(x), size(x)) - _rand_fill_reference!(rng, ref) + _rand_fill_reference!(rng, ref; counter_offset) @test Array(x) == ref return x end @@ -37,7 +43,11 @@ end @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} @test AK.CounterRNG(UInt16(123); alg=AK.Threefry()) isa AK.CounterRNG{AK.Threefry} @test AK.CounterRNG(UInt32(300)).seed == UInt64(300) + @test AK.CounterRNG(UInt32(300)).offset == UInt64(0) + @test AK.CounterRNG(0x1; offset=17).offset == UInt64(17) + @test AK.CounterRNG(0x1, AK.Philox()).offset == UInt64(0) @test_throws ArgumentError AK.CounterRNG(-1) + @test_throws ArgumentError AK.CounterRNG(1; offset=-1) Random.seed!(0x1234) expected_seed = Random.rand(Random.default_rng(), UInt64) @@ -45,11 +55,80 @@ end rng_auto = AK.CounterRNG() @test rng_auto.seed == expected_seed @test rng_auto.alg isa AK.Philox + @test rng_auto.offset == UInt64(0) + + rng_auto_off = AK.CounterRNG(; offset=42) + @test rng_auto_off.offset == UInt64(42) x1 = array_from_host(zeros(Float32, 1024)) x2 = array_from_host(zeros(Float32, 1024)) AK.rand!(rng_auto, x1; prefer_threads, block_size=64) AK.rand!(rng_auto, x2; prefer_threads, block_size=257) + @test rng_auto.offset == UInt64(2048) + @test Array(x1) != Array(x2) + end + + + @testset "abstract rng offset behavior" begin + mutable struct MutableNoOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + seed::UInt64 + alg::AK.Philox + end + + mutable struct MutableWithOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + seed::UInt64 + alg::AK.Philox + offset::UInt64 + end + + struct ImmutableWithOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + seed::UInt64 + alg::AK.Philox + offset::UInt64 + end + + rng_no_offset = MutableNoOffsetRNG(UInt64(0x1234), AK.Philox()) + x1 = array_from_host(zeros(Float32, 256)) + x2 = array_from_host(zeros(Float32, 256)) + AK.rand!(rng_no_offset, x1; prefer_threads, block_size=64) + AK.rand!(rng_no_offset, x2; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) + + rng_stream = MutableWithOffsetRNG(UInt64(0x1234), AK.Philox(), UInt64(0)) + s1 = array_from_host(zeros(Float32, 100)) + s2 = array_from_host(zeros(Float32, 100)) + s12 = array_from_host(zeros(Float32, 200)) + AK.rand!(rng_stream, s1; prefer_threads, block_size=64) + AK.rand!(rng_stream, s2; prefer_threads, block_size=64) + AK.rand!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), s12; prefer_threads, block_size=64) + @test vcat(Array(s1), Array(s2)) == Array(s12) + @test rng_stream.offset == UInt64(200) + + rng_imm = ImmutableWithOffsetRNG(UInt64(0x1234), AK.Philox(), UInt64(17)) + y1 = array_from_host(zeros(Float32, 64)) + y2 = array_from_host(zeros(Float32, 64)) + AK.rand!(rng_imm, y1; prefer_threads, block_size=64) + AK.rand!(rng_imm, y2; prefer_threads, block_size=64) + @test Array(y1) == Array(y2) + + @test AK.reset!(rng_stream) === rng_stream + @test rng_stream.offset == UInt64(0) + @test_throws ArgumentError AK.reset!(rng_no_offset) + @test_throws ArgumentError AK.reset!(rng_imm) + end + + + @testset "reset!" begin + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + x1 = array_from_host(zeros(Float32, 512)) + x2 = array_from_host(zeros(Float32, 512)) + + AK.rand!(rng, x1; prefer_threads, block_size=64) + @test rng.offset == UInt64(512) + @test AK.reset!(rng) === rng + @test rng.offset == UInt64(0) + AK.rand!(rng, x2; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) end @@ -73,7 +152,9 @@ end @test AK.raw_uint_type(Int8) === UInt32 @test AK.raw_uint_type(Int16) === UInt32 @test AK.raw_uint_type(Int32) === UInt32 - @test AK.raw_uint_type(Float16) === UInt32 + if RUN_FLOAT16_RAND_TESTS + @test AK.raw_uint_type(Float16) === UInt32 + end @test AK.raw_uint_type(Float32) === UInt32 @test AK.raw_uint_type(UInt64) === UInt64 @test AK.raw_uint_type(Int64) === UInt64 @@ -92,12 +173,16 @@ end @test AK.from_uint( Int64, 0b1111111111111111111111111111111111111111111111111111111111111111 % UInt64 ) == Int64(-1) - @test AK.from_uint(Float16, UInt32(0)) == Float16(0) + if RUN_FLOAT16_RAND_TESTS + @test AK.from_uint(Float16, UInt32(0)) == Float16(0) + end @test AK.from_uint(Bool, UInt32(0)) == false @test AK.from_uint(Bool, UInt32(1)) == true - @test AK.uint32_to_unit_float16(UInt32(0)) == Float16(0) - @test Float16(0) <= AK.uint32_to_unit_float16(typemax(UInt32)) < Float16(1) + if RUN_FLOAT16_RAND_TESTS + @test AK.uint32_to_unit_float16(UInt32(0)) == Float16(0) + @test Float16(0) <= AK.uint32_to_unit_float16(typemax(UInt32)) < Float16(1) + end @test AK.uint32_to_unit_float32(UInt32(0)) == 0.0f0 @test 0.0f0 <= AK.uint32_to_unit_float32(typemax(UInt32)) < 1.0f0 if RUN_FLOAT64_RAND_TESTS @@ -111,25 +196,26 @@ end for alg in RAND_ALGS rng = AK.CounterRNG(0x123456789abcdef; alg) for U in (UInt32, UInt64) - @test AK.rand_uint(rng, UInt64(0), U) == AK.rand_uint(rng, UInt64(0), U) - @test AK.rand_uint(rng, UInt64(1), U) != AK.rand_uint(rng, UInt64(0), U) + @test AK.rand_uint(rng.seed, rng.alg, UInt64(0), U) == AK.rand_uint(rng.seed, rng.alg, UInt64(0), U) + @test AK.rand_uint(rng.seed, rng.alg, UInt64(1), U) != AK.rand_uint(rng.seed, rng.alg, UInt64(0), U) - vals = [AK.rand_uint(rng, UInt64(i), U) for i in 0:511] + vals = [AK.rand_uint(rng.seed, rng.alg, UInt64(i), U) for i in 0:511] @test length(unique(vals)) > 460 end end rng_splitmix = AK.CounterRNG(0x31415926; alg=AK.SplitMix64()) for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - @test AK.rand_uint(rng_splitmix, c, UInt32) == AK._u32_hi( - AK.rand_uint(rng_splitmix, c, UInt64) + @test AK.rand_uint(rng_splitmix.seed, rng_splitmix.alg, c, UInt32) == AK._u32_hi( + AK.rand_uint(rng_splitmix.seed, rng_splitmix.alg, c, UInt64) ) end for alg in (AK.Philox(), AK.Threefry()) rng = AK.CounterRNG(0xabcdef1234567890; alg) for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - @test AK._u32_lo(AK.rand_uint(rng, c, UInt64)) == AK.rand_uint(rng, c, UInt32) + @test AK._u32_lo(AK.rand_uint(rng.seed, rng.alg, c, UInt64)) == + AK.rand_uint(rng.seed, rng.alg, c, UInt32) end end end @@ -139,10 +225,11 @@ end rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) for T in RAND_SCALAR_TYPES_BACKEND - s0 = AK.rand_scalar(rng, UInt64(0), T) - s1 = AK.rand_scalar(rng, UInt64(1), T) + s0 = AK.rand_scalar(rng.seed, rng.alg, UInt64(0), T) + s1 = AK.rand_scalar(rng.seed, rng.alg, UInt64(1), T) @test s0 isa T @test s1 isa T + @test s0 == AK.rand_scalar(rng.seed, rng.alg, UInt64(0), T) if !(T in (Bool, Float16, UInt8, UInt16, Int8, Int16)) @test s0 != s1 end @@ -153,32 +240,37 @@ end end c = UInt64(42) - @test AK.rand_scalar(rng, c, UInt8) == trunc(UInt8, AK.rand_uint(rng, c, UInt32) >> 24) - @test AK.rand_scalar(rng, c, UInt16) == trunc(UInt16, AK.rand_uint(rng, c, UInt32) >> 16) - @test AK.rand_scalar( - rng, c, Int8 - ) == reinterpret(Int8, trunc(UInt8, AK.rand_uint(rng, c, UInt32) >> 24)) - @test AK.rand_scalar( - rng, c, Int16 - ) == reinterpret(Int16, trunc(UInt16, AK.rand_uint(rng, c, UInt32) >> 16)) - @test AK.rand_scalar(rng, c, Int32) == reinterpret(Int32, AK.rand_uint(rng, c, UInt32)) - @test AK.rand_scalar(rng, c, Int64) == reinterpret(Int64, AK.rand_uint(rng, c, UInt64)) - @test AK.rand_scalar(rng, c, Float16) == AK.uint32_to_unit_float16( - AK.rand_uint(rng, c, UInt32) - ) - @test AK.rand_scalar(rng, c, Float32) == AK.uint32_to_unit_float32( - AK.rand_uint(rng, c, UInt32) + @test AK.rand_scalar(rng.seed, rng.alg, c, UInt8) == + trunc(UInt8, AK.rand_uint(rng.seed, rng.alg, c, UInt32) >> 24) + @test AK.rand_scalar(rng.seed, rng.alg, c, UInt16) == + trunc(UInt16, AK.rand_uint(rng.seed, rng.alg, c, UInt32) >> 16) + @test AK.rand_scalar(rng.seed, rng.alg, c, Int8) == + reinterpret(Int8, trunc(UInt8, AK.rand_uint(rng.seed, rng.alg, c, UInt32) >> 24)) + @test AK.rand_scalar(rng.seed, rng.alg, c, Int16) == + reinterpret(Int16, trunc(UInt16, AK.rand_uint(rng.seed, rng.alg, c, UInt32) >> 16)) + @test AK.rand_scalar(rng.seed, rng.alg, c, Int32) == + reinterpret(Int32, AK.rand_uint(rng.seed, rng.alg, c, UInt32)) + @test AK.rand_scalar(rng.seed, rng.alg, c, Int64) == + reinterpret(Int64, AK.rand_uint(rng.seed, rng.alg, c, UInt64)) + if RUN_FLOAT16_RAND_TESTS + @test AK.rand_scalar(rng.seed, rng.alg, c, Float16) == AK.uint32_to_unit_float16( + AK.rand_uint(rng.seed, rng.alg, c, UInt32) + ) + end + @test AK.rand_scalar(rng.seed, rng.alg, c, Float32) == AK.uint32_to_unit_float32( + AK.rand_uint(rng.seed, rng.alg, c, UInt32) ) - @test AK.rand_scalar(rng, c, Bool) == isodd(AK.rand_uint(rng, c, UInt32)) + @test AK.rand_scalar(rng.seed, rng.alg, c, Bool) == + isodd(AK.rand_uint(rng.seed, rng.alg, c, UInt32)) if RUN_FLOAT64_RAND_TESTS - @test AK.rand_scalar(rng, c, Float64) == AK.uint64_to_unit_float64( - AK.rand_uint(rng, c, UInt64) + @test AK.rand_scalar(rng.seed, rng.alg, c, Float64) == AK.uint64_to_unit_float64( + AK.rand_uint(rng.seed, rng.alg, c, UInt64) ) end - bools = [AK.rand_scalar(rng, UInt64(i), Bool) for i in 0:511] + bools = [AK.rand_scalar(rng.seed, rng.alg, UInt64(i), Bool) for i in 0:511] @test any(identity, bools) @test any(!, bools) - @test_throws ArgumentError AK.rand_scalar(rng, UInt64(0), UInt128) + @test_throws ArgumentError AK.rand_scalar(rng.seed, rng.alg, UInt64(0), UInt128) end @@ -199,21 +291,37 @@ end for T in RAND_SCALAR_TYPES_BACKEND x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) - AK.rand!(rng, x1; prefer_threads, block_size=64) - AK.rand!(rng, x2; prefer_threads, block_size=257) + rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) + rng2 = AK.CounterRNG(rng.seed; alg=rng.alg) + AK.rand!(rng1, x1; prefer_threads, block_size=64) + AK.rand!(rng2, x2; prefer_threads, block_size=257) @test Array(x1) == Array(x2) end - rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) for T in RAND_SCALAR_TYPES_BACKEND + rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) + rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) - AK.rand!(rng, x1; prefer_threads, block_size=64) + AK.rand!(rng1, x1; prefer_threads, block_size=64) AK.rand!(rng2, x2; prefer_threads, block_size=64) @test Array(x1) != Array(x2) end - for T in (Float16, Float32, UInt64, Bool) + begin + rng_stream = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + rng_once = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + x1 = array_from_host(zeros(Float32, 100)) + x2 = array_from_host(zeros(Float32, 100)) + x12 = array_from_host(zeros(Float32, 200)) + AK.rand!(rng_stream, x1; prefer_threads, block_size=64) + AK.rand!(rng_stream, x2; prefer_threads, block_size=64) + AK.rand!(rng_once, x12; prefer_threads, block_size=64) + @test vcat(Array(x1), Array(x2)) == Array(x12) + @test rng_stream.offset == UInt64(200) + end + + for T in (RUN_FLOAT16_RAND_TESTS ? (Float16, Float32, UInt64, Bool) : (Float32, UInt64, Bool)) xnd = array_from_host(zeros(T, 7, 11, 5)) _assert_rand_matches_reference!(rng, xnd; prefer_threads, block_size=128) end @@ -229,7 +337,10 @@ end prefer_threads=true ) ref_view = zeros(T, length(view_x)) - _rand_fill_reference!(rng, ref_view) + _rand_fill_reference!( + rng, ref_view; + counter_offset=rng.offset - UInt64(length(view_x)), + ) @test collect(view_x) == ref_view end end From 71a62d47f57653429b03a5621cf710511a0be49d Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 24 Mar 2026 20:02:41 +0000 Subject: [PATCH 11/20] style update + remove AbstractCounterRNG type in favour of purely allowing CounterRNG which now must have an offset. if needed, AK.reset!(::CounterRNG) can be called to reset a streaming CounterRNG every time AK.rand! is called, if needed --- docs/src/api/rand.md | 5 +-- prototype/RNGTest/stream.jl | 2 +- prototype/rand/test_rand.jl | 8 ++--- src/rand/philox.jl | 2 +- src/rand/rand.jl | 38 +++++++--------------- src/rand/threefry.jl | 1 + src/rand/utilities.jl | 65 ++++++++++++++++++++----------------- test/rand.jl | 6 ++-- test/runtests.jl | 8 ++++- 9 files changed, 66 insertions(+), 69 deletions(-) diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 5c5596ec..03ed7f3e 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -9,7 +9,7 @@ fixed `seed`, algorithm, and call sequence. - calls that share the same `CounterRNG` instance concurrently are not thread-safe. - call `AK.reset!(rng)` to rewind a mutable offset-bearing RNG back to offset `0x0`. -`AK.rand!` also accepts custom `AbstractCounterRNG` implementations: +`AK.rand!` also accepts custom `CounterRNG` implementations: - if they have a mutable `offset` field, streaming advancement is applied - if they have no `offset` field, each call behaves statelessly from counter `0` - if they have an immutable `offset` field, that offset is used as a fixed start and is not advanced @@ -23,7 +23,7 @@ convenience, Custom RNGs: - Define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm`. -- Define an RNG type `MyRNG <: AK.AbstractCounterRNG{MyAlg}` with fields `seed` and `alg`. +- Define a `CounterRNG` with fields `seed` and `alg`. - Add a mutable `offset::UInt64` field if you want stream advancement across calls; omit it for stateless calls from counter `0`. - Implement typed `rand_uint` methods: - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` @@ -89,6 +89,7 @@ AK.rand!(y) ```@docs AcceleratedKernels.CounterRNG +AcceleratedKernels.CounterRNGAlgorithm AcceleratedKernels.reset! AcceleratedKernels.rand! ``` diff --git a/prototype/RNGTest/stream.jl b/prototype/RNGTest/stream.jl index ba65ce9c..a3836454 100644 --- a/prototype/RNGTest/stream.jl +++ b/prototype/RNGTest/stream.jl @@ -13,7 +13,7 @@ function make_rng(seed::Integer, alg::Symbol; offset::Integer=0) end -mutable struct AKUInt64Stream{R <: AK.AbstractCounterRNG} +mutable struct AKUInt64Stream{R} rng::R chunk::Int idx::Int diff --git a/prototype/rand/test_rand.jl b/prototype/rand/test_rand.jl index 329214dc..ec3ce654 100644 --- a/prototype/rand/test_rand.jl +++ b/prototype/rand/test_rand.jl @@ -43,13 +43,13 @@ is_unit_interval(v) = all(x -> 0.0f0 <= x <= 1.0f0, v) # warmup compile run_cuda_rand!(x_cuda) -run_ak_rand_gpu!(RNG_SPLITMIX, x_splitmix) +# run_ak_rand_gpu!(RNG_SPLITMIX, x_splitmix) run_ak_rand_gpu!(RNG_PHILOX, x_philox) run_ak_rand_gpu!(RNG_THREEFRY, x_threefry) run_ak_rand_cpu!(RNG_SPLITMIX, x_cpu) @assert is_unit_interval(Array(x_cuda)) -@assert is_unit_interval(Array(x_splitmix)) +# @assert is_unit_interval(Array(x_splitmix)) @assert is_unit_interval(Array(x_philox)) @assert is_unit_interval(Array(x_threefry)) @assert is_unit_interval(x_cpu) @@ -60,8 +60,8 @@ println("CPU threads: ", Threads.nthreads()) println("\nCUDA.rand! benchmark (CuArray{Float32}, in-place)") display(@benchmark run_cuda_rand!($x_cuda)) -println("\nAK.rand! SplitMix64 benchmark (GPU, CuArray{Float32})") -display(@benchmark run_ak_rand_gpu!($RNG_SPLITMIX, $x_splitmix)) +# println("\nAK.rand! SplitMix64 benchmark (GPU, CuArray{Float32})") +# display(@benchmark run_ak_rand_gpu!($RNG_SPLITMIX, $x_splitmix)) println("\nAK.rand! Philox benchmark (GPU, CuArray{Float32})") display(@benchmark run_ak_rand_gpu!($RNG_PHILOX, $x_philox)) diff --git a/src/rand/philox.jl b/src/rand/philox.jl index 61e5f97b..0de9ff40 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -4,7 +4,7 @@ struct Philox <: CounterRNGAlgorithm end # Philox magic numbers const PHILOX_M0 = UInt32(0xD256D193) const PHILOX_W0 = UInt32(0x9E3779B9) -const PHILOX_ROUNDS = 10 +const PHILOX_ROUNDS = 7 @inline function _philox2x32_round(x0::UInt32, x1::UInt32, k0::UInt32) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 229a8991..b9db7563 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -1,12 +1,4 @@ -""" - abstract type CounterRNGAlgorithm end - abstract type AbstractCounterRNG{A <: CounterRNGAlgorithm} end - -RNG interface for counter-based random generation with AcceleratedKernels. -""" - abstract type CounterRNGAlgorithm end -abstract type AbstractCounterRNG{A <: CounterRNGAlgorithm} end """ @@ -31,11 +23,12 @@ Constructors: - `CounterRNG(; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0)` Auto-seeds once using `Base.rand(UInt64)`, with default `offset == 0`. """ -mutable struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractCounterRNG{A} - seed::UInt64 - alg::A +mutable struct CounterRNG{A <: CounterRNGAlgorithm} + const seed::UInt64 + const alg::A offset::UInt64 end +#TODO: need to figure out a nice way to allow custom counter RNGs function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0) @@ -54,7 +47,7 @@ CounterRNG(seed::Integer, alg::CounterRNGAlgorithm) = CounterRNG(seed; alg) """ - reset!(rng::AbstractCounterRNG) + reset!(rng::CounterRNG) Reset `rng.offset` to `0x0` for RNGs that support mutable stream offsets. @@ -62,7 +55,7 @@ This requires `rng` to: - have an `offset` field - be mutable """ -@inline function reset!(rng::AbstractCounterRNG) +@inline function reset!(rng::CounterRNG) @argcheck hasfield(typeof(rng), :offset) "reset! requires an `offset` field" @argcheck ismutabletype(typeof(rng)) "reset! requires a mutable RNG type" @@ -86,7 +79,7 @@ include("threefry.jl") """ rand!( - rng::AbstractCounterRNG, + rng::CounterRNG, v::AbstractArray{T}, backend::Backend=get_backend(v); @@ -124,7 +117,7 @@ Semantics: """ function rand!( - rng::AbstractCounterRNG, + rng::CounterRNG, v::AbstractArray{T}, backend::Backend=get_backend(v); @@ -139,26 +132,17 @@ function rand!( @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" - initial_offset = hasfield(typeof(rng), :offset) ? UInt64(getproperty(rng, :offset)) : UInt64(0) - - # local isbits captures from potentially mutable rng object + # Local isbits captures from potentially mutable rng object seed, alg = rng.seed, rng.alg foreachindex( v, backend; - max_tasks, - min_elems, - prefer_threads, - block_size, + max_tasks, min_elems, prefer_threads, block_size, ) do i @inbounds v[i] = rand_scalar(seed, alg, initial_offset + _counter_from_index(i), T) end - if hasfield(typeof(rng), :offset) && ismutabletype(typeof(rng)) - # XXX: maybe should be atomic add? would only be needed if AK.rand! were called - # concurrently on the same rng... ?? - rng.offset = initial_offset + UInt64(length(v)) - end + rng.offset += UInt64(length(v)) v end diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl index 2006886d..c9052b19 100644 --- a/src/rand/threefry.jl +++ b/src/rand/threefry.jl @@ -21,6 +21,7 @@ end seed::UInt64, counter::UInt64, )::Tuple{UInt32, UInt32} + x0 = _u32_lo(counter) x1 = _u32_hi(counter) diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index bc3da2f1..f2159c55 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -1,15 +1,17 @@ # lo: rightmost 32 bits, hi: leftmost 32 bits @inline _u32_lo(x::UInt64)::UInt32 = UInt32(x & UInt64(0xffffffff)) @inline _u32_hi(x::UInt64)::UInt32 = UInt32(x >> 32) + +# Construct UInt64 by bit concatenation of two UInt32s @inline _u64_from_u32s(lo::UInt32, hi::UInt32)::UInt64 = (UInt64(hi) << 32) | UInt64(lo) -# leftmost 32 bits of a*b cast to UInt64s +# Leftmost 32 bits of a*b cast to UInt64s @inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) # 32-bit rotate left by r positions @inline _rotl32(x::UInt32, r::UInt32)::UInt32 = (x << r) | (x >> (UInt32(32) - r)) - +# Get counter used for CounterRNG from element index @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) @@ -22,32 +24,32 @@ const ALLOWED_RAND_SCALARS = Union{ } -@inline raw_uint_type(::Type{UInt8}) = UInt32 -@inline raw_uint_type(::Type{UInt16}) = UInt32 -@inline raw_uint_type(::Type{UInt32}) = UInt32 -@inline raw_uint_type(::Type{Int8}) = UInt32 -@inline raw_uint_type(::Type{Int16}) = UInt32 -@inline raw_uint_type(::Type{Int32}) = UInt32 -@inline raw_uint_type(::Type{Float16}) = UInt32 -@inline raw_uint_type(::Type{Float32}) = UInt32 -@inline raw_uint_type(::Type{UInt64}) = UInt64 -@inline raw_uint_type(::Type{Int64}) = UInt64 -@inline raw_uint_type(::Type{Float64}) = UInt64 -@inline raw_uint_type(::Type{Bool}) = UInt32 - - -@inline from_uint(::Type{UInt8}, u::UInt32)::UInt8 = trunc(UInt8, u >> 24) -@inline from_uint(::Type{UInt16}, u::UInt32)::UInt16 = trunc(UInt16, u >> 16) -@inline from_uint(::Type{UInt32}, u::UInt32)::UInt32 = u -@inline from_uint(::Type{UInt64}, u::UInt64)::UInt64 = u -@inline from_uint(::Type{Int8}, u::UInt32)::Int8 = reinterpret(Int8, trunc(UInt8, u >> 24)) -@inline from_uint(::Type{Int16}, u::UInt32)::Int16 = reinterpret(Int16, trunc(UInt16, u >> 16)) -@inline from_uint(::Type{Int32}, u::UInt32)::Int32 = reinterpret(Int32, u) -@inline from_uint(::Type{Int64}, u::UInt64)::Int64 = reinterpret(Int64, u) -@inline from_uint(::Type{Float16}, u::UInt32)::Float16 = uint32_to_unit_float16(u) -@inline from_uint(::Type{Float32}, u::UInt32)::Float32 = uint32_to_unit_float32(u) -@inline from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) -@inline from_uint(::Type{Bool}, u::UInt32)::Bool = isodd(u) +@inline _rand_scalar_uint_type(::Type{UInt8}) = UInt32 +@inline _rand_scalar_uint_type(::Type{UInt16}) = UInt32 +@inline _rand_scalar_uint_type(::Type{UInt32}) = UInt32 +@inline _rand_scalar_uint_type(::Type{Int8}) = UInt32 +@inline _rand_scalar_uint_type(::Type{Int16}) = UInt32 +@inline _rand_scalar_uint_type(::Type{Int32}) = UInt32 +@inline _rand_scalar_uint_type(::Type{Float16}) = UInt32 +@inline _rand_scalar_uint_type(::Type{Float32}) = UInt32 +@inline _rand_scalar_uint_type(::Type{UInt64}) = UInt64 +@inline _rand_scalar_uint_type(::Type{Int64}) = UInt64 +@inline _rand_scalar_uint_type(::Type{Float64}) = UInt64 +@inline _rand_scalar_uint_type(::Type{Bool}) = UInt32 + + +@inline _rand_scalar_from_uint(::Type{UInt8}, u::UInt32)::UInt8 = trunc(UInt8, u >> 24) +@inline _rand_scalar_from_uint(::Type{UInt16}, u::UInt32)::UInt16 = trunc(UInt16, u >> 16) +@inline _rand_scalar_from_uint(::Type{UInt32}, u::UInt32)::UInt32 = u +@inline _rand_scalar_from_uint(::Type{UInt64}, u::UInt64)::UInt64 = u +@inline _rand_scalar_from_uint(::Type{Int8}, u::UInt32)::Int8 = reinterpret(Int8, trunc(UInt8, u >> 24)) +@inline _rand_scalar_from_uint(::Type{Int16}, u::UInt32)::Int16 = reinterpret(Int16, trunc(UInt16, u >> 16)) +@inline _rand_scalar_from_uint(::Type{Int32}, u::UInt32)::Int32 = reinterpret(Int32, u) +@inline _rand_scalar_from_uint(::Type{Int64}, u::UInt64)::Int64 = reinterpret(Int64, u) +@inline _rand_scalar_from_uint(::Type{Float16}, u::UInt32)::Float16 = uint32_to_unit_float16(u) +@inline _rand_scalar_from_uint(::Type{Float32}, u::UInt32)::Float32 = uint32_to_unit_float32(u) +@inline _rand_scalar_from_uint(::Type{Float64}, u::UInt64)::Float64 = uint64_to_unit_float64(u) +@inline _rand_scalar_from_uint(::Type{Bool}, u::UInt32)::Bool = isodd(u) #= @@ -77,10 +79,10 @@ Shared scalar generation: ::Type{T} )::T where {T <: ALLOWED_RAND_SCALARS} - UIntType = raw_uint_type(T) + UIntType = _rand_scalar_uint_type(T) u = rand_uint(seed, alg, counter, UIntType) - return from_uint(T, u) + return _rand_scalar_from_uint(T, u) end @@ -93,6 +95,7 @@ end # Convert random UInt32 bits to Float16 in [0, 1) by mantissa construction. @inline function uint32_to_unit_float16(u::UInt32)::Float16 + # Keep 10 random bits for the mantissa (drop 22 rightmost bits from the UInt32) # and combine with the bit pattern of Float16(1.0) (sign=0, exponent=15). bits = UInt16(0x3c00) | UInt16(u >> 22) @@ -104,6 +107,7 @@ end # Convert random UInt32 bits to Float32 in [0, 1) by mantissa construction. @inline function uint32_to_unit_float32(u::UInt32)::Float32 + # Keep 23 random bits for the mantissa (drop 9 rightmost bits from the UInt32) # and combine with the bit pattern of 1.0f0 (sign=0, exponent=127). bits = UInt32(0x3f800000) | (u >> 9) @@ -115,6 +119,7 @@ end # Convert random UInt64 bits to Float64 in [0, 1) by mantissa construction. @inline function uint64_to_unit_float64(u::UInt64)::Float64 + # Keep 52 random bits for the mantissa (drop 12 rightmost bits from the UInt64) # and combine with the bit pattern of 1.0 (sign=0, exponent=1023). bits = UInt64(0x3ff0000000000000) | (u >> 12) diff --git a/test/rand.jl b/test/rand.jl index b7ef1673..0495b866 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -70,18 +70,18 @@ end @testset "abstract rng offset behavior" begin - mutable struct MutableNoOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + mutable struct MutableNoOffsetRNG seed::UInt64 alg::AK.Philox end - mutable struct MutableWithOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + mutable struct MutableWithOffsetRNG seed::UInt64 alg::AK.Philox offset::UInt64 end - struct ImmutableWithOffsetRNG <: AK.AbstractCounterRNG{AK.Philox} + struct ImmutableWithOffsetRNG seed::UInt64 alg::AK.Philox offset::UInt64 diff --git a/test/runtests.jl b/test/runtests.jl index a2707b6b..d1a2d695 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -17,7 +17,13 @@ if "--CUDA" in ARGS const BACKEND = CUDABackend() TEST_DL[] = true elseif "--oneAPI" in ARGS - Pkg.add("oneAPI") + if Sys.iswindows() + # oneAPI v2.6.x can throw `UndefVarError: NEO_jll not defined` on native Windows. + # Pin to the latest known-good minor series until upstream fixes are available. + Pkg.add(name="oneAPI", version="2.5") + else + Pkg.add("oneAPI") + end using oneAPI oneAPI.versioninfo() const BACKEND = oneAPIBackend() From 42a434e6c0465593651f84e334838bf53b9327d6 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Tue, 24 Mar 2026 20:23:31 +0000 Subject: [PATCH 12/20] update tests and docs to match new CounterRNG interface --- docs/src/api/rand.md | 15 +++--- src/rand/rand.jl | 19 ++------ test/rand.jl | 109 ++++++++++++++++++++----------------------- 3 files changed, 61 insertions(+), 82 deletions(-) diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 03ed7f3e..aab3e5d5 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -7,27 +7,24 @@ fixed `seed`, algorithm, and call sequence. `AK.rand!(rng, v)` call. This means chunked fills are stream-consistent: - filling `100` then `100` elements yields the same `200` values as one `200`-element fill. - calls that share the same `CounterRNG` instance concurrently are not thread-safe. -- call `AK.reset!(rng)` to rewind a mutable offset-bearing RNG back to offset `0x0`. +- call `AK.reset!(rng)` to rewind a `CounterRNG` offset back to `0x0`. -`AK.rand!` also accepts custom `CounterRNG` implementations: -- if they have a mutable `offset` field, streaming advancement is applied -- if they have no `offset` field, each call behaves statelessly from counter `0` -- if they have an immutable `offset` field, that offset is used as a fixed start and is not advanced +`AK.rand!(rng, v)` accepts `rng::AK.CounterRNG`. +Passing other RNG container types is not supported and will throw a `MethodError`. Use an explicit `CounterRNG` when reproducibility is required. For convenience, `AK.rand!(v)` creates a fresh `CounterRNG()` on each call using one auto-seeded `Base.rand(UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. -`AK.reset!(rng)` rewinds offset to `0x0` for mutable RNGs that have an `offset` field. +`AK.reset!(rng::AK.CounterRNG)` rewinds `rng.offset` to `0x0`. -Custom RNGs: +Custom algorithms: - Define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm`. -- Define a `CounterRNG` with fields `seed` and `alg`. -- Add a mutable `offset::UInt64` field if you want stream advancement across calls; omit it for stateless calls from counter `0`. - Implement typed `rand_uint` methods: - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` +- Use your algorithm via `AK.CounterRNG(seed; alg=MyAlg(), offset=...)`. Both widths should be implemented so `AK.rand!` supports all integer/float output types without falling back or error. diff --git a/src/rand/rand.jl b/src/rand/rand.jl index b9db7563..833bcaed 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -28,7 +28,6 @@ mutable struct CounterRNG{A <: CounterRNGAlgorithm} const alg::A offset::UInt64 end -#TODO: need to figure out a nice way to allow custom counter RNGs function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0) @@ -49,16 +48,9 @@ CounterRNG(seed::Integer, alg::CounterRNGAlgorithm) = CounterRNG(seed; alg) """ reset!(rng::CounterRNG) -Reset `rng.offset` to `0x0` for RNGs that support mutable stream offsets. - -This requires `rng` to: -- have an `offset` field -- be mutable +Reset `rng.offset` to `0x0`. """ @inline function reset!(rng::CounterRNG) - @argcheck hasfield(typeof(rng), :offset) "reset! requires an `offset` field" - @argcheck ismutabletype(typeof(rng)) "reset! requires a mutable RNG type" - rng.offset = UInt64(0) return rng end @@ -95,12 +87,9 @@ include("threefry.jl") ) Fill `v` in-place with pseudo-random values using a counter-based RNG stream. For `v[i]`, the -counter is `start_offset + UInt64(i - 1)` in linear indexing order, where `start_offset` is: -- `rng.offset` if `rng` has an `offset` field -- `0` otherwise +counter is `rng.offset + UInt64(i - 1)` in linear indexing order. -After filling `v`, `rng.offset` advances by `length(v)` only when `rng` has a mutable `offset` -field. +After filling `v`, `rng.offset` advances by `length(v)`. Supported scalar element types are: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -133,7 +122,7 @@ function rand!( @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" # Local isbits captures from potentially mutable rng object - seed, alg = rng.seed, rng.alg + seed, alg, initial_offset = rng.seed, rng.alg, rng.offset foreachindex( v, backend; diff --git a/test/rand.jl b/test/rand.jl index 0495b866..90e285af 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -69,52 +69,45 @@ end end - @testset "abstract rng offset behavior" begin - mutable struct MutableNoOffsetRNG - seed::UInt64 - alg::AK.Philox - end - - mutable struct MutableWithOffsetRNG - seed::UInt64 - alg::AK.Philox - offset::UInt64 - end - - struct ImmutableWithOffsetRNG - seed::UInt64 - alg::AK.Philox - offset::UInt64 - end - - rng_no_offset = MutableNoOffsetRNG(UInt64(0x1234), AK.Philox()) - x1 = array_from_host(zeros(Float32, 256)) - x2 = array_from_host(zeros(Float32, 256)) - AK.rand!(rng_no_offset, x1; prefer_threads, block_size=64) - AK.rand!(rng_no_offset, x2; prefer_threads, block_size=64) - @test Array(x1) == Array(x2) - - rng_stream = MutableWithOffsetRNG(UInt64(0x1234), AK.Philox(), UInt64(0)) + @testset "counter rng offset behavior" begin + rng_stream = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox(), offset=UInt64(17)) s1 = array_from_host(zeros(Float32, 100)) s2 = array_from_host(zeros(Float32, 100)) s12 = array_from_host(zeros(Float32, 200)) AK.rand!(rng_stream, s1; prefer_threads, block_size=64) + @test rng_stream.offset == UInt64(117) AK.rand!(rng_stream, s2; prefer_threads, block_size=64) - AK.rand!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), s12; prefer_threads, block_size=64) + @test rng_stream.offset == UInt64(217) + + rng_once = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox(), offset=UInt64(17)) + AK.rand!(rng_once, s12; prefer_threads, block_size=64) @test vcat(Array(s1), Array(s2)) == Array(s12) - @test rng_stream.offset == UInt64(200) + @test rng_once.offset == UInt64(217) + + empty = array_from_host(zeros(Float32, 0)) + stream_offset = rng_stream.offset + AK.rand!(rng_stream, empty; prefer_threads, block_size=64) + @test rng_stream.offset == stream_offset + + @test AK.reset!(rng_stream) === rng_stream + @test rng_stream.offset == UInt64(0) - rng_imm = ImmutableWithOffsetRNG(UInt64(0x1234), AK.Philox(), UInt64(17)) y1 = array_from_host(zeros(Float32, 64)) y2 = array_from_host(zeros(Float32, 64)) - AK.rand!(rng_imm, y1; prefer_threads, block_size=64) - AK.rand!(rng_imm, y2; prefer_threads, block_size=64) + AK.rand!(rng_stream, y1; prefer_threads, block_size=64) + AK.rand!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), y2; prefer_threads, block_size=64) @test Array(y1) == Array(y2) - @test AK.reset!(rng_stream) === rng_stream - @test rng_stream.offset == UInt64(0) - @test_throws ArgumentError AK.reset!(rng_no_offset) - @test_throws ArgumentError AK.reset!(rng_imm) + mutable struct DummyRNG + seed::UInt64 + alg::AK.Philox + offset::UInt64 + end + + rng_dummy = DummyRNG(UInt64(0x1234), AK.Philox(), UInt64(0)) + x = array_from_host(zeros(Float32, 16)) + @test_throws MethodError AK.rand!(rng_dummy, x; prefer_threads, block_size=64) + @test_throws MethodError AK.reset!(rng_dummy) end @@ -146,38 +139,38 @@ end @test AK._counter_from_index(1) == UInt64(0) @test AK._counter_from_index(17) == UInt64(16) - @test AK.raw_uint_type(UInt8) === UInt32 - @test AK.raw_uint_type(UInt16) === UInt32 - @test AK.raw_uint_type(UInt32) === UInt32 - @test AK.raw_uint_type(Int8) === UInt32 - @test AK.raw_uint_type(Int16) === UInt32 - @test AK.raw_uint_type(Int32) === UInt32 + @test AK._rand_scalar_uint_type(UInt8) === UInt32 + @test AK._rand_scalar_uint_type(UInt16) === UInt32 + @test AK._rand_scalar_uint_type(UInt32) === UInt32 + @test AK._rand_scalar_uint_type(Int8) === UInt32 + @test AK._rand_scalar_uint_type(Int16) === UInt32 + @test AK._rand_scalar_uint_type(Int32) === UInt32 if RUN_FLOAT16_RAND_TESTS - @test AK.raw_uint_type(Float16) === UInt32 + @test AK._rand_scalar_uint_type(Float16) === UInt32 end - @test AK.raw_uint_type(Float32) === UInt32 - @test AK.raw_uint_type(UInt64) === UInt64 - @test AK.raw_uint_type(Int64) === UInt64 - @test AK.raw_uint_type(Bool) === UInt32 + @test AK._rand_scalar_uint_type(Float32) === UInt32 + @test AK._rand_scalar_uint_type(UInt64) === UInt64 + @test AK._rand_scalar_uint_type(Int64) === UInt64 + @test AK._rand_scalar_uint_type(Bool) === UInt32 if RUN_FLOAT64_RAND_TESTS - @test AK.raw_uint_type(Float64) === UInt64 + @test AK._rand_scalar_uint_type(Float64) === UInt64 end - @test AK.from_uint(UInt8, UInt32(0xabcdef01)) == UInt8(0xab) - @test AK.from_uint(UInt16, UInt32(0xabcdef01)) == UInt16(0xabcd) - @test AK.from_uint(UInt32, 0b1010 % UInt32) == 0b1010 % UInt32 - @test AK.from_uint(UInt64, 0b1010 % UInt64) == 0b1010 % UInt64 - @test AK.from_uint(Int8, UInt32(0xff000000)) == Int8(-1) - @test AK.from_uint(Int16, UInt32(0xffff0000)) == Int16(-1) - @test AK.from_uint(Int32, 0b11111111111111111111111111111111 % UInt32) == Int32(-1) - @test AK.from_uint( + @test AK._rand_scalar_from_uint(UInt8, UInt32(0xabcdef01)) == UInt8(0xab) + @test AK._rand_scalar_from_uint(UInt16, UInt32(0xabcdef01)) == UInt16(0xabcd) + @test AK._rand_scalar_from_uint(UInt32, 0b1010 % UInt32) == 0b1010 % UInt32 + @test AK._rand_scalar_from_uint(UInt64, 0b1010 % UInt64) == 0b1010 % UInt64 + @test AK._rand_scalar_from_uint(Int8, UInt32(0xff000000)) == Int8(-1) + @test AK._rand_scalar_from_uint(Int16, UInt32(0xffff0000)) == Int16(-1) + @test AK._rand_scalar_from_uint(Int32, 0b11111111111111111111111111111111 % UInt32) == Int32(-1) + @test AK._rand_scalar_from_uint( Int64, 0b1111111111111111111111111111111111111111111111111111111111111111 % UInt64 ) == Int64(-1) if RUN_FLOAT16_RAND_TESTS - @test AK.from_uint(Float16, UInt32(0)) == Float16(0) + @test AK._rand_scalar_from_uint(Float16, UInt32(0)) == Float16(0) end - @test AK.from_uint(Bool, UInt32(0)) == false - @test AK.from_uint(Bool, UInt32(1)) == true + @test AK._rand_scalar_from_uint(Bool, UInt32(0)) == false + @test AK._rand_scalar_from_uint(Bool, UInt32(1)) == true if RUN_FLOAT16_RAND_TESTS @test AK.uint32_to_unit_float16(UInt32(0)) == Float16(0) From a9582a021b9592708bccf939fdf0fee36b59fc3c Mon Sep 17 00:00:00 2001 From: fjbarter Date: Wed, 25 Mar 2026 02:39:47 +0000 Subject: [PATCH 13/20] initial randn! --- docs/src/api/rand.md | 10 ++ prototype/rand/plot/Project.toml | 3 + prototype/rand/randn.jl | 53 +++++++ src/rand/rand.jl | 5 +- src/rand/randn.jl | 258 +++++++++++++++++++++++++++++++ test/randn.jl | 228 +++++++++++++++++++++++++++ test/runtests.jl | 1 + 7 files changed, 557 insertions(+), 1 deletion(-) create mode 100644 prototype/rand/plot/Project.toml create mode 100644 prototype/rand/randn.jl create mode 100644 src/rand/randn.jl create mode 100644 test/randn.jl diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index aab3e5d5..2ac9d913 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -34,6 +34,11 @@ Supported element types: - `Float16`, `Float32`, `Float64` - `Bool` +`AK.randn!` fills arrays with standard normal samples and currently supports: +- `Float16`, `Float32`, `Float64` + +`AK.randn!` uses Box-Muller with open-interval uniforms in `(0, 1)` from a branch-free midpoint mapping. + The core of the random number generation produces either a `UInt32` or `UInt64` depending on the width of the requested element type. That `UInt` is then either: - Unsigned integers: returned as-is or truncated if necessary. @@ -82,6 +87,10 @@ AK.rand!(rng, v2) # Convenience (fresh auto-seeded RNG on each call) y = oneArray{Float32}(undef, 1024) AK.rand!(y) + +# Standard normal samples +z = oneArray{Float32}(undef, 1024) +AK.randn!(rng, z) ``` ```@docs @@ -89,4 +98,5 @@ AcceleratedKernels.CounterRNG AcceleratedKernels.CounterRNGAlgorithm AcceleratedKernels.reset! AcceleratedKernels.rand! +AcceleratedKernels.randn! ``` diff --git a/prototype/rand/plot/Project.toml b/prototype/rand/plot/Project.toml new file mode 100644 index 00000000..a95f271e --- /dev/null +++ b/prototype/rand/plot/Project.toml @@ -0,0 +1,3 @@ +[deps] +AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" +Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/prototype/rand/randn.jl b/prototype/rand/randn.jl new file mode 100644 index 00000000..a21cc088 --- /dev/null +++ b/prototype/rand/randn.jl @@ -0,0 +1,53 @@ +using BenchmarkTools +using CUDA + +import AcceleratedKernels as AK + + +const N = 100_000_000 +const GPU_BLOCK_SIZE = 256 + +const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox()) + +TestType = Float32 + +x_cuda = CuArray{TestType}(undef, N) +x_philox = CuArray{TestType}(undef, N) +x_cpu = Vector{TestType}(undef, N) + + +function run_cuda_randn!(x) + CUDA.randn!(x) + CUDA.synchronize() + return x +end + + +function run_ak_randn_gpu!(rng, x) + AK.randn!(rng, x; block_size=GPU_BLOCK_SIZE) + AK.synchronize(AK.get_backend(x)) + return x +end + + +function run_ak_randn_cpu!(rng, x) + AK.randn!(rng, x) + return x +end + +# warmup compile +run_cuda_randn!(x_cuda) +run_ak_randn_gpu!(RNG_PHILOX, x_philox) + +println("N = ", N) +println("CPU threads: ", Threads.nthreads()) + +println("\nCUDA.randn! benchmark (CuArray{$TestType}, in-place)") +display(@benchmark run_cuda_randn!($x_cuda)) + +println("\nAK.randn! Philox benchmark (GPU, CuArray{$TestType})") +display(@benchmark run_ak_randn_gpu!($RNG_PHILOX, $x_philox)) + +# println("\nAK.randn! benchmark (CPU, Vector{$TestType}, Philox)") +# display(@benchmark run_ak_randn_cpu!($RNG_PHILOX, $x_cpu)) + diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 833bcaed..bafd0bd4 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -66,6 +66,9 @@ include("splitmix.jl") include("philox.jl") include("threefry.jl") +# Normally distributed scalar generators and randn! +include("randn.jl") + @@ -121,7 +124,7 @@ function rand!( @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" - # Local isbits captures from potentially mutable rng object + # Local isbits captures from mutable rng object seed, alg, initial_offset = rng.seed, rng.alg, rng.offset foreachindex( diff --git a/src/rand/randn.jl b/src/rand/randn.jl new file mode 100644 index 00000000..f6acb0ef --- /dev/null +++ b/src/rand/randn.jl @@ -0,0 +1,258 @@ +const ALLOWED_RANDN_SCALARS = Union{Float16, Float32, Float64} + +const U24_MAX_SAFE_MIDPOINT = UInt32(0x00fffffe) # 2^24 - 2 +const U53_MAX_SAFE_MIDPOINT = UInt64(0x001ffffffffffffe) # 2^53 - 2 +const MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) # 2^-24 +const MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) # 2^-53 + + + + +#= +The below Float constructions are not duplicates of those in utilities.jl - they are needed to +ensure an interval of (0, 1) as opposed to [0, 1). Achieving this purely logically with midpoint +mapping means we can avoid a check for producing a 0 (which would normally cause a redraw). +Avoiding 0 is essential for Box-Muller due to the logarithm functions. +=# + + +# Convert random UInt32 bits to Float32 in (0, 1) using midpoint mapping on a 24-bit grid. +@inline function uint32_to_open_unit_float32_midpoint(u::UInt32)::Float32 + # `min` keeps the top midpoint below one after Float32 rounding. + k = min(u >> 8, U24_MAX_SAFE_MIDPOINT) + return (Float32(k) + 0.5f0) * MIDPOINT_SCALE_F32 +end + + +# Convert random UInt64 bits to Float64 in (0, 1) using midpoint mapping on a 53-bit grid. +@inline function uint64_to_open_unit_float64_midpoint(u::UInt64)::Float64 + # `min` keeps the top midpoint below one after Float64 rounding. + k = min(u >> 11, U53_MAX_SAFE_MIDPOINT) + return (Float64(k) + 0.5) * MIDPOINT_SCALE_F64 +end + + +# Float16 path reuses Float32 midpoint sampling for robust math in Box-Muller. +@inline function rand_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float16}, +)::Float16 + return Float16(rand_open01(seed, alg, counter, Float32)) +end + + +@inline function rand_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float32}, +)::Float32 + return uint32_to_open_unit_float32_midpoint(rand_uint(seed, alg, counter, UInt32)) +end + + +@inline function rand_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float64}, +)::Float64 + return uint64_to_open_unit_float64_midpoint(rand_uint(seed, alg, counter, UInt64)) +end + + +@inline function rand_open01(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} + throw(ArgumentError( + "Unsupported open-interval random type $(T). Supported: $(ALLOWED_RANDN_SCALARS)" + )) +end + + +@inline function randn_pair( + seed::UInt64, + alg::CounterRNGAlgorithm, + pair_counter::UInt64, + ::Type{Float16}, +)::Tuple{Float16, Float16} + z0, z1 = randn_pair(seed, alg, pair_counter, Float32) + return Float16(z0), Float16(z1) +end + + +@inline function randn_pair( + seed::UInt64, + alg::CounterRNGAlgorithm, + pair_counter::UInt64, + ::Type{Float32}, +)::Tuple{Float32, Float32} + u = rand_uint(seed, alg, pair_counter, UInt64) + u1 = uint32_to_open_unit_float32_midpoint(_u32_lo(u)) + u2 = uint32_to_open_unit_float32_midpoint(_u32_hi(u)) + radius = sqrt(-2.0f0 * log(u1)) + theta = Float32(2pi) * u2 + stheta, ctheta = sincos(theta) + return radius * ctheta, radius * stheta +end + + +@inline function randn_pair( + seed::UInt64, + alg::CounterRNGAlgorithm, + pair_counter::UInt64, + ::Type{Float64}, +)::Tuple{Float64, Float64} + c0 = pair_counter << 1 + u1 = rand_open01(seed, alg, c0, Float64) + u2 = rand_open01(seed, alg, c0 + UInt64(1), Float64) + radius = sqrt(-2.0 * log(u1)) + theta = Float64(2pi) * u2 + stheta, ctheta = sincos(theta) + return radius * ctheta, radius * stheta +end + + +@inline function randn_pair(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} + throw(ArgumentError( + "Unsupported normal random type $(T). Supported: $(ALLOWED_RANDN_SCALARS)" + )) +end + + +@inline function randn_scalar( + seed::UInt64, + alg::CounterRNGAlgorithm, + normal_counter::UInt64, + ::Type{T}, +)::T where {T <: ALLOWED_RANDN_SCALARS} + pair_counter = normal_counter >> 1 + z0, z1 = randn_pair(seed, alg, pair_counter, T) + return iszero(normal_counter & UInt64(0x1)) ? z0 : z1 +end + + +@inline function randn_scalar(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} + throw(ArgumentError( + "Unsupported normal random scalar type $(T). Supported: $(ALLOWED_RANDN_SCALARS)" + )) +end + + +""" + randn!( + rng::CounterRNG, + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + + # Implementation choice + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, + ) where {T <: AbstractFloat} + +Fill `v` in-place with pseudo-random samples from a standard normal distribution. + +For `v[i]`, the normal stream counter is `rng.offset + UInt64(i - 1)` in linear indexing order. +Values are generated using Box-Muller from midpoint-open uniforms in `(0, 1)`. + +After filling `v`, `rng.offset` advances by `length(v)`. +""" +function randn!( + rng::CounterRNG, + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) where T + + @argcheck T <: ALLOWED_RANDN_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)" + + isempty(v) && return v + + # Local isbits captures from mutable rng object. + seed, alg, initial_offset = rng.seed, rng.alg, rng.offset + len = length(v) + pair_start = initial_offset >> 1 + + # Even stream offset is the common path and maps pair `i` to output indices `(2i-1, 2i)`. + if iszero(initial_offset & UInt64(0x1)) + pair_count = cld(len, 2) + pair_indices = Base.OneTo(pair_count) + + # Fully branch-free hot path when both offset and length are even. + if iseven(len) + foreachindex( + pair_indices, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + pair_counter = pair_start + _counter_from_index(i) + z0, z1 = randn_pair(seed, alg, pair_counter, T) + i0 = (i << 1) - 1 + @inbounds v[i0] = z0 + @inbounds v[i0 + 1] = z1 + end + else + foreachindex( + pair_indices, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + pair_counter = pair_start + _counter_from_index(i) + z0, z1 = randn_pair(seed, alg, pair_counter, T) + i0 = (i << 1) - 1 + @inbounds v[i0] = z0 + i1 = i0 + 1 + + if i1 <= len + @inbounds v[i1] = z1 + end + end + end + else + # Odd stream offset shifts pair `i` to `(2i-2, 2i-1)`; only the first z0 is out of range. + pair_count = cld(len + 1, 2) + pair_indices = Base.OneTo(pair_count) + + foreachindex( + pair_indices, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + pair_counter = pair_start + _counter_from_index(i) + z0, z1 = randn_pair(seed, alg, pair_counter, T) + i0 = (i << 1) - 2 + + if i0 >= 1 + @inbounds v[i0] = z0 + end + + i1 = i0 + 1 + if i1 <= len + @inbounds v[i1] = z1 + end + end + end + + rng.offset += UInt64(len) + + v +end + + +function randn!( + v::AbstractArray, + args...; + kwargs..., +) + return randn!(CounterRNG(), v, args...; kwargs...) +end diff --git a/test/randn.jl b/test/randn.jl new file mode 100644 index 00000000..c0e9c56a --- /dev/null +++ b/test/randn.jl @@ -0,0 +1,228 @@ +const RANDN_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) +const RANDN_FLOAT_TYPES_BACKEND = IS_CPU_BACKEND ? (Float16, Float32, Float64) : (Float32,) + + +_is_finite(v) = all(isfinite, v) + + +function _randn_fill_reference!( + rng, + x::AbstractArray{T}; + counter_offset::UInt64=UInt64(0), +) where {T <: AK.ALLOWED_RANDN_SCALARS} + @inbounds for i in eachindex(x) + x[i] = AK.randn_scalar(rng.seed, rng.alg, counter_offset + UInt64(i - one(i)), T) + end + return x +end + + +function _assert_randn_matches_reference!(rng, x; kwargs...) + counter_offset = rng.offset + AK.randn!(rng, x; kwargs...) + ref = zeros(eltype(x), size(x)) + _randn_fill_reference!(rng, ref; counter_offset) + @test Array(x) == ref + return x +end + + +@testset "randn" begin + @testset "open interval helpers" begin + @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(UInt32(0)) < 1.0f0 + @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(typemax(UInt32)) < 1.0f0 + @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 + @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 + end + + + @testset "rand_open01 and randn_scalar" begin + seed = UInt64(0x123456789abcdef) + for alg in RANDN_ALGS + for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) + u32 = AK.rand_open01(seed, alg, c, Float32) + @test 0.0f0 < u32 < 1.0f0 + if IS_CPU_BACKEND + u64 = AK.rand_open01(seed, alg, c, Float64) + @test 0.0 < u64 < 1.0 + end + end + + for T in RANDN_FLOAT_TYPES_BACKEND + s0 = AK.randn_scalar(seed, alg, UInt64(42), T) + s1 = AK.randn_scalar(seed, alg, UInt64(43), T) + @test s0 isa T + @test s1 isa T + @test isfinite(s0) + @test isfinite(s1) + @test s0 == AK.randn_scalar(seed, alg, UInt64(42), T) + @test s1 == AK.randn_scalar(seed, alg, UInt64(43), T) + + p0, p1 = AK.randn_pair(seed, alg, UInt64(21), T) + @test AK.randn_scalar(seed, alg, UInt64(42), T) == p0 + @test AK.randn_scalar(seed, alg, UInt64(43), T) == p1 + end + end + + @test_throws ArgumentError AK.randn_scalar(seed, AK.Philox(), UInt64(0), UInt32) + end + + + @testset "randn! explicit rng" begin + lengths = (0, 1, 31, 32, 33, 257, 1024) + + for alg in RANDN_ALGS + rng = AK.CounterRNG(0x123456789abcdef; alg) + + for T in RANDN_FLOAT_TYPES_BACKEND + for len in lengths + x = array_from_host(zeros(T, len)) + _assert_randn_matches_reference!(rng, x; prefer_threads, block_size=64) + @test _is_finite(Array(x)) + end + end + + for T in RANDN_FLOAT_TYPES_BACKEND + x1 = array_from_host(zeros(T, 2048)) + x2 = array_from_host(zeros(T, 2048)) + rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) + rng2 = AK.CounterRNG(rng.seed; alg=rng.alg) + AK.randn!(rng1, x1; prefer_threads, block_size=64) + AK.randn!(rng2, x2; prefer_threads, block_size=257) + @test Array(x1) == Array(x2) + end + + for T in RANDN_FLOAT_TYPES_BACKEND + rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) + rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) + x1 = array_from_host(zeros(T, 2048)) + x2 = array_from_host(zeros(T, 2048)) + AK.randn!(rng1, x1; prefer_threads, block_size=64) + AK.randn!(rng2, x2; prefer_threads, block_size=64) + @test Array(x1) != Array(x2) + end + end + end + + + @testset "counter rng offset behavior" begin + rng_stream = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox(), offset=UInt64(17)) + s1 = array_from_host(zeros(Float32, 99)) + s2 = array_from_host(zeros(Float32, 101)) + s12 = array_from_host(zeros(Float32, 200)) + AK.randn!(rng_stream, s1; prefer_threads, block_size=64) + @test rng_stream.offset == UInt64(116) + AK.randn!(rng_stream, s2; prefer_threads, block_size=64) + @test rng_stream.offset == UInt64(217) + + rng_once = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox(), offset=UInt64(17)) + AK.randn!(rng_once, s12; prefer_threads, block_size=64) + @test vcat(Array(s1), Array(s2)) == Array(s12) + @test rng_once.offset == UInt64(217) + + empty = array_from_host(zeros(Float32, 0)) + stream_offset = rng_stream.offset + AK.randn!(rng_stream, empty; prefer_threads, block_size=64) + @test rng_stream.offset == stream_offset + + @test AK.reset!(rng_stream) === rng_stream + @test rng_stream.offset == UInt64(0) + + y1 = array_from_host(zeros(Float32, 64)) + y2 = array_from_host(zeros(Float32, 64)) + AK.randn!(rng_stream, y1; prefer_threads, block_size=64) + AK.randn!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), y2; prefer_threads, block_size=64) + @test Array(y1) == Array(y2) + end + + + @testset "reset!" begin + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + x1 = array_from_host(zeros(Float32, 512)) + x2 = array_from_host(zeros(Float32, 512)) + + AK.randn!(rng, x1; prefer_threads, block_size=64) + @test rng.offset == UInt64(512) + @test AK.reset!(rng) === rng + @test rng.offset == UInt64(0) + AK.randn!(rng, x2; prefer_threads, block_size=64) + + @test Array(x1) == Array(x2) + end + + + @testset "randn! n-dimensional and views" begin + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + + for T in RANDN_FLOAT_TYPES_BACKEND + xnd = array_from_host(zeros(T, 7, 11, 5)) + _assert_randn_matches_reference!(rng, xnd; prefer_threads, block_size=128) + end + + if IS_CPU_BACKEND + for T in RANDN_FLOAT_TYPES_BACKEND + base = zeros(T, 64) + view_x = @view base[2:2:end] + AK.randn!( + rng, view_x; + max_tasks=Threads.nthreads(), + min_elems=1, + prefer_threads=true + ) + ref_view = zeros(T, length(view_x)) + _randn_fill_reference!( + rng, ref_view; + counter_offset=rng.offset - UInt64(length(view_x)), + ) + @test collect(view_x) == ref_view + end + end + end + + + @testset "randn! convenience" begin + ref1 = array_from_host(zeros(Float32, 1024)) + ref2 = array_from_host(zeros(Float32, 1024)) + x1 = array_from_host(zeros(Float32, 1024)) + x2 = array_from_host(zeros(Float32, 1024)) + + Random.seed!(0xabcdef) + seed1 = Random.rand(Random.default_rng(), UInt64) + AK.randn!(AK.CounterRNG(seed1; alg=AK.Philox()), ref1; prefer_threads, block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) + AK.randn!(AK.CounterRNG(seed2; alg=AK.Philox()), ref2; prefer_threads, block_size=64) + + Random.seed!(0xabcdef) + AK.randn!(x1; prefer_threads, block_size=64) + AK.randn!(x2; prefer_threads, block_size=64) + @test Array(x1) == Array(ref1) + @test Array(x2) == Array(ref2) + + x_bad = zeros(UInt32, 16) + @test_throws ArgumentError AK.randn!(x_bad; prefer_threads) + @test_throws ArgumentError AK.randn!(AK.CounterRNG(0x1), x_bad; prefer_threads) + end + + + @testset "moments sanity" begin + n = 200_000 + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + + for T in RANDN_FLOAT_TYPES_BACKEND + x = array_from_host(zeros(T, n)) + AK.randn!(rng, x; prefer_threads, block_size=128) + xa = Float64.(Array(x)) + + m = sum(xa) / length(xa) + v = sum((xi - m)^2 for xi in xa) / length(xa) + + if T === Float16 + @test abs(m) < 0.1 + @test abs(v - one(v)) < 0.15 + else + @test abs(m) < 0.01 + @test abs(v - one(v)) < 0.03 + end + end + end +end diff --git a/test/runtests.jl b/test/runtests.jl index d1a2d695..5d3a6ad7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -76,6 +76,7 @@ include("partition.jl") include("looping.jl") include("map.jl") include("rand.jl") +include("randn.jl") include("sort.jl") include("reduce.jl") include("accumulate.jl") From 61aa11dc582ac474df2e05bda3cbad7d6f34c208 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Thu, 26 Mar 2026 13:23:44 +0000 Subject: [PATCH 14/20] ensure compile-time initial index bias, now beating CUDA for both odd and even offsets + array lengths. Added convenience rand() and randn() convenience constructors using KernelAbstractions.allocate based on the provided backend, Type, and dims --- prototype/rand/Project.toml | 1 + prototype/rand/randn.jl | 2 +- src/rand/rand.jl | 56 ++++++++++++ src/rand/randn.jl | 167 ++++++++++++++++++++++++------------ src/rand/utilities.jl | 19 ++++ test/rand.jl | 40 +++++++++ test/randn.jl | 118 +++++++++++++++++-------- 7 files changed, 309 insertions(+), 94 deletions(-) diff --git a/prototype/rand/Project.toml b/prototype/rand/Project.toml index 7757b4d8..675e6c7b 100644 --- a/prototype/rand/Project.toml +++ b/prototype/rand/Project.toml @@ -3,5 +3,6 @@ AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" Cthulhu = "f68482b8-f384-11e8-15f7-abe071a5a75f" +KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" PProf = "e4faabce-9ead-11e9-39d9-4379958e3056" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/prototype/rand/randn.jl b/prototype/rand/randn.jl index a21cc088..8370d914 100644 --- a/prototype/rand/randn.jl +++ b/prototype/rand/randn.jl @@ -7,7 +7,7 @@ import AcceleratedKernels as AK const N = 100_000_000 const GPU_BLOCK_SIZE = 256 -const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox()) +const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox(), offset=0x0) TestType = Float32 diff --git a/src/rand/rand.jl b/src/rand/rand.jl index bafd0bd4..c36a61e3 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -147,3 +147,59 @@ function rand!( ) return rand!(CounterRNG(), v, args...; kwargs...) end + + +""" + rand( + rng::CounterRNG, + backend::Backend, + ::Type{T}, + dims::Integer...; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + block_size::Int=256, + ) where T + +Allocate an array of element type `T` on `backend` with shape `dims`, fill it in-place via +[`rand!`](@ref), and return it. +""" +function rand( + rng::CounterRNG, + backend::Backend, + ::Type{T}, + dims::Integer...; + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) where T + return _allocate_and_fill( + rand!, rng, backend, T, dims...; + max_tasks, min_elems, prefer_threads, block_size, + ) +end + + +function rand( + backend::Backend, + ::Type{T}, + dims::Integer...; + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) where T + return rand( + CounterRNG(), backend, T, dims...; + max_tasks, min_elems, prefer_threads, block_size, + ) +end diff --git a/src/rand/randn.jl b/src/rand/randn.jl index f6acb0ef..f3cce140 100644 --- a/src/rand/randn.jl +++ b/src/rand/randn.jl @@ -139,6 +139,59 @@ end end +# `Val{ODD}` keeps parity in the type domain so each specialization (`ODD==0` / `ODD==1`) +# can fold index bias at compile time. +# - `Val{0}` => even-offset pair writes at indices `(2i-1, 2i)` so bias is `-1` +# - `Val{1}` => odd-offset pair writes at indices `(2i, 2i+1)` after prefix handling so bias is `0` +@inline _randn_i0_bias(::Val{0}) = -1 +@inline _randn_i0_bias(::Val{1}) = 0 + + +@inline function _randn_core!( + v::AbstractArray{T}, seed, alg, initial_offset, + backend, max_tasks, min_elems, prefer_threads, block_size, + ::Val{ODD}, +) where {T, ODD} + + len = length(v) + prefix_len = ODD + + # If offset is odd, need to individually handle the first element. + prefix_len == 1 && @allowscalar @inbounds v[1] = randn_scalar(seed, alg, initial_offset, T) + + # Stream is now even-aligned, so can foreachindex through the pairs. + pair_start = (initial_offset + UInt64(prefix_len)) >> 1 + + # Capture `Val(ODD)` into the closure so bias stays a compile-time constant inside the loop. + odd_val = Val(ODD) + i0_bias = _randn_i0_bias(odd_val) + remaining_len = len - prefix_len + pair_count = remaining_len >> 1 + + if pair_count > 0 + foreachindex( + Base.OneTo(pair_count), backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + pair_counter = pair_start + _counter_from_index(i) + z0, z1 = randn_pair(seed, alg, pair_counter, T) + i0 = (i << 1) + _randn_i0_bias(odd_val) + @inbounds v[i0] = z0 + @inbounds v[i0 + 1] = z1 + end + end + + # If an extra element remains after pair writing, fill it individually. + tail_index = (pair_count << 1) + i0_bias + 2 + if tail_index <= len + tail_counter = initial_offset + UInt64(tail_index - 1) + @allowscalar @inbounds v[tail_index] = randn_scalar(seed, alg, tail_counter, T) + end + + return v +end + + """ randn!( rng::CounterRNG, @@ -183,67 +236,19 @@ function randn!( # Local isbits captures from mutable rng object. seed, alg, initial_offset = rng.seed, rng.alg, rng.offset - len = length(v) - pair_start = initial_offset >> 1 - - # Even stream offset is the common path and maps pair `i` to output indices `(2i-1, 2i)`. - if iszero(initial_offset & UInt64(0x1)) - pair_count = cld(len, 2) - pair_indices = Base.OneTo(pair_count) - - # Fully branch-free hot path when both offset and length are even. - if iseven(len) - foreachindex( - pair_indices, backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - pair_counter = pair_start + _counter_from_index(i) - z0, z1 = randn_pair(seed, alg, pair_counter, T) - i0 = (i << 1) - 1 - @inbounds v[i0] = z0 - @inbounds v[i0 + 1] = z1 - end - else - foreachindex( - pair_indices, backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - pair_counter = pair_start + _counter_from_index(i) - z0, z1 = randn_pair(seed, alg, pair_counter, T) - i0 = (i << 1) - 1 - @inbounds v[i0] = z0 - i1 = i0 + 1 - - if i1 <= len - @inbounds v[i1] = z1 - end - end - end - else - # Odd stream offset shifts pair `i` to `(2i-2, 2i-1)`; only the first z0 is out of range. - pair_count = cld(len + 1, 2) - pair_indices = Base.OneTo(pair_count) - - foreachindex( - pair_indices, backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - pair_counter = pair_start + _counter_from_index(i) - z0, z1 = randn_pair(seed, alg, pair_counter, T) - i0 = (i << 1) - 2 - if i0 >= 1 - @inbounds v[i0] = z0 - end + core_args = ( + v, seed, alg, initial_offset, backend, max_tasks, min_elems, prefer_threads, block_size + ) - i1 = i0 + 1 - if i1 <= len - @inbounds v[i1] = z1 - end - end + # Dispatch depending on required initial index bias + if iseven(initial_offset) + _randn_core!(core_args..., Val(0)) + else + _randn_core!(core_args..., Val(1)) end - rng.offset += UInt64(len) + rng.offset += UInt64(length(v)) v end @@ -256,3 +261,51 @@ function randn!( ) return randn!(CounterRNG(), v, args...; kwargs...) end + + +""" + randn( + rng::CounterRNG, + backend::Backend, + ::Type{T}, + dims::Integer...; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + block_size::Int=256, + ) where T + +Allocate an array of element type `T` on `backend` with shape `dims`, fill it in-place via +[`randn!`](@ref), and return it. +""" +function randn( + rng::CounterRNG, + backend::Backend, + ::Type{T}, + dims::Integer...; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + block_size::Int=256, +) where T + return _allocate_and_fill( + randn!, rng, backend, T, dims...; + max_tasks, min_elems, prefer_threads, block_size, + ) +end + + +function randn( + backend::Backend, + ::Type{T}, + dims::Integer...; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + block_size::Int=256, +) where T + return randn( + CounterRNG(), backend, T, dims...; + max_tasks, min_elems, prefer_threads, block_size, + ) +end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index f2159c55..b2c60dbd 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -15,6 +15,25 @@ @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) +# Shared allocation + fill helper for rand/randn convenience constructors. +@inline function _allocate_and_fill( + fill!, + rng::CounterRNG, + backend::Backend, + ::Type{T}, + dims::Integer...; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + block_size::Int=256, +) where {T} + dims_int = Base.map(Int, dims) + v = KernelAbstractions.allocate(backend, T, dims_int) + fill!(rng, v, backend; max_tasks, min_elems, prefer_threads, block_size) + return v +end + + # Internal scalar eltypes currently supported by rand!. const ALLOWED_RAND_SCALARS = Union{ UInt8, UInt16, UInt32, UInt64, diff --git a/test/rand.jl b/test/rand.jl index 90e285af..d3eaccae 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -362,4 +362,44 @@ end @test_throws ArgumentError AK.rand!(x_bad; prefer_threads) @test_throws ArgumentError AK.rand!(AK.CounterRNG(0x1), x_bad; prefer_threads) end + + + @testset "rand allocation convenience" begin + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) + y = AK.rand(rng, BACKEND, Float32, Int32(6), UInt16(7); prefer_threads, block_size=64) + @test size(y) == (6, 7) + @test eltype(y) === Float32 + @test _is_unit_interval(Array(y)) + @test rng.offset == UInt64(length(y)) + + rng_alloc = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) + rng_fill = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) + y_alloc = AK.rand(rng_alloc, BACKEND, Float32, 128; prefer_threads, block_size=64) + y_fill = array_from_host(zeros(Float32, 128)) + AK.rand!(rng_fill, y_fill; prefer_threads, block_size=64) + @test Array(y_alloc) == Array(y_fill) + @test rng_alloc.offset == rng_fill.offset == UInt64(128) + + # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. + AK.rand(BACKEND, Float32, 1; prefer_threads, block_size=64) + + # Auto-seeded constructor should match explicit seed capture from default RNG. + Random.seed!(0x9abc) + seed = Random.rand(Random.default_rng(), UInt64) + ref = AK.rand(AK.CounterRNG(seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x9abc) + x = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x) == Array(ref) + + # Reseeding should reproduce the same auto-seeded draw. + Random.seed!(0x7777) + x1 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x7777) + x2 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) + + @test_throws ArgumentError AK.rand(AK.CounterRNG(0x1), BACKEND, UInt128, 16; prefer_threads) + @test_throws MethodError AK.rand(AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.rand(BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + end end diff --git a/test/randn.jl b/test/randn.jl index c0e9c56a..82261c87 100644 --- a/test/randn.jl +++ b/test/randn.jl @@ -1,8 +1,12 @@ const RANDN_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) const RANDN_FLOAT_TYPES_BACKEND = IS_CPU_BACKEND ? (Float16, Float32, Float64) : (Float32,) +const RANDN_LENGTHS = (0, 1, 2, 31, 32, 33, 257, 1024) -_is_finite(v) = all(isfinite, v) +_all_finite(v) = all(isfinite, v) +_randn_reference_atol(::Type{Float16}) = 16 * eps(Float16) +_randn_reference_atol(::Type{Float32}) = 64 * eps(Float32) +_randn_reference_atol(::Type{Float64}) = 64 * eps(Float64) function _randn_fill_reference!( @@ -22,28 +26,40 @@ function _assert_randn_matches_reference!(rng, x; kwargs...) AK.randn!(rng, x; kwargs...) ref = zeros(eltype(x), size(x)) _randn_fill_reference!(rng, ref; counter_offset) - @test Array(x) == ref + xa = Array(x) + + if IS_CPU_BACKEND + @test xa == ref + else + # randn uses Box-Muller (`log`, `sqrt`, `sincos`), and GPU libm implementations are not + # bit-identical to CPU scalar libm. Stream/counter mapping is still deterministic, but the + # final Float32 values can differ by a few ULP, so we use a tight absolute tolerance here. + atol = _randn_reference_atol(eltype(xa)) + @test all(isapprox.(xa, ref; rtol=zero(atol), atol)) + end + return x end @testset "randn" begin - @testset "open interval helpers" begin + @testset "scalar helpers" begin @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(UInt32(0)) < 1.0f0 @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(typemax(UInt32)) < 1.0f0 - @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 - @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 - end + if IS_CPU_BACKEND + @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 + @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 + end - @testset "rand_open01 and randn_scalar" begin seed = UInt64(0x123456789abcdef) for alg in RANDN_ALGS - for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - u32 = AK.rand_open01(seed, alg, c, Float32) + for counter in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) + u32 = AK.rand_open01(seed, alg, counter, Float32) @test 0.0f0 < u32 < 1.0f0 + if IS_CPU_BACKEND - u64 = AK.rand_open01(seed, alg, c, Float64) + u64 = AK.rand_open01(seed, alg, counter, Float64) @test 0.0 < u64 < 1.0 end end @@ -51,6 +67,7 @@ end for T in RANDN_FLOAT_TYPES_BACKEND s0 = AK.randn_scalar(seed, alg, UInt64(42), T) s1 = AK.randn_scalar(seed, alg, UInt64(43), T) + @test s0 isa T @test s1 isa T @test isfinite(s0) @@ -59,26 +76,25 @@ end @test s1 == AK.randn_scalar(seed, alg, UInt64(43), T) p0, p1 = AK.randn_pair(seed, alg, UInt64(21), T) - @test AK.randn_scalar(seed, alg, UInt64(42), T) == p0 - @test AK.randn_scalar(seed, alg, UInt64(43), T) == p1 + @test p0 == AK.randn_scalar(seed, alg, UInt64(42), T) + @test p1 == AK.randn_scalar(seed, alg, UInt64(43), T) end end + @test_throws ArgumentError AK.rand_open01(seed, AK.Philox(), UInt64(0), UInt32) @test_throws ArgumentError AK.randn_scalar(seed, AK.Philox(), UInt64(0), UInt32) end @testset "randn! explicit rng" begin - lengths = (0, 1, 31, 32, 33, 257, 1024) - for alg in RANDN_ALGS rng = AK.CounterRNG(0x123456789abcdef; alg) for T in RANDN_FLOAT_TYPES_BACKEND - for len in lengths + for len in RANDN_LENGTHS x = array_from_host(zeros(T, len)) _assert_randn_matches_reference!(rng, x; prefer_threads, block_size=64) - @test _is_finite(Array(x)) + @test _all_finite(Array(x)) end end @@ -87,16 +103,18 @@ end x2 = array_from_host(zeros(T, 2048)) rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) rng2 = AK.CounterRNG(rng.seed; alg=rng.alg) + AK.randn!(rng1, x1; prefer_threads, block_size=64) AK.randn!(rng2, x2; prefer_threads, block_size=257) @test Array(x1) == Array(x2) end for T in RANDN_FLOAT_TYPES_BACKEND - rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) - rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) + rng1 = AK.CounterRNG(rng.seed; alg=rng.alg) + rng2 = AK.CounterRNG(rng.seed + UInt64(1); alg=rng.alg) + AK.randn!(rng1, x1; prefer_threads, block_size=64) AK.randn!(rng2, x2; prefer_threads, block_size=64) @test Array(x1) != Array(x2) @@ -105,11 +123,12 @@ end end - @testset "counter rng offset behavior" begin + @testset "offset and reset semantics" begin rng_stream = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox(), offset=UInt64(17)) s1 = array_from_host(zeros(Float32, 99)) s2 = array_from_host(zeros(Float32, 101)) s12 = array_from_host(zeros(Float32, 200)) + AK.randn!(rng_stream, s1; prefer_threads, block_size=64) @test rng_stream.offset == UInt64(116) AK.randn!(rng_stream, s2; prefer_threads, block_size=64) @@ -136,22 +155,7 @@ end end - @testset "reset!" begin - rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) - x1 = array_from_host(zeros(Float32, 512)) - x2 = array_from_host(zeros(Float32, 512)) - - AK.randn!(rng, x1; prefer_threads, block_size=64) - @test rng.offset == UInt64(512) - @test AK.reset!(rng) === rng - @test rng.offset == UInt64(0) - AK.randn!(rng, x2; prefer_threads, block_size=64) - - @test Array(x1) == Array(x2) - end - - - @testset "randn! n-dimensional and views" begin + @testset "shapes and views" begin rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) for T in RANDN_FLOAT_TYPES_BACKEND @@ -163,12 +167,14 @@ end for T in RANDN_FLOAT_TYPES_BACKEND base = zeros(T, 64) view_x = @view base[2:2:end] + AK.randn!( rng, view_x; max_tasks=Threads.nthreads(), min_elems=1, - prefer_threads=true + prefer_threads=true, ) + ref_view = zeros(T, length(view_x)) _randn_fill_reference!( rng, ref_view; @@ -204,6 +210,46 @@ end end + @testset "randn allocation convenience" begin + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) + y = AK.randn(rng, BACKEND, Float32, Int32(6), UInt16(7); prefer_threads, block_size=64) + @test size(y) == (6, 7) + @test eltype(y) === Float32 + @test _all_finite(Array(y)) + @test rng.offset == UInt64(length(y)) + + rng_alloc = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) + rng_fill = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) + y_alloc = AK.randn(rng_alloc, BACKEND, Float32, 128; prefer_threads, block_size=64) + y_fill = array_from_host(zeros(Float32, 128)) + AK.randn!(rng_fill, y_fill; prefer_threads, block_size=64) + @test Array(y_alloc) == Array(y_fill) + @test rng_alloc.offset == rng_fill.offset == UInt64(128) + + # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. + AK.randn(BACKEND, Float32, 1; prefer_threads, block_size=64) + + # Auto-seeded constructor should match explicit seed capture from default RNG. + Random.seed!(0x9abc) + seed = Random.rand(Random.default_rng(), UInt64) + ref = AK.randn(AK.CounterRNG(seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x9abc) + x = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x) == Array(ref) + + # Reseeding should reproduce the same auto-seeded draw. + Random.seed!(0x7777) + x1 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x7777) + x2 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) + + @test_throws ArgumentError AK.randn(AK.CounterRNG(0x1), BACKEND, UInt32, 16; prefer_threads) + @test_throws MethodError AK.randn(AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.randn(BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + end + + @testset "moments sanity" begin n = 200_000 rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) From 9abe3881f5afb0ef56b9a794960609a5fd26adc0 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Thu, 26 Mar 2026 17:11:45 +0000 Subject: [PATCH 15/20] attempt to fix oneAPI test precompilation hang with Julia v1.10 by disabling package images --- .buildkite/pipeline.yml | 13 ++++++------- src/rand/rand.jl | 17 +++++++++++++++-- src/rand/randn.jl | 39 +++++++++++++++++++++++++++------------ src/rand/utilities.jl | 13 +++++-------- 4 files changed, 53 insertions(+), 29 deletions(-) diff --git a/.buildkite/pipeline.yml b/.buildkite/pipeline.yml index 43cfba3e..c0e58308 100644 --- a/.buildkite/pipeline.yml +++ b/.buildkite/pipeline.yml @@ -88,14 +88,13 @@ steps: - JuliaCI/julia#v1: version: "1.10" command: | - julia -e 'using Pkg + julia --pkgimages=no -e 'using Pkg - println("--- :julia: Instantiating environment") - Pkg.add("oneAPI") - Pkg.develop(path=".") - - println("+++ :julia: Running tests") - Pkg.test("AcceleratedKernels", test_args=["--oneAPI"])' + println("--- :julia: Instantiating environment") + Pkg.add("oneAPI") + Pkg.develop(path=".") + println("+++ :julia: Running tests") + Pkg.test("AcceleratedKernels", test_args=["--oneAPI"])' agents: queue: "juliagpu" intel: "*" diff --git a/src/rand/rand.jl b/src/rand/rand.jl index c36a61e3..af3fdef2 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -1,3 +1,10 @@ +const ALLOWED_RAND_SCALARS = Union{ + UInt8, UInt16, UInt32, UInt64, + Int8, Int16, Int32, Int64, + Float16, Float32, Float64, + Bool +} + abstract type CounterRNGAlgorithm end @@ -92,7 +99,8 @@ include("randn.jl") Fill `v` in-place with pseudo-random values using a counter-based RNG stream. For `v[i]`, the counter is `rng.offset + UInt64(i - 1)` in linear indexing order. -After filling `v`, `rng.offset` advances by `length(v)`. +After filling `v`, `rng.offset` advances by `length(v)`. It can be called without `rng`, in which +case the default `CounterRNG` is used. Supported scalar element types are: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -155,9 +163,13 @@ end backend::Backend, ::Type{T}, dims::Integer...; + + # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, prefer_threads::Bool=true, + + # GPU settings block_size::Int=256, ) where T @@ -178,7 +190,8 @@ function rand( # GPU settings block_size::Int=256, ) where T - return _allocate_and_fill( + @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" + return _allocate_and_fill_rand( rand!, rng, backend, T, dims...; max_tasks, min_elems, prefer_threads, block_size, ) diff --git a/src/rand/randn.jl b/src/rand/randn.jl index f3cce140..8d16c771 100644 --- a/src/rand/randn.jl +++ b/src/rand/randn.jl @@ -1,9 +1,11 @@ -const ALLOWED_RANDN_SCALARS = Union{Float16, Float32, Float64} +const ALLOWED_RANDN_SCALARS = Union{ + Float16, Float32, Float64 +} -const U24_MAX_SAFE_MIDPOINT = UInt32(0x00fffffe) # 2^24 - 2 -const U53_MAX_SAFE_MIDPOINT = UInt64(0x001ffffffffffffe) # 2^53 - 2 -const MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) # 2^-24 -const MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) # 2^-53 +const OPEN01_MAX_MIDPOINT_INDEX_F32 = UInt32(0x00fffffe) +const OPEN01_MAX_MIDPOINT_INDEX_F64 = UInt64(0x001ffffffffffffe) +const OPEN01_MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) +const OPEN01_MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) @@ -19,16 +21,16 @@ Avoiding 0 is essential for Box-Muller due to the logarithm functions. # Convert random UInt32 bits to Float32 in (0, 1) using midpoint mapping on a 24-bit grid. @inline function uint32_to_open_unit_float32_midpoint(u::UInt32)::Float32 # `min` keeps the top midpoint below one after Float32 rounding. - k = min(u >> 8, U24_MAX_SAFE_MIDPOINT) - return (Float32(k) + 0.5f0) * MIDPOINT_SCALE_F32 + k = min(u >> 8, OPEN01_MAX_MIDPOINT_INDEX_F32) + return (Float32(k) + 0.5f0) * OPEN01_MIDPOINT_SCALE_F32 end # Convert random UInt64 bits to Float64 in (0, 1) using midpoint mapping on a 53-bit grid. @inline function uint64_to_open_unit_float64_midpoint(u::UInt64)::Float64 # `min` keeps the top midpoint below one after Float64 rounding. - k = min(u >> 11, U53_MAX_SAFE_MIDPOINT) - return (Float64(k) + 0.5) * MIDPOINT_SCALE_F64 + k = min(u >> 11, OPEN01_MAX_MIDPOINT_INDEX_F64) + return (Float64(k) + 0.5) * OPEN01_MIDPOINT_SCALE_F64 end @@ -201,8 +203,6 @@ end # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, - - # Implementation choice prefer_threads::Bool=true, # GPU settings @@ -215,6 +215,8 @@ For `v[i]`, the normal stream counter is `rng.offset + UInt64(i - 1)` in linear Values are generated using Box-Muller from midpoint-open uniforms in `(0, 1)`. After filling `v`, `rng.offset` advances by `length(v)`. + +It can be called without an `rng`, in which case the default `CounterRNG` will be used. """ function randn!( rng::CounterRNG, @@ -269,9 +271,13 @@ end backend::Backend, ::Type{T}, dims::Integer...; + + # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, prefer_threads::Bool=true, + + # GPU settings block_size::Int=256, ) where T @@ -283,12 +289,17 @@ function randn( backend::Backend, ::Type{T}, dims::Integer...; + + # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, prefer_threads::Bool=true, + + # GPU settings block_size::Int=256, ) where T - return _allocate_and_fill( + @argcheck T <: ALLOWED_RANDN_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)" + return _allocate_and_fill_rand( randn!, rng, backend, T, dims...; max_tasks, min_elems, prefer_threads, block_size, ) @@ -299,9 +310,13 @@ function randn( backend::Backend, ::Type{T}, dims::Integer...; + + # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, prefer_threads::Bool=true, + + # GPU settings block_size::Int=256, ) where T return randn( diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index b2c60dbd..04f6929b 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -16,15 +16,19 @@ # Shared allocation + fill helper for rand/randn convenience constructors. -@inline function _allocate_and_fill( +@inline function _allocate_and_fill_rand( fill!, rng::CounterRNG, backend::Backend, ::Type{T}, dims::Integer...; + + # CPU settings max_tasks::Int=Threads.nthreads(), min_elems::Int=1, prefer_threads::Bool=true, + + # GPU settings block_size::Int=256, ) where {T} dims_int = Base.map(Int, dims) @@ -34,13 +38,6 @@ end -# Internal scalar eltypes currently supported by rand!. -const ALLOWED_RAND_SCALARS = Union{ - UInt8, UInt16, UInt32, UInt64, - Int8, Int16, Int32, Int64, - Float16, Float32, Float64, - Bool -} @inline _rand_scalar_uint_type(::Type{UInt8}) = UInt32 From 841bafb0c4e2ad0cf81af96c0a6e49caff7d64fd Mon Sep 17 00:00:00 2001 From: fjbarter Date: Thu, 26 Mar 2026 17:43:40 +0000 Subject: [PATCH 16/20] fix Threefry UInt32 device arithmetic to avoid breaking on Metal --- src/rand/threefry.jl | 19 ++++++++++--------- src/rand/utilities.jl | 2 +- test/randn.jl | 8 -------- 3 files changed, 11 insertions(+), 18 deletions(-) diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl index c9052b19..f6ef6321 100644 --- a/src/rand/threefry.jl +++ b/src/rand/threefry.jl @@ -9,9 +9,9 @@ const THREEFRY_ROTATIONS = ( const THREEFRY_ROUNDS = 20 -@inline function _threefry_key_word(k0::UInt32, k1::UInt32, k2::UInt32, idx::Int)::UInt32 - idx == 0 && return k0 - idx == 1 && return k1 +@inline function _threefry_key_word(k0::UInt32, k1::UInt32, k2::UInt32, idx::UInt32)::UInt32 + idx == UInt32(0) && return k0 + idx == UInt32(1) && return k1 return k2 end @@ -33,16 +33,17 @@ end x1 += k1 @inbounds for round in 0:(THREEFRY_ROUNDS - 1) - rot = THREEFRY_ROTATIONS[(round & 0x7) + 1] + round_u32 = UInt32(round) + rot = THREEFRY_ROTATIONS[Int((round_u32 & UInt32(0x7)) + UInt32(1))] x0 += x1 x1 = xor(_rotl32(x1, rot), x0) - if (round & 0x3) == 3 - s = (round >>> 2) + 1 - i0 = s % 3 - i1 = (s + 1) % 3 + if (round_u32 & UInt32(0x3)) == UInt32(0x3) + s = (round_u32 >>> 2) + UInt32(1) + i0 = s % UInt32(3) + i1 = (s + UInt32(1)) % UInt32(3) x0 += _threefry_key_word(k0, k1, k2, i0) - x1 += _threefry_key_word(k0, k1, k2, i1) + UInt32(s) + x1 += _threefry_key_word(k0, k1, k2, i1) + s end end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 04f6929b..556ca7b4 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -9,7 +9,7 @@ @inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) # 32-bit rotate left by r positions -@inline _rotl32(x::UInt32, r::UInt32)::UInt32 = (x << r) | (x >> (UInt32(32) - r)) +@inline _rotl32(x::UInt32, r::UInt32)::UInt32 = bitrotate(x, Int32(r)) # Get counter used for CounterRNG from element index @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) diff --git a/test/randn.jl b/test/randn.jl index 82261c87..0d239b24 100644 --- a/test/randn.jl +++ b/test/randn.jl @@ -90,14 +90,6 @@ end for alg in RANDN_ALGS rng = AK.CounterRNG(0x123456789abcdef; alg) - for T in RANDN_FLOAT_TYPES_BACKEND - for len in RANDN_LENGTHS - x = array_from_host(zeros(T, len)) - _assert_randn_matches_reference!(rng, x; prefer_threads, block_size=64) - @test _all_finite(Array(x)) - end - end - for T in RANDN_FLOAT_TYPES_BACKEND x1 = array_from_host(zeros(T, 2048)) x2 = array_from_host(zeros(T, 2048)) From 39e089ffb5a09518b248f5bf085d3830f8b3c069 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Fri, 27 Mar 2026 01:09:45 +0000 Subject: [PATCH 17/20] expand rand/randn convenience APIs and align docs/tests. Move randn open-interval helpers into utilities.jl and switch naming of internals. Simplify rand!/randn! wrappers and add convenience constructors for omitted rng, backend, or type, with backend-dependent defaults (Float64 on CPU, Float32 otherwise). Add explicit zero-arg guards so rand()/randn() require at least one dimension. Update rand.md with concise convenience semantics and examples, including type-only no-rng calls, plus doc entries for rand/randn. Expand tests to cover default-type dispatch, CPU fallback routes, typed no-rng overloads, and invalid-signature/kwarg throw behavior while preserving deterministic CounterRNG offset progression. --- docs/src/api/rand.md | 31 ++++++++- prototype/rand/Project.toml | 3 +- prototype/rand/plot/Project.toml | 3 - prototype/rand/randn.jl | 2 - prototype/rand/test_rand.jl | 25 +++---- src/rand/rand.jl | 42 +++++------ src/rand/randn.jl | 116 +++++-------------------------- src/rand/utilities.jl | 67 ++++++++++++++++++ test/rand.jl | 83 ++++++++++++++++++++++ test/randn.jl | 105 +++++++++++++++++++++++++--- test/runtests.jl | 8 +-- 11 files changed, 325 insertions(+), 160 deletions(-) delete mode 100644 prototype/rand/plot/Project.toml diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 2ac9d913..d0d41138 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -3,6 +3,10 @@ Counter-based random generation for CPU and GPU backends with deterministic stream behavior for fixed `seed`, algorithm, and call sequence. +Both in-place and allocation forms are supported: +- Uniform: `AK.rand!`, `AK.rand` +- Standard normal: `AK.randn!`, `AK.randn` + `CounterRNG` carries an internal `offset` (starting at `0`) that advances by `length(v)` on each `AK.rand!(rng, v)` call. This means chunked fills are stream-consistent: - filling `100` then `100` elements yields the same `200` values as one `200`-element fill. @@ -16,9 +20,16 @@ Use an explicit `CounterRNG` when reproducibility is required. For convenience, `AK.rand!(v)` creates a fresh `CounterRNG()` on each call using one auto-seeded `Base.rand(UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. +Likewise, `AK.rand(backend, args...)` creates a fresh auto-seeded `CounterRNG()` on each call. `AK.reset!(rng::AK.CounterRNG)` rewinds `rng.offset` to `0x0`. +Allocation convenience: +- Canonical forms are `AK.rand(rng, backend, T, dims...)` and `AK.randn(rng, backend, T, dims...)`. +- Defaults are shared: omit `rng` -> fresh `CounterRNG()`; omit `backend` -> CPU backend; omit `T` -> `Float64` on CPU backend and `Float32` otherwise. +- Common shorthands include `AK.rand(dims...)`, `AK.rand(T, dims...)`, `AK.rand(backend, dims...)`, and the corresponding `AK.randn(...)` variants. +- For explicit `rng`, both `AK.rand` and `AK.randn` advance `rng.offset` by `prod(dims)`. + Custom algorithms: - Define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm`. - Implement typed `rand_uint` methods: @@ -39,6 +50,9 @@ Supported element types: `AK.randn!` uses Box-Muller with open-interval uniforms in `(0, 1)` from a branch-free midpoint mapping. +`AK.randn!(v)` and `AK.randn(backend, args...)` create a fresh auto-seeded `CounterRNG()` on each +call, so repeated calls produce different outputs unless `Random.seed!()` is used. + The core of the random number generation produces either a `UInt32` or `UInt64` depending on the width of the requested element type. That `UInt` is then either: - Unsigned integers: returned as-is or truncated if necessary. @@ -72,6 +86,7 @@ Examples: ```julia import AcceleratedKernels as AK using oneAPI +using ROCArray # Reproducible rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) @@ -88,9 +103,19 @@ AK.rand!(rng, v2) y = oneArray{Float32}(undef, 1024) AK.rand!(y) -# Standard normal samples -z = oneArray{Float32}(undef, 1024) +# Allocation form +y_cpu_auto = AK.rand(1024) # defaults to CPU, Vector{Float64} +y_oneArray = AK.rand(oneAPIBackend(), Float32, 1024) # fresh RNG, allocate and fill oneArray +y_cpu_typed = AK.rand(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG + +# Standard normal filling +z = ROCArray{Float32}(undef, 1024) AK.randn!(rng, z) + +# Standard normal allocation form +z_cpu_auto = AK.randn(1024) # defaults to CPU, Vector{Float64} +z_ROCArray = AK.randn(oneAPIBackend(), 1024) # allocate and fill ROCArray{Float32} +z_cpu_typed = AK.randn(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG ``` ```@docs @@ -98,5 +123,7 @@ AcceleratedKernels.CounterRNG AcceleratedKernels.CounterRNGAlgorithm AcceleratedKernels.reset! AcceleratedKernels.rand! +AcceleratedKernels.rand AcceleratedKernels.randn! +AcceleratedKernels.randn ``` diff --git a/prototype/rand/Project.toml b/prototype/rand/Project.toml index 675e6c7b..d1926b1e 100644 --- a/prototype/rand/Project.toml +++ b/prototype/rand/Project.toml @@ -1,8 +1,7 @@ [deps] +AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" Cthulhu = "f68482b8-f384-11e8-15f7-abe071a5a75f" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" -PProf = "e4faabce-9ead-11e9-39d9-4379958e3056" -Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/prototype/rand/plot/Project.toml b/prototype/rand/plot/Project.toml deleted file mode 100644 index a95f271e..00000000 --- a/prototype/rand/plot/Project.toml +++ /dev/null @@ -1,3 +0,0 @@ -[deps] -AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1" -Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" diff --git a/prototype/rand/randn.jl b/prototype/rand/randn.jl index 8370d914..d552b5f8 100644 --- a/prototype/rand/randn.jl +++ b/prototype/rand/randn.jl @@ -48,6 +48,4 @@ display(@benchmark run_cuda_randn!($x_cuda)) println("\nAK.randn! Philox benchmark (GPU, CuArray{$TestType})") display(@benchmark run_ak_randn_gpu!($RNG_PHILOX, $x_philox)) -# println("\nAK.randn! benchmark (CPU, Vector{$TestType}, Philox)") -# display(@benchmark run_ak_randn_cpu!($RNG_PHILOX, $x_cpu)) diff --git a/prototype/rand/test_rand.jl b/prototype/rand/test_rand.jl index ec3ce654..5a7be0fc 100644 --- a/prototype/rand/test_rand.jl +++ b/prototype/rand/test_rand.jl @@ -11,11 +11,13 @@ const RNG_SPLITMIX = AK.CounterRNG(0x12345678; alg=AK.SplitMix64()) const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox()) const RNG_THREEFRY = AK.CounterRNG(0x12345678; alg=AK.Threefry()) -x_cuda = CuArray{Float32}(undef, N) -x_splitmix = CuArray{Float32}(undef, N) -x_philox = CuArray{Float32}(undef, N) -x_threefry = CuArray{Float32}(undef, N) -x_cpu = Vector{Float32}(undef, N) +TestType = Float32 + +x_cuda = CuArray{TestType}(undef, N) +x_splitmix = CuArray{TestType}(undef, N) +x_philox = CuArray{TestType}(undef, N) +x_threefry = CuArray{TestType}(undef, N) +x_cpu = Vector{TestType}(undef, N) function run_cuda_rand!(x) @@ -43,13 +45,11 @@ is_unit_interval(v) = all(x -> 0.0f0 <= x <= 1.0f0, v) # warmup compile run_cuda_rand!(x_cuda) -# run_ak_rand_gpu!(RNG_SPLITMIX, x_splitmix) run_ak_rand_gpu!(RNG_PHILOX, x_philox) run_ak_rand_gpu!(RNG_THREEFRY, x_threefry) run_ak_rand_cpu!(RNG_SPLITMIX, x_cpu) @assert is_unit_interval(Array(x_cuda)) -# @assert is_unit_interval(Array(x_splitmix)) @assert is_unit_interval(Array(x_philox)) @assert is_unit_interval(Array(x_threefry)) @assert is_unit_interval(x_cpu) @@ -57,18 +57,15 @@ run_ak_rand_cpu!(RNG_SPLITMIX, x_cpu) println("N = ", N) println("CPU threads: ", Threads.nthreads()) -println("\nCUDA.rand! benchmark (CuArray{Float32}, in-place)") +println("\nCUDA.rand! benchmark (CuArray{$TestType}, in-place)") display(@benchmark run_cuda_rand!($x_cuda)) -# println("\nAK.rand! SplitMix64 benchmark (GPU, CuArray{Float32})") -# display(@benchmark run_ak_rand_gpu!($RNG_SPLITMIX, $x_splitmix)) - -println("\nAK.rand! Philox benchmark (GPU, CuArray{Float32})") +println("\nAK.rand! Philox benchmark (GPU, CuArray{$TestType})") display(@benchmark run_ak_rand_gpu!($RNG_PHILOX, $x_philox)) -println("\nAK.rand! Threefry benchmark (GPU, CuArray{Float32})") +println("\nAK.rand! Threefry benchmark (GPU, CuArray{$TestType})") display(@benchmark run_ak_rand_gpu!($RNG_THREEFRY, $x_threefry)) -println("\nAK.rand! benchmark (CPU, Vector{Float32}, SplitMix64)") +println("\nAK.rand! benchmark (CPU, Vector{$TestType}, SplitMix64)") display(@benchmark run_ak_rand_cpu!($RNG_SPLITMIX, $x_cpu)) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index af3fdef2..06d3619e 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -148,13 +148,7 @@ function rand!( end -function rand!( - v::AbstractArray, - args...; - kwargs..., -) - return rand!(CounterRNG(), v, args...; kwargs...) -end +rand!(v::AbstractArray, args...; kwargs...) = rand!(CounterRNG(), v, args...; kwargs...) """ @@ -175,6 +169,11 @@ end Allocate an array of element type `T` on `backend` with shape `dims`, fill it in-place via [`rand!`](@ref), and return it. + +Convenience overloads: +- `rng` omitted: uses a fresh `CounterRNG()`. +- `backend` omitted: defaults to `CPU_BACKEND`. +- `T` omitted: defaults by backend (`Float64` on CPU backend, `Float32` otherwise). """ function rand( rng::CounterRNG, @@ -198,21 +197,16 @@ function rand( end -function rand( - backend::Backend, - ::Type{T}, - dims::Integer...; - - # CPU settings - max_tasks::Int=Threads.nthreads(), - min_elems::Int=1, - prefer_threads::Bool=true, - - # GPU settings - block_size::Int=256, -) where T - return rand( - CounterRNG(), backend, T, dims...; - max_tasks, min_elems, prefer_threads, block_size, - ) +function rand(rng::CounterRNG, backend::Backend, dims::Integer...; kwargs...) + DefaultScalarType = (backend == CPU_BACKEND) ? Float64 : Float32 + rand(rng, backend, DefaultScalarType, dims...; kwargs...) end + + +rand(rng::CounterRNG, args...; kwargs...) = rand(rng, CPU_BACKEND, args...; kwargs...) +rand(backend::Backend, args...; kwargs...) = rand(CounterRNG(), backend, args...; kwargs...) +rand(::Type{T}, dims::Integer...; kwargs...) where {T} = rand(CPU_BACKEND, T, dims...; kwargs...) +rand(dims::Integer...; kwargs...) = rand(CPU_BACKEND, dims...; kwargs...) +rand(; kwargs...) = throw(ArgumentError("rand requires at least one dimension")) + + diff --git a/src/rand/randn.jl b/src/rand/randn.jl index 8d16c771..b2b5dbb3 100644 --- a/src/rand/randn.jl +++ b/src/rand/randn.jl @@ -2,76 +2,6 @@ const ALLOWED_RANDN_SCALARS = Union{ Float16, Float32, Float64 } -const OPEN01_MAX_MIDPOINT_INDEX_F32 = UInt32(0x00fffffe) -const OPEN01_MAX_MIDPOINT_INDEX_F64 = UInt64(0x001ffffffffffffe) -const OPEN01_MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) -const OPEN01_MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) - - - - -#= -The below Float constructions are not duplicates of those in utilities.jl - they are needed to -ensure an interval of (0, 1) as opposed to [0, 1). Achieving this purely logically with midpoint -mapping means we can avoid a check for producing a 0 (which would normally cause a redraw). -Avoiding 0 is essential for Box-Muller due to the logarithm functions. -=# - - -# Convert random UInt32 bits to Float32 in (0, 1) using midpoint mapping on a 24-bit grid. -@inline function uint32_to_open_unit_float32_midpoint(u::UInt32)::Float32 - # `min` keeps the top midpoint below one after Float32 rounding. - k = min(u >> 8, OPEN01_MAX_MIDPOINT_INDEX_F32) - return (Float32(k) + 0.5f0) * OPEN01_MIDPOINT_SCALE_F32 -end - - -# Convert random UInt64 bits to Float64 in (0, 1) using midpoint mapping on a 53-bit grid. -@inline function uint64_to_open_unit_float64_midpoint(u::UInt64)::Float64 - # `min` keeps the top midpoint below one after Float64 rounding. - k = min(u >> 11, OPEN01_MAX_MIDPOINT_INDEX_F64) - return (Float64(k) + 0.5) * OPEN01_MIDPOINT_SCALE_F64 -end - - -# Float16 path reuses Float32 midpoint sampling for robust math in Box-Muller. -@inline function rand_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float16}, -)::Float16 - return Float16(rand_open01(seed, alg, counter, Float32)) -end - - -@inline function rand_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float32}, -)::Float32 - return uint32_to_open_unit_float32_midpoint(rand_uint(seed, alg, counter, UInt32)) -end - - -@inline function rand_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float64}, -)::Float64 - return uint64_to_open_unit_float64_midpoint(rand_uint(seed, alg, counter, UInt64)) -end - - -@inline function rand_open01(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} - throw(ArgumentError( - "Unsupported open-interval random type $(T). Supported: $(ALLOWED_RANDN_SCALARS)" - )) -end - - @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, @@ -90,8 +20,8 @@ end ::Type{Float32}, )::Tuple{Float32, Float32} u = rand_uint(seed, alg, pair_counter, UInt64) - u1 = uint32_to_open_unit_float32_midpoint(_u32_lo(u)) - u2 = uint32_to_open_unit_float32_midpoint(_u32_hi(u)) + u1 = _uint32_to_open_unit_float32_midpoint(_u32_lo(u)) + u2 = _uint32_to_open_unit_float32_midpoint(_u32_hi(u)) radius = sqrt(-2.0f0 * log(u1)) theta = Float32(2pi) * u2 stheta, ctheta = sincos(theta) @@ -106,8 +36,8 @@ end ::Type{Float64}, )::Tuple{Float64, Float64} c0 = pair_counter << 1 - u1 = rand_open01(seed, alg, c0, Float64) - u2 = rand_open01(seed, alg, c0 + UInt64(1), Float64) + u1 = rand_float_open01(seed, alg, c0, Float64) + u2 = rand_float_open01(seed, alg, c0 + UInt64(1), Float64) radius = sqrt(-2.0 * log(u1)) theta = Float64(2pi) * u2 stheta, ctheta = sincos(theta) @@ -256,13 +186,7 @@ function randn!( end -function randn!( - v::AbstractArray, - args...; - kwargs..., -) - return randn!(CounterRNG(), v, args...; kwargs...) -end +randn!(v::AbstractArray, args...; kwargs...) = randn!(CounterRNG(), v, args...; kwargs...) """ @@ -283,6 +207,11 @@ end Allocate an array of element type `T` on `backend` with shape `dims`, fill it in-place via [`randn!`](@ref), and return it. + +Convenience overloads: +- `rng` omitted: uses a fresh `CounterRNG()`. +- `backend` omitted: defaults to `CPU_BACKEND`. +- `T` omitted: defaults by backend (`Float64` on CPU backend, `Float32` otherwise). """ function randn( rng::CounterRNG, @@ -306,21 +235,14 @@ function randn( end -function randn( - backend::Backend, - ::Type{T}, - dims::Integer...; +function randn(rng::CounterRNG, backend::Backend, dims::Integer...; kwargs...) + DefaultScalarType = (backend == CPU_BACKEND) ? Float64 : Float32 + randn(rng, backend, DefaultScalarType, dims...; kwargs...) +end - # CPU settings - max_tasks::Int=Threads.nthreads(), - min_elems::Int=1, - prefer_threads::Bool=true, - # GPU settings - block_size::Int=256, -) where T - return randn( - CounterRNG(), backend, T, dims...; - max_tasks, min_elems, prefer_threads, block_size, - ) -end +randn(rng::CounterRNG, args...; kwargs...) = randn(rng, CPU_BACKEND, args...; kwargs...) +randn(backend::Backend, args...; kwargs...) = randn(CounterRNG(), backend, args...; kwargs...) +randn(::Type{T}, dims::Integer...; kwargs...) where {T} = randn(CPU_BACKEND, T, dims...; kwargs...) +randn(dims::Integer...; kwargs...) = randn(CPU_BACKEND, dims...; kwargs...) +randn(; kwargs...) = throw(ArgumentError("randn requires at least one dimension")) diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 556ca7b4..9e8ccf5d 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -143,3 +143,70 @@ end # Interpret as 1.mantissa, then subtract 1 for [0, 1) reinterpret(Float64, bits) - 1.0 end + + + + + +### Helpers for randn ### + + +# Midpoint-mapped open-interval Float sampling in (0, 1), used for Box-Muller +const OPEN01_MAX_MIDPOINT_INDEX_F32 = UInt32(0x00fffffe) +const OPEN01_MAX_MIDPOINT_INDEX_F64 = UInt64(0x001ffffffffffffe) +const OPEN01_MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) +const OPEN01_MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) + + +# Convert random UInt32 bits to Float32 in (0, 1) using midpoint mapping on a 24-bit grid. +@inline function _uint32_to_open_unit_float32_midpoint(u::UInt32)::Float32 + # `min` keeps the top midpoint below one after Float32 rounding. + k = min(u >> 8, OPEN01_MAX_MIDPOINT_INDEX_F32) + return (Float32(k) + 0.5f0) * OPEN01_MIDPOINT_SCALE_F32 +end + + +# Convert random UInt64 bits to Float64 in (0, 1) using midpoint mapping on a 53-bit grid. +@inline function _uint64_to_open_unit_float64_midpoint(u::UInt64)::Float64 + # `min` keeps the top midpoint below one after Float64 rounding. + k = min(u >> 11, OPEN01_MAX_MIDPOINT_INDEX_F64) + return (Float64(k) + 0.5) * OPEN01_MIDPOINT_SCALE_F64 +end + + +# Float16 path reuses Float32 midpoint sampling for robust math in Box-Muller. +@inline function rand_float_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float16}, +)::Float16 + return Float16(rand_float_open01(seed, alg, counter, Float32)) +end + + +@inline function rand_float_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float32}, +)::Float32 + return _uint32_to_open_unit_float32_midpoint(rand_uint(seed, alg, counter, UInt32)) +end + + +@inline function rand_float_open01( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{Float64}, +)::Float64 + return _uint64_to_open_unit_float64_midpoint(rand_uint(seed, alg, counter, UInt64)) +end + + +@inline function rand_float_open01(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} + throw(ArgumentError( + "Unsupported open-interval random type $(T). Supported: Union{Float16, Float32, Float64}" + )) +end diff --git a/test/rand.jl b/test/rand.jl index d3eaccae..a6b62c64 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -365,6 +365,8 @@ end @testset "rand allocation convenience" begin + default_alloc_type = IS_CPU_BACKEND ? Float64 : Float32 + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) y = AK.rand(rng, BACKEND, Float32, Int32(6), UInt16(7); prefer_threads, block_size=64) @test size(y) == (6, 7) @@ -372,6 +374,16 @@ end @test _is_unit_interval(Array(y)) @test rng.offset == UInt64(length(y)) + rng_default = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + rng_default_ref = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + y_default = AK.rand(rng_default, BACKEND, 128; prefer_threads, block_size=64) + y_default_ref = AK.rand( + rng_default_ref, BACKEND, default_alloc_type, 128; prefer_threads, block_size=64 + ) + @test eltype(y_default) === default_alloc_type + @test Array(y_default) == Array(y_default_ref) + @test rng_default.offset == rng_default_ref.offset == UInt64(128) + rng_alloc = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) rng_fill = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) y_alloc = AK.rand(rng_alloc, BACKEND, Float32, 128; prefer_threads, block_size=64) @@ -380,6 +392,26 @@ end @test Array(y_alloc) == Array(y_fill) @test rng_alloc.offset == rng_fill.offset == UInt64(128) + rng_cpu_default = AK.CounterRNG(UInt64(0x66); alg=AK.Philox()) + rng_cpu_default_ref = AK.CounterRNG(UInt64(0x66); alg=AK.Philox()) + y_cpu_default = AK.rand(rng_cpu_default, 128; prefer_threads, block_size=64) + y_cpu_default_ref = AK.rand( + rng_cpu_default_ref, AK.get_backend([]), 128; prefer_threads, block_size=64 + ) + @test eltype(y_cpu_default) === Float64 + @test Array(y_cpu_default) == Array(y_cpu_default_ref) + @test rng_cpu_default.offset == rng_cpu_default_ref.offset == UInt64(128) + + rng_cpu_typed = AK.CounterRNG(UInt64(0x77); alg=AK.Philox()) + rng_cpu_typed_ref = AK.CounterRNG(UInt64(0x77); alg=AK.Philox()) + y_cpu_typed = AK.rand(rng_cpu_typed, Float32, 128; prefer_threads, block_size=64) + y_cpu_typed_ref = AK.rand( + rng_cpu_typed_ref, AK.get_backend([]), Float32, 128; prefer_threads, block_size=64 + ) + @test eltype(y_cpu_typed) === Float32 + @test Array(y_cpu_typed) == Array(y_cpu_typed_ref) + @test rng_cpu_typed.offset == rng_cpu_typed_ref.offset == UInt64(128) + # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. AK.rand(BACKEND, Float32, 1; prefer_threads, block_size=64) @@ -391,6 +423,54 @@ end x = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) @test Array(x) == Array(ref) + # Auto-seeded convenience without explicit type should use backend-dependent default type. + Random.seed!(0x4242) + seed_default = Random.rand(Random.default_rng(), UInt64) + ref_default = AK.rand( + AK.CounterRNG(seed_default; alg=AK.Philox()), + BACKEND, + default_alloc_type, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x4242) + x_default = AK.rand(BACKEND, 64; prefer_threads, block_size=64) + @test eltype(x_default) === default_alloc_type + @test Array(x_default) == Array(ref_default) + + # Convenience without backend should default to CPU backend and Float64. + Random.seed!(0x4545) + seed_cpu_default = Random.rand(Random.default_rng(), UInt64) + ref_cpu_default = AK.rand( + AK.CounterRNG(seed_cpu_default; alg=AK.Philox()), + AK.get_backend([]), + Float64, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x4545) + x_cpu_default = AK.rand(64; prefer_threads, block_size=64) + @test eltype(x_cpu_default) === Float64 + @test Array(x_cpu_default) == Array(ref_cpu_default) + + # Type-only convenience should default to CPU backend. + Random.seed!(0x5656) + seed_cpu_typed = Random.rand(Random.default_rng(), UInt64) + ref_cpu_typed = AK.rand( + AK.CounterRNG(seed_cpu_typed; alg=AK.Philox()), + AK.get_backend([]), + Float32, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x5656) + x_cpu_typed_no_rng = AK.rand(Float32, 64; prefer_threads, block_size=64) + @test eltype(x_cpu_typed_no_rng) === Float32 + @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) + # Reseeding should reproduce the same auto-seeded draw. Random.seed!(0x7777) x1 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) @@ -401,5 +481,8 @@ end @test_throws ArgumentError AK.rand(AK.CounterRNG(0x1), BACKEND, UInt128, 16; prefer_threads) @test_throws MethodError AK.rand(AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg) @test_throws MethodError AK.rand(BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.rand(BACKEND, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.rand(16; prefer_threads, bad=:kwarg) + @test_throws ArgumentError AK.rand() end end diff --git a/test/randn.jl b/test/randn.jl index 0d239b24..2d7b5ffc 100644 --- a/test/randn.jl +++ b/test/randn.jl @@ -44,22 +44,22 @@ end @testset "randn" begin @testset "scalar helpers" begin - @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(UInt32(0)) < 1.0f0 - @test 0.0f0 < AK.uint32_to_open_unit_float32_midpoint(typemax(UInt32)) < 1.0f0 + @test 0.0f0 < AK._uint32_to_open_unit_float32_midpoint(UInt32(0)) < 1.0f0 + @test 0.0f0 < AK._uint32_to_open_unit_float32_midpoint(typemax(UInt32)) < 1.0f0 if IS_CPU_BACKEND - @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 - @test 0.0 < AK.uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 + @test 0.0 < AK._uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 + @test 0.0 < AK._uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 end seed = UInt64(0x123456789abcdef) for alg in RANDN_ALGS for counter in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - u32 = AK.rand_open01(seed, alg, counter, Float32) + u32 = AK.rand_float_open01(seed, alg, counter, Float32) @test 0.0f0 < u32 < 1.0f0 if IS_CPU_BACKEND - u64 = AK.rand_open01(seed, alg, counter, Float64) + u64 = AK.rand_float_open01(seed, alg, counter, Float64) @test 0.0 < u64 < 1.0 end end @@ -81,7 +81,7 @@ end end end - @test_throws ArgumentError AK.rand_open01(seed, AK.Philox(), UInt64(0), UInt32) + @test_throws ArgumentError AK.rand_float_open01(seed, AK.Philox(), UInt64(0), UInt32) @test_throws ArgumentError AK.randn_scalar(seed, AK.Philox(), UInt64(0), UInt32) end @@ -203,6 +203,8 @@ end @testset "randn allocation convenience" begin + default_alloc_type = IS_CPU_BACKEND ? Float64 : Float32 + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) y = AK.randn(rng, BACKEND, Float32, Int32(6), UInt16(7); prefer_threads, block_size=64) @test size(y) == (6, 7) @@ -210,6 +212,16 @@ end @test _all_finite(Array(y)) @test rng.offset == UInt64(length(y)) + rng_default = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + rng_default_ref = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + y_default = AK.randn(rng_default, BACKEND, 128; prefer_threads, block_size=64) + y_default_ref = AK.randn( + rng_default_ref, BACKEND, default_alloc_type, 128; prefer_threads, block_size=64 + ) + @test eltype(y_default) === default_alloc_type + @test Array(y_default) == Array(y_default_ref) + @test rng_default.offset == rng_default_ref.offset == UInt64(128) + rng_alloc = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) rng_fill = AK.CounterRNG(UInt64(0x55); alg=AK.Philox()) y_alloc = AK.randn(rng_alloc, BACKEND, Float32, 128; prefer_threads, block_size=64) @@ -218,17 +230,87 @@ end @test Array(y_alloc) == Array(y_fill) @test rng_alloc.offset == rng_fill.offset == UInt64(128) + rng_cpu_default = AK.CounterRNG(UInt64(0x66); alg=AK.Philox()) + rng_cpu_default_ref = AK.CounterRNG(UInt64(0x66); alg=AK.Philox()) + y_cpu_default = AK.randn(rng_cpu_default, 128; prefer_threads, block_size=64) + y_cpu_default_ref = AK.randn( + rng_cpu_default_ref, AK.get_backend([]), 128; prefer_threads, block_size=64 + ) + @test eltype(y_cpu_default) === Float64 + @test Array(y_cpu_default) == Array(y_cpu_default_ref) + @test rng_cpu_default.offset == rng_cpu_default_ref.offset == UInt64(128) + + rng_cpu_typed = AK.CounterRNG(UInt64(0x77); alg=AK.Philox()) + rng_cpu_typed_ref = AK.CounterRNG(UInt64(0x77); alg=AK.Philox()) + y_cpu_typed = AK.randn(rng_cpu_typed, Float32, 128; prefer_threads, block_size=64) + y_cpu_typed_ref = AK.randn( + rng_cpu_typed_ref, AK.get_backend([]), Float32, 128; prefer_threads, block_size=64 + ) + @test eltype(y_cpu_typed) === Float32 + @test Array(y_cpu_typed) == Array(y_cpu_typed_ref) + @test rng_cpu_typed.offset == rng_cpu_typed_ref.offset == UInt64(128) + # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. AK.randn(BACKEND, Float32, 1; prefer_threads, block_size=64) # Auto-seeded constructor should match explicit seed capture from default RNG. Random.seed!(0x9abc) seed = Random.rand(Random.default_rng(), UInt64) - ref = AK.randn(AK.CounterRNG(seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64) + ref = AK.randn(AK.CounterRNG( + seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64 + ) Random.seed!(0x9abc) x = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) @test Array(x) == Array(ref) + # Auto-seeded convenience without explicit type should use backend-dependent default type. + Random.seed!(0x4242) + seed_default = Random.rand(Random.default_rng(), UInt64) + ref_default = AK.randn( + AK.CounterRNG(seed_default; alg=AK.Philox()), + BACKEND, + default_alloc_type, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x4242) + x_default = AK.randn(BACKEND, 64; prefer_threads, block_size=64) + @test eltype(x_default) === default_alloc_type + @test Array(x_default) == Array(ref_default) + + # Convenience without backend should default to CPU backend and Float64. + Random.seed!(0x4545) + seed_cpu_default = Random.rand(Random.default_rng(), UInt64) + ref_cpu_default = AK.randn( + AK.CounterRNG(seed_cpu_default; alg=AK.Philox()), + AK.get_backend([]), + Float64, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x4545) + x_cpu_default = AK.randn(64; prefer_threads, block_size=64) + @test eltype(x_cpu_default) === Float64 + @test Array(x_cpu_default) == Array(ref_cpu_default) + + # Type-only convenience should default to CPU backend. + Random.seed!(0x5656) + seed_cpu_typed = Random.rand(Random.default_rng(), UInt64) + ref_cpu_typed = AK.randn( + AK.CounterRNG(seed_cpu_typed; alg=AK.Philox()), + AK.get_backend([]), + Float32, + 64; + prefer_threads, + block_size=64, + ) + Random.seed!(0x5656) + x_cpu_typed_no_rng = AK.randn(Float32, 64; prefer_threads, block_size=64) + @test eltype(x_cpu_typed_no_rng) === Float32 + @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) + # Reseeding should reproduce the same auto-seeded draw. Random.seed!(0x7777) x1 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) @@ -237,8 +319,13 @@ end @test Array(x1) == Array(x2) @test_throws ArgumentError AK.randn(AK.CounterRNG(0x1), BACKEND, UInt32, 16; prefer_threads) - @test_throws MethodError AK.randn(AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.randn( + AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg + ) @test_throws MethodError AK.randn(BACKEND, Float32, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.randn(BACKEND, 16; prefer_threads, bad=:kwarg) + @test_throws MethodError AK.randn(16; prefer_threads, bad=:kwarg) + @test_throws ArgumentError AK.randn() end diff --git a/test/runtests.jl b/test/runtests.jl index 5d3a6ad7..707afeea 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -17,13 +17,7 @@ if "--CUDA" in ARGS const BACKEND = CUDABackend() TEST_DL[] = true elseif "--oneAPI" in ARGS - if Sys.iswindows() - # oneAPI v2.6.x can throw `UndefVarError: NEO_jll not defined` on native Windows. - # Pin to the latest known-good minor series until upstream fixes are available. - Pkg.add(name="oneAPI", version="2.5") - else - Pkg.add("oneAPI") - end + Pkg.add("oneAPI") using oneAPI oneAPI.versioninfo() const BACKEND = oneAPIBackend() From 9595086ed35d6005627eeaf8733c305ee20c0a76 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Sat, 28 Mar 2026 00:08:13 +0000 Subject: [PATCH 18/20] document rand_uint and CounterRNGAlgorithm properly, improve RNG docs page --- docs/src/api/rand.md | 169 +++++++++++++++++++++++------------- prototype/rand/test_rand.jl | 26 ++---- src/rand/rand.jl | 9 ++ src/rand/utilities.jl | 28 ++++++ 4 files changed, 153 insertions(+), 79 deletions(-) diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index d0d41138..381a7976 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -1,92 +1,141 @@ ### Random Number Generation -Counter-based random generation for CPU and GPU backends with deterministic stream behavior for +Counter-based random generation for CPU and GPU backends with deterministic stream behaviour for a fixed `seed`, algorithm, and call sequence. Both in-place and allocation forms are supported: - Uniform: `AK.rand!`, `AK.rand` - Standard normal: `AK.randn!`, `AK.randn` -`CounterRNG` carries an internal `offset` (starting at `0`) that advances by `length(v)` on each -`AK.rand!(rng, v)` call. This means chunked fills are stream-consistent: +`CounterRNG` stores: +- `seed::UInt64` +- algorithm `alg` +- stream `offset::UInt64` + +The offset starts at `0` and advances by the number of generated values after each call. For +`AK.rand!(rng, v)` and `AK.randn!(rng, v)`, element `v[i]` is generated from logical counter +`rng.offset + UInt64(i - 1)` in linear indexing order. + +This gives stream-consistent chunking: - filling `100` then `100` elements yields the same `200` values as one `200`-element fill. -- calls that share the same `CounterRNG` instance concurrently are not thread-safe. -- call `AK.reset!(rng)` to rewind a `CounterRNG` offset back to `0x0`. +- `AK.reset!(rng)` rewinds `rng.offset` to `0x0`. -`AK.rand!(rng, v)` accepts `rng::AK.CounterRNG`. -Passing other RNG container types is not supported and will throw a `MethodError`. +Calls that share the same `CounterRNG` instance concurrently are not thread-safe and may race on +`offset`. -Use an explicit `CounterRNG` when reproducibility is required. For -convenience, -`AK.rand!(v)` creates a fresh `CounterRNG()` on each call using one auto-seeded -`Base.rand(UInt64)` draw, so repeated calls produce different outputs unless Random.seed!() is used. -Likewise, `AK.rand(backend, args...)` creates a fresh auto-seeded `CounterRNG()` on each call. +`AK.rand!` and `AK.randn!` accept `rng::AK.CounterRNG`. Passing other RNG container types is not +supported and will throw a `MethodError`. -`AK.reset!(rng::AK.CounterRNG)` rewinds `rng.offset` to `0x0`. +#### Auto-seeded convenience behaviour -Allocation convenience: -- Canonical forms are `AK.rand(rng, backend, T, dims...)` and `AK.randn(rng, backend, T, dims...)`. -- Defaults are shared: omit `rng` -> fresh `CounterRNG()`; omit `backend` -> CPU backend; omit `T` -> `Float64` on CPU backend and `Float32` otherwise. -- Common shorthands include `AK.rand(dims...)`, `AK.rand(T, dims...)`, `AK.rand(backend, dims...)`, and the corresponding `AK.randn(...)` variants. -- For explicit `rng`, both `AK.rand` and `AK.randn` advance `rng.offset` by `prod(dims)`. +Use an explicit `CounterRNG` when reproducibility is required. -Custom algorithms: -- Define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm`. -- Implement typed `rand_uint` methods: - - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` - - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` -- Use your algorithm via `AK.CounterRNG(seed; alg=MyAlg(), offset=...)`. +For convenience, calls without an explicit `rng` construct a fresh `CounterRNG()` on each call, +using one auto-seeded `Base.rand(UInt64)` draw. Therefore repeated bare calls intentionally produce +different outputs unless `Random.seed!()` is used first. + +Examples: +- `AK.rand!(v)` +- `AK.randn!(v)` +- `AK.rand(backend, args...)` +- `AK.randn(backend, args...)` + +These do **not** continue a shared stream across calls unless you pass the same explicit +`CounterRNG`. -Both widths should be implemented so `AK.rand!` supports all integer/float output types without falling back or error. +#### Allocation forms -Supported element types: +Canonical forms: +- `AK.rand(rng, backend, T, dims...)` +- `AK.randn(rng, backend, T, dims...)` + +Shared defaults: +- omit `rng` -> fresh `CounterRNG()` +- omit `backend` -> CPU backend +- omit `T` -> `Float64` on CPU backend, `Float32` otherwise + +Common shorthands include: +- `AK.rand(dims...)` +- `AK.rand(T, dims...)` +- `AK.rand(backend, dims...)` +- and the corresponding `AK.randn(...)` variants + +For explicit `rng`, both `AK.rand` and `AK.randn` advance `rng.offset` by the number of generated +elements, i.e. `prod(dims)`. + +#### Supported element types + +`AK.rand!` / `AK.rand` support: - `UInt8`, `UInt16`, `UInt32`, `UInt64` - `Int8`, `Int16`, `Int32`, `Int64` - `Float16`, `Float32`, `Float64` - `Bool` -`AK.randn!` fills arrays with standard normal samples and currently supports: +`AK.randn!` / `AK.randn` currently support: - `Float16`, `Float32`, `Float64` -`AK.randn!` uses Box-Muller with open-interval uniforms in `(0, 1)` from a branch-free midpoint mapping. +#### Value generation semantics + +The core generator produces either a `UInt32` or `UInt64`, depending on the requested output type. +That raw unsigned value is then mapped as follows: +- Unsigned integers: returned directly, or truncated if narrower +- Signed integers: the corresponding unsigned bit pattern reinterpreted as signed, then truncated if narrower +- Floats: mantissa construction onto a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)) +- Bool: `true` if the raw `UInt` draw is odd (`isodd(u)`), otherwise `false` -`AK.randn!(v)` and `AK.randn(backend, args...)` create a fresh auto-seeded `CounterRNG()` on each -call, so repeated calls produce different outputs unless `Random.seed!()` is used. +`AK.randn!` uses Box-Muller with midpoint-mapped open-interval uniforms in `(0, 1)`. -The core of the random number generation produces either a `UInt32` or `UInt64` depending on the width of the requested element type. -That `UInt` is then either: -- Unsigned integers: returned as-is or truncated if necessary. -- Signed integers: reinterpreted as a signed integer bit pattern and truncated if necessary. -- Floats: mantissa construction into a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)). -- Bool: `true` if the `UInt` draw is odd (`isodd(u)`), otherwise `false`. +#### Algorithms currently available -Algorithms currently available: - `SplitMix64` ([read more](https://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64)) - `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) - `Threefry` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) -Statistical-testing note: +`Philox` is the default algorithm for `CounterRNG()`. + +#### Statistical testing and security + - In this repository, `SplitMix64`, `Philox`, and `Threefry` have passed TestU01 BigCrush -- These generators are not intended to be cryptographically secure. +- These generators are not intended to be cryptographically secure + +#### Philox keying note + +AK uses `Philox2x32` internally, which has a single 32-bit Philox key word. + +Users may pass any non-negative `Integer` seed with `seed <= typemax(UInt64)`; AK converts it to +`UInt64` and derives the 32-bit Philox key using SplitMix. This wrapper choice is deliberate for +ease of use and deterministic streams, not a change to the Philox round function itself. -Philox keying note: -- AK uses `Philox2x32` internally (one 32-bit Philox key word). -- Users can pass any non-negative `Integer` seed; AK normalises to `UInt64` then derives the - 32-bit Philox key via a SplitMix-based mapping. -- This is a deliberate wrapper choice for ease of use (simple `seed` API with deterministic - streams), not a change to the Philox round function itself. -- Therefore, AK Philox streams are deterministic and high-quality, but not guaranteed to be - bit-for-bit identical to a raw Random123 Philox stream unless the same seed-to-key mapping and - counter convention are used. +Therefore, AK Philox streams are deterministic and high-quality, but are not guaranteed to be +bit-for-bit identical to a raw Random123 Philox stream unless the same seed-to-key mapping and +counter convention are used. -`Philox` is the default algorithm for `CounterRNG()` because it is thorough and very fast; it has been measured on par with `CUDA.rand!` and `SplitMix64` at ~390 GB/s on an Nvidia GeForce RTX -5060 (advertised 448 GB/s), i.e. effectively memory-bound throughput. +#### Custom algorithms + +To define a custom counter RNG: +- define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm` +- implement: + - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` + - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` + +Then use it via: +- `AK.CounterRNG(seed; alg=MyAlg(), offset=...)` + +Both widths should be implemented so `AK.rand!` supports all integer and floating-point output +types without fallback or error. + +#### Performance note + +`Philox` is the default because it is high-quality and very fast. `AK.rand!` has been measured at +roughly memory-bound throughput (~390 GB/s) on an Nvidia GeForce RTX 5060, including slightly better +performance than CURAND for large `CuArray{Float32}` fills and substantially faster `CuArray{Int32}` +filling than native `CUDA.rand!` in the benchmarks used for this repository. Examples: ```julia import AcceleratedKernels as AK using oneAPI -using ROCArray +using AMDGPU # Reproducible rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) @@ -94,36 +143,38 @@ v = oneArray{Float32}(undef, 1024) AK.rand!(rng, v) # Stream-consistent chunking +rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) v1 = oneArray{Float32}(undef, 100) v2 = oneArray{Float32}(undef, 100) AK.rand!(rng, v1) AK.rand!(rng, v2) -# Convenience (fresh auto-seeded RNG on each call) +# Convenience: fresh auto-seeded RNG on each call y = oneArray{Float32}(undef, 1024) AK.rand!(y) # Allocation form -y_cpu_auto = AK.rand(1024) # defaults to CPU, Vector{Float64} -y_oneArray = AK.rand(oneAPIBackend(), Float32, 1024) # fresh RNG, allocate and fill oneArray -y_cpu_typed = AK.rand(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG +y_cpu_auto = AK.rand(1024) # CPU, Vector{Float64} +y_one = AK.rand(oneAPIBackend(), Float32, 1024) # fresh RNG, allocate + fill oneArray +y_cpu_typed = AK.rand(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG # Standard normal filling z = ROCArray{Float32}(undef, 1024) AK.randn!(rng, z) # Standard normal allocation form -z_cpu_auto = AK.randn(1024) # defaults to CPU, Vector{Float64} -z_ROCArray = AK.randn(oneAPIBackend(), 1024) # allocate and fill ROCArray{Float32} -z_cpu_typed = AK.randn(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG +z_cpu_auto = AK.randn(1024) # CPU, Vector{Float64} +z_roc = AK.randn(ROCBackend(), 1024) # fresh RNG, allocate + fill ROCArray{Float32} +z_cpu_typed = AK.randn(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG ``` ```@docs AcceleratedKernels.CounterRNG AcceleratedKernels.CounterRNGAlgorithm +AcceleratedKernels.rand_uint AcceleratedKernels.reset! AcceleratedKernels.rand! AcceleratedKernels.rand AcceleratedKernels.randn! AcceleratedKernels.randn -``` +``` \ No newline at end of file diff --git a/prototype/rand/test_rand.jl b/prototype/rand/test_rand.jl index 5a7be0fc..0d916f29 100644 --- a/prototype/rand/test_rand.jl +++ b/prototype/rand/test_rand.jl @@ -7,16 +7,13 @@ import AcceleratedKernels as AK const N = 100_000_000 const GPU_BLOCK_SIZE = 256 -const RNG_SPLITMIX = AK.CounterRNG(0x12345678; alg=AK.SplitMix64()) + const RNG_PHILOX = AK.CounterRNG(0x12345678; alg=AK.Philox()) -const RNG_THREEFRY = AK.CounterRNG(0x12345678; alg=AK.Threefry()) -TestType = Float32 +TestType = Float32 x_cuda = CuArray{TestType}(undef, N) -x_splitmix = CuArray{TestType}(undef, N) x_philox = CuArray{TestType}(undef, N) -x_threefry = CuArray{TestType}(undef, N) x_cpu = Vector{TestType}(undef, N) @@ -40,19 +37,11 @@ function run_ak_rand_cpu!(rng, x) end -# Julia base rand() gives [0, 1) and so does EVERYTHING ELSE EVER! but CuRAND gives (0, 1] ... -is_unit_interval(v) = all(x -> 0.0f0 <= x <= 1.0f0, v) - -# warmup compile +# warmup run_cuda_rand!(x_cuda) run_ak_rand_gpu!(RNG_PHILOX, x_philox) -run_ak_rand_gpu!(RNG_THREEFRY, x_threefry) -run_ak_rand_cpu!(RNG_SPLITMIX, x_cpu) +run_ak_rand_cpu!(RNG_PHILOX, x_cpu) -@assert is_unit_interval(Array(x_cuda)) -@assert is_unit_interval(Array(x_philox)) -@assert is_unit_interval(Array(x_threefry)) -@assert is_unit_interval(x_cpu) println("N = ", N) println("CPU threads: ", Threads.nthreads()) @@ -63,9 +52,6 @@ display(@benchmark run_cuda_rand!($x_cuda)) println("\nAK.rand! Philox benchmark (GPU, CuArray{$TestType})") display(@benchmark run_ak_rand_gpu!($RNG_PHILOX, $x_philox)) -println("\nAK.rand! Threefry benchmark (GPU, CuArray{$TestType})") -display(@benchmark run_ak_rand_gpu!($RNG_THREEFRY, $x_threefry)) - -println("\nAK.rand! benchmark (CPU, Vector{$TestType}, SplitMix64)") -display(@benchmark run_ak_rand_cpu!($RNG_SPLITMIX, $x_cpu)) +println("\nAK.rand! benchmark (CPU, Vector{$TestType}, Philox)") +display(@benchmark run_ak_rand_cpu!($RNG_PHILOX, $x_cpu)) diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 06d3619e..b2b14bd1 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -5,6 +5,15 @@ const ALLOWED_RAND_SCALARS = Union{ Bool } + +""" + CounterRNGAlgorithm + +Abstract supertype for algorithms used by [`CounterRNG`](@ref). + +To define a custom counter-based RNG algorithm, subtype `CounterRNGAlgorithm` and implement +[`rand_uint`](@ref) for both `UInt32` and `UInt64` outputs. +""" abstract type CounterRNGAlgorithm end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 9e8ccf5d..35d90846 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -72,6 +72,34 @@ end Every RNG algorithm implements rand_uint(seed, alg, counter, UInt32/UInt64). This is the fallback for unsupported RNG algorithms. =# +""" + rand_uint(seed::UInt64, alg::CounterRNGAlgorithm, counter::UInt64, ::Type{UIntType}) -> UIntType + where {UIntType <: Union{UInt32, UInt64}} + +Low-level extension point for counter-based RNG algorithms used by [`CounterRNG`](@ref). + +`rand_uint` must deterministically map `(seed, alg, counter)` to a raw unsigned integer of the +requested width. Custom algorithms should implement methods for both: + +- `rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` +- `rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` + +These methods are used internally by [`rand!`](@ref), [`rand`](@ref), [`randn!`](@ref), and +[`randn`](@ref) to generate integers, floats, and normal samples. + +# Requirements +- The mapping must be deterministic for fixed `seed`, `alg`, and `counter`. +- Implement both `UInt32` and `UInt64` widths. +- The method should return raw random bits; higher-level type conversion is handled by AK separately. + +# Notes +- `counter` is the logical stream position (typically the array index). +- For block-based algorithms such as Philox or Threefry, the `UInt32` and `UInt64` methods may + share an internal block computation. +- The fallback method throws an `ArgumentError` for algorithms that do not implement `rand_uint`. + +See also: [`CounterRNGAlgorithm`](@ref), [`CounterRNG`](@ref). +""" @inline function rand_uint( ::UInt64, alg::CounterRNGAlgorithm, From 5dc7373973788acfed240043f5b8c5a75f712ab9 Mon Sep 17 00:00:00 2001 From: fjbarter Date: Wed, 18 Nov 2026 17:15:18 +0000 Subject: [PATCH 19/20] fast math for sincos and log for box-muller, avoid float64 widening, avoid sync with odd offsets with randn! --- docs/src/api/rand.md | 2 +- prototype/rand/Project.toml | 4 + src/rand/fastmath.jl | 196 ++++++++++++++++++++++++++++++++++++ src/rand/rand.jl | 153 ++++++++++++++++++++++++---- src/rand/randn.jl | 102 +++++++++++-------- src/rand/utilities.jl | 70 +------------ test/randn.jl | 90 +++++++++++++---- 7 files changed, 464 insertions(+), 153 deletions(-) create mode 100644 src/rand/fastmath.jl diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 381a7976..7b3f65ab 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -83,7 +83,7 @@ That raw unsigned value is then mapped as follows: - Floats: mantissa construction onto a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)) - Bool: `true` if the raw `UInt` draw is odd (`isodd(u)`), otherwise `false` -`AK.randn!` uses Box-Muller with midpoint-mapped open-interval uniforms in `(0, 1)`. +`AK.randn!` uses Box-Muller, with fast polynomial `log` and `sincospi` evaluated directly on the raw random bits (adapted from [PhiloxRNG.jl](https://github.com/medyan-dev/PhiloxRNG.jl)). These avoid libm calls and `Float64` widening, so `Float32` output is supported on devices without `Float64`. #### Algorithms currently available diff --git a/prototype/rand/Project.toml b/prototype/rand/Project.toml index d1926b1e..4ca85890 100644 --- a/prototype/rand/Project.toml +++ b/prototype/rand/Project.toml @@ -5,3 +5,7 @@ BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" Cthulhu = "f68482b8-f384-11e8-15f7-abe071a5a75f" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" +Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + +[sources] +AcceleratedKernels = {path = "../.."} diff --git a/src/rand/fastmath.jl b/src/rand/fastmath.jl new file mode 100644 index 00000000..d66f28f9 --- /dev/null +++ b/src/rand/fastmath.jl @@ -0,0 +1,196 @@ +# Fast, device-friendly log and sincospi for Box-Muller, operating directly on raw random bits. +# Avoids libm calls and Float64 widening, and uses explicit `fma` so results are bit-identical +# across backends. +# +# Adapted from PhiloxRNG.jl: https://github.com/medyan-dev/PhiloxRNG.jl +# License is MIT: Copyright (c) 2024 Nathan Zimmerberg, Patrick Kelly, and contributors +# +# The log polynomial, ln2 splitting and reconstruction are in turn adapted from fdlibm's +# e_log.c / e_logf.c (Sun Microsystems, 1993): https://github.com/JuliaMath/openlibm + + +# Polynomial coefficients for log(1+f), from fdlibm +const FASTLOG_POLY_F32 = (0.6666666f0, 0.40000972f0, 0.28498787f0, 0.24279079f0) +const FASTLOG_POLY_F64 = ( + 6.666666666666735130e-01, + 3.999999999940941908e-01, + 2.857142874366239149e-01, + 2.222219843214978396e-01, + 1.818357216161805012e-01, + 1.531383769920937332e-01, + 1.479819860511658591e-01, +) + +# log(2) split into high and low parts for an accurate k*log(2) +const FASTLOG_LN2_HI_F32 = 0.6931381f0 +const FASTLOG_LN2_LO_F32 = 9.058001f-6 +const FASTLOG_LN2_HI_F64 = 6.93147180369123816490e-01 +const FASTLOG_LN2_LO_F64 = 1.90821492927058770002e-10 + +# Bit patterns of sqrt(0.5), used to centre the reduced argument (1+f) on [sqrt(2)/2, sqrt(2)) +const FASTLOG_SQRT_HALF_I32 = reinterpret(Int32, Float32(sqrt(0.5))) +const FASTLOG_SQRT_HALF_I64 = reinterpret(Int64, sqrt(0.5)) + +# Minimax coefficients (in y^2) for sin(pi*y)/y and cos(pi*y) on y in [0, 0.25] +const FASTSINCOSPI_SIN_POLY_F32 = (3.1415927f0, -5.167708f0, 2.5497673f0, -0.58907866f0) +const FASTSINCOSPI_COS_POLY_F32 = (1.0f0, -4.934788f0, 4.057578f0, -1.3061346f0) +const FASTSINCOSPI_SIN_POLY_F64 = ( + 3.141592653589793, + -5.167712780049954, + 2.5501640398733785, + -0.5992645289398095, + 0.08214586918507949, + -0.007370021659123395, + 0.0004615322405282014, +) +const FASTSINCOSPI_COS_POLY_F64 = ( + 1.0, + -4.934802200544605, + 4.0587121263978485, + -1.3352627670374702, + 0.23533054723811608, + -0.025804938901032953, + 0.0019068114005246046, +) + +# Scales mapping raw bits onto the left-open unit interval (0, 1] +const LEFT_OPEN01_SCALE_F32 = ldexp(Float32(1), -32) +const LEFT_OPEN01_OFFSET_F32 = ldexp(Float32(1), -33) +const LEFT_OPEN01_SCALE_F64 = ldexp(Float64(1), -64) +const LEFT_OPEN01_OFFSET_F64 = ldexp(Float64(1), -65) + +# Scales mapping the octant-masked raw bits onto the reduced argument y in (0, 0.25) +const FASTSINCOSPI_SCALE_F32 = ldexp(Float32(1), -34) +const FASTSINCOSPI_OFFSET_F32 = ldexp(Float32(1), -32) +const FASTSINCOSPI_SCALE_F64 = ldexp(Float64(1), -66) +const FASTSINCOSPI_OFFSET_F64 = ldexp(Float64(1), -64) + + +# Horner's method with explicit `fma`. `Base.evalpoly` uses `muladd`, which lets the compiler +# decide whether to fuse; that can differ by an ulp between backends, so we force fusion here. +@inline function _fma_evalpoly(x::T, p::NTuple{4, T})::T where {T <: AbstractFloat} + return fma(x, fma(x, fma(x, p[4], p[3]), p[2]), p[1]) +end + + +@inline function _fma_evalpoly(x::T, p::NTuple{7, T})::T where {T <: AbstractFloat} + return fma(x, fma(x, fma(x, fma(x, fma(x, fma(x, p[7], p[6]), p[5]), p[4]), p[3]), p[2]), p[1]) +end + + +# Convert random UInt32 bits to Float32 in (0, 1] as (u + 0.5) * 2^-32. Never returns zero, so +# the result is always safe to pass to log. +@inline function _uint32_to_left_open_unit_float32(u::UInt32)::Float32 + return fma(Float32(u), LEFT_OPEN01_SCALE_F32, LEFT_OPEN01_OFFSET_F32) +end + + +# Convert random UInt64 bits to Float64 in (0, 1] as (u + 0.5) * 2^-64. +@inline function _uint64_to_left_open_unit_float64(u::UInt64)::Float64 + return fma(Float64(u), LEFT_OPEN01_SCALE_F64, LEFT_OPEN01_OFFSET_F64) +end + + +#= +Compute log(x) for x = _uint32_to_left_open_unit_float32(u) in (0, 1], without libm. + +1) Decompose x = 2^k * (1+f), where sqrt(2)/2 <= 1+f < sqrt(2) +2) Approximate log(1+f) with a polynomial in s = f/(2+f) +3) Reconstruct log(x) = k*log(2) + log(1+f), with log(2) split into high and low parts + +When k == 0 (x close to 1), f is instead taken directly from the complementary bits as +-_uint32_to_left_open_unit_float32(~u), which avoids cancellation in x - 1. +=# +@inline function _fast_log(::Type{Float32}, u::UInt32)::Float32 + x = _uint32_to_left_open_unit_float32(u) + + # Subtracting sqrt(0.5)'s bit pattern makes k step down by one at each power-of-two boundary + # below sqrt(0.5); shifting out the 23 mantissa bits leaves k. + ix = reinterpret(Int32, x) - FASTLOG_SQRT_HALF_I32 + k = ix >> Int32(23) + + # Masking keeps the mantissa bits of x; adding sqrt(0.5) back restores 1+f with an exponent of + # -1 or 0 (a borrow from the subtraction above propagates into the exponent field). + f_std = reinterpret(Float32, (ix & Int32(0x007fffff)) + FASTLOG_SQRT_HALF_I32) - 1.0f0 + f_comp = -_uint32_to_left_open_unit_float32(~u) + f = ifelse(k == Int32(0), f_comp, f_std) + + # log(1+f) = f - f^2/2 + s*(f^2/2 + R), with s = f/(2+f), R = s^2 * poly(s^2) + s = f / (2.0f0 + f) + z = s * s + hfsq = 0.5f0 * f * f + hfsq_r = fma(z, _fma_evalpoly(z, FASTLOG_POLY_F32), hfsq) + + k_f32 = Float32(k) + return fma(k_f32, FASTLOG_LN2_HI_F32, f - (hfsq - fma(s, hfsq_r, k_f32 * FASTLOG_LN2_LO_F32))) +end + + +# Float64 version of the above, for x = _uint64_to_left_open_unit_float64(u) +@inline function _fast_log(::Type{Float64}, u::UInt64)::Float64 + x = _uint64_to_left_open_unit_float64(u) + + ix = reinterpret(Int64, x) - FASTLOG_SQRT_HALF_I64 + k = ix >> Int64(52) + + f_std = reinterpret(Float64, (ix & Int64(0x000fffffffffffff)) + FASTLOG_SQRT_HALF_I64) - 1.0 + f_comp = -_uint64_to_left_open_unit_float64(~u) + f = ifelse(k == Int64(0), f_comp, f_std) + + s = f / (2.0 + f) + z = s * s + hfsq = 0.5 * f * f + hfsq_r = fma(z, _fma_evalpoly(z, FASTLOG_POLY_F64), hfsq) + + k_f64 = Float64(k) + return fma(k_f64, FASTLOG_LN2_HI_F64, f - (hfsq - fma(s, hfsq_r, k_f64 * FASTLOG_LN2_LO_F64))) +end + + +#= +Map 2^N raw bits to (sin(theta), cos(theta)) for theta uniformly spaced around the unit circle, +with no point landing exactly on an axis. + +1) The 3 rightmost bits of u select one of 8 octants (pi/4 each) +2) The remaining bits give the reduced argument y in (0, 0.25), biased by half a step to avoid y == 0 +3) Polynomials evaluate sin(pi*y) and cos(pi*y), then each octant bit applies one operation: + - bit 0: swap sin and cos + - bit 1: negate sin + - bit 2: negate cos + +The octants are not in geometric order, but the points are uniformly distributed regardless. +=# +@inline function _fast_sincospi(::Type{Float32}, u::UInt32)::Tuple{Float32, Float32} + y = fma(Float32(u & ~UInt32(0x7)), FASTSINCOSPI_SCALE_F32, FASTSINCOSPI_OFFSET_F32) + y2 = y * y + sin_raw = y * _fma_evalpoly(y2, FASTSINCOSPI_SIN_POLY_F32) + cos_raw = _fma_evalpoly(y2, FASTSINCOSPI_COS_POLY_F32) + return _sincospi_apply_octant(u % UInt8, sin_raw, cos_raw) +end + + +# Float64 version of the above, using 61 bits for the reduced argument +@inline function _fast_sincospi(::Type{Float64}, u::UInt64)::Tuple{Float64, Float64} + y = fma(Float64(u & ~UInt64(0x7)), FASTSINCOSPI_SCALE_F64, FASTSINCOSPI_OFFSET_F64) + y2 = y * y + sin_raw = y * _fma_evalpoly(y2, FASTSINCOSPI_SIN_POLY_F64) + cos_raw = _fma_evalpoly(y2, FASTSINCOSPI_COS_POLY_F64) + return _sincospi_apply_octant(u % UInt8, sin_raw, cos_raw) +end + + +# Branch-free octant reconstruction from the 3 rightmost bits of `octant` +@inline function _sincospi_apply_octant( + octant::UInt8, + sin_raw::T, + cos_raw::T, +)::Tuple{T, T} where {T <: AbstractFloat} + swap = !iszero(octant & UInt8(0x1)) + sin_neg = !iszero(octant & UInt8(0x2)) + cos_neg = !iszero(octant & UInt8(0x4)) + + s = ifelse(swap, cos_raw, sin_raw) + c = ifelse(swap, sin_raw, cos_raw) + + return ifelse(sin_neg, -s, s), ifelse(cos_neg, -c, c) +end diff --git a/src/rand/rand.jl b/src/rand/rand.jl index b2b14bd1..8bef11b6 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -6,6 +6,15 @@ const ALLOWED_RAND_SCALARS = Union{ } +""" + AbstractAKRNG + +Abstract supertype for AcceleratedKernels RNG objects, such as [`CounterRNG`](@ref) or +[`StreamRNG`](@ref). +""" +abstract type AbstractAKRNG end + + """ CounterRNGAlgorithm @@ -17,6 +26,84 @@ To define a custom counter-based RNG algorithm, subtype `CounterRNGAlgorithm` an abstract type CounterRNGAlgorithm end +""" + StreamRNGAlgorithm + +Abstract supertype for algorithms used by [`StreamRNG`](@ref). +""" +abstract type StreamRNGAlgorithm end + + +""" + StreamRNGState + +Abstract supertype for mutable stream RNG state objects stored by [`StreamRNG`](@ref). +""" +abstract type StreamRNGState end + + +""" + stream_init_state(seed::UInt64, alg::StreamRNGAlgorithm) -> StreamRNGState + +Extension point for stream RNG algorithms to build their initial mutable state from `seed`. +""" +@inline function stream_init_state(seed::UInt64, alg::StreamRNGAlgorithm)::StreamRNGState + throw(ArgumentError("No stream_init_state implementation for RNG algorithm: $(typeof(alg))")) +end + + +""" + StreamRNG(seed::Integer; alg::StreamRNGAlgorithm, state::Union{Nothing, StreamRNGState}=nothing) + +Stateful stream RNG container. + +`StreamRNG` stores: +- `seed` +- algorithm (`alg`) +- mutable stream state (`state::StreamRNGState`) + +If `state` is not provided, it is initialised via [`stream_init_state`](@ref). +""" +mutable struct StreamRNG{A <: StreamRNGAlgorithm} <: AbstractAKRNG + const seed::UInt64 + const alg::A + state::StreamRNGState +end + + +function StreamRNG( + seed::Integer; + alg::StreamRNGAlgorithm, + state::Union{Nothing, StreamRNGState}=nothing, +) + @argcheck seed >= 0 "Seed must be a non-negative integer" + seed_u64 = UInt64(seed) + state_obj = isnothing(state) ? stream_init_state(seed_u64, alg) : state + return StreamRNG(seed_u64, alg, state_obj) +end + + +function StreamRNG(; alg::StreamRNGAlgorithm=Xoshiro256PP(), state::Union{Nothing, StreamRNGState}=nothing) + return StreamRNG(Base.rand(UInt64); alg, state) +end + + +StreamRNG(seed::Integer, alg::StreamRNGAlgorithm) = StreamRNG(seed; alg) +StreamRNG(seed::Integer, alg::StreamRNGAlgorithm, state::StreamRNGState) = + StreamRNG(seed; alg, state) + + +""" + reset!(rng::StreamRNG) + +Reset `rng.state` to the seed-derived initial stream state. +""" +@inline function reset!(rng::StreamRNG) + rng.state = stream_init_state(rng.seed, rng.alg) + return rng +end + + """ CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox()) @@ -39,7 +126,7 @@ Constructors: - `CounterRNG(; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0)` Auto-seeds once using `Base.rand(UInt64)`, with default `offset == 0`. """ -mutable struct CounterRNG{A <: CounterRNGAlgorithm} +mutable struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractAKRNG const seed::UInt64 const alg::A offset::UInt64 @@ -81,8 +168,10 @@ include("utilities.jl") include("splitmix.jl") include("philox.jl") include("threefry.jl") +include("rand_cpu.jl") # Normally distributed scalar generators and randn! +include("fastmath.jl") include("randn.jl") @@ -90,7 +179,7 @@ include("randn.jl") """ rand!( - rng::CounterRNG, + rng::AbstractAKRNG, v::AbstractArray{T}, backend::Backend=get_backend(v); @@ -105,11 +194,12 @@ include("randn.jl") block_size::Int=256, ) -Fill `v` in-place with pseudo-random values using a counter-based RNG stream. For `v[i]`, the -counter is `rng.offset + UInt64(i - 1)` in linear indexing order. +Fill `v` in-place with pseudo-random values using `rng`. -After filling `v`, `rng.offset` advances by `length(v)`. It can be called without `rng`, in which -case the default `CounterRNG` is used. +- For [`CounterRNG`](@ref), each `v[i]` uses counter + `rng.offset + UInt64(i - 1)` in linear indexing order, and `rng.offset` advances by `length(v)`. +- For `StreamRNG{Xoshiro256PP}`, only CPU backend + dense arrays are currently supported, and + `rng.state` is advanced by the CPU stream implementation. Supported scalar element types are: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -126,7 +216,7 @@ Semantics: """ function rand!( - rng::CounterRNG, + rng::AbstractAKRNG, v::AbstractArray{T}, backend::Backend=get_backend(v); @@ -138,26 +228,49 @@ function rand!( # GPU settings block_size::Int=256, ) where T - @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" - # Local isbits captures from mutable rng object - seed, alg, initial_offset = rng.seed, rng.alg, rng.offset - - foreachindex( - v, backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - @inbounds v[i] = rand_scalar(seed, alg, initial_offset + _counter_from_index(i), T) + if rng isa CounterRNG + crng = rng::CounterRNG + + # Local isbits captures from mutable rng object + seed, alg, initial_offset = crng.seed, crng.alg, crng.offset + + foreachindex( + v, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + @inbounds v[i] = rand_scalar(seed, alg, initial_offset + _counter_from_index(i), T) + end + + crng.offset += UInt64(length(v)) + return v + end + + if rng isa StreamRNG{Xoshiro256PP} + srng = rng::StreamRNG{Xoshiro256PP} + @argcheck backend == CPU_BACKEND "StreamRNG with Xoshiro256PP is only supported on CPU backend" + @argcheck v isa DenseArray "StreamRNG with Xoshiro256PP currently supports dense arrays only" + + _rand_cpu_xoshiro!(vec(v), srng; max_tasks, min_elems) + return v + end + + if rng isa StreamRNG + throw(ArgumentError( + "No rand! implementation for StreamRNG algorithm $(typeof(rng.alg)) on backend $(backend)" + )) end - rng.offset += UInt64(length(v)) - - v + throw(ArgumentError( + "No rand! implementation for RNG type $(typeof(rng)) on backend $(backend)" + )) end -rand!(v::AbstractArray, args...; kwargs...) = rand!(CounterRNG(), v, args...; kwargs...) +rand!(v::AbstractArray, args...; kwargs...) = rand!( + _default_rng_from_backend(get_backend(v)), v, args...; kwargs... +) """ diff --git a/src/rand/randn.jl b/src/rand/randn.jl index b2b5dbb3..65c2612d 100644 --- a/src/rand/randn.jl +++ b/src/rand/randn.jl @@ -13,6 +13,20 @@ const ALLOWED_RANDN_SCALARS = Union{ end +# Box-Muller transform from raw random bits: `u_radius` sets the radius, `u_angle` the angle. +# `sqrt_llvm` skips the DomainError branch of `sqrt`; the argument is always non-negative here. +@inline function _box_muller( + ::Type{T}, + u_radius::UIntType, + u_angle::UIntType, +)::Tuple{T, T} where {T <: Union{Float32, Float64}, UIntType <: Union{UInt32, UInt64}} + radius = Base.sqrt_llvm(T(-2) * _fast_log(T, u_radius)) + stheta, ctheta = _fast_sincospi(T, u_angle) + return radius * ctheta, radius * stheta +end + + +# One UInt64 draw per pair: the two 32-bit halves drive the radius and angle respectively @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, @@ -20,15 +34,11 @@ end ::Type{Float32}, )::Tuple{Float32, Float32} u = rand_uint(seed, alg, pair_counter, UInt64) - u1 = _uint32_to_open_unit_float32_midpoint(_u32_lo(u)) - u2 = _uint32_to_open_unit_float32_midpoint(_u32_hi(u)) - radius = sqrt(-2.0f0 * log(u1)) - theta = Float32(2pi) * u2 - stheta, ctheta = sincos(theta) - return radius * ctheta, radius * stheta + return _box_muller(Float32, _u32_lo(u), _u32_hi(u)) end +# Two UInt64 draws per pair, at counters `2 * pair_counter` (radius) and `2 * pair_counter + 1` (angle) @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, @@ -36,12 +46,9 @@ end ::Type{Float64}, )::Tuple{Float64, Float64} c0 = pair_counter << 1 - u1 = rand_float_open01(seed, alg, c0, Float64) - u2 = rand_float_open01(seed, alg, c0 + UInt64(1), Float64) - radius = sqrt(-2.0 * log(u1)) - theta = Float64(2pi) * u2 - stheta, ctheta = sincos(theta) - return radius * ctheta, radius * stheta + u_radius = rand_uint(seed, alg, c0, UInt64) + u_angle = rand_uint(seed, alg, c0 + UInt64(1), UInt64) + return _box_muller(Float64, u_radius, u_angle) end @@ -71,14 +78,27 @@ end end -# `Val{ODD}` keeps parity in the type domain so each specialization (`ODD==0` / `ODD==1`) -# can fold index bias at compile time. -# - `Val{0}` => even-offset pair writes at indices `(2i-1, 2i)` so bias is `-1` -# - `Val{1}` => odd-offset pair writes at indices `(2i, 2i+1)` after prefix handling so bias is `0` +# `Val{ODD}` keeps offset parity in the type domain so each specialization (`ODD==0` / `ODD==1`) +# can fold index bias and head handling at compile time. +# - `Val{0}` => pair `i` writes at indices `(2i-1, 2i)` so bias is `-1` +# - `Val{1}` => pair `i` writes at indices `(2i-2, 2i-1)` so bias is `-2` @inline _randn_i0_bias(::Val{0}) = -1 -@inline _randn_i0_bias(::Val{1}) = 0 +@inline _randn_i0_bias(::Val{1}) = -2 + +# Only the first pair at an odd offset has a `z0` that falls before `v[1]` +@inline _randn_head_in_bounds(::Val{0}, i0) = true +@inline _randn_head_in_bounds(::Val{1}, i0) = i0 >= 1 + +#= +Fill `v` from the Box-Muller pairs overlapping the normal counters +`[initial_offset, initial_offset + length(v))`, with one task/thread per pair. + +When the offset or end is odd, the first or last pair straddles the array bounds; the out-of-bounds +half is computed and discarded, so `v[i]` depends only on its counter `initial_offset + i - 1`. +This keeps head and tail handling inside the single parallel launch (no scalar writes). +=# @inline function _randn_core!( v::AbstractArray{T}, seed, alg, initial_offset, backend, max_tasks, min_elems, prefer_threads, block_size, @@ -86,40 +106,33 @@ end ) where {T, ODD} len = length(v) - prefix_len = ODD - # If offset is odd, need to individually handle the first element. - prefix_len == 1 && @allowscalar @inbounds v[1] = randn_scalar(seed, alg, initial_offset, T) + # Pairs covering counters `[initial_offset, initial_offset + len)` + pair_start = initial_offset >> 1 + pair_count = (len + ODD + 1) >> 1 - # Stream is now even-aligned, so can foreachindex through the pairs. - pair_start = (initial_offset + UInt64(prefix_len)) >> 1 - - # Capture `Val(ODD)` into the closure so bias stays a compile-time constant inside the loop. + # Capture `Val(ODD)` into the closure so parity handling stays compile-time inside the loop. odd_val = Val(ODD) - i0_bias = _randn_i0_bias(odd_val) - remaining_len = len - prefix_len - pair_count = remaining_len >> 1 - - if pair_count > 0 - foreachindex( - Base.OneTo(pair_count), backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - pair_counter = pair_start + _counter_from_index(i) - z0, z1 = randn_pair(seed, alg, pair_counter, T) - i0 = (i << 1) + _randn_i0_bias(odd_val) + + foreachindex( + Base.OneTo(pair_count), backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + pair_counter = pair_start + _counter_from_index(i) + z0, z1 = randn_pair(seed, alg, pair_counter, T) + i0 = (i << 1) + _randn_i0_bias(odd_val) + + if 1 < i < pair_count + # Interior pairs always lie fully inside `v`; unconditional stores can be merged @inbounds v[i0] = z0 @inbounds v[i0 + 1] = z1 + else + # Boundary pairs may straddle either end of `v` + _randn_head_in_bounds(odd_val, i0) && (@inbounds v[i0] = z0) + i0 + 1 <= len && (@inbounds v[i0 + 1] = z1) end end - # If an extra element remains after pair writing, fill it individually. - tail_index = (pair_count << 1) + i0_bias + 2 - if tail_index <= len - tail_counter = initial_offset + UInt64(tail_index - 1) - @allowscalar @inbounds v[tail_index] = randn_scalar(seed, alg, tail_counter, T) - end - return v end @@ -142,7 +155,8 @@ end Fill `v` in-place with pseudo-random samples from a standard normal distribution. For `v[i]`, the normal stream counter is `rng.offset + UInt64(i - 1)` in linear indexing order. -Values are generated using Box-Muller from midpoint-open uniforms in `(0, 1)`. +Values are generated using Box-Muller, with polynomial `log` and `sincospi` evaluated directly on +the raw random bits in the requested precision (`Float16` is computed in `Float32`). After filling `v`, `rng.offset` advances by `length(v)`. diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index 35d90846..c25c75c3 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -15,6 +15,9 @@ @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) +@inline _default_rng_from_backend(backend::Backend) = backend == CPU_BACKEND ? StreamRNG() : CounterRNG() + + # Shared allocation + fill helper for rand/randn convenience constructors. @inline function _allocate_and_fill_rand( fill!, @@ -171,70 +174,3 @@ end # Interpret as 1.mantissa, then subtract 1 for [0, 1) reinterpret(Float64, bits) - 1.0 end - - - - - -### Helpers for randn ### - - -# Midpoint-mapped open-interval Float sampling in (0, 1), used for Box-Muller -const OPEN01_MAX_MIDPOINT_INDEX_F32 = UInt32(0x00fffffe) -const OPEN01_MAX_MIDPOINT_INDEX_F64 = UInt64(0x001ffffffffffffe) -const OPEN01_MIDPOINT_SCALE_F32 = ldexp(Float32(1), -24) -const OPEN01_MIDPOINT_SCALE_F64 = ldexp(Float64(1), -53) - - -# Convert random UInt32 bits to Float32 in (0, 1) using midpoint mapping on a 24-bit grid. -@inline function _uint32_to_open_unit_float32_midpoint(u::UInt32)::Float32 - # `min` keeps the top midpoint below one after Float32 rounding. - k = min(u >> 8, OPEN01_MAX_MIDPOINT_INDEX_F32) - return (Float32(k) + 0.5f0) * OPEN01_MIDPOINT_SCALE_F32 -end - - -# Convert random UInt64 bits to Float64 in (0, 1) using midpoint mapping on a 53-bit grid. -@inline function _uint64_to_open_unit_float64_midpoint(u::UInt64)::Float64 - # `min` keeps the top midpoint below one after Float64 rounding. - k = min(u >> 11, OPEN01_MAX_MIDPOINT_INDEX_F64) - return (Float64(k) + 0.5) * OPEN01_MIDPOINT_SCALE_F64 -end - - -# Float16 path reuses Float32 midpoint sampling for robust math in Box-Muller. -@inline function rand_float_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float16}, -)::Float16 - return Float16(rand_float_open01(seed, alg, counter, Float32)) -end - - -@inline function rand_float_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float32}, -)::Float32 - return _uint32_to_open_unit_float32_midpoint(rand_uint(seed, alg, counter, UInt32)) -end - - -@inline function rand_float_open01( - seed::UInt64, - alg::CounterRNGAlgorithm, - counter::UInt64, - ::Type{Float64}, -)::Float64 - return _uint64_to_open_unit_float64_midpoint(rand_uint(seed, alg, counter, UInt64)) -end - - -@inline function rand_float_open01(::UInt64, ::CounterRNGAlgorithm, ::UInt64, ::Type{T}) where {T} - throw(ArgumentError( - "Unsupported open-interval random type $(T). Supported: Union{Float16, Float32, Float64}" - )) -end diff --git a/test/randn.jl b/test/randn.jl index 2d7b5ffc..b5d18fe0 100644 --- a/test/randn.jl +++ b/test/randn.jl @@ -31,9 +31,9 @@ function _assert_randn_matches_reference!(rng, x; kwargs...) if IS_CPU_BACKEND @test xa == ref else - # randn uses Box-Muller (`log`, `sqrt`, `sincos`), and GPU libm implementations are not - # bit-identical to CPU scalar libm. Stream/counter mapping is still deterministic, but the - # final Float32 values can differ by a few ULP, so we use a tight absolute tolerance here. + # randn's Box-Muller uses explicit `fma` polynomials rather than libm, so results are + # typically bit-identical across backends. Backends may still differ in `sqrt` or division + # rounding, so we keep a tight absolute tolerance here rather than requiring equality. atol = _randn_reference_atol(eltype(xa)) @test all(isapprox.(xa, ref; rtol=zero(atol), atol)) end @@ -43,27 +43,65 @@ end @testset "randn" begin - @testset "scalar helpers" begin - @test 0.0f0 < AK._uint32_to_open_unit_float32_midpoint(UInt32(0)) < 1.0f0 - @test 0.0f0 < AK._uint32_to_open_unit_float32_midpoint(typemax(UInt32)) < 1.0f0 - - if IS_CPU_BACKEND - @test 0.0 < AK._uint64_to_open_unit_float64_midpoint(UInt64(0)) < 1.0 - @test 0.0 < AK._uint64_to_open_unit_float64_midpoint(typemax(UInt64)) < 1.0 + @testset "fastmath" begin + @test 0.0f0 < AK._uint32_to_left_open_unit_float32(UInt32(0)) <= 1.0f0 + @test 0.0f0 < AK._uint32_to_left_open_unit_float32(typemax(UInt32)) <= 1.0f0 + @test 0.0 < AK._uint64_to_left_open_unit_float64(UInt64(0)) <= 1.0 + @test 0.0 < AK._uint64_to_left_open_unit_float64(typemax(UInt64)) <= 1.0 + + # Edge cases: log never reaches zero or -Inf, angles never land on an axis + @test AK._fast_log(Float32, typemax(UInt32)) < 0 + @test AK._fast_log(Float32, typemin(UInt32)) > -Inf32 + @test AK._fast_log(Float64, typemax(UInt64)) < 0 + @test AK._fast_log(Float64, typemin(UInt64)) > -Inf + @test AK._fast_sincospi(Float32, typemin(UInt32)) === (Float32(2pi * 2.0^-33), 1.0f0) + @test AK._fast_sincospi(Float64, typemin(UInt64)) === (2pi * 2.0^-65, 1.0) + + # Reference Box-Muller radius sqrt(-2 log(x)) in Float64, using log1p near x = 1 + ref_radius(u::UInt32) = sqrt(-2 * log(fma(Float64(u), 2.0^-32, 2.0^-33))) + ref_radius(u::UInt64) = sqrt(-2 * ( + u < UInt64(2)^63 ? + log(fma(Float64(u), 2.0^-64, 2.0^-65)) : + log1p(-fma(Float64(~u), 2.0^-64, 2.0^-65)) + )) + fast_radius(::Type{T}, u) where {T} = Base.sqrt_llvm(-2 * AK._fast_log(T, u)) + + # Reference sincospi with the same octant mapping as `_fast_sincospi` + function ref_sincospi(u::Unsigned) + nbits = 8 * sizeof(u) + y = fma(Float64(u & ~oftype(u, 0x7)), 2.0^-(nbits + 2), 2.0^-nbits) + return AK._sincospi_apply_octant(u % UInt8, sinpi(y), cospi(y)) end + sincospi_err(::Type{T}, u) where {T} = maximum(abs.(AK._fast_sincospi(T, u) .- ref_sincospi(u))) + + # Sample the full UInt32 range, plus both ends densely + us32 = vcat( + collect(UInt32(0):UInt32(4093):typemax(UInt32)), + collect(UInt32(0):UInt32(1 << 16)), + collect(typemax(UInt32) - UInt32(1 << 16):typemax(UInt32)), + ) + @test maximum(u -> abs(fast_radius(Float32, u) - ref_radius(u)), us32) < 5e-7 + @test maximum(u -> sincospi_err(Float32, u), us32) < 2e-7 + + # Sample the full UInt64 range, plus both ends and the midpoint densely + us64 = vcat( + [UInt64(i) << 44 for i in 0:((1 << 20) - 1)], + collect(UInt64(0):UInt64(1 << 16)), + collect(UInt64(2)^63 - UInt64(1 << 16):UInt64(2)^63 + UInt64(1 << 16)), + collect(typemax(UInt64) - UInt64(1 << 16):typemax(UInt64)), + ) + @test maximum(u -> abs(fast_radius(Float64, u) - ref_radius(u)), us64) < 3e-15 + @test maximum(u -> sincospi_err(Float64, u), us64) < 4e-16 + + # Mean of log(x) over uniform x in (0, 1] is -1 (midpoint-sampled over the UInt32 range) + mean_log = sum(u -> Float64(AK._fast_log(Float32, u)), UInt32(128):UInt32(256):typemax(UInt32)) / 2^24 + @test abs(mean_log + 1) < 1e-6 + end + + @testset "scalar helpers" begin seed = UInt64(0x123456789abcdef) for alg in RANDN_ALGS - for counter in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - u32 = AK.rand_float_open01(seed, alg, counter, Float32) - @test 0.0f0 < u32 < 1.0f0 - - if IS_CPU_BACKEND - u64 = AK.rand_float_open01(seed, alg, counter, Float64) - @test 0.0 < u64 < 1.0 - end - end - for T in RANDN_FLOAT_TYPES_BACKEND s0 = AK.randn_scalar(seed, alg, UInt64(42), T) s1 = AK.randn_scalar(seed, alg, UInt64(43), T) @@ -81,7 +119,6 @@ end end end - @test_throws ArgumentError AK.rand_float_open01(seed, AK.Philox(), UInt64(0), UInt32) @test_throws ArgumentError AK.randn_scalar(seed, AK.Philox(), UInt64(0), UInt32) end @@ -131,6 +168,17 @@ end @test vcat(Array(s1), Array(s2)) == Array(s12) @test rng_once.offset == UInt64(217) + # Two odd-length fills (second starts at an odd offset) match one fill of the combined length + rng_split = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) + a = array_from_host(zeros(Float32, 5)) + b = array_from_host(zeros(Float32, 5)) + AK.randn!(rng_split, a; prefer_threads) + AK.randn!(rng_split, b; prefer_threads) + + ab = array_from_host(zeros(Float32, 10)) + AK.randn!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), ab; prefer_threads) + @test vcat(Array(a), Array(b)) == Array(ab) + empty = array_from_host(zeros(Float32, 0)) stream_offset = rng_stream.offset AK.randn!(rng_stream, empty; prefer_threads, block_size=64) From 3f72dbfe32c1f200db8d054f6941d03ad0ec5cad Mon Sep 17 00:00:00 2001 From: fjbarter Date: Mon, 30 Nov 2026 11:55:54 +0000 Subject: [PATCH 20/20] respond to pr #80 review: forward to GPUArrays for on-device rng, but contribute threaded deterministic CPU generation that outperforms Base, and the option for completely determinstic generation regardless of backend. --- Project.toml | 2 + docs/src/api/rand.md | 118 +++++----- prototype/rand/Base_rand_vs_AK.jl | 15 ++ prototype/rand/Base_randn_vs_AK.jl | 20 ++ src/AcceleratedKernels.jl | 1 + src/rand/fastmath.jl | 196 ----------------- src/rand/philox.jl | 72 ++++--- src/rand/rand.jl | 125 ++++++----- src/rand/rand_cpu.jl | 270 +++++++++++++++++++++++ src/rand/randn.jl | 226 +++++++++++-------- src/rand/splitmix.jl | 30 +-- src/rand/threefry.jl | 75 ------- src/rand/utilities.jl | 125 +++++++---- src/rand/ziggurat.jl | 334 +++++++++++++++++++++++++++++ test/rand.jl | 153 ++++++++----- test/randn.jl | 200 +++++++++-------- 16 files changed, 1238 insertions(+), 724 deletions(-) create mode 100644 prototype/rand/Base_rand_vs_AK.jl create mode 100644 prototype/rand/Base_randn_vs_AK.jl delete mode 100644 src/rand/fastmath.jl create mode 100644 src/rand/rand_cpu.jl delete mode 100644 src/rand/threefry.jl create mode 100644 src/rand/ziggurat.jl diff --git a/Project.toml b/Project.toml index b0c601d9..1eb3e52f 100644 --- a/Project.toml +++ b/Project.toml @@ -8,6 +8,7 @@ ArgCheck = "dce04be8-c92d-5529-be00-80e4d2c0e197" GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a" +PhiloxRNG = "508b8dab-2d72-462c-b792-eb7ae329b456" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" UnsafeAtomics = "013be700-e6cd-48c3-b4a1-df204f14c38f" @@ -22,6 +23,7 @@ ArgCheck = "2" GPUArraysCore = "0.2.0" KernelAbstractions = "0.9.34" Markdown = "1" +PhiloxRNG = "1.1" Random = "1" UnsafeAtomics = "0.3.0" julia = "1.10" diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md index 7b3f65ab..251a8976 100644 --- a/docs/src/api/rand.md +++ b/docs/src/api/rand.md @@ -1,7 +1,13 @@ ### Random Number Generation -Counter-based random generation for CPU and GPU backends with deterministic stream behaviour for a -fixed `seed`, algorithm, and call sequence. +Random generation for CPU and GPU backends with deterministic stream behaviour for a fixed `seed` +and call sequence. Two RNG types are available: +- `StreamRNG`: a parallelised Xoshiro256++ stream on the CPU backend, identical for any number of + threads; the CPU default +- `CounterRNG`: counter-based (Philox), giving identical values on every backend, CPU or GPU + +Without an explicit RNG, GPU arrays are filled by their array package's own `Random.rand!` / +`Random.randn!` (GPUArrays' RNG for JuliaGPU backends); AK does not duplicate that front end. Both in-place and allocation forms are supported: - Uniform: `AK.rand!`, `AK.rand` @@ -23,16 +29,19 @@ This gives stream-consistent chunking: Calls that share the same `CounterRNG` instance concurrently are not thread-safe and may race on `offset`. -`AK.rand!` and `AK.randn!` accept `rng::AK.CounterRNG`. Passing other RNG container types is not -supported and will throw a `MethodError`. +`AK.rand!` and `AK.randn!` accept `rng::AK.CounterRNG` on any backend, or `rng::AK.StreamRNG` on +the CPU backend. #### Auto-seeded convenience behaviour -Use an explicit `CounterRNG` when reproducibility is required. +Use an explicit RNG when reproducibility is required. -For convenience, calls without an explicit `rng` construct a fresh `CounterRNG()` on each call, -using one auto-seeded `Base.rand(UInt64)` draw. Therefore repeated bare calls intentionally produce -different outputs unless `Random.seed!()` is used first. +For convenience, calls without an explicit `rng` on the CPU backend construct a fresh `StreamRNG()` +on each call, using one auto-seeded `Base.rand(UInt64)` draw. Therefore repeated bare calls +intentionally produce different outputs unless `Random.seed!()` is used first. On other backends, +bare calls forward to the array package's `Random.rand!` / `Random.randn!`, which use that +package's own RNG (seeded through it, not through `Random.seed!()`), and AK's keyword settings are +unused. Examples: - `AK.rand!(v)` @@ -40,8 +49,7 @@ Examples: - `AK.rand(backend, args...)` - `AK.randn(backend, args...)` -These do **not** continue a shared stream across calls unless you pass the same explicit -`CounterRNG`. +These do **not** continue a shared stream across calls unless you pass the same explicit RNG. #### Allocation forms @@ -50,7 +58,7 @@ Canonical forms: - `AK.randn(rng, backend, T, dims...)` Shared defaults: -- omit `rng` -> fresh `CounterRNG()` +- omit `rng` -> fresh `StreamRNG()` on the CPU backend, the array package's `Random` fill otherwise - omit `backend` -> CPU backend - omit `T` -> `Float64` on CPU backend, `Float32` otherwise @@ -60,7 +68,7 @@ Common shorthands include: - `AK.rand(backend, dims...)` - and the corresponding `AK.randn(...)` variants -For explicit `rng`, both `AK.rand` and `AK.randn` advance `rng.offset` by the number of generated +For explicit `rng`, both `AK.rand` and `AK.randn` advance the stream by the number of generated elements, i.e. `prod(dims)`. #### Supported element types @@ -76,60 +84,73 @@ elements, i.e. `prod(dims)`. #### Value generation semantics -The core generator produces either a `UInt32` or `UInt64`, depending on the requested output type. +For `CounterRNG`, the core generator produces either a `UInt32` or `UInt64`, depending on the requested output type. That raw unsigned value is then mapped as follows: - Unsigned integers: returned directly, or truncated if narrower - Signed integers: the corresponding unsigned bit pattern reinterpreted as signed, then truncated if narrower - Floats: mantissa construction onto a uniform grid in `[0, 1)` ([read more](https://lomont.org/posts/2017/unit-random/)) - Bool: `true` if the raw `UInt` draw is odd (`isodd(u)`), otherwise `false` -`AK.randn!` uses Box-Muller, with fast polynomial `log` and `sincospi` evaluated directly on the raw random bits (adapted from [PhiloxRNG.jl](https://github.com/medyan-dev/PhiloxRNG.jl)). These avoid libm calls and `Float64` widening, so `Float32` output is supported on devices without `Float64`. +With `CounterRNG`, normal samples of each precision draw from their own independent stream (the seed +is mixed with a per-precision constant), so mixing `AK.rand!` and `AK.randn!` calls of different +element types on one `CounterRNG` never reuses random bits between elements. -#### Algorithms currently available +With `CounterRNG`, `AK.randn!` uses Box-Muller from [PhiloxRNG.jl](https://github.com/medyan-dev/PhiloxRNG.jl), with fast polynomial `log` and `sincospi` evaluated directly on the raw random bits. These avoid libm calls and `Float64` widening, so `Float32` output is supported on devices without `Float64`. -- `SplitMix64` ([read more](https://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64)) -- `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) -- `Threefry` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)) +#### CPU stream RNG -`Philox` is the default algorithm for `CounterRNG()`. +`StreamRNG` (default algorithm `Xoshiro256PP()`) holds a Xoshiro256++ state, seeded from `seed` +via SplitMix64. For `AK.rand!(rng, v)` on the CPU backend: +- `v[i]` is the `i`th output of the stream from `rng.state` in linear indexing order, converted + exactly as Base's scalar `rand(::Xoshiro, T)`; this equals a sequential loop over a + `Random.Xoshiro` with the same state +- `rng.state` advances by `length(v)` steps, giving the same stream-consistent chunking as + `CounterRNG` +- the result is identical for any number of tasks: each task jumps ahead to its first element in + bounded time (at most 64 precomputed power-of-two jumps), then advances several segments of the + stream in lockstep -#### Statistical testing and security +`AK.randn!(rng::StreamRNG, v)` follows the same rules, using the ziggurat method (as Base) with +exactly one stream output per sample: in the rare rejection case, extra randomness comes from a +local SplitMix64 sequence seeded by that output rather than from the stream. Values therefore +differ from Base's `randn`, but are identical for any number of tasks. -- In this repository, `SplitMix64`, `Philox`, and `Threefry` have passed TestU01 BigCrush -- These generators are not intended to be cryptographically secure +On an Apple M5 Pro, filling a 10M-element `Vector{Float64}` on a single task runs at ~22 GB/s with +`AK.rand!` and ~8 GB/s with `AK.randn!`, matching single-threaded `Random.rand!` and +`Random.randn!`; on 18 threads these reach ~115 GB/s and ~80 GB/s. `CounterRNG` reaches ~28 GB/s and +~17 GB/s on the same CPU; use it when the same values are required across CPU and GPU backends. -#### Philox keying note +#### Algorithm -AK uses `Philox2x32` internally, which has a single 32-bit Philox key word. +`CounterRNG` uses `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)), +the only (and default) algorithm. -Users may pass any non-negative `Integer` seed with `seed <= typemax(UInt64)`; AK converts it to -`UInt64` and derives the 32-bit Philox key using SplitMix. This wrapper choice is deliberate for -ease of use and deterministic streams, not a change to the Philox round function itself. +#### Statistical testing and security -Therefore, AK Philox streams are deterministic and high-quality, but are not guaranteed to be -bit-for-bit identical to a raw Random123 Philox stream unless the same seed-to-key mapping and -counter convention are used. +- In this repository, `Philox` (Philox4x32-10) has passed TestU01 BigCrush +- These generators are not intended to be cryptographically secure -#### Custom algorithms +#### Philox keying note -To define a custom counter RNG: -- define an algorithm type `MyAlg <: AK.CounterRNGAlgorithm` -- implement: - - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` - - `AK.rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` +AK's `Philox` is Random123's Philox4x32-10 (a 128-bit counter, a 64-bit key, and 128 random bits +per block evaluation), evaluated by [PhiloxRNG.jl](https://github.com/medyan-dev/PhiloxRNG.jl). -Then use it via: -- `AK.CounterRNG(seed; alg=MyAlg(), offset=...)` +Users may pass any non-negative `Integer` seed with `seed <= typemax(UInt64)`; the seed is used +directly as the 64-bit Philox key, so distinct seeds always give distinct streams. Block `b` uses +the counter whose low 64 bits are `b`. Each block yields four 32-bit or two 64-bit outputs (or two +or one Box-Muller pairs), and 32-bit outputs and normal samples of each precision use separate key +domains (the seed XORed with fixed constants), so their different layouts never share random bits. -Both widths should be implemented so `AK.rand!` supports all integer and floating-point output -types without fallback or error. +Raw blocks are bit-identical to Random123 (PhiloxRNG.jl tests them against its known-answer +vectors); the mapping of blocks to array elements is AK's own. #### Performance note -`Philox` is the default because it is high-quality and very fast. `AK.rand!` has been measured at -roughly memory-bound throughput (~390 GB/s) on an Nvidia GeForce RTX 5060, including slightly better -performance than CURAND for large `CuArray{Float32}` fills and substantially faster `CuArray{Int32}` -filling than native `CUDA.rand!` in the benchmarks used for this repository. +`CounterRNG` fills are memory-bound on GPUs. On an Apple M5 Pro with 100M elements, `AK.rand!` and +`AK.randn!` with `CounterRNG` match the throughput of Metal's own `Random.rand!` / `Random.randn!` +(GPUArrays' RNG) within a few percent for `Float32`, `Int32`, `UInt8` and `Float16`, at the GPU's +write bandwidth for 32-bit types. Without an explicit RNG, GPU fills use that backend +implementation directly. Examples: ```julia @@ -149,13 +170,13 @@ v2 = oneArray{Float32}(undef, 100) AK.rand!(rng, v1) AK.rand!(rng, v2) -# Convenience: fresh auto-seeded RNG on each call +# Convenience without an RNG: on GPU arrays this forwards to the backend's Random.rand! y = oneArray{Float32}(undef, 1024) AK.rand!(y) # Allocation form y_cpu_auto = AK.rand(1024) # CPU, Vector{Float64} -y_one = AK.rand(oneAPIBackend(), Float32, 1024) # fresh RNG, allocate + fill oneArray +y_one = AK.rand(oneAPIBackend(), Float32, 1024) # allocate oneArray, fill via oneAPI's Random.rand! y_cpu_typed = AK.rand(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG # Standard normal filling @@ -164,14 +185,13 @@ AK.randn!(rng, z) # Standard normal allocation form z_cpu_auto = AK.randn(1024) # CPU, Vector{Float64} -z_roc = AK.randn(ROCBackend(), 1024) # fresh RNG, allocate + fill ROCArray{Float32} +z_roc = AK.randn(ROCBackend(), 1024) # allocate ROCArray{Float32}, fill via Random.randn! z_cpu_typed = AK.randn(rng, Float16, 1024) # CPU backend, explicit type, explicit RNG ``` ```@docs AcceleratedKernels.CounterRNG -AcceleratedKernels.CounterRNGAlgorithm -AcceleratedKernels.rand_uint +AcceleratedKernels.StreamRNG AcceleratedKernels.reset! AcceleratedKernels.rand! AcceleratedKernels.rand diff --git a/prototype/rand/Base_rand_vs_AK.jl b/prototype/rand/Base_rand_vs_AK.jl new file mode 100644 index 00000000..de7fee23 --- /dev/null +++ b/prototype/rand/Base_rand_vs_AK.jl @@ -0,0 +1,15 @@ +import AcceleratedKernels as AK +using Random +using BenchmarkTools + +N = 1_000_000 +TestType = Float64 + +x = Vector{TestType}(undef, N) + + +println("Random.rand!, $N-element Vector{$TestType}") +display(@benchmark rand!(x)) + +println("AK.rand!, $N-element Vector{$TestType}") +display(@benchmark AK.rand!(x)) diff --git a/prototype/rand/Base_randn_vs_AK.jl b/prototype/rand/Base_randn_vs_AK.jl new file mode 100644 index 00000000..a87a084c --- /dev/null +++ b/prototype/rand/Base_randn_vs_AK.jl @@ -0,0 +1,20 @@ +import AcceleratedKernels as AK +using Random +using BenchmarkTools +using Metal + +N = 1_000_000 +TestType = Float32 + +x = Vector{TestType}(undef, N) + +function AK_rand_fill(x_gpu) + AK.randn!(x_gpu) + AK.synchronize(AK.get_backend(x_gpu)) +end + +println("Random.randn!, $N-element Vector{$TestType}") +display(@benchmark randn!(x)) + +println("AK.randn!, $N-element Vector{$TestType}") +display(@benchmark AK.randn!(x)) diff --git a/src/AcceleratedKernels.jl b/src/AcceleratedKernels.jl index 7262cbed..51a6bd21 100644 --- a/src/AcceleratedKernels.jl +++ b/src/AcceleratedKernels.jl @@ -16,6 +16,7 @@ using GPUArraysCore: AnyGPUArray, @allowscalar using KernelAbstractions using KernelAbstractions: @context using Random +import PhiloxRNG import UnsafeAtomics diff --git a/src/rand/fastmath.jl b/src/rand/fastmath.jl deleted file mode 100644 index d66f28f9..00000000 --- a/src/rand/fastmath.jl +++ /dev/null @@ -1,196 +0,0 @@ -# Fast, device-friendly log and sincospi for Box-Muller, operating directly on raw random bits. -# Avoids libm calls and Float64 widening, and uses explicit `fma` so results are bit-identical -# across backends. -# -# Adapted from PhiloxRNG.jl: https://github.com/medyan-dev/PhiloxRNG.jl -# License is MIT: Copyright (c) 2024 Nathan Zimmerberg, Patrick Kelly, and contributors -# -# The log polynomial, ln2 splitting and reconstruction are in turn adapted from fdlibm's -# e_log.c / e_logf.c (Sun Microsystems, 1993): https://github.com/JuliaMath/openlibm - - -# Polynomial coefficients for log(1+f), from fdlibm -const FASTLOG_POLY_F32 = (0.6666666f0, 0.40000972f0, 0.28498787f0, 0.24279079f0) -const FASTLOG_POLY_F64 = ( - 6.666666666666735130e-01, - 3.999999999940941908e-01, - 2.857142874366239149e-01, - 2.222219843214978396e-01, - 1.818357216161805012e-01, - 1.531383769920937332e-01, - 1.479819860511658591e-01, -) - -# log(2) split into high and low parts for an accurate k*log(2) -const FASTLOG_LN2_HI_F32 = 0.6931381f0 -const FASTLOG_LN2_LO_F32 = 9.058001f-6 -const FASTLOG_LN2_HI_F64 = 6.93147180369123816490e-01 -const FASTLOG_LN2_LO_F64 = 1.90821492927058770002e-10 - -# Bit patterns of sqrt(0.5), used to centre the reduced argument (1+f) on [sqrt(2)/2, sqrt(2)) -const FASTLOG_SQRT_HALF_I32 = reinterpret(Int32, Float32(sqrt(0.5))) -const FASTLOG_SQRT_HALF_I64 = reinterpret(Int64, sqrt(0.5)) - -# Minimax coefficients (in y^2) for sin(pi*y)/y and cos(pi*y) on y in [0, 0.25] -const FASTSINCOSPI_SIN_POLY_F32 = (3.1415927f0, -5.167708f0, 2.5497673f0, -0.58907866f0) -const FASTSINCOSPI_COS_POLY_F32 = (1.0f0, -4.934788f0, 4.057578f0, -1.3061346f0) -const FASTSINCOSPI_SIN_POLY_F64 = ( - 3.141592653589793, - -5.167712780049954, - 2.5501640398733785, - -0.5992645289398095, - 0.08214586918507949, - -0.007370021659123395, - 0.0004615322405282014, -) -const FASTSINCOSPI_COS_POLY_F64 = ( - 1.0, - -4.934802200544605, - 4.0587121263978485, - -1.3352627670374702, - 0.23533054723811608, - -0.025804938901032953, - 0.0019068114005246046, -) - -# Scales mapping raw bits onto the left-open unit interval (0, 1] -const LEFT_OPEN01_SCALE_F32 = ldexp(Float32(1), -32) -const LEFT_OPEN01_OFFSET_F32 = ldexp(Float32(1), -33) -const LEFT_OPEN01_SCALE_F64 = ldexp(Float64(1), -64) -const LEFT_OPEN01_OFFSET_F64 = ldexp(Float64(1), -65) - -# Scales mapping the octant-masked raw bits onto the reduced argument y in (0, 0.25) -const FASTSINCOSPI_SCALE_F32 = ldexp(Float32(1), -34) -const FASTSINCOSPI_OFFSET_F32 = ldexp(Float32(1), -32) -const FASTSINCOSPI_SCALE_F64 = ldexp(Float64(1), -66) -const FASTSINCOSPI_OFFSET_F64 = ldexp(Float64(1), -64) - - -# Horner's method with explicit `fma`. `Base.evalpoly` uses `muladd`, which lets the compiler -# decide whether to fuse; that can differ by an ulp between backends, so we force fusion here. -@inline function _fma_evalpoly(x::T, p::NTuple{4, T})::T where {T <: AbstractFloat} - return fma(x, fma(x, fma(x, p[4], p[3]), p[2]), p[1]) -end - - -@inline function _fma_evalpoly(x::T, p::NTuple{7, T})::T where {T <: AbstractFloat} - return fma(x, fma(x, fma(x, fma(x, fma(x, fma(x, p[7], p[6]), p[5]), p[4]), p[3]), p[2]), p[1]) -end - - -# Convert random UInt32 bits to Float32 in (0, 1] as (u + 0.5) * 2^-32. Never returns zero, so -# the result is always safe to pass to log. -@inline function _uint32_to_left_open_unit_float32(u::UInt32)::Float32 - return fma(Float32(u), LEFT_OPEN01_SCALE_F32, LEFT_OPEN01_OFFSET_F32) -end - - -# Convert random UInt64 bits to Float64 in (0, 1] as (u + 0.5) * 2^-64. -@inline function _uint64_to_left_open_unit_float64(u::UInt64)::Float64 - return fma(Float64(u), LEFT_OPEN01_SCALE_F64, LEFT_OPEN01_OFFSET_F64) -end - - -#= -Compute log(x) for x = _uint32_to_left_open_unit_float32(u) in (0, 1], without libm. - -1) Decompose x = 2^k * (1+f), where sqrt(2)/2 <= 1+f < sqrt(2) -2) Approximate log(1+f) with a polynomial in s = f/(2+f) -3) Reconstruct log(x) = k*log(2) + log(1+f), with log(2) split into high and low parts - -When k == 0 (x close to 1), f is instead taken directly from the complementary bits as --_uint32_to_left_open_unit_float32(~u), which avoids cancellation in x - 1. -=# -@inline function _fast_log(::Type{Float32}, u::UInt32)::Float32 - x = _uint32_to_left_open_unit_float32(u) - - # Subtracting sqrt(0.5)'s bit pattern makes k step down by one at each power-of-two boundary - # below sqrt(0.5); shifting out the 23 mantissa bits leaves k. - ix = reinterpret(Int32, x) - FASTLOG_SQRT_HALF_I32 - k = ix >> Int32(23) - - # Masking keeps the mantissa bits of x; adding sqrt(0.5) back restores 1+f with an exponent of - # -1 or 0 (a borrow from the subtraction above propagates into the exponent field). - f_std = reinterpret(Float32, (ix & Int32(0x007fffff)) + FASTLOG_SQRT_HALF_I32) - 1.0f0 - f_comp = -_uint32_to_left_open_unit_float32(~u) - f = ifelse(k == Int32(0), f_comp, f_std) - - # log(1+f) = f - f^2/2 + s*(f^2/2 + R), with s = f/(2+f), R = s^2 * poly(s^2) - s = f / (2.0f0 + f) - z = s * s - hfsq = 0.5f0 * f * f - hfsq_r = fma(z, _fma_evalpoly(z, FASTLOG_POLY_F32), hfsq) - - k_f32 = Float32(k) - return fma(k_f32, FASTLOG_LN2_HI_F32, f - (hfsq - fma(s, hfsq_r, k_f32 * FASTLOG_LN2_LO_F32))) -end - - -# Float64 version of the above, for x = _uint64_to_left_open_unit_float64(u) -@inline function _fast_log(::Type{Float64}, u::UInt64)::Float64 - x = _uint64_to_left_open_unit_float64(u) - - ix = reinterpret(Int64, x) - FASTLOG_SQRT_HALF_I64 - k = ix >> Int64(52) - - f_std = reinterpret(Float64, (ix & Int64(0x000fffffffffffff)) + FASTLOG_SQRT_HALF_I64) - 1.0 - f_comp = -_uint64_to_left_open_unit_float64(~u) - f = ifelse(k == Int64(0), f_comp, f_std) - - s = f / (2.0 + f) - z = s * s - hfsq = 0.5 * f * f - hfsq_r = fma(z, _fma_evalpoly(z, FASTLOG_POLY_F64), hfsq) - - k_f64 = Float64(k) - return fma(k_f64, FASTLOG_LN2_HI_F64, f - (hfsq - fma(s, hfsq_r, k_f64 * FASTLOG_LN2_LO_F64))) -end - - -#= -Map 2^N raw bits to (sin(theta), cos(theta)) for theta uniformly spaced around the unit circle, -with no point landing exactly on an axis. - -1) The 3 rightmost bits of u select one of 8 octants (pi/4 each) -2) The remaining bits give the reduced argument y in (0, 0.25), biased by half a step to avoid y == 0 -3) Polynomials evaluate sin(pi*y) and cos(pi*y), then each octant bit applies one operation: - - bit 0: swap sin and cos - - bit 1: negate sin - - bit 2: negate cos - -The octants are not in geometric order, but the points are uniformly distributed regardless. -=# -@inline function _fast_sincospi(::Type{Float32}, u::UInt32)::Tuple{Float32, Float32} - y = fma(Float32(u & ~UInt32(0x7)), FASTSINCOSPI_SCALE_F32, FASTSINCOSPI_OFFSET_F32) - y2 = y * y - sin_raw = y * _fma_evalpoly(y2, FASTSINCOSPI_SIN_POLY_F32) - cos_raw = _fma_evalpoly(y2, FASTSINCOSPI_COS_POLY_F32) - return _sincospi_apply_octant(u % UInt8, sin_raw, cos_raw) -end - - -# Float64 version of the above, using 61 bits for the reduced argument -@inline function _fast_sincospi(::Type{Float64}, u::UInt64)::Tuple{Float64, Float64} - y = fma(Float64(u & ~UInt64(0x7)), FASTSINCOSPI_SCALE_F64, FASTSINCOSPI_OFFSET_F64) - y2 = y * y - sin_raw = y * _fma_evalpoly(y2, FASTSINCOSPI_SIN_POLY_F64) - cos_raw = _fma_evalpoly(y2, FASTSINCOSPI_COS_POLY_F64) - return _sincospi_apply_octant(u % UInt8, sin_raw, cos_raw) -end - - -# Branch-free octant reconstruction from the 3 rightmost bits of `octant` -@inline function _sincospi_apply_octant( - octant::UInt8, - sin_raw::T, - cos_raw::T, -)::Tuple{T, T} where {T <: AbstractFloat} - swap = !iszero(octant & UInt8(0x1)) - sin_neg = !iszero(octant & UInt8(0x2)) - cos_neg = !iszero(octant & UInt8(0x4)) - - s = ifelse(swap, cos_raw, sin_raw) - c = ifelse(swap, sin_raw, cos_raw) - - return ifelse(sin_neg, -s, s), ifelse(cos_neg, -c, c) -end diff --git a/src/rand/philox.jl b/src/rand/philox.jl index 0de9ff40..1f0bee2a 100644 --- a/src/rand/philox.jl +++ b/src/rand/philox.jl @@ -1,59 +1,61 @@ +# Philox4x32-10 (Random123), evaluated by PhiloxRNG.jl: 128-bit counter, 64-bit key (the seed), +# 128 random bits per block struct Philox <: CounterRNGAlgorithm end -# Philox magic numbers -const PHILOX_M0 = UInt32(0xD256D193) -const PHILOX_W0 = UInt32(0x9E3779B9) -const PHILOX_ROUNDS = 7 +# 32-bit outputs pack 4 per block and 64-bit outputs 2 per block, so the two layouts use separate +# key domains (SHA-512 initial hash value, nothing up the sleeve) +const PHILOX4X32_DOMAIN_U32 = 0x510e527fade682d1 -@inline function _philox2x32_round(x0::UInt32, x1::UInt32, k0::UInt32) - lo = PHILOX_M0 * x0 - hi = _mulhi_u32(PHILOX_M0, x0) - y0 = xor(xor(hi, k0), x1) - y1 = lo - return y0, y1 +# Evaluate block `block` of the stream for `seed`: the seed is the 64-bit key, and the block index +# fills the low 64 bits of the counter +@inline function _philox4x32_block(seed::UInt64, block::UInt64)::NTuple{4, UInt32} + return PhiloxRNG.philox4x32_10(block, UInt64(0), seed) end -# Evaluate one Philox block at `counter`, returning two 32-bit lanes `(x0, x1)` -@inline function _philox2x32_block( - seed::UInt64, - counter::UInt64, -)::Tuple{UInt32, UInt32} - x0 = _u32_lo(counter) - x1 = _u32_hi(counter) - - k0 = splitmix32_from_u64(seed) - - @inbounds for _ in 1:PHILOX_ROUNDS - x0, x1 = _philox2x32_round(x0, x1, k0) - k0 += PHILOX_W0 - end - - return x0, x1 -end - - -# Return lane 0 from the single Philox block at `counter` +# Counter `c` is lane `c % 4` of block `c ÷ 4`, in the 32-bit key domain @inline function rand_uint( seed::UInt64, alg::Philox, counter::UInt64, ::Type{UInt32}, )::UInt32 - x0, _ = _philox2x32_block(seed, counter) - return x0 + x = _philox4x32_block(xor(seed, PHILOX4X32_DOMAIN_U32), counter >> 2) + lane = counter & UInt64(0x3) + return ifelse(lane == 0, x[1], ifelse(lane == 1, x[2], ifelse(lane == 2, x[3], x[4]))) end -# Build UInt64 from the two lanes `(x0, x1)` of the same Philox block at `counter` +# Counter `c` is half `c % 2` of block `c ÷ 2` @inline function rand_uint( seed::UInt64, alg::Philox, counter::UInt64, ::Type{UInt64}, )::UInt64 - x0, x1 = _philox2x32_block(seed, counter) - return _u64_from_u32s(x0, x1) + x = _philox4x32_block(seed, counter >> 1) + return iseven(counter) ? _u64_from_u32s(x[1], x[2]) : _u64_from_u32s(x[3], x[4]) +end + + +# Elements per group in `rand!`: 32-bit scalars fill 4 elements per block, 64-bit scalars 2 +@inline function _rand_group_size(::Philox, ::Type{T}) where {T} + return _rand_scalar_uint_type(T) === UInt32 ? Val(4) : Val(2) +end + + +# All scalars from block `group`, identical to `rand_scalar` at counters `group * G` onwards +@inline function rand_group(seed::UInt64, alg::Philox, group::UInt64, ::Type{T}) where {T} + if _rand_scalar_uint_type(T) === UInt32 + x = _philox4x32_block(xor(seed, PHILOX4X32_DOMAIN_U32), group) + return Base.map(u -> _rand_scalar_from_uint(T, u), x) + else + x = _philox4x32_block(seed, group) + return ( + _rand_scalar_from_uint(T, _u64_from_u32s(x[1], x[2])), + _rand_scalar_from_uint(T, _u64_from_u32s(x[3], x[4])), + ) + end end diff --git a/src/rand/rand.jl b/src/rand/rand.jl index 8bef11b6..8d821dce 100644 --- a/src/rand/rand.jl +++ b/src/rand/rand.jl @@ -15,65 +15,52 @@ Abstract supertype for AcceleratedKernels RNG objects, such as [`CounterRNG`](@r abstract type AbstractAKRNG end -""" - CounterRNGAlgorithm - -Abstract supertype for algorithms used by [`CounterRNG`](@ref). - -To define a custom counter-based RNG algorithm, subtype `CounterRNGAlgorithm` and implement -[`rand_uint`](@ref) for both `UInt32` and `UInt64` outputs. -""" +# Internal algorithm supertypes: `Philox` is currently the only `CounterRNG` algorithm, and +# `Xoshiro256PP` the only `StreamRNG` algorithm abstract type CounterRNGAlgorithm end - - -""" - StreamRNGAlgorithm - -Abstract supertype for algorithms used by [`StreamRNG`](@ref). -""" abstract type StreamRNGAlgorithm end -""" - StreamRNGState - -Abstract supertype for mutable stream RNG state objects stored by [`StreamRNG`](@ref). -""" +# Internal supertype for stream states: immutable values, replaced by `StreamRNG` as it advances abstract type StreamRNGState end -""" - stream_init_state(seed::UInt64, alg::StreamRNGAlgorithm) -> StreamRNGState - -Extension point for stream RNG algorithms to build their initial mutable state from `seed`. -""" +# Internal: build an algorithm's initial stream state from `seed` @inline function stream_init_state(seed::UInt64, alg::StreamRNGAlgorithm)::StreamRNGState throw(ArgumentError("No stream_init_state implementation for RNG algorithm: $(typeof(alg))")) end """ - StreamRNG(seed::Integer; alg::StreamRNGAlgorithm, state::Union{Nothing, StreamRNGState}=nothing) + StreamRNG( + seed::Integer; + alg::StreamRNGAlgorithm=Xoshiro256PP(), + state::Union{Nothing, StreamRNGState}=nothing, + ) -Stateful stream RNG container. +Stateful stream RNG for the CPU backend. `StreamRNG` stores: - `seed` -- algorithm (`alg`) -- mutable stream state (`state::StreamRNGState`) +- algorithm (`alg`): `Xoshiro256PP()`, the only (and default) algorithm +- current stream state (`state`), initialised from `seed` via SplitMix64 unless given -If `state` is not provided, it is initialised via [`stream_init_state`](@ref). +Constructors: +- `StreamRNG(seed::Integer; alg::StreamRNGAlgorithm=Xoshiro256PP(), state=nothing)` + Uses an explicit non-negative seed. +- `StreamRNG(; alg::StreamRNGAlgorithm=Xoshiro256PP(), state=nothing)` + Auto-seeds once using `Base.rand(UInt64)`. """ -mutable struct StreamRNG{A <: StreamRNGAlgorithm} <: AbstractAKRNG +mutable struct StreamRNG{A <: StreamRNGAlgorithm, S <: StreamRNGState} <: AbstractAKRNG const seed::UInt64 const alg::A - state::StreamRNGState + state::S end function StreamRNG( seed::Integer; - alg::StreamRNGAlgorithm, + alg::StreamRNGAlgorithm=Xoshiro256PP(), state::Union{Nothing, StreamRNGState}=nothing, ) @argcheck seed >= 0 "Seed must be a non-negative integer" @@ -167,11 +154,10 @@ include("utilities.jl") # Algorithm-specific integer generators include("splitmix.jl") include("philox.jl") -include("threefry.jl") include("rand_cpu.jl") # Normally distributed scalar generators and randn! -include("fastmath.jl") +include("ziggurat.jl") include("randn.jl") @@ -198,8 +184,14 @@ Fill `v` in-place with pseudo-random values using `rng`. - For [`CounterRNG`](@ref), each `v[i]` uses counter `rng.offset + UInt64(i - 1)` in linear indexing order, and `rng.offset` advances by `length(v)`. -- For `StreamRNG{Xoshiro256PP}`, only CPU backend + dense arrays are currently supported, and - `rng.state` is advanced by the CPU stream implementation. +- For [`StreamRNG`](@ref) with `Xoshiro256PP` (CPU backend only), `v[i]` is the `i`th output of the + Xoshiro256++ stream from `rng.state` in linear indexing order, and `rng.state` advances by + `length(v)` steps. Each value is converted exactly as Base's scalar `rand(::Xoshiro, T)`, so the + result equals a sequential loop over a `Random.Xoshiro` with the same state, regardless of the + number of tasks used. +- Without `rng`: a fresh auto-seeded `StreamRNG()` on the CPU backend. On other backends this + forwards to the array package's own `Random.rand!(v)` (GPUArrays' RNG for JuliaGPU backends), and + the keyword settings are unused; pass a `CounterRNG` for values identical across backends. Supported scalar element types are: - `UInt8`, `UInt16`, `UInt32`, `UInt64` @@ -207,7 +199,7 @@ Supported scalar element types are: - `Float16`, `Float32`, `Float64` - `Bool` -Semantics: +Semantics for [`CounterRNG`](@ref): - Unsigned integers: raw random bit patterns of requested width. - Signed integers: corresponding unsigned patterns reinterpreted as signed. - Floats: mantissa-based conversion from `UInt32`/`UInt64` into `[0, 1)`, uniform over the @@ -236,12 +228,11 @@ function rand!( # Local isbits captures from mutable rng object seed, alg, initial_offset = crng.seed, crng.alg, crng.offset - foreachindex( - v, backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - @inbounds v[i] = rand_scalar(seed, alg, initial_offset + _counter_from_index(i), T) - end + # One block evaluation per group of elements + _fill_groups!( + rand_group, seed, alg, v, initial_offset, _rand_group_size(alg, T), + backend, max_tasks, min_elems, prefer_threads, block_size, + ) crng.offset += UInt64(length(v)) return v @@ -250,9 +241,11 @@ function rand!( if rng isa StreamRNG{Xoshiro256PP} srng = rng::StreamRNG{Xoshiro256PP} @argcheck backend == CPU_BACKEND "StreamRNG with Xoshiro256PP is only supported on CPU backend" - @argcheck v isa DenseArray "StreamRNG with Xoshiro256PP currently supports dense arrays only" - _rand_cpu_xoshiro!(vec(v), srng; max_tasks, min_elems) + _xoshiro_fill_stream!( + _xoshiro_scalar_from_uint64, srng, v, Val(XOSHIRO_RAND_LANES); + max_tasks, min_elems, + ) return v end @@ -268,14 +261,29 @@ function rand!( end -rand!(v::AbstractArray, args...; kwargs...) = rand!( - _default_rng_from_backend(get_backend(v)), v, args...; kwargs... -) +function rand!( + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) where T + @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" + return _fill_default!( + rand!, Random.rand!, v, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) +end """ rand( - rng::CounterRNG, + rng::AbstractAKRNG, backend::Backend, ::Type{T}, dims::Integer...; @@ -293,12 +301,13 @@ Allocate an array of element type `T` on `backend` with shape `dims`, fill it in [`rand!`](@ref), and return it. Convenience overloads: -- `rng` omitted: uses a fresh `CounterRNG()`. +- `rng` omitted: allocates, then fills via [`rand!`](@ref) without an RNG (a fresh `StreamRNG()` on + CPU backend, the array package's `Random.rand!` otherwise). - `backend` omitted: defaults to `CPU_BACKEND`. - `T` omitted: defaults by backend (`Float64` on CPU backend, `Float32` otherwise). """ function rand( - rng::CounterRNG, + rng::AbstractAKRNG, backend::Backend, ::Type{T}, dims::Integer...; @@ -319,14 +328,20 @@ function rand( end -function rand(rng::CounterRNG, backend::Backend, dims::Integer...; kwargs...) +function rand(rng::AbstractAKRNG, backend::Backend, dims::Integer...; kwargs...) DefaultScalarType = (backend == CPU_BACKEND) ? Float64 : Float32 rand(rng, backend, DefaultScalarType, dims...; kwargs...) end -rand(rng::CounterRNG, args...; kwargs...) = rand(rng, CPU_BACKEND, args...; kwargs...) -rand(backend::Backend, args...; kwargs...) = rand(CounterRNG(), backend, args...; kwargs...) +rand(rng::AbstractAKRNG, args...; kwargs...) = rand(rng, CPU_BACKEND, args...; kwargs...) +function rand(backend::Backend, ::Type{T}, dims::Integer...; kwargs...) where T + @argcheck T <: ALLOWED_RAND_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)" + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return rand!(v, backend; kwargs...) +end +rand(backend::Backend, dims::Integer...; kwargs...) = + rand(backend, (backend == CPU_BACKEND) ? Float64 : Float32, dims...; kwargs...) rand(::Type{T}, dims::Integer...; kwargs...) where {T} = rand(CPU_BACKEND, T, dims...; kwargs...) rand(dims::Integer...; kwargs...) = rand(CPU_BACKEND, dims...; kwargs...) rand(; kwargs...) = throw(ArgumentError("rand requires at least one dimension")) diff --git a/src/rand/rand_cpu.jl b/src/rand/rand_cpu.jl new file mode 100644 index 00000000..075a3b5a --- /dev/null +++ b/src/rand/rand_cpu.jl @@ -0,0 +1,270 @@ +struct Xoshiro256PP <: StreamRNGAlgorithm end + + +# Xoshiro256++ state: four 64-bit words, replaced (not mutated) as the stream advances +struct XoshiroState <: StreamRNGState + s0::UInt64 + s1::UInt64 + s2::UInt64 + s3::UInt64 +end + + +# Jump-ahead table dimensions +const XOSHIRO_STATE_BITS = 256 +const XOSHIRO_JUMP_BITS = 64 + +# Below this many elements per task, spawning and jumping costs more than it saves. Results do not +# depend on the task count, so raising the user's `min_elems` to this floor is purely a speed choice. +const XOSHIRO_MIN_ELEMS_PER_TASK = 8192 + +# Within a task, the number of stream segments advanced in lockstep (tuned separately for uniform +# and normal output), and the shortest range worth splitting into lanes (each extra lane costs a jump) +const XOSHIRO_RAND_LANES = 4 +const XOSHIRO_RANDN_LANES = 2 +const XOSHIRO_MIN_ELEMS_LANES = 256 + + +# Seed the four state words with consecutive SplitMix64 outputs +@inline function stream_init_state(seed::UInt64, ::Xoshiro256PP)::XoshiroState + s0 = _splitmix64_mix(seed + 1 * SPLITMIX64_INCREMENT) + s1 = _splitmix64_mix(seed + 2 * SPLITMIX64_INCREMENT) + s2 = _splitmix64_mix(seed + 3 * SPLITMIX64_INCREMENT) + s3 = _splitmix64_mix(seed + 4 * SPLITMIX64_INCREMENT) + return XoshiroState(s0, s1, s2, s3) +end + + +# One Xoshiro256++ step: return the output of the current state, and the next state +@inline function _xoshiro_next(st::XoshiroState)::Tuple{UInt64, XoshiroState} + s0, s1, s2, s3 = st.s0, st.s1, st.s2, st.s3 + out = bitrotate(s0 + s3, 23) + s0 + + t = s1 << 17 + s2 = xor(s2, s0) + s3 = xor(s3, s1) + s1 = xor(s1, s2) + s0 = xor(s0, s3) + s2 = xor(s2, t) + s3 = bitrotate(s3, 45) + + return out, XoshiroState(s0, s1, s2, s3) +end + + +#= +Convert one raw Xoshiro output to the requested scalar exactly as Base's scalar +`rand(::Xoshiro, T)` does, so a stream fill matches a scalar loop over `Random.Xoshiro`: +- narrower integers and Bool take the leftmost bits +- floats scale the leftmost bits of the matching unsigned width onto a grid in [0, 1) +=# +@inline _xoshiro_scalar_from_uint64(::Type{UInt64}, u::UInt64)::UInt64 = u +@inline _xoshiro_scalar_from_uint64(::Type{Int64}, u::UInt64)::Int64 = u % Int64 +@inline function _xoshiro_scalar_from_uint64( + ::Type{T}, + u::UInt64, +)::T where {T <: Union{Bool, UInt8, UInt16, UInt32, Int8, Int16, Int32}} + return (u >>> (64 - 8 * sizeof(T))) % T +end +@inline function _xoshiro_scalar_from_uint64(::Type{Float16}, u::UInt64)::Float16 + return Float16(Float32(u >>> 53) * Float32(0x1.0p-11)) +end +@inline function _xoshiro_scalar_from_uint64(::Type{Float32}, u::UInt64)::Float32 + return Float32(u >>> 40) * Float32(0x1.0p-24) +end +@inline function _xoshiro_scalar_from_uint64(::Type{Float64}, u::UInt64)::Float64 + return Float64(u >>> 11) * 0x1.0p-53 +end + + +#= +Jump-ahead. One Xoshiro step is linear over GF(2), so stepping `2^k` times is a fixed 256x256 +bit-matrix. `XOSHIRO_JUMP_MAPS[:, k + 1]` stores the columns of that matrix for `2^k` steps, +with column `j` being the image of the state with only bit `j` set. + +Advancing by `n` steps applies the matrix for each set bit of `n`, i.e. at most 64 matrix-vector +products regardless of `n`. +=# +@inline function _xoshiro_basis_state(bit::Int)::XoshiroState + word = UInt64(1) << (bit % 64) + return XoshiroState( + bit < 64 ? word : UInt64(0), + 64 <= bit < 128 ? word : UInt64(0), + 128 <= bit < 192 ? word : UInt64(0), + 192 <= bit ? word : UInt64(0), + ) +end + + +# XOR into `acc` the matrix columns selected by the set bits of one state word +@inline function _xoshiro_accumulate_word( + acc::XoshiroState, + maps::Matrix{XoshiroState}, + k::Int, + w::UInt64, + bit_offset::Int, +)::XoshiroState + s0, s1, s2, s3 = acc.s0, acc.s1, acc.s2, acc.s3 + while w != 0 + col = @inbounds maps[bit_offset + trailing_zeros(w) + 1, k] + s0 = xor(s0, col.s0) + s1 = xor(s1, col.s1) + s2 = xor(s2, col.s2) + s3 = xor(s3, col.s3) + w &= w - UInt64(1) + end + return XoshiroState(s0, s1, s2, s3) +end + + +# Apply the `k`th matrix in `maps` to `st` +@inline function _xoshiro_apply_map( + maps::Matrix{XoshiroState}, + k::Int, + st::XoshiroState, +)::XoshiroState + acc = XoshiroState(UInt64(0), UInt64(0), UInt64(0), UInt64(0)) + acc = _xoshiro_accumulate_word(acc, maps, k, st.s0, 0) + acc = _xoshiro_accumulate_word(acc, maps, k, st.s1, 64) + acc = _xoshiro_accumulate_word(acc, maps, k, st.s2, 128) + acc = _xoshiro_accumulate_word(acc, maps, k, st.s3, 192) + return acc +end + + +function _xoshiro_build_jump_maps()::Matrix{XoshiroState} + maps = Matrix{XoshiroState}(undef, XOSHIRO_STATE_BITS, XOSHIRO_JUMP_BITS) + + # 2^0 steps: image of each basis state under a single step + for bit in 0:(XOSHIRO_STATE_BITS - 1) + _, maps[bit + 1, 1] = _xoshiro_next(_xoshiro_basis_state(bit)) + end + + # 2^k steps: square the 2^(k-1) matrix by applying it to each of its own columns + for k in 2:XOSHIRO_JUMP_BITS, j in 1:XOSHIRO_STATE_BITS + maps[j, k] = _xoshiro_apply_map(maps, k - 1, maps[j, k - 1]) + end + + return maps +end + + +const XOSHIRO_JUMP_MAPS = _xoshiro_build_jump_maps() + + +# Advance `st` by `n` steps in bounded time +@inline function _xoshiro_jump(st::XoshiroState, n::UInt64)::XoshiroState + k = 1 + while n != 0 + if isodd(n) + st = _xoshiro_apply_map(XOSHIRO_JUMP_MAPS, k, st) + end + n >>= 1 + k += 1 + end + return st +end + + +# Fill `v[idx[i]] = f(T, u_i)` for `i` in `irange` sequentially from `st`, where `u_i` is the stream +# output at position `i`; return the state after the last step +@inline function _xoshiro_fill_sequential!( + f, + v::AbstractArray{T}, + idx, + irange::UnitRange{Int}, + st::XoshiroState, +)::XoshiroState where {T} + @inbounds for i in irange + u, st = _xoshiro_next(st) + v[idx[i]] = f(T, u) + end + return st +end + + +#= +Same result as `_xoshiro_fill_sequential!`, but faster: `irange` is split into `K` contiguous +segments of the same stream, each lane jumps to its segment start, and all lanes advance in +lockstep (independent dependency chains, as in Base's bulk Xoshiro fill). Any remainder after the +`K` equal segments continues from the last lane, so the returned state is the same as sequential. + +Kept out of line as a function barrier: inlined into the task closure, the ziggurat kernel ran ~30% +slower. +=# +@noinline function _xoshiro_fill_lanes!( + f, + v::AbstractArray{T}, + idx, + irange::UnitRange{Int}, + st::XoshiroState, + ::Val{K}, +)::XoshiroState where {T, K} + seg_len = length(irange) ÷ K + i0 = first(irange) + + lanes = ntuple(k -> _xoshiro_jump(st, UInt64((k - 1) * seg_len)), Val(K)) + + @inbounds for r in 0:(seg_len - 1) + steps = Base.map(_xoshiro_next, lanes) + lanes = Base.map(last, steps) + for k in 1:K + v[idx[i0 + (k - 1) * seg_len + r]] = f(T, first(steps[k])) + end + end + + return _xoshiro_fill_sequential!(f, v, idx, (i0 + K * seg_len):last(irange), lanes[K]) +end + + +# Fill `v[idx[i]]` for `i` in `irange` from `st`, using `K` lanes when the range is long enough +@inline function _xoshiro_fill_range!( + f, + v::AbstractArray, + idx, + irange::UnitRange{Int}, + st::XoshiroState, + lanes::Val{K}, +)::XoshiroState where {K} + if K > 1 && length(irange) >= XOSHIRO_MIN_ELEMS_LANES + return _xoshiro_fill_lanes!(f, v, idx, irange, st, lanes) + else + return _xoshiro_fill_sequential!(f, v, idx, irange, st) + end +end + + +#= +Parallel Xoshiro256++ stream fill, shared by `rand!` and `randn!`. + +`v[i]` (in linear indexing order) is `f(T, u_i)`, where `u_i` is the `i`th output from `rng.state`; +`f` must consume exactly that one output. Each task jumps directly to the stream position of its +first element, so the result is identical for any number of tasks. The task holding the last +element finishes exactly `length(v)` steps ahead, giving the new state. +=# +function _xoshiro_fill_stream!( + f::F, + rng::StreamRNG{Xoshiro256PP}, + v::AbstractArray, + lanes::Val; + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where {F} + + num_elems = length(v) + iszero(num_elems) && return v + + idx = eachindex(IndexLinear(), v) + start_state = rng.state + end_state = Ref(start_state) + + min_elems = max(min_elems, XOSHIRO_MIN_ELEMS_PER_TASK) + itask_partition(num_elems, max_tasks, min_elems) do _, irange + st = _xoshiro_jump(start_state, UInt64(first(irange) - 1)) + st = _xoshiro_fill_range!(f, v, idx, irange, st, lanes) + last(irange) == num_elems && (end_state[] = st) + end + + rng.state = end_state[] + return v +end diff --git a/src/rand/randn.jl b/src/rand/randn.jl index 65c2612d..4edbacb3 100644 --- a/src/rand/randn.jl +++ b/src/rand/randn.jl @@ -2,6 +2,17 @@ const ALLOWED_RANDN_SCALARS = Union{ Float16, Float32, Float64 } + +#= +Key domains: normal samples draw from their own independent streams, one per precision, by mixing a +constant into the seed. The counter layouts differ (one counter per uniform in `rand!`, one per +Float32 pair, two per Float64 pair), so without this, a mixed sequence of calls sharing one +`CounterRNG` could make two different elements read the same random word. Constants are SHA-512 +initial hash values (nothing up the sleeve). +=# +const RANDN_DOMAIN_F32 = 0x3c6ef372fe94f82b +const RANDN_DOMAIN_F64 = 0xa54ff53a5f1d36f1 + @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, @@ -13,42 +24,37 @@ const ALLOWED_RANDN_SCALARS = Union{ end -# Box-Muller transform from raw random bits: `u_radius` sets the radius, `u_angle` the angle. -# `sqrt_llvm` skips the DomainError branch of `sqrt`; the argument is always non-negative here. -@inline function _box_muller( - ::Type{T}, - u_radius::UIntType, - u_angle::UIntType, -)::Tuple{T, T} where {T <: Union{Float32, Float64}, UIntType <: Union{UInt32, UInt64}} - radius = Base.sqrt_llvm(T(-2) * _fast_log(T, u_radius)) - stheta, ctheta = _fast_sincospi(T, u_angle) - return radius * ctheta, radius * stheta -end - +#= +Box-Muller via PhiloxRNG.jl's `boxmuller(F, u1, u2)`, which uses fast polynomial `log` and +`sincospi` evaluated directly on the raw bits in the output precision (no libm calls and no Float64 +widening): `u1` sets the angle and `u2` the radius. Pairs below take `(u1, u2)` from consecutive +draws, so for `Philox` they are exactly PhiloxRNG's `randn_f32` / `randn_f64` outputs. +=# -# One UInt64 draw per pair: the two 32-bit halves drive the radius and angle respectively +# One UInt64 draw per pair, split into its two 32-bit halves @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, pair_counter::UInt64, ::Type{Float32}, )::Tuple{Float32, Float32} - u = rand_uint(seed, alg, pair_counter, UInt64) - return _box_muller(Float32, _u32_lo(u), _u32_hi(u)) + u = rand_uint(xor(seed, RANDN_DOMAIN_F32), alg, pair_counter, UInt64) + return PhiloxRNG.boxmuller(Float32, _u32_lo(u), _u32_hi(u)) end -# Two UInt64 draws per pair, at counters `2 * pair_counter` (radius) and `2 * pair_counter + 1` (angle) +# Two UInt64 draws per pair, at counters `2 * pair_counter` and `2 * pair_counter + 1` @inline function randn_pair( seed::UInt64, alg::CounterRNGAlgorithm, pair_counter::UInt64, ::Type{Float64}, )::Tuple{Float64, Float64} + domain_seed = xor(seed, RANDN_DOMAIN_F64) c0 = pair_counter << 1 - u_radius = rand_uint(seed, alg, c0, UInt64) - u_angle = rand_uint(seed, alg, c0 + UInt64(1), UInt64) - return _box_muller(Float64, u_radius, u_angle) + u1 = rand_uint(domain_seed, alg, c0, UInt64) + u2 = rand_uint(domain_seed, alg, c0 + UInt64(1), UInt64) + return PhiloxRNG.boxmuller(Float64, u1, u2) end @@ -78,62 +84,41 @@ end end -# `Val{ODD}` keeps offset parity in the type domain so each specialization (`ODD==0` / `ODD==1`) -# can fold index bias and head handling at compile time. -# - `Val{0}` => pair `i` writes at indices `(2i-1, 2i)` so bias is `-1` -# - `Val{1}` => pair `i` writes at indices `(2i-2, 2i-1)` so bias is `-2` -@inline _randn_i0_bias(::Val{0}) = -1 -@inline _randn_i0_bias(::Val{1}) = -2 - +# Outputs per group in `randn!`: one Box-Muller pair by default +@inline _randn_group_size(::CounterRNGAlgorithm, ::Type) = Val(2) +@inline randn_group(seed::UInt64, alg::CounterRNGAlgorithm, group::UInt64, ::Type{T}) where {T} = + randn_pair(seed, alg, group, T) -# Only the first pair at an odd offset has a `z0` that falls before `v[1]` -@inline _randn_head_in_bounds(::Val{0}, i0) = true -@inline _randn_head_in_bounds(::Val{1}, i0) = i0 >= 1 +# Philox: a Float64 pair is exactly one block; same values as the generic method, which reads the +# block's two 64-bit halves through `rand_uint` at counters `2p` and `2p + 1` +@inline function randn_pair( + seed::UInt64, + alg::Philox, + pair_counter::UInt64, + ::Type{Float64}, +)::Tuple{Float64, Float64} + return PhiloxRNG.randn_f64(pair_counter, UInt64(0), xor(seed, RANDN_DOMAIN_F64)) +end -#= -Fill `v` from the Box-Muller pairs overlapping the normal counters -`[initial_offset, initial_offset + length(v))`, with one task/thread per pair. - -When the offset or end is odd, the first or last pair straddles the array bounds; the out-of-bounds -half is computed and discarded, so `v[i]` depends only on its counter `initial_offset + i - 1`. -This keeps head and tail handling inside the single parallel launch (no scalar writes). -=# -@inline function _randn_core!( - v::AbstractArray{T}, seed, alg, initial_offset, - backend, max_tasks, min_elems, prefer_threads, block_size, - ::Val{ODD}, -) where {T, ODD} - - len = length(v) - - # Pairs covering counters `[initial_offset, initial_offset + len)` - pair_start = initial_offset >> 1 - pair_count = (len + ODD + 1) >> 1 - - # Capture `Val(ODD)` into the closure so parity handling stays compile-time inside the loop. - odd_val = Val(ODD) - foreachindex( - Base.OneTo(pair_count), backend; - max_tasks, min_elems, prefer_threads, block_size, - ) do i - pair_counter = pair_start + _counter_from_index(i) - z0, z1 = randn_pair(seed, alg, pair_counter, T) - i0 = (i << 1) + _randn_i0_bias(odd_val) - - if 1 < i < pair_count - # Interior pairs always lie fully inside `v`; unconditional stores can be merged - @inbounds v[i0] = z0 - @inbounds v[i0 + 1] = z1 - else - # Boundary pairs may straddle either end of `v` - _randn_head_in_bounds(odd_val, i0) && (@inbounds v[i0] = z0) - i0 + 1 <= len && (@inbounds v[i0 + 1] = z1) - end - end - - return v +# Philox: one block holds two Float32 pairs, so fill four outputs per block evaluation +@inline _randn_group_size(::Philox, ::Type{T}) where {T <: Union{Float16, Float32}} = Val(4) +@inline function randn_group( + seed::UInt64, + alg::Philox, + group::UInt64, + ::Type{Float32}, +)::NTuple{4, Float32} + return PhiloxRNG.randn_f32(group, UInt64(0), xor(seed, RANDN_DOMAIN_F32)) +end +@inline function randn_group( + seed::UInt64, + alg::Philox, + group::UInt64, + ::Type{Float16}, +)::NTuple{4, Float16} + return Base.map(Float16, randn_group(seed, alg, group, Float32)) end @@ -160,7 +145,10 @@ the raw random bits in the requested precision (`Float16` is computed in `Float3 After filling `v`, `rng.offset` advances by `length(v)`. -It can be called without an `rng`, in which case the default `CounterRNG` will be used. +It can be called without an `rng`: on the CPU backend a fresh auto-seeded `StreamRNG()` is used, +and on other backends this forwards to the array package's own `Random.randn!(v)` (GPUArrays' RNG +for JuliaGPU backends), with the keyword settings unused. Pass a `CounterRNG` for values identical +across backends. """ function randn!( rng::CounterRNG, @@ -183,29 +171,84 @@ function randn!( # Local isbits captures from mutable rng object. seed, alg, initial_offset = rng.seed, rng.alg, rng.offset - core_args = ( - v, seed, alg, initial_offset, backend, max_tasks, min_elems, prefer_threads, block_size + _fill_groups!( + randn_group, seed, alg, v, initial_offset, _randn_group_size(alg, T), + backend, max_tasks, min_elems, prefer_threads, block_size, ) - # Dispatch depending on required initial index bias - if iseven(initial_offset) - _randn_core!(core_args..., Val(0)) - else - _randn_core!(core_args..., Val(1)) - end - rng.offset += UInt64(length(v)) v end -randn!(v::AbstractArray, args...; kwargs...) = randn!(CounterRNG(), v, args...; kwargs...) +""" + randn!( + rng::StreamRNG{Xoshiro256PP}, + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + + # Unused, accepted for a uniform signature + prefer_threads::Bool=true, + block_size::Int=256, + ) where {T <: AbstractFloat} + +CPU backend only. `v[i]` (in linear indexing order) is a standard normal sample computed by the +ziggurat method from the `i`th output of the Xoshiro256++ stream from `rng.state`, and +`rng.state` advances by `length(v)` steps. Each sample consumes exactly one stream output, so the +result is identical for any number of tasks, and consecutive fills match one combined fill. +`Float16` and `Float32` samples are rounded from `Float64`. +""" +function randn!( + rng::StreamRNG{Xoshiro256PP}, + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + + # Unused, accepted for a uniform signature + prefer_threads::Bool=true, + block_size::Int=256, +) where T + @argcheck T <: ALLOWED_RANDN_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)" + @argcheck backend == CPU_BACKEND "StreamRNG with Xoshiro256PP is only supported on CPU backend" + + return _xoshiro_fill_stream!( + _ziggurat_normal_from_uint64, rng, v, Val(XOSHIRO_RANDN_LANES); + max_tasks, min_elems, + ) +end + + +function randn!( + v::AbstractArray{T}, + backend::Backend=get_backend(v); + + # CPU settings + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + prefer_threads::Bool=true, + + # GPU settings + block_size::Int=256, +) where T + @argcheck T <: ALLOWED_RANDN_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)" + return _fill_default!( + randn!, Random.randn!, v, backend; + max_tasks, min_elems, prefer_threads, block_size, + ) +end """ randn( - rng::CounterRNG, + rng::AbstractAKRNG, backend::Backend, ::Type{T}, dims::Integer...; @@ -223,12 +266,13 @@ Allocate an array of element type `T` on `backend` with shape `dims`, fill it in [`randn!`](@ref), and return it. Convenience overloads: -- `rng` omitted: uses a fresh `CounterRNG()`. +- `rng` omitted: allocates, then fills via [`randn!`](@ref) without an RNG (a fresh `StreamRNG()` on + CPU backend, the array package's `Random.randn!` otherwise). - `backend` omitted: defaults to `CPU_BACKEND`. - `T` omitted: defaults by backend (`Float64` on CPU backend, `Float32` otherwise). """ function randn( - rng::CounterRNG, + rng::AbstractAKRNG, backend::Backend, ::Type{T}, dims::Integer...; @@ -249,14 +293,20 @@ function randn( end -function randn(rng::CounterRNG, backend::Backend, dims::Integer...; kwargs...) +function randn(rng::AbstractAKRNG, backend::Backend, dims::Integer...; kwargs...) DefaultScalarType = (backend == CPU_BACKEND) ? Float64 : Float32 randn(rng, backend, DefaultScalarType, dims...; kwargs...) end -randn(rng::CounterRNG, args...; kwargs...) = randn(rng, CPU_BACKEND, args...; kwargs...) -randn(backend::Backend, args...; kwargs...) = randn(CounterRNG(), backend, args...; kwargs...) +randn(rng::AbstractAKRNG, args...; kwargs...) = randn(rng, CPU_BACKEND, args...; kwargs...) +function randn(backend::Backend, ::Type{T}, dims::Integer...; kwargs...) where T + @argcheck T <: ALLOWED_RANDN_SCALARS "Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)" + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return randn!(v, backend; kwargs...) +end +randn(backend::Backend, dims::Integer...; kwargs...) = + randn(backend, (backend == CPU_BACKEND) ? Float64 : Float32, dims...; kwargs...) randn(::Type{T}, dims::Integer...; kwargs...) where {T} = randn(CPU_BACKEND, T, dims...; kwargs...) randn(dims::Integer...; kwargs...) = randn(CPU_BACKEND, dims...; kwargs...) randn(; kwargs...) = throw(ArgumentError("randn requires at least one dimension")) diff --git a/src/rand/splitmix.jl b/src/rand/splitmix.jl index cc474be1..12b3d6ca 100644 --- a/src/rand/splitmix.jl +++ b/src/rand/splitmix.jl @@ -1,4 +1,4 @@ -struct SplitMix64 <: CounterRNGAlgorithm end +# SplitMix64 mixing, used to seed StreamRNG states and for the ziggurat's rejection fallback # SplitMix64 magic numbers const SPLITMIX64_INCREMENT = UInt64(0x9e3779b97f4a7c15) @@ -14,31 +14,3 @@ const SPLITMIX64_MIX_B = UInt64(0x94d049bb133111eb) x = xor(x, x >> 31) return x end - - -# Derive a 32-bit seed word from a 64-bit seed using SplitMix64 mixing. -@inline function splitmix32_from_u64(seed::UInt64)::UInt32 - return _u32_hi(_splitmix64_mix(seed + SPLITMIX64_INCREMENT)) -end - - -# Natural SplitMix64 output path: compute 64 random bits directly from one counter -@inline function rand_uint( - seed::UInt64, - alg::SplitMix64, - counter::UInt64, - ::Type{UInt64}, -)::UInt64 - return _splitmix64_mix(counter + seed + SPLITMIX64_INCREMENT) -end - - -# UInt32 path is derived from the high 32 bits of the UInt64 SplitMix output -@inline function rand_uint( - seed::UInt64, - alg::SplitMix64, - counter::UInt64, - ::Type{UInt32}, -)::UInt32 - return _u32_hi(rand_uint(seed, alg, counter, UInt64)) -end diff --git a/src/rand/threefry.jl b/src/rand/threefry.jl deleted file mode 100644 index f6ef6321..00000000 --- a/src/rand/threefry.jl +++ /dev/null @@ -1,75 +0,0 @@ -struct Threefry <: CounterRNGAlgorithm end - -# Threefry magic numbers -const THREEFRY_PARITY = UInt32(0x1BD11BDA) -const THREEFRY_ROTATIONS = ( - UInt32(13), UInt32(15), UInt32(26), UInt32(6), - UInt32(17), UInt32(29), UInt32(16), UInt32(24), -) -const THREEFRY_ROUNDS = 20 - - -@inline function _threefry_key_word(k0::UInt32, k1::UInt32, k2::UInt32, idx::UInt32)::UInt32 - idx == UInt32(0) && return k0 - idx == UInt32(1) && return k1 - return k2 -end - - -# Evaluate one Threefry block at `counter`, returning two 32-bit lanes `(x0, x1)` -@inline function _threefry2x32_block( - seed::UInt64, - counter::UInt64, -)::Tuple{UInt32, UInt32} - - x0 = _u32_lo(counter) - x1 = _u32_hi(counter) - - k0 = _u32_lo(seed) - k1 = _u32_hi(seed) - k2 = xor(THREEFRY_PARITY, xor(k0, k1)) - - x0 += k0 - x1 += k1 - - @inbounds for round in 0:(THREEFRY_ROUNDS - 1) - round_u32 = UInt32(round) - rot = THREEFRY_ROTATIONS[Int((round_u32 & UInt32(0x7)) + UInt32(1))] - x0 += x1 - x1 = xor(_rotl32(x1, rot), x0) - - if (round_u32 & UInt32(0x3)) == UInt32(0x3) - s = (round_u32 >>> 2) + UInt32(1) - i0 = s % UInt32(3) - i1 = (s + UInt32(1)) % UInt32(3) - x0 += _threefry_key_word(k0, k1, k2, i0) - x1 += _threefry_key_word(k0, k1, k2, i1) + s - end - end - - return x0, x1 -end - - -# Return lane 0 from the single Threefry block at `counter` -@inline function rand_uint( - seed::UInt64, - alg::Threefry, - counter::UInt64, - ::Type{UInt32}, -)::UInt32 - x0, _ = _threefry2x32_block(seed, counter) - return x0 -end - - -# Build UInt64 from the two lanes `(x0, x1)` of the same Threefry block at `counter` -@inline function rand_uint( - seed::UInt64, - alg::Threefry, - counter::UInt64, - ::Type{UInt64}, -)::UInt64 - x0, x1 = _threefry2x32_block(seed, counter) - return _u64_from_u32s(x0, x1) -end diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl index c25c75c3..f62e8180 100644 --- a/src/rand/utilities.jl +++ b/src/rand/utilities.jl @@ -5,23 +5,40 @@ # Construct UInt64 by bit concatenation of two UInt32s @inline _u64_from_u32s(lo::UInt32, hi::UInt32)::UInt64 = (UInt64(hi) << 32) | UInt64(lo) -# Leftmost 32 bits of a*b cast to UInt64s -@inline _mulhi_u32(a::UInt32, b::UInt32)::UInt32 = UInt32((UInt64(a) * UInt64(b)) >> 32) - -# 32-bit rotate left by r positions -@inline _rotl32(x::UInt32, r::UInt32)::UInt32 = bitrotate(x, Int32(r)) - # Get counter used for CounterRNG from element index @inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) -@inline _default_rng_from_backend(backend::Backend) = backend == CPU_BACKEND ? StreamRNG() : CounterRNG() +#= +Fill `v` without an explicit RNG. On the CPU backend this uses a fresh auto-seeded `StreamRNG` with +AK's parallel fill. On other backends it forwards to the array package's own `Random` implementation +(e.g. GPUArrays' Philox RNG for CUDA and Metal arrays), so AK does not duplicate the GPU `Random` +front end; AK's keyword settings do not apply there. Pass an explicit `CounterRNG` for fills that +are identical across backends. +=# +@inline function _fill_default!( + ak_fill!, + random_fill!, + v::AbstractArray, + backend::Backend; + max_tasks::Int, + min_elems::Int, + prefer_threads::Bool, + block_size::Int, +) + if backend == CPU_BACKEND + return ak_fill!(StreamRNG(), v, backend; max_tasks, min_elems, prefer_threads, block_size) + else + random_fill!(v) + return v + end +end # Shared allocation + fill helper for rand/randn convenience constructors. @inline function _allocate_and_fill_rand( fill!, - rng::CounterRNG, + rng::AbstractAKRNG, backend::Backend, ::Type{T}, dims::Integer...; @@ -41,6 +58,64 @@ end +#= +Fill `v` from groups of `G` consecutive outputs (e.g. one Philox block, or one Box-Muller pair), +with one task/thread per group overlapping the counters `[initial_offset, initial_offset + length(v))`. +`group_fn(seed, alg, g, T)` (e.g. `rand_group` or `randn_group`) returns the `G` outputs for counters +`g * G` to `g * G + G - 1`. It is called directly rather than through a captured closure, which ran +~1.5x slower on CPU. + +When the offset or end is not a multiple of `G`, the first or last group straddles the array bounds; +its out-of-bounds outputs are computed and discarded, so `v[i]` depends only on its counter +`initial_offset + i - 1`. This keeps head and tail handling inside the single parallel launch. +=# +@inline function _fill_groups!( + group_fn::F, + seed::UInt64, + alg::CounterRNGAlgorithm, + v::AbstractArray{T}, + initial_offset::UInt64, + ::Val{G}, + backend::Backend, + max_tasks::Int, + min_elems::Int, + prefer_threads::Bool, + block_size::Int, +) where {F, T, G} + + len = length(v) + iszero(len) && return v + + # Position of v[1] within its group, and the groups covering all of v + head = Int(initial_offset % UInt64(G)) + group_start = initial_offset ÷ UInt64(G) + group_count = cld(len + head, G) + + foreachindex( + Base.OneTo(group_count), backend; + max_tasks, min_elems, prefer_threads, block_size, + ) do i + outs = group_fn(seed, alg, group_start + _counter_from_index(i), T) + i0 = (i - 1) * G + 1 - head + + if 1 < i < group_count + # Interior groups always lie fully inside `v`; unconditional stores can be merged + for k in 1:G + @inbounds v[i0 + k - 1] = outs[k] + end + else + # Boundary groups may straddle either end of `v` + for k in 1:G + j = i0 + k - 1 + 1 <= j <= len && (@inbounds v[j] = outs[k]) + end + end + end + + return v +end + + @inline _rand_scalar_uint_type(::Type{UInt8}) = UInt32 @@ -72,37 +147,11 @@ end #= -Every RNG algorithm implements rand_uint(seed, alg, counter, UInt32/UInt64). -This is the fallback for unsupported RNG algorithms. +Internal interface: each counter RNG algorithm implements +`rand_uint(seed::UInt64, alg, counter::UInt64, ::Type{UInt32 / UInt64})`, deterministically mapping +`(seed, alg, counter)` to raw random bits; type conversion is handled separately by `rand_scalar`. +This is the fallback for unsupported algorithms. =# -""" - rand_uint(seed::UInt64, alg::CounterRNGAlgorithm, counter::UInt64, ::Type{UIntType}) -> UIntType - where {UIntType <: Union{UInt32, UInt64}} - -Low-level extension point for counter-based RNG algorithms used by [`CounterRNG`](@ref). - -`rand_uint` must deterministically map `(seed, alg, counter)` to a raw unsigned integer of the -requested width. Custom algorithms should implement methods for both: - -- `rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt32})::UInt32` -- `rand_uint(seed::UInt64, alg::MyAlg, counter::UInt64, ::Type{UInt64})::UInt64` - -These methods are used internally by [`rand!`](@ref), [`rand`](@ref), [`randn!`](@ref), and -[`randn`](@ref) to generate integers, floats, and normal samples. - -# Requirements -- The mapping must be deterministic for fixed `seed`, `alg`, and `counter`. -- Implement both `UInt32` and `UInt64` widths. -- The method should return raw random bits; higher-level type conversion is handled by AK separately. - -# Notes -- `counter` is the logical stream position (typically the array index). -- For block-based algorithms such as Philox or Threefry, the `UInt32` and `UInt64` methods may - share an internal block computation. -- The fallback method throws an `ArgumentError` for algorithms that do not implement `rand_uint`. - -See also: [`CounterRNGAlgorithm`](@ref), [`CounterRNG`](@ref). -""" @inline function rand_uint( ::UInt64, alg::CounterRNGAlgorithm, diff --git a/src/rand/ziggurat.jl b/src/rand/ziggurat.jl new file mode 100644 index 00000000..6b2b482e --- /dev/null +++ b/src/rand/ziggurat.jl @@ -0,0 +1,334 @@ +# Ziggurat method for standard normal variates (Marsaglia and Tsang, https://www.jstatsoft.org/v05/i08/). +# Algorithm and tables taken from julia's Random stdlib (normal.jl), copied rather than referenced +# because they are internal to Random. +# License is MIT: https://julialang.org/license +# +# Unlike Base, each normal sample consumes exactly one stream output `u`, so element `i` of an array +# always maps to stream position `i`, which is what allows deterministic parallel filling. In the +# rare (~0.7%) rejection case, Base draws further values from the stream; here the extra randomness +# comes from a local SplitMix64 sequence seeded by `u` instead, leaving the stream untouched. + + +# Rightmost x of the base strip, and its inverse +const ZIGGURAT_R = 3.6541528853610087963519472518 +const ZIGGURAT_INV_R = inv(ZIGGURAT_R) + + +# Next output of the local SplitMix64 sequence with state `s` +@inline function _ziggurat_local_next(s::UInt64)::Tuple{UInt64, UInt64} + s += SPLITMIX64_INCREMENT + return _splitmix64_mix(s), s +end + + +# Next uniform Float64 in [0, 1) from the local sequence, as Base's `rand(rng)` +@inline function _ziggurat_local_u01(s::UInt64)::Tuple{Float64, UInt64} + w, s = _ziggurat_local_next(s) + return Float64(w >>> 11) * 0x1.0p-53, s +end + + +# Standard normal from one raw 64-bit stream output +@inline function _ziggurat_normal(u::UInt64)::Float64 + # 52 random bits: rightmost bit is the sign, next 8 bits pick the strip, the rest the position + r = u >>> 12 + rabs = Int64(r >> 1) + idx = rabs & 0xff + x = ifelse(r % Bool, -rabs, rabs) * @inbounds(ZIGGURAT_WI[idx + 1]) + + # Inside the strip's rectangle: accepted ~99.3% of the time + rabs < @inbounds(ZIGGURAT_KI[idx + 1]) && return x + + return _ziggurat_normal_unlikely(u) +end + + +# Rejection path for `_ziggurat_normal`, drawing any extra randomness from the local sequence +@noinline function _ziggurat_normal_unlikely(u::UInt64)::Float64 + s = u + r = u >>> 12 + + while true + rabs = Int64(r >> 1) + idx = rabs & 0xff + x = ifelse(r % Bool, -rabs, rabs) * @inbounds(ZIGGURAT_WI[idx + 1]) + rabs < @inbounds(ZIGGURAT_KI[idx + 1]) && return x + + if idx == 0 + # Base strip: sample the tail beyond ZIGGURAT_R + while true + a, s = _ziggurat_local_u01(s) + b, s = _ziggurat_local_u01(s) + xx = -ZIGGURAT_INV_R * log1p(-a) + yy = -log1p(-b) + if yy + yy > xx * xx + return (rabs >> 8) % Bool ? -ZIGGURAT_R - xx : ZIGGURAT_R + xx + end + end + else + # Wedge between the strip's rectangle and the density curve + c, s = _ziggurat_local_u01(s) + f0 = @inbounds ZIGGURAT_FI[idx] + f1 = @inbounds ZIGGURAT_FI[idx + 1] + (f0 - f1) * c + f1 < exp(-0.5 * x * x) && return x + end + + # Rejected: restart with 52 fresh bits from the local sequence + w, s = _ziggurat_local_next(s) + r = w >>> 12 + end +end + + +# Normal sample of type `T` from one raw stream output; narrower types are rounded from Float64 +@inline function _ziggurat_normal_from_uint64( + ::Type{T}, + u::UInt64, +)::T where {T <: Union{Float16, Float32, Float64}} + return T(_ziggurat_normal(u)) +end + + + + +### Tables for normal variates, from julia's Random stdlib ### + +const ZIGGURAT_KI = + UInt64[0x0007799ec012f7b2,0x0000000000000000,0x0006045f4c7de363,0x0006d1aa7d5ec0a5, + 0x000728fb3f60f777,0x0007592af4e9fbc0,0x000777a5c0bf655d,0x00078ca3857d2256, + 0x00079bf6b0ffe58b,0x0007a7a34ab092ad,0x0007b0d2f20dd1cb,0x0007b83d3aa9cb52, + 0x0007be597614224d,0x0007c3788631abe9,0x0007c7d32bc192ee,0x0007cb9263a6e86d, + 0x0007ced483edfa84,0x0007d1b07ac0fd39,0x0007d437ef2da5fc,0x0007d678b069aa6e, + 0x0007d87db38c5c87,0x0007da4fc6a9ba62,0x0007dbf611b37f3b,0x0007dd7674d0f286, + 0x0007ded5ce8205f6,0x0007e018307fb62b,0x0007e141081bd124,0x0007e2533d712de8, + 0x0007e3514bbd7718,0x0007e43d54944b52,0x0007e5192f25ef42,0x0007e5e67481118d, + 0x0007e6a6897c1ce2,0x0007e75aa6c7f64c,0x0007e803df8ee498,0x0007e8a326eb6272, + 0x0007e93954717a28,0x0007e9c727f8648f,0x0007ea4d4cc85a3c,0x0007eacc5c4907a9, + 0x0007eb44e0474cf6,0x0007ebb754e47419,0x0007ec242a3d8474,0x0007ec8bc5d69645, + 0x0007ecee83d3d6e9,0x0007ed4cb8082f45,0x0007eda6aee0170f,0x0007edfcae2dfe68, + 0x0007ee4ef5dccd3e,0x0007ee9dc08c394e,0x0007eee9441a17c7,0x0007ef31b21b4fb1, + 0x0007ef773846a8a7,0x0007efba00d35a17,0x0007effa32ccf69f,0x0007f037f25e1278, + 0x0007f0736112d12c,0x0007f0ac9e145c25,0x0007f0e3c65e1fcc,0x0007f118f4ed8e54, + 0x0007f14c42ed0dc8,0x0007f17dc7daa0c3,0x0007f1ad99aac6a5,0x0007f1dbcce80015, + 0x0007f20874cf56bf,0x0007f233a36a3b9a,0x0007f25d69a604ad,0x0007f285d7694a92, + 0x0007f2acfba75e3b,0x0007f2d2e4720909,0x0007f2f79f09c344,0x0007f31b37ec883b, + 0x0007f33dbae36abc,0x0007f35f330f08d5,0x0007f37faaf2fa79,0x0007f39f2c805380, + 0x0007f3bdc11f4f1c,0x0007f3db71b83850,0x0007f3f846bba121,0x0007f4144829f846, + 0x0007f42f7d9a8b9d,0x0007f449ee420432,0x0007f463a0f8675e,0x0007f47c9c3ea77b, + 0x0007f494e643cd8e,0x0007f4ac84e9c475,0x0007f4c37dc9cd50,0x0007f4d9d638a432, + 0x0007f4ef934a5b6a,0x0007f504b9d5f33d,0x0007f5194e78b352,0x0007f52d55994a96, + 0x0007f540d36aba0c,0x0007f553cbef0e77,0x0007f56642f9ec8f,0x0007f5783c32f31e, + 0x0007f589bb17f609,0x0007f59ac2ff1525,0x0007f5ab5718b15a,0x0007f5bb7a71427c, + 0x0007f5cb2ff31009,0x0007f5da7a67cebe,0x0007f5e95c7a24e7,0x0007f5f7d8b7171e, + 0x0007f605f18f5ef4,0x0007f613a958ad0a,0x0007f621024ed7e9,0x0007f62dfe94f8cb, + 0x0007f63aa036777a,0x0007f646e928065a,0x0007f652db488f88,0x0007f65e786213ff, + 0x0007f669c22a7d8a,0x0007f674ba446459,0x0007f67f623fc8db,0x0007f689bb9ac294, + 0x0007f693c7c22481,0x0007f69d881217a6,0x0007f6a6fdd6ac36,0x0007f6b02a4c61ee, + 0x0007f6b90ea0a7f4,0x0007f6c1abf254c0,0x0007f6ca03521664,0x0007f6d215c2db82, + 0x0007f6d9e43a3559,0x0007f6e16fa0b329,0x0007f6e8b8d23729,0x0007f6efc09e4569, + 0x0007f6f687c84cbf,0x0007f6fd0f07ea09,0x0007f703570925e2,0x0007f709606cad03, + 0x0007f70f2bc8036f,0x0007f714b9a5b292,0x0007f71a0a85725d,0x0007f71f1edc4d9e, + 0x0007f723f714c179,0x0007f728938ed843,0x0007f72cf4a03fa0,0x0007f7311a945a16, + 0x0007f73505ac4bf8,0x0007f738b61f03bd,0x0007f73c2c193dc0,0x0007f73f67bd835c, + 0x0007f74269242559,0x0007f745305b31a1,0x0007f747bd666428,0x0007f74a103f12ed, + 0x0007f74c28d414f5,0x0007f74e0709a42d,0x0007f74faab939f9,0x0007f75113b16657, + 0x0007f75241b5a155,0x0007f753347e16b8,0x0007f753ebb76b7c,0x0007f75467027d05, + 0x0007f754a5f4199d,0x0007f754a814b207,0x0007f7546ce003ae,0x0007f753f3c4bb29, + 0x0007f7533c240e92,0x0007f75245514f41,0x0007f7510e91726c,0x0007f74f971a9012, + 0x0007f74dde135797,0x0007f74be2927971,0x0007f749a39e051c,0x0007f747202aba8a, + 0x0007f744571b4e3c,0x0007f741473f9efe,0x0007f73def53dc43,0x0007f73a4dff9bff, + 0x0007f73661d4deaf,0x0007f732294f003f,0x0007f72da2d19444,0x0007f728cca72bda, + 0x0007f723a5000367,0x0007f71e29f09627,0x0007f7185970156b,0x0007f7123156c102, + 0x0007f70baf5c1e2c,0x0007f704d1150a23,0x0007f6fd93f1a4e5,0x0007f6f5f53b10b6, + 0x0007f6edf211023e,0x0007f6e587671ce9,0x0007f6dcb2021679,0x0007f6d36e749c64, + 0x0007f6c9b91bf4c6,0x0007f6bf8e1c541b,0x0007f6b4e95ce015,0x0007f6a9c68356ff, + 0x0007f69e20ef5211,0x0007f691f3b517eb,0x0007f6853997f321,0x0007f677ed03ff19, + 0x0007f66a08075bdc,0x0007f65b844ab75a,0x0007f64c5b091860,0x0007f63c8506d4bc, + 0x0007f62bfa8798fe,0x0007f61ab34364b0,0x0007f608a65a599a,0x0007f5f5ca4737e8, + 0x0007f5e214d05b48,0x0007f5cd7af7066e,0x0007f5b7f0e4c2a1,0x0007f5a169d68fcf, + 0x0007f589d80596a5,0x0007f5712c8d0174,0x0007f557574c912b,0x0007f53c46c77193, + 0x0007f51fe7feb9f2,0x0007f5022646ecfb,0x0007f4e2eb17ab1d,0x0007f4c21dd4a3d1, + 0x0007f49fa38ea394,0x0007f47b5ebb62eb,0x0007f4552ee27473,0x0007f42cf03d58f5, + 0x0007f4027b48549f,0x0007f3d5a44119df,0x0007f3a63a8fb552,0x0007f37408155100, + 0x0007f33ed05b55ec,0x0007f3064f9c183e,0x0007f2ca399c7ba1,0x0007f28a384bb940, + 0x0007f245ea1b7a2b,0x0007f1fcdffe8f1b,0x0007f1ae9af758cd,0x0007f15a8917f27e, + 0x0007f10001ccaaab,0x0007f09e413c418a,0x0007f034627733d7,0x0007efc15815b8d5, + 0x0007ef43e2bf7f55,0x0007eeba84e31dfe,0x0007ee237294df89,0x0007ed7c7c170141, + 0x0007ecc2f0d95d3a,0x0007ebf377a46782,0x0007eb09d6deb285,0x0007ea00a4f17808, + 0x0007e8d0d3da63d6,0x0007e771023b0fcf,0x0007e5d46c2f08d8,0x0007e3e937669691, + 0x0007e195978f1176,0x0007deb2c0e05c1c,0x0007db0362002a19,0x0007d6202c151439, + 0x0007cf4b8f00a2cb,0x0007c4fd24520efd,0x0007b362fbf81816,0x00078d2d25998e24] +const ZIGGURAT_WI = + [1.7367254121602630e-15,9.5586603514556339e-17,1.2708704834810623e-16, + 1.4909740962495474e-16,1.6658733631586268e-16,1.8136120810119029e-16, + 1.9429720153135588e-16,2.0589500628482093e-16,2.1646860576895422e-16, + 2.2622940392218116e-16,2.3532718914045892e-16,2.4387234557428771e-16, + 2.5194879829274225e-16,2.5962199772528103e-16,2.6694407473648285e-16, + 2.7395729685142446e-16,2.8069646002484804e-16,2.8719058904113930e-16, + 2.9346417484728883e-16,2.9953809336782113e-16,3.0543030007192440e-16, + 3.1115636338921572e-16,3.1672988018581815e-16,3.2216280350549905e-16, + 3.2746570407939751e-16,3.3264798116841710e-16,3.3771803417353232e-16, + 3.4268340353119356e-16,3.4755088731729758e-16,3.5232663846002031e-16, + 3.5701624633953494e-16,3.6162480571598339e-16,3.6615697529653540e-16, + 3.7061702777236077e-16,3.7500889278747798e-16,3.7933619401549554e-16, + 3.8360228129677279e-16,3.8781025861250247e-16,3.9196300853257678e-16, + 3.9606321366256378e-16,4.0011337552546690e-16,4.0411583124143332e-16, + 4.0807276830960448e-16,4.1198623774807442e-16,4.1585816580828064e-16, + 4.1969036444740733e-16,4.2348454071520708e-16,4.2724230518899761e-16, + 4.3096517957162941e-16,4.3465460355128760e-16,4.3831194100854571e-16, + 4.4193848564470665e-16,4.4553546609579137e-16,4.4910405058828750e-16, + 4.5264535118571397e-16,4.5616042766900381e-16,4.5965029108849407e-16, + 4.6311590702081647e-16,4.6655819856008752e-16,4.6997804906941950e-16, + 4.7337630471583237e-16,4.7675377680908526e-16,4.8011124396270155e-16, + 4.8344945409350080e-16,4.8676912627422087e-16,4.9007095245229938e-16, + 4.9335559904654139e-16,4.9662370843221783e-16,4.9987590032409088e-16, + 5.0311277306593187e-16,5.0633490483427195e-16,5.0954285476338923e-16, + 5.1273716399787966e-16,5.1591835667857364e-16,5.1908694086703434e-16, + 5.2224340941340417e-16,5.2538824077194543e-16,5.2852189976823820e-16, + 5.3164483832166176e-16,5.3475749612647295e-16,5.3786030129452348e-16, + 5.4095367096239933e-16,5.4403801186554671e-16,5.4711372088173611e-16, + 5.5018118554603362e-16,5.5324078453927836e-16,5.5629288815190902e-16, + 5.5933785872484621e-16,5.6237605106900435e-16,5.6540781286489604e-16, + 5.6843348504368141e-16,5.7145340215092040e-16,5.7446789269419609e-16, + 5.7747727947569648e-16,5.8048187991076857e-16,5.8348200633338921e-16, + 5.8647796628943653e-16,5.8947006281858718e-16,5.9245859472561339e-16, + 5.9544385684180598e-16,5.9842614027720281e-16,6.0140573266426640e-16, + 6.0438291839361250e-16,6.0735797884236057e-16,6.1033119259564394e-16, + 6.1330283566179110e-16,6.1627318168165963e-16,6.1924250213258470e-16, + 6.2221106652737879e-16,6.2517914260879998e-16,6.2814699653988953e-16, + 6.3111489309056042e-16,6.3408309582080600e-16,6.3705186726088149e-16, + 6.4002146908880247e-16,6.4299216230548961e-16,6.4596420740788321e-16, + 6.4893786456033965e-16,6.5191339376461587e-16,6.5489105502874154e-16, + 6.5787110853507413e-16,6.6085381480782587e-16,6.6383943488035057e-16, + 6.6682823046247459e-16,6.6982046410815579e-16,6.7281639938375311e-16, + 6.7581630103719006e-16,6.7882043516829803e-16,6.8182906940062540e-16, + 6.8484247305500383e-16,6.8786091732516637e-16,6.9088467545571690e-16, + 6.9391402292275690e-16,6.9694923761748294e-16,6.9999060003307640e-16, + 7.0303839345521508e-16,7.0609290415654822e-16,7.0915442159548734e-16, + 7.1222323861967788e-16,7.1529965167453030e-16,7.1838396101720629e-16, + 7.2147647093647067e-16,7.2457748997883870e-16,7.2768733118146927e-16, + 7.3080631231227429e-16,7.3393475611774048e-16,7.3707299057898310e-16, + 7.4022134917657997e-16,7.4338017116476479e-16,7.4654980185558890e-16, + 7.4973059291369793e-16,7.5292290266240584e-16,7.5612709640179217e-16, + 7.5934354673958895e-16,7.6257263393567558e-16,7.6581474626104873e-16, + 7.6907028037219191e-16,7.7233964170182985e-16,7.7562324486711744e-16, + 7.7892151409638524e-16,7.8223488367564108e-16,7.8556379841610841e-16, + 7.8890871414417552e-16,7.9227009821522709e-16,7.9564843005293662e-16, + 7.9904420171571300e-16,8.0245791849212591e-16,8.0589009952726568e-16, + 8.0934127848215009e-16,8.1281200422845008e-16,8.1630284158098775e-16, + 8.1981437207065329e-16,8.2334719476060504e-16,8.2690192710884700e-16, + 8.3047920588053737e-16,8.3407968811366288e-16,8.3770405214202216e-16, + 8.4135299867980282e-16,8.4502725197240968e-16,8.4872756101861549e-16, + 8.5245470086955962e-16,8.5620947401062333e-16,8.5999271183276646e-16, + 8.6380527620052589e-16,8.6764806112455816e-16,8.7152199454736980e-16, + 8.7542804025171749e-16,8.7936719990210427e-16,8.8334051523084080e-16, + 8.8734907038131345e-16,8.9139399442240861e-16,8.9547646404950677e-16, + 8.9959770648910994e-16,9.0375900262601175e-16,9.0796169037400680e-16, + 9.1220716831348461e-16,9.1649689962191353e-16,9.2083241632623076e-16, + 9.2521532390956933e-16,9.2964730630864167e-16,9.3413013134252651e-16, + 9.3866565661866598e-16,9.4325583596767065e-16,9.4790272646517382e-16, + 9.5260849610662787e-16,9.5737543220974496e-16,9.6220595062948384e-16, + 9.6710260588230542e-16,9.7206810229016259e-16,9.7710530627072088e-16, + 9.8221725991905411e-16,9.8740719604806711e-16,9.9267855488079765e-16, + 9.9803500261836449e-16,1.0034804521436181e-15,1.0090190861637457e-15, + 1.0146553831467086e-15,1.0203941464683124e-15,1.0262405372613567e-15, + 1.0322001115486456e-15,1.0382788623515399e-15,1.0444832676000471e-15, + 1.0508203448355195e-15,1.0572977139009890e-15,1.0639236690676801e-15, + 1.0707072623632994e-15,1.0776584002668106e-15,1.0847879564403425e-15, + 1.0921079038149563e-15,1.0996314701785628e-15,1.1073733224935752e-15, + 1.1153497865853155e-15,1.1235791107110833e-15,1.1320817840164846e-15, + 1.1408809242582780e-15,1.1500027537839792e-15,1.1594771891449189e-15, + 1.1693385786910960e-15,1.1796266352955801e-15,1.1903876299282890e-15, + 1.2016759392543819e-15,1.2135560818666897e-15,1.2261054417450561e-15, + 1.2394179789163251e-15,1.2536093926602567e-15,1.2688244814255010e-15, + 1.2852479319096109e-15,1.3031206634689985e-15,1.3227655770195326e-15, + 1.3446300925011171e-15,1.3693606835128518e-15,1.3979436672775240e-15, + 1.4319989869661328e-15,1.4744848603597596e-15,1.5317872741611144e-15, + 1.6227698675312968e-15] +const ZIGGURAT_FI = + [1.0000000000000000e+00,9.7710170126767082e-01,9.5987909180010600e-01, + 9.4519895344229909e-01,9.3206007595922991e-01,9.1999150503934646e-01, + 9.0872644005213032e-01,8.9809592189834297e-01,8.8798466075583282e-01, + 8.7830965580891684e-01,8.6900868803685649e-01,8.6003362119633109e-01, + 8.5134625845867751e-01,8.4291565311220373e-01,8.3471629298688299e-01, + 8.2672683394622093e-01,8.1892919160370192e-01,8.1130787431265572e-01, + 8.0384948317096383e-01,7.9654233042295841e-01,7.8937614356602404e-01, + 7.8234183265480195e-01,7.7543130498118662e-01,7.6863731579848571e-01, + 7.6195334683679483e-01,7.5537350650709567e-01,7.4889244721915638e-01, + 7.4250529634015061e-01,7.3620759812686210e-01,7.2999526456147568e-01, + 7.2386453346862967e-01,7.1781193263072152e-01,7.1183424887824798e-01, + 7.0592850133275376e-01,7.0009191813651117e-01,6.9432191612611627e-01, + 6.8861608300467136e-01,6.8297216164499430e-01,6.7738803621877308e-01, + 6.7186171989708166e-01,6.6639134390874977e-01,6.6097514777666277e-01, + 6.5561147057969693e-01,6.5029874311081637e-01,6.4503548082082196e-01, + 6.3982027745305614e-01,6.3465179928762327e-01,6.2952877992483625e-01, + 6.2445001554702606e-01,6.1941436060583399e-01,6.1442072388891344e-01, + 6.0946806492577310e-01,6.0455539069746733e-01,5.9968175261912482e-01, + 5.9484624376798689e-01,5.9004799633282545e-01,5.8528617926337090e-01, + 5.8055999610079034e-01,5.7586868297235316e-01,5.7121150673525267e-01, + 5.6658776325616389e-01,5.6199677581452390e-01,5.5743789361876550e-01, + 5.5291049042583185e-01,5.4841396325526537e-01,5.4394773119002582e-01, + 5.3951123425695158e-01,5.3510393238045717e-01,5.3072530440366150e-01, + 5.2637484717168403e-01,5.2205207467232140e-01,5.1775651722975591e-01, + 5.1348772074732651e-01,5.0924524599574761e-01,5.0502866794346790e-01, + 5.0083757512614835e-01,4.9667156905248933e-01,4.9253026364386815e-01, + 4.8841328470545758e-01,4.8432026942668288e-01,4.8025086590904642e-01, + 4.7620473271950547e-01,4.7218153846772976e-01,4.6818096140569321e-01, + 4.6420268904817391e-01,4.6024641781284248e-01,4.5631185267871610e-01, + 4.5239870686184824e-01,4.4850670150720273e-01,4.4463556539573912e-01, + 4.4078503466580377e-01,4.3695485254798533e-01,4.3314476911265209e-01, + 4.2935454102944126e-01,4.2558393133802180e-01,4.2183270922949573e-01, + 4.1810064983784795e-01,4.1438753404089090e-01,4.1069314827018799e-01, + 4.0701728432947315e-01,4.0335973922111429e-01,3.9972031498019700e-01, + 3.9609881851583223e-01,3.9249506145931540e-01,3.8890886001878855e-01, + 3.8534003484007706e-01,3.8178841087339344e-01,3.7825381724561896e-01, + 3.7473608713789086e-01,3.7123505766823922e-01,3.6775056977903225e-01, + 3.6428246812900372e-01,3.6083060098964775e-01,3.5739482014578022e-01, + 3.5397498080007656e-01,3.5057094148140588e-01,3.4718256395679348e-01, + 3.4380971314685055e-01,3.4045225704452164e-01,3.3711006663700588e-01, + 3.3378301583071823e-01,3.3047098137916342e-01,3.2717384281360129e-01, + 3.2389148237639104e-01,3.2062378495690530e-01,3.1737063802991350e-01, + 3.1413193159633707e-01,3.1090755812628634e-01,3.0769741250429189e-01, + 3.0450139197664983e-01,3.0131939610080288e-01,2.9815132669668531e-01, + 2.9499708779996164e-01,2.9185658561709499e-01,2.8872972848218270e-01, + 2.8561642681550159e-01,2.8251659308370741e-01,2.7943014176163772e-01, + 2.7635698929566810e-01,2.7329705406857691e-01,2.7025025636587519e-01, + 2.6721651834356114e-01,2.6419576399726080e-01,2.6118791913272082e-01, + 2.5819291133761890e-01,2.5521066995466168e-01,2.5224112605594190e-01, + 2.4928421241852824e-01,2.4633986350126363e-01,2.4340801542275012e-01, + 2.4048860594050039e-01,2.3758157443123795e-01,2.3468686187232990e-01, + 2.3180441082433859e-01,2.2893416541468023e-01,2.2607607132238020e-01, + 2.2323007576391746e-01,2.2039612748015194e-01,2.1757417672433113e-01, + 2.1476417525117358e-01,2.1196607630703015e-01,2.0917983462112499e-01, + 2.0640540639788071e-01,2.0364274931033485e-01,2.0089182249465656e-01, + 1.9815258654577511e-01,1.9542500351413428e-01,1.9270903690358912e-01, + 1.9000465167046496e-01,1.8731181422380025e-01,1.8463049242679927e-01, + 1.8196065559952254e-01,1.7930227452284767e-01,1.7665532144373500e-01, + 1.7401977008183875e-01,1.7139559563750595e-01,1.6878277480121151e-01, + 1.6618128576448205e-01,1.6359110823236570e-01,1.6101222343751107e-01, + 1.5844461415592431e-01,1.5588826472447920e-01,1.5334316106026283e-01, + 1.5080929068184568e-01,1.4828664273257453e-01,1.4577520800599403e-01, + 1.4327497897351341e-01,1.4078594981444470e-01,1.3830811644855071e-01, + 1.3584147657125373e-01,1.3338602969166913e-01,1.3094177717364430e-01, + 1.2850872227999952e-01,1.2608687022018586e-01,1.2367622820159654e-01, + 1.2127680548479021e-01,1.1888861344290998e-01,1.1651166562561080e-01, + 1.1414597782783835e-01,1.1179156816383801e-01,1.0944845714681163e-01, + 1.0711666777468364e-01,1.0479622562248690e-01,1.0248715894193508e-01, + 1.0018949876880981e-01,9.7903279038862284e-02,9.5628536713008819e-02, + 9.3365311912690860e-02,9.1113648066373634e-02,8.8873592068275789e-02, + 8.6645194450557961e-02,8.4428509570353374e-02,8.2223595813202863e-02, + 8.0030515814663056e-02,7.7849336702096039e-02,7.5680130358927067e-02, + 7.3522973713981268e-02,7.1377949058890375e-02,6.9245144397006769e-02, + 6.7124653827788497e-02,6.5016577971242842e-02,6.2921024437758113e-02, + 6.0838108349539864e-02,5.8767952920933758e-02,5.6710690106202902e-02, + 5.4666461324888914e-02,5.2635418276792176e-02,5.0617723860947761e-02, + 4.8613553215868521e-02,4.6623094901930368e-02,4.4646552251294443e-02, + 4.2684144916474431e-02,4.0736110655940933e-02,3.8802707404526113e-02, + 3.6884215688567284e-02,3.4980941461716084e-02,3.3093219458578522e-02, + 3.1221417191920245e-02,2.9365939758133314e-02,2.7527235669603082e-02, + 2.5705804008548896e-02,2.3902203305795882e-02,2.2117062707308864e-02, + 2.0351096230044517e-02,1.8605121275724643e-02,1.6880083152543166e-02, + 1.5177088307935325e-02,1.3497450601739880e-02,1.1842757857907888e-02, + 1.0214971439701471e-02,8.6165827693987316e-03,7.0508754713732268e-03, + 5.5224032992509968e-03,4.0379725933630305e-03,2.6090727461021627e-03, + 1.2602859304985975e-03] diff --git a/test/rand.jl b/test/rand.jl index a6b62c64..fa5768c8 100644 --- a/test/rand.jl +++ b/test/rand.jl @@ -1,4 +1,4 @@ -const RAND_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) +const RAND_ALGS = (AK.Philox(),) const RAND_SCALAR_TYPES_ALL = ( UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, @@ -15,6 +15,10 @@ const RUN_FLOAT64_RAND_TESTS = IS_CPU_BACKEND _is_unit_interval(v) = all(x -> !isnan(x) && zero(x) <= x < one(x), v) +# AK's default RNG on the CPU backend, with an explicit seed (other backends forward to `Random`) +_default_rng(seed) = AK.StreamRNG(seed) + + function _rand_fill_reference!( rng, x::AbstractArray{T}; @@ -39,9 +43,7 @@ end @testset "rand" begin @testset "constructors" begin - @test AK.CounterRNG(0x1; alg=AK.SplitMix64()) isa AK.CounterRNG{AK.SplitMix64} @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} - @test AK.CounterRNG(UInt16(123); alg=AK.Threefry()) isa AK.CounterRNG{AK.Threefry} @test AK.CounterRNG(UInt32(300)).seed == UInt64(300) @test AK.CounterRNG(UInt32(300)).offset == UInt64(0) @test AK.CounterRNG(0x1; offset=17).offset == UInt64(17) @@ -134,8 +136,6 @@ end @test AK._u32_hi(word) == hi @test AK._u32_lo(word) == lo @test AK._u64_from_u32s(lo, hi) == word - @test AK._mulhi_u32(0xffffffff % UInt32, 0xffffffff % UInt32) == 0xfffffffe % UInt32 - @test AK._rotl32(0b10000000000000000000000000000001 % UInt32, UInt32(1)) == 0b11 % UInt32 @test AK._counter_from_index(1) == UInt64(0) @test AK._counter_from_index(17) == UInt64(16) @@ -197,19 +197,18 @@ end end end - rng_splitmix = AK.CounterRNG(0x31415926; alg=AK.SplitMix64()) - for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - @test AK.rand_uint(rng_splitmix.seed, rng_splitmix.alg, c, UInt32) == AK._u32_hi( - AK.rand_uint(rng_splitmix.seed, rng_splitmix.alg, c, UInt64) - ) - end - - for alg in (AK.Philox(), AK.Threefry()) - rng = AK.CounterRNG(0xabcdef1234567890; alg) - for c in (UInt64(0), UInt64(1), UInt64(17), UInt64(1023)) - @test AK._u32_lo(AK.rand_uint(rng.seed, rng.alg, c, UInt64)) == - AK.rand_uint(rng.seed, rng.alg, c, UInt32) - end + # Philox blocks come from PhiloxRNG.jl, which tests them against Random123's known-answer + # vectors. Check AK's layout on top: block `b` is `philox4x32_10(b, 0, seed)`; 64-bit counter + # `c` is half `c % 2` of block `c ÷ 2`; 32-bit counter `c` is lane `c % 4` of block `c ÷ 4` + # in the 32-bit key domain + seed = 0xabcdef1234567890 + for c in (UInt64(0), UInt64(1), UInt64(6), UInt64(1023)) + x = AK.PhiloxRNG.philox4x32_10(c >> 1, UInt64(0), seed) + half = iseven(c) ? AK._u64_from_u32s(x[1], x[2]) : AK._u64_from_u32s(x[3], x[4]) + @test AK.rand_uint(seed, AK.Philox(), c, UInt64) == half + + y = AK.PhiloxRNG.philox4x32_10(c >> 2, UInt64(0), xor(seed, AK.PHILOX4X32_DOMAIN_U32)) + @test AK.rand_uint(seed, AK.Philox(), c, UInt32) == y[(c & 3) + 1] end end @@ -340,23 +339,67 @@ end end + @testset "StreamRNG" begin + if IS_CPU_BACKEND + # Long enough for 3 tasks at the minimum elements per task, forcing the jump-ahead path + n = 3 * AK.XOSHIRO_MIN_ELEMS_PER_TASK + 1 + + # Matches a sequential scalar loop over Base's Xoshiro from the same state, for every type. + # The next draw checks the advanced state. + for T in RAND_SCALAR_TYPES_ALL + rng = AK.StreamRNG(0x1234) + st = rng.state + xoshiro = Random.Xoshiro(st.s0, st.s1, st.s2, st.s3) + + x = AK.rand!(rng, zeros(T, n); max_tasks=3) + @test x == [rand(xoshiro, T) for _ in 1:n] + @test AK.rand!(rng, zeros(UInt64, 1))[1] == rand(xoshiro, UInt64) + end + + # Identical values and final state regardless of the number of tasks + rng1 = AK.StreamRNG(0x99) + rngn = AK.StreamRNG(0x99) + x1 = AK.rand!(rng1, zeros(n); max_tasks=1) + xn = AK.rand!(rngn, zeros(n); max_tasks=3) + @test x1 == xn + @test rng1.state == rngn.state + + # Two consecutive fills match one fill of the combined length + rng_split = AK.StreamRNG(0x5) + ab = vcat(AK.rand!(rng_split, zeros(5)), AK.rand!(rng_split, zeros(5))) + @test ab == AK.rand!(AK.StreamRNG(0x5), zeros(10)) + else + @test_throws ArgumentError AK.rand!(AK.StreamRNG(0x1), array_from_host(zeros(Float32, 16))) + end + end + + @testset "rand! convenience" begin ref1 = array_from_host(zeros(Float32, 1024)) ref2 = array_from_host(zeros(Float32, 1024)) x1 = array_from_host(zeros(Float32, 1024)) x2 = array_from_host(zeros(Float32, 1024)) - Random.seed!(0xabcdef) - seed1 = Random.rand(Random.default_rng(), UInt64) - AK.rand!(AK.CounterRNG(seed1; alg=AK.Philox()), ref1; prefer_threads, block_size=64) - seed2 = Random.rand(Random.default_rng(), UInt64) - AK.rand!(AK.CounterRNG(seed2; alg=AK.Philox()), ref2; prefer_threads, block_size=64) - - Random.seed!(0xabcdef) - AK.rand!(x1; prefer_threads, block_size=64) - AK.rand!(x2; prefer_threads, block_size=64) - @test Array(x1) == Array(ref1) - @test Array(x2) == Array(ref2) + if IS_CPU_BACKEND + # A fresh StreamRNG per call, auto-seeded from Random's default RNG + Random.seed!(0xabcdef) + seed1 = Random.rand(Random.default_rng(), UInt64) + AK.rand!(_default_rng(seed1), ref1; prefer_threads, block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) + AK.rand!(_default_rng(seed2), ref2; prefer_threads, block_size=64) + + Random.seed!(0xabcdef) + AK.rand!(x1; prefer_threads, block_size=64) + AK.rand!(x2; prefer_threads, block_size=64) + @test Array(x1) == Array(ref1) + @test Array(x2) == Array(ref2) + else + # Forwarded to the array package's own `Random.rand!` + AK.rand!(x1; prefer_threads, block_size=64) + AK.rand!(x2; prefer_threads, block_size=64) + @test _is_unit_interval(Array(x1)) + @test Array(x1) != Array(x2) + end x_bad = zeros(UInt128, 16) @test_throws ArgumentError AK.rand!(x_bad; prefer_threads) @@ -415,35 +458,27 @@ end # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. AK.rand(BACKEND, Float32, 1; prefer_threads, block_size=64) - # Auto-seeded constructor should match explicit seed capture from default RNG. - Random.seed!(0x9abc) - seed = Random.rand(Random.default_rng(), UInt64) - ref = AK.rand(AK.CounterRNG(seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64) - Random.seed!(0x9abc) - x = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) - @test Array(x) == Array(ref) - - # Auto-seeded convenience without explicit type should use backend-dependent default type. - Random.seed!(0x4242) - seed_default = Random.rand(Random.default_rng(), UInt64) - ref_default = AK.rand( - AK.CounterRNG(seed_default; alg=AK.Philox()), - BACKEND, - default_alloc_type, - 64; - prefer_threads, - block_size=64, - ) - Random.seed!(0x4242) + # Without an explicit type, the element type defaults by backend x_default = AK.rand(BACKEND, 64; prefer_threads, block_size=64) @test eltype(x_default) === default_alloc_type - @test Array(x_default) == Array(ref_default) + @test size(x_default) == (64,) + @test _is_unit_interval(Array(x_default)) + + if IS_CPU_BACKEND + # Auto-seeded StreamRNG should match explicit seed capture from Random's default RNG + Random.seed!(0x9abc) + seed = Random.rand(Random.default_rng(), UInt64) + ref = AK.rand(_default_rng(seed), BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x9abc) + x = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x) == Array(ref) + end # Convenience without backend should default to CPU backend and Float64. Random.seed!(0x4545) seed_cpu_default = Random.rand(Random.default_rng(), UInt64) ref_cpu_default = AK.rand( - AK.CounterRNG(seed_cpu_default; alg=AK.Philox()), + _default_rng(seed_cpu_default), AK.get_backend([]), Float64, 64; @@ -459,7 +494,7 @@ end Random.seed!(0x5656) seed_cpu_typed = Random.rand(Random.default_rng(), UInt64) ref_cpu_typed = AK.rand( - AK.CounterRNG(seed_cpu_typed; alg=AK.Philox()), + _default_rng(seed_cpu_typed), AK.get_backend([]), Float32, 64; @@ -471,12 +506,14 @@ end @test eltype(x_cpu_typed_no_rng) === Float32 @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) - # Reseeding should reproduce the same auto-seeded draw. - Random.seed!(0x7777) - x1 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) - Random.seed!(0x7777) - x2 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) - @test Array(x1) == Array(x2) + # Reseeding Random reproduces the auto-seeded CPU draw (other backends use their own RNG) + if IS_CPU_BACKEND + Random.seed!(0x7777) + x1 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x7777) + x2 = AK.rand(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) + end @test_throws ArgumentError AK.rand(AK.CounterRNG(0x1), BACKEND, UInt128, 16; prefer_threads) @test_throws MethodError AK.rand(AK.CounterRNG(0x1), BACKEND, Float32, 16; prefer_threads, bad=:kwarg) diff --git a/test/randn.jl b/test/randn.jl index b5d18fe0..58a41e01 100644 --- a/test/randn.jl +++ b/test/randn.jl @@ -1,4 +1,4 @@ -const RANDN_ALGS = (AK.SplitMix64(), AK.Philox(), AK.Threefry()) +const RANDN_ALGS = (AK.Philox(),) const RANDN_FLOAT_TYPES_BACKEND = IS_CPU_BACKEND ? (Float16, Float32, Float64) : (Float32,) const RANDN_LENGTHS = (0, 1, 2, 31, 32, 33, 257, 1024) @@ -43,62 +43,6 @@ end @testset "randn" begin - @testset "fastmath" begin - @test 0.0f0 < AK._uint32_to_left_open_unit_float32(UInt32(0)) <= 1.0f0 - @test 0.0f0 < AK._uint32_to_left_open_unit_float32(typemax(UInt32)) <= 1.0f0 - @test 0.0 < AK._uint64_to_left_open_unit_float64(UInt64(0)) <= 1.0 - @test 0.0 < AK._uint64_to_left_open_unit_float64(typemax(UInt64)) <= 1.0 - - # Edge cases: log never reaches zero or -Inf, angles never land on an axis - @test AK._fast_log(Float32, typemax(UInt32)) < 0 - @test AK._fast_log(Float32, typemin(UInt32)) > -Inf32 - @test AK._fast_log(Float64, typemax(UInt64)) < 0 - @test AK._fast_log(Float64, typemin(UInt64)) > -Inf - @test AK._fast_sincospi(Float32, typemin(UInt32)) === (Float32(2pi * 2.0^-33), 1.0f0) - @test AK._fast_sincospi(Float64, typemin(UInt64)) === (2pi * 2.0^-65, 1.0) - - # Reference Box-Muller radius sqrt(-2 log(x)) in Float64, using log1p near x = 1 - ref_radius(u::UInt32) = sqrt(-2 * log(fma(Float64(u), 2.0^-32, 2.0^-33))) - ref_radius(u::UInt64) = sqrt(-2 * ( - u < UInt64(2)^63 ? - log(fma(Float64(u), 2.0^-64, 2.0^-65)) : - log1p(-fma(Float64(~u), 2.0^-64, 2.0^-65)) - )) - fast_radius(::Type{T}, u) where {T} = Base.sqrt_llvm(-2 * AK._fast_log(T, u)) - - # Reference sincospi with the same octant mapping as `_fast_sincospi` - function ref_sincospi(u::Unsigned) - nbits = 8 * sizeof(u) - y = fma(Float64(u & ~oftype(u, 0x7)), 2.0^-(nbits + 2), 2.0^-nbits) - return AK._sincospi_apply_octant(u % UInt8, sinpi(y), cospi(y)) - end - sincospi_err(::Type{T}, u) where {T} = maximum(abs.(AK._fast_sincospi(T, u) .- ref_sincospi(u))) - - # Sample the full UInt32 range, plus both ends densely - us32 = vcat( - collect(UInt32(0):UInt32(4093):typemax(UInt32)), - collect(UInt32(0):UInt32(1 << 16)), - collect(typemax(UInt32) - UInt32(1 << 16):typemax(UInt32)), - ) - @test maximum(u -> abs(fast_radius(Float32, u) - ref_radius(u)), us32) < 5e-7 - @test maximum(u -> sincospi_err(Float32, u), us32) < 2e-7 - - # Sample the full UInt64 range, plus both ends and the midpoint densely - us64 = vcat( - [UInt64(i) << 44 for i in 0:((1 << 20) - 1)], - collect(UInt64(0):UInt64(1 << 16)), - collect(UInt64(2)^63 - UInt64(1 << 16):UInt64(2)^63 + UInt64(1 << 16)), - collect(typemax(UInt64) - UInt64(1 << 16):typemax(UInt64)), - ) - @test maximum(u -> abs(fast_radius(Float64, u) - ref_radius(u)), us64) < 3e-15 - @test maximum(u -> sincospi_err(Float64, u), us64) < 4e-16 - - # Mean of log(x) over uniform x in (0, 1] is -1 (midpoint-sampled over the UInt32 range) - mean_log = sum(u -> Float64(AK._fast_log(Float32, u)), UInt32(128):UInt32(256):typemax(UInt32)) / 2^24 - @test abs(mean_log + 1) < 1e-6 - end - - @testset "scalar helpers" begin seed = UInt64(0x123456789abcdef) for alg in RANDN_ALGS @@ -232,17 +176,26 @@ end x1 = array_from_host(zeros(Float32, 1024)) x2 = array_from_host(zeros(Float32, 1024)) - Random.seed!(0xabcdef) - seed1 = Random.rand(Random.default_rng(), UInt64) - AK.randn!(AK.CounterRNG(seed1; alg=AK.Philox()), ref1; prefer_threads, block_size=64) - seed2 = Random.rand(Random.default_rng(), UInt64) - AK.randn!(AK.CounterRNG(seed2; alg=AK.Philox()), ref2; prefer_threads, block_size=64) - - Random.seed!(0xabcdef) - AK.randn!(x1; prefer_threads, block_size=64) - AK.randn!(x2; prefer_threads, block_size=64) - @test Array(x1) == Array(ref1) - @test Array(x2) == Array(ref2) + if IS_CPU_BACKEND + # A fresh StreamRNG per call, auto-seeded from Random's default RNG + Random.seed!(0xabcdef) + seed1 = Random.rand(Random.default_rng(), UInt64) + AK.randn!(_default_rng(seed1), ref1; prefer_threads, block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) + AK.randn!(_default_rng(seed2), ref2; prefer_threads, block_size=64) + + Random.seed!(0xabcdef) + AK.randn!(x1; prefer_threads, block_size=64) + AK.randn!(x2; prefer_threads, block_size=64) + @test Array(x1) == Array(ref1) + @test Array(x2) == Array(ref2) + else + # Forwarded to the array package's own `Random.randn!` + AK.randn!(x1; prefer_threads, block_size=64) + AK.randn!(x2; prefer_threads, block_size=64) + @test _all_finite(Array(x1)) + @test Array(x1) != Array(x2) + end x_bad = zeros(UInt32, 16) @test_throws ArgumentError AK.randn!(x_bad; prefer_threads) @@ -301,37 +254,27 @@ end # Warm-up first call path so one-time compilation/backend init does not perturb RNG checks. AK.randn(BACKEND, Float32, 1; prefer_threads, block_size=64) - # Auto-seeded constructor should match explicit seed capture from default RNG. - Random.seed!(0x9abc) - seed = Random.rand(Random.default_rng(), UInt64) - ref = AK.randn(AK.CounterRNG( - seed; alg=AK.Philox()), BACKEND, Float32, 64; prefer_threads, block_size=64 - ) - Random.seed!(0x9abc) - x = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) - @test Array(x) == Array(ref) - - # Auto-seeded convenience without explicit type should use backend-dependent default type. - Random.seed!(0x4242) - seed_default = Random.rand(Random.default_rng(), UInt64) - ref_default = AK.randn( - AK.CounterRNG(seed_default; alg=AK.Philox()), - BACKEND, - default_alloc_type, - 64; - prefer_threads, - block_size=64, - ) - Random.seed!(0x4242) + # Without an explicit type, the element type defaults by backend x_default = AK.randn(BACKEND, 64; prefer_threads, block_size=64) @test eltype(x_default) === default_alloc_type - @test Array(x_default) == Array(ref_default) + @test size(x_default) == (64,) + @test _all_finite(Array(x_default)) + + if IS_CPU_BACKEND + # Auto-seeded StreamRNG should match explicit seed capture from Random's default RNG + Random.seed!(0x9abc) + seed = Random.rand(Random.default_rng(), UInt64) + ref = AK.randn(_default_rng(seed), BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x9abc) + x = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x) == Array(ref) + end # Convenience without backend should default to CPU backend and Float64. Random.seed!(0x4545) seed_cpu_default = Random.rand(Random.default_rng(), UInt64) ref_cpu_default = AK.randn( - AK.CounterRNG(seed_cpu_default; alg=AK.Philox()), + _default_rng(seed_cpu_default), AK.get_backend([]), Float64, 64; @@ -347,7 +290,7 @@ end Random.seed!(0x5656) seed_cpu_typed = Random.rand(Random.default_rng(), UInt64) ref_cpu_typed = AK.randn( - AK.CounterRNG(seed_cpu_typed; alg=AK.Philox()), + _default_rng(seed_cpu_typed), AK.get_backend([]), Float32, 64; @@ -359,12 +302,14 @@ end @test eltype(x_cpu_typed_no_rng) === Float32 @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) - # Reseeding should reproduce the same auto-seeded draw. - Random.seed!(0x7777) - x1 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) - Random.seed!(0x7777) - x2 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) - @test Array(x1) == Array(x2) + # Reseeding Random reproduces the auto-seeded CPU draw (other backends use their own RNG) + if IS_CPU_BACKEND + Random.seed!(0x7777) + x1 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + Random.seed!(0x7777) + x2 = AK.randn(BACKEND, Float32, 64; prefer_threads, block_size=64) + @test Array(x1) == Array(x2) + end @test_throws ArgumentError AK.randn(AK.CounterRNG(0x1), BACKEND, UInt32, 16; prefer_threads) @test_throws MethodError AK.randn( @@ -377,11 +322,64 @@ end end + @testset "mixed calls share no random words" begin + # Regression: randn! precisions and rand! used to share one counter space with different + # layouts, so a Float64 fill followed by a Float32 fill, or rand! ending on an odd element + # followed by randn!, reused random words; across seeds the dependent values correlated + # at ~1.0 and ~-0.6 respectively. Counter logic is backend-independent, so test on CPU. + corr(x, y) = (xc = x .- sum(x) / length(x); yc = y .- sum(y) / length(y); + sum(xc .* yc) / sqrt(sum(abs2, xc) * sum(abs2, yc))) + + nseeds = 1000 + cos64, cos32, u, z2 = zeros(nseeds), zeros(nseeds), zeros(nseeds), zeros(nseeds) + for s in 1:nseeds + rng = AK.CounterRNG(s) + x64 = AK.randn!(rng, zeros(Float64, 6)) + x32 = AK.randn!(rng, zeros(Float32, 6)) + cos64[s] = maximum(abs, x64[3:4]) / hypot(x64[3], x64[4]) + cos32[s] = maximum(abs, x32[1:2]) / hypot(x32[1], x32[2]) + + rng = AK.CounterRNG(s) + u[s] = AK.rand!(rng, zeros(5))[5] + z2[s] = AK.randn!(rng, zeros(1))[1]^2 + end + @test abs(corr(cos64, cos32)) < 0.15 + @test abs(corr(u, z2)) < 0.15 + end + + + @testset "StreamRNG" begin + if IS_CPU_BACKEND + # Long enough for 3 tasks at the minimum elements per task, forcing the jump-ahead path + n = 3 * AK.XOSHIRO_MIN_ELEMS_PER_TASK + 1 + + # Identical values and final state regardless of the number of tasks + for T in RANDN_FLOAT_TYPES_BACKEND + rng1 = AK.StreamRNG(0x99) + rngn = AK.StreamRNG(0x99) + x1 = AK.randn!(rng1, zeros(T, n); max_tasks=1) + xn = AK.randn!(rngn, zeros(T, n); max_tasks=3) + @test x1 == xn + @test rng1.state == rngn.state + end + + # Two consecutive fills match one fill of the combined length + rng_split = AK.StreamRNG(0x5) + ab = vcat(AK.randn!(rng_split, zeros(5)), AK.randn!(rng_split, zeros(5))) + @test ab == AK.randn!(AK.StreamRNG(0x5), zeros(10)) + else + @test_throws ArgumentError AK.randn!(AK.StreamRNG(0x1), array_from_host(zeros(Float32, 16))) + end + end + + @testset "moments sanity" begin n = 200_000 - rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + rngs = IS_CPU_BACKEND ? + (AK.CounterRNG(0x123456789abcdef), AK.StreamRNG(0x123456789abcdef)) : + (AK.CounterRNG(0x123456789abcdef),) - for T in RANDN_FLOAT_TYPES_BACKEND + for rng in rngs, T in RANDN_FLOAT_TYPES_BACKEND x = array_from_host(zeros(T, n)) AK.randn!(rng, x; prefer_threads, block_size=128) xa = Float64.(Array(x))