iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📈

Exploring Matrix Product States (9) — 100-Qubit Entangled State

に公開

Objective

I have written about Vidal's canonical form for Matrix Product States (MPS) in Thinking about Matrix Product States (6) — Vidal's Canonical Form and Thinking about Matrix Product States (8) — Vidal's Canonical Form Part 2. This time, I would like to use this to create an entangled state of 100 qubits and verify that it was successfully created.

Implementation

Import the necessary modules.

from __future__ import annotations
import numpy as np
from opt_einsum import contract

from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.quantum_info.random import random_statevector

I have already described the implementation of "Vidal's canonical form," but since there were various minor errors, I will fix them while also implementing 2-qubit gates. Rather than a deep understanding, it's more of a "it works" level of implementation, so there might still be some mistakes. For this topic, even if there are small errors, I don't think it will overturn the main point, so I won't worry too much about it.

Basically, I intended to follow the implementation in The density-matrix renormalization group in the age of matrix product states and Efficient classical simulation of slightly entangled quantum computations, but for parts where I didn't quite understand how things fit together, I decided by trial and error—plugging in various values and checking the output until it felt right.

Vidal's Canonical Form

def TT_SVD_Vidal(
    C: np.ndarray, num_qubits: int | None = None, dims: tuple[int] = None
) -> tuple[list[np.ndarray], list[np.ndarray]]:
    """TT_SVD Vidal algorithm

    Args:
        C (np.ndarray): n-dimensional input tensor
        num_qubits (int | None): number of qubits

    Returns:
        list[np.ndarray]: Γs
        list[np.ndarray]: Λs
    """

    gammas = []
    lambdas = []

    if num_qubits is None:
        num_qubits = int(np.log2(np.prod(C.shape)))
    if num_qubits < 2:
        raise ValueError(f"num_qubits ({num_qubits}) must be larger than one.")

    if dims is None:
        dims = (2,) * num_qubits
    C = C.reshape(dims)

    r = []
    for sep in range(1, num_qubits):
        row_dim = np.prod(dims[:sep])
        col_dim = np.prod(dims[sep:])
        rank = np.linalg.matrix_rank(C.reshape(row_dim, col_dim))
        r.append(rank)

    for i in range(num_qubits - 1):
        if i == 0:
            ri_1 = 1
        else:
            ri_1 = r[i - 1]
        ri = r[i]
        C = C.reshape(ri_1 * dims[i], np.prod(dims[i + 1:]))
        U, S, Vh = np.linalg.svd(C, full_matrices=False)
        U = U[:, :ri]
        S = S[:ri]
        Vh = Vh[:ri, :]
        U = U.reshape(ri_1, dims[i], ri)
        if i > 0:
            for a in range(U.shape[0]):
                U[a, :, :] /= lambdas[-1][a]
        gammas.append(U)
        lambdas.append(S)
        C = np.diag(S) @ Vh
    gammas.append(Vh)
    gammas[0] = gammas[0].reshape(dims[0], r[0])
    return gammas, lambdas


def make_expr(n_qubits: int) -> str:
    outer_indices = [chr(i) for i in range(ord("A"), ord("Z") + 1)]
    inner_indices = [chr(i) for i in range(ord("a"), ord("z") + 1)]

    expr = []
    prev_inner = ""
    for i, (outer_i, inner_i) in enumerate(zip(outer_indices, inner_indices)):
        if i + 1 < n_qubits:
            expr.extend([f"{prev_inner}{outer_i}{inner_i}", inner_i])
            prev_inner = inner_i
        else:
            expr.extend([f"{prev_inner}{outer_i}"])
            break
    return ",".join(expr) + "->" + "".join(outer_indices[:n_qubits])

The above is the fix for Thinking about Matrix Product States (8) — Vidal's Canonical Form Part 2—or rather, an implementation that works well enough for various purposes.

Next, the implementation of 1-qubit gates is as follows.

1-Qubit Gates

