diff --git a/Project.toml b/Project.toml index b21d6f81..0d92ef52 100644 --- a/Project.toml +++ b/Project.toml @@ -10,7 +10,9 @@ Atomix = "a9b6321e-bd34-4604-b9c9-b65b8de01458" GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527" KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c" KernelInterface = "4ee993da-d684-4d17-a7dd-4e58e78d92bf" +PhiloxRNG = "508b8dab-2d72-462c-b792-eb7ae329b456" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" [weakdeps] AMDGPU = "21141c5a-9bdb-4563-92ae-f87d6854732e" @@ -39,6 +41,8 @@ KernelAbstractions = "0.9.43, 0.10" KernelInterface = "0.4" Metal = "1.12" OpenCL = "1" +PhiloxRNG = "1.1" PrecompileTools = "1" +Random = "1" julia = "1.10" oneAPI = "2.10" diff --git a/docs/make.jl b/docs/make.jl index 6d3b5a1e..fc76f41e 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -29,6 +29,7 @@ makedocs(; "Algorithms and Backends" => "api/algorithms.md", "General Loops" => "api/foreachindex.md", "Map" => "api/map.md", + "Random Number Generation" => "api/rand.md", "Sorting" => "api/sort.md", "Selection" => "api/select.md", "Reduce" => "api/reduce.md", diff --git a/docs/src/api/rand.md b/docs/src/api/rand.md new file mode 100644 index 00000000..fab4910f --- /dev/null +++ b/docs/src/api/rand.md @@ -0,0 +1,203 @@ +### Random Number Generation + +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` +- Standard normal: `AK.randn!`, `AK.randn` + +`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. +- `AK.reset!(rng)` rewinds `rng.offset` to `0x0`. + +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` on any backend, or `rng::AK.StreamRNG` on +the CPU backend. + +#### Auto-seeded convenience behaviour + +Use an explicit RNG when reproducibility is required. + +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)` +- `AK.randn!(v)` +- `AK.rand(dims...; backend)` +- `AK.randn(dims...; backend)` + +These do **not** continue a shared stream across calls unless you pass the same explicit RNG. + +#### Allocation forms + +Canonical forms: +- `AK.rand(rng, T, dims...; backend)` +- `AK.randn(rng, T, dims...; backend)` + +Shared defaults: +- omit `rng` -> fresh `StreamRNG()` on the CPU backend, the array package's `Random` fill otherwise +- omit `backend` -> the host (CPU) backend +- omit `T` -> `Float64` on CPU backend, `Float32` otherwise + +Common shorthands include: +- `AK.rand(dims...)` +- `AK.rand(T, dims...)` +- `AK.rand(dims...; backend)` +- and the corresponding `AK.randn(...)` variants + +Like AK's other operations, all forms also accept `block_size` (kernels) and `max_tasks` / +`min_elems` (host threads) keywords. + +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 + +`AK.rand!` / `AK.rand` support: +- `UInt8`, `UInt16`, `UInt32`, `UInt64` +- `Int8`, `Int16`, `Int32`, `Int64` +- `Float16`, `Float32`, `Float64` +- `Bool` + +`AK.randn!` / `AK.randn` currently support: +- `Float16`, `Float32`, `Float64` + +#### Value generation semantics + +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` + +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. + +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`. + +#### CPU stream RNG + +`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 + +`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. + +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. + +#### Algorithm + +`CounterRNG` uses `Philox` ([read more](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf)), +the only (and default) algorithm. + +#### Statistical testing and security + +- In this repository, `Philox` (Philox4x32-10) has passed TestU01 BigCrush +- These generators are not intended to be cryptographically secure + +#### Philox keying note + +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). + +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. + +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 + +`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 +import AcceleratedKernels as AK +using oneAPI +using AMDGPU + +# Reproducible +rng = AK.CounterRNG(0x12345678; alg=AK.Philox()) +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 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(Float32, 1024; backend=oneAPIBackend()) # 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 +z = ROCArray{Float32}(undef, 1024) +AK.randn!(rng, z) + +# Standard normal allocation form +z_cpu_auto = AK.randn(1024) # CPU, Vector{Float64} +z_roc = AK.randn(1024; backend=ROCBackend()) # 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.StreamRNG +AcceleratedKernels.reset! +AcceleratedKernels.rand! +AcceleratedKernels.rand +AcceleratedKernels.randn! +AcceleratedKernels.randn +``` \ No newline at end of file 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..c3a6705f --- /dev/null +++ b/prototype/RNGTest/stream.jl @@ -0,0 +1,83 @@ +import AcceleratedKernels as AK + + +# `:philox` tests the backend-agnostic `CounterRNG` (Philox4x32-10), `:xoshiro` the CPU default +# `StreamRNG` (Xoshiro256++). In both, `offset` skips that many outputs from the start of the stream. +function make_rng(seed::Integer, alg::Symbol; offset::Integer=0) + if alg === :philox + return AK.CounterRNG(seed; alg=AK.Philox(), offset=offset) + elseif alg === :xoshiro + rng = AK.StreamRNG(seed) + # StreamRNG has no offset field; jump the stream state ahead instead (internal helper) + rng.state = AK._xoshiro_jump(rng.state, UInt64(offset)) + return rng + end + throw(ArgumentError("alg must be :philox or :xoshiro; got $alg")) +end + + +mutable struct AKUInt64Stream{R} + 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/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/prototype/rand/Project.toml b/prototype/rand/Project.toml new file mode 100644 index 00000000..4ca85890 --- /dev/null +++ b/prototype/rand/Project.toml @@ -0,0 +1,11 @@ +[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" +Metal = "dde4c033-4e86-420c-a63e-0dd931031962" + +[sources] +AcceleratedKernels = {path = "../.."} diff --git a/prototype/rand/randn.jl b/prototype/rand/randn.jl new file mode 100644 index 00000000..d552b5f8 --- /dev/null +++ b/prototype/rand/randn.jl @@ -0,0 +1,51 @@ +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(), offset=0x0) + +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)) + + diff --git a/prototype/rand/test_rand.jl b/prototype/rand/test_rand.jl new file mode 100644 index 00000000..0d916f29 --- /dev/null +++ b/prototype/rand/test_rand.jl @@ -0,0 +1,57 @@ +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_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 + + +# warmup +run_cuda_rand!(x_cuda) +run_ak_rand_gpu!(RNG_PHILOX, x_philox) +run_ak_rand_cpu!(RNG_PHILOX, x_cpu) + + +println("N = ", N) +println("CPU threads: ", Threads.nthreads()) + +println("\nCUDA.rand! benchmark (CuArray{$TestType}, in-place)") +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! benchmark (CPU, Vector{$TestType}, Philox)") +display(@benchmark run_ak_rand_cpu!($RNG_PHILOX, $x_cpu)) + diff --git a/src/AcceleratedKernels.jl b/src/AcceleratedKernels.jl index 2115b540..2b13dc88 100644 --- a/src/AcceleratedKernels.jl +++ b/src/AcceleratedKernels.jl @@ -34,6 +34,8 @@ import Adapt using GPUArraysCore: AnyGPUArray, @allowscalar, neutral_element using KernelAbstractions using KernelAbstractions: @context +import PhiloxRNG +import Random # Sub-group operations, with KernelAbstractions 0.10 @static if isdefined(KernelAbstractions, :KernelInterface) const KI = KernelAbstractions.KernelInterface @@ -62,6 +64,7 @@ include("accumulate/accumulate.jl") include("findall.jl") include("reverse.jl") include("predicates.jl") +include("rand/rand.jl") end # module AcceleratedKernels diff --git a/src/rand/philox.jl b/src/rand/philox.jl new file mode 100644 index 00000000..1f0bee2a --- /dev/null +++ b/src/rand/philox.jl @@ -0,0 +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 + + +# 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 + + +# 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 + + +# 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 + 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 + + +# Counter `c` is half `c % 2` of block `c ÷ 2` +@inline function rand_uint( + seed::UInt64, + alg::Philox, + counter::UInt64, + ::Type{UInt64}, +)::UInt64 + 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 new file mode 100644 index 00000000..061e1d4d --- /dev/null +++ b/src/rand/rand.jl @@ -0,0 +1,333 @@ +const ALLOWED_RAND_SCALARS = Union{ + UInt8, UInt16, UInt32, UInt64, + Int8, Int16, Int32, Int64, + Float16, Float32, Float64, + Bool +} + +@inline function _check_rand_eltype(::Type{T}) where {T} + T <: ALLOWED_RAND_SCALARS || + throw(ArgumentError("Unsupported eltype $T. Supported: $(ALLOWED_RAND_SCALARS)")) +end + + +""" + AbstractAKRNG + +Abstract supertype for AcceleratedKernels RNG objects, such as [`CounterRNG`](@ref) or +[`StreamRNG`](@ref). +""" +abstract type AbstractAKRNG end + + +# Internal algorithm supertypes: `Philox` is currently the only `CounterRNG` algorithm, and +# `Xoshiro256PP` the only `StreamRNG` algorithm +abstract type CounterRNGAlgorithm end +abstract type StreamRNGAlgorithm end + + +# Internal supertype for stream states: immutable values, replaced by `StreamRNG` as it advances +abstract type StreamRNGState end + + +# 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=Xoshiro256PP(), + state::Union{Nothing, StreamRNGState}=nothing, + ) + +Stateful stream RNG for the CPU backend. + +`StreamRNG` stores: +- `seed` +- algorithm (`alg`): `Xoshiro256PP()`, the only (and default) algorithm +- current stream state (`state`), initialised from `seed` via SplitMix64 unless given + +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, S <: StreamRNGState} <: AbstractAKRNG + const seed::UInt64 + const alg::A + state::S +end + + +function StreamRNG( + seed::Integer; + alg::StreamRNGAlgorithm=Xoshiro256PP(), + 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()) + +Counter-based RNG for [`rand!`](@ref). + +`CounterRNG` stores: +- `seed` +- 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(), 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`. +""" +mutable struct CounterRNG{A <: CounterRNGAlgorithm} <: AbstractAKRNG + const seed::UInt64 + const alg::A + offset::UInt64 +end + + +function CounterRNG(seed::Integer; alg::CounterRNGAlgorithm=Philox(), offset::Integer=0) + @argcheck seed >= 0 "Seed must be a non-negative integer" + @argcheck offset >= 0 "Offset must be a non-negative integer" + CounterRNG(UInt64(seed), alg, UInt64(offset)) +end + + +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::CounterRNG) + +Reset `rng.offset` to `0x0`. +""" +@inline function reset!(rng::CounterRNG) + rng.offset = UInt64(0) + return rng +end + + + + +# Shared helpers +include("utilities.jl") + +# Algorithm-specific integer generators +include("splitmix.jl") +include("philox.jl") +include("rand_cpu.jl") + +# Normally distributed scalar generators and randn! +include("ziggurat.jl") +include("randn.jl") + + + + +""" + rand!( + [rng::AbstractAKRNG,] + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + ) + +Fill `v` in-place with pseudo-random values, and return it. The backend is resolved from `v` +unless given; `block_size` applies to kernels and `max_tasks` / `min_elems` to host threads. + +- For [`CounterRNG`](@ref), each `v[i]` uses counter `rng.offset + UInt64(i - 1)` in linear + indexing order, and `rng.offset` advances by `length(v)`. Values depend only on the seed and the + counter, so they are identical on every backend and for any launch configuration. +- For [`StreamRNG`](@ref) (host 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. +- Without `rng`: a fresh auto-seeded `StreamRNG()` on the host 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` +- `Int8`, `Int16`, `Int32`, `Int64` +- `Float16`, `Float32`, `Float64` +- `Bool` + +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 + produced mantissa grid (not over all representable floats). +- Bool: `true` if the raw `UInt` draw is odd (`isodd(u)`), otherwise `false`. +""" +function rand!( + rng::AbstractAKRNG, + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where T + _check_rand_eltype(T) + backend = resolve_backend(backend, v) + + if rng isa CounterRNG + crng = rng::CounterRNG + + # Local isbits captures from mutable rng object + seed, alg, initial_offset = crng.seed, crng.alg, crng.offset + + # One block evaluation per group of elements + _fill_groups!( + rand_group, seed, alg, v, initial_offset, _rand_group_size(alg, T), + backend, block_size, max_tasks, min_elems, + ) + + crng.offset += UInt64(length(v)) + return v + end + + if rng isa StreamRNG{Xoshiro256PP} + srng = rng::StreamRNG{Xoshiro256PP} + @argcheck runs_threads(backend) "StreamRNG is only supported on the host backend" + + _xoshiro_fill_stream!( + _xoshiro_scalar_from_uint64, srng, v, Val(XOSHIRO_RAND_LANES); + max_tasks, min_elems, + ) + return v + end + + throw(ArgumentError( + "No rand! implementation for RNG type $(typeof(rng)) on backend $(backend)" + )) +end + + +function rand!( + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where T + _check_rand_eltype(T) + return _fill_default!( + rand!, Random.rand!, v, resolve_backend(backend, v); + block_size, max_tasks, min_elems, + ) +end + + +""" + rand( + [rng::AbstractAKRNG,] + [::Type{T},] + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + ) + +Allocate an array of element type `T` and shape `dims` on `backend`, fill it in-place via +[`rand!`](@ref), and return it. + +- `backend` omitted: the host backend. +- `rng` omitted: fills via [`rand!`](@ref) without an RNG (a fresh `StreamRNG()` on the host + backend, the array package's `Random.rand!` otherwise). +- `T` omitted: `Float64` on the host backend, `Float32` otherwise. +""" +function rand( + rng::AbstractAKRNG, + ::Type{T}, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) where T + _check_rand_eltype(T) + backend = resolve_backend(backend) + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return rand!(rng, v; backend, kwargs...) +end + + +function rand( + ::Type{T}, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) where T + _check_rand_eltype(T) + backend = resolve_backend(backend) + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return rand!(v; backend, kwargs...) +end + + +function rand( + rng::AbstractAKRNG, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) + backend = resolve_backend(backend) + return rand(rng, _default_rand_eltype(backend), dims...; backend, kwargs...) +end + + +function rand(dims::Integer...; backend::Union{Nothing, Backend}=nothing, kwargs...) + backend = resolve_backend(backend) + return rand(_default_rand_eltype(backend), dims...; backend, kwargs...) +end + + +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..0537aef5 --- /dev/null +++ b/src/rand/rand_cpu.jl @@ -0,0 +1,272 @@ +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 new file mode 100644 index 00000000..915eb35b --- /dev/null +++ b/src/rand/randn.jl @@ -0,0 +1,282 @@ +const ALLOWED_RANDN_SCALARS = Union{ + Float16, Float32, Float64 +} + +@inline function _check_randn_eltype(::Type{T}) where {T} + T <: ALLOWED_RANDN_SCALARS || + throw(ArgumentError("Unsupported eltype $T. Supported: $(ALLOWED_RANDN_SCALARS)")) +end + + +#= +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, + pair_counter::UInt64, + ::Type{Float16}, +)::Tuple{Float16, Float16} + z0, z1 = randn_pair(seed, alg, pair_counter, Float32) + return Float16(z0), Float16(z1) +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, 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(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` 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 + 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 + + +@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 + + +# 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) + + +# 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 + + +# 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 + + +""" + randn!( + [rng::AbstractAKRNG,] + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + ) where {T <: AbstractFloat} + +Fill `v` in-place with pseudo-random samples from a standard normal distribution, and return it. +The backend is resolved from `v` unless given; `block_size` applies to kernels and `max_tasks` / +`min_elems` to host threads. + +- For [`CounterRNG`](@ref), the normal counter of `v[i]` is `rng.offset + UInt64(i - 1)` in linear + indexing order, and `rng.offset` advances by `length(v)`. Values are generated with Box-Muller + from PhiloxRNG.jl, with polynomial `log` and `sincospi` evaluated directly on the raw random bits + in the requested precision (`Float16` is computed in `Float32`). +- For [`StreamRNG`](@ref) (host backend only), `v[i]` is computed by the ziggurat method from the + `i`th output of the Xoshiro256++ stream from `rng.state`, which advances by `length(v)` steps. + Each sample consumes exactly one stream output, so the result is identical for any number of + tasks. `Float16` and `Float32` samples are rounded from `Float64`. +- Without `rng`: a fresh auto-seeded `StreamRNG()` on the host backend. 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. + +In each case, consecutive fills match one fill of the combined length. +""" +function randn!( + rng::CounterRNG, + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where T + _check_randn_eltype(T) + backend = resolve_backend(backend, v) + + isempty(v) && return v + + # Local isbits captures from mutable rng object. + seed, alg, initial_offset = rng.seed, rng.alg, rng.offset + + _fill_groups!( + randn_group, seed, alg, v, initial_offset, _randn_group_size(alg, T), + backend, block_size, max_tasks, min_elems, + ) + + rng.offset += UInt64(length(v)) + + v +end + + +function randn!( + rng::StreamRNG{Xoshiro256PP}, + v::AbstractArray{T}; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where T + _check_randn_eltype(T) + backend = resolve_backend(backend, v) + @argcheck runs_threads(backend) "StreamRNG is only supported on the host 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::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, +) where T + _check_randn_eltype(T) + return _fill_default!( + randn!, Random.randn!, v, resolve_backend(backend, v); + block_size, max_tasks, min_elems, + ) +end + + +""" + randn( + [rng::AbstractAKRNG,] + [::Type{T},] + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + block_size::Int=256, + max_tasks::Int=Threads.nthreads(), + min_elems::Int=1, + ) + +Allocate an array of element type `T` and shape `dims` on `backend`, fill it in-place via +[`randn!`](@ref), and return it. + +- `backend` omitted: the host backend. +- `rng` omitted: fills via [`randn!`](@ref) without an RNG (a fresh `StreamRNG()` on the host + backend, the array package's `Random.randn!` otherwise). +- `T` omitted: `Float64` on the host backend, `Float32` otherwise. +""" +function randn( + rng::AbstractAKRNG, + ::Type{T}, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) where T + _check_randn_eltype(T) + backend = resolve_backend(backend) + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return randn!(rng, v; backend, kwargs...) +end + + +function randn( + ::Type{T}, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) where T + _check_randn_eltype(T) + backend = resolve_backend(backend) + v = KernelAbstractions.allocate(backend, T, Base.map(Int, dims)) + return randn!(v; backend, kwargs...) +end + + +function randn( + rng::AbstractAKRNG, + dims::Integer...; + backend::Union{Nothing, Backend}=nothing, + kwargs..., +) + backend = resolve_backend(backend) + return randn(rng, _default_rand_eltype(backend), dims...; backend, kwargs...) +end + + +function randn(dims::Integer...; backend::Union{Nothing, Backend}=nothing, kwargs...) + backend = resolve_backend(backend) + return randn(_default_rand_eltype(backend), dims...; backend, kwargs...) +end + + +randn(; kwargs...) = throw(ArgumentError("randn requires at least one dimension")) diff --git a/src/rand/splitmix.jl b/src/rand/splitmix.jl new file mode 100644 index 00000000..12b3d6ca --- /dev/null +++ b/src/rand/splitmix.jl @@ -0,0 +1,16 @@ +# SplitMix64 mixing, used to seed StreamRNG states and for the ziggurat's rejection fallback + +# 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 diff --git a/src/rand/utilities.jl b/src/rand/utilities.jl new file mode 100644 index 00000000..dcf40d81 --- /dev/null +++ b/src/rand/utilities.jl @@ -0,0 +1,203 @@ +# 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) + +# Get counter used for CounterRNG from element index +@inline _counter_from_index(i)::UInt64 = UInt64(i - one(i)) + + +#= +Fill `v` without an explicit RNG. On the host backend this uses a fresh auto-seeded `StreamRNG` +with AK's threaded 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; + block_size::Int, + max_tasks::Int, + min_elems::Int, +) + if runs_threads(backend) + return ak_fill!(StreamRNG(), v; backend, block_size, max_tasks, min_elems) + else + random_fill!(v) + return v + end +end + + +# Element type of the allocating forms when none is given: `Float64` on the host, `Float32` on GPUs +@inline _default_rand_eltype(backend::Backend) = runs_threads(backend) ? Float64 : Float32 + + +#= +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, + block_size::Int, + max_tasks::Int, + min_elems::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, block_size, max_tasks, min_elems) 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 +@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) + + +#= +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. +=# +@inline function rand_uint( + ::UInt64, + alg::CounterRNGAlgorithm, + ::UInt64, + ::Type{UIntType} +)::UIntType where {UIntType <: Union{UInt32, UInt64}} + throw(ArgumentError("No rand_uint implementation for RNG algorithm: $(typeof(alg))")) +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( + seed::UInt64, + alg::CounterRNGAlgorithm, + counter::UInt64, + ::Type{T} +)::T where {T <: ALLOWED_RAND_SCALARS} + + UIntType = _rand_scalar_uint_type(T) + u = rand_uint(seed, alg, counter, UIntType) + + return _rand_scalar_from_uint(T, u) +end + + +@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) + # 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) + 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) + # 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) + reinterpret(Float32, bits) - 1.0f0 +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) + + # Interpret as 1.mantissa, then subtract 1 for [0, 1) + reinterpret(Float64, bits) - 1.0 +end diff --git a/src/rand/ziggurat.jl b/src/rand/ziggurat.jl new file mode 100644 index 00000000..c5a3f877 --- /dev/null +++ b/src/rand/ziggurat.jl @@ -0,0 +1,335 @@ +# 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/generic/rand.jl b/test/generic/rand.jl new file mode 100644 index 00000000..93b7aecc --- /dev/null +++ b/test/generic/rand.jl @@ -0,0 +1,520 @@ +const RAND_ALGS = (AK.Philox(),) +const RAND_SCALAR_TYPES_ALL = ( + UInt8, UInt16, UInt32, UInt64, + Int8, Int16, Int32, Int64, + Float16, Float32, Float64, + Bool, +) +const RAND_SCALAR_TYPES_BACKEND = AK.runs_threads(BACKEND) ? + RAND_SCALAR_TYPES_ALL : + (UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Bool) +const RUN_FLOAT16_RAND_TESTS = AK.runs_threads(BACKEND) +const RUN_FLOAT64_RAND_TESTS = AK.runs_threads(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}; + counter_offset::UInt64=UInt64(0), +) where {T <: AK.ALLOWED_RAND_SCALARS} + @inbounds for i in eachindex(x) + 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; counter_offset) + @test Array(x) == ref + return x +end + + +@testset "rand" begin + @testset "constructors" begin + @test AK.CounterRNG(UInt32(0x1); alg=AK.Philox()) isa AK.CounterRNG{AK.Philox} + @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) + Random.seed!(0x1234) + 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; block_size=64) + AK.rand!(rng_auto, x2; block_size=257) + @test rng_auto.offset == UInt64(2048) + @test Array(x1) != Array(x2) + 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, 100)) + s2 = array_from_host(zeros(Float32, 100)) + s12 = array_from_host(zeros(Float32, 200)) + AK.rand!(rng_stream, s1; block_size=64) + @test rng_stream.offset == UInt64(117) + AK.rand!(rng_stream, s2; 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; 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.rand!(rng_stream, empty; 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.rand!(rng_stream, y1; block_size=64) + AK.rand!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), y2; block_size=64) + @test Array(y1) == Array(y2) + + 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; block_size=64) + @test_throws MethodError AK.reset!(rng_dummy) + 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; block_size=64) + @test rng.offset == UInt64(512) + @test AK.reset!(rng) === rng + @test rng.offset == UInt64(0) + AK.rand!(rng, x2; block_size=64) + + @test Array(x1) == Array(x2) + end + + + @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._counter_from_index(1) == UInt64(0) + @test AK._counter_from_index(17) == UInt64(16) + + @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._rand_scalar_uint_type(Float16) === UInt32 + end + @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._rand_scalar_uint_type(Float64) === UInt64 + end + + @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._rand_scalar_from_uint(Float16, UInt32(0)) == Float16(0) + end + @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) + @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 + @test AK.uint64_to_unit_float64(UInt64(0)) == 0.0 + @test 0.0 <= AK.uint64_to_unit_float64(typemax(UInt64)) < 1.0 + end + end + + + @testset "rand_uint" begin + for alg in RAND_ALGS + rng = AK.CounterRNG(0x123456789abcdef; alg) + for U in (UInt32, UInt64) + @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.seed, rng.alg, UInt64(i), U) for i in 0:511] + @test length(unique(vals)) > 460 + end + 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 + + + @testset "rand_scalar" begin + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + + for T in RAND_SCALAR_TYPES_BACKEND + 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 + if T <: AbstractFloat + @test zero(T) <= s0 < one(T) + @test zero(T) <= s1 < one(T) + end + end + + c = UInt64(42) + @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.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.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.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.seed, rng.alg, UInt64(0), UInt128) + end + + + @testset "rand! explicit rng" begin + lengths = (0, 1, 31, 32, 33, 257, 1024) + rng = AK.CounterRNG(0x123456789abcdef; alg=AK.Philox()) + + for T in RAND_SCALAR_TYPES_BACKEND + for len in lengths + x = array_from_host(zeros(T, len)) + _assert_rand_matches_reference!(rng, x; block_size=64) + if T <: AbstractFloat + @test _is_unit_interval(Array(x)) + end + end + end + + for T in RAND_SCALAR_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.rand!(rng1, x1; block_size=64) + AK.rand!(rng2, x2; block_size=257) + @test Array(x1) == Array(x2) + end + + 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!(rng1, x1; block_size=64) + AK.rand!(rng2, x2; block_size=64) + @test Array(x1) != Array(x2) + end + + 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; block_size=64) + AK.rand!(rng_stream, x2; block_size=64) + AK.rand!(rng_once, x12; 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; block_size=128) + end + + if AK.runs_threads(BACKEND) + for T in RAND_SCALAR_TYPES_BACKEND + base = zeros(T, 64) + view_x = @view base[2:2:end] + AK.rand!( + rng, view_x; + max_tasks=Threads.nthreads(), + min_elems=1, + ) + ref_view = zeros(T, length(view_x)) + _rand_fill_reference!( + rng, ref_view; + counter_offset=rng.offset - UInt64(length(view_x)), + ) + @test collect(view_x) == ref_view + end + end + end + + + @testset "StreamRNG" begin + if AK.runs_threads(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)) + + if AK.runs_threads(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; block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) + AK.rand!(_default_rng(seed2), ref2; block_size=64) + + Random.seed!(0xabcdef) + AK.rand!(x1; block_size=64) + AK.rand!(x2; 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; block_size=64) + AK.rand!(x2; 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) + @test_throws ArgumentError AK.rand!(AK.CounterRNG(0x1), x_bad) + end + + + @testset "rand allocation convenience" begin + default_alloc_type = AK.runs_threads(BACKEND) ? Float64 : Float32 + + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) + y = AK.rand(rng, Float32, Int32(6), UInt16(7); backend=BACKEND, 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_default = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + rng_default_ref = AK.CounterRNG(UInt64(0x99); alg=AK.Philox()) + y_default = AK.rand(rng_default, 128; backend=BACKEND, block_size=64) + y_default_ref = AK.rand( + rng_default_ref, default_alloc_type, 128; backend=BACKEND, 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, Float32, 128; backend=BACKEND, block_size=64) + y_fill = array_from_host(zeros(Float32, 128)) + AK.rand!(rng_fill, y_fill; block_size=64) + @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; block_size=64) + y_cpu_default_ref = AK.rand( + rng_cpu_default_ref, 128; 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; block_size=64) + y_cpu_typed_ref = AK.rand( + rng_cpu_typed_ref, Float32, 128; 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(Float32, 1; backend=BACKEND, block_size=64) + + # Without an explicit type, the element type defaults by backend + x_default = AK.rand(64; backend=BACKEND, block_size=64) + @test eltype(x_default) === default_alloc_type + @test size(x_default) == (64,) + @test _is_unit_interval(Array(x_default)) + + if AK.runs_threads(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), Float32, 64; backend=BACKEND, block_size=64) + Random.seed!(0x9abc) + x = AK.rand(Float32, 64; backend=BACKEND, 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( + _default_rng(seed_cpu_default), + Float64, + 64; + block_size=64, + ) + Random.seed!(0x4545) + x_cpu_default = AK.rand(64; 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( + _default_rng(seed_cpu_typed), + Float32, + 64; + block_size=64, + ) + Random.seed!(0x5656) + x_cpu_typed_no_rng = AK.rand(Float32, 64; block_size=64) + @test eltype(x_cpu_typed_no_rng) === Float32 + @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) + + # Reseeding Random reproduces the auto-seeded CPU draw (other backends use their own RNG) + if AK.runs_threads(BACKEND) + Random.seed!(0x7777) + x1 = AK.rand(Float32, 64; backend=BACKEND, block_size=64) + Random.seed!(0x7777) + x2 = AK.rand(Float32, 64; backend=BACKEND, block_size=64) + @test Array(x1) == Array(x2) + end + + @test_throws ArgumentError AK.rand(AK.CounterRNG(0x1), UInt128, 16; backend=BACKEND) + @test_throws MethodError AK.rand(AK.CounterRNG(0x1), Float32, 16; backend=BACKEND, bad=:kwarg) + @test_throws MethodError AK.rand(Float32, 16; backend=BACKEND, bad=:kwarg) + @test_throws MethodError AK.rand(16; backend=BACKEND, bad=:kwarg) + @test_throws MethodError AK.rand(16; bad=:kwarg) + @test_throws ArgumentError AK.rand() + end +end diff --git a/test/generic/randn.jl b/test/generic/randn.jl new file mode 100644 index 00000000..6e37e9ad --- /dev/null +++ b/test/generic/randn.jl @@ -0,0 +1,397 @@ +const RANDN_ALGS = (AK.Philox(),) +const RANDN_FLOAT_TYPES_BACKEND = AK.runs_threads(BACKEND) ? (Float16, Float32, Float64) : (Float32,) +const RANDN_LENGTHS = (0, 1, 2, 31, 32, 33, 257, 1024) + +# AK's default RNG on the host backend, with an explicit seed (other backends forward to `Random`) +_default_rng(seed) = AK.StreamRNG(seed) + + +_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!( + 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) + xa = Array(x) + + if AK.runs_threads(BACKEND) + @test xa == ref + else + # 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 + + return x +end + + +@testset "randn" begin + @testset "scalar helpers" begin + seed = UInt64(0x123456789abcdef) + for alg in RANDN_ALGS + 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 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.randn_scalar(seed, AK.Philox(), UInt64(0), UInt32) + end + + + @testset "randn! explicit rng" begin + for alg in RANDN_ALGS + rng = AK.CounterRNG(0x123456789abcdef; alg) + + 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; block_size=64) + AK.randn!(rng2, x2; block_size=257) + @test Array(x1) == Array(x2) + 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 + UInt64(1); alg=rng.alg) + + AK.randn!(rng1, x1; block_size=64) + AK.randn!(rng2, x2; block_size=64) + @test Array(x1) != Array(x2) + end + end + end + + + @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; block_size=64) + @test rng_stream.offset == UInt64(116) + AK.randn!(rng_stream, s2; 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; block_size=64) + @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) + AK.randn!(rng_split, b) + + ab = array_from_host(zeros(Float32, 10)) + AK.randn!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), ab) + @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; 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; block_size=64) + AK.randn!(AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()), y2; block_size=64) + @test Array(y1) == Array(y2) + end + + + @testset "shapes 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; block_size=128) + end + + if AK.runs_threads(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, + ) + + 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)) + + if AK.runs_threads(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; block_size=64) + seed2 = Random.rand(Random.default_rng(), UInt64) + AK.randn!(_default_rng(seed2), ref2; block_size=64) + + Random.seed!(0xabcdef) + AK.randn!(x1; block_size=64) + AK.randn!(x2; 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; block_size=64) + AK.randn!(x2; 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) + @test_throws ArgumentError AK.randn!(AK.CounterRNG(0x1), x_bad) + end + + + @testset "randn allocation convenience" begin + default_alloc_type = AK.runs_threads(BACKEND) ? Float64 : Float32 + + rng = AK.CounterRNG(UInt64(0x1234); alg=AK.Philox()) + y = AK.randn(rng, Float32, Int32(6), UInt16(7); backend=BACKEND, block_size=64) + @test size(y) == (6, 7) + @test eltype(y) === Float32 + @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, 128; backend=BACKEND, block_size=64) + y_default_ref = AK.randn( + rng_default_ref, default_alloc_type, 128; backend=BACKEND, 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, Float32, 128; backend=BACKEND, block_size=64) + y_fill = array_from_host(zeros(Float32, 128)) + AK.randn!(rng_fill, y_fill; block_size=64) + @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; block_size=64) + y_cpu_default_ref = AK.randn( + rng_cpu_default_ref, 128; 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; block_size=64) + y_cpu_typed_ref = AK.randn( + rng_cpu_typed_ref, Float32, 128; 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(Float32, 1; backend=BACKEND, block_size=64) + + # Without an explicit type, the element type defaults by backend + x_default = AK.randn(64; backend=BACKEND, block_size=64) + @test eltype(x_default) === default_alloc_type + @test size(x_default) == (64,) + @test _all_finite(Array(x_default)) + + if AK.runs_threads(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), Float32, 64; backend=BACKEND, block_size=64) + Random.seed!(0x9abc) + x = AK.randn(Float32, 64; backend=BACKEND, 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( + _default_rng(seed_cpu_default), + Float64, + 64; + block_size=64, + ) + Random.seed!(0x4545) + x_cpu_default = AK.randn(64; 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( + _default_rng(seed_cpu_typed), + Float32, + 64; + block_size=64, + ) + Random.seed!(0x5656) + x_cpu_typed_no_rng = AK.randn(Float32, 64; block_size=64) + @test eltype(x_cpu_typed_no_rng) === Float32 + @test Array(x_cpu_typed_no_rng) == Array(ref_cpu_typed) + + # Reseeding Random reproduces the auto-seeded CPU draw (other backends use their own RNG) + if AK.runs_threads(BACKEND) + Random.seed!(0x7777) + x1 = AK.randn(Float32, 64; backend=BACKEND, block_size=64) + Random.seed!(0x7777) + x2 = AK.randn(Float32, 64; backend=BACKEND, block_size=64) + @test Array(x1) == Array(x2) + end + + @test_throws ArgumentError AK.randn(AK.CounterRNG(0x1), UInt32, 16; backend=BACKEND) + @test_throws MethodError AK.randn( + AK.CounterRNG(0x1), Float32, 16; backend=BACKEND, bad=:kwarg + ) + @test_throws MethodError AK.randn(Float32, 16; backend=BACKEND, bad=:kwarg) + @test_throws MethodError AK.randn(16; backend=BACKEND, bad=:kwarg) + @test_throws MethodError AK.randn(16; bad=:kwarg) + @test_throws ArgumentError AK.randn() + 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 AK.runs_threads(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 + rngs = AK.runs_threads(BACKEND) ? + (AK.CounterRNG(0x123456789abcdef), AK.StreamRNG(0x123456789abcdef)) : + (AK.CounterRNG(0x123456789abcdef),) + + for rng in rngs, T in RANDN_FLOAT_TYPES_BACKEND + x = array_from_host(zeros(T, n)) + AK.randn!(rng, x; 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