Skip to content

11. Quantum Computing

This chapter introduces the GPU-based quantum circuit simulation resources provided by the computing platform, as well as how to apply for a cluster account and submit simulator jobs.

11.1 High-Performance GPU Simulator

This section mainly describes high-performance GPU simulators for quantum circuits deployed on the IHEP V100 GPU cluster, such as the Qiskit GPU simulator (qiskit-aer). The simulator supports MPI-based multi-GPU parallelism.

11.2 Cluster Account and Login

Users Without an IHEP Cluster Account

Refer to Section 4.1.1 Unified Authentication Account to register an IHEP unified authentication account, then apply for a cluster AFS account. Select QC in the Affiliated Application field and fill in the other information according to your actual situation.

Users With an Existing IHEP Cluster Account

If you already have an IHEP cluster account but do not belong to the QC user group, apply for a secondary group according to Section 4.1.3 Apply to Add a Secondary Group.

Log in to https://ink.ihep.ac.cn, then go to Dashboard → Apply for second linux group → Secondary group apply and select the QC secondary group.

After the application is approved, a user directory will be created under /hpcfs/quantum/ on the cluster.

11.3 Simulator Job Submission

Software Environment

Use module to manage software environments such as MPI compilers and quantum simulators:

module use /hpcfs/quantum/modulefiles
module av

The command above shows available software and versions. Use module load to load the corresponding software. For example, module load quantum/qiskit-2.4.1-aer-gpu loads the IBM Qiskit quantum programming framework. Through the qiskit-aer backend, it supports high-performance GPU simulation and can use MPI for multi-GPU simulation of quantum circuits that exceed the memory of a single GPU.

module load quantum/pennylane-lightning-0.45.0 loads Xanadu's PennyLane simulator, which is well suited for quantum machine learning research. It provides the high-performance C++-based CPU simulator lightning.qubit, the NVIDIA cuQuantum-based GPU simulator lightning.gpu, and the Kokkos-based cross-platform GPU simulator lightning.kokkos, with support for MPI acceleration across multiple GPUs and multiple nodes.

Slurm Job Submission

When submitting quantum simulation jobs through Slurm, use gpu for partition, qc for account, and qcnormal for qos.

Qiskit Simulator

An example Slurm job script (which can be named submit.sh) is shown below:

#!/bin/bash
#SBATCH --partition=gpu
#SBATCH --qos=qcnormal
#SBATCH --account=qc
#SBATCH --job-name=qv
#SBATCH --output=qv.%j.out
#SBATCH --error=qv.%j.err
#SBATCH --nodes=1
#SBATCH --gres=gpu:v100:1
#SBATCH --ntasks=1
#SBATCH --mem=40G

module purge
module use /hpcfs/quantum/modulefiles
module load quantum/qiskit-2.4.1-aer-gpu

export OMP_NUM_THREADS=1

ulimit -s unlimited

echo "Slurm job ID: $SLURM_JOB_ID"
echo "Slurm job partition: $SLURM_JOB_PARTITION"
echo "Slurm job account: $SLURM_JOB_ACCOUNT"
echo "Slurm job nodes: $SLURM_JOB_NODELIST"

python compare_cpu_gpu.py --qubits-min 10 --qubits-max 25

compare_cpu_gpu.py compares the performance of Qiskit's QuantumVolume quantum circuit on CPU and GPU for different numbers of qubits. The script is as follows:

"""Compare CPU vs Thrust GPU simulation time on Quantum Volume circuits."""

from __future__ import annotations

import argparse

from qiskit import transpile
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import quantum_volume
from qiskit_aer import AerSimulator

OUTPUT = "compare_cpu_gpu.png"
SEED = 12345

BACKENDS = (
    ("CPU", " dc2626", "s"),
    ("GPU", " 2563eb", "o"),
)


def make_circuit(qubits: int, depth: int) -> QuantumCircuit:
    circuit = quantum_volume(qubits, depth, seed=0)
    circuit.measure_all()
    return circuit


def run_benchmark(qubits: int, device: str, *, depth: int, shots: int) -> float:
    sim = AerSimulator(method="statevector", device=device)
    circuit = transpile(make_circuit(qubits, depth), sim)
    result = sim.run(circuit, shots=shots, seed_simulator=SEED).result()

    data = result.to_dict()["results"][0]
    if data.get("status") != "DONE":
        raise RuntimeError(f"{device} failed at {qubits} qubits: {data.get('status')}")
    return float(data["time_taken"])


