Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
20eea2c
on-device rand! with three options for stateless counter-based RNG
fjbarter Mar 16, 2026
3c3e81a
add convenience for AK.rand!(X), and single UInt64 seed construction …
fjbarter Mar 16, 2026
f590d5e
just use foreachindex for the kernel now that it is simple enough
fjbarter Mar 16, 2026
9e471d6
finalise tests and docs
fjbarter Mar 16, 2026
65caf10
ensure deteminism in convenience tests by avoiding race causing inter…
fjbarter Mar 17, 2026
3d1e0c0
fix Random dep for use with julia v1.10
fjbarter Mar 17, 2026
48cd247
add Bool scalar support with isodd() on a UInt32
fjbarter Mar 17, 2026
68e03c3
add support for Float16, UInt8, UInt16, Int8, Int16 (was bored)
fjbarter Mar 17, 2026
8677d84
Add more faithful seed-key mapping for Philox, and improve thoroughne…
fjbarter Mar 18, 2026
d687e2a
streaming rng by now including an offset, incremented by length(x) wh…
fjbarter Mar 23, 2026
71a62d4
style update + remove AbstractCounterRNG type in favour of purely all…
fjbarter Mar 24, 2026
42a434e
update tests and docs to match new CounterRNG interface
fjbarter Mar 24, 2026
a9582a0
initial randn!
fjbarter Mar 25, 2026
61aa11d
ensure compile-time initial index bias, now beating CUDA for both odd…
fjbarter Mar 26, 2026
9abe388
attempt to fix oneAPI test precompilation hang with Julia v1.10 by di…
fjbarter Mar 26, 2026
841bafb
fix Threefry UInt32 device arithmetic to avoid breaking on Metal
fjbarter Mar 26, 2026
39e089f
expand rand/randn convenience APIs and align docs/tests. Move randn o…
fjbarter Mar 27, 2026
9595086
document rand_uint and CounterRNGAlgorithm properly, improve RNG docs…
fjbarter Mar 28, 2026
5dc7373
fast math for sincos and log for box-muller, avoid float64 widening, …
fjbarter Nov 18, 2026
3f72dbf
respond to pr #80 review: forward to GPUArrays for on-device rng, but…
fjbarter Nov 30, 2026
8c5c29e
Merge remote-tracking branch 'upstream/main' into rand_fill
fjbarter Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
1 change: 1 addition & 0 deletions docs/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
203 changes: 203 additions & 0 deletions docs/src/api/rand.md
Original file line number Diff line number Diff line change
@@ -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
```
3 changes: 3 additions & 0 deletions prototype/RNGTest/Project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[deps]
AcceleratedKernels = "6a4ca0a5-0e36-4168-a932-d9be78d558f1"
RNGTest = "97cc5700-e6cb-5ca1-8fb2-7f6b45264ecd"
33 changes: 33 additions & 0 deletions prototype/RNGTest/README.md
Original file line number Diff line number Diff line change
@@ -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`).
26 changes: 26 additions & 0 deletions prototype/RNGTest/run_bigcrush.jl
Original file line number Diff line number Diff line change
@@ -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))
23 changes: 23 additions & 0 deletions prototype/RNGTest/run_smallcrush.jl
Original file line number Diff line number Diff line change
@@ -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)
Loading