{"id":16977867,"url":"https://github.com/jcmgray/cotengrust","last_synced_at":"2025-06-22T11:06:32.319Z","repository":{"id":193341416,"uuid":"685677333","full_name":"jcmgray/cotengrust","owner":"jcmgray","description":"Rust accelerated contraction ordering primitives for tensor networks and einsums","archived":false,"fork":false,"pushed_at":"2025-06-16T20:09:21.000Z","size":153,"stargazers_count":19,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-22T11:05:43.093Z","etag":null,"topics":["contraction","contraction-order","einsum","tensor","tensor-contraction","tensor-network","tensor-networks"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"agpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jcmgray.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-08-31T18:57:15.000Z","updated_at":"2025-06-16T20:09:18.000Z","dependencies_parsed_at":"2024-04-19T21:34:20.469Z","dependency_job_id":"5000477f-fc66-4654-aca3-58bc2cd206a2","html_url":"https://github.com/jcmgray/cotengrust","commit_stats":null,"previous_names":["jcmgray/cotengrust"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/jcmgray/cotengrust","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcmgray%2Fcotengrust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcmgray%2Fcotengrust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcmgray%2Fcotengrust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcmgray%2Fcotengrust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jcmgray","download_url":"https://codeload.github.com/jcmgray/cotengrust/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcmgray%2Fcotengrust/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261282324,"owners_count":23134939,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["contraction","contraction-order","einsum","tensor","tensor-contraction","tensor-network","tensor-networks"],"created_at":"2024-10-14T01:29:58.201Z","updated_at":"2025-06-22T11:06:27.298Z","avatar_url":"https://github.com/jcmgray.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# cotengrust\n\n`cotengrust` provides fast rust implementations of contraction ordering\nprimitives for tensor networks or einsum expressions. The two main functions\nare:\n\n- `optimize_optimal(inputs, output, size_dict, **kwargs)`\n- `optimize_greedy(inputs, output, size_dict, **kwargs)`\n\nThe optimal algorithm is an optimized version of the `opt_einsum` 'dp'\npath - itself an implementation of https://arxiv.org/abs/1304.6112.\n\nThere is also a variant of the greedy algorithm, which runs `ntrials` of greedy,\nrandomized paths and computes and reports the flops cost (log10) simultaneously:\n\n- `optimize_random_greedy_track_flops(inputs, output, size_dict, **kwargs)`\n\n\n## Installation\n\n`cotengrust` is available for most platforms from\n[PyPI](https://pypi.org/project/cotengrust/):\n\n```bash\npip install cotengrust\n```\n\nor if you want to develop locally (which requires [pyo3](https://github.com/PyO3/pyo3)\nand [maturin](https://github.com/PyO3/maturin)):\n\n```bash\ngit clone https://github.com/jcmgray/cotengrust.git\ncd cotengrust\nmaturin develop --release\n```\n(the release flag is very important for assessing performance!).\n\n\n## Usage\n\nIf `cotengrust` is installed, then by default `cotengra` will use it for its\ngreedy, random-greedy, and optimal subroutines, notably subtree\nreconfiguration. You can also call the routines directly:\n\n```python\nimport cotengra as ctg\nimport cotengrust as ctgr\n\n# specify an 8x8 square lattice contraction\ninputs, output, shapes, size_dict = ctg.utils.lattice_equation([8, 8])\n\n# find the optimal 'combo' contraction path\n%%time\npath = ctgr.optimize_optimal(inputs, output, size_dict, minimize='combo')\n# CPU times: user 13.7 s, sys: 83.4 ms, total: 13.7 s\n# Wall time: 13.7 s\n\n# construct a contraction tree for further introspection\ntree = ctg.ContractionTree.from_path(\n    inputs, output, size_dict, path=path\n)\ntree.plot_rubberband()\n```\n![optimal-8x8-order](https://github.com/jcmgray/cotengrust/assets/8982598/f8e18ff2-5ace-4e46-81e1-06bffaef5e45)\n\n\n## Benchmarks\n\nThe following benchmarks illustrate performance and may be a useful comparison point for other implementations.\n\n---\n\nFirst, the runtime of the optimal algorithm on random 3-regular graphs,\nwith all bond sizes set to 2, for different `mimimize` targets:\n\n\u003cimg src=\"https://github.com/user-attachments/assets/e1b906a8-e234-4558-b183-7141c41beb24\" width=\"400\"\u003e\n\nTaken over 20 instances, lines show mean and bands show standard error on mean. Note how much easier it is\nto find optimal paths for the *maximum* intermediate size or cost only (vs. *total* for all contractions).\nWhile the runtime generally scales exponentially, for some specific geometries it might reduce to\npolynomial.\n\n---\n\nFor very large graphs, the `random_greedy` optimizer is appropriate, and there is a tradeoff between how\nlong one lets it run (`ntrials`) and the best cost it achieves. Here we plot these for various\n$N=L\\times L$ square grid graphs, with all bond sizes set to 2, for different `ntrials`\n(labelled on each marker):\n\n\u003cimg src=\"https://github.com/user-attachments/assets/e319b5cf-25ea-4273-aa0f-4f3acb3beaa6\" width=\"400\"\u003e\n\nAgain, data is taken over 20 runs, with lines and bands showing mean and standard error on the mean.\nIn most cases 32-64 trials is sufficient to achieve close to convergence, but for larger or harder\ngraphs you may need more. The empirical scaling of the random-greedy algorithm is very roughly\n$\\mathcal{O}(N^{1.5})$ here.\n\n---\n\nThe depth 20 sycamore quantum circuit amplitude is a standard benchmark nowadays, it is generally\na harder graph than the 2d lattice. Still, the random-greedy approach can do quite well due to its\nsampling of both temperature and `costmod`:\n\n\u003cimg src=\"https://github.com/user-attachments/assets/17b34e11-a755-4ed7-b88b-39b9e5424cfc\" width=\"400\"\u003e\n\nAgain, each point is a `ntrials` setting, and the lines and bands show the mean and error on the mean\nrespectively, across 20 repeats. The dashed line shows the roughly best known line from other more\nadvanced methods.\n\n---\n\n\n## API\n\nThe optimize functions follow the api of the python implementations in `cotengra.pathfinders.path_basic.py`.\n\n```python\ndef optimize_optimal(\n    inputs,\n    output,\n    size_dict,\n    minimize='flops',\n    cost_cap=2,\n    search_outer=False,\n    simplify=True,\n    use_ssa=False,\n):\n    \"\"\"Find an optimal contraction ordering.\n\n    Parameters\n    ----------\n    inputs : Sequence[Sequence[str]]\n        The indices of each input tensor.\n    output : Sequence[str]\n        The indices of the output tensor.\n    size_dict : dict[str, int]\n        The size of each index.\n    minimize : str, optional\n        The cost function to minimize. The options are:\n\n        - \"flops\": minimize with respect to total operation count only\n          (also known as contraction cost)\n        - \"size\": minimize with respect to maximum intermediate size only\n          (also known as contraction width)\n        - 'max': minimize the single most expensive contraction, i.e. the\n          asymptotic (in index size) scaling of the contraction\n        - 'write' : minimize the sum of all tensor sizes, i.e. memory written\n        - 'combo' or 'combo={factor}` : minimize the sum of\n          FLOPS + factor * WRITE, with a default factor of 64.\n        - 'limit' or 'limit={factor}` : minimize the sum of\n          MAX(FLOPS, alpha * WRITE) for each individual contraction, with a\n          default factor of 64.\n\n        'combo' is generally a good default in term of practical hardware\n        performance, where both memory bandwidth and compute are limited.\n    cost_cap : float, optional\n        The maximum cost of a contraction to initially consider. This acts like\n        a sieve and is doubled at each iteration until the optimal path can\n        be found, but supplying an accurate guess can speed up the algorithm.\n    search_outer : bool, optional\n        If True, consider outer product contractions. This is much slower but\n        theoretically might be required to find the true optimal 'flops'\n        ordering. In practical settings (i.e. with minimize='combo'), outer\n        products should not be required.\n    simplify : bool, optional\n        Whether to perform simplifications before optimizing. These are:\n\n        - ignore any indices that appear in all terms\n        - combine any repeated indices within a single term\n        - reduce any non-output indices that only appear on a single term\n        - combine any scalar terms\n        - combine any tensors with matching indices (hadamard products)\n\n        Such simpifications may be required in the general case for the proper\n        functioning of the core optimization, but may be skipped if the input\n        indices are already in a simplified form.\n    use_ssa : bool, optional\n        Whether to return the contraction path in 'single static assignment'\n        (SSA) format (i.e. as if each intermediate is appended to the list of\n        inputs, without removals). This can be quicker and easier to work with\n        than the 'linear recycled' format that `numpy` and `opt_einsum` use.\n\n    Returns\n    -------\n    path : list[list[int]]\n        The contraction path, given as a sequence of pairs of node indices. It\n        may also have single term contractions if `simplify=True`.\n    \"\"\"\n    ...\n\n\ndef optimize_greedy(\n    inputs,\n    output,\n    size_dict,\n    costmod=1.0,\n    temperature=0.0,\n    simplify=True,\n    use_ssa=False,\n):\n    \"\"\"Find a contraction path using a (randomizable) greedy algorithm.\n\n    Parameters\n    ----------\n    inputs : Sequence[Sequence[str]]\n        The indices of each input tensor.\n    output : Sequence[str]\n        The indices of the output tensor.\n    size_dict : dict[str, int]\n        A dictionary mapping indices to their dimension.\n    costmod : float, optional\n        When assessing local greedy scores how much to weight the size of the\n        tensors removed compared to the size of the tensor added::\n\n            score = size_ab / costmod - (size_a + size_b) * costmod\n\n        This can be a useful hyper-parameter to tune.\n    temperature : float, optional\n        When asessing local greedy scores, how much to randomly perturb the\n        score. This is implemented as::\n\n            score -\u003e sign(score) * log(|score|) - temperature * gumbel()\n\n        which implements boltzmann sampling.\n    simplify : bool, optional\n        Whether to perform simplifications before optimizing. These are:\n\n        - ignore any indices that appear in all terms\n        - combine any repeated indices within a single term\n        - reduce any non-output indices that only appear on a single term\n        - combine any scalar terms\n        - combine any tensors with matching indices (hadamard products)\n\n        Such simpifications may be required in the general case for the proper\n        functioning of the core optimization, but may be skipped if the input\n        indices are already in a simplified form.\n    use_ssa : bool, optional\n        Whether to return the contraction path in 'single static assignment'\n        (SSA) format (i.e. as if each intermediate is appended to the list of\n        inputs, without removals). This can be quicker and easier to work with\n        than the 'linear recycled' format that `numpy` and `opt_einsum` use.\n\n    Returns\n    -------\n    path : list[list[int]]\n        The contraction path, given as a sequence of pairs of node indices. It\n        may also have single term contractions if `simplify=True`.\n    \"\"\"\n\ndef optimize_simplify(\n    inputs,\n    output,\n    size_dict,\n    use_ssa=False,\n):\n    \"\"\"Find the (partial) contracton path for simplifiactions only.\n\n    Parameters\n    ----------\n    inputs : Sequence[Sequence[str]]\n        The indices of each input tensor.\n    output : Sequence[str]\n        The indices of the output tensor.\n    size_dict : dict[str, int]\n        A dictionary mapping indices to their dimension.\n    use_ssa : bool, optional\n        Whether to return the contraction path in 'single static assignment'\n        (SSA) format (i.e. as if each intermediate is appended to the list of\n        inputs, without removals). This can be quicker and easier to work with\n        than the 'linear recycled' format that `numpy` and `opt_einsum` use.\n\n    Returns\n    -------\n    path : list[list[int]]\n        The contraction path, given as a sequence of pairs of node indices. It\n        may also have single term contractions.\n    \"\"\"\n    ...\n\ndef optimize_random_greedy_track_flops(\n    inputs,\n    output,\n    size_dict,\n    ntrials=1,\n    costmod=(0.1, 4.0),\n    temperature=(0.001, 1.0),\n    seed=None,\n    simplify=True,\n    use_ssa=False,\n):\n    \"\"\"Perform a batch of random greedy optimizations, simulteneously tracking\n    the best contraction path in terms of flops, so as to avoid constructing a\n    separate contraction tree.\n\n    Parameters\n    ----------\n    inputs : tuple[tuple[str]]\n        The indices of each input tensor.\n    output : tuple[str]\n        The indices of the output tensor.\n    size_dict : dict[str, int]\n        A dictionary mapping indices to their dimension.\n    ntrials : int, optional\n        The number of random greedy trials to perform. The default is 1.\n    costmod : (float, float), optional\n        When assessing local greedy scores how much to weight the size of the\n        tensors removed compared to the size of the tensor added::\n\n            score = size_ab / costmod - (size_a + size_b) * costmod\n\n        It is sampled uniformly from the given range.\n    temperature : (float, float), optional\n        When asessing local greedy scores, how much to randomly perturb the\n        score. This is implemented as::\n\n            score -\u003e sign(score) * log(|score|) - temperature * gumbel()\n\n        which implements boltzmann sampling. It is sampled log-uniformly from\n        the given range.\n    seed : int, optional\n        The seed for the random number generator.\n    simplify : bool, optional\n        Whether to perform simplifications before optimizing. These are:\n\n        - ignore any indices that appear in all terms\n        - combine any repeated indices within a single term\n        - reduce any non-output indices that only appear on a single term\n        - combine any scalar terms\n        - combine any tensors with matching indices (hadamard products)\n\n        Such simpifications may be required in the general case for the proper\n        functioning of the core optimization, but may be skipped if the input\n        indices are already in a simplified form.\n    use_ssa : bool, optional\n        Whether to return the contraction path in 'single static assignment'\n        (SSA) format (i.e. as if each intermediate is appended to the list of\n        inputs, without removals). This can be quicker and easier to work with\n        than the 'linear recycled' format that `numpy` and `opt_einsum` use.\n\n    Returns\n    -------\n    path : list[list[int]]\n        The best contraction path, given as a sequence of pairs of node\n        indices.\n    flops : float\n        The flops (/ contraction cost / number of multiplications), of the best\n        contraction path, given log10.\n    \"\"\"\n    ...\n\ndef ssa_to_linear(ssa_path, n=None):\n    \"\"\"Convert a SSA path to linear format.\"\"\"\n    ...\n\ndef find_subgraphs(inputs, output, size_dict,):\n    \"\"\"Find all disconnected subgraphs of a specified contraction.\"\"\"\n    ...\n```\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcmgray%2Fcotengrust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjcmgray%2Fcotengrust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcmgray%2Fcotengrust/lists"}