PauliComposer: Compute Tensor Products of Pauli Matrices Efficiently

We introduce a simple algorithm that efficiently computes tensor products of Pauli matrices. This is done by tailoring the calculations to this specific case, which allows to avoid unnecessary calculations. The strength of this strategy is benchmarked against state-of-the-art techniques, showing a remarkable acceleration. As a side product, we provide an optimized method for one key calculus in quantum simulations: the Pauli basis decomposition of Hamiltonians.


I. INTRODUCTION
Pauli matrices [1] are one of the most important and well-known set of matrices within the field of quantum physics.They are particularly important both in physics and chemistry when used to describe Hamiltonians of many-body spin glasses [2][3][4][5][6][7] or for quantum simulations [8][9][10][11][12][13].The vast majority of these systems are out of analytic control so that they are usually simulated through exact diagonalization which requires their Hamiltonians to be written in its matrix form.While this task may be regarded as a trivial matter in a mathematical sense, it involves the calculation of an exponentially growing number of operations.Furthermore, description of quantum systems via Matrix Product States (MPS) [14], Density Matrix Renormalization Group (DMRG) [15] and Projected Entangled Pair States (PEPS) [16] also involve large scale Hamiltonians, as well as Lanczos method [17], whose formulation has been efficiently encoded on quantum hardware recently [18].
In this work, we present the PauliComposer (PC) algorithm which significantly expedites this calculation.It exploits the fact that any Pauli word only has one element different from zero per row and column, so a number of calculations can be avoided.Additionally, each matrix entry can be computed without performing any multiplications.Even though the exponential scaling of the Hilbert space cannot be avoided, PC can boost inner calculations where several tensor products involving Pauli matrices appear.In particular, those that appear while building Hamiltonians as weighted sums of Pauli strings or decomposing an operator in the Pauli basis.
The PC algorithm could be implemented in computational frameworks in which this sort of operations are crucial, such as the Python modules Qiskit [19], Penny-Lane [20], OpenFermion [21] and Cirq [22].It can also potentially be used in many other applications, such as the Pauli basis decomposition of the Fock space [23] and conventional computation of Ising model Hamiltonians to solve optimization problems [24][25][26][27], among others.
The rest of the article is organized as follows: in Sec.II we describe the algorithm formulation in depth, showing a pseudocode-written routine for its computation.In Sec.III, a set of tests is performed to show that a remarkable speed-up can be achieved when compared to state-of-the-art techniques.In Sec.IV, we show how this PC algorithm can be used to solve relevant problems.Finally, the conclusions drawn from the presented results are given in Sec.V. We provide proofs for several statements and details of the algorithm in the appendices.

