2025 Volume 34 Issue 5
Article Contents

Xuanzhao Gao, Xiaofeng Li, Jinguo Liu. Programming guide for solving constraint satisfaction problems with tensor networks[J]. Chinese Physics B, 2025, 34(5): 050201. doi: 10.1088/1674-1056/adbee2
Citation: Xuanzhao Gao, Xiaofeng Li, Jinguo Liu. Programming guide for solving constraint satisfaction problems with tensor networks[J]. Chinese Physics B, 2025, 34(5): 050201. doi: 10.1088/1674-1056/adbee2

Programming guide for solving constraint satisfaction problems with tensor networks

  • Received Date: 30/12/2024
    Accepted Date: 01/03/2025
    Available Online: 01/04/2025
通讯作者: 陈斌, bchen63@163.com
  • 1. 

    沈阳化工大学材料科学与工程学院 沈阳 110142

  1. 本站搜索
  2. 百度学术搜索
  3. 万方数据库搜索
  4. CNKI搜索

Figures(59)  /  Tables(1)

Article Metrics

Article views(947) PDF downloads(5) Cited by(0)

Access History

Programming guide for solving constraint satisfaction problems with tensor networks

Abstract: Constraint satisfaction problems (CSPs) are a class of problems that are ubiquitous in science and engineering. They feature a collection of constraints specified over subsets of variables. A CSP can be solved either directly or by reducing it to other problems. This paper introduces the Julia ecosystem for solving and analyzing CSPs with a focus on the programming practices. We introduce some important CSPs and show how these problems are reduced to each other. We also show how to transform CSPs into tensor networks, how to optimize the tensor network contraction orders, and how to extract the solution space properties by contracting the tensor networks with generic element types. Examples are given, which include computing the entropy constant, analyzing the overlap gap property, and the reduction between CSPs.

1.   Introduction
  • A constraint satisfaction problem (CSP) is a class of problems that are ubiquitous in science and engineering. These problems include, for example, the independent set problem,[1] the cutting problem,[2] the dominating set,[1] set packing,[3] set covering,[4] vertex coloring,[5,6] K-SAT,[7,8] and the vertex cover problem.[9] These problems have a wide range of applications in scheduling, logistics, wireless networks and telecommunication, and computer vision, among others.[10,11] Finding an optimum solution for these problems is typically NP-hard in the worst case.[12]

    How to solve these problems efficiently is a longstanding challenge in computer science, and has become increasingly connected to physics. The performance of an algorithm is closely related to the problem size and the solution space properties or energy landscape.[13] For example, if a problem exhibits the overlap gap property, then any local search algorithm may fail to find the global optimum in sub-exponential time.[14] It also applies to quantum algorithms, for example, the quantum variational optimizer for the independent set problem can be polynomially faster than the classical algorithm when the solution space is uniformly connected.[15,16] So understanding the solution space properties is crucial for designing efficient classical and quantum algorithms. A CSP can also be addressed by reducing it to other CSPs so that solvers for these problems can also be used. In this case, the overhead of the reduction is critical for the performance as well. Efficient reduction algorithms are developed in recent years due to the rising trend in using physical systems to solve general CSPs through reductions to other problems, such as spin glass on Ising machines,[17,18] QUBO on quantum annealing processor[19] and independent set problems on King’s sub-graph.[16,20,21] While problem reductions are fundamental concepts in computer science, these techniques were not widely used by physicists in the past.

    To reduce the barrier for physicists to study CSPs, we introduce the Julia[22] ecosystem for reducing and analyzing CSPs. Julia is a high performance programming language designed for scientific computing. It is as easy to use as Python, but with the performance of C.[23] The main tool we will use is GenericTensorNetworks.jl, which is a tensor network based CSPs solution framework.[24,25] At the time of writing, its version is 4.0.1. Numerous other scientific computing software packages have been developed based on Julia, such as the ITensors.jl[26] for tensor network based many-body physics, the Yao.jl[27] for variational quantum circuits, JuMP.jl[28] for mathematical optimization, and DifferentialEquations.jl[29] for solving differential equations. The GenericTensorNetworks.jl enables us to extract the solution space properties by contracting the tensor networks with generic element types, where the supported solution space properties include the partition function, the solution size, the number of solutions, the solution enumeration and sampling. The framework is shown in Fig. 1. GenericTensorNetworks.jl is built on top of the tensor network contraction library OMEinsum.jl and the problem reduction library ProblemReductions.jl. The ProblemReductions.jl library provides a set of problem definitions and reduction interfaces for CSPs. Since it is not practical to implement all the problems and reductions in the library, it provides a flexible interface for users to define their own problems and reductions. The OMEinsum.jl library provides the tensor network contraction engine, with the state-of-the-art contraction order optimization technique. Its tensor network contraction supports the CUDA backend, which is powered by Julia’s dynamic and generic approach for GPU programming.[30]

    In the following discussion, we first introduce the CSP problems in Section 2, with a focus on the reduction between CSPs. Then we introduce the tensor network representation of CSPs in Section 3, and show how to optimize the tensor network contraction order in Section 4. Finally, we show how to extract the solution space properties by contracting the tensor networks with generic element types in Section 5. If you have a Julia REPL, you can follow the code examples in the following sections by copy-pasting the codes.

