News

日本語 · English · 中文

[Contribution] Building a Quantum Computing Simulator and an Introduction to VQE with PyTorch and NetworkX

This article introduces an implementation that uses PyTorch's einsum to perform tensor calculations on quantum states and NetworkX to visualize the topology of circuits. In the second half, we implement the learning process of the Variational Quantum Eigensolver (VQE) using PyTorch's automatic differentiation and Optimizer.

1. Introduction

In the development of quantum computing algorithms, methods that treat circuits as tensors are gaining attention. This article introduces an implementation that calculates quantum states using PyTorch's einsum (Einstein summation notation) and visualizes circuit topology using NetworkX. In the second half, we implement the learning process of VQE (Variational Quantum Eigensolver), a quantum-classical hybrid algorithm based on this approach.

2. Core Technology: Why PyTorch?

  • State Representation via Tensors: Qubits are treated as multi-dimensional arrays, enabling high-speed computation on GPUs.
  • Flexibility of einsum: By using torch.einsum, complex gate operations can be described with intuitive index specifications.
  • Automatic Differentiation (Autograd): If gate angles are defined as parameters, the quantum circuit can be optimized similarly to AI training.

3. Basic Section: Entangled Circuit and Visualization with NetworkX

First, we implement a circuit that creates "Bell states (quantum entanglement)." Here, in addition to calculation, we draw the structure of the circuit using the graph theory library NetworkX.

import torch
import networkx as nx
import matplotlib.pyplot as plt

# 1. Preparation: Definition of Quantum Gates (PyTorch Tensor)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# H gate (Hadamard)
H_gate = torch.tensor([[1, 1], [1, -1]], dtype=torch.complex64, device=device) / (2**0.5)

# CX gate (Controlled-NOT): 4th-order tensor [out_target, out_control, in_target, in_control]
CX_gate = torch.zeros((2, 2, 2, 2), dtype=torch.complex64, device=device)
CX_gate[0, 0, 0, 0] = 1
CX_gate[1, 0, 1, 0] = 1
CX_gate[1, 1, 0, 1] = 1 # When control is (1), 0 -> 1
CX_gate[0, 1, 1, 1] = 1 # When control is (1), 1 -> 0

# 2. Creation of Initial State (2-qubit |00>)
state = torch.zeros((2, 2), dtype=torch.complex64, device=device)
state[0, 0] = 1.0

# 3. Execution of Quantum Calculation (torch.einsum)
# Step 1: Apply H gate to Q0 ('ki, ij -> kj' : convert i to k)
state = torch.einsum('ki, ij -> kj', H_gate, state)
# Step 2: Apply CX gate ('lmij, ij -> lm' : convert input ij to output lm)
state = torch.einsum('lmij, ij -> lm', CX_gate, state)

# 4. Sampling (Measurement)
probs = torch.abs(state)**2
probs_flat = probs.flatten()
samples = torch.multinomial(probs_flat, num_samples=1024, replacement=True)
counts = torch.bincount(samples, minlength=4)

print("--- Measurement Results (00, 01, 10, 11) ---")
print(counts)

# 5. Drawing Circuit Topology with NetworkX
def draw_circuit():
    G = nx.DiGraph()
    nodes = {
        "Q0_in": (0, 1), "Q1_in": (0, 0),
        "H": (1, 1), "CX": (2, 0.5),
        "Q0_out": (3, 1), "Q1_out": (3, 0)
    }
    G.add_nodes_from(nodes.keys())
    edges = [("Q0_in", "H"), ("H", "CX"), ("CX", "Q0_out"), ("Q1_in", "CX"), ("CX", "Q1_out")]
    G.add_edges_from(edges)
    plt.figure(figsize=(8, 4))
    nx.draw(G, pos=nodes, with_labels=True, node_color='plum', node_size=2500, font_weight='bold', arrows=True)
    plt.title("Quantum Circuit Topology via NetworkX")
    plt.show()

draw_circuit()

--- Measurement Results (00, 01, 10, 11) ---
tensor([512, 0, 512, 0])


4. Applied Section: Parameter Learning of VQE with PyTorch

Next, we implement VQE, which learns the angles of the circuit to "minimize energy" on top of this simulation platform. PyTorch's Optimizer finds the optimal parameters for the quantum circuit.

import torch.optim as optim

# 1. Definition of Differentiable RY Gate
def get_RY(theta):
    t = theta.squeeze()
    gate = torch.stack([
        torch.stack([torch.cos(t/2), -torch.sin(t/2)]),
        torch.stack([torch.sin(t/2), torch.cos(t/2)])
    ])
    return gate.to(torch.complex64)

# 2. Target Hamiltonian (Example: Z gate)
H = torch.tensor([[1.0, 0.0], [0.0, -1.0]], dtype=torch.complex64)

# 3. Parameter Learning Settings
theta = torch.tensor([0.1], requires_grad=True)
optimizer = optim.Adam([theta], lr=0.1)

print("\n--- Start VQE Learning ---")
for step in range(101):
    optimizer.zero_grad()
    
    # Start from |0> state
    state_in = torch.tensor([1.0, 0.0], dtype=torch.complex64)
    
    # Apply gate and calculate expectation value
    RY = get_RY(theta)
    state_out = RY @ state_in
    energy = torch.real(torch.vdot(state_out, H @ state_out))
    
    # Backpropagation
    energy.backward()
    optimizer.step()
    
    if step % 20 == 0:
        print(f"Step {step:3}: Energy = {energy.item():.4f}, Theta = {theta.item():.4f}")

print(f"Optimization Complete: Theta = {theta.item():.4f} (Target: 3.1416)")

--- Start VQE Learning ---
Step 0: Energy = 0.9950, Theta = 0.2000
Step 20: Energy = -0.5598, Theta = 2.2736
Step 40: Energy = -0.9378, Theta = 3.4935
Step 60: Energy = -0.9972, Theta = 3.0556
Step 80: Energy = -0.9999, Theta = 3.1590
Step 100: Energy = -1.0000, Theta = 3.1375
Optimization Complete: Theta = 3.1375 (Target: 3.1416)


5. Summary

By using PyTorch, it becomes possible to interpret quantum circuit calculations as numerical computations and utilize powerful optimization engines. Additionally, by combining it with NetworkX, it becomes possible to visually manage the wiring between qubits, which becomes increasingly complex.

This approach is highly effective for understanding the behavior of small-scale quantum circuits and developing prototypes for quantum machine learning.

This article was translated from the Japanese original. 日本語で読む

← Latest articles