diff --git a/src/expr.rs b/src/expr.rs new file mode 100644 index 0000000..3a3c4cc --- /dev/null +++ b/src/expr.rs @@ -0,0 +1,201 @@ +//! Tensors read as expressions: the tree of building blocks a tensor is +//! composed of, with their types erased, so that it can be inspected and +//! rewritten into an equal one before it is evaluated. The compositions of +//! `function` fix their shape in their type, which a rewrite cannot change; an +//! `Expr` holds it as data. +//! +//! There is no second way of building a tensor here. The tree of any tensor +//! built with the functions of this crate is read through `Function::parts` +//! when it is rewritten, and every node of an expression evaluates as the +//! composition it stands for, built with `compose` and `multiset_lift` out of +//! the very parts it was read from. + +use std::fmt; +use std::rc::Rc; + +use crate::function::{Function, Parts, compose, multiset_lift}; +use crate::multiset::Multiset; +use crate::sets::{HRect, Multisets, Values}; +use crate::tensor::Tensor; + +/// A tensor, with its type erased. +pub type TensorMap = Rc>>; + +/// A function on values `f: π•Š β†’ π•Š`, with its type erased. +pub type ValueMap = Rc, Codomain = Values>>; + +/// An index map `ρ`, with its type erased. +pub type IndexMap = Rc>; + +/// An index function to multisets of indices `ψ`, with its type erased. Its +/// codomain tells how many indices it may send one to. +pub type MultiIndexMap = Rc>>; + +/// A reduction `Ξ©`, with its type erased. Its neutral element is what it gives +/// for the empty multiset. +pub type ReductionMap = Rc>, Codomain = Values>>; + +/// A tensor on a hrect, read as an expression tree. Cloning one shares the +/// tree, and a rewrite shares every subtree it leaves unchanged. +pub struct Expr(Rc>); + +struct Inner { + node: Node, + // What the node evaluates as: the tensor it was read from, or the + // composition of its parts. + tensor: TensorMap, +} + +/// The node at the root of an expression. +pub enum Node { + /// A tensor that is not looked into: a leaf of the tree, such as the + /// physical tensor holding the stored values of a sparse tensor. + Tensor(TensorMap), + /// `f ∘ T`: `f` applied to each value of `T`. + Map { f: ValueMap, input: Expr }, + /// `T ∘ ρ`: `T` read through the index map `ρ`. + Reindex { input: Expr, rho: IndexMap }, + /// `Ξ© ∘ Εͺ ∘ ψ`: at each index, `Ξ©` of the values of `U` at the indices `ψ` + /// maps it to. + Reduce { + omega: ReductionMap, + u: Expr, + psi: MultiIndexMap, + }, +} + +// Written out rather than derived, which would require `A: Clone`: cloning an +// expression only shares it. +impl Clone for Expr { + fn clone(&self) -> Self { + Self(Rc::clone(&self.0)) + } +} + +impl Expr { + pub fn node(&self) -> &Node { + &self.0.node + } + + /// The tensor the expression evaluates as. + pub fn tensor(&self) -> TensorMap { + Rc::clone(&self.0.tensor) + } + + /// Whether two expressions are the same one, not only equal. + pub(crate) fn ptr_eq(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +impl Expr { + /// The expression of `tensor`, read from the way it was built. What is not + /// a composition of a function on values after a tensor, of a tensor after + /// an index map, or of a reduction after a lifted tensor after an index + /// function, is a leaf: a function on values from another type, a jagged + /// tensor, or any tensor whose parts are not known. + pub(crate) fn of(tensor: impl Tensor + 'static) -> Self { + Self::read(Rc::new(tensor)) + } + + fn read(tensor: TensorMap) -> Self { + let node = Self::node_of(&tensor).unwrap_or_else(|| Node::Tensor(Rc::clone(&tensor))); + Self(Rc::new(Inner { node, tensor })) + } + + fn node_of(tensor: &TensorMap) -> Option> { + let Parts::Composition { outer, inner } = tensor.parts()? else { + return None; + }; + if let (Some(f), Some(input)) = ( + outer.get::, Values>(), + inner.get::>(), + ) { + return Some(Node::Map { + f, + input: Self::read(input), + }); + } + if let (Some(input), Some(rho)) = + (outer.get::>(), inner.get::()) + { + return Some(Node::Reindex { + input: Self::read(input), + rho, + }); + } + let omega = outer.get::>, Values>()?; + let lifted = inner.get::>>()?; + let Parts::Composition { outer, inner } = lifted.parts()? else { + return None; + }; + let lift = outer.get::, Multisets>>()?; + let psi = inner.get::>()?; + let Parts::Lift(u) = lift.parts()? else { + return None; + }; + Some(Node::Reduce { + omega, + u: Self::read(u.get::>()?), + psi, + }) + } + + /// The expression with `node` at its root, which evaluates as the + /// composition of its parts. As with `compose`, what an index map or index + /// function lands in must lie in the domain of what is read through it. + pub fn new(node: Node) -> Self { + let tensor: TensorMap = match &node { + Node::Tensor(tensor) => Rc::clone(tensor), + Node::Map { f, input } => Rc::new(compose(Rc::clone(f), input.tensor())), + Node::Reindex { input, rho } => Rc::new(compose(input.tensor(), Rc::clone(rho))), + Node::Reduce { omega, u, psi } => Rc::new(compose( + Rc::clone(omega), + compose(multiset_lift(u.tensor()), Rc::clone(psi)), + )), + }; + Self(Rc::new(Inner { node, tensor })) + } +} + +/// The neutral element `e` of a reduction: what it gives for the empty +/// multiset. +pub fn neutral(omega: &ReductionMap) -> A { + omega.apply(&Multiset::default()) +} + +/// An expression evaluates as the tensor it was read from or built as. +impl Function for Expr { + type Domain = HRect; + type Codomain = Values; + + fn apply(&self, index: &[usize]) -> A { + self.0.tensor.apply(index) + } + + fn domain(&self) -> HRect { + self.0.tensor.domain() + } + + fn codomain(&self) -> Values { + Values::new() + } + + fn parts(&self) -> Option { + self.0.tensor.parts() + } +} + +/// Prints the shape of the tree, the kind of each node and what it holds: +/// `Reduce(Map(Tensor))` for `Ξ£ ∘ (f ∘ U)β€Ύ ∘ ψ`. The functions at the nodes are +/// not printed, as nothing tells what they are but their values. +impl fmt::Debug for Expr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.node() { + Node::Tensor(_) => f.write_str("Tensor"), + Node::Map { input, .. } => write!(f, "Map({input:?})"), + Node::Reindex { input, .. } => write!(f, "Reindex({input:?})"), + Node::Reduce { u, .. } => write!(f, "Reduce({u:?})"), + } + } +} diff --git a/src/function.rs b/src/function.rs index baf5cb4..6510693 100644 --- a/src/function.rs +++ b/src/function.rs @@ -2,6 +2,7 @@ //! multisets. Tensors, index maps, index functions and reductions are all //! functions, and every operation on them is built from these. +use std::any::Any; use std::borrow::Borrow; use std::rc::Rc; @@ -20,6 +21,46 @@ pub trait Function { fn domain(&self) -> Self::Domain; fn codomain(&self) -> Self::Codomain; + + /// What this function is composed of, or `None` for one that is not looked + /// into, such as a physical tensor. This is how a rewrite reads the + /// structure of an expression built with the functions of this crate, + /// without that structure being written out a second time. + fn parts(&self) -> Option + where + Self: 'static, + { + None + } +} + +/// A function with its type erased down to its domain and codomain, as held by +/// a composition or a lifted function that is taken apart. +pub struct Part(Box); + +impl Part { + pub fn new(f: Rc) -> Self { + let erased: Rc> = f; + Self(Box::new(erased)) + } + + /// The function, if it goes from `D` to `C`. This is how one tells a function + /// on values from a tensor or an index map: by what it goes between. + pub fn get( + &self, + ) -> Option>> { + self.0 + .downcast_ref::>>() + .cloned() + } +} + +/// The ways a function is built from others. +pub enum Parts { + /// `outer ∘ inner`. + Composition { outer: Part, inner: Part }, + /// `fΜ„`, the extension of `f` to multisets. + Lift(Part), } // A shared function is the same function, so that one can be used in several @@ -39,12 +80,21 @@ impl Function for Rc { fn codomain(&self) -> Self::Codomain { (**self).codomain() } + + fn parts(&self) -> Option + where + Self: 'static, + { + (**self).parts() + } } -/// `f ∘ g`: applies `g`, then `f` to the result. +/// `f ∘ g`: applies `g`, then `f` to the result. Both are shared, so that a +/// composition can be taken apart into its parts, and a rewrite of it can reuse +/// them as they are. pub struct Composition { - f: F, - g: G, + f: Rc, + g: Rc, } /// Composes `f` after `g`. Composing a tensor after an index map re-indexes it, @@ -60,7 +110,10 @@ where codomain.lies_in(&domain), "the inner function lands in {codomain:?}, which does not lie in the domain {domain:?} of the outer one" ); - Composition { f, g } + Composition { + f: Rc::new(f), + g: Rc::new(g), + } } impl Function for Composition @@ -82,6 +135,16 @@ where fn codomain(&self) -> Self::Codomain { self.f.codomain() } + + fn parts(&self) -> Option + where + Self: 'static, + { + Some(Parts::Composition { + outer: Part::new(Rc::clone(&self.f)), + inner: Part::new(Rc::clone(&self.g)), + }) + } } /// A function from multisets to multisets: the extension of `f` to multisets, @@ -89,11 +152,11 @@ where /// of its elements, repeats included, so it goes from the multisets of the /// domain of `f` to those of its codomain. pub struct MultiFunction { - f: F, + f: Rc, } pub fn multiset_lift(f: F) -> MultiFunction { - MultiFunction { f } + MultiFunction { f: Rc::new(f) } } impl Function for MultiFunction { @@ -113,6 +176,13 @@ impl Function for MultiFunction { fn codomain(&self) -> Self::Codomain { Multisets::new(self.f.codomain()) } + + fn parts(&self) -> Option + where + Self: 'static, + { + Some(Parts::Lift(Part::new(Rc::clone(&self.f)))) + } } /// A function on values, given as a closure, from `A` to `B`. Composed after a diff --git a/src/index_functions.rs b/src/index_functions.rs index 273d5ce..37fe0f5 100644 --- a/src/index_functions.rs +++ b/src/index_functions.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::rc::Rc; use crate::function::Function; @@ -338,7 +339,7 @@ pub struct EmptyMapping { impl EmptyMapping { pub fn new(domain: HRect, codomain: HRect) -> Self { Self { - signature: MultiIndexFunctionSignature::new(domain, Multisets::new(codomain)), + signature: MultiIndexFunctionSignature::new(domain, Multisets::at_most(codomain, 0)), } } } @@ -363,8 +364,14 @@ pub struct COO { impl COO { pub fn new(domain: HRect, inverse_coords: Vec>) -> Self { let codomain = HRect::new(vec![inverse_coords.len()]); + // An index is sent to every stored value at its coordinate, so to as + // many as the coordinate repeated most often. + let max_len = most_repeated(&inverse_coords, domain.ndim()); Self { - signature: MultiIndexFunctionSignature::new(domain, Multisets::new(codomain)), + signature: MultiIndexFunctionSignature::new( + domain, + Multisets::at_most(codomain, max_len), + ), inverse_coords, } } @@ -374,6 +381,21 @@ impl COO { } } +/// How many times the coordinate repeated most often appears: at most this many +/// of them match an index. A coordinate with fewer or more coordinates than the +/// domain has dimensions is matched on a part of the index only, so then only +/// the count of all of them is a safe bound. +fn most_repeated(coords: &[Vec], ndim: usize) -> usize { + if coords.iter().any(|coord| coord.len() != ndim) { + return coords.len(); + } + let mut counts: HashMap<&[usize], usize> = HashMap::new(); + for coord in coords { + *counts.entry(coord).or_default() += 1; + } + counts.into_values().max().unwrap_or(0) +} + impl IndexFunction for COO { type Codomain = Multisets; @@ -408,7 +430,7 @@ impl Diagonal { Self { signature: MultiIndexFunctionSignature::new( domain, - Multisets::new(HRect::new(vec![extent])), + Multisets::at_most(HRect::new(vec![extent]), 1), ), } } @@ -487,11 +509,11 @@ impl InvProjection { codomain.ndim() ); let mut shape = codomain.shape().to_vec(); - shape.remove(dim); + let extent = shape.remove(dim); Self { signature: MultiIndexFunctionSignature::new( HRect::new(shape), - Multisets::new(codomain), + Multisets::at_most(codomain, extent), ), dim, } @@ -615,10 +637,19 @@ impl InvAffine { offset, } = affine; let preimage = Preimage::new(&basis, signature.domain().shape()); + // An injective affine map sends at most one index of the box back to + // each one. Otherwise this is not worked out, and the size of the box + // is the bound. + let size: usize = signature.domain().shape().iter().product(); + let max_len = if preimage.is_injective() { + size.min(1) + } else { + size + }; Self { signature: MultiIndexFunctionSignature::new( signature.codomain().clone(), - Multisets::new(signature.domain().clone()), + Multisets::at_most(signature.domain().clone(), max_len), ), offset, preimage, diff --git a/src/lattice.rs b/src/lattice.rs index 1c7d4d3..0efdec8 100644 --- a/src/lattice.rs +++ b/src/lattice.rs @@ -38,6 +38,13 @@ impl Preimage { } } + /// Whether `x ↦ basisΒ·x` sends no two integer points to one, which is when + /// the basis has full column rank. It then sends no two indices of the box + /// to one either, so `solve` finds at most one of them. + pub(crate) fn is_injective(&self) -> bool { + self.h_pivots.len() == self.extents.len() + } + /// Every index `x` of the box with `basisΒ·x = c`. pub(crate) fn solve(&self, c: &[i64]) -> Vec> { let mut z = vec![0; self.h_pivots.len()]; diff --git a/src/lib.rs b/src/lib.rs index 89ab9db..dd7af29 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,18 +2,23 @@ //! compositions or functional transforms. pub mod display; +pub mod expr; pub mod function; pub mod functions; pub mod index_functions; mod lattice; pub mod multiset; pub mod reductions; +pub mod rewrite; pub mod sets; pub mod signature; pub mod tensor; pub use display::format_boxed; -pub use function::{Composition, Function, MultiFunction, ValueFunction, compose, multiset_lift}; +pub use expr::{Expr, IndexMap, MultiIndexMap, Node, ReductionMap, TensorMap, ValueMap, neutral}; +pub use function::{ + Composition, Function, MultiFunction, Part, Parts, ValueFunction, compose, multiset_lift, +}; pub use functions::{ Dims, clamp, concatenate, diagonalize, eye, eye_rect, mm, movedim, negate, ones, permute, prod, scale, sparse_coo_tensor, sparse_latticed_tensor, square, squeeze, stack, sum, transpose, @@ -28,6 +33,10 @@ pub use reductions::{ Inf, InfReduction, Product, ProductReduction, Reduction, ReductionFunction, Sum, SumReduction, Sup, SupReduction, }; +pub use rewrite::{ + ElementWiseIntoSparse, ElementWiseThroughReindex, FuseElementWise, Rule, default_rules, + rewrite, rewrite_with, +}; pub use sets::{HRect, IndexSet, JaggedDomain, Multisets, Set, Values}; pub use signature::{HRectSignature, Signature}; pub use tensor::{JaggedTensor, Physical, ReductionTensor, Tensor}; diff --git a/src/main.rs b/src/main.rs index 1b89d3b..0c7b766 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,9 @@ use std::rc::Rc; use cten::{ - COO, Function, HRect, Physical, Product, Stride, Sum, Sup, compose, diagonalize, eye, movedim, - multiset_lift, negate, ones, square, transpose, zeros, + COO, Function, HRect, Physical, Product, Stride, Sum, Sup, ValueFunction, compose, diagonalize, + eye, format_boxed, movedim, multiset_lift, negate, ones, rewrite, rewrite_with, square, + transpose, zeros, }; fn main() { @@ -77,4 +78,15 @@ fn main() { println!("\nzeroed:\n{zeroed}"); // Transposing an identity built over no data at all gives it back. println!("\ntransposed_identity:\n{transposed_identity}"); + + // Rewriting: by Theorem 1, relu is applied to the 6 stored values of the + // sparse tensor only, and not at its 30 indices. + let relu = ValueFunction::new(|x: f32| x.max(0.0)); + let relu_sparse = Rc::new(compose(relu, transpose(sparse_coo.clone()))); + let rewritten = rewrite(relu_sparse.clone()); + println!( + "\nrelu of transposed sparse_coo: {:?}", + rewrite_with(relu_sparse, &[]) + ); + println!("rewritten: {rewritten:?}\n{}", format_boxed(&rewritten)); } diff --git a/src/rewrite.rs b/src/rewrite.rs new file mode 100644 index 0000000..5239043 --- /dev/null +++ b/src/rewrite.rs @@ -0,0 +1,204 @@ +//! Rewriting a tensor into an equal one before evaluating it, using the +//! identities between compositions of the paper. The tensor is read as an +//! expression, each identity is a `Rule`, which rewrites the root of an +//! expression when it applies, and `rewrite_with` applies rules all over it +//! until none applies any more. +//! +//! The rules here push a function on values `f` down an expression, towards the +//! values it is stored as: through index maps, and into a sparse tensor by +//! Theorem 1, after which `f` is applied to the stored values only. Further +//! identities, such as Theorems 2 and 3 on products of sparse tensors, would be +//! further rules, along with the nodes they rewrite. + +use std::rc::Rc; + +use crate::expr::{Expr, Node, ValueMap, neutral}; +use crate::function::compose; +use crate::tensor::Tensor; + +/// An identity `lhs = rhs` between expressions, used left to right. +pub trait Rule { + fn name(&self) -> &'static str; + + /// The expression `expr` is equal to by this identity, or `None` when the + /// root of `expr` is not of the form it rewrites. Only the root is looked + /// at: `rewrite_with` takes care of the rest of the tree. + fn apply(&self, expr: &Expr) -> Option>; +} + +/// Theorem 1: `f ∘ Ξ£ ∘ Εͺ ∘ ψ = Ξ£ ∘ (f ∘ U)β€Ύ ∘ ψ` when `ψ` maps every index to a +/// multiset of at most one element and `f(0) = 0`. The two sides agree on the +/// empty multiset as `f(0) = 0`, and on a multiset `{{x}}` as both give `f(x)`. +/// The same holds for any reduction `Ξ©` and its neutral element `e`, as Lemma 6 +/// shows, once `f(e) = e`: this rule applies to all of them. +/// +/// Whether `f(e) = e` is found by evaluating `f` at `e`, once per rewrite, and +/// whether `ψ` maps to at most one element by the bound its codomain gives on +/// the size of its multisets, which is never too low. +/// `ψ` is left as it is, so `f` is then applied only where `U` is read: at the +/// stored values, and not at every index of the tensor. +pub struct ElementWiseIntoSparse; + +impl Rule for ElementWiseIntoSparse { + fn name(&self) -> &'static str { + "element-wise into sparse (Theorem 1)" + } + + fn apply(&self, expr: &Expr) -> Option> { + let Node::Map { f, input } = expr.node() else { + return None; + }; + let Node::Reduce { omega, u, psi } = input.node() else { + return None; + }; + // Checked first, so that `f` is not evaluated in vain. + if psi.codomain().max_len().is_none_or(|len| len > 1) { + return None; + } + let e = neutral(omega); + if f.apply(&e) != e { + return None; + } + let u = Expr::new(Node::Map { + f: Rc::clone(f), + input: u.clone(), + }); + Some(Expr::new(Node::Reduce { + omega: Rc::clone(omega), + u, + psi: Rc::clone(psi), + })) + } +} + +/// `f ∘ (T ∘ ρ) = (f ∘ T) ∘ ρ`, which is associativity of composition: applying +/// `f` after reading `T` through `ρ` is reading `f ∘ T` through `ρ`. It costs the +/// same, but brings `f` next to `T`, where other rules may apply, as Theorem 1 +/// does to a sparse tensor that is transposed or otherwise re-indexed. +pub struct ElementWiseThroughReindex; + +impl Rule for ElementWiseThroughReindex { + fn name(&self) -> &'static str { + "element-wise through re-indexing" + } + + fn apply(&self, expr: &Expr) -> Option> { + let Node::Map { f, input } = expr.node() else { + return None; + }; + let Node::Reindex { input, rho } = input.node() else { + return None; + }; + let input = Expr::new(Node::Map { + f: Rc::clone(f), + input: input.clone(), + }); + Some(Expr::new(Node::Reindex { + input, + rho: Rc::clone(rho), + })) + } +} + +/// `g ∘ (f ∘ T) = (g ∘ f) ∘ T`, associativity again. Theorem 1 may apply to +/// `g ∘ f` when it does not to `f` alone: with `f(x) = x + 1` and +/// `g(x) = x - 1`, neither keeps 0 but their composition does. +pub struct FuseElementWise; + +impl Rule for FuseElementWise { + fn name(&self) -> &'static str { + "fuse element-wise functions" + } + + fn apply(&self, expr: &Expr) -> Option> { + let Node::Map { f: g, input } = expr.node() else { + return None; + }; + let Node::Map { f, input } = input.node() else { + return None; + }; + let fused: ValueMap = Rc::new(compose(Rc::clone(g), Rc::clone(f))); + Some(Expr::new(Node::Map { + f: fused, + input: input.clone(), + })) + } +} + +/// The rules `rewrite` applies, in the order it tries them at each node. +pub fn default_rules() -> Vec>> { + vec![ + Box::new(ElementWiseIntoSparse), + Box::new(ElementWiseThroughReindex), + Box::new(FuseElementWise), + ] +} + +/// `tensor` rewritten by the default rules into a tensor equal to it at every +/// index, and cheaper or as cheap to evaluate. It may be any tensor built with +/// the functions of this crate. +pub fn rewrite(tensor: impl Tensor + 'static) -> Expr { + rewrite_with(tensor, &default_rules()) +} + +/// `tensor` read as an expression and rewritten by `rules` until none applies +/// anywhere in it. With no rules, this is the expression as read. +pub fn rewrite_with( + tensor: impl Tensor + 'static, + rules: &[Box>], +) -> Expr { + rewrite_expr(&Expr::of(tensor), rules) +} + +/// The children of a node are rewritten first, then the first rule that +/// applies to the node rewrites it, and what it gives is rewritten in turn, +/// since it may let rules apply further down. The rules must not undo one +/// another: the ones here each move a function on values further down the tree +/// or merge two of them, so a rewrite ends. A node none of whose children +/// changed is kept as it is, so that it still evaluates as the tensor it was +/// read from. +fn rewrite_expr(expr: &Expr, rules: &[Box>]) -> Expr { + let rebuilt = match expr.node() { + Node::Tensor(_) => expr.clone(), + Node::Map { f, input } => { + let rewritten = rewrite_expr(input, rules); + if rewritten.ptr_eq(input) { + expr.clone() + } else { + Expr::new(Node::Map { + f: Rc::clone(f), + input: rewritten, + }) + } + } + Node::Reindex { input, rho } => { + let rewritten = rewrite_expr(input, rules); + if rewritten.ptr_eq(input) { + expr.clone() + } else { + Expr::new(Node::Reindex { + input: rewritten, + rho: Rc::clone(rho), + }) + } + } + Node::Reduce { omega, u, psi } => { + let rewritten = rewrite_expr(u, rules); + if rewritten.ptr_eq(u) { + expr.clone() + } else { + Expr::new(Node::Reduce { + omega: Rc::clone(omega), + u: rewritten, + psi: Rc::clone(psi), + }) + } + } + }; + for rule in rules { + if let Some(rewritten) = rule.apply(&rebuilt) { + return rewrite_expr(&rewritten, rules); + } + } + rebuilt +} diff --git a/src/sets.rs b/src/sets.rs index c0c800c..38d1b9c 100644 --- a/src/sets.rs +++ b/src/sets.rs @@ -161,21 +161,41 @@ impl Set for Values { } } -/// The multisets of elements of `S`, written `M(S)` in the paper. +/// The multisets of elements of `S`, written `M(S)` in the paper, or only those +/// of at most a given number of elements. That bound is what makes an index +/// function `ψ: 𝒱 β†’ β„³(𝒰)` that of a sparse tensor (Definition 4): with a +/// bound of one, every index is sent to at most one stored value. It is part of +/// the codomain, so that a rewrite can ask any `ψ` for it, whatever its type. #[derive(Clone, Debug)] pub struct Multisets { set: S, + max_len: Option, } impl Multisets { + /// All the multisets of elements of `set`, of any size. pub fn new(set: S) -> Self { - Self { set } + Self { set, max_len: None } + } + + /// The multisets of elements of `set` holding at most `max_len` of them. + pub fn at_most(set: S, max_len: usize) -> Self { + Self { + set, + max_len: Some(max_len), + } } /// The set the elements of the multisets are drawn from. pub fn set(&self) -> &S { &self.set } + + /// The most elements a multiset of this set holds, or `None` for no bound. + /// A bound may be loose, but is never too low. + pub fn max_len(&self) -> Option { + self.max_len + } } impl Set for Multisets { @@ -183,6 +203,11 @@ impl Set for Multisets { type Owned = Multiset; fn lies_in(&self, other: &Self) -> bool { - self.set.lies_in(&other.set) + let within = match (self.max_len, other.max_len) { + (_, None) => true, + (Some(len), Some(other)) => len <= other, + (None, Some(_)) => false, + }; + within && self.set.lies_in(&other.set) } } diff --git a/tests/index_functions.rs b/tests/index_functions.rs index fa746a4..07a83cf 100644 --- a/tests/index_functions.rs +++ b/tests/index_functions.rs @@ -208,8 +208,19 @@ fn assert_inv_affine_matches_a_scan( offset, HRect::new(shape.clone()), )); + // The bound on the size of the multisets is never too low. + let bound = inv_affine + .signature() + .codomain() + .max_len() + .expect("an inv affine always bounds its multisets"); for y in indices(&shape) { let lands = expected.remove(&y).unwrap_or_default(); + assert!( + lands.len() <= bound, + "{} indices land on {y:?}", + lands.len() + ); assert_eq!(sorted(inv_affine.map(&y)), lands, "at {y:?}"); } } @@ -407,3 +418,67 @@ fn a_where_sends_each_index_to_the_part_its_condition_picks() { assert_eq!(picks.map(&[1]), vec![1, 1]); assert_eq!(picks.map(&[2]), vec![0, 2]); } + +/// The bound the codomain of `psi` gives on the size of its multisets. +fn max_len(psi: &impl IndexFunction>) -> Option { + psi.signature().codomain().max_len() +} + +/// Whether `psi` is known to send every index to at most one index. +fn at_most_one(psi: &impl IndexFunction>) -> bool { + max_len(psi).is_some_and(|len| len <= 1) +} + +#[test] +fn multi_index_functions_bound_the_size_of_their_multisets() { + let shape = HRect::new(vec![6, 5]); + let unique = COO::new(shape.clone(), vec![vec![0, 0], vec![4, 2], vec![5, 4]]); + let repeated = COO::new(shape.clone(), vec![vec![0, 0], vec![4, 2], vec![0, 0]]); + let rows = InvProjection::new(shape.clone(), 1); + let empty = EmptyMapping::new(shape.clone(), HRect::new(vec![0])); + let diagonal = Diagonal::new(HRect::new(vec![4, 4, 4])); + + assert_eq!(max_len(&empty), Some(0)); + assert_eq!(max_len(&diagonal), Some(1)); + assert_eq!(max_len(&unique), Some(1)); + assert_eq!(max_len(&repeated), Some(2)); + assert_eq!(repeated.map(&[0, 0]).len(), 2); + assert_eq!(max_len(&rows), Some(5)); + assert!(at_most_one(&empty) && at_most_one(&diagonal) && at_most_one(&unique)); + assert!(!at_most_one(&repeated) && !at_most_one(&rows)); +} + +// A basis of full column rank sends no two indices to one; otherwise only the +// size of the box is claimed, even where, as on a box of one index along the +// kernel, no two indices actually land on one. +#[test] +fn an_inv_affine_is_at_most_one_when_its_basis_is_injective() { + let inv_affine = |basis: Vec>, physical: Vec, shape: Vec| { + let offset = vec![0; shape.len()]; + InvAffine::new(Affine::new( + HRect::new(physical), + basis, + offset, + HRect::new(shape), + )) + }; + + assert!(at_most_one(&inv_affine( + vec![vec![2], vec![3]], + vec![3], + vec![5, 7] + ))); + assert!(at_most_one(&inv_affine( + vec![vec![1, 0], vec![1, 1]], + vec![4, 3], + vec![4, 6] + ))); + let summed = inv_affine(vec![vec![1, 1]], vec![3, 3], vec![5]); + assert_eq!(max_len(&summed), Some(9)); + assert!(!at_most_one(&summed)); + assert!(!at_most_one(&inv_affine( + vec![vec![1, 1]], + vec![3, 1], + vec![3] + ))); +} diff --git a/tests/rewriting.rs b/tests/rewriting.rs new file mode 100644 index 0000000..22dcb58 --- /dev/null +++ b/tests/rewriting.rs @@ -0,0 +1,461 @@ +use std::cell::Cell; +use std::rc::Rc; + +use cten::{ + COO, ElementWiseIntoSparse, Expr, Function, HRect, Node, Physical, Rule, Stride, Sup, Tensor, + ValueFunction, Values, compose, diagonalize, eye, multiset_lift, negate, rewrite, rewrite_with, + sparse_coo_tensor, sparse_latticed_tensor, square, stack, sum, transpose, +}; + +/// Every index of a hrect of the given shape. +fn indices(shape: &[usize]) -> Vec> { + shape.iter().fold(vec![vec![]], |prefixes, &extent| { + prefixes + .iter() + .flat_map(|prefix| { + (0..extent).map(move |coord| { + let mut index = prefix.clone(); + index.push(coord); + index + }) + }) + .collect() + }) +} + +/// `tensor` read as an expression, with no rule applied. +fn read(tensor: impl Tensor + 'static) -> Expr { + rewrite_with(tensor, &[]) +} + +/// The shape of the tree of an expression, such as `Reduce(Map(Tensor))`. +trait Shape { + fn shape(&self) -> String; +} + +impl Shape for Expr { + fn shape(&self) -> String { + format!("{self:?}") + } +} + +/// Checks that two tensors have one domain and agree at each of its indices. +fn assert_same(actual: &dyn Tensor, expected: &dyn Tensor) { + let domain = expected.domain(); + assert_eq!(actual.domain(), domain); + for index in indices(domain.shape()) { + assert_eq!(actual.apply(&index), expected.apply(&index), "at {index:?}"); + } +} + +/// Whether two tensors of one domain differ at some index. +fn differ(a: &dyn Tensor, b: &dyn Tensor) -> bool { + indices(a.domain().shape()) + .iter() + .any(|index| a.apply(index) != b.apply(index)) +} + +/// Stored values, with negative ones so that `relu` and `square` change them. +fn stored() -> Vec { + vec![1.5, -2.0, 3.0, -0.5, 5.0, -6.0] +} + +fn values() -> Physical { + Physical::new(stored()) +} + +/// A row-major 2 Γ— 3 matrix over the stored values. +fn matrix() -> impl Tensor + 'static { + compose(values(), Stride::new(HRect::new(vec![2, 3]), vec![3, 1])) +} + +/// The coordinates of the sparse examples, one row per dimension, all distinct. +fn coordinates() -> Vec> { + vec![vec![0, 0, 4, 5, 1, 2], vec![0, 3, 2, 4, 3, 0]] +} + +fn sparse() -> impl Tensor + 'static { + sparse_coo_tensor(coordinates(), values(), vec![6, 5]) +} + +fn latticed() -> impl Tensor + 'static { + sparse_latticed_tensor( + matrix(), + vec![vec![1, 0], vec![0, 2], vec![1, 1]], + vec![0, 0, 0], + vec![2, 5, 4], + ) +} + +fn relu() -> ValueFunction { + ValueFunction::new(|x: f32| x.max(0.0)) +} + +/// Functions on values with `f(0) = 0`, for Theorem 1 to apply to. +fn zero_preserving() -> Vec> { + vec![ + ValueFunction::new(|x: f32| -x), + ValueFunction::new(|x: f32| x * x), + relu(), + ValueFunction::new(f32::tanh), + ] +} + +/// Checks, for each zero-preserving `f`, that `f ∘ tensor` rewrites to an +/// expression of shape `expected`, and that the rewrite changes no value. +fn assert_pushed_in(tensor: impl Fn() -> T, expected: &str) { + for f in zero_preserving() { + let original = Rc::new(compose(f, tensor())); + let rewritten = rewrite(Rc::clone(&original)); + assert_eq!(rewritten.shape(), expected); + assert_same(&rewritten, &*original); + } +} + +// Tensors built with the functions of the crate are read back as the +// compositions they are, and evaluate as they did. +#[test] +fn a_tensor_is_read_as_the_composition_it_was_built_as() { + assert_eq!(read(values()).shape(), "Tensor"); + assert_eq!(read(matrix()).shape(), "Reindex(Tensor)"); + assert_eq!(read(sparse()).shape(), "Reduce(Tensor)"); + assert_eq!( + read(compose(relu(), transpose(sparse()))).shape(), + "Map(Reindex(Reduce(Tensor)))" + ); + assert_eq!(read(eye(3)).shape(), "Reduce(Reduce(Tensor))"); + assert_same(&read(latticed()), &latticed()); +} + +// A tensor read but not rewritten evaluates as itself, not as a copy of it. +#[test] +fn an_expression_evaluates_as_the_tensor_it_was_read_from() { + let sparse: Rc = Rc::new(sparse()); + let expr = read(Rc::clone(&sparse)); + let Node::Reduce { u, .. } = expr.node() else { + panic!("a sparse tensor is read as a reduction"); + }; + + assert_eq!(expr.parts().is_some(), sparse.parts().is_some()); + assert_eq!(u.domain(), HRect::new(vec![6])); + assert_same(&expr, &*sparse); +} + +// Parts shared through an `Rc`, as `main.rs` shares a lifted tensor between +// several, or erased as `Rc`, are looked into all the same. +#[test] +fn shared_and_erased_parts_are_looked_into() { + let lifted = Rc::new(multiset_lift(Rc::new(values()))); + let coo = Rc::new(COO::new( + HRect::new(vec![13]), + vec![vec![0], vec![4], vec![5], vec![1], vec![10], vec![12]], + )); + let sparse: Rc = Rc::new(compose(cten::Sum::new(), compose(lifted, coo))); + let rewritten = rewrite(compose(relu(), Rc::clone(&sparse))); + + assert_eq!(rewritten.shape(), "Reduce(Map(Tensor))"); + assert_same(&rewritten, &compose(relu(), sparse)); +} + +/// A tensor of this test's own, which says nothing of its parts. +struct Ramp; + +impl Function for Ramp { + type Domain = HRect; + type Codomain = Values; + + fn apply(&self, index: &[usize]) -> f32 { + index[0] as f32 - 2.0 + } + + fn domain(&self) -> HRect { + HRect::new(vec![4]) + } + + fn codomain(&self) -> Values { + Values::new() + } +} + +// What is not known to be a composition is a leaf, which the rules do not look +// into: a tensor of another crate, a jagged tensor, or a function on values +// from another type of values. +#[test] +fn what_is_not_known_to_be_a_composition_is_a_leaf() { + let parts: Vec> = vec![Rc::new(values()), Rc::new(values())]; + let from_ints = compose( + ValueFunction::new(|x: i64| x as f32), + Physical::new(vec![1_i64, 2, 3]), + ); + + assert_eq!(read(Ramp).shape(), "Tensor"); + assert_eq!( + rewrite(compose(relu(), diagonalize(Ramp, 2))).shape(), + "Reduce(Map(Tensor))" + ); + assert_eq!(read(stack(parts, 0)).shape(), "Tensor"); + assert_eq!(read(from_ints).shape(), "Tensor"); + assert!(matches!( + read(compose( + ValueFunction::new(|x: i64| x as f32), + Physical::new(vec![1_i64]) + )) + .node(), + Node::Tensor(_) + )); +} + +#[test] +fn a_zero_preserving_function_moves_into_a_diagonal_tensor() { + assert_pushed_in(|| diagonalize(values(), 2), "Reduce(Map(Tensor))"); + assert_pushed_in(|| diagonalize(values(), 3), "Reduce(Map(Tensor))"); +} + +#[test] +fn a_zero_preserving_function_moves_into_a_sparse_coo_tensor() { + assert_pushed_in(sparse, "Reduce(Map(Tensor))"); +} + +#[test] +fn a_zero_preserving_function_moves_into_a_sparse_latticed_tensor() { + assert_pushed_in(latticed, "Reduce(Reindex(Map(Tensor)))"); +} + +// The helpers of `functions` are read like any composition. +#[test] +fn the_helpers_of_the_crate_are_rewritten_too() { + let negated = rewrite(negate(sparse())); + let squared = rewrite(square(transpose(diagonalize(values(), 2)))); + + assert_eq!(negated.shape(), "Reduce(Map(Tensor))"); + assert_eq!(squared.shape(), "Reindex(Reduce(Map(Tensor)))"); + assert_same(&negated, &negate(sparse())); + assert_same(&squared, &square(transpose(diagonalize(values(), 2)))); +} + +// The diagonal of `eye` is a product over the empty multiset, so `f` moves in +// once more when `f(1) = 1`, by the same rule with the neutral element of a +// product: `relu` is then never evaluated, and `negate` only on the diagonal. +#[test] +fn a_function_moves_into_eye_as_far_as_it_keeps_neutral_elements() { + let relu_rewritten = rewrite(compose(relu(), eye(4))); + let negated_rewritten = rewrite(negate(eye(4))); + + assert_eq!(relu_rewritten.shape(), "Reduce(Reduce(Map(Tensor)))"); + assert_eq!(negated_rewritten.shape(), "Reduce(Map(Reduce(Tensor)))"); + assert_same(&relu_rewritten, &compose(relu(), eye(4))); + assert_same(&negated_rewritten, &negate(eye(4))); +} + +// `f ∘ (A ∘ ρ) = (f ∘ A) ∘ ρ` brings `f` next to the sparse tensor first. +#[test] +fn a_zero_preserving_function_moves_through_a_transpose_into_a_sparse_tensor() { + assert_pushed_in(|| transpose(sparse()), "Reindex(Reduce(Map(Tensor)))"); +} + +#[test] +fn nested_zero_preserving_functions_both_move_in() { + let nested = || compose(ValueFunction::new(f32::tanh), square(sparse())); + let rewritten = rewrite(nested()); + + assert_eq!(rewritten.shape(), "Reduce(Map(Tensor))"); + assert_same(&rewritten, &nested()); +} + +// Neither `x + 1` nor `x - 1` keeps 0, but their composition does: fusing them +// lets Theorem 1 apply to it. +#[test] +fn functions_that_only_keep_zero_together_move_in_together() { + let nested = || { + compose( + ValueFunction::new(|x: f32| x - 1.0), + compose(ValueFunction::new(|x: f32| x + 1.0), sparse()), + ) + }; + let rewritten = rewrite(nested()); + + assert_eq!(rewritten.shape(), "Reduce(Map(Tensor))"); + assert_same(&rewritten, &nested()); +} + +// The rule asks `f(e) = e` of the neutral element `e` of the reduction: -∞ for +// a sup, which doubling keeps and `relu` does not. +#[test] +fn a_function_moves_into_a_sup_tensor_when_it_keeps_its_neutral_element() { + let sup = || { + let coo = COO::new(HRect::new(vec![6]), vec![vec![0], vec![4], vec![5]]); + compose(Sup::new(), compose(multiset_lift(values()), coo)) + }; + let doubled = || compose(ValueFunction::new(|x: f32| 2.0 * x), sup()); + + assert_eq!(rewrite(doubled()).shape(), "Reduce(Map(Tensor))"); + assert_eq!( + rewrite(compose(relu(), sup())).shape(), + "Map(Reduce(Tensor))" + ); + assert_same(&rewrite(doubled()), &doubled()); + assert_same(&rewrite(compose(relu(), sup())), &compose(relu(), sup())); +} + +/// `Ξ£ ∘ (f ∘ U)β€Ύ ∘ ψ` built by hand from `Ξ£ ∘ Εͺ ∘ ψ`: what Theorem 1 would +/// rewrite `f ∘ Ξ£ ∘ Εͺ ∘ ψ` to, whether or not it applies. +fn naive(tensor: impl Tensor + 'static, f: ValueFunction) -> Expr { + let expr = read(tensor); + let Node::Reduce { omega, u, psi } = expr.node() else { + panic!("{expr:?} is not a reduction tensor"); + }; + let u = Expr::new(Node::Map { + f: Rc::new(f), + input: u.clone(), + }); + Expr::new(Node::Reduce { + omega: Rc::clone(omega), + u, + psi: Rc::clone(psi), + }) +} + +// Off the stored values, `f ∘ Ξ£` gives `f(0)` and `Ξ£ ∘ fΜ„` gives 0. +#[test] +fn a_function_that_does_not_keep_zero_stays_outside() { + let functions = || { + [ + ValueFunction::new(|x: f32| x + 1.0), + ValueFunction::new(f32::cos), + ] + }; + for (f, same) in functions().into_iter().zip(functions()) { + let original = Rc::new(compose(f, sparse())); + let rewritten = rewrite(Rc::clone(&original)); + + assert_eq!(rewritten.shape(), "Map(Reduce(Tensor))"); + assert_same(&rewritten, &*original); + assert!(differ(&naive(sparse(), same), &*original)); + } +} + +// With two values at `[0, 0]`, `f ∘ Ξ£` squares their sum and `Ξ£ ∘ fΜ„` sums +// their squares. +#[test] +fn a_function_stays_outside_a_coo_with_a_repeated_coordinate() { + let repeated = || { + sparse_coo_tensor( + vec![vec![0, 0, 4, 5, 1, 0], vec![0, 3, 2, 4, 3, 0]], + values(), + vec![6, 5], + ) + }; + let rewritten = rewrite(square(repeated())); + let naive = naive(repeated(), ValueFunction::new(|x: f32| x * x)); + + assert_eq!(rewritten.shape(), "Map(Reduce(Tensor))"); + assert_same(&rewritten, &square(repeated())); + assert_eq!(rewritten.apply(&[0, 0]), (1.5f32 - 6.0).powi(2)); + assert_eq!(naive.apply(&[0, 0]), 1.5f32.powi(2) + 36.0); +} + +#[test] +fn a_function_stays_outside_a_sum_over_a_dimension() { + let rewritten = rewrite(square(sum(matrix(), 1))); + let naive = naive(sum(matrix(), 1), ValueFunction::new(|x: f32| x * x)); + + assert_eq!(rewritten.shape(), "Map(Reduce(Reindex(Tensor)))"); + assert_same(&rewritten, &square(sum(matrix(), 1))); + assert!(differ(&naive, &square(sum(matrix(), 1)))); +} + +// Two indices of the physical tensor land on each but the first and last ones. +#[test] +fn a_function_stays_outside_a_sparse_latticed_tensor_of_a_non_injective_basis() { + let summed = || sparse_latticed_tensor(matrix(), vec![vec![1, 1]], vec![0], vec![4]); + let rewritten = rewrite(square(summed())); + let naive = naive(summed(), ValueFunction::new(|x: f32| x * x)); + + assert_eq!(rewritten.shape(), "Map(Reduce(Reindex(Tensor)))"); + assert_same(&rewritten, &square(summed())); + assert!(differ(&naive, &square(summed()))); +} + +// Under a rule set without pushing through index maps, a re-indexed sparse +// tensor is out of reach of Theorem 1. +#[test] +fn only_the_given_rules_apply() { + let rules: Vec>> = vec![Box::new(ElementWiseIntoSparse)]; + let transposed = || compose(relu(), transpose(sparse())); + + assert_eq!( + rewrite_with(transposed(), &rules).shape(), + "Map(Reindex(Reduce(Tensor)))" + ); + assert_eq!( + rewrite(transposed()).shape(), + "Reindex(Reduce(Map(Tensor)))" + ); +} + +// What no rule changes is kept as it was read, and evaluates as the tensor it +// was read from. +#[test] +fn a_rewrite_that_changes_nothing_keeps_the_expression() { + let rewritten = rewrite(square(sum(matrix(), 1))); + + assert_eq!(rewritten.shape(), read(square(sum(matrix(), 1))).shape()); + assert_same(&rewritten, &square(sum(matrix(), 1))); +} + +/// `relu`, counting its calls in `calls`. +fn counted_relu(calls: &Rc>) -> ValueFunction { + let calls = Rc::clone(calls); + ValueFunction::new(move |x: f32| { + calls.set(calls.get() + 1); + x.max(0.0) + }) +} + +/// The calls `tensor` makes to the function counted in `calls`, when read at +/// every index of its domain. +fn calls_to_read(tensor: &dyn Tensor, calls: &Rc>) -> usize { + calls.set(0); + for index in indices(tensor.domain().shape()) { + tensor.apply(&index); + } + calls.get() +} + +// The original applies `relu` at each of the 30 indices, the rewritten one at +// the 6 stored values only, also through a transpose. +#[test] +fn a_rewritten_sparse_tensor_applies_the_function_at_its_stored_values_only() { + let calls = Rc::new(Cell::new(0)); + let original = Rc::new(compose(counted_relu(&calls), sparse())); + let rewritten = rewrite(Rc::clone(&original)); + + assert_eq!(calls_to_read(&*original, &calls), 30); + assert_eq!(calls_to_read(&rewritten, &calls), 6); + + let transposed = Rc::new(compose(counted_relu(&calls), transpose(sparse()))); + let rewritten = rewrite(Rc::clone(&transposed)); + assert_eq!(calls_to_read(&*transposed, &calls), 30); + assert_eq!(calls_to_read(&rewritten, &calls), 6); +} + +// On `eye(n)`, `relu` moves past the product over no values and is never +// applied, where the original applies it nΒ² times. +#[test] +fn a_rewritten_eye_never_applies_relu() { + let calls = Rc::new(Cell::new(0)); + let original = Rc::new(compose(counted_relu(&calls), eye(5))); + let rewritten = rewrite(Rc::clone(&original)); + + assert_eq!(calls_to_read(&*original, &calls), 25); + assert_eq!(calls_to_read(&rewritten, &calls), 0); +} + +// Theorem 1 asks once whether `f(0) = 0`, by evaluating `f` at 0. +#[test] +fn rewriting_evaluates_the_function_once_at_the_neutral_element() { + let calls = Rc::new(Cell::new(0)); + rewrite(compose(counted_relu(&calls), sparse())); + + assert_eq!(calls.get(), 1); +} diff --git a/tests/sets.rs b/tests/sets.rs index b2fd0c0..5513f18 100644 --- a/tests/sets.rs +++ b/tests/sets.rs @@ -1,4 +1,4 @@ -use cten::{HRect, IndexSet, JaggedDomain}; +use cten::{HRect, IndexSet, JaggedDomain, Multisets, Set}; #[test] fn a_hrect_holds_exactly_the_indices_within_its_shape() { @@ -58,3 +58,19 @@ fn a_jagged_domain_needs_parts_of_one_rank() { fn a_jagged_domain_needs_a_part() { JaggedDomain::new(vec![]); } + +// The multisets of at most k elements lie in those of at most more, and in +// those of any size, but not the other way round. +#[test] +fn multisets_of_bounded_size_lie_in_those_of_a_larger_bound() { + let hrect = || HRect::new(vec![4]); + let any = Multisets::new(hrect()); + let one = Multisets::at_most(hrect(), 1); + let two = Multisets::at_most(hrect(), 2); + + assert_eq!(any.max_len(), None); + assert_eq!(one.max_len(), Some(1)); + assert!(one.lies_in(&two) && one.lies_in(&any) && two.lies_in(&any)); + assert!(!two.lies_in(&one) && !any.lies_in(&two)); + assert!(!Multisets::at_most(HRect::new(vec![5]), 1).lies_in(&any)); +}