2.   Constraint satisfaction problem
  • Among the computationally hard problems, the constraint satisfaction problems (CSPs) are a class of problems that are closely related to physical models. ProblemReductions.jl provides an interface for defining CSPs and reductions between them as shown in Fig. 2. In this section, we introduce the definition of some famous CSPs, and show how these problems are defined and reduced to each other in ProblemReductions.jl.

  • The CSPs problems implemented in ProblemReductions.jl are listed in Fig. 2, below we will introduce these problems one by one.

  • We start by defining the graph topologies used in this work. Most CSPs introduced in this work are defined on graphs, which are not limited to simple graphs. A simple graph can be relaxed to hyper-graphs, where an edge can connect any number of vertices, or restricted to unit disk graphs, where an edge can only connect two vertices with distance less than a given threshold in a low-dimensional embedding space. To simplify the discussion, we will focus on unit disk graphs in Figs. 3(b) and 3(c), and simple graphs in Figs. 3(a) and 3(d). Their code implementation is as follows.

    Spin glass[31,32] system is a type of disordered magnetic system that exhibits glassy behavior. The Hamiltonian of the system on a simple graph G = (V, E) is given by

    where Jij∈R is the coupling strength between spins i and j, hi∈R is the external field on spin i, and σi ∈ {−1, 1} is the spin variable. The following code defines a spin glass on a Petersen graph with unit coupling strength and zero external field.

    One can get a detailed description from the docstring of the function. Just type ? in the Julia REPL followed by the function name, e.g., what’s more, we can use fieldnames function to print the fields of a problem type.

    An equivalent problem to the spin glass problem is the quadratic unconstrained binary optimization (QUBO),[31] which can be described as a quadratic form fQ(x) = xTQx, where x is a vector of binary decision variables and Q is a square matrix. The matrix Q can be interpreted as the adjacency matrix of a graph, where the diagonal elements are zero. We emphasize the constraint that elements of x are binary variables is crucial. When relaxing this constraint, the problem of finding the minimum or maximum of fQ(x) can be solved in polynomial time by finding the eigen-decomposition of Q. With this constraint, finding the minimum or maximum of fQ(x) becomes NP-hard and cannot be solved efficiently by any existing algorithm. Due to its close connection to Ising models, QUBO constitutes a central problem class for adiabatic quantum computation, where it is solved through a physical process called quantum annealing. In ProblemReductions.jl, we can use type QUBO to define the QUBO problem.

    Another related NP-hard problem is the max cut problem,[2] which is to partition the vertices into two subsets that maximize the total weight of the edges connecting the two subsets. This problem is equivalent to the spin glass problem with positive uniform coupling strength and zero external field, and the ground state of the spin glass problem is the solution to the max cut problem. An example is given below, where a max cut problem is defined on a Petersen graph, and a solution is shown in Fig. 4(a).

    Independent sets[1] are the subsets of vertices of a graph, where no two of which are adjacent, and the independent set problem is to find such sets of a given graph. The problem is closely related to the hard-core lattice gas model[33] in statistical physics. A maximum independent set (MIS) is an independent set of largest possible size for a given graph G, and the optimization problem of finding such a set is called the maximum independent set problem. Finding an MIS for a given graph is an NP-complete problem[34] and various exponential-time algorithms have been developed for solving it.[35] It has garnered significant attention in recent decades due to its natural mapping to Rydberg atom-based quantum computing.[21] The following code defines the independent set problem on a Petersen graph, and a solution is shown in Fig. 4(b).

    The second field is the weights of the vertices, which are set to UnitWeight by default, representing the unweighted version. The size of the independent set is the sum of the weights of its vertices. In the following, we will not explicitly state this for each problem in the rest of the paper for the sake of simplicity. A variant of the independent set problem is the maximal independent set (MIS) problem, where the “maximal” means that the independent set cannot be extended by adding any other vertex. Its solution space contains all the maximal independent sets, which is smaller than the solution space of the independent set problem.

    Another problem that is closely related to the independent set problem is the minimum vertex cover problem. They are treated as the same problem in many literatures. A vertex cover is a set of vertices such that every edge in the graph has at least one endpoint in this set, and the minimum vertex cover problem is to find the smallest such set. The complement of an independent set must be a vertex cover, since an edge cannot be covered by two vertices in the independent set. Conversely, the complement of a vertex cover is an independent set. Therefore, the complement of the maximum independent set is the minimum vertex cover. In the following example, we define the minimum vertex cover problem on a Petersen graph.

    Vertex coloring[5,6] refers to the problem of assigning colors to the vertices of a graph in such a way that no two adjacent vertices share the same color. The vertex coloring problem seeks to determine whether it is possible to color all vertices of a given simple graph using k colors while ensuring that adjacent vertices are not colored the same. The problem of finding the minimum number of colors required to color a given graph is one of Karp’s 21 NP-complete problems.[36] One of the major applications of graph coloring is register allocation in compilers.[37] In the following example, we define the vertex coloring problem on a Petersen graph using 3 colors, and a solution is shown in Fig. 4(c).

    Dominating set[1] is a problem to identify a dominating set that minimizes either the number of vertices or the total weight. A dominating set for a graph G is a subset D of its vertices such that every vertex in G is either included in D or is adjacent to at least one vertex in D. It is a classical NP-complete decision problem and has a wide application in fields such as wireless networking,[38] document summarization, and designing secure systems for electrical grids. Below is the code that defines the dominating set problem on a Petersen graph.

    Matching[39] is a subset of the edges of the graph such that no two edges in the set have the same vertex, and the vertex matching problem is to find the matching with maximum number of edges or maximum total weight. Finding the maximum matching for a simple graph G = (V, E) can be solved by Edmonds’ blossom algorithm in O(|V|2|E|) time,[40] hence no hard problem can be reduced to the matching problem. However, the counting version of the matching problem is in the complexity class #P-complete.[41] The following code defines the matching problem on a Petersen graph.

  • Satisfiability problem[7,8] is the first problem that was proven to be NP-complete, which is to determine whether a given boolean formula is satisfiable. The satisfiability problem is a fundamental problem in computer science and has wide applications in fields such as artificial intelligence, cryptography, and automated reasoning. There is no known algorithm that can solve the SAT problem in time faster than exponential time.[42,43] In ProblemReductions.jl, the boolean variables, i.e., the literals, are defined by the BoolVar function as follows.

    With these boolean variables, a general satisfiability problem is defined as follows, where the boolean formula is given in the conjunctive normal form (CNF).

    If the number of literals in a clause is fixed to k, using the K-satisfiability problem is preferred. In the following example, we define a 3-SAT problem.

    Circuit satisfiability (circuit SAT)[9] is a variant of the satisfiability problem, where the boolean formula is represented by a circuit. In ProblemReductions.jl, we can use macro expression @circuit to define a circuit and then use it as the input of the CircuitSAT problem.

  • Integer factorization (factoring) problem[9,44] is to find the decomposition of a positive integer into a product of integers. The corresponding decision problem is to determine whether a given integer n has a factor, other than 1, that is smaller than k, which is classified as NP-intermediate (less difficult than NP-complete but more difficult than P). Many cryptographic protocols are based on the presumed difficulty of factoring large composite integers or a related problem, for example, the RSA problem.[45] An algorithm that efficiently factors an arbitrary integer would render RSA-based public-key cryptography insecure. In ProblemReductions.jl, one can define the factoring problem by the Factoring function as follows.

    Set cover problem[4] is defined on a set of elements and a collection of subsets, and the goal is to find the minimum number of subsets that cover all the elements. It is a hypergraph generalization of the vertex cover problem, however, its decision version is in the complexity class NP-complete.[36] An example is given below, where the set of elements is {1,2,3,4,5} and the subsets are {{1,2,3},{1,3,5},{1,2},{4},{4,5}}.

    Set packing[3] is also defined on a set of elements and a collection of subsets. The goal is to find the maximum number of subsets that are pairwise disjoint, meaning that no two subsets share any common elements. It is a hypergraph generalization of the independent set problem, and its decision version is also NP-complete.[36] The following example shows how to define a set packing problem.

  • In this section, we introduce the interfaces for problem reduction in ProblemReductions.jl. If a problem A can be reduced to problem B, then we can use the solution of B to solve A, i.e., A ≤pB, meaning B is not easier than A. The reduction is not only a tool to show the hardness of a problem, but also a tool to connect different problems. For example, it allows us to solve a problem by reducing it to an Ising problem or an independent set problem on low-dimensional grid that is implementable on physical hardware, e.g., D-Wave quantum annealing processor, Ising machines[17] and Rydberg atom arrays.[16,20,21]

    In Fig. 2, we show some common reductions between constraint satisfaction problems (CSPs). Since it is not practical to construct the reduction between all the CSPs, in ProblemReductions.jl, we only implement a finite set of reductions. A problem can be reduced to another if a reduction path exists to connect them.

    As shown in Fig. 5, a workflow of problem reduction can be separated into four parts: reduction, target problem extraction, solving, and solution extraction. In the reduction phase, we call the reduceto function to reduce a source problem to a target problem. The reduction result contains not only the target problem, but also intermediate information to help convert the solution back. The target problem can be extracted by the target_problem function. To solve it, we resort to the unified solver interface findbest. Finally, we can extract the solution for source problem by the extract_solution function. In the following example, we convert an integer factorization problem to a circuit satisfiability problem with a direct reduction rule.

    Here, the findbest function is used to solve the circuit satisfiability problem. The built-in solver is BruteForce. After GenericTensorNetworks.jl is loaded, a tensor network based solver GTNSolver will also be available.

    In some other cases, a direct reduction rule is not available, then a reduction path must be provided by the user. It can be constructed by the reduction_paths function that returns all the possible reduction paths connecting two problem types. In the following example, we convert an integer factorization problem to a spin glass problem with an automatically generated reduction path.

    In this example, there exist multiple reduction paths from the factoring problem to the spin glass problem, which is Factoring → CircuitSAT → SpinGlass.[21] The reduction transforms the factoring problem into 63 vertices spin glass problems. Although the reduction is not free and requires some overhead, it is a powerful tool that enables us to fully utilize existing solvers to solve new problems.

