Skip to content

Deterministic multithreaded CPU rand!/randn! and backend-agnostic CounterRNG - #219

Open
fjbarter wants to merge 21 commits into
JuliaGPU:mainfrom
fjbarter:rand_fill
Open

fjbarter wants to merge 21 commits into
JuliaGPU:mainfrom
fjbarter:rand_fill

Conversation

@fjbarter

Copy link
Copy Markdown

This is a reworked follow-up to #80. Thanks again @maleadt for the thorough review and benchmarks there, and for crediting the [0, 1) fix in GPUArrays.jl#872. The issues you and @nhz2 found were all totally valid, and have either been sorted or deleted upon the new dependence on PhiloxRNG.jl.

What I'm aiming for

  1. A fast, multithreaded, deterministic rand!/randn! for CPU arrays that outperforms Base's single-threaded fill, with the same output for any number of threads.
  2. An optional, fully deterministic RNG that is backend-agnostic: the same values on CPU and GPU, independent of launch configuration, thread count or how a fill is split. This comes from the reproducible simulation work we're doing at Birmingham, where runs need to reproduce exactly regardless of the hardware or backend they run on. As far as I can tell this isn't covered elsewhere: GPUArrays' new RNG is GPU-only and uses a fresh counter per call.

Changes since #80

  • GPUArrays remains the GPU front end. Without an explicit RNG, AK.rand!/AK.randn! on GPU arrays simply forward to Random.rand!/Random.randn!, so there is no second default GPU implementation.
  • No duplicated RNG maths. The opt-in CounterRNG is built on PhiloxRNG.jl (philox4x32_10, randn_f32/randn_f64, boxmuller). AK only adds the mapping from elements to counters, offset-based streaming, and boundary handling.
  • Both bugs fixed. The full 64-bit seed is now the Philox key, so distinct seeds always give distinct streams (21412 and 140572 included). Normals of each precision draw from separate key domains, so mixing rand!/randn! calls of different types never reuses counters; a regression test covers both mixed-call cases.
  • Earlier review points: randn! no longer synchronises (odd offsets and lengths are handled inside a single launch), and nothing widens to Float64 on the GPU path. Uniform floats stay in [0, 1).

CPU: StreamRNG (default for CPU arrays)

This is a Xoshiro256++ stream with bounded-time jump-ahead, where each task jumps directly to its first element with at most 64 power-of-two jumps. The output is identical for any thread count, and rand! reproduces Base's scalar rand(::Xoshiro, T) stream from the same state. randn! uses a ziggurat with exactly one stream output per sample: rare rejections draw from a local SplitMix64 sequence instead of the stream. I validated it with χ² tests on 2³² samples (full distribution, tail and consecutive pairs), using Base's randn! as a control

10M Float64, Apple M5 Pro:

Base (1 thread) AK 1 thread AK 2 threads AK 18 threads
rand! 3.6 ms 3.7 ms 1.8 ms 0.7 ms
randn! 10.0 ms 9.7 ms 5.1 ms 1.0 ms

Backend-agnostic: opt-in CounterRNG

CounterRNG now depends on PhiloxRNG.jl, calling its philox4x32_10 for the random blocks and its randn_f32/randn_f64/boxmuller for normals, rather than carrying any Philox or Box-Muller code of its own. Each element is a pure function of the seed and its position (offset + i), so values don't depend on backend, launch configuration or thread count, and two consecutive 5-element fills equal one 10-element fill. A seeded 10M fill is bit-identical between CPU (1 and 18 threads) and Metal. I haven't yet verified CUDA, AMD or oneAPI. The reason I want to keep this implementation is (as in the aforementioned goals) the usefulness of a 100% deterministic RNG regardless of backend. Nothing is duplicated, but AK handles the counter in such a way that successive calls produce a deterministic stream

As expected, it's memory-bound on the GPU, at the same throughput as the default path, i.e. Metal's Random.rand!/randn!, which use GPUArrays' Philox4x32-10 RNG (100M elements, Apple M5 Pro, GB/s):

(For reference, a write-only fill! of a Float32 array runs at 239 GB/s on the same device, so 32-bit fills from either RNG are at the memory bandwidth limit.)

AK CounterRNG Metal.rand!/randn! (GPUArrays)
rand! Float32 241 235
rand! Int32 242 242
rand! UInt8 134 132
randn! Float32 236 236
randn! Float16 167 158

New dependency: PhiloxRNG. This also adds back the Random standard library, which main recently dropped, for forwarding to Random.rand!/Random.randn!.

Please let me know what you think about the new structure. As mentioned, the deterministic behaviour is essential for some of our work and I think others will find it useful. If, however, you and the rest of the team think it doesn't belong here then we can find a home for it in another repo.

fjbarter added 21 commits March 16, 2026 01:06
…for fresh fills with simple calls. determinism obviously remains if an rng is passed
…mittent test failure. fence Float64 tests to CPU-only to avoid breaking CI on Metal and oneAPI
…en AK.rand!(x) is called. This gives stream-like behaviour without any on-device state but still faster than CURAND. Add RNGTest in prototyping for BigCrush and SmallCrush (Philox, SM64, and Threefry all now confirmed to pass in the AK implementation)
…owing CounterRNG which now must have an offset. if needed, AK.reset!(::CounterRNG) can be called to reset a streaming CounterRNG every time AK.rand! is called, if needed
… and even offsets + array lengths. Added convenience rand() and randn() convenience constructors using KernelAbstractions.allocate based on the provided backend, Type, and dims
…pen-interval helpers into utilities.jl and switch naming of internals. Simplify rand!/randn! wrappers and add convenience constructors for omitted rng, backend, or type, with backend-dependent defaults (Float64 on CPU, Float32 otherwise). Add explicit zero-arg guards so rand()/randn() require at least one dimension. Update rand.md with concise convenience semantics and examples, including type-only no-rng calls, plus doc entries for rand/randn. Expand tests to cover default-type dispatch, CPU fallback routes, typed no-rng overloads, and invalid-signature/kwarg throw behavior while preserving deterministic CounterRNG offset progression.
…rng, but contribute threaded deterministic CPU generation that outperforms Base, and the option for completely determinstic generation regardless of backend.
@maleadt

maleadt commented Dec 3, 2026

Copy link
Copy Markdown
Member

Thanks, but I'm not inclined to take a 3KLOC RNG that only serves the CPU back-end, which we're trying to deprecate in favor of a unified KA + PoCL approach... Wouldn't this be better suited as a Base/Random.jl contribution?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants