Package: cotengrust
cotengrustcotengrustprovides fast rust implementations of contraction ordering
primitives for tensor networks or einsum expressions. The two main functions
are:optimize_optimal(inputs, output, size_dict, **kwargs)optimize_greedy(inputs, output, size_dict, **kwargs)The optimal algorithm is an optimized version of theopt_einsum'dp'
path - itself an implementation ofhttps://arxiv.org/abs/1304.6112.Installationcotengrustis available for most platforms fromPyPI:pipinstallcotengrustor if you want to develop locally (which requirespyo3andmaturin):gitclonehttps://github.com/jcmgray/cotengrust.gitcdcotengrust
maturindevelop--release(the release flag is very important for assessing performance!).UsageIfcotengrustis installed, then by defaultcotengrawill use it for its
greedy and optimal subroutines, notably subtree reconfiguration. You can also
call the routines directly:importcotengraasctgimportcotengrustasctgr# specify an 8x8 square lattice contractioninputs,output,shapes,size_dict=ctg.utils.lattice_equation([8,8])# find the optimal 'combo' contraction path%%timepath=ctgr.optimize_optimal(inputs,output,size_dict,minimize='combo')# CPU times: user 13.7 s, sys: 83.4 ms, total: 13.7 s# Wall time: 13.7 s# construct a contraction tree for further introspectiontree=ctg.ContractionTree.from_path(inputs,output,size_dict,path=path)tree.plot_rubberband()APIThe optimize functions follow the api of the python implementations incotengra.pathfinders.path_basic.py.defoptimize_optimal(inputs,output,size_dict,minimize='flops',cost_cap=2,search_outer=False,simplify=True,use_ssa=False,):"""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, optionalThe 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)- 'write' : minimize the sum of all tensor sizes, i.e. memory written- 'combo' or 'combo={factor}` : minimize the sum ofFLOPS + factor * WRITE, with a default factor of 64.- 'limit' or 'limit={factor}` : minimize the sum ofMAX(FLOPS, alpha * WRITE) for each individual contraction, with adefault factor of 64.'combo' is generally a good default in term of practical hardwareperformance, where both memory bandwidth and compute are limited.cost_cap : float, optionalThe maximum cost of a contraction to initially consider. This acts likea sieve and is doubled at each iteration until the optimal path canbe found, but supplying an accurate guess can speed up the algorithm.search_outer : bool, optionalIf True, consider outer product contractions. This is much slower buttheoretically might be required to find the true optimal 'flops'ordering. In practical settings (i.e. with minimize='combo'), outerproducts should not be required.simplify : bool, optionalWhether 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 properfunctioning of the core optimization, but may be skipped if the inputindices are already in a simplified form.use_ssa : bool, optionalWhether to return the contraction path in 'single static assignment'(SSA) format (i.e. as if each intermediate is appended to the list ofinputs, without removals). This can be quicker and easier to work withthan 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. Itmay also have single term contractions if `simplify=True`."""...defoptimize_greedy(inputs,output,size_dict,costmod=1.0,temperature=0.0,simplify=True,use_ssa=False,):"""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, optionalWhen assessing local greedy scores how much to weight the size of thetensors removed compared to the size of the tensor added::score = size_ab - costmod * (size_a + size_b)This can be a useful hyper-parameter to tune.temperature : float, optionalWhen asessing local greedy scores, how much to randomly perturb thescore. This is implemented as::score -> sign(score) * log(|score|) - temperature * gumbel()which implements boltzmann sampling.simplify : bool, optionalWhether 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 properfunctioning of the core optimization, but may be skipped if the inputindices are already in a simplified form.use_ssa : bool, optionalWhether to return the contraction path in 'single static assignment'(SSA) format (i.e. as if each intermediate is appended to the list ofinputs, without removals). This can be quicker and easier to work withthan 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. Itmay also have single term contractions if `simplify=True`."""defoptimize_simplify(inputs,output,size_dict,use_ssa=False,):"""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, optionalWhether to return the contraction path in 'single static assignment'(SSA) format (i.e. as if each intermediate is appended to the list ofinputs, without removals). This can be quicker and easier to work withthan 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. Itmay also have single term contractions."""...defssa_to_linear(ssa_path,n=None):"""Convert a SSA path to linear format."""...deffind_subgraphs(inputs,output,size_dict,):"""Find all disconnected subgraphs of a specified contraction."""...