Skip to main content

ruxla_import/
lib.rs

1//! Importing functions written in JAX into ruxla's IR.
2//!
3//! The Python function `ruxla.export_jaxpr(fn, *args)` traces a JAX
4//! function, rewrites its jaxpr into the primitives that ruxla's IR has
5//! (inlining calls, expanding the PRNG on raw `u32` key data, and so on),
6//! and writes it as a JSON document. [`from_json`] reads the document into a
7//! [`Function`], which ruxla runs like a function traced from Rust: with the
8//! interpreter, compiled ahead of time to Rust (`ruxla-codegen`), or lowered
9//! to XLA.
10//!
11//! The document's format is described in `python/ruxla/_jaxpr.py`: a
12//! function of variables (ids, element types, and shapes), constants and
13//! literals (base64 of their little-endian bytes), and equations (the
14//! primitive's name, the inputs, the outputs, and the parameters as JSON
15//! values). The primitives and most parameters have JAX's names, which are
16//! also ruxla's.
17//!
18//! # Examples
19//!
20//! ```
21//! use ruxla_ir::HostArray;
22//!
23//! // `jnp.sin(x)` for `x: f32[2]`, as `ruxla.export_jaxpr` writes it.
24//! let doc = r#"{"format_version": 1, "function": {
25//!     "invars": [{"id": 0, "dtype": "f32", "shape": [2]}], "constvars": [],
26//!     "eqns": [{"prim": "sin", "inputs": [{"var": 0}],
27//!               "outputs": [{"id": 1, "dtype": "f32", "shape": [2]}],
28//!               "params": {"accuracy": null}}],
29//!     "outvars": [{"var": 1}]}}"#;
30//! let f = ruxla_import::from_json(doc).unwrap();
31//! assert_eq!(f.to_string(), "{ lambda ; a:f32[2]. let\n    b:f32[2] = sin a\n  in (b,) }");
32//! ```
33
34use std::collections::HashMap;
35use std::sync::Arc;
36
37use ruxla_ir::{
38    AVal, Atom, DType, DotDims, EighImplementation, Eqn, Function, GatherDims, GatherScatterMode,
39    HostArray, Literal, Params, Precision, Prim, RoundingMethod, ScatterDims, Shape, SvdAlgorithm,
40    Var,
41};
42use serde_json::{Map, Value};
43
44/// The version of the JSON document that this crate reads.
45pub const FORMAT_VERSION: u64 = 1;
46
47/// Errors while importing a document.
48#[derive(Debug, thiserror::Error)]
49#[non_exhaustive]
50pub enum Error {
51    /// The text is not JSON.
52    #[error("invalid JSON: {0}")]
53    Json(#[from] serde_json::Error),
54    /// The document does not have the expected structure.
55    #[error("malformed document: {0}")]
56    Malformed(String),
57    /// The document uses a primitive or parameter that ruxla does not have.
58    #[error("{prim}: unsupported: {message}")]
59    Unsupported {
60        /// The primitive.
61        prim: String,
62        /// What is not supported.
63        message: String,
64    },
65    /// The imported function is not well formed (its types do not check).
66    #[error(transparent)]
67    Ir(#[from] ruxla_ir::Error),
68}
69
70/// A specialized result type.
71pub type Result<T, E = Error> = std::result::Result<T, E>;
72
73/// Reads the JSON document written by `ruxla.export_jaxpr` into a function,
74/// and checks that its types agree with ruxla's shape inference.
75///
76/// # Errors
77///
78/// Returns an error if the text is not such a document, if it uses a
79/// primitive or parameter that ruxla does not have, or if the function's
80/// types do not check.
81pub fn from_json(text: &str) -> Result<Function> {
82    let doc: Value = serde_json::from_str(text)?;
83    from_value(&doc)
84}
85
86/// [`from_json`] from a parsed document.
87///
88/// # Errors
89///
90/// As [`from_json`].
91pub fn from_value(doc: &Value) -> Result<Function> {
92    let version = doc
93        .get("format_version")
94        .and_then(Value::as_u64)
95        .ok_or_else(|| malformed("no format_version"))?;
96    if version != FORMAT_VERSION {
97        return Err(malformed(format!(
98            "format version {version}; this build reads version {FORMAT_VERSION}"
99        )));
100    }
101    let f = Reader::default().function(field(doc, "function")?)?;
102    f.check()?;
103    Ok(f)
104}
105
106fn malformed(m: impl Into<String>) -> Error {
107    Error::Malformed(m.into())
108}
109
110fn unsupported(prim: &str, m: impl Into<String>) -> Error {
111    Error::Unsupported {
112        prim: prim.to_string(),
113        message: m.into(),
114    }
115}
116
117fn field<'a>(v: &'a Value, name: &str) -> Result<&'a Value> {
118    v.get(name)
119        .ok_or_else(|| malformed(format!("missing field {name:?} in {}", short(v))))
120}
121
122fn short(v: &Value) -> String {
123    let s = v.to_string();
124    if s.len() > 200 {
125        format!("{}...", &s[..200])
126    } else {
127        s
128    }
129}
130
131fn array<'a>(v: &'a Value, what: &str) -> Result<&'a Vec<Value>> {
132    v.as_array()
133        .ok_or_else(|| malformed(format!("{what} is not a list: {}", short(v))))
134}
135
136fn uint(v: &Value, what: &str) -> Result<usize> {
137    v.as_u64().map(|x| x as usize).ok_or_else(|| {
138        malformed(format!(
139            "{what} is not a non-negative integer: {}",
140            short(v)
141        ))
142    })
143}
144
145fn int(v: &Value, what: &str) -> Result<i64> {
146    v.as_i64()
147        .ok_or_else(|| malformed(format!("{what} is not an integer: {}", short(v))))
148}
149
150fn uints(v: &Value, what: &str) -> Result<Vec<usize>> {
151    array(v, what)?.iter().map(|x| uint(x, what)).collect()
152}
153
154fn boolean(v: &Value, what: &str) -> Result<bool> {
155    v.as_bool()
156        .ok_or_else(|| malformed(format!("{what} is not a boolean: {}", short(v))))
157}
158
159fn float(v: &Value, what: &str) -> Result<f64> {
160    v.as_f64()
161        .ok_or_else(|| malformed(format!("{what} is not a number: {}", short(v))))
162}
163
164fn dtype(v: &Value) -> Result<DType> {
165    let name = v
166        .as_str()
167        .ok_or_else(|| malformed(format!("element type is not a string: {}", short(v))))?;
168    DType::from_name(name).ok_or_else(|| malformed(format!("unknown element type {name:?}")))
169}
170
171/// Decodes standard base64 (with padding), the encoding of the data of
172/// constants and literals in the documents.
173///
174/// # Errors
175///
176/// Returns [`Error::Malformed`] if `s` is not base64.
177pub fn base64(s: &str) -> Result<Vec<u8>> {
178    fn digit(c: u8) -> Option<u32> {
179        Some(match c {
180            b'A'..=b'Z' => c - b'A',
181            b'a'..=b'z' => c - b'a' + 26,
182            b'0'..=b'9' => c - b'0' + 52,
183            b'+' => 62,
184            b'/' => 63,
185            _ => return None,
186        } as u32)
187    }
188    let bytes = s.as_bytes();
189    if !bytes.len().is_multiple_of(4) {
190        return Err(malformed("base64 of a length that is not a multiple of 4"));
191    }
192    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
193    for chunk in bytes.chunks(4) {
194        let pad = chunk.iter().rev().take_while(|&&c| c == b'=').count();
195        let mut n = 0u32;
196        for &c in &chunk[..4 - pad] {
197            n = n << 6 | digit(c).ok_or_else(|| malformed("invalid base64"))?;
198        }
199        n <<= 6 * pad as u32;
200        let b = n.to_be_bytes();
201        out.extend_from_slice(&b[1..4 - pad]);
202    }
203    Ok(out)
204}
205
206#[derive(Default)]
207struct Reader {
208    vars: HashMap<u64, Var>,
209}
210
211impl Reader {
212    fn aval(v: &Value) -> Result<AVal> {
213        Ok(AVal::new(
214            Shape::from(uints(field(v, "shape")?, "shape")?),
215            dtype(field(v, "dtype")?)?,
216        ))
217    }
218
219    /// Defines the variable `v` (`{"id", "dtype", "shape"}`).
220    fn define(&mut self, v: &Value) -> Result<Var> {
221        let id = field(v, "id")?
222            .as_u64()
223            .ok_or_else(|| malformed("variable id"))?;
224        let var = Var::new(Self::aval(v)?);
225        if self.vars.insert(id, var.clone()).is_some() {
226            return Err(malformed(format!("variable {id} is defined twice")));
227        }
228        Ok(var)
229    }
230
231    fn atom(&self, a: &Value) -> Result<Atom> {
232        if let Some(id) = a.get("var") {
233            let id = id.as_u64().ok_or_else(|| malformed("variable id"))?;
234            return self
235                .vars
236                .get(&id)
237                .cloned()
238                .map(Atom::Var)
239                .ok_or_else(|| malformed(format!("variable {id} is used before it is defined")));
240        }
241        let data = field(a, "lit")?
242            .as_str()
243            .ok_or_else(|| malformed("literal data"))?;
244        let value =
245            HostArray::from_bytes(&base64(data)?, Shape::scalar(), dtype(field(a, "dtype")?)?)?;
246        Ok(Atom::Lit(Literal::new(value)))
247    }
248
249    fn function(&mut self, f: &Value) -> Result<Function> {
250        let mut constvars = Vec::new();
251        for c in array(field(f, "constvars")?, "constvars")? {
252            let v = self.define(c)?;
253            let data = field(c, "data")?
254                .as_str()
255                .ok_or_else(|| malformed("constant data"))?;
256            let a = v.aval().clone();
257            let value = HostArray::from_bytes(&base64(data)?, a.shape, a.dtype)?;
258            constvars.push((v, value));
259        }
260        let invars = array(field(f, "invars")?, "invars")?
261            .iter()
262            .map(|v| self.define(v))
263            .collect::<Result<Vec<_>>>()?;
264        let mut eqns = Vec::new();
265        for e in array(field(f, "eqns")?, "eqns")? {
266            self.eqn(e, &mut eqns)?;
267        }
268        let outvars = array(field(f, "outvars")?, "outvars")?
269            .iter()
270            .map(|a| self.atom(a))
271            .collect::<Result<Vec<_>>>()?;
272        Ok(Function {
273            constvars,
274            invars,
275            eqns,
276            outvars,
277        })
278    }
279
280    /// Reads the equation `e` and appends it to `eqns` (after the
281    /// broadcasts of its scalar operands, if any).
282    fn eqn(&mut self, e: &Value, eqns: &mut Vec<Eqn>) -> Result<()> {
283        let name = field(e, "prim")?
284            .as_str()
285            .ok_or_else(|| malformed("primitive name"))?;
286        let mut inputs = array(field(e, "inputs")?, "inputs")?
287            .iter()
288            .map(|a| self.atom(a))
289            .collect::<Result<Vec<_>>>()?;
290        let empty = Map::new();
291        let params = match e.get("params") {
292            Some(Value::Object(m)) => m,
293            _ => &empty,
294        };
295        let prim = ruxla_prims::by_name(name)
296            .ok_or_else(|| unsupported(name, "ruxla has no such primitive"))?;
297        let params = self.params(name, params, &inputs)?;
298        broadcast_scalars(&prim, &params, &mut inputs, eqns);
299        let outputs = array(field(e, "outputs")?, "outputs")?
300            .iter()
301            .map(|v| self.define(v))
302            .collect::<Result<Vec<_>>>()?;
303        eqns.push(Eqn {
304            prim,
305            inputs,
306            params,
307            outputs,
308            loc: None,
309        });
310        Ok(())
311    }
312
313    fn sub_function(&mut self, v: &Value) -> Result<Arc<Function>> {
314        let f = field(v, "function")?;
315        Ok(Arc::new(self.function(f)?))
316    }
317
318    fn params(&mut self, name: &str, p: &Map<String, Value>, inputs: &[Atom]) -> Result<Params> {
319        let get = |k: &str| {
320            p.get(k)
321                .ok_or_else(|| malformed(format!("{name}: missing parameter {k:?}")))
322        };
323        // Parameters that must be absent (null) because ruxla's primitive
324        // does not have them.
325        let null = |k: &str| -> Result<()> {
326            match p.get(k) {
327                None | Some(Value::Null) => Ok(()),
328                Some(v) => Err(unsupported(name, format!("parameter {k} = {}", short(v)))),
329            }
330        };
331        Ok(match name {
332            "convert_element_type" | "bitcast_convert_type" => Params::Convert {
333                new_dtype: dtype(get("new_dtype")?)?,
334            },
335            "round" => Params::Round {
336                method: match get("rounding_method")? {
337                    Value::Number(n) if n.as_u64() == Some(0) => RoundingMethod::AwayFromZero,
338                    Value::Number(n) if n.as_u64() == Some(1) => RoundingMethod::ToNearestEven,
339                    Value::String(s) if s == "AWAY_FROM_ZERO" => RoundingMethod::AwayFromZero,
340                    Value::String(s) if s == "TO_NEAREST_EVEN" => RoundingMethod::ToNearestEven,
341                    v => return Err(unsupported(name, format!("rounding method {v}"))),
342                },
343            },
344            "integer_pow" => Params::IntegerPow {
345                y: int(get("y")?, "y")? as i32,
346            },
347            "broadcast_in_dim" => Params::BroadcastInDim {
348                shape: Shape::from(uints(get("shape")?, "shape")?),
349                broadcast_dimensions: uints(get("broadcast_dimensions")?, "broadcast_dimensions")?,
350            },
351            "reshape" => {
352                null("dimensions")?;
353                Params::Reshape {
354                    new_sizes: Shape::from(uints(get("new_sizes")?, "new_sizes")?),
355                }
356            }
357            "transpose" => Params::Transpose {
358                permutation: uints(get("permutation")?, "permutation")?,
359            },
360            "reduce_sum" | "reduce_max" | "reduce_min" => Params::Reduce {
361                axes: uints(get("axes")?, "axes")?,
362            },
363            "argmax" | "argmin" => {
364                let axes = uints(get("axes")?, "axes")?;
365                let [axis] = axes[..] else {
366                    return Err(unsupported(name, format!("axes {axes:?}")));
367                };
368                Params::ArgMinMax {
369                    axis,
370                    index_dtype: dtype(get("index_dtype")?)?,
371                }
372            }
373            "dot_general" => {
374                let dn = array(get("dimension_numbers")?, "dimension_numbers")?;
375                let pair = |i: usize| -> Result<(Vec<usize>, Vec<usize>)> {
376                    let x = array(
377                        dn.get(i).ok_or_else(|| malformed("dimension_numbers"))?,
378                        "dimension_numbers",
379                    )?;
380                    match &x[..] {
381                        [a, b] => Ok((uints(a, "dims")?, uints(b, "dims")?)),
382                        _ => Err(malformed("dimension_numbers")),
383                    }
384                };
385                let (lc, rc) = pair(0)?;
386                let (lb, rb) = pair(1)?;
387                Params::DotGeneral {
388                    dimension_numbers: DotDims {
389                        lhs_contracting: lc,
390                        rhs_contracting: rc,
391                        lhs_batch: lb,
392                        rhs_batch: rb,
393                    },
394                    precision: precision(name, p.get("precision"))?,
395                    preferred_element_type: opt_dtype(p.get("preferred_element_type"))?,
396                }
397            }
398            "conv_general_dilated" => {
399                let dn = get("dimension_numbers")?;
400                Params::ConvGeneralDilated {
401                    window_strides: uints(get("window_strides")?, "window_strides")?,
402                    padding: pairs(get("padding")?)?,
403                    lhs_dilation: uints(get("lhs_dilation")?, "lhs_dilation")?,
404                    rhs_dilation: uints(get("rhs_dilation")?, "rhs_dilation")?,
405                    dimension_numbers: ruxla_ir::ConvDims {
406                        lhs_spec: uints(field(dn, "lhs_spec")?, "lhs_spec")?,
407                        rhs_spec: uints(field(dn, "rhs_spec")?, "rhs_spec")?,
408                        out_spec: uints(field(dn, "out_spec")?, "out_spec")?,
409                    },
410                    feature_group_count: uint(get("feature_group_count")?, "feature_group_count")?,
411                    batch_group_count: uint(get("batch_group_count")?, "batch_group_count")?,
412                    precision: precision(name, p.get("precision"))?,
413                    preferred_element_type: opt_dtype(p.get("preferred_element_type"))?,
414                }
415            }
416            "iota" => Params::Iota {
417                dtype: dtype(get("dtype")?)?,
418                shape: Shape::from(uints(get("shape")?, "shape")?),
419                dimension: uint(get("dimension")?, "dimension")?,
420            },
421            "slice" => {
422                let start_indices = uints(get("start_indices")?, "start_indices")?;
423                let strides = match p.get("strides") {
424                    None | Some(Value::Null) => vec![1; start_indices.len()],
425                    Some(v) => uints(v, "strides")?,
426                };
427                Params::Slice {
428                    start_indices,
429                    limit_indices: uints(get("limit_indices")?, "limit_indices")?,
430                    strides,
431                }
432            }
433            "dynamic_slice" => Params::DynamicSlice {
434                slice_sizes: uints(get("slice_sizes")?, "slice_sizes")?,
435            },
436            "concatenate" => Params::Concatenate {
437                dimension: uint(get("dimension")?, "dimension")?,
438            },
439            "pad" => Params::Pad {
440                padding_config: array(get("padding_config")?, "padding_config")?
441                    .iter()
442                    .map(|t| match &array(t, "padding_config")?[..] {
443                        [lo, hi, interior] => Ok((
444                            int(lo, "padding")?,
445                            int(hi, "padding")?,
446                            uint(interior, "interior padding")?,
447                        )),
448                        _ => Err(malformed("padding_config")),
449                    })
450                    .collect::<Result<_>>()?,
451            },
452            "rev" => Params::Rev {
453                dimensions: uints(get("dimensions")?, "dimensions")?,
454            },
455            "sort" => Params::Sort {
456                dimension: uint(get("dimension")?, "dimension")?,
457                is_stable: boolean(get("is_stable")?, "is_stable")?,
458                num_keys: uint(get("num_keys")?, "num_keys")?,
459            },
460            "cumsum" | "cumprod" | "cummax" | "cummin" | "cumlogsumexp" => Params::Cumulative {
461                axis: uint(get("axis")?, "axis")?,
462                reverse: boolean(get("reverse")?, "reverse")?,
463            },
464            "top_k" => {
465                let rank = inputs[0].aval().shape.rank();
466                let axis = match p.get("axis") {
467                    None | Some(Value::Null) => rank.saturating_sub(1),
468                    Some(v) => {
469                        let a = int(v, "axis")?;
470                        if a < 0 {
471                            (rank as i64 + a) as usize
472                        } else {
473                            a as usize
474                        }
475                    }
476                };
477                Params::TopK {
478                    k: uint(get("k")?, "k")?,
479                    axis,
480                    is_stable: p.get("is_stable").and_then(Value::as_bool).unwrap_or(false),
481                }
482            }
483            "gather" => {
484                null("fill_value")?;
485                let dn = get("dimension_numbers")?;
486                let opt = |k: &str| -> Result<Vec<usize>> {
487                    match dn.get(k) {
488                        None | Some(Value::Null) => Ok(Vec::new()),
489                        Some(v) => uints(v, k),
490                    }
491                };
492                Params::Gather {
493                    dimension_numbers: GatherDims {
494                        offset_dims: opt("offset_dims")?,
495                        collapsed_slice_dims: opt("collapsed_slice_dims")?,
496                        start_index_map: opt("start_index_map")?,
497                        operand_batching_dims: opt("operand_batching_dims")?,
498                        start_indices_batching_dims: opt("start_indices_batching_dims")?,
499                    },
500                    slice_sizes: uints(get("slice_sizes")?, "slice_sizes")?,
501                    mode: mode(name, get("mode")?)?,
502                    indices_are_sorted: boolean(get("indices_are_sorted")?, "indices_are_sorted")?,
503                    unique_indices: boolean(get("unique_indices")?, "unique_indices")?,
504                }
505            }
506            "scatter" | "scatter-add" | "scatter-mul" | "scatter-min" | "scatter-max" => {
507                let dn = get("dimension_numbers")?;
508                let opt = |k: &str| -> Result<Vec<usize>> {
509                    match dn.get(k) {
510                        None | Some(Value::Null) => Ok(Vec::new()),
511                        Some(v) => uints(v, k),
512                    }
513                };
514                Params::Scatter {
515                    dimension_numbers: ScatterDims {
516                        update_window_dims: opt("update_window_dims")?,
517                        inserted_window_dims: opt("inserted_window_dims")?,
518                        scatter_dims_to_operand_dims: opt("scatter_dims_to_operand_dims")?,
519                        operand_batching_dims: opt("operand_batching_dims")?,
520                        scatter_indices_batching_dims: opt("scatter_indices_batching_dims")?,
521                    },
522                    mode: mode(name, get("mode")?)?,
523                    indices_are_sorted: boolean(get("indices_are_sorted")?, "indices_are_sorted")?,
524                    unique_indices: boolean(get("unique_indices")?, "unique_indices")?,
525                }
526            }
527            "triangular_solve" => Params::TriangularSolve {
528                left_side: boolean(get("left_side")?, "left_side")?,
529                lower: boolean(get("lower")?, "lower")?,
530                transpose_a: boolean(get("transpose_a")?, "transpose_a")?,
531                conjugate_a: boolean(get("conjugate_a")?, "conjugate_a")?,
532                unit_diagonal: boolean(get("unit_diagonal")?, "unit_diagonal")?,
533            },
534            "qr" => {
535                null("use_magma")?;
536                Params::Qr {
537                    full_matrices: boolean(get("full_matrices")?, "full_matrices")?,
538                    pivoting: boolean(get("pivoting")?, "pivoting")?,
539                }
540            }
541            "schur" => {
542                null("select_callable")?;
543                if p.get("sort_eig_vals").and_then(Value::as_bool) == Some(true) {
544                    return Err(unsupported(name, "sorted eigenvalues"));
545                }
546                Params::Schur {
547                    compute_schur_vectors: boolean(
548                        get("compute_schur_vectors")?,
549                        "compute_schur_vectors",
550                    )?,
551                }
552            }
553            "ormqr" => Params::Ormqr {
554                left: boolean(get("left")?, "left")?,
555                transpose: boolean(get("transpose")?, "transpose")?,
556            },
557            "symmetric_product" => Params::SymmetricProduct {
558                alpha: float(get("alpha")?, "alpha")?,
559                beta: float(get("beta")?, "beta")?,
560            },
561            "tridiagonal" => Params::Tridiagonal {
562                lower: boolean(get("lower")?, "lower")?,
563            },
564            "tridiagonal_solve" => Params::TridiagonalSolve {
565                perturb_singular: boolean(get("perturb_singular")?, "perturb_singular")?,
566            },
567            "eig" => {
568                null("implementation")?;
569                Params::Eig {
570                    compute_left_eigenvectors: boolean(
571                        get("compute_left_eigenvectors")?,
572                        "compute_left_eigenvectors",
573                    )?,
574                    compute_right_eigenvectors: boolean(
575                        get("compute_right_eigenvectors")?,
576                        "compute_right_eigenvectors",
577                    )?,
578                    enable_eigvec_derivs: boolean(
579                        get("enable_eigvec_derivs")?,
580                        "enable_eigvec_derivs",
581                    )?,
582                }
583            }
584            "eigh" | "svd" => {
585                let algorithm = match p.get("algorithm") {
586                    None | Some(Value::Null) => None,
587                    Some(Value::String(a)) => Some(a.as_str()),
588                    Some(_) => return Err(malformed("algorithm")),
589                };
590                let subset_by_index = match p.get("subset_by_index") {
591                    None | Some(Value::Null) => None,
592                    Some(Value::Array(range)) => match &range[..] {
593                        [start, end] => Some((
594                            uint(start, "subset_by_index")?,
595                            uint(end, "subset_by_index")?,
596                        )),
597                        _ => return Err(malformed("subset_by_index")),
598                    },
599                    Some(_) => return Err(malformed("subset_by_index")),
600                };
601                if name == "eigh" {
602                    Params::Eigh {
603                        lower: boolean(get("lower")?, "lower")?,
604                        sort_eigenvalues: boolean(get("sort_eigenvalues")?, "sort_eigenvalues")?,
605                        subset_by_index,
606                        algorithm: algorithm
607                            .map(|a| {
608                                EighImplementation::from_name(a)
609                                    .ok_or_else(|| malformed(format!("eigh algorithm {a}")))
610                            })
611                            .transpose()?,
612                    }
613                } else {
614                    Params::Svd {
615                        full_matrices: boolean(get("full_matrices")?, "full_matrices")?,
616                        compute_uv: boolean(get("compute_uv")?, "compute_uv")?,
617                        subset_by_index,
618                        algorithm: algorithm
619                            .map(|a| {
620                                SvdAlgorithm::from_name(a)
621                                    .ok_or_else(|| malformed(format!("svd algorithm {a}")))
622                            })
623                            .transpose()?,
624                    }
625                }
626            }
627            "cond" => Params::Cond {
628                branches: array(get("branches")?, "branches")?
629                    .iter()
630                    .map(|b| self.sub_function(b))
631                    .collect::<Result<_>>()?,
632            },
633            "while" => Params::While {
634                cond: self.sub_function(get("cond_jaxpr")?)?,
635                body: self.sub_function(get("body_jaxpr")?)?,
636                cond_nconsts: uint(get("cond_nconsts")?, "cond_nconsts")?,
637                body_nconsts: uint(get("body_nconsts")?, "body_nconsts")?,
638            },
639            "scan" => Params::Scan {
640                body: self.sub_function(get("jaxpr")?)?,
641                length: uint(get("length")?, "length")?,
642                reverse: boolean(get("reverse")?, "reverse")?,
643                num_consts: uint(get("num_consts")?, "num_consts")?,
644                num_carry: uint(get("num_carry")?, "num_carry")?,
645            },
646            _ => {
647                // Elementwise and other primitives without parameters in
648                // ruxla. JAX's optional parameters must have their default.
649                for k in ["accuracy", "out_dtype"] {
650                    null(k)?;
651                }
652                for (k, v) in p {
653                    if !matches!(k.as_str(), "accuracy" | "out_dtype") && !is_opaque(v) {
654                        return Err(unsupported(name, format!("parameter {k} = {}", short(v))));
655                    }
656                }
657                Params::None
658            }
659        })
660    }
661}
662
663/// JAX's elementwise primitives broadcast scalars and dimensions of size 1
664/// (`lt x 4:i32[]` for `x: i32[4, 4]`, `mul x y` for `x: f32[4]` and `y:
665/// f32[1]`), but ruxla's want operands of the same shape: if the primitive
666/// rejects the inputs and they broadcast to a common shape, they are
667/// broadcast to it (with equations appended to `eqns`).
668fn broadcast_scalars(prim: &Prim, params: &Params, inputs: &mut [Atom], eqns: &mut Vec<Eqn>) {
669    let avals: Vec<AVal> = inputs.iter().map(Atom::aval).collect();
670    if inputs.len() < 2 || prim.abstract_eval(&avals, params).is_ok() {
671        return;
672    }
673    let rank = avals.iter().map(|a| a.shape.rank()).max().unwrap_or(0);
674    let mut dims = vec![1usize; rank];
675    for a in &avals {
676        let r = a.shape.rank();
677        if r == 0 {
678            continue;
679        }
680        if r != rank {
681            return;
682        }
683        for (d, &n) in dims.iter_mut().zip(a.shape.dims()) {
684            if n != 1 {
685                if *d != 1 && *d != n {
686                    return;
687                }
688                *d = n;
689            }
690        }
691    }
692    let shape = Shape::from(dims);
693    for x in inputs.iter_mut() {
694        let a = x.aval();
695        if a.shape == shape {
696            continue;
697        }
698        let out = Var::new(AVal::new(shape.clone(), a.dtype));
699        let broadcast_dimensions = (0..a.shape.rank()).collect();
700        eqns.push(Eqn {
701            prim: ruxla_prims::BROADCAST_IN_DIM,
702            inputs: vec![x.clone()],
703            params: Params::BroadcastInDim {
704                shape: shape.clone(),
705                broadcast_dimensions,
706            },
707            outputs: vec![out.clone()],
708            loc: None,
709        });
710        *x = Atom::Var(out);
711    }
712}
713
714/// A parameter that ruxla does not use (shardings, layouts).
715fn is_opaque(v: &Value) -> bool {
716    v.is_null() || v.get("opaque").is_some()
717}
718
719fn pairs(v: &Value) -> Result<Vec<(i64, i64)>> {
720    array(v, "padding")?
721        .iter()
722        .map(|t| match &array(t, "padding")?[..] {
723            [lo, hi] => Ok((int(lo, "padding")?, int(hi, "padding")?)),
724            _ => Err(malformed("padding")),
725        })
726        .collect()
727}
728
729fn opt_dtype(v: Option<&Value>) -> Result<Option<DType>> {
730    match v {
731        None | Some(Value::Null) => Ok(None),
732        Some(v) => dtype(v).map(Some),
733    }
734}
735
736fn precision(prim: &str, v: Option<&Value>) -> Result<Precision> {
737    let one = |v: &Value| -> Result<Precision> {
738        Ok(match v {
739            Value::Null => Precision::Default,
740            Value::String(s) if s == "DEFAULT" => Precision::Default,
741            Value::String(s) if s == "HIGH" => Precision::High,
742            Value::String(s) if s == "HIGHEST" => Precision::Highest,
743            v => return Err(unsupported(prim, format!("precision {}", short(v)))),
744        })
745    };
746    match v {
747        None | Some(Value::Null) => Ok(Precision::Default),
748        Some(Value::Array(ps)) => {
749            let ps = ps.iter().map(one).collect::<Result<Vec<_>>>()?;
750            Ok(ps.into_iter().max_by_key(|p| *p as u8).unwrap_or_default())
751        }
752        Some(v) => one(v),
753    }
754}
755
756fn mode(prim: &str, v: &Value) -> Result<GatherScatterMode> {
757    Ok(match v {
758        Value::String(s) if s == "CLIP" => GatherScatterMode::Clip,
759        Value::String(s) if s == "FILL_OR_DROP" => GatherScatterMode::FillOrDrop,
760        Value::String(s) if s == "PROMISE_IN_BOUNDS" => GatherScatterMode::PromiseInBounds,
761        Value::Number(n) if n.as_u64() == Some(0) => GatherScatterMode::Clip,
762        Value::Number(n) if n.as_u64() == Some(1) => GatherScatterMode::FillOrDrop,
763        Value::Number(n) if n.as_u64() == Some(2) => GatherScatterMode::PromiseInBounds,
764        v => return Err(unsupported(prim, format!("mode {}", short(v)))),
765    })
766}
767
768/// The primitive named `name`, if ruxla has it.
769pub fn primitive(name: &str) -> Option<Prim> {
770    ruxla_prims::by_name(name)
771}
772
773#[cfg(test)]
774mod tests {
775    use super::*;
776
777    #[test]
778    fn base64_decodes() {
779        assert_eq!(base64("").unwrap(), b"");
780        assert_eq!(base64("Zg==").unwrap(), b"f");
781        assert_eq!(base64("Zm8=").unwrap(), b"fo");
782        assert_eq!(base64("Zm9v").unwrap(), b"foo");
783        assert_eq!(base64("AACAPw==").unwrap(), 1.0f32.to_le_bytes());
784        assert!(base64("Zm9").is_err());
785    }
786
787    #[test]
788    fn rejects_unknown_primitives() {
789        let doc = r#"{"format_version": 1, "function": {
790            "invars": [{"id": 0, "dtype": "f32", "shape": []}], "constvars": [],
791            "eqns": [{"prim": "frobnicate", "inputs": [{"var": 0}],
792                      "outputs": [{"id": 1, "dtype": "f32", "shape": []}], "params": {}}],
793            "outvars": [{"var": 1}]}}"#;
794        let e = from_json(doc).unwrap_err();
795        assert!(e.to_string().contains("frobnicate"), "{e}");
796    }
797
798    #[test]
799    fn checks_types() {
800        // The output is declared i32, but `sin` gives f32.
801        let doc = r#"{"format_version": 1, "function": {
802            "invars": [{"id": 0, "dtype": "f32", "shape": []}], "constvars": [],
803            "eqns": [{"prim": "sin", "inputs": [{"var": 0}],
804                      "outputs": [{"id": 1, "dtype": "i32", "shape": []}], "params": {}}],
805            "outvars": [{"var": 1}]}}"#;
806        assert!(matches!(from_json(doc), Err(Error::Ir(_))));
807    }
808
809    #[test]
810    fn reads_constants_and_literals() {
811        // c + 2.0 with the constant c = [1.0, 3.0].
812        let doc = r#"{"format_version": 1, "function": {
813            "invars": [], "constvars": [{"id": 0, "dtype": "f32", "shape": [2], "data": "AACAPwAAQEA="}],
814            "eqns": [{"prim": "add", "inputs": [{"var": 0}, {"lit": "AAAAQA==", "dtype": "f32"}],
815                      "outputs": [{"id": 1, "dtype": "f32", "shape": [2]}], "params": {}}],
816            "outvars": [{"var": 1}]}}"#;
817        let f = from_json(doc).unwrap();
818        let out = ruxla_interp::eval(&f, &[]).unwrap();
819        assert_eq!(out[0].to_vec::<f32>().unwrap(), [3.0, 5.0]);
820    }
821
822    #[test]
823    fn reads_linear_algebra() {
824        // `lax.linalg.qr(x, pivoting=True, full_matrices=False)` and
825        // `jnp.linalg.eigh(s)`, as `ruxla.export_jaxpr` writes them.
826        let doc = r#"{"format_version": 1, "function": {
827            "invars": [{"id": 0, "dtype": "f32", "shape": [4, 3]},
828                       {"id": 1, "dtype": "f32", "shape": [3, 3]}], "constvars": [],
829            "eqns": [
830              {"prim": "qr", "inputs": [{"var": 0}],
831               "outputs": [{"id": 2, "dtype": "f32", "shape": [4, 3]},
832                           {"id": 3, "dtype": "f32", "shape": [3, 3]},
833                           {"id": 4, "dtype": "i32", "shape": [3]}],
834               "params": {"pivoting": true, "full_matrices": false, "use_magma": null}},
835              {"prim": "eigh", "inputs": [{"var": 1}],
836               "outputs": [{"id": 5, "dtype": "f32", "shape": [3, 3]},
837                           {"id": 6, "dtype": "f32", "shape": [3]}],
838               "params": {"lower": true, "sort_eigenvalues": true,
839                          "subset_by_index": null, "algorithm": null}}],
840            "outvars": [{"var": 4}, {"var": 6}]}}"#;
841        let f = from_json(doc).unwrap();
842        let x = ruxla_ir::HostArray::from_vec(
843            vec![
844                1.0f32, 0.0, 5.0, 2.0, 0.1, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
845            ],
846            [4, 3],
847        );
848        let s = ruxla_ir::HostArray::from_vec(
849            vec![2.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 3.0],
850            [3, 3],
851        );
852        let out = ruxla_interp::eval(&f, &[x, s]).unwrap();
853        assert_eq!(out[0].to_vec::<i32>().unwrap(), [2, 0, 1]);
854        assert_eq!(out[1].to_vec::<f32>().unwrap(), [1.0, 2.0, 3.0]);
855        // A subset of the eigenvalues (which JAX computes on TPU only).
856        let partial = doc
857            .replace(r#""subset_by_index": null"#, r#""subset_by_index": [1, 3]"#)
858            .replace(
859                r#"{"id": 5, "dtype": "f32", "shape": [3, 3]}"#,
860                r#"{"id": 5, "dtype": "f32", "shape": [3, 2]}"#,
861            )
862            .replace(
863                r#"{"id": 6, "dtype": "f32", "shape": [3]}"#,
864                r#"{"id": 6, "dtype": "f32", "shape": [2]}"#,
865            );
866        let f = from_json(&partial).unwrap();
867        let s = ruxla_ir::HostArray::from_vec(
868            vec![2.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 3.0],
869            [3, 3],
870        );
871        let x = ruxla_ir::HostArray::from_vec(vec![0.0f32; 12], [4, 3]);
872        let out = ruxla_interp::eval(&f, &[x, s]).unwrap();
873        assert_eq!(out[1].to_vec::<f32>().unwrap(), [2.0, 3.0]);
874        // JAX's names of the algorithms.
875        let jacobi = doc.replace(r#""algorithm": null"#, r#""algorithm": "JACOBI""#);
876        let f = from_json(&jacobi).unwrap();
877        assert!(matches!(
878            f.eqns[1].params,
879            Params::Eigh {
880                algorithm: Some(EighImplementation::Jacobi),
881                ..
882            }
883        ));
884    }
885}