II. ALGORITHM FORMULATION
In this section we discuss the PC algorithm formulation in detail.Pauli matrices are hermitian, involutory and unitary matrices that together with the identity form the set σ {0,1,2,3} = {I, X, Y, Z}.Given an input string x = x n−1 . . .x 0 ∈ {0, 1, 2, 3} n , the PC algorithm constructs Let us denote its matrix elements as P j,k (x) with j, k = 0, . . ., 2 n − 1.It is important to remark that for each row j, there will be a single column k(j) such that P j,k(j) ̸ = 0 (see App. A).The solution amounts to a map from the initial Pauli string to the positions and values of the 2 n nonzero elements.This calculation will be done sequentially, hence the complexity of the algorithm will be bounded from below by this number.
As a first step, it is worth noting that Pauli string matrices are either real (all elements are ±1) or purely imaginary (all are ±i).This depends on n Y , the number of Y operators in P (x).We can redefine Ỹ := iY , so that σ{0,1,2,3} = {I, X, Ỹ , Z} and P (x) := σxn−1 ⊗ • • • ⊗ σx0 .As a result, every entry in P (x) will be ±1.This implies that there is no need to compute any multiplication: the problem reduces to locating the nonzero entries in P (x) and tracking sign changes.The original P (x) can be recovered as P (x) = (−i) n Y mod 4 P (x).
We will now present an iterative procedure to compute P by finding for each row j the nonzero column number k(j) and its corresponding value Pj,k(j) .For the first row, j = 0, the nonzero element P0,k(0) , can be found at where [ • ] 10 is the decimal representation of a bit string and y(x i ) tracks the diagonality of σ xi , where y(x i ) is equal to 0 if x i = {0, 3} (thus σ xi ∈ {I, Z}) and 1 otherwise (thus σ xi ∈ {X, Y }).The value of this entry is The following entries can be computed iteratively.At the end of stage l, with l = 0, • • • , n − 1, all nonzero elements in the first 2 l+1 rows of P j,k(j) will have been computed using the information given by the substring x l . . .x 0 .At the next step, l + 1, the following 2 l rows are filled using the ones that had already been computed, where the row-column relation k(j) is given by The second term of the RHS of this relation takes into account the way that the blocks of zeros returned at stage l affect the new relative location of the nonzero blocks within the new 2 l+1 × 2 l+1 subcomposition.Its corresponding values are obtained from the previous ones, up to a possible change of sign given by with ϵ l equal to 1 if x l ∈ {0, 1} and −1 otherwise.This ϵ l is nothing but a parameter that takes into account if σ x l introduces a sign flip.In Alg. 1 a pseudocode that summarizes the presented algorithm using (2)-( 5), is shown.
For the particular case of diagonal Pauli strings (only I and Z matrices), there is no need to compute the rowcolumn relation k(j), just the sign assignment is enough.Even if this is also the case for anti-diagonal matrices, we focus on the diagonal case due to its relevance in combinatorial problems [24][25][26][27].See Alg. 2 for the pseudocode of this case (PDC stands for PauliDiagonalComposer ).
The PC algorithm is able to circumvent the calculation of a significant amount of operations.When generic Kronecker product routines (see App. B) are used for the same task, the amount of multiplications needed for computing a Pauli string is O[n2 2n ] and O[n2 n ] for dense and sparse matrices, respectively.In contrast, the PC algorithm, considering the worst-case scenarios, needs In all cases our algorithm can significantly outperform those that are not specifically designed for Pauli matrices.
On top of that, this method is also advantageous for computing weighted Pauli strings.Following (3), W := ωP , with arbitrary ω, can be computed by defining // rows 4 k, m ← empty 2 n -array // columns/entries 5 k(0) ← y(xn−1) . . .y(x0) in base 10 4 which avoids having to do any extra multiplication.This change is reflected in Alg. 1 by changing line 6 to m(0) ← ω(−i) n Y mod 4 and line 4 to m(0) ← ω in Alg. 2. This is specially important as it can be used to compute Hamiltonians written as a weighted sum of Pauli strings, where H = x ω x P (x).

III. BENCHMARKING
In this section we analyse the improvement that the PC strategy introduces against other known algorithms labelled as Naive (regular Kronecker product), Algorithm 993 (Alg993) [28], Mixed and Tree [29,30].Further details can be found in App.B. We benchmark these algorithms using MATLAB [31] as it is proficient at operating with matrices (it incorporates optimized routines of the well-known BLAS and LAPACK libraries [32,33]).The PC avoids matrix operations and thus it would not be ideal to implement it using MATLAB.Instead, we use Python [34] since many quantum computing libraries are written in this language [19][20][21][22].See Tab.I for a full description of the computational resources used.
Concerning memory needs, with this algorithm only 2 n nonzero elements out of 2 2n are stored.This is exactly the same as using sparse matrices, thus, no major improvement is to be expected.As for the computational time, we compare how different algorithms behave as the length n of the Pauli string increases.In Fig. 1   times for general and diagonal Pauli strings are shown.

execution
For the PC methods, we use the PC routine (Alg. 1) for the general case and the PDC routine (Alg.2) for the diagonal one.In accordance to our theoretical analysis, the PC algorithm proves to be the best performing routine.On a more technical note, when using the PC routine, matrices with complex values (n Y odd) take twice as much time as real valued ones (n Y even).Consequently, we compute their execution times separately and then average them.Moreover, it is convenient to choose when to use PC or PDC as the latter can be up to 10 times faster.

