Skip to main content

ruxla_prims/
random.rs

1//! `threefry2x32`, the hash of JAX's random numbers (`jax.random`), as a
2//! primitive: JAX lowers it with rolled loops on CPU and unrolled on GPU,
3//! where a loop of 5 iterations would launch kernels in every iteration.
4
5use std::collections::HashMap;
6use std::sync::{Arc, Mutex, OnceLock, PoisonError};
7
8use ruxla_ir::batching::{BatchCx, Batched};
9use ruxla_ir::lowering::{HloValue, LowerCx, Platform};
10use ruxla_ir::{
11    AVal, Atom, DType, Error, EvalCx, Function, HostArray, Literal, Params, Prim, Primitive,
12    Result, Shape, Var,
13};
14
15use crate::batching::bdim_at_front;
16use crate::control::SCAN;
17use crate::elementwise::{
18    ADD, CONVERT_ELEMENT_TYPE, OR, SHIFT_LEFT, SHIFT_RIGHT_LOGICAL, SUB, XOR,
19};
20use crate::structural::{BROADCAST_IN_DIM, RESHAPE, SLICE};
21use crate::util::{Emit, wrong_params};
22
23/// `threefry2x32`.
24#[derive(Debug)]
25pub(crate) struct Threefry2x32;
26/// The threefry2x32 hash of the counters `(x1, x2)` with the key
27/// `(k1, k2)`, elementwise; operands of rank 0 are broadcast to the shape
28/// of the others, as in JAX.
29pub static THREEFRY2X32: Prim = Prim::new(&Threefry2x32);
30
31use ruxla_kernels::random::{ROTATIONS, threefry2x32 as hash};
32
33/// The shape of the result: that of the operands of nonzero rank, which
34/// must agree.
35fn result_shape(name: &'static str, inputs: &[AVal]) -> Result<Shape> {
36    let mut shape: Option<&Shape> = None;
37    for a in inputs {
38        if a.dtype != DType::U32 {
39            return Err(Error::type_error(
40                name,
41                format!("the operands must be u32, got {a}"),
42            ));
43        }
44        if a.shape.rank() == 0 {
45            continue;
46        }
47        match shape {
48            Some(s) if *s != a.shape => {
49                return Err(Error::type_error(
50                    name,
51                    format!("incompatible shapes [{s}] and [{}]", a.shape),
52                ));
53            }
54            _ => shape = Some(&a.shape),
55        }
56    }
57    Ok(shape.cloned().unwrap_or_else(Shape::scalar))
58}
59
60impl Primitive for Threefry2x32 {
61    fn name(&self) -> &'static str {
62        "threefry2x32"
63    }
64    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
65        if !matches!(params, Params::None) {
66            return Err(wrong_params(self.name()));
67        }
68        if inputs.len() != 4 {
69            return Err(Error::type_error(self.name(), "expected 4 operands"));
70        }
71        let shape = result_shape(self.name(), inputs)?;
72        let aval = AVal::new(shape, DType::U32);
73        Ok(vec![aval.clone(), aval])
74    }
75    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
76        let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
77        let shape = result_shape(self.name(), &avals)?;
78        let n = shape.size();
79        let values: Vec<Vec<u32>> = inputs
80            .iter()
81            .map(|x| {
82                x.to_vec::<u32>()
83                    .map_err(|e| Error::Malformed(e.to_string()))
84            })
85            .collect::<Result<_>>()?;
86        let at = |v: &[u32], i: usize| if v.len() == 1 { v[0] } else { v[i] };
87        let (mut a, mut b) = (Vec::with_capacity(n), Vec::with_capacity(n));
88        for i in 0..n {
89            let (y1, y2) = hash(
90                at(&values[0], i),
91                at(&values[1], i),
92                at(&values[2], i),
93                at(&values[3], i),
94            );
95            a.push(y1);
96            b.push(y2);
97        }
98        Ok(vec![
99            HostArray::from_vec(a, shape.clone()),
100            HostArray::from_vec(b, shape),
101        ])
102    }
103    /// Elementwise with broadcasting: every operand gets the batch dimension
104    /// first and the full shape.
105    fn batch(
106        &'static self,
107        cx: &mut dyn BatchCx,
108        inputs: &[Batched],
109        params: &Params,
110    ) -> Result<Vec<Batched>> {
111        let avals: Vec<AVal> = inputs
112            .iter()
113            .map(|x| {
114                let mut a = x.atom.aval();
115                if let Some(d) = x.bdim {
116                    a.shape.remove(d);
117                }
118                a
119            })
120            .collect();
121        let example = result_shape(self.name(), &avals)?;
122        let mut full = vec![cx.axis_size()];
123        full.extend_from_slice(&example);
124        let mut atoms = Vec::new();
125        for x in inputs {
126            let front = bdim_at_front(cx, x)?;
127            let a = front.aval();
128            atoms.push(if a.shape.dims() == &full[..] {
129                front
130            } else {
131                // `[n]` (an example of rank 0) to `[n, example...]`.
132                cx.bind(
133                    BROADCAST_IN_DIM,
134                    &[front],
135                    Params::BroadcastInDim {
136                        shape: full.clone().into(),
137                        broadcast_dimensions: vec![0],
138                    },
139                )?
140                .remove(0)
141            });
142        }
143        let outs = cx.bind(THREEFRY2X32, &atoms, params.clone())?;
144        Ok(outs
145            .into_iter()
146            .map(|atom| Batched {
147                atom,
148                bdim: Some(0),
149            })
150            .collect())
151    }
152    /// An out-of-line function, as JAX emits it: with rolled loops on CPU,
153    /// unrolled elsewhere.
154    fn lower(
155        &self,
156        cx: &mut dyn LowerCx,
157        inputs: &[HloValue],
158        _: &Params,
159        outputs: &[AVal],
160    ) -> Result<Vec<HloValue>> {
161        let in_avals: Vec<AVal> = inputs.iter().map(|x| x.aval.clone()).collect();
162        // The functions are kept for the life of the process: the lowering
163        // emits a function once per function object, so they must not be
164        // dropped and their addresses reused.
165        type Cache = HashMap<(Platform, Vec<AVal>), Arc<Function>>;
166        static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
167        let key = (cx.platform(), in_avals);
168        let cached = CACHE
169            .get_or_init(Default::default)
170            .lock()
171            .unwrap_or_else(PoisonError::into_inner)
172            .get(&key)
173            .cloned();
174        let f = match cached {
175            Some(f) => f,
176            None => {
177                let f = Arc::new(lowering_function(key.0, &key.1)?);
178                CACHE
179                    .get_or_init(Default::default)
180                    .lock()
181                    .unwrap_or_else(PoisonError::into_inner)
182                    .entry(key)
183                    .or_insert(f)
184                    .clone()
185            }
186        };
187        let symbol = cx.function(&f, "threefry2x32")?;
188        Ok(cx.op("func.call", inputs, &format!("callee = @{symbol}"), outputs))
189    }
190}
191
192/// The function that the lowering calls for operands of types `in_avals`:
193/// the hash with rolled loops on CPU, unrolled on GPU (exposed for tests,
194/// which evaluate both).
195///
196/// # Errors
197///
198/// Returns an error if the operands are not `u32` of compatible shapes.
199#[doc(hidden)]
200pub fn lowering_function(platform: Platform, in_avals: &[AVal]) -> Result<Function> {
201    match platform {
202        Platform::Cpu => rolled(in_avals),
203        Platform::Gpu => unrolled(in_avals),
204    }
205}
206
207impl Emit {
208    /// `x` broadcast to `shape` (if it has rank 0 and `shape` does not).
209    fn broadcast(&mut self, x: &Atom, shape: &Shape) -> Result<Atom> {
210        if x.aval().shape == *shape {
211            return Ok(x.clone());
212        }
213        Ok(self
214            .apply(
215                BROADCAST_IN_DIM,
216                std::slice::from_ref(x),
217                Params::BroadcastInDim {
218                    shape: shape.clone(),
219                    broadcast_dimensions: Vec::new(),
220                },
221            )?
222            .remove(0))
223    }
224
225    /// The keys with the same shape (one of rank 0 broadcast to the shape
226    /// of the other), and the third key `k1 ^ k2 ^ 0x1BD11BDA`.
227    fn keys(&mut self, k1: &Atom, k2: &Atom) -> Result<(Atom, Atom, Atom)> {
228        let shape = if k1.aval().shape.rank() > 0 {
229            k1.aval().shape
230        } else {
231            k2.aval().shape
232        };
233        let k1 = self.broadcast(k1, &shape)?;
234        let k2 = self.broadcast(k2, &shape)?;
235        let k = self.op(XOR, &[k1.clone(), k2.clone()])?;
236        let c = self.broadcast(&u32_lit(0x1BD1_1BDA), &shape)?;
237        let ks2 = self.op(XOR, &[k, c])?;
238        Ok((k1, k2, ks2))
239    }
240
241    /// `x + y` with `y` broadcast to the shape of `x`.
242    fn add(&mut self, x: &Atom, y: &Atom) -> Result<Atom> {
243        let shape = x.aval().shape;
244        let y = self.broadcast(y, &shape)?;
245        self.op(ADD, &[x.clone(), y])
246    }
247
248    /// One round: `x0 += x1; x1 = rotl(x1, r) ^ x0`, with the rotation `r`
249    /// and `32 - r` as scalars broadcast to the shape (as JAX's
250    /// `rotate_left` computes it).
251    fn round(
252        &mut self,
253        x: [Atom; 2],
254        r: &Atom,
255        r_complement: &Atom,
256        shape: &Shape,
257    ) -> Result<[Atom; 2]> {
258        let [x0, x1] = x;
259        let x0 = self.op(ADD, &[x0, x1.clone()])?;
260        let rb = self.broadcast(r, shape)?;
261        let left = self.op(SHIFT_LEFT, &[x1.clone(), rb])?;
262        let cb = self.broadcast(r_complement, shape)?;
263        let right = self.op(SHIFT_RIGHT_LOGICAL, &[x1, cb])?;
264        let rotated = self.op(OR, &[left, right])?;
265        let x1 = self.op(XOR, &[x0.clone(), rotated])?;
266        Ok([x0, x1])
267    }
268}
269
270fn u32_lit(v: u32) -> Atom {
271    Atom::Lit(Literal::new(HostArray::scalar(v)))
272}
273
274fn i32_lit(v: i32) -> Atom {
275    Atom::Lit(Literal::new(HostArray::scalar(v)))
276}
277
278/// The inputs of a lowering function and the shape of the result.
279fn inputs(in_avals: &[AVal]) -> Result<(Vec<Var>, Vec<Atom>, Shape)> {
280    let shape = result_shape("threefry2x32", in_avals)?;
281    let vars: Vec<Var> = in_avals.iter().cloned().map(Var::new).collect();
282    let atoms = vars.iter().cloned().map(Atom::Var).collect();
283    Ok((vars, atoms, shape))
284}
285
286/// The hash with JAX's rolled loops (`fori_loop` over the 5 groups of 4
287/// rounds, carrying the rotations), the same equations as the generic
288/// implementation traces.
289fn rolled(in_avals: &[AVal]) -> Result<Function> {
290    let (invars, args, shape) = inputs(in_avals)?;
291    let (k1, k2, c1, c2) = (&args[0], &args[1], &args[2], &args[3]);
292    let mut e = Emit { eqns: Vec::new() };
293    let (k1, k2, ks2) = &e.keys(k1, k2)?;
294    let x0 = e.add(c1, k1)?;
295    let x1 = e.add(c2, k2)?;
296    let rot = |v: [u32; 4]| HostArray::from_vec(v.to_vec(), [4]);
297    let rot_vars = [
298        Var::new(AVal::new([4], DType::U32)),
299        Var::new(AVal::new([4], DType::U32)),
300    ];
301
302    // The body: (i, x0, x1, ks0, ks1, ks2, rot0, rot1) -> the next state.
303    let key_aval = |a: &Atom| a.aval();
304    let carry_avals = [
305        AVal::scalar(DType::I32),
306        x0.aval(),
307        x1.aval(),
308        key_aval(k2),
309        ks2.aval(),
310        key_aval(k1),
311        AVal::new([4], DType::U32),
312        AVal::new([4], DType::U32),
313    ];
314    let bvars: Vec<Var> = carry_avals.iter().cloned().map(Var::new).collect();
315    let b: Vec<Atom> = bvars.iter().cloned().map(Atom::Var).collect();
316    let mut be = Emit { eqns: Vec::new() };
317    let next_i = be.op(ADD, &[b[0].clone(), i32_lit(1)])?;
318    let mut x = [b[1].clone(), b[2].clone()];
319    for j in 0..4 {
320        let s = be
321            .apply(
322                SLICE,
323                std::slice::from_ref(&b[6]),
324                Params::Slice {
325                    start_indices: vec![j],
326                    limit_indices: vec![j + 1],
327                    strides: vec![1],
328                },
329            )?
330            .remove(0);
331        let r = be
332            .apply(
333                RESHAPE,
334                &[s],
335                Params::Reshape {
336                    new_sizes: Shape::scalar(),
337                },
338            )?
339            .remove(0);
340        let rc = be.op(SUB, &[u32_lit(32), r.clone()])?;
341        x = be.round(x, &r, &rc, &shape)?;
342    }
343    let step_i = be.op(ADD, &[b[0].clone(), i32_lit(1)])?;
344    let step = be
345        .apply(
346            CONVERT_ELEMENT_TYPE,
347            &[step_i],
348            Params::Convert {
349                new_dtype: DType::U32,
350            },
351        )?
352        .remove(0);
353    let [x0n, x1n] = x;
354    let x0n = be.add(&x0n, &b[3])?;
355    let x1n = be.add(&x1n, &b[4])?;
356    let x1n = be.add(&x1n, &step)?;
357    let body = Function {
358        constvars: Vec::new(),
359        invars: bvars,
360        eqns: be.eqns,
361        outvars: vec![
362            next_i,
363            x0n,
364            x1n,
365            b[4].clone(),
366            b[5].clone(),
367            b[3].clone(),
368            b[7].clone(),
369            b[6].clone(),
370        ],
371    };
372    let outs = e.apply(
373        SCAN,
374        &[
375            i32_lit(0),
376            x0,
377            x1,
378            k2.clone(),
379            ks2.clone(),
380            k1.clone(),
381            Atom::Var(rot_vars[0].clone()),
382            Atom::Var(rot_vars[1].clone()),
383        ],
384        Params::Scan {
385            body: Arc::new(body),
386            length: 5,
387            reverse: false,
388            num_consts: 0,
389            num_carry: 8,
390        },
391    )?;
392    let [rv0, rv1] = rot_vars;
393    Ok(Function {
394        constvars: vec![(rv0, rot(ROTATIONS[0])), (rv1, rot(ROTATIONS[1]))],
395        invars,
396        eqns: e.eqns,
397        outvars: vec![outs[1].clone(), outs[2].clone()],
398    })
399}
400
401/// The hash with the 20 rounds unrolled, as JAX lowers it on GPU.
402fn unrolled(in_avals: &[AVal]) -> Result<Function> {
403    let (invars, args, shape) = inputs(in_avals)?;
404    let (k1, k2, c1, c2) = (&args[0], &args[1], &args[2], &args[3]);
405    let mut e = Emit { eqns: Vec::new() };
406    let (k1, k2, ks2) = &e.keys(k1, k2)?;
407    let ks = [k1.clone(), k2.clone(), ks2.clone()];
408    let mut x = [e.add(c1, &ks[0])?, e.add(c2, &ks[1])?];
409    for i in 0..5 {
410        for &r in &ROTATIONS[i % 2] {
411            x = e.round(x, &u32_lit(r), &u32_lit(32 - r), &shape)?;
412        }
413        let [x0, x1] = x;
414        let x0 = e.add(&x0, &ks[(i + 1) % 3])?;
415        let x1 = e.add(&x1, &ks[(i + 2) % 3])?;
416        let x1 = e.add(&x1, &u32_lit(i as u32 + 1))?;
417        x = [x0, x1];
418    }
419    let [x0, x1] = x;
420    Ok(Function {
421        constvars: Vec::new(),
422        invars,
423        eqns: e.eqns,
424        outvars: vec![x0, x1],
425    })
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    /// The known-answer test of the Threefry paper (Random123), which JAX
433    /// also checks.
434    #[test]
435    fn known_answers() {
436        assert_eq!(hash(0, 0, 0, 0), (0x6b20_0159, 0x99ba_4efe));
437        assert_eq!(
438            hash(0xffff_ffff, 0xffff_ffff, 0xffff_ffff, 0xffff_ffff),
439            (0x1cb9_96fc, 0xbb00_2be7)
440        );
441        assert_eq!(
442            hash(0x1319_8a2e, 0x0370_7344, 0x243f_6a88, 0x85a3_08d3),
443            (0xc492_3a9c, 0x483d_f7a0)
444        );
445    }
446
447    #[test]
448    fn the_lowering_functions_are_well_typed() {
449        let avals = [
450            AVal::scalar(DType::U32),
451            AVal::scalar(DType::U32),
452            AVal::new([3], DType::U32),
453            AVal::new([3], DType::U32),
454        ];
455        for platform in [Platform::Cpu, Platform::Gpu] {
456            let f = lowering_function(platform, &avals).unwrap();
457            f.check().unwrap();
458            assert_eq!(f.out_avals(), [avals[2].clone(), avals[2].clone()]);
459        }
460    }
461}