Skip to main content

ruxla_ir/
print.rs

1//! Printing functions in the jaxpr format.
2
3use std::collections::HashMap;
4use std::fmt::{self, Write};
5
6use ruxla_kernels::Value;
7use ruxla_kernels::array::GatherScatterMode;
8
9use crate::function::{Atom, Eqn, Function, Params, Precision, RoundingMethod, SelectPrim, Var};
10
11impl fmt::Display for Function {
12    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13        let mut p = Printer::default();
14        p.function(self, 0)?;
15        f.write_str(&p.out)
16    }
17}
18
19/// Names variables `a`, ..., `z`, `ba`, ... in order of appearance.
20#[derive(Default)]
21struct Printer {
22    out: String,
23    names: HashMap<u64, String>,
24}
25
26enum Entry<'a> {
27    Text(String),
28    Function(&'a Function),
29    Functions(Vec<&'a Function>),
30}
31
32impl Printer {
33    fn name(&mut self, v: &Var) -> String {
34        let n = self.names.len();
35        self.names
36            .entry(v.id())
37            .or_insert_with(|| alphabetic(n))
38            .clone()
39    }
40
41    fn binder(&mut self, v: &Var) -> String {
42        format!("{}:{}", self.name(v), v.aval())
43    }
44
45    fn atom(&mut self, a: &Atom) -> String {
46        match a {
47            Atom::Var(v) => self.name(v),
48            Atom::Lit(l) => format!("{}:{}", scalar(l.value().get(0)), l.value().aval()),
49        }
50    }
51
52    fn function(&mut self, f: &Function, indent: usize) -> fmt::Result {
53        let consts: Vec<String> = f.constvars.iter().map(|(v, _)| self.binder(v)).collect();
54        let ins: Vec<String> = f.invars.iter().map(|v| self.binder(v)).collect();
55        let sep = |v: &[String]| {
56            if v.is_empty() {
57                String::new()
58            } else {
59                format!(" {}", v.join(" "))
60            }
61        };
62        write!(self.out, "{{ lambda{} ;{}. let", sep(&consts), sep(&ins))?;
63        for eqn in &f.eqns {
64            write!(self.out, "\n{:w$}", "", w = indent + 4)?;
65            self.eqn(eqn, indent + 4)?;
66        }
67        let outs: Vec<String> = f.outvars.iter().map(|a| self.atom(a)).collect();
68        let trailing = if outs.len() == 1 { "," } else { "" };
69        write!(
70            self.out,
71            "\n{:w$}in ({}{trailing}) }}",
72            "",
73            outs.join(", "),
74            w = indent + 2
75        )
76    }
77
78    fn eqn(&mut self, eqn: &Eqn, indent: usize) -> fmt::Result {
79        let outs: Vec<String> = eqn.outputs.iter().map(|v| self.binder(v)).collect();
80        write!(self.out, "{} = {}", outs.join(" "), eqn.prim)?;
81        self.params(&eqn.params, indent)?;
82        for a in &eqn.inputs {
83            let s = self.atom(a);
84            write!(self.out, " {s}")?;
85        }
86        Ok(())
87    }
88
89    fn params(&mut self, params: &Params, indent: usize) -> fmt::Result {
90        let entries: Vec<(&str, String)> = match params {
91            Params::None => return Ok(()),
92            Params::Convert { new_dtype } => vec![("new_dtype", new_dtype.to_string())],
93            Params::Extern { name, module, .. } => vec![
94                ("name", name.clone()),
95                ("module", format!("<{} bytes>", module.len())),
96            ],
97            Params::Round { method } => vec![(
98                "rounding_method",
99                String::from(match method {
100                    RoundingMethod::AwayFromZero => "AWAY_FROM_ZERO",
101                    RoundingMethod::ToNearestEven => "TO_NEAREST_EVEN",
102                }),
103            )],
104            Params::IntegerPow { y } => vec![("y", y.to_string())],
105            Params::BroadcastInDim {
106                shape,
107                broadcast_dimensions,
108            } => vec![
109                ("broadcast_dimensions", tuple(broadcast_dimensions)),
110                ("shape", tuple(shape)),
111            ],
112            Params::Reshape { new_sizes } => vec![("new_sizes", tuple(new_sizes))],
113            Params::Transpose { permutation } => vec![("permutation", tuple(permutation))],
114            Params::Reduce { axes } => vec![("axes", tuple(axes))],
115            Params::ArgMinMax { axis, index_dtype } => {
116                vec![
117                    ("axes", tuple(&[*axis])),
118                    ("index_dtype", index_dtype.to_string()),
119                ]
120            }
121            Params::DotGeneral {
122                dimension_numbers: d,
123                precision,
124                preferred_element_type,
125            } => vec![
126                (
127                    "dimension_numbers",
128                    format!(
129                        "(({}, {}), ({}, {}))",
130                        list(&d.lhs_contracting),
131                        list(&d.rhs_contracting),
132                        list(&d.lhs_batch),
133                        list(&d.rhs_batch)
134                    ),
135                ),
136                ("precision", precision_name(*precision)),
137                (
138                    "preferred_element_type",
139                    preferred_element_type.map_or(String::from("None"), |d| d.to_string()),
140                ),
141            ],
142            Params::ConvGeneralDilated {
143                window_strides,
144                padding,
145                lhs_dilation,
146                rhs_dilation,
147                dimension_numbers: d,
148                feature_group_count,
149                batch_group_count,
150                precision,
151                preferred_element_type,
152            } => vec![
153                ("batch_group_count", batch_group_count.to_string()),
154                (
155                    "dimension_numbers",
156                    format!(
157                        "ConvDimensionNumbers(lhs_spec={}, rhs_spec={}, out_spec={})",
158                        tuple(&d.lhs_spec),
159                        tuple(&d.rhs_spec),
160                        tuple(&d.out_spec)
161                    ),
162                ),
163                ("feature_group_count", feature_group_count.to_string()),
164                ("lhs_dilation", tuple(lhs_dilation)),
165                ("padding", pairs(padding)),
166                ("precision", precision_name(*precision)),
167                (
168                    "preferred_element_type",
169                    preferred_element_type.map_or(String::from("None"), |d| d.to_string()),
170                ),
171                ("rhs_dilation", tuple(rhs_dilation)),
172                ("window_strides", tuple(window_strides)),
173            ],
174            Params::ReduceWindow {
175                window_dimensions,
176                window_strides,
177                padding,
178                base_dilation,
179                window_dilation,
180            } => vec![
181                ("base_dilation", tuple(base_dilation)),
182                ("padding", pairs(padding)),
183                ("window_dilation", tuple(window_dilation)),
184                ("window_dimensions", tuple(window_dimensions)),
185                ("window_strides", tuple(window_strides)),
186            ],
187            Params::SelectAndScatterAdd {
188                select_prim,
189                window_dimensions,
190                window_strides,
191                padding,
192            } => vec![
193                ("padding", pairs(padding)),
194                ("select_prim", select_name(*select_prim)),
195                ("window_dimensions", tuple(window_dimensions)),
196                ("window_strides", tuple(window_strides)),
197            ],
198            Params::SelectAndGatherAdd {
199                select_prim,
200                window_dimensions,
201                window_strides,
202                padding,
203                base_dilation,
204                window_dilation,
205            } => vec![
206                ("base_dilation", tuple(base_dilation)),
207                ("padding", pairs(padding)),
208                ("select_prim", select_name(*select_prim)),
209                ("window_dilation", tuple(window_dilation)),
210                ("window_dimensions", tuple(window_dimensions)),
211                ("window_strides", tuple(window_strides)),
212            ],
213            Params::Iota {
214                dtype,
215                shape,
216                dimension,
217            } => vec![
218                ("dimension", dimension.to_string()),
219                ("dtype", dtype.to_string()),
220                ("shape", tuple(shape)),
221            ],
222            Params::Slice {
223                start_indices,
224                limit_indices,
225                strides,
226            } => vec![
227                ("limit_indices", tuple(limit_indices)),
228                ("start_indices", tuple(start_indices)),
229                (
230                    "strides",
231                    if strides.iter().all(|&s| s == 1) {
232                        String::from("None")
233                    } else {
234                        tuple(strides)
235                    },
236                ),
237            ],
238            Params::DynamicSlice { slice_sizes } => vec![("slice_sizes", tuple(slice_sizes))],
239            Params::Concatenate { dimension } => vec![("dimension", dimension.to_string())],
240            Params::Pad { padding_config } => {
241                let items: Vec<String> = padding_config
242                    .iter()
243                    .map(|(l, h, i)| format!("({l}, {h}, {i})"))
244                    .collect();
245                let trailing = if items.len() == 1 { "," } else { "" };
246                vec![(
247                    "padding_config",
248                    format!("({}{trailing})", items.join(", ")),
249                )]
250            }
251            Params::Rev { dimensions } => vec![("dimensions", tuple(dimensions))],
252            Params::Sort {
253                dimension,
254                is_stable,
255                num_keys,
256            } => vec![
257                ("dimension", dimension.to_string()),
258                ("is_stable", py_bool(*is_stable)),
259                ("num_keys", num_keys.to_string()),
260            ],
261            Params::Cumulative { axis, reverse } => {
262                vec![("axis", axis.to_string()), ("reverse", py_bool(*reverse))]
263            }
264            // JAX prints the integer value of the `FftType` enum.
265            Params::Fft {
266                fft_type,
267                fft_lengths,
268            } => vec![
269                ("fft_lengths", tuple(fft_lengths)),
270                ("fft_type", fft_type.index().to_string()),
271            ],
272            Params::TopK { k, axis, is_stable } => vec![
273                ("axis", axis.to_string()),
274                ("is_stable", py_bool(*is_stable)),
275                ("k", k.to_string()),
276            ],
277            Params::TriangularSolve {
278                left_side,
279                lower,
280                transpose_a,
281                conjugate_a,
282                unit_diagonal,
283            } => vec![
284                ("conjugate_a", py_bool(*conjugate_a)),
285                ("left_side", py_bool(*left_side)),
286                ("lower", py_bool(*lower)),
287                ("transpose_a", py_bool(*transpose_a)),
288                ("unit_diagonal", py_bool(*unit_diagonal)),
289            ],
290            Params::LuPivotsToPermutation { permutation_size } => {
291                vec![("permutation_size", permutation_size.to_string())]
292            }
293            Params::Qr {
294                full_matrices,
295                pivoting,
296            } => vec![
297                ("full_matrices", py_bool(*full_matrices)),
298                ("pivoting", py_bool(*pivoting)),
299                ("use_magma", String::from("None")),
300            ],
301            Params::Eigh {
302                lower,
303                sort_eigenvalues,
304                subset_by_index,
305                algorithm,
306            } => vec![
307                (
308                    "algorithm",
309                    algorithm.map_or_else(
310                        || String::from("None"),
311                        |a| format!("EighImplementation.{}", a.name()),
312                    ),
313                ),
314                ("lower", py_bool(*lower)),
315                ("sort_eigenvalues", py_bool(*sort_eigenvalues)),
316                ("subset_by_index", py_range(*subset_by_index)),
317            ],
318            Params::Schur {
319                compute_schur_vectors,
320            } => vec![
321                ("compute_schur_vectors", py_bool(*compute_schur_vectors)),
322                ("select_callable", String::from("None")),
323                ("sort_eig_vals", String::from("False")),
324            ],
325            Params::Ormqr { left, transpose } => {
326                vec![("left", py_bool(*left)), ("transpose", py_bool(*transpose))]
327            }
328            Params::SymmetricProduct { alpha, beta } => {
329                vec![
330                    ("alpha", format!("{alpha:?}")),
331                    ("beta", format!("{beta:?}")),
332                ]
333            }
334            Params::HostCallback { callback, .. } => {
335                vec![("callback", callback.name().to_string())]
336            }
337            Params::Tridiagonal { lower } => vec![("lower", py_bool(*lower))],
338            Params::TridiagonalSolve { perturb_singular } => {
339                vec![("perturb_singular", py_bool(*perturb_singular))]
340            }
341            Params::Eig {
342                compute_left_eigenvectors,
343                compute_right_eigenvectors,
344                enable_eigvec_derivs,
345            } => vec![
346                (
347                    "compute_left_eigenvectors",
348                    py_bool(*compute_left_eigenvectors),
349                ),
350                (
351                    "compute_right_eigenvectors",
352                    py_bool(*compute_right_eigenvectors),
353                ),
354                ("enable_eigvec_derivs", py_bool(*enable_eigvec_derivs)),
355                ("implementation", String::from("None")),
356            ],
357            Params::Svd {
358                full_matrices,
359                compute_uv,
360                subset_by_index,
361                algorithm,
362            } => vec![
363                (
364                    "algorithm",
365                    algorithm.map_or_else(
366                        || String::from("None"),
367                        |a| format!("SvdAlgorithm.{}", a.name()),
368                    ),
369                ),
370                ("compute_uv", py_bool(*compute_uv)),
371                ("full_matrices", py_bool(*full_matrices)),
372                ("subset_by_index", py_range(*subset_by_index)),
373            ],
374            Params::Gather {
375                dimension_numbers: d,
376                slice_sizes,
377                mode,
378                indices_are_sorted,
379                unique_indices,
380            } => vec![
381                (
382                    "dimension_numbers",
383                    format!(
384                        "GatherDimensionNumbers(offset_dims={}, collapsed_slice_dims={}, start_index_map={}, \
385                         operand_batching_dims={}, start_indices_batching_dims={})",
386                        tuple(&d.offset_dims),
387                        tuple(&d.collapsed_slice_dims),
388                        tuple(&d.start_index_map),
389                        tuple(&d.operand_batching_dims),
390                        tuple(&d.start_indices_batching_dims)
391                    ),
392                ),
393                ("fill_value", String::from("None")),
394                ("indices_are_sorted", py_bool(*indices_are_sorted)),
395                ("mode", mode_name(*mode)),
396                ("slice_sizes", tuple(slice_sizes)),
397                ("unique_indices", py_bool(*unique_indices)),
398            ],
399            Params::Scatter {
400                dimension_numbers: d,
401                mode,
402                indices_are_sorted,
403                unique_indices,
404            } => vec![
405                (
406                    "dimension_numbers",
407                    format!(
408                        "ScatterDimensionNumbers(update_window_dims={}, inserted_window_dims={}, \
409                         scatter_dims_to_operand_dims={}, operand_batching_dims={}, \
410                         scatter_indices_batching_dims={})",
411                        tuple(&d.update_window_dims),
412                        tuple(&d.inserted_window_dims),
413                        tuple(&d.scatter_dims_to_operand_dims),
414                        tuple(&d.operand_batching_dims),
415                        tuple(&d.scatter_indices_batching_dims)
416                    ),
417                ),
418                ("indices_are_sorted", py_bool(*indices_are_sorted)),
419                ("mode", mode_name(*mode)),
420                ("unique_indices", py_bool(*unique_indices)),
421            ],
422            Params::Cond { branches } => {
423                return self.multiline(
424                    vec![(
425                        "branches",
426                        Entry::Functions(branches.iter().map(AsRef::as_ref).collect()),
427                    )],
428                    indent,
429                );
430            }
431            Params::While {
432                cond,
433                body,
434                cond_nconsts,
435                body_nconsts,
436            } => {
437                return self.multiline(
438                    vec![
439                        ("body_jaxpr", Entry::Function(body)),
440                        ("body_nconsts", Entry::Text(body_nconsts.to_string())),
441                        ("cond_jaxpr", Entry::Function(cond)),
442                        ("cond_nconsts", Entry::Text(cond_nconsts.to_string())),
443                    ],
444                    indent,
445                );
446            }
447            Params::Scan {
448                body,
449                length,
450                reverse,
451                num_consts,
452                num_carry,
453            } => {
454                return self.multiline(
455                    vec![
456                        ("jaxpr", Entry::Function(body)),
457                        ("length", Entry::Text(length.to_string())),
458                        ("num_carry", Entry::Text(num_carry.to_string())),
459                        ("num_consts", Entry::Text(num_consts.to_string())),
460                        ("reverse", Entry::Text(py_bool(*reverse))),
461                    ],
462                    indent,
463                );
464            }
465            Params::CustomJvp {
466                call,
467                jvp,
468                num_consts,
469            } => {
470                return self.multiline(
471                    vec![
472                        ("call_jaxpr", Entry::Function(call)),
473                        ("jvp", Entry::Function(jvp)),
474                        ("num_consts", Entry::Text(num_consts.to_string())),
475                    ],
476                    indent,
477                );
478            }
479            Params::CustomVjp {
480                call,
481                fwd,
482                bwd,
483                num_consts,
484            } => {
485                return self.multiline(
486                    vec![
487                        ("bwd", Entry::Function(bwd)),
488                        ("call_jaxpr", Entry::Function(call)),
489                        ("fwd", Entry::Function(fwd)),
490                        ("num_consts", Entry::Text(num_consts.to_string())),
491                    ],
492                    indent,
493                );
494            }
495            Params::CustomLin { bwd, num_res } => {
496                return self.multiline(
497                    vec![
498                        ("bwd", Entry::Function(bwd)),
499                        ("num_res", Entry::Text(num_res.to_string())),
500                    ],
501                    indent,
502                );
503            }
504            Params::Checkpoint { body } => {
505                return self.multiline(
506                    vec![
507                        ("jaxpr", Entry::Function(body)),
508                        ("prevent_cse", Entry::Text(py_bool(true))),
509                    ],
510                    indent,
511                );
512            }
513            Params::Jit { name, body } => {
514                return self.multiline(
515                    vec![
516                        ("jaxpr", Entry::Function(body)),
517                        ("name", Entry::Text(name.clone())),
518                    ],
519                    indent,
520                );
521            }
522        };
523        let joined: Vec<String> = entries.iter().map(|(k, v)| format!("{k}={v}")).collect();
524        write!(self.out, "[{}]", joined.join(" "))
525    }
526
527    fn multiline(&mut self, entries: Vec<(&str, Entry<'_>)>, indent: usize) -> fmt::Result {
528        let pad = " ".repeat(indent + 2);
529        self.out.push('[');
530        for (name, entry) in entries {
531            write!(self.out, "\n{pad}{name}=")?;
532            match entry {
533                Entry::Text(t) => self.out.push_str(&t),
534                Entry::Function(f) => self.function(f, indent + 2)?,
535                Entry::Functions(fs) => {
536                    self.out.push('(');
537                    for f in fs {
538                        write!(self.out, "\n{pad}  ")?;
539                        self.function(f, indent + 4)?;
540                    }
541                    write!(self.out, "\n{pad})")?;
542                }
543            }
544        }
545        write!(self.out, "\n{:indent$}]", "")
546    }
547}
548
549fn scalar(v: Value) -> String {
550    match v {
551        Value::Bool(b) => py_bool(b),
552        Value::Int(i) => i.to_string(),
553        Value::UInt(u) => u.to_string(),
554        Value::Float(f) => format!("{f:?}"),
555        // As Python prints complex numbers.
556        Value::Complex(re, im) => {
557            let sign = if im.is_sign_negative() { "-" } else { "+" };
558            format!("({re:?}{sign}{:?}j)", im.abs())
559        }
560    }
561}
562
563fn mode_name(mode: GatherScatterMode) -> String {
564    String::from(match mode {
565        GatherScatterMode::Clip => "GatherScatterMode.CLIP",
566        GatherScatterMode::FillOrDrop => "GatherScatterMode.FILL_OR_DROP",
567        GatherScatterMode::PromiseInBounds => "GatherScatterMode.PROMISE_IN_BOUNDS",
568    })
569}
570
571fn alphabetic(mut n: usize) -> String {
572    let mut digits = Vec::new();
573    loop {
574        digits.push(b'a' + (n % 26) as u8);
575        n /= 26;
576        if n == 0 {
577            break;
578        }
579    }
580    digits.reverse();
581    String::from_utf8(digits).expect("ASCII")
582}
583
584/// `None` or a Python pair `(start, end)`.
585fn py_range(range: Option<(usize, usize)>) -> String {
586    range.map_or_else(|| String::from("None"), |(a, b)| format!("({a}, {b})"))
587}
588
589fn py_bool(b: bool) -> String {
590    String::from(if b { "True" } else { "False" })
591}
592
593fn tuple(items: &[usize]) -> String {
594    match items {
595        [x] => format!("({x},)"),
596        _ => format!(
597            "({})",
598            items
599                .iter()
600                .map(ToString::to_string)
601                .collect::<Vec<_>>()
602                .join(", ")
603        ),
604    }
605}
606
607fn precision_name(precision: Precision) -> String {
608    String::from(match precision {
609        Precision::Default => "None",
610        Precision::High => "HIGH",
611        Precision::Highest => "HIGHEST",
612    })
613}
614
615fn select_name(select_prim: SelectPrim) -> String {
616    String::from(match select_prim {
617        SelectPrim::Ge => "ge",
618        SelectPrim::Le => "le",
619    })
620}
621
622/// Formats `(low, high)` pairs as a Python tuple of tuples.
623fn pairs(items: &[(i64, i64)]) -> String {
624    let parts: Vec<String> = items.iter().map(|(l, h)| format!("({l}, {h})")).collect();
625    let trailing = if parts.len() == 1 { "," } else { "" };
626    format!("({}{trailing})", parts.join(", "))
627}
628
629fn list(items: &[usize]) -> String {
630    format!(
631        "[{}]",
632        items
633            .iter()
634            .map(ToString::to_string)
635            .collect::<Vec<_>>()
636            .join(", ")
637    )
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643
644    #[test]
645    fn names_and_tuples() {
646        assert_eq!(alphabetic(0), "a");
647        assert_eq!(alphabetic(26), "ba");
648        assert_eq!(tuple(&[3]), "(3,)");
649        assert_eq!(tuple(&[]), "()");
650        assert_eq!(list(&[1, 2]), "[1, 2]");
651        assert_eq!(pairs(&[(1, -1)]), "((1, -1),)");
652        assert_eq!(pairs(&[]), "()");
653        assert_eq!(scalar(Value::Complex(1.0, -2.5)), "(1.0-2.5j)");
654    }
655}