ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! Pytrees: structures of values.

use std::fmt;

use ruxla_kernels::Element;

use crate::backend::Backend;
use crate::value::{Array, Bool, Scalar};

/// A description of a pytree's structure, for writing it out to other
/// languages (the field names of structs, for example).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum TreeDef {
    /// A leaf (a scalar or an array).
    Leaf,
    /// No leaves (`()`).
    None,
    /// A tuple.
    Tuple(Vec<TreeDef>),
    /// A list (`Vec` or a Rust array).
    List(Vec<TreeDef>),
    /// A struct with named fields.
    Struct {
        /// The name of the type.
        name: String,
        /// The names of the fields.
        fields: Vec<String>,
        /// The structures of the fields.
        children: Vec<TreeDef>,
    },
}

impl TreeDef {
    /// Returns the number of leaves.
    pub fn num_leaves(&self) -> usize {
        match self {
            TreeDef::Leaf => 1,
            TreeDef::None => 0,
            TreeDef::Tuple(c) | TreeDef::List(c) | TreeDef::Struct { children: c, .. } => {
                c.iter().map(TreeDef::num_leaves).sum()
            }
        }
    }
}

impl fmt::Display for TreeDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let join = |c: &[TreeDef]| {
            c.iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        };
        match self {
            TreeDef::Leaf => f.write_str("*"),
            TreeDef::None => f.write_str("()"),
            TreeDef::Tuple(c) => write!(f, "({}{})", join(c), if c.len() == 1 { "," } else { "" }),
            TreeDef::List(c) => write!(f, "[{}]", join(c)),
            TreeDef::Struct {
                name,
                fields,
                children,
            } => {
                let parts: Vec<String> = fields
                    .iter()
                    .zip(children)
                    .map(|(n, c)| format!("{n}={c}"))
                    .collect();
                write!(f, "{name}({})", parts.join(", "))
            }
        }
    }
}

/// A pytree: a structure of scalars and arrays on backend `B`.
///
/// Implement it with `#[derive(Tree)]` for structs whose type parameter is
/// the backend.
pub trait Tree<B: Backend>: Clone {
    /// The same structure on backend `C`.
    type On<C: Backend>: Tree<C>;

    /// Appends the leaves, in order.
    fn flatten(&self, leaves: &mut Vec<B::Leaf>);

    /// Builds a value of the same structure from leaves.
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self;

    /// Builds a value of the same structure on backend `C` from leaves
    /// (static fields are copied from `self`).
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C>;

    /// Describes the structure.
    fn def(&self) -> TreeDef;

    /// Selects `on_true` or `on_false` leaf by leaf.
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self;
}

fn next<L>(leaves: &mut dyn Iterator<Item = L>) -> L {
    leaves.next().expect("too few leaves for the structure")
}

impl<B: Backend, T: Element> Tree<B> for Scalar<B, T> {
    type On<C: Backend> = Scalar<C, T>;
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        leaves.push(B::scalar_leaf::<T>(self.0));
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        Scalar(B::leaf_scalar::<T>(next(leaves)))
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Scalar<C, T> {
        Scalar(C::leaf_scalar::<T>(next(leaves)))
    }
    fn def(&self) -> TreeDef {
        TreeDef::Leaf
    }
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        Scalar(B::select::<T>(pred.0, on_true.0, on_false.0))
    }
}

impl<B: Backend, T: Element> Tree<B> for Array<B, T> {
    type On<C: Backend> = Array<C, T>;
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        leaves.push(B::array_leaf::<T>(&self.0));
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        Array(B::leaf_array::<T>(next(leaves)))
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Array<C, T> {
        Array(C::leaf_array::<T>(next(leaves)))
    }
    fn def(&self) -> TreeDef {
        TreeDef::Leaf
    }
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        let shape = on_true.shape();
        let c = B::broadcast_in_dim::<bool>(&B::to_array::<bool>(pred.0), &shape, &[]);
        Array(B::a_select::<T>(&c, &on_true.0, &on_false.0))
    }
}

impl<B: Backend> Tree<B> for () {
    type On<C: Backend> = ();
    fn flatten(&self, _: &mut Vec<B::Leaf>) {}
    fn unflatten_like(&self, _: &mut dyn Iterator<Item = B::Leaf>) -> Self {}
    fn rebuild<C: Backend>(&self, _: &mut dyn Iterator<Item = C::Leaf>) {}
    fn def(&self) -> TreeDef {
        TreeDef::None
    }
    fn select(_: Bool<B>, _: &Self, _: &Self) -> Self {}
}

macro_rules! tuple_tree {
    ($($t:ident $i:tt),+) => {
        impl<B: Backend, $($t: Tree<B>),+> Tree<B> for ($($t,)+) {
            type On<C: Backend> = ($($t::On<C>,)+);
            fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
                $(self.$i.flatten(leaves);)+
            }
            fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
                ($(self.$i.unflatten_like(leaves),)+)
            }
            fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
                ($(self.$i.rebuild::<C>(leaves),)+)
            }
            fn def(&self) -> TreeDef {
                TreeDef::Tuple(vec![$(self.$i.def()),+])
            }
            fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
                ($($t::select(pred, &on_true.$i, &on_false.$i),)+)
            }
        }
    };
}