3.   Tensor network representation of constraint satisfaction problems
  • In previous sections, we have introduced the CSPs and the reductions between them, but a general framework to solve these problems is still missing. In this section, we introduce a tensor network representation of the constraint satisfaction problems (CSPs) to facilitate their analysis and solution. We show that both the energy model and the partition function of the CSPs can be effectively represented by tensor networks, and an example tensor network representation of the independent set problem is given.

  • Let us consider a constraint satisfaction problem on a hyper-graph G = (V, E), where V is the set of vertices associated with variables and E is the set of hyper-edges associated with constraints. The energy model of the problem is defined as

    where s is an assignment of variables and h(e, s) is an energy term associated with hyper-edge e ∈ E representing the constraint on e. Invalid configurations due to the hard constraints in some problems, e.g., the independence constraint in the independent set problem, are characterized by infinite energy penalty. The partition function for the energy model at inverse temperature β is defined as

    Since the energy term h(e, s) only involves the spins on the vertices that belong to the hyper-edge e, eβh(e, s) is a tensor of rank |e| and the partition function is a tensor network, where two tensors are connected if and only if they have shared variables in their corresponding hyper-edges. In the infinite temperature limit, β → 0, the partition function is equivalent to the number of valid configurations. For certain problems, although finding one best solution is easy, counting the number of valid configurations is hard, e.g., counting the number of satisfying assignments of 2-SAT is #P-hard.[41]

  • In the following, we will show the tensor network representation of the independent set problem. Given a graph G = (V, E), the energy model of the independent set problem is

    where nv is the number of vertices in the independent set, i.e., nv = 1 if v is in the independent set, and nv = 0 otherwise, wv is the weight of vertex v. The larger the size of the independent set, the lower the energy. An example is given below. The partition function at inverse temperature β can be represented as

    It can be represented as a tensor network. For each edge (u, v) ∈ E, the pairwise interaction can be represented as a rank-2 tensor

    where 1 and 0 are the multiplicative identity and zero, respectively. For each vertex v ∈ V, a rank-one tensor W(nv) is associated with each vertex v ∈ V, which is given by

    As an example, we consider computing the partition function of a square graph with 4 vertices and 4 edges. The graph and its corresponding tensor network for the independent set problem are shown below.

    The resulting tensor network is equivalent to the following sum-product form:

    Using GenericTensorNetworks, the tensor network can be constructed automatically as follows.

    The resulting tensor network has 3 fields: problem, code, and fixedvertices. The problem field is the problem instance of type IndependentSet. The code field is the einsum notation defined by OMEinsum with optimized contraction order. Einsum notation is a compact way to represent the tensor networks topology, and the contraction order is optimized by OMEinsum to minimize the number of operations and memory usage. The OMEinsum.flatten function is used to remove the contraction order, such that we can see the underlying tensor network structure more clearly. In the flattened form, the input tensors and output tensor are separated by the arrow symbol “−>”. The output tensor is associated with an empty string, which means the output tensor is a scalar. The input tensors are separated by commas, and the indices of the input tensors are separated by the “o” symbol. In this example, there are 4 input tensors of rank 2 and 4 input tensors of rank 1. The rank 2 tensors are associated with the edge tensors B(nu, nv), and the rank 1 tensors are associated with the vertex tensors W(nv). The last field fixedvertices is a dictionary that stores the fixed vertices and their corresponding values. In this example, there are no fixed vertices, so the dictionary is empty.

