cotengra.core

Core contraction tree data structure and methods.

Attributes

Classes

CompressedStatsTracker

MaxCounter

Simple class to keep track of the maximum in a likely changing

oset

An ordered set which stores elements as the keys of dict (ordered as of

SliceInfo

ContractionTree

Binary tree representing a tensor network contraction.

ContractionTreeCompressed

A contraction tree for compressed contractions. Currently the only

ContractionTreeMulti

Binary tree representing a tensor network contraction.

PartitionTreeBuilder

Function wrapper that takes a function that partitions graphs and

Functions

make_contractor(tree[, order, prefer_einsum, ...])

Get a reusable function which performs the contraction corresponding

get_hypergraph(inputs[, output, size_dict, accel])

Single entry-point for creating a, possibly accelerated, HyperGraph.

can_scatter(pool)

Whether pool can make objects remote.

maybe_leave_pool(pool)

Logic required for nested parallelism in dask.distributed.

maybe_rejoin_pool(is_worker, pool)

Logic required for nested parallelism in dask.distributed.

parse_parallel_arg(parallel)

scatter(pool, data)

Interface for maybe turning data into a remote object or reference.

submit(pool, fn, *args, **kwargs)

Interface for submitting fn(*args, **kwargs) to pool.

parallel_temper_tree(tree_or_trees[, tfinal, tstart, ...])

Perform parallel tempering optimization of a contraction tree. This

simulated_anneal_tree(tree[, tfinal, tstart, tsteps, ...])

Perform a simulated annealing optimization of this contraction

plot_contractions(tree[, order, color_size, ...])

plot_contractions_alt(tree[, x, y, color, size, ...])

plot_hypergraph(H, *[, edge_color, node_color, ...])

plot_tree_circuit(tree[, edge_colormap, ...])

plot_tree_flat(tree[, edge_color, leaf_color, ...])

Plot a ContractionTree as a flat, 2D diagram, including all indices

plot_tree_ring(tree, **kwargs)

plot_tree_rubberband(tree[, order, colormap, ...])

Plot a ContractionTree using 'rubberbands' to represent intermediate

plot_tree_span(tree, **kwargs)

plot_tree_tent(tree, **kwargs)

get_score_fn(minimize)

compute_size_by_dict(indices, size_dict)

Computes the product of sizes of indices based on size_dict.

deprecated(fn, old_name, new_name)

get_rng([seed])

Get a source of random numbers.

get_symbol(i)

Get the symbol corresponding to int i - runs through the usual 52

inputs_output_to_eq(inputs, output[, canonicalize])

Convert an explicit list of inputs and output to a str einsum equation.

node_from_seq(it)

prod(it)

Compute the product of sequence of numbers it.

cached_node_property(name)

Decorator for caching information about nodes.

union_it(bs)

Non-variadic version of various set type unions.

legs_union(legs_seq)

Combine a sequence of legs into a single set of legs, summing their

legs_without(legs, ind)

Discard ind from legs to create a new set of legs.

get_with_default(k, obj, default)

get_slice_strides(sliced_inds)

Compute the 'strides' given the (ordered) dictionary of sliced indices.

_reconfigure_tree(tree, *args, **kwargs)

_slice_and_reconfigure_tree(tree, *args, **kwargs)

_get_tree_info(tree)

_describe_tree(tree[, info])

jitter(x, strength, rng)

jitter_dict(d, strength[, seed])

separate(xs, blocks)

Partition xs into n different list based on the corresponding

Module Contents

cotengra.core.make_contractor(tree, order=None, prefer_einsum=False, strip_exponent=False, check_zero=False, implementation=None, autojit=False, progbar=False)[source]

Get a reusable function which performs the contraction corresponding to tree. The various options provide defaults that can also be overrode when calling the standard contractor.

Parameters:
  • tree (ContractionTree) – The contraction tree.

  • order (str or callable, optional) – Supplied to ContractionTree.traverse(), the order in which to perform the pairwise contractions given by the tree.

  • prefer_einsum (bool, optional) – Prefer to use einsum for pairwise contractions, even if tensordot can perform the contraction.

  • strip_exponent (bool, optional) – If True, the function will strip the exponent from the output array and return it separately.

  • check_zero (bool, optional) – If True, when strip_exponent=True, explicitly check for zero-valued intermediates that would otherwise produce nan, instead terminating early if encountered and returning (0.0, 0.0).

  • implementation (str or tuple[callable, callable], optional) –

    What library to use to actually perform the contractions. Options are

    • ”auto”: let cotengra choose

    • ”autoray”: dispatch with autoray, using the tensordot and einsum implementation of the backend

    • ”cotengra”: use the tensordot and einsum implementation of cotengra, which is based on batch matrix multiplication. This is faster for some backends like numpy, and also enables libraries which don’t yet provide tensordot and einsum to be used.

    • ”cuquantum”: use the cuquantum library to perform the whole contraction (not just individual contractions).

    • tuple[callable, callable]: manually supply the tensordot and einsum implementations to use.

  • autojit (bool, optional) – If True, use autoray.autojit() to compile the contraction function.

  • progbar (bool, optional) – Whether to show progress through the contraction by default.

Returns:

fn – The contraction function, with signature fn(*arrays).

Return type:

callable

cotengra.core.get_hypergraph(inputs, output=None, size_dict=None, accel=False)[source]

Single entry-point for creating a, possibly accelerated, HyperGraph.

cotengra.core.can_scatter(pool)[source]

Whether pool can make objects remote.

cotengra.core.maybe_leave_pool(pool)[source]

Logic required for nested parallelism in dask.distributed.

cotengra.core.maybe_rejoin_pool(is_worker, pool)[source]

Logic required for nested parallelism in dask.distributed.

cotengra.core.parse_parallel_arg(parallel)[source]
cotengra.core.scatter(pool, data)[source]

Interface for maybe turning data into a remote object or reference.

cotengra.core.submit(pool, fn, *args, **kwargs)[source]

Interface for submitting fn(*args, **kwargs) to pool.

cotengra.core.parallel_temper_tree(tree_or_trees, tfinal=0.01, tstart=1, tsteps=50, num_trees=8, numiter=50, minimize=None, target_size=None, slice_mode='drift', parallel_slice_mode='temperature', swappiness=1.0, max_time=None, seed=None, parallel='auto', info=None, progbar=False, inplace=False)[source]

Perform parallel tempering optimization of a contraction tree. This anneals num_trees different trees at a range of temperatures between tfinal and tstart. After each step, trees are exchanged between neighboring temperatures according to the Metropolis-Hastings criterion.

Parameters:
  • tree_or_trees (ContractionTree or sequence of ContractionTree) – The tree or trees to optimize. If less than num_trees are given, then they will be cycled. If more than num_trees are given, then the length will override num_trees.

  • tfinal (float, optional) – The final temperature.

  • tstart (float, optional) – The starting temperature.

  • tsteps (int, optional) – The number of temperature steps, each with numiter iterations. After each step, trees are exchanged between neighboring temperatures.

  • num_trees (int, optional) – The number of trees and thus temperatures to optimize in parallel.

  • numiter (int, optional) – The number of iterations to perform at each step. The total number of sweeps (per parallel temperature) is numiter * tsteps.

  • minimize ({'flops', 'combo', 'write', 'size', ...}, optional) – The objective function to minimize.

  • target_size (int, optional) – The target size of the contraction.

  • slice_mode ({'basic', 'reslice', 'drift'}, optional) – The mode for slicing the contraction tree within each annealing iteration.

  • parallel_slice_mode ({'temperature', 'time', 'constant'}, optional) – The parallel mode for slicing the contraction tree. If ‘temperature’, then the target size decreases with temperature. If ‘time’, then the target size decreases with time. If ‘constant’, then the target size is constant.

  • seed (int, optional) – A random seed.

  • parallel ('auto', False, True, int, or distributed.Client) – Whether to parallelize the search.

  • progbar (bool, optional) – Whether to show live progress.

  • inplace (bool, optional) – Whether to perform the optimization inplace.

cotengra.core.simulated_anneal_tree(tree, tfinal=0.05, tstart=2, tsteps=50, numiter=50, minimize=None, target_size=None, target_size_initial=None, slice_mode='basic', seed=None, progbar=False, inplace=False)[source]

Perform a simulated annealing optimization of this contraction tree, based on “Multi-Tensor Contraction for XEB Verification of Quantum Circuits” by Gleb Kalachev, Pavel Panteleev, Man-Hong Yung (arXiv:2108.05665), and the “treesa” implementation in OMEinsumContractionOrders.jl by Jin-Guo Liu and Pan Zhang.

Parameters:
  • tfinal (float, optional) – The final temperature.

  • tstart (float, optional) – The starting temperature.

  • tsteps (int, optional) – The number of temperature steps.

  • numiter (int, optional) – The number of sweeps at each temperature step.

  • minimize ({'flops', 'combo', 'write', 'size', ...}, optional) – The objective function to minimize.

  • target_size (int, optional) – The target size to slice the contraction to. A schedule is used to reach this only at the final temperature step.

  • target_size_initial (int, optional) – The initial target size to use in the slicing schedule. If None, then the current size is used.

  • slice_mode ({'basic', 'reslice', 'drift'}, optional) – The mode for slicing the contraction tree within each annealing iteration. ‘basic’ always unslices a random index and then slices to the target size. ‘reslice’ unslices all indices and then slices to the target size. ‘drift’ unslices a random index with probability 1/4 and slices to the target size with probability 3/4. It is therefore not guaranteed to reach the target size, but may be more explorative for long annealing schedules.

  • seed (int, optional) – A random seed.

  • progbar (bool, optional) – Whether to show live progress.

  • inplace (bool, optional) – Whether to perform the optimization inplace.

Return type:

ContractionTree

cotengra.core.plot_contractions(tree, order=None, color_size=(0.6, 0.4, 0.7), color_cost=(0.3, 0.7, 0.5), figsize=(8, 3))[source]
cotengra.core.plot_contractions_alt(tree, x='peak-size', y='flops', color='stage', size='scaling', width=400, height=400, point_opacity=0.8, color_scheme='lightmulti', x_scale='log', y_scale='log', color_scale='log', size_scale='linear')[source]
cotengra.core.plot_hypergraph(H, *, edge_color=True, node_color=True, highlight=(), centrality='simple', colormap='plasma', pos=None, dim=2, layout='auto', initial_layout='auto', iterations='auto', k=None, use_forceatlas2=False, flatten=False, node_size=None, node_scale=1.0, edge_alpha=1 / 3, edge_style='solid', hyperedge_style='dashed', draw_edge_labels=None, fontcolor=(0.5, 0.5, 0.5), edge_labels_font_size=8, edge_labels_font_family='monospace', node_labels_font_size=10, node_labels_font_family='monospace', info=None, ax=None, figsize=(5, 5))[source]
cotengra.core.plot_tree_circuit(tree, edge_colormap='GnBu', edge_max_width=None, node_colormap='YlOrRd', node_max_size=None, figsize=None)[source]
cotengra.core.plot_tree_flat(tree, edge_color=True, leaf_color=True, node_color=(0.5, 0.5, 0.5, 0.5), hyperedge_style='dashed', multiedge_spread=0.05, multiedge_smoothing=0.5, multiedge_midlength=0.5, fontcolor=(0.5, 0.5, 0.5), edge_labels_font_size=6, edge_labels_font_family='monospace', node_labels_font_size=8, node_labels_font_family='monospace', show_sliced=True, figsize=None)[source]

Plot a ContractionTree as a flat, 2D diagram, including all indices at every intermediate contraction. This can be useful for small contractions, and does not require any graph layout algorithm.

Parameters:
  • tree (ContractionTree) – The contraction tree to plot.

  • edge_color (bool or color, optional) – Whether to color the edges, or a specific color to use. If True (default), each edge will be colored according to a hash of its index.

  • leaf_color (bool or color, optional) – Whether to color the input nodes, or a specific color to use. If True (default), each leaf node will be colored with an automatically generated sequence according to its linear position in the input.

  • node_color (bool or color, optional) – Whether to color the intermediate nodes, or a specific color to use. If True (default), each intermediate node will be colored with the average color of its children.

  • hyperedge_style (str, optional) – The linestyle to use for hyperedges, i.e. indices that don’t appeary exactly twice on either inputs or the output.

  • multiedge_spread (float, optional) – The spread of multi-edges between nodes.

  • multiedge_smoothing (float, optional) – The smoothing of multi-edges between nodes.

  • multiedge_midlength (float, optional) – The midlength of multi-edges between nodes.

  • fontcolor (color, optional) – The color to use for edge and node labels.

  • edge_labels_font_size (int, optional) – The font size to use for edge labels.

  • edge_labels_font_family (str, optional) – The font family to use for edge labels.

  • node_labels_font_size (int, optional) – The font size to use for node labels.

  • node_labels_font_family (str, optional) – The font family to use for node labels.

  • show_sliced (bool, optional) – Whether to list sliced indices at the top left.

  • figsize (tuple, optional) – The size of the figure to create, if not specified will be based on the number of nodes in the tree.

Returns:

  • fig (matplotlib.figure.Figure) – The figure containing the plot.

  • ax (matplotlib.axes.Axes) – The axes containing the plot.

cotengra.core.plot_tree_ring(tree, **kwargs)[source]
cotengra.core.plot_tree_rubberband(tree, order=None, colormap='Spectral', with_edge_labels=None, with_node_labels=None, highlight=(), centrality=False, layout='auto', node_size=None, node_color=(0.5, 0.5, 0.5, 1.0), edge_color=(0.5, 0.5, 0.5), edge_alpha=1 / 3, edge_style='solid', hyperedge_style='dashed', draw_edge_labels=None, edge_labels_font_size=8, edge_labels_font_family='monospace', iterations=500, ax=None, figsize=(5, 5))[source]

Plot a ContractionTree using ‘rubberbands’ to represent intermediate contractions / subgraphs. This can be intuitive for small and / or planar contractions.

cotengra.core.plot_tree_span(tree, **kwargs)[source]
cotengra.core.plot_tree_tent(tree, **kwargs)[source]
cotengra.core.DEFAULT_COMBO_FACTOR = 64
class cotengra.core.CompressedStatsTracker(hg, chi)[source]
__slots__ = ('chi', 'flops', 'max_size', 'peak_size', 'write', 'total_size', 'total_size_post_contract',...
copy()[source]
update_pre_step()[source]
update_pre_compress(hg, *nodes)[source]
update_post_compress(hg, *nodes)[source]
update_pre_contract(hg, i, j)[source]
update_post_contract(hg, ij)[source]
update_post_step()[source]
update_score(other)[source]
property combo_score
abstract property score
describe(join=' ')[source]
__repr__()[source]

Return repr(self).

cotengra.core.get_score_fn(minimize)[source]
class cotengra.core.MaxCounter(it=None)[source]

Simple class to keep track of the maximum in a likely changing sequence of elements.

Parameters:

it (None or sequence of hashable, optional) – The initial items to add.

Examples

>>> mc = MaxCounter([1, 2, 3, 3])
>>> mc.max()
3
>>> mc.discard(3)
>>> mc.max()
3
>>> mc.discard(3)
>>> mc.max()
2
>>> mc.add(10)
>>> mc.max()
10
__slots__ = ('_c', '_max_element')
copy()[source]
discard(x)[source]

Discard element x and possibly update the maximum.

add(x)[source]

Add element x and possibly update the maximum.

max()[source]

The maximum element in this list.

cotengra.core.compute_size_by_dict(indices, size_dict)[source]

Computes the product of sizes of indices based on size_dict.

Parameters:
  • indices (iterable[str] or iterable[int]) – The indices of the term.

  • size_dict (dict or list) – Mapping (or list/tuple if the indices are indexing integers, which can be slightly faster) of indices to sizes.

Returns:

d – The resulting product.

Return type:

int

Examples

>>> compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
90
cotengra.core.deprecated(fn, old_name, new_name)[source]
cotengra.core.get_rng(seed=None)[source]

Get a source of random numbers.

Parameters:

seed (None or int or random.Random, optional) – The seed for the random number generator. If None, use the default random number generator. If an integer, use a new random number generator with the given seed. If a random.Random instance, use that instance.

cotengra.core.get_symbol(i)[source]

Get the symbol corresponding to int i - runs through the usual 52 letters before resorting to unicode characters, starting at chr(192) and skipping surrogates.

Examples

get_symbol(2) #> ‘c’

get_symbol(200) #> ‘Ŕ’

get_symbol(20000) #> ‘京’

cotengra.core.inputs_output_to_eq(inputs, output, canonicalize=False)[source]

Convert an explicit list of inputs and output to a str einsum equation.

Parameters:
  • inputs (list[list[str]]) – The input terms.

  • output (list[str]) – The output term.

  • canonicalize (bool, optional) – Whether to canonicalize (map into [a-zA-Z]) equation, by default False.

Returns:

eq – The einsum equation.

Return type:

str

cotengra.core.node_from_seq(it)[source]
class cotengra.core.oset(it=())[source]

An ordered set which stores elements as the keys of dict (ordered as of python 3.6). ‘A few times’ slower than using a set directly for small sizes, but makes everything deterministic.

__slots__ = ('_d',)
classmethod _from_dict(d)[source]
classmethod from_dict(d)[source]

Public method makes sure to copy incoming dictionary.

copy()[source]
add(k)[source]
discard(k)[source]
remove(k)[source]
clear()[source]
update(*others)[source]
union(*others)[source]
intersection_update(*others)[source]
intersection(*others)[source]
difference_update(*others)[source]
difference(*others)[source]
symmetric_difference(other)[source]
__eq__(other)[source]

Return self==value.

__or__(other)[source]
__ior__(other)[source]
__and__(other)[source]
__iand__(other)[source]
__sub__(other)[source]
__isub__(other)[source]
__len__()[source]
__iter__()[source]
__contains__(x)[source]
__repr__()[source]

Return repr(self).

cotengra.core.prod(it)[source]

Compute the product of sequence of numbers it.

cotengra.core.cached_node_property(name)[source]

Decorator for caching information about nodes.

cotengra.core.union_it(bs)[source]

Non-variadic version of various set type unions.

cotengra.core.legs_union(legs_seq)[source]

Combine a sequence of legs into a single set of legs, summing their appearances.

cotengra.core.legs_without(legs, ind)[source]

Discard ind from legs to create a new set of legs.

cotengra.core.get_with_default(k, obj, default)[source]
class cotengra.core.SliceInfo[source]
inner: bool
ind: str
size: int
project: int | None
property sliced_range
cotengra.core.get_slice_strides(sliced_inds)[source]

Compute the ‘strides’ given the (ordered) dictionary of sliced indices.

class cotengra.core.ContractionTree(inputs, output, size_dict, track_childless=False, track_flops=False, track_write=False, track_size=False, objective=None)[source]

Binary tree representing a tensor network contraction.

Parameters:
  • inputs (sequence of str) – The list of input tensor’s indices.

  • output (str) – The output indices.

  • size_dict (dict[str, int]) – The size of each index.

  • track_childless (bool, optional) – Whether to dynamically keep track of which nodes are childless. Useful if you are ‘divisively’ building the tree.

  • track_flops (bool, optional) – Whether to dynamically keep track of the total number of flops. If False You can still compute this once the tree is complete.

  • track_write (bool, optional) – Whether to dynamically keep track of the total number of elements written. If False You can still compute this once the tree is complete.

  • track_size (bool, optional) – Whether to dynamically keep track of the largest tensor so far. If False You can still compute this once the tree is complete.

  • objective (str or Objective, optional) – An default objective function to use for further optimization and scoring, for example reconfiguring or computing the combo cost. If not supplied the default is to create a flops objective when needed.

children

Mapping of each node to two children.

Type:

dict[node, tuple[node]]

info

Information about the tree nodes. The key is the set of inputs (a set of inputs indices) the node contains. Or in other words, the subgraph of the node. The value is a dictionary to cache information about effective ‘leg’ indices, size, flops of formation etc.

Type:

dict[node, dict]

set_state_from(other)[source]

Set the internal state of this tree to that of other.

copy()[source]

Create a copy of this ContractionTree.

set_default_objective(objective)[source]

Set the objective function for this tree.

get_default_objective()[source]

Get the objective function for this tree.

get_default_combo_factor()[source]

Get the default combo factor for this tree.

property nslices
Simple alias for how many independent contractions this tree
represents overall.
property nchunks
The number of 'chunks' - determined by the number of sliced output
indices.
node_to_terms(node)[source]

Turn a node – a frozen set of ints – into the corresponding terms – a sequence of sets of str corresponding to input indices.

gen_leaves()[source]

Generate the nodes representing leaves of the contraction tree, i.e. of size 1 each corresponding to a single input tensor.

get_incomplete_nodes()[source]

Get the set of current nodes that have no children and the set of nodes that have no parents. These are the ‘childless’ and ‘parentless’ nodes respectively, that need to be contracted to complete the tree. The parentless nodes are grouped into the childless nodes that contain them as subgraphs.

Returns:

groups – A mapping of childless nodes to the list of parentless nodes are beneath them.

Return type:

dict[frozenet[int], list[frozenset[int]]]

See also

autocomplete

autocomplete(**contract_opts)[source]

Contract all remaining node groups (as computed by tree.get_incomplete_nodes) in the tree to complete it.

Parameters:

contract_opts – Options to pass to tree.contract_nodes.

classmethod from_path(inputs, output, size_dict, *, path=None, ssa_path=None, autocomplete='auto', check=False, **kwargs)[source]

Create a (completed) ContractionTree from the usual inputs plus a standard contraction path or ‘ssa_path’ - you need to supply one.

Parameters:
  • inputs (Sequence[Sequence[str]]) – The input indices of each tensor, as single unicode characters.

  • output (Sequence[str]) – The output indices.

  • size_dict (dict[str, int]) – The size of each index.

  • path (Sequence[Sequence[int]], optional) – The contraction path, a sequence of pairs of tensor ids to contract. The ids are linear indices into the list of temporary tensors, which are recycled as each contraction pops a pair and appends the result. This or ssa_path must be supplied.

  • ssa_path (Sequence[Sequence[int]], optional) – The contraction path, a sequence of pairs of indices to contract. The indices are single use, as if the result of each contraction is appended to the end of the list of temporary tensors without popping. This or path must be supplied.

  • autocomplete ("auto" or bool, optional) – Whether to automatically complete the path, i.e. contract all remaining nodes. If “auto” then a warning is issued if the path is not complete.

  • check (bool, optional) – Whether to perform some basic checks while creating the contraction nodes.

Return type:

ContractionTree

classmethod from_info(info, **kwargs)[source]

Create a ContractionTree from an opt_einsum.PathInfo object.

classmethod from_eq(eq, size_dict, **kwargs)[source]

Create a empty ContractionTree directly from an equation and set of shapes.

Parameters:
  • eq (str) – The einsum string equation.

  • size_dict (dict[str, int]) – The size of each index.

get_eq()[source]

Get the einsum equation corresponding to this tree. Note that this is the total (or original) equation, so includes indices which have been sliced.

Returns:

eq

Return type:

str

get_shapes()[source]

Get the shapes of the input tensors corresponding to this tree.

Returns:

shapes

Return type:

tuple[tuple[int]]

get_inputs_sliced()[source]

Get the input indices corresponding to a single slice of this tree, i.e. with sliced indices removed.

Returns:

inputs

Return type:

tuple[tuple[str]]

get_output_sliced()[source]

Get the output indices corresponding to a single slice of this tree, i.e. with sliced indices removed.

Returns:

output

Return type:

tuple[str]

get_eq_sliced()[source]

Get the einsum equation corresponding to a single slice of this tree, i.e. with sliced indices removed.

Returns:

eq

Return type:

str

get_shapes_sliced()[source]

Get the shapes of the input tensors corresponding to a single slice of this tree, i.e. with sliced indices removed.

Returns:

shapes

Return type:

tuple[tuple[int]]

classmethod from_edge_path(edge_path, inputs, output, size_dict, check=False, **kwargs)[source]

Create a ContractionTree from an edge elimination ordering.

_add_node(node, check=False)[source]
_remove_node(node)[source]

Remove node from this tree and update the flops and maximum size if tracking them respectively, as well as input pre-processing.

compute_leaf_legs(i)[source]

Compute the effective ‘outer’ indices for the ith input tensor. This is not always simply the ith input indices, due to A) potential slicing and B) potential preprocessing.