def plot_results(
    qubits_list: list[int],
    timings: dict[str, list[float]],
    *,
    depth: int,
    shots: int,
) -> None:
    import matplotlib.pyplot as plt
    from matplotlib.ticker import MaxNLocator, ScalarFormatter

    plt.style.use("ggplot")
    fig, ax = plt.subplots(figsize=(9, 5.5), dpi=150)
    for device, color, marker in BACKENDS:
        ax.plot(
            qubits_list,
            timings[device],
            label=device,
            color=color,
            marker=marker,
            markersize=7,
            linewidth=2,
            markerfacecolor="white",
            markeredgewidth=1.8,
            markeredgecolor=color,
        )

    ax.set_xlabel("Number of qubits", fontsize=12)
    ax.set_ylabel("Simulation time (s)", fontsize=12)
    ax.set_title(
        f"CPU vs GPU (QV depth={depth}, shots={shots})",
        fontsize=13,
        fontweight="semibold",
        pad=12,
    )
    ax.set_xticks(qubits_list)
    ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
    ax.set_yscale("log")
    ax.legend(frameon=True, fancybox=True, shadow=False, fontsize=10)
    ax.grid(True, which="both", linestyle="--", linewidth=0.6, alpha=0.7)
    fig.tight_layout()
    fig.savefig(OUTPUT, bbox_inches="tight")
    plt.close(fig)


def main() -> None:
    parser = argparse.ArgumentParser(description="Compare CPU vs GPU on QV.")
    parser.add_argument("--qubits-min", type=int, default=20)
    parser.add_argument("--qubits-max", type=int, default=27)
    parser.add_argument("--depth", type=int, default=40)
    parser.add_argument("--shots", type=int, default=2000)
    args = parser.parse_args()

    qubits_list = list(range(args.qubits_min, args.qubits_max + 1))
    timings: dict[str, list[float]] = {device: [] for device, *_ in BACKENDS}

    for qubits in qubits_list:
        for device, *_ in BACKENDS:
            elapsed = run_benchmark(
                qubits, device, depth=args.depth, shots=args.shots
            )
            timings[device].append(elapsed)
            print(f"qubits={qubits:2d}  {device}: {elapsed:.6f} s", flush=True)

    for device, *_ in BACKENDS:
        print(f"{device}: {timings[device]}", flush=True)

    plot_results(qubits_list, timings, depth=args.depth, shots=args.shots)
    print(f"Saved plot: {OUTPUT}", flush=True)


if __name__ == "__main__":
    main()

Submit the job to a GPU compute node with sbatch submit.sh. Use squeue -u $USER to view the current user's jobs.

The result is shown below. GPU-based quantum circuit simulation is significantly faster.

CPU vs GPU performance comparison for the qiskit-aer simulator

Figure 11-1 CPU vs GPU performance comparison for the qiskit-aer simulator

The script above is located in /hpcfs/quantum/examples/qiskit for reference (Qiskit 2.4.1, qiskit-aer 0.17.2).

PennyLane Simulator

An example Slurm job script (which can be named submit.sh) is shown below:

#!/bin/bash
#SBATCH --partition=gpu
#SBATCH --qos=qcnormal
#SBATCH --account=qc
#SBATCH --job-name=qml-example
#SBATCH --output=qml.%j.out
#SBATCH --error=qml.%j.err
#SBATCH --nodes=1
#SBATCH --gres=gpu:v100:2
#SBATCH --ntasks=8
#SBATCH --mem=80G

module use /hpcfs/quantum/modulefiles
module load quantum/pennylane-lightning-0.45.0

echo "Python environment used: $(which python)"
echo "Running on node: $SLURM_JOB_NODELIST"
echo "Circuit: benchmark.py (25 qubits, 3 layers, 5 runs)"

# CPU OpenMP uses 8 cores.
OMP_NUM_THREADS=8 python benchmark.py lightning.qubit

# cuQuantumGPU acceleration: one process uses a single GPU. mpirun -np 2 use two GPUs.
python benchmark.py lightning.gpu
mpirun -np 2 python benchmark.py lightning.gpu

# Kokkos GPU acceleration: one process uses a single GPU. mpirun -np 2 use two GPUs.
python benchmark.py lightning.kokkos
mpirun -np 2 python benchmark.py lightning.kokkos