4.   Choose the right tensor network contraction order optimizer
  • After representing CSPs as tensor networks, we can extract the solution space properties by contracting the tensor networks with generic element types. However, contracting a tensor network can be a challenging task, since naively looping over all indices is O(2n) in time complexity, where n is the number of indices. To reduce the complexity, we need to find a good contraction order, which is the order of contracting the indices. Different contraction orders lead to different complexities, while finding the optimal contraction order, i.e., the contraction order with minimal complexity, is NP-complete.[46] Luckily, a close-to-optimal contraction order is usually acceptable, which could be found in a reasonable time with a heuristic optimizer. In the past decade, methods have been developed to optimize the contraction orders, including both exact ones and heuristic ones. Among these methods, multiple heuristic methods can handle networks with more than 104 tensors efficiently.[47,48] In this section, we will first introduce the basic concepts and then review the methods for finding a good contraction order.

  • A contraction order can be represented as a rooted tree, where the leaves are the tensors to be contracted and the root is the final result. In actual calculation, we prefer binary contractions, i.e., contracting two tensors at a time, so that we can make use of BLAS[49] libraries to speed up the calculation by converting these two tensors as matrices. In this way, a given contraction order can be represented as a binary tree, where the leaves are the original tensors, the nodes are the intermediate tensors after contracting two tensors, and the root is the final result. For a given contraction order, the following three metrics are defined to describe its quality:

    Time complexity (tc): the total number of operations.

    Space complexity (sc): the maximum number of elements in the largest intermediate result.

    Read-write complexity (rwc): the total number of elements to be read and written from memory.

    The goal of contraction order optimization is to find a binary contraction order called the optimal contraction order, which minimizes the weighted sum of these complexity metrics. In the example shown in Subsection 3.2, the optimal contraction order is given by the following binary tree.

    The largest tensor during contraction has a rank of 2, which is the smallest among all possible contraction orders. In the following, we define the unoptimized tensor network topology manually with OMEinsum and then show how to optimize the contraction order.

    The EinCode is the default constructor for specifying the tensor network topology. It takes indices for the input tensors as the first argument and the output tensor as the second argument. The uniformsize function is used to specify the uniform dimension of each index, which returns a dictionary mapping each index to its dimension. The contraction_complexity function is used to compute the time complexity, space complexity, and read–write complexity of the contraction. The time complexity is 24 because the default contraction naively looks over all indices without creating intermediate tensors. This leads to a large time complexity of 2n for an n-index contraction. Moreover, the non-binary contraction does not make use of BLAS libraries, leading to a large overhead. In the following, we call the optimize_code function to optimize the contraction order.

    The first argument of the optimize_code function is the EinCode to be optimized, the second argument is the size dictionary, and the third argument is the optimizer. The TreeSA is a heuristic optimizer based on the local search method. It returns a SlicedEinCode, which is a contraction order with sliced indices. Slicing is a technique to reduce the space complexity by looping over a subset of indices. Here, since we did not set how many indices to slice, the first field of the SlicedEinCode is empty. Since the demonstrated graph is too small, the time complexity is not reduced. In the following subsection, we will introduce more methods for optimizing the contraction order. They can be used to replace the TreeSA() method in the above example.

  • OMEinsum.jl includes various methods to automatically find a good contraction order and serves as a backend of GenericTensorNetworks.jl. We list some methods for optimizing contraction order in Fig. 6. Two of the methods give the contraction order with the optimal space complexity, they are the exact tree-width solver and the state compression method that are implemented in TensorOperations.jl.[50] Both require a time exponential in the number of tensors to optimize the contraction order, thus they are not suitable for large tensor networks with more than 50 tensors. For larger networks such as those from a quantum circuit,[46] probabilistic inference problem[48] or the combinatorial optimization,[25,51] we usually resort to faster heuristic methods. There is a trade-off between the time for optimization and the quality of the contraction order. The better contraction order is usually obtained at the cost of more time to optimize the contraction order.

    In the following, we will introduce the methods implemented in OMEinsum.jl in detail.

  • The Greedy method is one of the simplest and fastest methods for optimizing the contraction order. The idea is to greedily select the pair of tensors with the smallest cost to contract at each step. In each step, for all possible pairs of tensors, the cost of the contraction is evaluated, which is defined as

    where Ti and Tj are the tensors to be contracted, Ti * Tj is the intermediate tensor after contracting Ti and Tj, and α is a parameter. Then the pair with the smallest cost is selected and then contracted, which forms a new tensor. This process is repeated until all tensors are contracted. This method is fast, however it is easy to be trapped in local minima. It mainly targets the space complexity, while the time complexity is also reduced due to the smaller intermediate tensors.

    A variant of the greedy method is called the hyper-greedy method,[47] where in each step one samples according to the Boltzmann distribution given by P(Ti,Tj)=e−L(Ti,Tj)/T instead of directly selecting the pair with the smallest cost, where T is the temperature. If setting T = 0, the hyper-greedy method is equivalent to the greedy method. In this case, it is possible for the process to escape from local minima. Then the process is repeated multiple times and the best result is selected.

    In OMEinsum.jl, the greedy method is implemented as GreedyMethod, with three parameters: α, temperature, and nrepeat. Their default values are set to 0.0, 0.0, and 10, respectively.

  • The local search method[52] is a heuristic method based on the idea of simulated annealing. The method starts from a random contraction order and then applies the following four possible transforms as shown in Fig. 7, which correspond to the different ways to contract three sub-networks:

    where we slightly abuse the notation “*” to denote the tensor contraction, and A, B, C are the sub-networks to be contracted.

    Due to the commutative property of the tensor contraction, such transformations do not change the result of the contraction. Even though these transformations are simple, all possible contraction orders can be reached from any initial contraction order. The local search method starts from a random contraction tree. In each step, the above rules are randomly applied to transform the tree and then the cost of the new tree is evaluated, which is defined as

    where ws and wrw are the weights of the space complexity and read–write complexity compared to the time complexity, respectively. The optimal choice of weights depends on the specific device and tensor contraction algorithm. One can freely tune the weights to achieve the best performance for their specific problem. Then the transformation is accepted with a probability given by the Metropolis criterion, which is

    where β is the inverse temperature, and ΔL is the difference of the cost of the new and old contraction trees. During the process, the temperature is gradually decreased, and the process stops when the temperature is low enough. Additionally, the TreeSA method supports the slicing technique. When the space complexity is too large, one can loop over a subset of indices, and then contract the intermediate results in the end. Such a technique can reduce the space complexity, but slicing n indices will increase the time complexity by 2n.

    In OMEinsum.jl, the local search method is implemented as TreeSA, as shown in the following example.

  • Binary partition is a heuristic method[47] that builds the contraction tree in a top-down manner. A tensor network can be represented as a weighted hypergraph, where the tensors are the vertices and the shared indices are the hyperedges. The weight of the hyperedge associated with index i is given by wi = log2size(i), where size(i) is the dimension of index i. Then by finding a balanced min cut on the hypergraph, we can partition the hypergraph into two parts, which represent two sub-networks to be contracted with each other. In each step, the indices associated with the cut edges together with the open indices are looped over during the contraction. Since the open indices are fixed, minimizing the total weight of the cut edges is equivalent to minimizing the time complexity of a single contraction step. Such a bipartition is repeated recursively until the resulting sub-networks are small enough to be optimized by other simpler methods. An example of the bipartition process is shown in Fig. 8. The tensor network is first partitioned into two sub-networks by cutting edges i and k. The resulting sub-networks are then further bipartitioned until each sub-network is small enough.

    In the past few decades, the graph community has developed many algorithms for the balanced min cut problem and provided the corresponding software packages, such as KaHyPar.[53] In OMEinsum.jl, the binary partition based methods are implemented as KaHyParBipartite and SABipartite, which solve the balanced min cut problem by KaHyPar and simulated annealing method, respectively.

  • Motivated by the results of Markov and Shi,[46] the contraction order can be obtained by solving the tree decomposition of the line graph of the tensor network. An index elimination order can be obtained from the tree decomposition, which gives a contraction order with contraction complexity upper bounded by the width of the tree decomposition.[47,52] Among all tree decompositions, the tree decomposition with minimal width is called the optimal tree decomposition, and its width is called the treewidth. The treewidth is an upper bound on time complexity of the single contraction step, thus the contraction order with a minimal time complexity can be derived from the optimal tree decomposition.

    OMEinsum.jl provides an exact treewidth based method ExactTreewidth, which implements the Bouchitté–Todinca algorithm.[54] Solving the exact treewidth for an arbitrary graph is NP-hard and takes exponential time, hence it only works for small networks. Since the tree decomposition does not guarantee the contraction tree to be binary, a greedy method is used to convert the non-binary contractions into binary ones.

