Repository navigation
Conversation
Device-side `Random.rand(T, dims)` is backed by Philox2x32-7 with a per-block-derived key (block id linearization XOR'd with the threaded seed). Two new placeholder intrinsics — `rng_counter(stream)` / `rng_advance(stream, n)` for the per-element counter and `rng_seed(stream)` / `rng_set_seed(stream, s)` for the per-stream key — sit alongside `rng_default()` (shared default stream) and `rng_stream()` (a fresh stream per call site). `lower_rng_state!` rewrites them to concrete SSA values and threads counter/seed through structured CFG via the high-level `thread_through_loop!` / `thread_through_branches!` helpers in `transform/control_flow.jl`, paying zero cost when no RNG intrinsic appears in the IR. Adds a `seed::UInt32` field to `KernelState` (previously a ghost), drawn from `RandomDevice` per launch. `lower_rng_state!` consumes it to seed the default stream so bare `rand()` produces uncorrelated output across launches without any explicit seeding. In-kernel `Random.seed!(default_rng(), s)` overrides per stream. Non-default `DeviceRNG()` streams use the stream-ID mix in `rng_key` for cross-stream divergence, and also pick up the host seed. Host-side: `cuTile.RNG(seed, counter)` wraps a `(seed, counter)` pair that drives `Random.rand!(::RNG, ::CuArray)` via `rand_fill_*` fill kernels. The fill kernels take `(seed, counter)` as explicit arguments, call `Random.seed!` + `rng_advance` at entry, and write `RAND_FILL_TILE` elements per block via `store_partition_view` (which silently clips OOB elements, so any `length(A)` is supported). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Philox core stays strictly UInt32-typed; output types are produced by
a small `finalize_tile` dispatch table (4 methods covering 9 types) that
either bitcasts (signless same-width), truncates (narrower ints), or
runs `u01` (floats — Float16/BFloat16 narrow from Float32). Host-side,
the per-T `rand_fill_T` functions collapse to one parametric
`rand_fill_kernel{T}`, and the user surfaces (`Random.rand` overlays,
explicit-stream methods, `cuTile.rand`/`rand!`) consolidate to a single
`RandTypes` union.
Also fixes `similar_type` to handle UnionAll Tile types: without an
explicit `<:Tile{T}` overload, `similar_type(Tile{UInt32, S} where S,
Int32)` would fall through to the scalar fallback and return `Int32`,
which broke `bitcast`/`trunci` tfunc inference (the chain widened to a
scalar and `store(out, pid, t)` dispatched to the scalar-value path).
Adds `rand_uint64_tile`, which packs both Philox outputs (`c1`, `c2`)
per call into a UInt64 — same Philox cost per element as the existing
UInt32 path (which discards `c2`). Three new `finalize_tile` methods
dispatch on `Tile{UInt64}`: identity for UInt64, `bitcast` for Int64,
and a `u01(::Type{Float64}, ::Tile{UInt64})` that uses the
GPUArrays/CUDA.jl bit-pattern construction (avoids costly
`Float64(::UInt64)` on consumer GPUs and forces the low mantissa bit
set to keep the (0, 1] log-safe convention).
`rand_tile` now dispatches on output width via two `Rand32Types` /
`Rand64Types` unions; everything else (overlays, host kernel, surfaces)
already routes through `RandTypes` so picks up the new types
automatically.
For `n ≥ 2`, do `n/2` Philox calls and `cat((c1, c2), 1)` instead of `n`
calls discarding `c2`. The cyclic tile distribution makes the cat a
register-level no-op — verified on the `rand_fill_kernel` SASS
(`RAND_FILL_TILE=512`):
UInt32 base → cat Float32 base → cat
Total SASS 176 → 120 (-32%) 184 → 144 (-22%)
IMAD.HI (mulhii) 20 → 11 16 → 13
IMAD (muli) 50 → 30 46 → 33
SHFL 0 → 0 0 → 0
LDS/STS 0 → 0 0 → 0
STG.E 4 → 4 4 → 4
Float32 (and Float16/BFloat16) shows a smaller relative win because the
per-element FMA conversion is unchanged — only Philox compute halves.
The 0D scalar form keeps the single-call shape (no second lane to place).
The host counter advance stays at the logical element count `n` (not the
actual `n/2` Philox calls), keeping the host advance scheme T-agnostic at
the cost of using half the counter range — 2^31 still usable per stream.
Output bytes for `cuTile.RNG(seed)` differ from the previous two commits:
the first half of each tile is unchanged, the second half is now `c2` of
the same counter range instead of `c1` of the next range. No test depends
on byte-exact output across versions; full suite passes (1836/1836).
Generalizes tier 3's cat-style packing one level deeper. Each Philox
call yields 64 bits (2 UInt32s, both used after tier 3); now we also
shrink the raw UInt32 tile by the output width's `fan_out`:
output T raw UInt32s Philox calls (n=512) IMAD.HI in SASS
32-bit n n/2 11
16-bit n/2 n/4 5
8-bit n/4 n/8 7
Refactor structure (per Tim's "localize the bit-packing" suggestion):
all "use more bits per call" logic lives in `rand_uint{8,16,32,64}_tile`.
Other types route through `underlying_rand` to the matching-width
unsigned core, then `finalize_tile` does a same-width conversion only
(bitcast for signed, `u01` for floats). The per-output-width fan_out is
encoded once in `underlying_rand`'s dispatch table and never repeated.
Float16 / BFloat16 get fresh `u01(::Type, ::Tile{UInt16})` paths using
the exponent trick (top mantissa bits | exp-for-[1,2) | low bit set,
bitcast, subtract 1) rather than narrowing from a Float32 u01 — the
narrow path needed twice the Philox bits per output. Float32/Float64
u01s are unchanged.
For `n < fan_out` (0D scalar UInt16; 0D / 2-elt UInt8) the natural
split overproduces; `extract` takes the prefix.
SASS check (rand_fill_kernel, RAND_FILL_TILE=512, sm_120): zero added
warp shuffles or shared-mem traffic at any width — same register-level
no-op argument as tier 3, just split-then-cat now that we also unpack
sub-UInt32 chunks.
(Note: BFloat16 `.-` (broadcast subtract) hits a Tile IR normalizer
gap — `sub_float` for `Tile{BFloat16}` operands isn't recognized while
the direct `-` overload is. Worked around with direct `-`; MWE at
/tmp/mwe_bf16_dot_minus.jl.)
Explains the underlying_rand → finalize_tile split (width-matched Philox core + same-width type conversion), where to add a new same- width output type, and how the structure extends to randn.
Replaces the broadcast_to(Tile(literal), shape) pattern with the
language-level fill(literal, shape) (and the variadic fill(literal, n)
where the shape is a single dim). Removes the bc_const / bc_const_f32
helpers — they're now one-liners that fill subsumes. Same SASS;
cleaner intent ("make a shape-sized tile of this value" vs "broadcast
this 0D tile to a wider shape").
Also extends `constant_to_bytes` (compiler/codegen/values.jl) to
generically handle any Integer / AbstractFloat eltype rather than
hardcoding 32/64-bit widths — needed for the new fill(::UInt16, ...)
and fill(::Float16/BFloat16, ...) constants in the new u01 paths.
The two type-specific cases for Bool stay (it's the one type whose
byte representation isn't `reinterpret`-equivalent).
|
Now supports multiple types, reinterpreting the 2xUInt32 data we get from the Philox RNG (which is something CUDA.jl's This is getting pretty feature-complete for an initial version, I think. |
|
Some final benchmark results, by Claude. Hardware: RTX 5080 (Blackwell, sm 12.0, 84 SMs, ~65 MiB L2, 960 GB/s DRAM peak) Memory-bound:
|
| RNG | per-call | GB/s | % of 960 GB/s peak |
|---|---|---|---|
| cuTile.RNG | 1.19 ms | 902 | 94 % |
| CUDA.RNG (GPUArrays) | 1.19 ms | 902 | 94 % |
| cuRAND.LibraryRNG | 1.19 ms | 902 | 94 % |
| PhiloxRNG.jl | 1.19 ms | 902 | 94 % |
| cuRAND.NativeRNG | 3.97 ms | 270 | 28 % |
At DRAM saturation, every production RNG is mechanically tied at ~94 %
of the RTX 5080's bandwidth peak. cuRAND.NativeRNG (CUDA.jl's per-warp
shared-memory Philox) is 3.4× slower because its state design caps it at
1 UInt64 per call per warp.
In L2 (16 MiB Float32) — cuTile is fastest
| RNG | per-call | vs cuTile |
|---|---|---|
| cuTile.RNG | 7.98 µs | — |
| CUDA.RNG (GPUArrays) | 9.75 µs | +22 % |
| PhiloxRNG.jl | 8.82 µs | +11 % |
| cuRAND.LibraryRNG | 12.31 µs | +54 % |
| cuRAND.NativeRNG | 62.81 µs | +687 % |
Type sweep at saturation (256 MiB / 128 MiB / 64 MiB, GB/s)
| Type | cuTile | GPUArrays | cuRAND.Lib | NativeRNG |
|---|---|---|---|---|
| Float32 | 905 | 908 | 917 | 267 |
| Float64 | 906 | 912 | 502 | 534 |
| Float16 | 897 | 905 | n/a | 134 |
| BFloat16 | 897 | 378 | n/a | 134 |
| UInt32 | 904 | 908 | 912 | 267 |
| UInt64 | 907 | 910 | n/a | 534 |
| UInt16 | 899 | 775 | n/a | 134 |
| UInt8 | 787 | 639 | n/a | 67 |
Three things stand out:
- BFloat16: cuTile is 2.4× faster than GPUArrays. GPUArrays'
BatchedRandTypes
union excludes BFloat16, so it falls through to a generic per-element kernel.
cuTile routes BFloat16 through the same UInt16 core as Float16 and stays at peak. - Float64: cuRAND.LibraryRNG drops to 502 GB/s. The wrapper picks the XORWOW
default, which emits 32 bits/call → 2 calls/Float64. - Small-int types: cuTile is the only generator that holds peak across
UInt8/UInt16/BFloat16. cuRAND.Library doesn't support these types at all.
Compute-bound: K-mix kernel (cuRANDDx in scope)
To isolate Philox throughput from DRAM, each thread does K Philox calls,
XOR-folds them in registers, and writes one UInt32. With K large, the
single 4-byte write is negligible; we measure raw Philox math.
cuRANDDx (NVIDIA's device-side header library, equivalent of cuFFTDx for
RNGs) is included for real here: I compiled
curanddx_kmix.cu to a CUBIN with nvcc -arch=sm_120 and called the
entry points directly via cudacall.
Throughput is in G32/s = billions of 32-bit Philox outputs / second.
| Generator | K=1 | K=2 | K=4 | K=8 | K=16 | K=32 | K=64 |
|---|---|---|---|---|---|---|---|
| cuTile.RNG (Phx2x32-7) | 207 | 349 | 593 | 1059 | 1376 | 1790 | 2122 ⭐ |
| cuRANDDx Phx4x32-7 | 591 | 925 | 1290 | 1641 | 1868 | 2018 | 2080 |
| GPUArrays-style 4x32-10 | 475 | 734 | 1001 | 1204 | 1338 | 1409 | 1455 |
| cuRANDDx Phx4x32-10 | 507 | 747 | 985 | 1169 | 1269 | 1328 | 1364 |
| PhiloxRNG.jl 4x32-10 | 427 | 635 | 839 | 989 | 1114 | 1142 | 1181 |
Asymptote (K=64) per-round normalisation
Each Philox round costs the same mul32 + xor work per output regardless
of lane count or round count, so dividing by Rounds gives a fair "SM
peak Philox math" comparison:
| Generator | Rounds | G32/s | G32/s per round |
|---|---|---|---|
| cuTile (Phx2x32-7) | 7 | 2122 | 303 |
| cuRANDDx (Phx4x32-7) | 7 | 2080 | 297 |
| GPUArrays-style (4x32-10) | 10 | 1455 | 146 |
| cuRANDDx (Phx4x32-10) | 10 | 1364 | 136 |
| PhiloxRNG.jl (4x32-10) | 10 | 1181 | 118 |
Two things stand out:
- cuTile and cuRANDDx are both at the SM's per-round ceiling (~300 G32/s
per round). Tile IR + Julia codegen is competitive with NVCC at the
instruction-mix level. - At equal algorithm (Phx4x32-10), the Julia-emitted kernel beats
NVIDIA's cuRANDDx by 7 % (1455 vs 1364 G32/s). cuRANDDx'sRNGthread
state advances a 128-bit counter on everygenerate4(); the Julia kernel
computes the next counter(tid, k, 0, 0)directly in registers.
cuTile is slowest at K=1 because of the launch overhead.
Counter-based PRNG just like CUDA.jl, but using tiles as state instead of shared memory. Uses intrinsics to allocate RNG streams and states, expanded/lowered by a dedicated pass.
Performance is good, memory-bound:
Fixes #189