has_preprocessing()[source]
has_hyper_indices()[source]

Check if there are any ‘hyper’ indices in the contraction, i.e. indices that don’t appear exactly twice, when considering the inputs and output.

get_legs(node)[source]

Get the effective ‘outer’ indices for the collection of tensors in node.

get_involved(node)[source]

Get all the indices involved in the formation of subgraph node.

get_size(node)[source]

Get the tensor size of node.

get_flops(node)[source]

Get the FLOPs for the pairwise contraction that will create node.

get_can_dot(node)[source]

Get whether this contraction can be performed as a dot product (i.e. with tensordot), or else requires einsum, as it has indices that don’t appear exactly twice in either the inputs or the output.

get_inds(node)[source]

Get the indices of this node - an ordered string version of get_legs that starts with tree.inputs and maintains the order they appear in each contraction ‘ABC,abc->ABCabc’, to match tensordot.

get_tensordot_axes(node)[source]

Get the axes arg for a tensordot ocontraction that produces node. The pairs are sorted in order of appearance on the left input.

get_tensordot_perm(node)[source]

Get the permutation required, if any, to bring the tensordot output of this nodes contraction into line with self.get_inds(node).

get_einsum_eq(node)[source]

Get the einsum string describing the contraction that produces node, unlike get_inds the characters are mapped into [a-zA-Z], for compatibility with numpy.einsum for example.