def apply_one_qubit_gate(
    gammas: list[np.ndarray], U: np.ndarray, qubit: int
) -> None:
    gamma = gammas[qubit]
    if qubit == 0:  # expr: ia
        gamma = np.einsum("ij,ja->ia", U, gamma)
    elif qubit + 1 >= len(gammas):  # expr: ai
        gamma = np.einsum("ij,aj->ai", U, gamma)
    else:  # expr: aib
        gamma = np.einsum("ij,ajb->aib", U, gamma)
    gammas[qubit][:] = gamma


PauliX = np.array([[0, 1], [1, 0]], dtype=float)
PauliY = np.array([[0, -1j], [1j, 0]], dtype=complex)
PauliZ = np.array([[1, 0], [0, -1]], dtype=float)
Hadamard = np.array([[1, 1], [1, -1]], dtype=float) / np.sqrt(2)


def apply_X(gammas: list[np.ndarray], qubit: int) -> None:
    apply_one_qubit_gate(gammas, PauliX, qubit)


def apply_Y(gammas: list[np.ndarray], qubit: int) -> None:
    apply_one_qubit_gate(gammas, PauliY, qubit)


def apply_Z(gammas: list[np.ndarray], qubit: int) -> None:
    apply_one_qubit_gate(gammas, PauliZ, qubit)


def apply_H(gammas: list[np.ndarray], qubit: int) -> None:
    apply_one_qubit_gate(gammas, Hadamard, qubit)

Furthermore, the implementation of 2-qubit gates is as follows.

I am pretending to perform the reshape in a plausible way, but truth be told, I don't fully understand it and am just using an implementation that "seems to work."

2-Qubit Gates

def swap_ij_of_controlled_gate(mat: np.ndarray) -> np.ndarray:
    mat2 = np.zeros_like(mat)
    mat2[0, 0] = mat2[2, 2] = 1
    mat2[1, 1] = mat[2, 2]
    mat2[1, 3] = mat[2, 3]
    mat2[3, 1] = mat[3, 2]
    mat2[3, 3] = mat[3, 3]
    return mat2


def apply_two_qubits_gate(
    gammas: list[np.ndarray], lambdas: list[np.ndarray],
    U: np.ndarray, control: int, target: int
) -> None:
    U2 = swap_ij_of_controlled_gate(U).reshape(2, 2, 2, 2)
    U = U.reshape(2, 2, 2, 2)

    i, j = control, target

    if i+1 != j and j+1 != i:
        raise ValueError(f"only adjuscent qubits are supported.")

    reverse = False
    if j < i:
        i, j = j, i
        reverse = True

    if i == 0:
        if len(gammas) == 2:
            expr = "IJAB,Aa,a,aB->IJ"
        else:
            expr = "IJAB,Aa,a,aBb->IJb"
        left_dim = gammas[i].shape[0]
    elif j + 1 < len(gammas):
        expr = "IJAB,aAb,b,bBc->aIJc"
        left_dim = gammas[i].shape[0] * gammas[i].shape[1]
    else:
        expr = "IJAB,aAb,b,bB->aIJ"
        left_dim = gammas[i].shape[0] * gammas[i].shape[1]

    if not reverse:
        C = np.einsum(expr, U, gammas[i], lambdas[i], gammas[j])
    else:
        C = np.einsum(expr, U2, gammas[i], lambdas[i], gammas[j])

    updated_gammas, updated_lambdas = TT_SVD_Vidal(
        C, num_qubits=2, dims=(left_dim, -1)
    )
    if i > 0:
        updated_gammas[0] = updated_gammas[0].reshape(-1, 2, len(updated_lambdas[0]))
    if j + 1 < len(gammas):
        updated_gammas[1] = updated_gammas[1].reshape(len(updated_lambdas[0]), 2, -1)
    else:
        updated_gammas[1] = updated_gammas[1].reshape(-1, 2)
    gammas[i] = updated_gammas[0]
    lambdas[i] = updated_lambdas[0]
    gammas[i+1] = updated_gammas[1]


CX = np.array([
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 1],
    [0, 0, 1, 0]
], dtype=float)


CY = np.array([
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 0, -1j],
    [0, 0, 1j, 0]
], dtype=complex)


CZ = np.array([
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [0, 0, 0, -1]
], dtype=float)