5.   Tensor networks contraction for solution space analysis
  • This section introduces how to use the generic tensor network for solution space analysis. The generic tensor network method serves as a unified framework for solving constraint satisfaction problems through tensor networks, by linking the desired properties of the solution space with the algebraic operations employed in tensor network contraction. Its Julia implementation is included in GenericTensorNetworks.jl, and the main feature is included in a single function solve.

    The solve function takes two positional arguments, one is the target CSP problem, the other is the wanted property. Here, the target problem is the unweighted independent set problem defined on a 20 × 20 square lattice, and the wanted property is the partition function at infinite temperature Z(β = 0). One extra keyword argument usecuda=false is used to specify not using CUDA for the tensor network contraction. What is happening behind the solve function is shown in Fig. 1, the CSP problem is converted to an energy model and then to a tensor network. Then the contraction order is optimized. Depending on the wanted property, the tensor network is contracted with the corresponding algebra. Here, the wanted property is the partition function, which corresponds to the standard real number algebra. The full list of the properties and their associated algebra is shown in Table 1. The output is an array. Here, a 0-dimensional array represents a scalar, which corresponds to the infinite temperature partition function, or the number of all independent sets. From the output, we can see that it is an extremely large number, which is way beyond the data range of a 64-bit integer. Thus, here the output is represented as floating point numbers by default.

  • In the zero temperature limit, the logarithm of the partition function (Eq. (3)) can be rewritten as

    from which the tropical semiring algebra emerges.[25] The tropical semiring is a semiring of extended real numbers with the operations of minimum (or maximum) and addition replacing the usual operations of addition and multiplication, respectively.

    By contracting the tensor network with the tropical semiring, we can get the maximum size. The Julia programming language allows us to define a new type Tropical to represent the tropical semiring as demonstrated in the following code.

    The property associated with the tropical semiring is SizeMax, as shown in Table 1. So we can use the following code to get the maximum size of independent sets of the Petersen graph.

  • Continuing from the previous section, we introduce more properties that are associated with the counting and enumeration. The rigorous definition of the relevant algebra can be found in Ref. [51]. The SizeMax(k) property is used for obtaining the largest k sizes of independent sets of the Petersen graph with the extended tropical semiring. It is useful for obtaining the lowest lying solutions of the weighted problems.

    The output is a vector of two identical tropical numbers, which is due to the degeneracy of the largest two sizes. The CountingMax property is used for counting how many maximum-size solutions there are.

    When not specifying the number of solutions, the return type is CountingTropical and the counting is stored in the c field, otherwise the return type is TruncatedPoly and the counting is stored in the coeffs field. The CountingAll property is used for counting all solutions.

    This counting property is similar to the PartitionFunction(0.0) property, but uses integer with arbitrary precision as the return type. The GraphPolynomial property is used for counting the number of solutions at different sizes. Graph polynomial is an important concept in algebraic graph theory. Popular graph polynomials include the independence polynomial,[55] the matching polynomial,[56] and the chromatic polynomial.[57] The generic tensor network method provides the GraphPolynomial property for CSP problems with integer sizes, which returns a polynomial that stores the number of solutions at different sizes in its coefficients.

    The SingleConfigMax property is used for obtaining one solution with the largest size. The return type is CountingTropical and the solution is stored in the c field. In Julia, a type can be parameterized by another type, which is called a parameterized type. Here, CountingTropical is parameterized by ConfigSampler, which is a type that stores the solution as a binary string. The SingleConfigMax(k) property is used for obtaining one solution for each largest k size. The return type is ExtendedTropical and the solutions are stored in the orders field. The solutions are represented as a vector of CountingTropical parameterized by ConfigSampler.

    The ConfigsMax property is used for obtaining all solutions with the largest size. The return type is CountingTropical and the solutions are stored in the c field, which has type ConfigEnumerator. The ConfigsMax(k) property is used for obtaining all solutions with the largest k sizes. The return type is TruncatedPoly and the solutions are stored in the coeffs field. Similarly, the ConfigsAll property is used for obtaining all solutions. The return type is an iterable of type ConfigEnumerator.

    For larger solution spaces, the tree_storage option can be used to save memory. The return type is SumProductTree and the solutions are stored in the sum product expression tree so that the memory usage is significantly reduced. To extract the solutions from the tree, we can use the collect function. Interestingly, you can obtain a set of unbiased samples from the tree by using the generate_samples function without enumerating the solutions.

    This tree_storage option is also available for the ConfigsMax and ConfigsMin properties.