get_centrality(node)[source]
total_flops(dtype=None, log=None)[source]

Sum the flops contribution from every node in the tree.

Parameters:

dtype ({'float', 'complex', None}, optional) – Scale the answer depending on the assumed data type.

total_write()[source]

Sum the total amount of memory that will be created and operated on.

combo_cost(factor=DEFAULT_COMBO_FACTOR, combine=sum, log=None)[source]
total_cost[source]
max_size(log=None)[source]

The size of the largest intermediate tensor.

peak_size(order=None, log=None)[source]

Get the peak concurrent size of tensors needed - this depends on the traversal order, i.e. the exact contraction path, not just the contraction tree.

contract_stats(force=False)[source]

Simulteneously compute the total flops, write and size of the contraction tree. This is more efficient than calling each of the individual methods separately. Once computed, each quantity is then automatically tracked.

Returns:

stats – The total flops, write and size.

Return type:

dict[str, int]

arithmetic_intensity()[source]

The ratio of total flops to total write - the higher the better for extracting good computational performance.

contraction_scaling()[source]

This is computed simply as the maximum number of indices involved in any single contraction, which will match the scaling assuming that all dimensions are equal.

contraction_cost(log=None)[source]

Get the total number of scalar operations ~ time complexity.

contraction_width(log=2)[source]

