JAX and tinygrad generate random numbers with Threefry-2x32 (20 rounds), a counter-based generator: the output is a pure function of a 64-bit key and a 64-bit counter, so it can be computed in parallel and inside any compiled program. Implement it using arithmetic only.
threefry2x32(key, counter): key = (k0, k1) and counter = (c0, c1) are 32-bit words given as integers (either unsigned in [0,232) or signed). Return the two output words (x0, x1) as unsigned integers in [0,232).
The algorithm, with every addition modulo 232:
- Key schedule: ks0=k0, ks1=k1 and ks2=k0⊕k1⊕0x1BD11BDA.
- Start with x0=c0+ks0 and x1=c1+ks1.
- Do 5 groups of 4 rounds. Group g=0,…,4 uses the rotation amounts (13,15,26,6) when g is even and (17,29,16,24) when g is odd. A round with rotation r is x0←x0+x1, then x1←rotl(x1,r)⊕x0.
- After group g, inject the key: x0←x0+ks(g+1)mod3 and x1←x1+ks(g+2)mod3+g+1.
Arithmetic only: use +, -, *, //, %, comparisons and integer constants, never ^, &, |, ~, << or >>. A test runs your function on an integer type that raises an error if a bitwise operator is used; with such inputs, return values of that type (for example by reducing with %), not plain ints.