Random numbers
On this page

Random numbers: typeshade/random

typeshade/random is the second common module (Rule 11.20). It holds the generators and the hashes a kernel draws from, and the fills a host calls. Each one gives the same bits on every tier.

1. The device face

A "use typeshade" file imports the three scalar helpers and calls them in its own kernel or entry. The draw in the sample depends on the seed and the index only, so the tier and the dispatch shape do not change it.

jitter.shade.ts
"use typeshade";
import { xorshift32, hash32, uniform } from "typeshade/random";
export function jitter(out: array<f32>, seed: u32): void {
for (let i: u32 = 0; i < out.length; i++) {
out[i] = uniform(hash32(seed ^ i));
}
}
FunctionWhat it does
xorshift32(state: u32): u32One step of xorshift32. A zero state stays zero, so seed it with a word that is not zero.
hash32(x: u32): u32A 32-bit integer finaliser, for a draw from an index with no state. hash32(0) is 0.
uniform(word: u32): f32The 24 high bits of word as an f32 in [0, 1). The value is exact in f32, so one word gives one number on every tier.

2. The host face

Host code imports the same subpath. The three helpers are there too, as functions that run on the CPU, and three more stand beside them. generator(seed) uses the same hash32 and uniform, so a shuffle on the host and a draw on the device from one seed agree bit for bit.

host.ts
import { fillUniform, generator } from 'typeshade/random';
import { resident } from 'typeshade/runtime';
const noise = resident(1024, 'f32');
fillUniform(noise, 12345); // element i is uniform(hash32(12345 ^ i))
const draw = generator(12345); // the same draws on the host
const first = draw();
FunctionWhat it does
fillUniform(out, seed: u32)A kernel function. Element i is uniform(hash32(seed ^ i)), a draw in [0, 1).
fillWords(out: array<u32>, seed: u32)A kernel function. Element i is hash32(seed ^ i).
generator(seed: u32): () => numberPlain JavaScript. Each call gives the next draw of a counter that starts at 0.

3. What it is held to

The compiler's tests hold fillUniform(out, seed) on the CPU tier to generator(seed) element for element. Its differential gate holds the two fills on WebGPU and WebGL2 to the CPU oracle.

4. Not yet

A normal distribution, a counter-based generator with a larger state such as Philox or PCG, and a permutation are later deliveries.

Back to the language overview

Edit this page Report a problem