Get log2 of the size of the largest tensor.

compressed_contract_stats(chi=None, order='surface_order', compress_late=None)[source]
total_flops_compressed(chi=None, order='surface_order', compress_late=None, dtype=None, log=None)[source]

Estimate the total flops for a compressed contraction of this tree with maximum bond size chi. This includes basic estimates of the ops to perform contractions, QRs and SVDs.

contraction_cost_compressed[source]
total_write_compressed(chi=None, order='surface_order', compress_late=None, accel='auto', log=None)[source]

Compute the total size of all intermediate tensors when a compressed contraction is performed with maximum bond size chi, ordered by order. This is relevant maybe for time complexity and e.g. autodiff space complexity (since every intermediate is kept).

combo_cost_compressed(chi=None, order='surface_order', compress_late=None, factor=None, log=None)[source]
total_cost_compressed[source]
max_size_compressed(chi=None, order='surface_order', compress_late=None, log=None)[source]

Compute the maximum sized tensor produced when a compressed contraction is performed with maximum bond size chi, ordered by order. This is close to the ideal space complexity if only tensors that are being directly operated on are kept in memory.

peak_size_compressed(chi=None, order='surface_order', compress_late=None, accel='auto', log=None)[source]

Compute the peak size of combined intermediate tensors when a compressed contraction is performed with maximum bond size chi, ordered by order. This is the practical space complexity if one is not swapping intermediates in and out of memory.

contraction_width_compressed(chi=None, order='surface_order', compress_late=None, log=2)[source]

Compute log2 of the maximum sized tensor produced when a compressed contraction is performed with maximum bond size chi, ordered by order.

_update_tracked(node)[source]
contract_nodes_pair(x, y, legs=None, cost=None, size=None, check=False)[source]

Contract node x with node y in the tree to create a new parent node, which is returned.

Parameters:
  • x (frozenset[int]) – The first node to contract.

  • y (frozenset[int]) – The second node to contract.

  • legs (dict[str, int], optional) – The effective ‘legs’ of the new node if already known. If not given, this is computed from the inputs of x and y.

  • cost (int, optional) – The cost of the contraction if already known. If not given, this is computed from the inputs of x and y.

  • size (int, optional) – The size of the new node if already known. If not given, this is computed from the inputs of x and y.

  • check (bool, optional) – Whether to check the inputs are valid.