benchmark.py builds a parameterized quantum circuit and computes its Jacobian, comparing the runtime of the following setups:

  • CPU: 8-core OpenMP parallelism (OMP_NUM_THREADS=8, lightning.qubit backend)
  • GPU (cuQuantum): lightning.gpu backend, single GPU vs two GPUs (mpirun -np 2, MPI)
  • GPU (Kokkos): lightning.kokkos backend, also single GPU vs two GPUs

The script is as follows:

"""Jacobian time for lightning.qubit, lightning.gpu, and lightning.kokkos.

CPU, 8 OpenMP threads:
    OMP_NUM_THREADS=8 python benchmark.py lightning.qubit

One GPU (no MPI):
    python benchmark.py lightning.gpu
    python benchmark.py lightning.kokkos

Several GPUs:
    mpirun -np 2 python benchmark.py lightning.gpu
    mpirun -np 2 python benchmark.py lightning.kokkos
"""

import os
import sys
from timeit import default_timer as timer

import pennylane as qml

wires = 25
layers = 3
num_runs = 5

DEVICES = ("lightning.qubit", "lightning.gpu", "lightning.kokkos")


def world():
    rank = int(os.environ.get("OMPI_COMM_WORLD_RANK", "0"))
    size = int(os.environ.get("OMPI_COMM_WORLD_SIZE", "1"))
    return rank, size


def main():
    if len(sys.argv) != 2 or sys.argv[1] not in DEVICES:
        names = "|".join(DEVICES)
        print(f"usage: python benchmark.py {names}", file=sys.stderr)
        sys.exit(2)

    device_name = sys.argv[1]
    rank, size = world()
    # lightning.qubit is OpenMP only.
    if device_name == "lightning.qubit":
        dev = qml.device(device_name, wires=wires, batch_obs=True)
    else:
        dev = qml.device(device_name, wires=wires, batch_obs=True, mpi=size > 1)

    @qml.qnode(dev, diff_method="adjoint")
    def circuit(parameters):
        qml.StronglyEntanglingLayers(weights=parameters, wires=range(wires))
        return qml.math.hstack([qml.expval(qml.PauliZ(i)) for i in range(wires)])

    # Every MPI rank must differentiate the same parameters.
    qml.numpy.random.seed(0)
    shape = qml.StronglyEntanglingLayers.shape(n_layers=layers, n_wires=wires)
    weights = qml.numpy.random.random(size=shape)

    timing = []
    for _ in range(num_runs):
        start = timer()
        qml.jacobian(circuit)(weights)
        timing.append(timer() - start)

    if rank == 0:
        if device_name == "lightning.qubit":
            threads = os.environ.get("OMP_NUM_THREADS", "default")
            where = f"{threads} threads"
        else:
            where = f"{size} GPU"
        print(f"{device_name:16} {where:10} {qml.numpy.mean(timing):.3f} s")


if __name__ == "__main__":
    main()

Typical output looks like this:

Circuit: benchmark.py (25 qubits, 3 layers, 5 runs)
lightning.qubit  8 threads  240.511 s
lightning.gpu    1 GPU      10.512 s
lightning.gpu    2 GPU      33.425 s
lightning.kokkos 1 GPU      19.543 s
lightning.kokkos 2 GPU      12.690 s

Compared with the CPU (8-core OpenMP), single-GPU speedups are substantial: about 23× for lightning.gpu and about 12× for lightning.kokkos. The backends differ in their underlying implementations: lightning.gpu is built on NVIDIA cuQuantum (cuStateVec) and is heavily optimized for CUDA GPUs, so it is usually faster on a single card; lightning.kokkos is based on the portable Kokkos parallel framework, runs on a wider range of hardware, and often scales more steadily across multiple GPUs (MPI). In this example, two GPUs further speed up lightning.kokkos relative to one GPU, while lightning.gpu becomes slower—communication overhead outweighs the parallel benefit. Small circuits are not always a good fit for multi-GPU runs; you should benchmark to find the best setup for your workload.

The script above is located in /hpcfs/quantum/examples/pennylane for reference (PennyLane 0.45.0, cuStateVec 1.9.0).

FAQ

See FAQ.

🤖 AI 助手
💬 快速提问 ×

有问题?输入后跳转到对话页继续交流