IV. REAL USE CASES OF THE PAULICOMPOSER ALGORITHM
The PC algorithm can be used to perform useful calculations in physics.In this section, the Pauli basis decomposition of a Hamiltonian and the construction of a Hamiltonian as a sum of weighted Pauli strings are discussed in detail.Another worth mentioning scenario is the digital implementation of the complex exponential of a Pauli string, i.e. e −iθP (x) = cos(θ)I − i sin(θ)P (x).
Pauli basis decomposition of a Hamiltonian.-Thedecomposition of a Hamiltonian written as a 2 n × 2 n matrix into the Pauli basis is a common problem in quantum computing.Given a general Hamiltonian H, this decomposition can be written as H = x ω x P (x) with x = x n−1 . . .x 0 and P (x) as in (1).The coefficients ω x are obtained from the orthogonal projection as Following the discussion in Sec.II, the double sum collapses to a single one in (6) since there is only one nonzero element per row and column.Each of these weights can be computed independently, which allows for a parallel implementation.Additionally, in some special cases, it can be known in advance if some ω x will vanish: • If H is symmetric, strings with an odd number of Y matrices can be avoided (2 n−1 (2 n + 1) terms).
• If H is diagonal, only strings composed by I and Z will contribute (2 n terms).
The operations made by PauliDecomposer (PD) are This PD algorithm checks if the input matrix satisfies one of the aforementioned cases and computes the coefficients using the PC routine and ( 6), discarding all vanishing Pauli strings.This workflow considerably enhances our results, especially for diagonal matrices.In Tab.II and Fig. 2, we tested the most extended methods for decomposing matrices into weighted sums of Pauli strings against PD, using Python [34] to compare their performance.In particular, we used the SparsePauliOp class from Qiskit [19] and the decompose hamiltonian function from PennyLane [20] (only works with hermitian Hamiltonians).To the best of authors' knowledge, both routines are based on Naive approach without inspecting the input matrix nature before proceeding.
Four types of random 2 n × 2 n matrices were generated, namely non-hermitian H NH , hermitian H H , symmetric H S and diagonal H D matrices.The PD vastly outperforms Qiskit and PennyLane routines, specially for the symmetric and diagonal cases.
Building of a Hamiltonian as a sum of weighted Pauli strings.-ManyHamiltonians are written in terms of weighted Pauli strings.Our method can compute weighted Pauli strings directly without extra computations.In Fig. 3 we show a performance comparison of the presented methods for computing Hamiltonians written as sums of weighted Pauli strings.The Hamiltonian used is similar to the one proposed in [27], being the corresponding weights ⃗ α and ⃗ β arbitrary and σ i 3 as defined in (B2).This Hamiltonian is computed using Alg.3, which uses the PDC routine (see Alg. 2) with  two inputs: the string x ∈ {0, 3} n to compute and the weights to consider.In the PDC case, we use two strategies: compute each weighted term of (7) directly and compute each Pauli string and then multiply it by its corresponding weight (solid and dashed lines in Fig. 3, respectively).This is done by changing lines 6 to H ← H + α i PDC(str 1 ) and 10 to H ← H + β ij PDC(str 2 ) in Alg. 3 for the second one.There is no significant difference between both methods.

V. CONCLUSIONS
The fast and reliable computation of tensor products of Pauli matrices is crucial in the field of quantum mechanics and, in particular, of quantum computing.In this article we propose a novel algorithm with proven  This is achieved by taking advantage of the properties of Pauli matrices and the tensor product definition, which implies that one can avoid trivial operations such as multiplying constants by one and waste time computing elements with value zero that could be known in advance.
Concerning memory resources, it is convenient to store the obtained results as sparse matrices since only 2 n out of 2 2n entries will not be zero for a Pauli string of length n, i.e. the density of the resultant matrix will be 2 −n (see App. A).
Our benchmark tests suggest that the PauliComposer algorithm and its variants can achieve a remarkable acceleration when compared to the most well-known methods for the same purpose both for single Pauli strings and real use cases.In particular, the most considerable outperformance can be seen in Tab.II for the symmetric and diagonal matrix decomposition over the Pauli basis.
Finally, its simple implementation (Alg.1-2) can potentially allow to integrate the PC routines into quantum simulation packages to enhance inner calculations.
to simplify the calculation into a simple product of block diagonal matrices.Based on this procedure, Alg993 is presented in [28].It can be shown that this method performs over O[n2 n ] operations.Besides that, as Fig. 1 suggests, the fact that it requires to transpose and reshape several matrices has a non-negligible effect that fatally increases its computation time.Finally, the Tree routine starts storing pairs of tensor products as if n even and proceeds with the resultant matrices following the same logic, which allows to compute (1) by iteratively grouping its terms by pairs.For better results, this method can be parallelized.

Figure 1 .
Figure 1.(Color online) Execution times for computing general (solid line) and diagonal (dashed) n-Pauli strings using different methods.

Figure 2 .
Figure 2. (Color online) Execution times for decomposing 2 n × 2 n (a) non-hermitian HNH, (b) hermitian HH, (c) symmetric HS and (d) diagonal HD matrices with different methods.For PC and PDC, solid (dotted) line depicts sequential (parallelized) decomposition.See Tab.II.As expected, notice that the larger n, the higher impact of parallelization.

Figure 3 .
Figure 3. (Color online) Execution times for computing (7) using Alg. 3 (solid line) and computing previously the Pauli string and multiply it by its corresponding weight (dashed).

Figure 4 .
Figure 4. (Color online) Scheme for computing the number of zeros of an arbitrary composition of n Pauli matrices.

Table I .
Computer specifications.

Table II .
Execution times (in seconds) for decomposing an arbitrary 2 n × 2 n matrix.Here, PC and PDC calculations were made computing weights sequentially and in parallel.