Skip to main content

ruxla_core/
tree.rs

1//! Pytrees: structures of values.
2
3use std::fmt;
4
5use ruxla_kernels::Element;
6
7use crate::backend::Backend;
8use crate::value::{Array, Bool, Scalar};
9
10/// A description of a pytree's structure, for writing it out to other
11/// languages (the field names of structs, for example).
12#[derive(Clone, PartialEq, Eq, Hash, Debug)]
13pub enum TreeDef {
14    /// A leaf (a scalar or an array).
15    Leaf,
16    /// No leaves (`()`).
17    None,
18    /// A tuple.
19    Tuple(Vec<TreeDef>),
20    /// A list (`Vec` or a Rust array).
21    List(Vec<TreeDef>),
22    /// A struct with named fields.
23    Struct {
24        /// The name of the type.
25        name: String,
26        /// The names of the fields.
27        fields: Vec<String>,
28        /// The structures of the fields.
29        children: Vec<TreeDef>,
30    },
31}
32
33impl TreeDef {
34    /// Returns the number of leaves.
35    pub fn num_leaves(&self) -> usize {
36        match self {
37            TreeDef::Leaf => 1,
38            TreeDef::None => 0,
39            TreeDef::Tuple(c) | TreeDef::List(c) | TreeDef::Struct { children: c, .. } => {
40                c.iter().map(TreeDef::num_leaves).sum()
41            }
42        }
43    }
44}
45
46impl fmt::Display for TreeDef {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        let join = |c: &[TreeDef]| {
49            c.iter()
50                .map(ToString::to_string)
51                .collect::<Vec<_>>()
52                .join(", ")
53        };
54        match self {
55            TreeDef::Leaf => f.write_str("*"),
56            TreeDef::None => f.write_str("()"),
57            TreeDef::Tuple(c) => write!(f, "({}{})", join(c), if c.len() == 1 { "," } else { "" }),
58            TreeDef::List(c) => write!(f, "[{}]", join(c)),
59            TreeDef::Struct {
60                name,
61                fields,
62                children,
63            } => {
64                let parts: Vec<String> = fields
65                    .iter()
66                    .zip(children)
67                    .map(|(n, c)| format!("{n}={c}"))
68                    .collect();
69                write!(f, "{name}({})", parts.join(", "))
70            }
71        }
72    }
73}
74
75/// A pytree: a structure of scalars and arrays on backend `B`.
76///
77/// Implement it with `#[derive(Tree)]` for structs whose type parameter is
78/// the backend.
79pub trait Tree<B: Backend>: Clone {
80    /// The same structure on backend `C`.
81    type On<C: Backend>: Tree<C>;
82
83    /// Appends the leaves, in order.
84    fn flatten(&self, leaves: &mut Vec<B::Leaf>);
85
86    /// Builds a value of the same structure from leaves.
87    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self;
88
89    /// Builds a value of the same structure on backend `C` from leaves
90    /// (static fields are copied from `self`).
91    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C>;
92
93    /// Describes the structure.
94    fn def(&self) -> TreeDef;
95
96    /// Selects `on_true` or `on_false` leaf by leaf.
97    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self;
98}
99
100fn next<L>(leaves: &mut dyn Iterator<Item = L>) -> L {
101    leaves.next().expect("too few leaves for the structure")
102}
103
104impl<B: Backend, T: Element> Tree<B> for Scalar<B, T> {
105    type On<C: Backend> = Scalar<C, T>;
106    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
107        leaves.push(B::scalar_leaf::<T>(self.0));
108    }
109    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
110        Scalar(B::leaf_scalar::<T>(next(leaves)))
111    }
112    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Scalar<C, T> {
113        Scalar(C::leaf_scalar::<T>(next(leaves)))
114    }
115    fn def(&self) -> TreeDef {
116        TreeDef::Leaf
117    }
118    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
119        Scalar(B::select::<T>(pred.0, on_true.0, on_false.0))
120    }
121}
122
123impl<B: Backend, T: Element> Tree<B> for Array<B, T> {
124    type On<C: Backend> = Array<C, T>;
125    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
126        leaves.push(B::array_leaf::<T>(&self.0));
127    }
128    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
129        Array(B::leaf_array::<T>(next(leaves)))
130    }
131    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Array<C, T> {
132        Array(C::leaf_array::<T>(next(leaves)))
133    }
134    fn def(&self) -> TreeDef {
135        TreeDef::Leaf
136    }
137    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
138        let shape = on_true.shape();
139        let c = B::broadcast_in_dim::<bool>(&B::to_array::<bool>(pred.0), &shape, &[]);
140        Array(B::a_select::<T>(&c, &on_true.0, &on_false.0))
141    }
142}
143
144impl<B: Backend> Tree<B> for () {
145    type On<C: Backend> = ();
146    fn flatten(&self, _: &mut Vec<B::Leaf>) {}
147    fn unflatten_like(&self, _: &mut dyn Iterator<Item = B::Leaf>) -> Self {}
148    fn rebuild<C: Backend>(&self, _: &mut dyn Iterator<Item = C::Leaf>) {}
149    fn def(&self) -> TreeDef {
150        TreeDef::None
151    }
152    fn select(_: Bool<B>, _: &Self, _: &Self) -> Self {}
153}
154
155macro_rules! tuple_tree {
156    ($($t:ident $i:tt),+) => {
157        impl<B: Backend, $($t: Tree<B>),+> Tree<B> for ($($t,)+) {
158            type On<C: Backend> = ($($t::On<C>,)+);
159            fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
160                $(self.$i.flatten(leaves);)+
161            }
162            fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
163                ($(self.$i.unflatten_like(leaves),)+)
164            }
165            fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
166                ($(self.$i.rebuild::<C>(leaves),)+)
167            }
168            fn def(&self) -> TreeDef {
169                TreeDef::Tuple(vec![$(self.$i.def()),+])
170            }
171            fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
172                ($($t::select(pred, &on_true.$i, &on_false.$i),)+)
173            }
174        }
175    };
176}
177
178tuple_tree!(A 0);
179tuple_tree!(A 0, B1 1);
180tuple_tree!(A 0, B1 1, C1 2);
181tuple_tree!(A 0, B1 1, C1 2, D 3);
182tuple_tree!(A 0, B1 1, C1 2, D 3, E 4);
183tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5);
184tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5, G 6);
185tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5, G 6, H 7);
186
187impl<B: Backend, T: Tree<B>> Tree<B> for Vec<T> {
188    type On<C: Backend> = Vec<T::On<C>>;
189    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
190        self.iter().for_each(|x| x.flatten(leaves));
191    }
192    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
193        self.iter().map(|x| x.unflatten_like(leaves)).collect()
194    }
195    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
196        self.iter().map(|x| x.rebuild::<C>(leaves)).collect()
197    }
198    fn def(&self) -> TreeDef {
199        TreeDef::List(self.iter().map(Tree::def).collect())
200    }
201    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
202        on_true
203            .iter()
204            .zip(on_false)
205            .map(|(a, b)| T::select(pred, a, b))
206            .collect()
207    }
208}
209
210/// `None` has no leaves and `Some(x)` has the leaves of `x`, as `None` and
211/// values are in JAX's pytrees.
212impl<B: Backend, T: Tree<B>> Tree<B> for Option<T> {
213    type On<C: Backend> = Option<T::On<C>>;
214    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
215        if let Some(x) = self {
216            x.flatten(leaves);
217        }
218    }
219    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
220        self.as_ref().map(|x| x.unflatten_like(leaves))
221    }
222    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
223        self.as_ref().map(|x| x.rebuild::<C>(leaves))
224    }
225    fn def(&self) -> TreeDef {
226        self.as_ref().map_or(TreeDef::None, Tree::def)
227    }
228    #[track_caller]
229    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
230        match (on_true, on_false) {
231            (Some(a), Some(b)) => Some(T::select(pred, a, b)),
232            (None, None) => None,
233            _ => panic!("cannot select between `Some` and `None`"),
234        }
235    }
236}
237
238impl<B: Backend, T: Tree<B>, const N: usize> Tree<B> for [T; N] {
239    type On<C: Backend> = [T::On<C>; N];
240    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
241        self.iter().for_each(|x| x.flatten(leaves));
242    }
243    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
244        std::array::from_fn(|i| self[i].unflatten_like(leaves))
245    }
246    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
247        std::array::from_fn(|i| self[i].rebuild::<C>(leaves))
248    }
249    fn def(&self) -> TreeDef {
250        TreeDef::List(self.iter().map(Tree::def).collect())
251    }
252    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
253        std::array::from_fn(|i| T::select(pred, &on_true[i], &on_false[i]))
254    }
255}
256
257/// Selects `on_true` or `on_false` leaf by leaf (`jax.tree.map` of
258/// `lax.select`).
259pub fn select_tree<B: Backend, T: Tree<B>>(pred: Bool<B>, on_true: &T, on_false: &T) -> T {
260    T::select(pred, on_true, on_false)
261}
262
263/// Returns the leaves of a pytree.
264pub fn leaves<B: Backend, T: Tree<B>>(tree: &T) -> Vec<B::Leaf> {
265    let mut l = Vec::new();
266    tree.flatten(&mut l);
267    l
268}
269
270/// Returns the leaves of a pytree as arrays of element type `T` (scalars as
271/// arrays of rank 0), for code that treats every leaf alike, such as
272/// optimizers.
273///
274/// # Panics
275///
276/// Panics if a leaf has another element type.
277///
278/// # Examples
279///
280/// ```
281/// use ruxla_core::{Array, F32, Native, leaves_as};
282///
283/// let tree = (F32::<Native>::new(1.0), Array::<Native, f32>::from_vec(vec![2.0, 3.0], [2]));
284/// let arrays = leaves_as::<Native, f32, _>(&tree);
285/// assert_eq!(arrays[1].to_vec(), [2.0, 3.0]);
286/// ```
287#[track_caller]
288pub fn leaves_as<B: Backend, T: Element, X: Tree<B>>(tree: &X) -> Vec<Array<B, T>> {
289    leaves(tree)
290        .into_iter()
291        .map(|l| {
292            let dtype = B::leaf_aval(&l).dtype;
293            assert_eq!(
294                dtype,
295                T::DTYPE,
296                "expected leaves of type {}, got {dtype}",
297                T::DTYPE
298            );
299            Array(B::leaf_array::<T>(l))
300        })
301        .collect()
302}
303
304/// Builds a pytree with the structure of `like` from arrays, one per leaf
305/// (the inverse of [`leaves_as`]).
306///
307/// # Panics
308///
309/// Panics if the number of arrays differs from the number of leaves.
310#[track_caller]
311pub fn unflatten_arrays<B: Backend, T: Element, X: Tree<B>>(
312    like: &X,
313    arrays: Vec<Array<B, T>>,
314) -> X {
315    let n = arrays.len();
316    let mut it = arrays.iter().map(|a| B::array_leaf::<T>(&a.0));
317    let out = like.unflatten_like(&mut it);
318    assert!(
319        it.next().is_none() && leaves(like).len() == n,
320        "expected one array per leaf"
321    );
322    out
323}