6.   Applications
  • The hard square entropy constant is a quantity arising in statistical mechanics of hard-square lattice gases[58,59] to understand phase transitions for these systems. It is defined as limL→∞F(L)1/L2, where F(L) is the number of independent sets of a given lattice dimension L × L. Since the number of independent sets of a 1-dimensional lattice of length n is the nth Fibonacci number, F(L) forms a well-known integer sequence (OEIS A006506), which is thought as a two-dimensional generalization of the Fibonacci numbers. Unlike the 1D Fibonacci numbers, F(L) has no known polynomial-time algorithm to compute. The following code computes the hard square entropy constant for square lattice graphs of size L × L.

    The generic tensor network method allows us to compute the hard square entropy constant for square lattice graphs of size L × L with L up to more than 39.

  • The solution space analysis is crucial for designing better algorithms. This section uses the independent set problem as an example to demonstrate the overlap gap property of the solution space, and how it can be different for different types of graphs. How to characterize the hardness of a problem instance is one of the most important questions in the field of constraint satisfaction problems.

    Unless the problem size is very small, enumeration of solutions at different energies is intractable. To tell if the enumeration of solutions is feasible or not, we first count the number of solutions at different energies. This task is closely related to the graph polynomials. For example, the independence polynomial of a graph G is a polynomial that counts the number of independent sets at different sizes

    where ck is the number of independent sets of size k and α(G) is the size of the largest independent set of G. If we can resolve the coefficients of the independence polynomial, we also know the number of independent sets at different sizes. In the program, we use the property name GraphPolynomial to denote the graph polynomial, including the independence polynomial.

    The GraphPolynomial property is accessible for problems with integer sizes. It has a keyword argument method, which can be :finitefield, :polynomial, :laurent, :fft or :fitting. Here, we use the default method :finitefield to compute the independence polynomial of the Petersen graph, which has arbitrary precision. However, this method is unable to handle the problems with negative sizes, such as the spin glass. In such cases, we can use the :laurent method, which is based on the Laurent polynomial and can handle the negative polynomial orders.

    We plot the number of solutions at different sizes for a 20 × 20 King’s subgraph at filling 0.8 and a 180 vertices 3-regular graph in Figs. 11(a) and 11(b). The numbers of solutions at different sizes grow exponentially. The solutions with the largest sizes are the most important, since they are highly related to the hardness of the problem. However, even for the largest solutions, the number of solutions is still too large to be enumerated. We use the tree_storage option of ConfigsMax property to save memory. The following code generates 10000 samples from the largest two solutions of a 20 × 20 King’s subgraph at filling 0.8 and gets the pair-wise Hamming distance distribution.

    Similar results can be obtained for the 180 vertices 3-regular graph. The results are shown in Figs. 11(c) and 11(d). We can see that their Hamming distance distributions are very different. A random King’s subgraph is more likely to have a small Hamming distance distribution, with a clear single peak. While the 3-regular graph has a more uniform distribution, with multiple peaks, which is an evidence of the overlap gap property.

  • In this section, we introduce an extension of ProblemReductions.jl, the UnitDiskMapping.jl package, that contains extra reductions rules which allow users to reduce the factoring problem to the computational hard problems to that on a unit disk graph.[21] The ultimate goal is to reduce a computational hard problem to the ground state finding problem of a physical system, such that computational hard problems can be solved by cooling a physical system to its ground state.[16] Reducing the reduction overhead and understanding the change of solution space properties are crucial for designing better physics based algorithms. To reduce the factoring problem to the weighted independent set problem on King’s subgraph, the best known reduction requires O(n2) vertices,[21] where n is the number of bits. To use the extension, we just use two packages together. The following code reduces the factoring problem to the weighted independent set problem on King’s subgraph and gets the overlap gap property.

    One can easily verify that 13 × 17 = 221.

    From the generated samples, we can visualize the Hamming distance distribution of the solutions with the largest 2 sizes in Fig. 12. It turns out that the Hamming distance distribution has multiple peaks, which is an evidence of the overlap gap property.

  • As a final example, we show how to use generic tensor network method to conquer the challenge problem released in the Song Shan Lake Spring School 2019. The problem statement is as follows.

    Problem 1 In the Buckyball structure (fullerene) illustrated in Fig. 13, we assign an Ising spin to each vertex, with neighboring spins interacting through an antiferromagnetic coupling of unit strength. (a) Get ln(Z)/N, where N is the number of vertices, and Z is the partition function at temperature 1.0. (b) Count the ground state degeneracy.

    This problem can be easily solved by using the GenericTensorNetworks.jl package as follows.

    The UnitDiskGraph type is a type that represents the unit disk graph, which is a graph that each vertex is a point in Euclidean space. Two vertices are connected by an edge if the distance between them is less than or equal to the given radius. By solving the PartitionFunction and CountingMin properties, we find that the logarithm of the partition function per vertex is ∼1.30737 and the ground state degeneracy is 16000, which is consistent with the expected results.

