Skip to main content

ruxla_ir/
function.rs

1//! Functions of the IR: variables, equations, and parameters.
2
3use std::collections::HashSet;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, Ordering};
6
7use ruxla_kernels::DType;
8use ruxla_kernels::array::{DotDims, GatherDims, GatherScatterMode, ScatterDims};
9use ruxla_kernels::fft::FftType;
10use ruxla_kernels::window::ConvDims;
11
12use crate::error::{Error, Result};
13use crate::host::HostArray;
14use crate::primitive::Prim;
15use crate::shape::{AVal, Shape};
16
17/// Where in the user's code an equation was created.
18pub type SrcLoc = &'static std::panic::Location<'static>;
19
20/// A variable: a unique id and an abstract value.
21#[derive(Clone, PartialEq, Eq, Hash, Debug)]
22pub struct Var {
23    id: u64,
24    aval: AVal,
25}
26
27impl Var {
28    /// Creates a variable with a fresh id.
29    pub fn new(aval: AVal) -> Self {
30        static NEXT: AtomicU64 = AtomicU64::new(0);
31        Self {
32            id: NEXT.fetch_add(1, Ordering::Relaxed),
33            aval,
34        }
35    }
36
37    /// Returns the id.
38    pub fn id(&self) -> u64 {
39        self.id
40    }
41
42    /// Returns the abstract value.
43    pub fn aval(&self) -> &AVal {
44        &self.aval
45    }
46}
47
48/// A scalar constant used directly as an operand.
49#[derive(Clone, PartialEq, Debug)]
50pub struct Literal(HostArray);
51
52impl Literal {
53    /// Creates a literal.
54    ///
55    /// # Panics
56    ///
57    /// Panics if `value` is not a scalar.
58    #[track_caller]
59    pub fn new(value: HostArray) -> Self {
60        assert_eq!(value.shape().rank(), 0, "literals must be scalars");
61        Self(value)
62    }
63
64    /// Returns the value.
65    pub fn value(&self) -> &HostArray {
66        &self.0
67    }
68}
69
70/// An operand: a variable or a literal.
71#[derive(Clone, PartialEq, Debug)]
72pub enum Atom {
73    /// A variable.
74    Var(Var),
75    /// A literal.
76    Lit(Literal),
77}
78
79impl Atom {
80    /// Returns the abstract value.
81    pub fn aval(&self) -> AVal {
82        match self {
83            Atom::Var(v) => v.aval().clone(),
84            Atom::Lit(l) => l.value().aval(),
85        }
86    }
87}
88
89impl From<Var> for Atom {
90    fn from(v: Var) -> Self {
91        Atom::Var(v)
92    }
93}
94
95/// The precision of matrix multiplication on accelerators.
96#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
97pub enum Precision {
98    /// The backend's default (TensorFloat-32 for `f32` on recent GPUs).
99    #[default]
100    Default,
101    /// Higher than the default.
102    High,
103    /// Full precision of the operand type.
104    Highest,
105}
106
107/// How `round` rounds halfway cases.
108#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
109pub enum RoundingMethod {
110    /// Away from zero (`lax.round`'s default).
111    #[default]
112    AwayFromZero,
113    /// To even (`jnp.round`).
114    ToNearestEven,
115}
116
117/// The algorithm of `eigh` (JAX's `EighImplementation`).
118#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
119pub enum EighImplementation {
120    /// The QR algorithm on the tridiagonal form (LAPACK's).
121    Qr,
122    /// Cyclic Jacobi rotations.
123    Jacobi,
124    /// The spectral divide and conquer by the polar decomposition (JAX on
125    /// TPU; ruxla uses the QR algorithm).
126    Qdwh,
127}
128
129impl EighImplementation {
130    /// JAX's name of the variant (`JACOBI`).
131    pub fn name(self) -> &'static str {
132        match self {
133            Self::Qr => "QR",
134            Self::Jacobi => "JACOBI",
135            Self::Qdwh => "QDWH",
136        }
137    }
138
139    /// The variant of JAX's name.
140    pub fn from_name(name: &str) -> Option<Self> {
141        [Self::Qr, Self::Jacobi, Self::Qdwh]
142            .into_iter()
143            .find(|v| v.name() == name)
144    }
145}
146
147/// The algorithm of `svd` (JAX's `SvdAlgorithm`).
148#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
149pub enum SvdAlgorithm {
150    /// The platform's default.
151    Default,
152    /// The QR algorithm on the bidiagonal form.
153    Qr,
154    /// One-sided Jacobi rotations.
155    Jacobi,
156    /// By the polar decomposition (JAX on GPU; ruxla uses the QR
157    /// algorithm natively).
158    Polar,
159    /// Divide and conquer (LAPACK's `gesdd`; ruxla uses the QR algorithm
160    /// natively).
161    DivideAndConquer,
162}
163
164impl SvdAlgorithm {
165    /// JAX's name of the variant (`QR`).
166    pub fn name(self) -> &'static str {
167        match self {
168            Self::Default => "DEFAULT",
169            Self::Qr => "QR",
170            Self::Jacobi => "JACOBI",
171            Self::Polar => "POLAR",
172            Self::DivideAndConquer => "DIVIDE_AND_CONQUER",
173        }
174    }
175
176    /// The variant of JAX's name.
177    pub fn from_name(name: &str) -> Option<Self> {
178        [
179            Self::Default,
180            Self::Qr,
181            Self::Jacobi,
182            Self::Polar,
183            Self::DivideAndConquer,
184        ]
185        .into_iter()
186        .find(|v| v.name() == name)
187    }
188}
189
190/// The comparison that `select_and_scatter_add` and `select_and_gather_add`
191/// select elements with (JAX's `select_prim`).
192#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
193pub enum SelectPrim {
194    /// `ge`: the maximum (for `reduce_window_max`).
195    Ge,
196    /// `le`: the minimum (for `reduce_window_min`).
197    Le,
198}
199
200/// The parameters of an equation, one variant per family of primitives.
201#[derive(Clone, PartialEq, Debug)]
202#[non_exhaustive]
203pub enum Params {
204    /// No parameters.
205    None,
206    /// `convert_element_type` and `bitcast_convert_type`.
207    Convert {
208        /// The type to convert to.
209        new_dtype: DType,
210    },
211    /// `round`.
212    Round {
213        /// How halfway cases are rounded.
214        method: RoundingMethod,
215    },
216    /// `integer_pow`.
217    IntegerPow {
218        /// The exponent.
219        y: i32,
220    },
221    /// `broadcast_in_dim`.
222    BroadcastInDim {
223        /// The shape of the result.
224        shape: Shape,
225        /// For each operand dimension, the result dimension it becomes.
226        broadcast_dimensions: Vec<usize>,
227    },
228    /// `reshape`.
229    Reshape {
230        /// The shape of the result.
231        new_sizes: Shape,
232    },
233    /// `transpose`.
234    Transpose {
235        /// The operand dimension of each result dimension.
236        permutation: Vec<usize>,
237    },
238    /// `reduce_sum`, `reduce_max`, `reduce_min`.
239    Reduce {
240        /// The dimensions to reduce.
241        axes: Vec<usize>,
242    },
243    /// `argmax`, `argmin`.
244    ArgMinMax {
245        /// The dimension to reduce.
246        axis: usize,
247        /// The type of the indices.
248        index_dtype: DType,
249    },
250    /// `dot_general`.
251    DotGeneral {
252        /// The contracting and batch dimensions.
253        dimension_numbers: DotDims,
254        /// The precision on accelerators.
255        precision: Precision,
256        /// The type of the result, if it differs from the operands.
257        preferred_element_type: Option<DType>,
258    },
259    /// `conv_general_dilated`.
260    ConvGeneralDilated {
261        /// The step between windows in each spatial dimension.
262        window_strides: Vec<usize>,
263        /// `(low, high)` padding of each spatial dimension of the (dilated)
264        /// input; negative padding removes elements.
265        padding: Vec<(i64, i64)>,
266        /// The dilation of each spatial dimension of the input.
267        lhs_dilation: Vec<usize>,
268        /// The dilation of each spatial dimension of the kernel.
269        rhs_dilation: Vec<usize>,
270        /// The layout of the operands and the result.
271        dimension_numbers: ConvDims,
272        /// The number of groups of input and output features.
273        feature_group_count: usize,
274        /// The number of groups of the batch (as output feature groups).
275        batch_group_count: usize,
276        /// The precision on accelerators.
277        precision: Precision,
278        /// The type of the result, if it differs from the operands.
279        preferred_element_type: Option<DType>,
280    },
281    /// `reduce_window_sum`, `reduce_window_max`, `reduce_window_min`.
282    ReduceWindow {
283        /// The size of the window in each dimension.
284        window_dimensions: Vec<usize>,
285        /// The step between windows in each dimension.
286        window_strides: Vec<usize>,
287        /// `(low, high)` padding of each dimension of the (dilated) operand.
288        padding: Vec<(i64, i64)>,
289        /// The dilation of the operand.
290        base_dilation: Vec<usize>,
291        /// The dilation of the window.
292        window_dilation: Vec<usize>,
293    },
294    /// `select_and_scatter_add`.
295    SelectAndScatterAdd {
296        /// How elements are selected in each window.
297        select_prim: SelectPrim,
298        /// The size of the window in each dimension.
299        window_dimensions: Vec<usize>,
300        /// The step between windows in each dimension.
301        window_strides: Vec<usize>,
302        /// `(low, high)` padding of each dimension of the operand.
303        padding: Vec<(i64, i64)>,
304    },
305    /// `select_and_gather_add`.
306    SelectAndGatherAdd {
307        /// How elements are selected in each window.
308        select_prim: SelectPrim,
309        /// The size of the window in each dimension.
310        window_dimensions: Vec<usize>,
311        /// The step between windows in each dimension.
312        window_strides: Vec<usize>,
313        /// `(low, high)` padding of each dimension of the (dilated) operand.
314        padding: Vec<(i64, i64)>,
315        /// The dilation of the operand.
316        base_dilation: Vec<usize>,
317        /// The dilation of the window.
318        window_dilation: Vec<usize>,
319    },
320    /// `iota`.
321    Iota {
322        /// The type of the result.
323        dtype: DType,
324        /// The shape of the result.
325        shape: Shape,
326        /// The dimension along which values increase.
327        dimension: usize,
328    },
329    /// `slice`.
330    Slice {
331        /// The first index of each dimension.
332        start_indices: Vec<usize>,
333        /// One past the last index of each dimension.
334        limit_indices: Vec<usize>,
335        /// The step of each dimension.
336        strides: Vec<usize>,
337    },
338    /// `dynamic_slice`.
339    DynamicSlice {
340        /// The size of the slice in each dimension.
341        slice_sizes: Vec<usize>,
342    },
343    /// `concatenate`.
344    Concatenate {
345        /// The dimension to join along.
346        dimension: usize,
347    },
348    /// `pad`.
349    Pad {
350        /// `(low, high, interior)` padding of each dimension.
351        padding_config: Vec<(i64, i64, usize)>,
352    },
353    /// `rev`.
354    Rev {
355        /// The dimensions to reverse.
356        dimensions: Vec<usize>,
357    },
358    /// `sort`.
359    Sort {
360        /// The dimension to sort along.
361        dimension: usize,
362        /// Whether equal keys keep their order.
363        is_stable: bool,
364        /// The number of leading operands that are keys, compared
365        /// lexicographically.
366        num_keys: usize,
367    },
368    /// `cumsum`, `cumprod`, `cummax`, `cummin`, and `cumlogsumexp`.
369    Cumulative {
370        /// The dimension to accumulate along.
371        axis: usize,
372        /// Whether to accumulate from the end.
373        reverse: bool,
374    },
375    /// `fft`.
376    Fft {
377        /// The kind of transform.
378        fft_type: FftType,
379        /// The lengths of the transformed (trailing) axes of the result
380        /// (of the operand, except the last for `Irfft`).
381        fft_lengths: Vec<usize>,
382    },
383    /// `top_k`.
384    TopK {
385        /// The number of largest elements to return.
386        k: usize,
387        /// The dimension to search along.
388        axis: usize,
389        /// Whether equal elements keep their order.
390        is_stable: bool,
391    },
392    /// `triangular_solve`.
393    TriangularSolve {
394        /// Solve `op(a) x = b` if true, `x op(a) = b` if false.
395        left_side: bool,
396        /// Use the lower triangle of `a` if true, the upper if false.
397        lower: bool,
398        /// `op(a)` transposes `a`.
399        transpose_a: bool,
400        /// `op(a)` conjugates `a` (no effect for real numbers).
401        conjugate_a: bool,
402        /// The diagonal of `a` is taken to be ones (and not read).
403        unit_diagonal: bool,
404    },
405    /// `lu_pivots_to_permutation`.
406    LuPivotsToPermutation {
407        /// The size of the permutation (at least the number of pivots).
408        permutation_size: usize,
409    },
410    /// `qr`.
411    Qr {
412        /// `q` is square (`m x m`) if true, `m x min(m, n)` if false.
413        full_matrices: bool,
414        /// Column pivoting (not supported yet; always false).
415        pivoting: bool,
416    },
417    /// `eigh`.
418    Eigh {
419        /// Read the lower triangle of the operand if true, the upper if
420        /// false.
421        lower: bool,
422        /// Whether the eigenvalues must be sorted in ascending order (they
423        /// always are).
424        sort_eigenvalues: bool,
425        /// The range `[start, end)` of the (ascending) eigenvalues and
426        /// their eigenvectors that are returned (all if `None`).
427        subset_by_index: Option<(usize, usize)>,
428        /// The algorithm (the platform's default if `None`).
429        algorithm: Option<EighImplementation>,
430    },
431    /// `schur`: the Schur decomposition.
432    Schur {
433        /// Whether the Schur vectors are computed.
434        compute_schur_vectors: bool,
435    },
436    /// `ormqr`: the product with `Q` of Householder reflectors.
437    Ormqr {
438        /// `Q c` if true, `c Q` if false.
439        left: bool,
440        /// `Q^H` in place of `Q`.
441        transpose: bool,
442    },
443    /// `symmetric_product`: `alpha a a^T + beta c`.
444    SymmetricProduct {
445        /// The factor of `a a^T`.
446        alpha: f64,
447        /// The factor of `c`.
448        beta: f64,
449    },
450    /// `tridiagonal`: the reduction of Hermitian matrices to tridiagonal
451    /// form.
452    Tridiagonal {
453        /// Whether the lower triangle is read (otherwise the upper one).
454        lower: bool,
455    },
456    /// `host_callback`: a Rust function on host arrays.
457    HostCallback {
458        /// The function.
459        callback: crate::callback::HostCallback,
460        /// The types of the results.
461        outputs: Vec<AVal>,
462    },
463    /// `tridiagonal_solve`: the solution of tridiagonal systems.
464    TridiagonalSolve {
465        /// Whether tiny pivots are perturbed so that numerically singular
466        /// systems give finite solutions.
467        perturb_singular: bool,
468    },
469    /// `eig`: the eigendecomposition of general matrices.
470    Eig {
471        /// Whether the left eigenvectors are computed.
472        compute_left_eigenvectors: bool,
473        /// Whether the right eigenvectors are computed.
474        compute_right_eigenvectors: bool,
475        /// Whether the eigenvectors are differentiable (JAX's opt-in: the
476        /// derivatives hold for distinct eigenvalues only).
477        enable_eigvec_derivs: bool,
478    },
479    /// `svd`.
480    Svd {
481        /// `u` and `vt` are square if true, `m x k` and `k x n` if false.
482        full_matrices: bool,
483        /// Whether `u` and `vt` are computed (otherwise only the singular
484        /// values are returned).
485        compute_uv: bool,
486        /// The range `[start, end)` of the (descending) singular values and
487        /// their vectors that are returned (all if `None`).
488        subset_by_index: Option<(usize, usize)>,
489        /// The algorithm (the platform's default if `None`).
490        algorithm: Option<SvdAlgorithm>,
491    },
492    /// `gather`.
493    Gather {
494        /// How indices and slices map to the result.
495        dimension_numbers: GatherDims,
496        /// The size of the slice in each operand dimension.
497        slice_sizes: Vec<usize>,
498        /// How out-of-bounds indices are treated.
499        mode: GatherScatterMode,
500        /// Whether the indices are sorted (a hint).
501        indices_are_sorted: bool,
502        /// Whether the indices are unique (a hint).
503        unique_indices: bool,
504    },
505    /// The scatter family.
506    Scatter {
507        /// How indices and updates map to the operand.
508        dimension_numbers: ScatterDims,
509        /// How out-of-bounds indices are treated.
510        mode: GatherScatterMode,
511        /// Whether the indices are sorted (a hint).
512        indices_are_sorted: bool,
513        /// Whether the indices are unique (a hint).
514        unique_indices: bool,
515    },
516    /// `cond`: calls the branch chosen by an index.
517    Cond {
518        /// The branches, which take and return the same types.
519        branches: Vec<Arc<Function>>,
520    },
521    /// `while`: repeats the body while the predicate holds.
522    While {
523        /// Takes `cond_nconsts` constants and the carry; returns a bool.
524        cond: Arc<Function>,
525        /// Takes `body_nconsts` constants and the carry; returns the carry.
526        body: Arc<Function>,
527        /// The number of constants of the predicate.
528        cond_nconsts: usize,
529        /// The number of constants of the body.
530        body_nconsts: usize,
531    },
532    /// `scan`: a loop over the leading dimension of some inputs.
533    Scan {
534        /// Takes constants, the carry, and slices of the scanned inputs;
535        /// returns the carry and slices of the outputs.
536        body: Arc<Function>,
537        /// The number of iterations.
538        length: usize,
539        /// Whether to iterate from the end.
540        reverse: bool,
541        /// The number of constants.
542        num_consts: usize,
543        /// The number of carried values.
544        num_carry: usize,
545    },
546    /// `jit`: a call to a function compiled as a unit.
547    Jit {
548        /// The name, for display.
549        name: String,
550        /// The function.
551        body: Arc<Function>,
552    },
553    /// `custom_jvp_call`: a function with a JVP rule written by the user
554    /// (`jax.custom_jvp`).
555    CustomJvp {
556        /// Takes the constants and the arguments; returns the outputs.
557        call: Arc<Function>,
558        /// Takes the constants, the arguments, and a tangent for each
559        /// argument; returns the outputs and a tangent for each output.
560        jvp: Arc<Function>,
561        /// The number of constants (values the function captured, which are
562        /// not differentiated).
563        num_consts: usize,
564    },
565    /// `custom_vjp_call`: a function with a VJP rule written by the user
566    /// (`jax.custom_vjp`).
567    CustomVjp {
568        /// Takes the constants and the arguments; returns the outputs.
569        call: Arc<Function>,
570        /// Takes the constants and the arguments; returns the outputs and
571        /// the residuals.
572        fwd: Arc<Function>,
573        /// Takes the residuals and a cotangent for each output; returns a
574        /// cotangent for each argument.
575        bwd: Arc<Function>,
576        /// The number of constants (not differentiated).
577        num_consts: usize,
578    },
579    /// `custom_lin`: the linear part of a `custom_vjp_call` in forward mode,
580    /// which only reverse mode can use (it is transposed into `bwd`).
581    CustomLin {
582        /// The backward function of the `custom_vjp_call`.
583        bwd: Arc<Function>,
584        /// The number of residuals (the first inputs).
585        num_res: usize,
586    },
587    /// `checkpoint`: a function whose intermediate values are recomputed in
588    /// reverse mode instead of stored (`jax.checkpoint`).
589    Checkpoint {
590        /// The function.
591        body: Arc<Function>,
592    },
593    /// `extern_call`: a call to the public `main` of a StableHLO module
594    /// written by another program (such as `jax.export`), which XLA links
595    /// with the caller.
596    Extern {
597        /// The name, for display and for the symbols of the linked module.
598        name: String,
599        /// The module, in the MLIR text format.
600        module: Arc<str>,
601        /// The types of the inputs of `main`.
602        inputs: Vec<AVal>,
603        /// The types of the outputs of `main`.
604        outputs: Vec<AVal>,
605    },
606}
607
608impl Params {
609    /// Returns the functions nested in the parameters.
610    pub fn functions(&self) -> Vec<&Function> {
611        match self {
612            Params::Jit { body, .. } | Params::Scan { body, .. } => vec![body],
613            Params::Cond { branches } => branches.iter().map(AsRef::as_ref).collect(),
614            Params::While { cond, body, .. } => vec![cond, body],
615            Params::CustomJvp { call, jvp, .. } => vec![call, jvp],
616            Params::CustomVjp { call, fwd, bwd, .. } => vec![call, fwd, bwd],
617            Params::CustomLin { bwd, .. } => vec![bwd],
618            Params::Checkpoint { body } => vec![body],
619            _ => Vec::new(),
620        }
621    }
622}
623
624/// An equation: applies a primitive to operands and defines variables.
625#[derive(Clone, PartialEq, Debug)]
626pub struct Eqn {
627    /// The primitive.
628    pub prim: Prim,
629    /// The operands.
630    pub inputs: Vec<Atom>,
631    /// The parameters.
632    pub params: Params,
633    /// The variables defined by the equation.
634    pub outputs: Vec<Var>,
635    /// Where the equation was created, if known.
636    pub loc: Option<SrcLoc>,
637}
638
639/// A function of the IR (a closed jaxpr).
640#[derive(Clone, PartialEq, Debug, Default)]
641pub struct Function {
642    /// Variables bound to constant arrays.
643    pub constvars: Vec<(Var, HostArray)>,
644    /// The inputs.
645    pub invars: Vec<Var>,
646    /// The equations, in order of evaluation.
647    pub eqns: Vec<Eqn>,
648    /// The outputs.
649    pub outvars: Vec<Atom>,
650}
651
652impl Function {
653    /// Returns the abstract values of the inputs.
654    pub fn in_avals(&self) -> Vec<AVal> {
655        self.invars.iter().map(|v| v.aval().clone()).collect()
656    }
657
658    /// Returns the abstract values of the outputs.
659    pub fn out_avals(&self) -> Vec<AVal> {
660        self.outvars.iter().map(Atom::aval).collect()
661    }
662
663    /// Checks that the function is well formed and well typed: every
664    /// variable is defined once before it is used, and the outputs of every
665    /// equation match the abstract evaluation of its primitive (recursively).
666    ///
667    /// # Errors
668    ///
669    /// Returns [`Error::Malformed`] describing the first problem.
670    pub fn check(&self) -> Result<()> {
671        let mut defined = HashSet::new();
672        for (v, value) in &self.constvars {
673            if value.aval() != *v.aval() {
674                return Err(Error::Malformed(format!(
675                    "constant {:?} bound to {v:?}",
676                    value.aval()
677                )));
678            }
679            if !defined.insert(v.id()) {
680                return Err(Error::Malformed(format!("{v:?} is defined twice")));
681            }
682        }
683        for v in &self.invars {
684            if !defined.insert(v.id()) {
685                return Err(Error::Malformed(format!("{v:?} is defined twice")));
686            }
687        }
688        for (i, eqn) in self.eqns.iter().enumerate() {
689            let context = |m: String| Error::Malformed(format!("equation {i} ({}): {m}", eqn.prim));
690            for a in &eqn.inputs {
691                if let Atom::Var(v) = a
692                    && !defined.contains(&v.id())
693                {
694                    return Err(context(format!("{v:?} is used before it is defined")));
695                }
696            }
697            let in_avals: Vec<AVal> = eqn.inputs.iter().map(Atom::aval).collect();
698            let out = eqn
699                .prim
700                .abstract_eval(&in_avals, &eqn.params)
701                .map_err(|e| context(e.to_string()))?;
702            let actual: Vec<AVal> = eqn.outputs.iter().map(|v| v.aval().clone()).collect();
703            if out != actual {
704                return Err(context(format!(
705                    "outputs are {actual:?}, but abstract evaluation gives {out:?}"
706                )));
707            }
708            for f in eqn.params.functions() {
709                f.check().map_err(|e| context(e.to_string()))?;
710            }
711            for v in &eqn.outputs {
712                if !defined.insert(v.id()) {
713                    return Err(context(format!("{v:?} is defined twice")));
714                }
715            }
716        }
717        for a in &self.outvars {
718            if let Atom::Var(v) = a
719                && !defined.contains(&v.id())
720            {
721                return Err(Error::Malformed(format!("output {v:?} is not defined")));
722            }
723        }
724        Ok(())
725    }
726}