From da16bcb406abb6c5ce7de134875ab8d4f861f768 Mon Sep 17 00:00:00 2001 From: Johnnie Gray Date: Fri, 27 Sep 2024 11:34:17 -0700 Subject: [PATCH] add minimize="max" optimal option and docstrings --- README.md | 33 ++++---- cotengrust.pyi | 32 ++++---- src/lib.rs | 213 ++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 246 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 42f7b15..21b39e1 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,8 @@ def optimize_optimal( (also known as contraction cost) - "size": minimize with respect to maximum intermediate size only (also known as contraction width) + - 'max': minimize the single most expensive contraction, i.e. the + asymptotic (in index size) scaling of the contraction - 'write' : minimize the sum of all tensor sizes, i.e. memory written - 'combo' or 'combo={factor}` : minimize the sum of FLOPS + factor * WRITE, with a default factor of 64. @@ -117,11 +119,11 @@ def optimize_optimal( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input @@ -177,11 +179,11 @@ def optimize_greedy( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input @@ -226,7 +228,6 @@ def optimize_simplify( path : list[list[int]] The contraction path, given as a sequence of pairs of node indices. It may also have single term contractions. - """ ... @@ -275,11 +276,11 @@ def optimize_random_greedy_track_flops( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input diff --git a/cotengrust.pyi b/cotengrust.pyi index df96584..aa7b206 100644 --- a/cotengrust.pyi +++ b/cotengrust.pyi @@ -51,11 +51,11 @@ def optimize_greedy( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input @@ -102,6 +102,8 @@ def optimize_optimal( (also known as contraction cost) - "size": minimize with respect to maximum intermediate size only (also known as contraction width) + - 'max': minimize the single most expensive contraction, i.e. the + asymptotic (in index size) scaling of the contraction - 'write' : minimize the sum of all tensor sizes, i.e. memory written - 'combo' or 'combo={factor}` : minimize the sum of FLOPS + factor * WRITE, with a default factor of 64. @@ -123,11 +125,11 @@ def optimize_optimal( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input @@ -192,11 +194,11 @@ def optimize_random_greedy_track_flops( simplify : bool, optional Whether to perform simplifications before optimizing. These are: - - ignore any indices that appear in all terms - - combine any repeated indices within a single term - - reduce any non-output indices that only appear on a single term - - combine any scalar terms - - combine any tensors with matching indices (hadamard products) + - ignore any indices that appear in all terms + - combine any repeated indices within a single term + - reduce any non-output indices that only appear on a single term + - combine any scalar terms + - combine any tensors with matching indices (hadamard products) Such simpifications may be required in the general case for the proper functioning of the core optimization, but may be skipped if the input diff --git a/src/lib.rs b/src/lib.rs index 78251b0..fdaf686 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -571,6 +571,31 @@ fn compute_con_cost_flops( (new_legs, new_score) } +fn compute_con_cost_max( + temp_legs: Legs, + appearances: &Vec, + sizes: &Vec, + iscore: Score, + jscore: Score, + _factor: Score, +) -> (Legs, Score) { + // remove indices that have reached final appearance + // and compute cost and size of local contraction + let mut new_legs: Legs = Legs::with_capacity(temp_legs.len()); + let mut cost: Score = 0.0; + for (ix, ix_count) in temp_legs.into_iter() { + // all involved indices contribute to the cost + let d = sizes[ix as usize]; + cost += d; + if ix_count != appearances[ix as usize] { + // not last appearance -> kept index contributes to new size + new_legs.push((ix, ix_count)); + } + } + let new_score = iscore.max(jscore).max(cost); + (new_legs, new_score) +} + fn compute_con_cost_size( temp_legs: Legs, appearances: &Vec, @@ -703,12 +728,13 @@ impl ContractionProcessor { } let compute_cost = match minimize_type { "flops" => compute_con_cost_flops, + "max" => compute_con_cost_max, "size" => compute_con_cost_size, "write" => compute_con_cost_write, "combo" => compute_con_cost_combo, "limit" => compute_con_cost_limit, _ => panic!( - "minimize must be one of 'flops', 'size', 'write', 'combo', or 'limit', got {}", + "minimize must be one of 'flops', 'max', 'size', 'write', 'combo', or 'limit', got {}", minimize ), }; @@ -904,6 +930,27 @@ fn find_subgraphs( #[pyfunction] #[pyo3(signature = (inputs, output, size_dict, use_ssa=None))] +/// Find the (partial) contracton path for simplifiactions only. +/// +/// Parameters +/// ---------- +/// inputs : Sequence[Sequence[str]] +/// The indices of each input tensor. +/// output : Sequence[str] +/// The indices of the output tensor. +/// size_dict : dict[str, int] +/// A dictionary mapping indices to their dimension. +/// use_ssa : bool, optional +/// Whether to return the contraction path in 'single static assignment' +/// (SSA) format (i.e. as if each intermediate is appended to the list of +/// inputs, without removals). This can be quicker and easier to work with +/// than the 'linear recycled' format that `numpy` and `opt_einsum` use. +/// +/// Returns +/// ------- +/// path : list[list[int]] +/// The contraction path, given as a sequence of pairs of node indices. It +/// may also have single term contractions. fn optimize_simplify( inputs: Vec>, output: Vec, @@ -922,6 +969,53 @@ fn optimize_simplify( #[pyfunction] #[pyo3(signature = (inputs, output, size_dict, costmod=None, temperature=None, seed=None, simplify=None, use_ssa=None))] +/// Find a contraction path using a (randomizable) greedy algorithm. +/// +/// Parameters +/// ---------- +/// inputs : Sequence[Sequence[str]] +/// The indices of each input tensor. +/// output : Sequence[str] +/// The indices of the output tensor. +/// size_dict : dict[str, int] +/// A dictionary mapping indices to their dimension. +/// costmod : float, optional +/// When assessing local greedy scores how much to weight the size of the +/// tensors removed compared to the size of the tensor added:: +/// +/// score = size_ab / costmod - (size_a + size_b) * costmod +/// +/// This can be a useful hyper-parameter to tune. +/// temperature : float, optional +/// When asessing local greedy scores, how much to randomly perturb the +/// score. This is implemented as:: +/// +/// score -> sign(score) * log(|score|) - temperature * gumbel() +/// +/// which implements boltzmann sampling. +/// simplify : bool, optional +/// Whether to perform simplifications before optimizing. These are: +/// +/// - ignore any indices that appear in all terms +/// - combine any repeated indices within a single term +/// - reduce any non-output indices that only appear on a single term +/// - combine any scalar terms +/// - combine any tensors with matching indices (hadamard products) +/// +/// Such simpifications may be required in the general case for the proper +/// functioning of the core optimization, but may be skipped if the input +/// indices are already in a simplified form. +/// use_ssa : bool, optional +/// Whether to return the contraction path in 'single static assignment' +/// (SSA) format (i.e. as if each intermediate is appended to the list of +/// inputs, without removals). This can be quicker and easier to work with +/// than the 'linear recycled' format that `numpy` and `opt_einsum` use. +/// +/// Returns +/// ------- +/// path : list[list[int]] +/// The contraction path, given as a sequence of pairs of node indices. It +/// may also have single term contractions if `simplify=True`. fn optimize_greedy( py: Python, inputs: Vec>, @@ -954,6 +1048,63 @@ fn optimize_greedy( #[pyfunction] #[pyo3(signature = (inputs, output, size_dict, ntrials, costmod=None, temperature=None, seed=None, simplify=None, use_ssa=None))] +/// Perform a batch of random greedy optimizations, simulteneously tracking +/// the best contraction path in terms of flops, so as to avoid constructing a +/// separate contraction tree. +/// +/// Parameters +/// ---------- +/// inputs : tuple[tuple[str]] +/// The indices of each input tensor. +/// output : tuple[str] +/// The indices of the output tensor. +/// size_dict : dict[str, int] +/// A dictionary mapping indices to their dimension. +/// ntrials : int, optional +/// The number of random greedy trials to perform. The default is 1. +/// costmod : (float, float), optional +/// When assessing local greedy scores how much to weight the size of the +/// tensors removed compared to the size of the tensor added:: +/// +/// score = size_ab / costmod - (size_a + size_b) * costmod +/// +/// It is sampled uniformly from the given range. +/// temperature : (float, float), optional +/// When asessing local greedy scores, how much to randomly perturb the +/// score. This is implemented as:: +/// +/// score -> sign(score) * log(|score|) - temperature * gumbel() +/// +/// which implements boltzmann sampling. It is sampled log-uniformly from +/// the given range. +/// seed : int, optional +/// The seed for the random number generator. +/// simplify : bool, optional +/// Whether to perform simplifications before optimizing. These are: +/// +/// - ignore any indices that appear in all terms +/// - combine any repeated indices within a single term +/// - reduce any non-output indices that only appear on a single term +/// - combine any scalar terms +/// - combine any tensors with matching indices (hadamard products) +/// +/// Such simpifications may be required in the general case for the proper +/// functioning of the core optimization, but may be skipped if the input +/// indices are already in a simplified form. +/// use_ssa : bool, optional +/// Whether to return the contraction path in 'single static assignment' +/// (SSA) format (i.e. as if each intermediate is appended to the list of +/// inputs, without removals). This can be quicker and easier to work with +/// than the 'linear recycled' format that `numpy` and `opt_einsum` use. +/// +/// Returns +/// ------- +/// path : list[list[int]] +/// The best contraction path, given as a sequence of pairs of node +/// indices. +/// flops : float +/// The flops (/ contraction cost / number of multiplications), of the best +/// contraction path, given log10. fn optimize_random_greedy_track_flops( py: Python, inputs: Vec>, @@ -1040,6 +1191,66 @@ fn optimize_random_greedy_track_flops( #[pyfunction] #[pyo3(signature = (inputs, output, size_dict, minimize=None, cost_cap=None, search_outer=None, simplify=None, use_ssa=None))] +/// Find an optimal contraction ordering. +/// +/// Parameters +/// ---------- +/// inputs : Sequence[Sequence[str]] +/// The indices of each input tensor. +/// output : Sequence[str] +/// The indices of the output tensor. +/// size_dict : dict[str, int] +/// The size of each index. +/// minimize : str, optional +/// The cost function to minimize. The options are: +/// +/// - "flops": minimize with respect to total operation count only +/// (also known as contraction cost) +/// - "size": minimize with respect to maximum intermediate size only +/// (also known as contraction width) +/// - 'max': minimize the single most expensive contraction, i.e. the +/// asymptotic (in index size) scaling of the contraction +/// - 'write' : minimize the sum of all tensor sizes, i.e. memory written +/// - 'combo' or 'combo={factor}` : minimize the sum of +/// FLOPS + factor * WRITE, with a default factor of 64. +/// - 'limit' or 'limit={factor}` : minimize the sum of +/// MAX(FLOPS, alpha * WRITE) for each individual contraction, with a +/// default factor of 64. +/// +/// 'combo' is generally a good default in term of practical hardware +/// performance, where both memory bandwidth and compute are limited. +/// cost_cap : float, optional +/// The maximum cost of a contraction to initially consider. This acts like +/// a sieve and is doubled at each iteration until the optimal path can +/// be found, but supplying an accurate guess can speed up the algorithm. +/// search_outer : bool, optional +/// If True, consider outer product contractions. This is much slower but +/// theoretically might be required to find the true optimal 'flops' +/// ordering. In practical settings (i.e. with minimize='combo'), outer +/// products should not be required. +/// simplify : bool, optional +/// Whether to perform simplifications before optimizing. These are: +/// +/// - ignore any indices that appear in all terms +/// - combine any repeated indices within a single term +/// - reduce any non-output indices that only appear on a single term +/// - combine any scalar terms +/// - combine any tensors with matching indices (hadamard products) +/// +/// Such simpifications may be required in the general case for the proper +/// functioning of the core optimization, but may be skipped if the input +/// indices are already in a simplified form. +/// use_ssa : bool, optional +/// Whether to return the contraction path in 'single static assignment' +/// (SSA) format (i.e. as if each intermediate is appended to the list of +/// inputs, without removals). This can be quicker and easier to work with +/// than the 'linear recycled' format that `numpy` and `opt_einsum` use. +/// +/// Returns +/// ------- +/// path : list[list[int]] +/// The contraction path, given as a sequence of pairs of node indices. It +/// may also have single term contractions if `simplify=True`. fn optimize_optimal( py: Python, inputs: Vec>,