tuple_tree!(A 0);
tuple_tree!(A 0, B1 1);
tuple_tree!(A 0, B1 1, C1 2);
tuple_tree!(A 0, B1 1, C1 2, D 3);
tuple_tree!(A 0, B1 1, C1 2, D 3, E 4);
tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5);
tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5, G 6);
tuple_tree!(A 0, B1 1, C1 2, D 3, E 4, F 5, G 6, H 7);

impl<B: Backend, T: Tree<B>> Tree<B> for Vec<T> {
    type On<C: Backend> = Vec<T::On<C>>;
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        self.iter().for_each(|x| x.flatten(leaves));
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        self.iter().map(|x| x.unflatten_like(leaves)).collect()
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
        self.iter().map(|x| x.rebuild::<C>(leaves)).collect()
    }
    fn def(&self) -> TreeDef {
        TreeDef::List(self.iter().map(Tree::def).collect())
    }
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        on_true
            .iter()
            .zip(on_false)
            .map(|(a, b)| T::select(pred, a, b))
            .collect()
    }
}

/// `None` has no leaves and `Some(x)` has the leaves of `x`, as `None` and
/// values are in JAX's pytrees.
impl<B: Backend, T: Tree<B>> Tree<B> for Option<T> {
    type On<C: Backend> = Option<T::On<C>>;
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        if let Some(x) = self {
            x.flatten(leaves);
        }
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        self.as_ref().map(|x| x.unflatten_like(leaves))
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
        self.as_ref().map(|x| x.rebuild::<C>(leaves))
    }
    fn def(&self) -> TreeDef {
        self.as_ref().map_or(TreeDef::None, Tree::def)
    }
    #[track_caller]
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        match (on_true, on_false) {
            (Some(a), Some(b)) => Some(T::select(pred, a, b)),
            (None, None) => None,
            _ => panic!("cannot select between `Some` and `None`"),
        }
    }
}

impl<B: Backend, T: Tree<B>, const N: usize> Tree<B> for [T; N] {
    type On<C: Backend> = [T::On<C>; N];
    fn flatten(&self, leaves: &mut Vec<B::Leaf>) {
        self.iter().for_each(|x| x.flatten(leaves));
    }
    fn unflatten_like(&self, leaves: &mut dyn Iterator<Item = B::Leaf>) -> Self {
        std::array::from_fn(|i| self[i].unflatten_like(leaves))
    }
    fn rebuild<C: Backend>(&self, leaves: &mut dyn Iterator<Item = C::Leaf>) -> Self::On<C> {
        std::array::from_fn(|i| self[i].rebuild::<C>(leaves))
    }
    fn def(&self) -> TreeDef {
        TreeDef::List(self.iter().map(Tree::def).collect())
    }
    fn select(pred: Bool<B>, on_true: &Self, on_false: &Self) -> Self {
        std::array::from_fn(|i| T::select(pred, &on_true[i], &on_false[i]))
    }
}

/// Selects `on_true` or `on_false` leaf by leaf (`jax.tree.map` of
/// `lax.select`).
pub fn select_tree<B: Backend, T: Tree<B>>(pred: Bool<B>, on_true: &T, on_false: &T) -> T {
    T::select(pred, on_true, on_false)
}

/// Returns the leaves of a pytree.
pub fn leaves<B: Backend, T: Tree<B>>(tree: &T) -> Vec<B::Leaf> {
    let mut l = Vec::new();
    tree.flatten(&mut l);
    l
}

/// Returns the leaves of a pytree as arrays of element type `T` (scalars as
/// arrays of rank 0), for code that treats every leaf alike, such as
/// optimizers.
///
/// # Panics
///
/// Panics if a leaf has another element type.
///
/// # Examples
///
/// ```
/// use ruxla_core::{Array, F32, Native, leaves_as};
///
/// let tree = (F32::<Native>::new(1.0), Array::<Native, f32>::from_vec(vec![2.0, 3.0], [2]));
/// let arrays = leaves_as::<Native, f32, _>(&tree);
/// assert_eq!(arrays[1].to_vec(), [2.0, 3.0]);
/// ```
#[track_caller]
pub fn leaves_as<B: Backend, T: Element, X: Tree<B>>(tree: &X) -> Vec<Array<B, T>> {
    leaves(tree)
        .into_iter()
        .map(|l| {
            let dtype = B::leaf_aval(&l).dtype;
            assert_eq!(
                dtype,
                T::DTYPE,
                "expected leaves of type {}, got {dtype}",
                T::DTYPE
            );
            Array(B::leaf_array::<T>(l))
        })
        .collect()
}

/// Builds a pytree with the structure of `like` from arrays, one per leaf
/// (the inverse of [`leaves_as`]).
///
/// # Panics
///
/// Panics if the number of arrays differs from the number of leaves.
#[track_caller]
pub fn unflatten_arrays<B: Backend, T: Element, X: Tree<B>>(
    like: &X,
    arrays: Vec<Array<B, T>>,
) -> X {
    let n = arrays.len();
    let mut it = arrays.iter().map(|a| B::array_leaf::<T>(&a.0));
    let out = like.unflatten_like(&mut it);
    assert!(
        it.next().is_none() && leaves(like).len() == n,
        "expected one array per leaf"
    );
    out
}