def apply_CX(gammas, lambdas, i, j):
    apply_two_qubits_gate(gammas, lambdas, CX, i, j)

def apply_CY(gammas, lambdas, i, j):
    apply_two_qubits_gate(gammas, lambdas, CY, i, j)

def apply_CZ(gammas, lambdas, i, j):
    apply_two_qubits_gate(gammas, lambdas, CZ, i, j)

That is the implementation, and with this, we can run the level of content we want to achieve this time.

Testing

Since I couldn't think of a way to prove the validity of the implementation, I evaluated it by creating a random state vector and checking if it matches the result when performing an MPS simulation with Qiskit.

def reverse_sv(sv: Statevector) -> dict[str, complex]:
    return {k: v for k, v in sorted([(bin(i)[2:].zfill(sv.num_qubits)[::-1], coeff)
        for i, coeff in enumerate(sv.data)], key=lambda k_v: k_v[0])}


num_qubits = 5


def experiment(gate, indices):
    sv = random_statevector(2**num_qubits, seed=1234)
    qc = QuantumCircuit(num_qubits)
    i, j = indices
    if gate == "cx":
        qc.cx(i, j)
    elif gate == "cy":
        qc.cy(i, j)
    elif gate == "cz":
        qc.cz(i, j)

    evolved_sv = sv.evolve(qc)
    answer = np.array(list(reverse_sv(evolved_sv).values()))
    
    data = np.array(list(reverse_sv(sv).values()))
    gammas, lambdas = TT_SVD_Vidal(data)
    if gate == "cx":
        apply_CX(gammas, lambdas, i, j)
    elif gate == "cy":
        apply_CY(gammas, lambdas, i, j)
    elif gate == "cz":
        apply_CZ(gammas, lambdas, i, j)
    
    lambdas_ = lambdas[:]
    lambdas_.append(None)
    operands = []
    for i, (gamma, lam) in enumerate(zip(gammas, lambdas_)):
        operands.append(gamma)
        if lam is not None:
            operands.append(lam)
    
    expr = make_expr(sv.num_qubits)
    tensor = np.einsum(expr, *operands).flatten()
    global_phase_adjust = answer[0] / tensor[0]
    result = np.allclose(tensor * global_phase_adjust, answer)
    if not result:
        print(gate, indices)
    return result


indices_pairs = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3)]

total = 0
ok = 0
for gate in ["cx", "cy", "cz"]:
    for indices in indices_pairs:
        if experiment(gate, indices):
            ok += 1
        total += 1

print(f"OK: {ok}/{total}")

OK: 24/24

Since the results match Qiskit regardless of where CX, CY, and CZ are applied to the random state vector, it seems acceptable.

I have implemented various other tests as well, but I will omit them.

100-Qubit Entangled State

This is the main part of this article. Since np.einsum seemed to complain about having too many operands, I used contract from opt_einsum instead.

I want to create an MPS corresponding to \ket{\Psi} = \ket{0}^{\otimes 100}, but if I create it naively, this state vector cannot be stored in memory even before applying SVD. Therefore, I will create a function zeros_mps to directly construct the MPS. I compared the results with those created using state vector + SVD for cases up to 20 qubits.

def zeros_state(n: int):
    state = ket_ZERO
    for _ in range(n - 1):
        state = np.kron(state, ket_ZERO)
    return state

def zeros_mps(n: int):
    gammas = [np.array([[1.], [0.]])]
    lambdas = [np.array([1.])]
    for _ in range(1, n - 1):
        gammas.append(np.array([[[1.], [0.]]]))
        lambdas.append(np.array([1.]))
    gammas.append(np.array([[1., 0.]]))
    return gammas, lambdas

for n in range(2, 20+1):
    gammas, lambdas = TT_SVD_Vidal(zeros_state(n))
    gammas2, lambdas2 = zeros_mps(n)
    for i, (gamma1, gamma2) in enumerate(zip(gammas, gammas2)):
        assert gamma1.shape == gamma2.shape, (i, gamma1.shape, gamma2.shape)
        assert np.allclose(gamma1, gamma2)
    for i, (lam1, lam2) in enumerate(zip(lambdas, lambdas2)):
        assert lam1.shape == lam2.shape, (i, lam1.shape, lam2.shape)
        assert np.allclose(lam1, lam2)