Returns:

parent – The new parent node of x and y.

Return type:

frozenset[int]

contract_nodes(nodes, optimize='auto-hq', check=False, extra_opts=None)[source]

Contract an arbitrary number of nodes in the tree to build up a subtree. The root of this subtree (a new intermediate) is returned.

is_complete()[source]

Check every node has two children, unless it is a leaf.

get_default_order()[source]
_traverse_ordered(order)[source]

Traverse the tree in the order that minimizes order(node), but still constrained to produce children before parents.

traverse(order=None)[source]

Generate, in order, all the node merges in this tree. Non-recursive! This ensures children are always visited before their parent.

Parameters:

order (None or callable, optional) – How to order the contractions within the tree. If a callable is given (which should take a node as its argument), try to contract nodes that minimize this function first.

Returns:

The bottom up ordered sequence of tree merges, each a tuple of (parent, left_child, right_child).

Return type:

generator[tuple[node]]

See also

descend

descend(mode='dfs')[source]

Generate, from root to leaves, all the node merges in this tree. Non-recursive! This ensures parents are visited before their children.

Parameters:

mode ({'dfs', bfs}, optional) – How expand from a parent.

Returns:

The top down ordered sequence of tree merges, each a tuple of (parent, left_child, right_child).

Return type:

generator[tuple[node]

See also

traverse

get_subtree(node, size, search='bfs', seed=None)[source]

Get a subtree spanning down from node which will have size leaves (themselves not necessarily leaves of the actual tree).

Parameters:
  • node (node) – The node of the tree to start with.

  • size (int) – How many subtree leaves to aim for.

  • search ({'bfs', 'dfs', 'random'}, optional) –

    How to build the tree:

    • ’bfs’: breadth first expansion

    • ’dfs’: depth first expansion (largest nodes first)

    • ’random’: random expansion

  • seed (None, int or random.Random, optional) – Random number generator seed, if search is ‘random’.

Returns:

  • sub_leaves (tuple[node]) – Nodes which are subtree leaves.

  • branches (tuple[node]) – Nodes which are between the subtree leaves and root.

remove_ind(ind, project=None, inplace=False)[source]

Remove (i.e. by default slice) index ind from this contraction tree, taking care to update all relevant information about each node.

remove_ind_[source]
restore_ind(ind, inplace=False)[source]

Restore (unslice or un-project) index ind to this contraction tree, taking care to update all relevant information about each node.

Parameters:
  • ind (str) – The index to restore.

  • inplace (bool, optional) – Whether to perform the restoration inplace or not.

Return type:

ContractionTree

restore_ind_[source]
unslice_rand(seed=None, inplace=False)[source]

Unslice (restore) a random index from this contraction tree.

Parameters:
  • seed (None, int or random.Random, optional) – Random number generator seed.

  • inplace (bool, optional) – Whether to perform the unslicing inplace or not.

Return type:

ContractionTree

unslice_rand_[source]
unslice_all(inplace=False)[source]

Unslice (restore) all sliced indices from this contraction tree.

Parameters:

inplace (bool, optional) – Whether to perform the unslicing inplace or not.

Return type:

ContractionTree

unslice_all_[source]
calc_subtree_candidates(pwr=2, what='flops')[source]
subtree_reconfigure(subtree_size=8, subtree_search='bfs', weight_what='flops', weight_pwr=2, select='max', maxiter=500, seed=None, minimize=None, optimize=None, inplace=False, progbar=False)[source]

Reconfigure subtrees of this tree with locally optimal paths.

Parameters:
  • subtree_size (int, optional) – The size of subtree to consider. Cost is exponential in this.

  • subtree_search ({'bfs', 'dfs', 'random'}, optional) –

    How to build the subtrees:

    • ’bfs’: breadth-first-search creating balanced subtrees

    • ’dfs’: depth-first-search creating imbalanced subtrees

    • ’random’: random subtree building

  • weight_what ({'flops', 'size'}, optional) – When assessing nodes to build and optimize subtrees from whether to score them by the (local) contraction cost, or tensor size.

  • weight_pwr (int, optional) – When assessing nodes to build and optimize subtrees from, how to scale their score into a probability: score**(1 / weight_pwr). The larger this is the more explorative the algorithm is when select='random'.

  • select ({'max', 'min', 'random'}, optional) –

    What order to select node subtrees to optimize:

    • ’max’: choose the highest score first

    • ’min’: choose the lowest score first

    • ’random’: choose randomly weighted on score – see weight_pwr.

  • maxiter (int, optional) – How many subtree optimizations to perform, the algorithm can terminate before this if all subtrees have been optimized.

  • seed (int, optional) – A random seed (seeds python system random module).

  • minimize ({'flops', 'size'}, optional) – Whether to minimize with respect to contraction flops or size.

  • inplace (bool, optional) – Whether to perform the reconfiguration inplace or not.

  • progbar (bool, optional) – Whether to show live progress of the reconfiguration.

Return type:

ContractionTree

subtree_reconfigure_[source]
subtree_reconfigure_forest(num_trees=8, num_restarts=10, restart_fraction=0.5, subtree_maxiter=100, subtree_size=10, subtree_search=('random', 'bfs'), subtree_select=('random',), subtree_weight_what=('flops', 'size'), subtree_weight_pwr=(2,), parallel='auto', parallel_maxiter_steps=4, minimize=None, seed=None, progbar=False, inplace=False)[source]

‘Forested’ version of subtree_reconfigure which is more explorative and can be parallelized. It stochastically generates a ‘forest’ reconfigured trees, then only keeps some fraction of these to generate the next forest.

Parameters:
  • num_trees (int, optional) – The number of trees to reconfigure at each stage.

  • num_restarts (int, optional) – The number of times to halt, prune and then restart the tree reconfigurations.

  • restart_fraction (float, optional) – The fraction of trees to keep at each stage and generate the next forest from.

  • subtree_maxiter (int, optional) – Number of subtree reconfigurations per step. num_restarts * subtree_maxiter is the max number of total subtree reconfigurations for the final tree produced.

  • subtree_size (int, optional) – The size of subtrees to search for and reconfigure.

  • subtree_search (tuple[{'random', 'bfs', 'dfs'}], optional) – Tuple of options for the search kwarg of ContractionTree.subtree_reconfigure() to randomly sample.

  • subtree_select (tuple[{'random', 'max', 'min'}], optional) – Tuple of options for the select kwarg of ContractionTree.subtree_reconfigure() to randomly sample.

  • subtree_weight_what (tuple[{'flops', 'size'}], optional) – Tuple of options for the weight_what kwarg of ContractionTree.subtree_reconfigure() to randomly sample.

  • subtree_weight_pwr (tuple[int], optional) – Tuple of options for the weight_pwr kwarg of ContractionTree.subtree_reconfigure() to randomly sample.

  • parallel ('auto', False, True, int, or distributed.Client) – Whether to parallelize the search.

  • parallel_maxiter_steps (int, optional) – If parallelizing, how many steps to break each reconfiguration into in order to evenly saturate many processes.

  • minimize ({'flops', 'size', ..., Objective}, optional) – Whether to minimize the total flops or maximum size of the contraction tree.

  • seed (None, int or random.Random, optional) – A random seed to use.

  • progbar (bool, optional) – Whether to show live progress.

  • inplace (bool, optional) – Whether to perform the subtree reconfiguration inplace.

Return type:

ContractionTree

subtree_reconfigure_forest_[source]
simulated_anneal[source]
simulated_anneal_[source]
parallel_temper[source]
parallel_temper_[source]
slice(target_size=None, target_overhead=None, target_slices=None, temperature=0.01, minimize=None, allow_outer=True, max_repeats=16, reslice=False, seed=None, inplace=False)[source]

Slice this tree (turn some indices into indices which are explicitly summed over rather than being part of contractions). The indices are stored in tree.sliced_inds, and the contraction width updated to take account of the slicing. Calling tree.contract(arrays) moreover which automatically perform the slicing and summation.

Parameters:
  • target_size (int, optional) – The target number of entries in the largest tensor of the sliced contraction. The search algorithm will terminate after this is reached.

  • target_slices (int, optional) – The target or minimum number of ‘slices’ to consider - individual contractions after slicing indices. The search algorithm will terminate after this is breached. This is on top of the current number of slices.

  • target_overhead (float, optional) – The target increase in total number of floating point operations. For example, a value of 2.0 will terminate the search just before the cost of computing all the slices individually breaches twice that of computing the original contraction all at once.

  • temperature (float, optional) – How much to randomize the repeated search.

  • minimize ({'flops', 'size', ..., Objective}, optional) – Which metric to score the overhead increase against.

  • allow_outer (bool, optional) – Whether to allow slicing of outer indices.

  • max_repeats (int, optional) – How many times to repeat the search with a slight randomization.

  • reslice (bool, optional) – Whether to reslice the tree, i.e. first remove all currently sliced indices and start the search again. Generally any ‘good’ sliced indices will be easily found again.

  • seed (None, int or random.Random, optional) – A random seed or generator to use for the search.

  • inplace (bool, optional) – Whether the remove the indices from this tree inplace or not.

Return type:

ContractionTree

slice_[source]
slice_and_reconfigure(target_size, step_size=2, temperature=0.01, minimize=None, allow_outer=True, max_repeats=16, reslice=False, reconf_opts=None, progbar=False, inplace=False)[source]

Interleave slicing (removing indices into an exterior sum) with subtree reconfiguration to minimize the overhead induced by this slicing.

Parameters:
  • target_size (int) – Slice the tree until the maximum intermediate size is this or smaller.

  • step_size (int, optional) – The minimum size reduction to try and achieve before switching to a round of subtree reconfiguration.

  • temperature (float, optional) – The temperature to supply to SliceFinder for searching for indices.

  • minimize ({'flops', 'size', ..., Objective}, optional) – The metric to minimize when slicing and reconfiguring subtrees.

  • max_repeats (int, optional) – The number of slicing attempts to perform per search.

  • progbar (bool, optional) – Whether to show live progress.

  • inplace (bool, optional) – Whether to perform the slicing and reconfiguration inplace.

  • reconf_opts (None or dict, optional) – Supplied to ContractionTree.subtree_reconfigure() or ContractionTree.subtree_reconfigure_forest(), depending on ‘forested’ key value.

slice_and_reconfigure_[source]
slice_and_reconfigure_forest(target_size, step_size=2, num_trees=8, restart_fraction=0.5, temperature=0.02, max_repeats=32, reslice=False, minimize=None, allow_outer=True, parallel='auto', progbar=False, inplace=False, reconf_opts=None)[source]

‘Forested’ version of ContractionTree.slice_and_reconfigure(). This maintains a ‘forest’ of trees with different slicing and subtree reconfiguration attempts, pruning the worst at each step and generating a new forest from the best.

Parameters:
  • target_size (int) – Slice the tree until the maximum intermediate size is this or smaller.

  • step_size (int, optional) – The minimum size reduction to try and achieve before switching to a round of subtree reconfiguration.

  • num_restarts (int, optional) – The number of times to halt, prune and then restart the tree reconfigurations.

  • restart_fraction (float, optional) – The fraction of trees to keep at each stage and generate the next forest from.

  • temperature (float, optional) – The temperature at which to randomize the sliced index search.

  • max_repeats (int, optional) – The number of slicing attempts to perform per search.

  • parallel ('auto', False, True, int, or distributed.Client) – Whether to parallelize the search.

  • progbar (bool, optional) – Whether to show live progress.

  • inplace (bool, optional) – Whether to perform the slicing and reconfiguration inplace.

  • reconf_opts (None or dict, optional) – Supplied to ContractionTree.slice_and_reconfigure().

Return type:

ContractionTree

slice_and_reconfigure_forest_[source]
compressed_reconfigure(minimize=None, order_only=False, max_nodes='auto', max_time=None, local_score=None, exploration_power=0, best_score=None, progbar=False, inplace=False)[source]

Reconfigure this tree according to peak_size_compressed.

Parameters:
  • chi (int) – The maximum bond dimension to consider.

  • order_only (bool, optional) – Whether to only consider the ordering of the current tree contractions, or all possible contractions, starting with the current.

  • max_nodes (int, optional) – Set the maximum number of contraction steps to consider.

  • max_time (float, optional) – Set the maximum time to spend on the search.

  • local_score (callable, optional) –

    A function that assigns a score to a potential contraction, with a lower score giving more priority to explore that contraction earlier. It should have signature:

    local_score(step, new_score, dsize, new_size)
    

    where step is the number of steps so far, new_score is the score of the contraction so far, dsize is the change in memory by the current step, and new_size is the new memory size after contraction.

  • exploration_power (float, optional) – If not 0.0, the inverse power to which the step is raised in the default local score function. Higher values favor exploring more promising branches early on - at the cost of increased memory. Ignored if local_score is supplied.

  • best_score (float, optional) – Manually specify an upper bound for best score found so far.

  • progbar (bool, optional) – If True, display a progress bar.

  • inplace (bool, optional) – Whether to perform the reconfiguration inplace on this tree.

Return type:

ContractionTree

compressed_reconfigure_[source]
windowed_reconfigure(minimize=None, order_only=False, window_size=20, max_iterations=100, max_window_tries=1000, score_temperature=0.0, queue_temperature=1.0, scorer=None, queue_scorer=None, seed=None, inplace=False, progbar=False, **kwargs)[source]
windowed_reconfigure_[source]
flat_tree(order=None)[source]

Create a nested tuple representation of the contraction tree like:

((0, (1, 2)), ((3, 4), ((5, (6, 7)), (8, 9))))

Such that the contraction will progress like:

((0, (1, 2)), ((3, 4), ((5, (6, 7)), (8, 9))))
((0, 12), (34, ((5, 67), 89)))
(012, (34, (567, 89)))
(012, (34, 56789))
(012, 3456789)
0123456789

Where each integer represents a leaf (i.e. single element node).

get_leaves_ordered()[source]

Return the list of leaves as ordered by the contraction tree.

Return type:

tuple[frozenset[str]]

get_path(order=None)[source]

Generate a standard path from the contraction tree.

path[source]
get_numpy_path(order=None)[source]

Generate a path compatible with the optimize kwarg of numpy.einsum.

get_ssa_path(order=None)[source]

Generate a ssa path from the contraction tree.

ssa_path[source]
surface_order(node)[source]
set_surface_order_from_path(ssa_path)[source]
get_path_surface()[source]
path_surface[source]
get_ssa_path_surface()[source]
ssa_path_surface[source]
get_spans()[source]

Get all (which could mean none) potential embeddings of this contraction tree into a spanning tree of the original graph.

Return type:

tuple[dict[frozenset[int], frozenset[int]]]

compute_centralities(combine='mean')[source]

Compute a centrality for every node in this contraction tree.

get_hypergraph(accel=False)[source]

Get a hypergraph representing the uncontracted network (i.e. the leaves).

reset_contraction_indices()[source]

Reset all information regarding the explicit contraction indices ordering.

sort_contraction_indices(priority='flops', make_output_contig=True, make_contracted_contig=True, reset=True)[source]

Set explicit orders for the contraction indices of this self to optimize for one of two things: contiguity in contracted (‘k’) indices, or contiguity of left and right output (‘m’ and ‘n’) indices.

Parameters:
  • priority ({'flops', 'size', 'root', 'leaves'}, optional) – Which order to process the intermediate nodes in. Later nodes re-sort previous nodes so are more likely to keep their ordering. E.g. for ‘flops’ the mostly costly contracton will be process last and thus will be guaranteed to have its indices exactly sorted.

  • make_output_contig (bool, optional) – When processing a pairwise contraction, sort the parent contraction indices so that the order of indices is the order they appear from left to right in the two child (input) tensors.

  • make_contracted_contig (bool, optional) – When processing a pairwise contraction, sort the child (input) tensor indices so that all contracted indices appear contiguously.

  • reset (bool, optional) – Reset all indices to the default order before sorting.

print_contractions(sort=None, show_brackets=True)[source]

Print each pairwise contraction, with colorized indices (if colorama is installed), and other information.

get_contractor(order=None, prefer_einsum=False, strip_exponent=False, check_zero=False, implementation=None, autojit=False, progbar=False)[source]

Get a reusable function which performs the contraction corresponding to this tree, cached.

Parameters:
  • tree (ContractionTree) – The contraction tree.

  • order (str or callable, optional) – Supplied to ContractionTree.traverse(), the order in which to perform the pairwise contractions given by the tree.

  • prefer_einsum (bool, optional) – Prefer to use einsum for pairwise contractions, even if tensordot can perform the contraction.

  • strip_exponent (bool, optional) – If True, the function will strip the exponent from the output array and return it separately.

  • check_zero (bool, optional) – If True, when strip_exponent=True, explicitly check for zero-valued intermediates that would otherwise produce nan, instead terminating early if encountered and returning (0.0, 0.0).

  • implementation (str or tuple[callable, callable], optional) –

    What library to use to actually perform the contractions. Options are:

    • None: let cotengra choose.

    • ”autoray”: dispatch with autoray, using the tensordot and einsum implementation of the backend.

    • ”cotengra”: use the tensordot and einsum implementation of cotengra, which is based on batch matrix multiplication. This is faster for some backends like numpy, and also enables libraries which don’t yet provide tensordot and einsum to be used.

    • ”cuquantum”: use the cuquantum library to perform the whole contraction (not just individual contractions).

    • tuple[callable, callable]: manually supply the tensordot and einsum implementations to use.

  • autojit (bool, optional) – If True, use autoray.autojit() to compile the contraction function.

  • progbar (bool, optional) – Whether to show progress through the contraction by default.

Returns:

fn – The contraction function, with signature fn(*arrays).

Return type:

callable

contract_core(arrays, order=None, prefer_einsum=False, strip_exponent=False, check_zero=False, backend=None, implementation=None, autojit='auto', progbar=False)[source]

Contract arrays with this tree. The order of the axes and output is assumed to be that of tree.inputs and tree.output, but with sliced indices removed. This functon contracts the core tree and thus if indices have been sliced the arrays supplied need to be sliced as well.

Parameters:
  • arrays (sequence of array) – The arrays to contract.

  • order (str or callable, optional) – Supplied to ContractionTree.traverse().

  • prefer_einsum (bool, optional) – Prefer to use einsum for pairwise contractions, even if tensordot can perform the contraction.

  • backend (str, optional) – What library to use for einsum and transpose, will be automatically inferred from the arrays if not given.

  • autojit ("auto" or bool, optional) – Whether to use autoray.autojit to jit compile the expression. If “auto”, then let cotengra choose.

  • progbar (bool, optional) – Show progress through the contraction.

slice_key(i, strides=None)[source]

Get the combination of sliced index values for overall slice i.

Parameters:

i (int) – The overall slice index.

Returns:

key – The value each sliced index takes for slice i.

Return type:

dict[str, int]

slice_arrays(arrays, i)[source]

Take arrays and slice the relevant inputs according to tree.sliced_inds and the dynary representation of i.

contract_slice(arrays, i, **kwargs)[source]

Get slices i of arrays and then contract them.

gather_slices(slices, backend=None, progbar=False)[source]

Gather all the output contracted slices into a single full result. If none of the sliced indices appear in the output, then this is a simple sum - otherwise the slices need to be partially summed and partially stacked.

gen_output_chunks(arrays, with_key=False, progbar=False, **contract_opts)[source]

Generate each output chunk of the contraction - i.e. take care of summing internally sliced indices only first. This assumes that the sliced_inds are sorted by whether they appear in the output or not (the default order). Useful for performing some kind of reduction over the final tensor object like fn(x).sum() without constructing the entire thing.

Parameters:
  • arrays (sequence of array) – The arrays to contract.

  • with_key (bool, optional) – Whether to yield the output index configuration key along with the chunk.

  • progbar (bool, optional) – Show progress through the contraction chunks.

Yields:
  • chunk (array) – A chunk of the contracted result.

  • key (dict[str, int]) – The value each sliced output index takes for this chunk.

contract(arrays, order=None, prefer_einsum=False, strip_exponent=False, check_zero=False, backend=None, implementation=None, autojit='auto', progbar=False)[source]

Contract arrays with this tree. This function takes unsliced arrays and handles the slicing, contractions and gathering. The order of the axes and output is assumed to match that of tree.inputs and tree.output.

Parameters:
  • arrays (sequence of array) – The arrays to contract.

  • order (str or callable, optional) – Supplied to ContractionTree.traverse().

  • prefer_einsum (bool, optional) – Prefer to use einsum for pairwise contractions, even if tensordot can perform the contraction.

  • strip_exponent (bool, optional) – If True, eagerly strip the exponent (in log10) from intermediate tensors to control numerical problems from leaving the range of the datatype. This method then returns the scaled ‘mantissa’ output array and the exponent separately.

  • check_zero (bool, optional) – If True, when strip_exponent=True, explicitly check for zero-valued intermediates that would otherwise produce nan, instead terminating early if encountered and returning (0.0, 0.0).

  • backend (str, optional) – What library to use for tensordot, einsum and transpose, it will be automatically inferred from the input arrays if not given.

  • autojit (bool, optional) – Whether to use the ‘autojit’ feature of autoray to compile the contraction expression.

  • progbar (bool, optional) – Whether to show a progress bar.

Returns:

  • output (array) – The contracted output, it will be scaled if strip_exponent==True.

  • exponent (float) – The exponent of the output in base 10, returned only if strip_exponent==True.

contract_mpi(arrays, comm=None, root=None, **kwargs)[source]

Contract the slices of this tree and sum them in parallel - assuming we are already running under MPI.

Parameters:
  • arrays (sequence of array) – The input (unsliced arrays)

  • comm (None or mpi4py communicator) – Defaults to mpi4py.MPI.COMM_WORLD if not given.

  • root (None or int, optional) – If root=None, an Allreduce will be performed such that every process has the resulting tensor, else if an integer e.g. root=0, the result will be exclusively gathered to that process using Reduce, with every other process returning None.

  • kwargs – Supplied to contract_slice().

benchmark(dtype, max_time=60, min_reps=3, max_reps=100, warmup=True, **contract_opts)[source]

Benchmark the contraction of this tree.

Parameters:
  • dtype ({"float32", "float64", "complex64", "complex128"}) – The datatype to use.

  • max_time (float, optional) – The maximum time to spend benchmarking in seconds.

  • min_reps (int, optional) – The minimum number of repetitions to perform, regardless of time.

  • max_reps (int, optional) – The maximum number of repetitions to perform, regardless of time.

  • warmup (bool or int, optional) – Whether to perform a warmup run before the benchmark. If an int, the number of warmup runs to perform.

  • contract_opts – Supplied to contract_slice().

Returns:

A dictionary of benchmarking results. The keys are:

  • ”time_per_slice”float

    The average time to contract a single slice.

  • ”est_time_total”float

    The estimated total time to contract all slices.

  • ”est_gigaflops”float

    The estimated gigaflops of the contraction.

Return type:

dict

See also

contract_slice

plot_ring[source]
plot_tent[source]
plot_span[source]
plot_flat[source]
plot_circuit[source]
plot_rubberband[source]
plot_contractions[source]
plot_contractions_alt[source]
plot_hypergraph(**kwargs)[source]
describe(info='normal', join=' ')[source]

Return a string describing the contraction tree.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

cotengra.core._reconfigure_tree(tree, *args, **kwargs)[source]
cotengra.core._slice_and_reconfigure_tree(tree, *args, **kwargs)[source]
cotengra.core._get_tree_info(tree)[source]
cotengra.core._describe_tree(tree, info='normal')[source]
class cotengra.core.ContractionTreeCompressed(inputs, output, size_dict, track_childless=False, track_flops=False, track_write=False, track_size=False, objective=None)[source]

Bases: ContractionTree

A contraction tree for compressed contractions. Currently the only difference is that this defaults to the ‘surface’ traversal ordering.

classmethod from_path(inputs, output, size_dict, *, path=None, ssa_path=None, check=False, **kwargs)[source]

Create a (completed) ContractionTreeCompressed from the usual inputs plus a standard contraction path or ‘ssa_path’ - you need to supply one. This also set the default ‘surface’ traversal ordering to be the initial path.

get_default_order()[source]
get_default_objective()[source]

Get the objective function for this tree.

get_default_chi()[source]
get_default_compress_late()[source]
total_flops[source]
total_write[source]
combo_cost[source]
total_cost[source]
max_size[source]
peak_size[source]
contraction_cost[source]
contraction_width[source]
total_flops_exact[source]
total_write_exact[source]
combo_cost_exact[source]
total_cost_exact[source]
max_size_exact[source]
peak_size_exact[source]
abstract get_contractor(*_, **__)[source]

Get a reusable function which performs the contraction corresponding to this tree, cached.

Parameters:
  • tree (ContractionTree) – The contraction tree.

  • order (str or callable, optional) – Supplied to ContractionTree.traverse(), the order in which to perform the pairwise contractions given by the tree.

  • prefer_einsum (bool, optional) – Prefer to use einsum for pairwise contractions, even if tensordot can perform the contraction.

  • strip_exponent (bool, optional) – If True, the function will strip the exponent from the output array and return it separately.

  • check_zero (bool, optional) – If True, when strip_exponent=True, explicitly check for zero-valued intermediates that would otherwise produce nan, instead terminating early if encountered and returning (0.0, 0.0).

  • implementation (str or tuple[callable, callable], optional) –

    What library to use to actually perform the contractions. Options are:

    • None: let cotengra choose.

    • ”autoray”: dispatch with autoray, using the tensordot and einsum implementation of the backend.

    • ”cotengra”: use the tensordot and einsum implementation of cotengra, which is based on batch matrix multiplication. This is faster for some backends like numpy, and also enables libraries which don’t yet provide tensordot and einsum to be used.

    • ”cuquantum”: use the cuquantum library to perform the whole contraction (not just individual contractions).

    • tuple[callable, callable]: manually supply the tensordot and einsum implementations to use.

  • autojit (bool, optional) – If True, use autoray.autojit() to compile the contraction function.

  • progbar (bool, optional) – Whether to show progress through the contraction by default.

Returns:

fn – The contraction function, with signature fn(*arrays).

Return type:

callable

class cotengra.core.ContractionTreeMulti(inputs, output, size_dict, track_childless=False, track_flops=False, track_write=False, track_size=False, objective=None)[source]

Bases: ContractionTree

Binary tree representing a tensor network contraction.

Parameters:
  • inputs (sequence of str) – The list of input tensor’s indices.

  • output (str) – The output indices.

  • size_dict (dict[str, int]) – The size of each index.

  • track_childless (bool, optional) – Whether to dynamically keep track of which nodes are childless. Useful if you are ‘divisively’ building the tree.

  • track_flops (bool, optional) – Whether to dynamically keep track of the total number of flops. If False You can still compute this once the tree is complete.

  • track_write (bool, optional) – Whether to dynamically keep track of the total number of elements written. If False You can still compute this once the tree is complete.

  • track_size (bool, optional) – Whether to dynamically keep track of the largest tensor so far. If False You can still compute this once the tree is complete.

  • objective (str or Objective, optional) – An default objective function to use for further optimization and scoring, for example reconfiguring or computing the combo cost. If not supplied the default is to create a flops objective when needed.

children

Mapping of each node to two children.

Type:

dict[node, tuple[node]]

info

Information about the tree nodes. The key is the set of inputs (a set of inputs indices) the node contains. Or in other words, the subgraph of the node. The value is a dictionary to cache information about effective ‘leg’ indices, size, flops of formation etc.

Type:

dict[node, dict]

set_varmults(varmults)[source]
get_varmults()[source]
set_numconfigs(numconfigs)[source]
get_numconfigs()[source]
class cotengra.core.PartitionTreeBuilder(partition_fn)[source]

Function wrapper that takes a function that partitions graphs and uses it to build a contraction tree. partition_fn should have signature:

def partition_fn(inputs, output, size_dict,

weight_nodes, weight_edges, **kwargs):

… return membership

Where weight_nodes and weight_edges decsribe how to weight the nodes and edges of the graph respectively and membership should be a list of integers of length len(inputs) labelling which partition each input node should be put it.

build_divide(inputs, output, size_dict, random_strength=0.01, cutoff=10, parts=2, parts_decay=0.5, sub_optimize='greedy', super_optimize='auto-hq', check=False, seed=None, **partition_opts)[source]
build_agglom(inputs, output, size_dict, random_strength=0.01, groupsize=4, check=False, sub_optimize='greedy', seed=None, **partition_opts)[source]
trial_fn(inputs, output, size_dict, **partition_opts)[source]
trial_fn_agglom(inputs, output, size_dict, **partition_opts)[source]
cotengra.core.jitter(x, strength, rng)[source]
cotengra.core.jitter_dict(d, strength, seed=None)[source]
cotengra.core.separate(xs, blocks)[source]

Partition xs into n different list based on the corresponding labels in blocks.