7.   Conclusion and future work
  • In this paper, we introduce the Julia ecosystem for solving constraint satisfaction problems with tensor networks, including the reduction between constraint satisfaction problems, the tensor network representation of constraint satisfaction problems, the tensor network contraction order optimizer, and the solution space analysis. The example codes are available at https://github.com/ArrogantGao/tensornetwork4csp. Source code is available in the following GitHub repositories.

    GenericTensorNetworks.jl: https://github.com/QuEraComputing/GenericTensorNetworks.jl

    OMEinsum.jl: https://github.com/under-Peter/OMEinsum.jl

    ProblemReductions.jl: https://github.com/GiggleLiu/ProblemReductions.jl

    Questions and contributions are welcome in the form of issues and pull requests. In the future, we will continue to improve the performance of the tensor network contraction, and to extend the tensor network method to more constraint satisfaction problems through problem reduction. At the same time, we have to warn the readers that the tensor network method is usually not the best choice when users only need a single solution, especially for a problem with a high-dimensional graph topology. The branching algorithm works better as an exact solver in many cases.[60,61] While for approximate solvers, local search and evolutionary algorithms[62] can be more efficient. The generic tensor network method is designed for counting the number of solutions and analyzing the solution space properties.

Figure (59)  Table (1) Reference (62)

Catalog

    /

    DownLoad:  Full-Size Img  PowerPoint
    Return
    Return