Since no issues occurred, I believe it was implemented correctly.

Experiment

Since it consumes quite a few indices, I will prepare a set of indices.

In this experiment, I decided to create \ket{\Psi} = \frac{1}{\sqrt{2}}(\ket{0}^{\otimes 100} - \ket{1}^{\otimes 100}) and calculate the wave functions \Psi_{00\cdots 0} = \frac{1}{\sqrt{2}} and \Psi_{11\cdots 1} = -\frac{1}{\sqrt{2}}.

%%time

indices = [chr(i) for i in range(ord("a"), ord("z")+1)] 
indices += [chr(i) for i in range(ord("A"), ord("Z")+1)]
indices += [chr(i) for i in range(ord("α"), ord("ω")+1)]
indices += [chr(i) for i in range(ord("Α"), ord("Ρ")+1)]
indices += [chr(i) for i in range(ord("Σ"), ord("Ω")+1)]

num_qubits = 100
gammas, lambdas = zeros_mps(num_qubits)

apply_H(gammas, 0)
for i in range(num_qubits - 1):
    apply_CX(gammas, lambdas, i, i + 1)
apply_Z(gammas, num_qubits - 1)

The wave functions to be calculated are obtained by

\begin{align*} \Psi_{00 \cdots 0} = \sum_{\alpha_0,\cdots,\alpha_{d-1},\alpha_d} \Gamma^{[1] 0}_{\alpha_1} \lambda^{[1]}_{\alpha_1} \Gamma^{[2] 0}_{\alpha_1 \alpha_2} \lambda^{[2]}_{\alpha_2} \cdots \Gamma^{[d] 0}_{\alpha_{d-1}} \end{align*}

and

\begin{align*} \Psi_{11 \cdots 1} = \sum_{\alpha_0,\cdots,\alpha_{d-1},\alpha_d} \Gamma^{[1] 1}_{\alpha_1} \lambda^{[1]}_{\alpha_1} \Gamma^{[2] 1}_{\alpha_1 \alpha_2} \lambda^{[2]}_{\alpha_2} \cdots \Gamma^{[d] 1}_{\alpha_{d-1}} \end{align*}

so I will create the operands and expr to calculate these and pass them to contract of opt_einsum.

First, prepare the operands to be used for the contraction calculation.

idx = 0
ket_ZEROs_operands = [gammas[0][idx, :]]
for lam, gamma in zip(lambdas[:-1], gammas[1:-1]):
    ket_ZEROs_operands.append(lam)
    ket_ZEROs_operands.append(gamma[:, idx, :])
ket_ZEROs_operands.append(lambdas[-1])
ket_ZEROs_operands.append(gammas[-1][:, idx])

idx = 1
ket_ONEs_operands = [gammas[0][idx, :]]
for lam, gamma in zip(lambdas[:-1], gammas[1:-1]):
    ket_ONEs_operands.append(lam)
    ket_ONEs_operands.append(gamma[:, idx, :])
ket_ONEs_operands.append(lambdas[-1])
ket_ONEs_operands.append(gammas[-1][:, idx])

Next, create the expr for the contraction calculation.

expr = [indices[0]]  # for first Gamma
for i, (a, b) in enumerate(zip(indices[:-1], indices[1:])):
    if i + 2 >= num_qubits:
        break
    expr.append(a)  # for Lambda
    expr.append(f"{a}{b}")  # for Gamma
expr.append(indices[num_qubits - 2])  # for last Lambda
expr.append(indices[num_qubits - 2])  # for last Gamma
expr = ",".join(expr) + "->" + "".join(outer_indices[:n_qubits])

Finally, execute the actual contraction calculation. At the same time, let's also check various pieces of information.

print(f"The amount of entanglement: {max([len(lam) for lam in lambdas])}")
print(expr)
wave_func_for_zeros = contract(expr, *ket_ZEROs_operands)
wave_func_for_ones = contract(expr, *ket_ONEs_operands)
print("The wave func of |00..00>:", wave_func_for_zeros)
print("The wave func of |11..11>:", wave_func_for_ones)
print(np.isclose(abs(wave_func_for_zeros)**2 + abs(wave_func_for_ones)**2, 1))

The amount of entanglement: 2
a,a,ab,b,bc,c,cd,d,de,e,ef,f,fg,g,gh,h,hi,i,ij,j,jk,k,kl,l,lm,m,mn,n,no,o,op,p,pq,q,qr,r,rs,s,st,t,tu,u,uv,v,vw,w,wx,x,xy,y,yz,z,zA,A,AB,B,BC,C,CD,D,DE,E,EF,F,FG,G,GH,H,HI,I,IJ,J,JK,K,KL,L,LM,M,MN,N,NO,O,OP,P,PQ,Q,QR,R,RS,S,ST,T,TU,U,UV,V,VW,W,WX,X,XY,Y,YZ,Z,Zα,α,αβ,β,βγ,γ,γδ,δ,δε,ε,εζ,ζ,ζη,η,ηθ,θ,θι,ι,ικ,κ,κλ,λ,λμ,μ,μν,ν,νξ,ξ,ξο,ο,οπ,π,πρ,ρ,ρς,ς,ςσ,σ,στ,τ,τυ,υ,υφ,φ,φχ,χ,χψ,ψ,ψω,ω,ωΑ,Α,ΑΒ,Β,ΒΓ,Γ,ΓΔ,Δ,ΔΕ,Ε,ΕΖ,Ζ,ΖΗ,Η,ΗΘ,Θ,ΘΙ,Ι,ΙΚ,Κ,ΚΛ,Λ,ΛΜ,Μ,MΝ,N,NΞ,Ξ,ΞΟ,Ο,ΟΠ,Π,ΠΡ,Ρ,ΡΣ,Σ,ΣT,T,TΥ,Υ,ΥΦ,Φ,ΦΧ,Χ,Χ->
The wave func of |00..00>: 0.7071067811865475
The wave func of |11..11>: -0.7071067811865475
True
CPU times: user 421 ms, sys: 844 ms, total: 1.27 s
Wall time: 67.9 ms

First, the amount of entanglement for the GHZ state is 2 regardless of the number of qubits, which is a slightly entangled state in Vidal's sense. Therefore, it can be computed efficiently using tensor network calculations.

I displayed the contents of expr just in case, and it's quite a mess. It has used up almost all the prepared characters.

The wave functions were found to be \frac{1}{\sqrt{2}} and -\frac{1}{\sqrt{2}} as expected, and since the sum of squares is 1, we can see that the other wave functions are 0. Thus, we have confirmed that \ket{\Psi} = \frac{1}{\sqrt{2}}(\ket{0}^{\otimes 100} - \ket{1}^{\otimes 100}) was correctly created.

And as evidence of the efficient computation, the output shows that it took slightly less than 70ms to calculate everything, from qubit preparation to gate application, even though it was executed on a CPU.

Summary

I have confirmed through the NumPy implementation that "simulations of 100 qubits are feasible using tensor network calculations." Of course, this only means it is "possible when it is possible." For example, attempting to verify the wave functions for all computational bases would involve 2^n contraction calculations, requiring exponential resources (in terms of time). Therefore, it practically becomes unfeasible.

Furthermore, as seen in Thinking about Matrix Product States (7) — QAOA and Entanglement Amount, in the case of circuits where the amount of entanglement grows exponentially with the number of qubits n, such as the QAOA ansatz, the number of summation calculations within the tensor network increases on an exponential order, making this also unsuitable (it is not a slightly entangled state in Vidal's sense).

There are undoubtedly various other considerations, but it feels that efficient computation via this type of MPS simulation is possible as long as the various quantities increase on the order of \operatorname{poly}(n) relative to n.

References

[S] Ulrich Schollwoeck, The density-matrix renormalization group in the age of matrix product states, arXiv:1008.3477, 2010.
[V] Guifre Vidal, Efficient classical simulation of slightly entangled quantum computations, arXiv:quant-ph/0301063, 2003.

GitHubで編集を提案

Discussion