Korean
언어
English
Bengali
French
German
Japanese
Korean
Portuguese
Spanish
Tamil

참고

이 페이지는 tutorials/algorithms/03_vqe_simulation_with_noise.ipynb 에서 생성되었다.

Qiskit Aer Primitives를 이용한 VQE

이 노트북은 Qiskit Aer Primitives 를 활용하여 로컬에서 노이즈가 없는 시뮬레이션과 노이즈가 있는 시뮬레이션을 모두 실행하는 방법을 보여준다. Qiskit Aer를 사용하면 사용자 정의 노이즈 모델을 정의할 수 있을 뿐만 아니라 실제 양자 장치의 특성을 기반으로 노이즈 모델을 쉽게 만들 수 있다. 이 노트북은 로컬 노이즈 시뮬레이터로 알고리즘을 실행하는 일반적인 워크플로우를 설명하기 위해 후자의 예를 보여준다.

Qiskit Aer 노이즈 모델에 대한 자세한 내용은 온라인 Qiskit Aer 문서, 에서 찾을 수 있으며 노이즈 모델을 생성하는 법 과 관련한 튜토리얼도 있으니 참고하도록 한다.

선택된 알고리듬은 또 다시 VQE이며, 여기서 작업은 해밀토니안의 최소(바닥 상태) 에너지를 찾는 것으로 구성된다. 이전 튜토리얼에 표시된 것처럼 VQE는 큐비트 연산자를 입력으로 받아들인다. 여기서는 SparsePauliOp 클래스를 사용하여 원래 Qiskit Nature가 H2 분자에 대해 계산했던 파울리 연산자 세트를 사용한다.

[1]:
from qiskit.quantum_info import SparsePauliOp

H2_op = SparsePauliOp.from_list(
    [
        ("II", -1.052373245772859),
        ("IZ", 0.39793742484318045),
        ("ZI", -0.39793742484318045),
        ("ZZ", -0.01128010425623538),
        ("XX", 0.18093119978423156),
    ]
)

print(f"Number of qubits: {H2_op.num_qubits}")
Number of qubits: 2

위의 문제점이 여전히 쉽게 고전적으로 추적 가능하기 때문에 NumPyMinimumEigensolver 를 사용하여 참조 값을 계산할 수 있으므로 나중에 결과를 비교할 수 있다.

[2]:
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp

numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
Reference value: -1.85728

다음 예제에서는 모두 다음과 같이 정의된 동일한 ansatz 및 옵티마이저를 사용한다:

[3]:
# define ansatz and optimizer
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SPSA

iterations = 125
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
spsa = SPSA(maxiter=iterations)

노이즈를 포함하지 않은 성능

먼저 노이즈를 추가하지 않은 기본 Aer 시뮬레이터에서 VQE 를 실행하여 재현 가능한 결과를 얻기 위해 고정 시드를 사용하여 실행 및 트랜스파일 한다. 이 결과는 정확한 계산의 기준값에 상대적으로 가까워야 한다.

[4]:
# define callback
# note: Re-run this cell to restart lists before training
counts = []
values = []


def store_intermediate_result(eval_count, parameters, mean, std):
    counts.append(eval_count)
    values.append(mean)
[5]:
# define Aer Estimator for noiseless statevector simulation
from qiskit.utils import algorithm_globals
from qiskit_aer.primitives import Estimator as AerEstimator

seed = 170
algorithm_globals.random_seed = seed

noiseless_estimator = AerEstimator(
    run_options={"seed": seed, "shots": 1024},
    transpile_options={"seed_transpiler": seed},
)
[6]:
# instantiate and run VQE
from qiskit.algorithms.minimum_eigensolvers import VQE

vqe = VQE(
    noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)

print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(
    f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}"
)
VQE on Aer qasm simulator (no noise): -1.84322
Delta from reference energy value is 0.01406

수렴 중에 위의 에너지 값을 포착하여 아래 그래프에서 무엇이 진행되었는지 추적할 수 있다.

[7]:
import pylab

pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with no noise")
[7]:
Text(0.5, 1.0, 'Convergence with no noise')
../../_images/tutorials_algorithms_03_vqe_simulation_with_noise_12_1.png

노이즈를 포함한 성능

이제 시뮬레이션에 노이즈를 추가해 보겠다. 특히 (가짜) 장치에서 노이즈 모델을 추출한다. 서론에서 설명한 바와 같이, 처음부터 사용자 지정 노이즈 모델을 만드는 것도 가능하지만, 이 작업은 이 노트북에서 다루지 않는다.

먼저 실제 기기 백엔드를 확보해야하고 configurationproperties 을 사용하여 기기와 일치하도록 결합 맵(coupling map) 과 노이즈 모델을 설정할 수 있다. 참고: 이 결합 맵을 선택하는 경우 변분 형태의 얽힌 맵으로 사용할 수도 있다.

[8]:
from qiskit_aer.noise import NoiseModel
from qiskit.providers.fake_provider import FakeVigo

# fake providers contain data from real IBM Quantum devices stored in Qiskit Terra,
# and are useful for extracting realistic noise models.
device = FakeVigo()

coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)

print(noise_model)
NoiseModel:
  Basis gates: ['cx', 'id', 'rz', 'sx', 'x']
  Instructions with noise: ['id', 'measure', 'sx', 'x', 'cx']
  Qubits with noise: [0, 1, 2, 3, 4]
  Specific qubit errors: [('id', (0,)), ('id', (1,)), ('id', (2,)), ('id', (3,)), ('id', (4,)), ('sx', (0,)), ('sx', (1,)), ('sx', (2,)), ('sx', (3,)), ('sx', (4,)), ('x', (0,)), ('x', (1,)), ('x', (2,)), ('x', (3,)), ('x', (4,)), ('cx', (3, 4)), ('cx', (4, 3)), ('cx', (3, 1)), ('cx', (1, 3)), ('cx', (1, 2)), ('cx', (2, 1)), ('cx', (0, 1)), ('cx', (1, 0)), ('measure', (0,)), ('measure', (1,)), ('measure', (2,)), ('measure', (3,)), ('measure', (4,))]

노이즈 모델이 정의되면 Aer Estimator 를 사용하여 VQE 를 실행할 수 있다. 여기서 backend_options 딕셔너리를 사용하여 노이즈 모델을 기본 시뮬레이터로 전달할 수 있다. 이 시뮬레이션은 노이즈가 없는 시뮬레이션보다 시간이 오래 걸린다.

[9]:
noisy_estimator = AerEstimator(
    backend_options={
        "method": "density_matrix",
        "coupling_map": coupling_map,
        "noise_model": noise_model,
    },
    run_options={"seed": seed, "shots": 1024},
    transpile_options={"seed_transpiler": seed},
)

이제 VQE 클래스의 새 인스턴스를 정의하는 대신 이전 VQE 인스턴스에 새 estimator를 할당할 수 있다. 콜백 메서드가 다시 사용되므로 나중에 수렴 그래프를 표시하려면 countsvalues 변수도 다시 시작해야 한다.

[10]:
# re-start callback variables
counts = []
values = []
[11]:
vqe.estimator = noisy_estimator

result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)

print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(
    f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}"
)
VQE on Aer qasm simulator (with noise): -1.74645
Delta from reference energy value is 0.11083
[12]:
if counts or values:
    pylab.rcParams["figure.figsize"] = (12, 4)
    pylab.plot(counts, values)
    pylab.xlabel("Eval count")
    pylab.ylabel("Energy")
    pylab.title("Convergence with noise")
../../_images/tutorials_algorithms_03_vqe_simulation_with_noise_20_0.png

요약

이 튜토리얼에서는 H2 분자 바닥 상태에 대한 세 가지 계산을 비교했다. 먼저 고전적인 최소 교윳값 해석기를 사용하여 기준 값을 생성한다. 그런 다음, 1024개 샷의 Qiskit Air Estimator 를 사용하여 VQE 를 실행한다. 마지막으로, 백엔드에서 노이즈 모델을 추출하여 노이즈 시뮬레이션을 위한 새로운 Estimator 를 정의하는 데 사용한다. 결과는 다음과 같다:

[13]:
print(f"Reference value: {ref_value:.5f}")
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
Reference value: -1.85728
VQE on Aer qasm simulator (no noise): -1.84322
VQE on Aer qasm simulator (with noise): -1.74645

노이즈 없는 시뮬레이션의 결과가 정확한 기준값에 가깝지만 여전히 약간의 차이가 있다는 것을 알 수 있다. 이는 샷 수를 1024개로 제한함으로써 발생하는 샘플링 노이즈 때문이다. 샷 수가 많을수록 이 샘플링 오류가 줄어들고 이 두 값 사이의 간격이 좁아진다.

실제 장치 (또는 시뮬레이션된 노이즈 모델)에 의해 도입된 노이즈의 경우, 다양한 오류 완화 기술을 통해 해결할 수 있다. Qiskit Runtime Primitivesresilience_level 옵션을 통해 오류 완화를 활성화했다. 이 옵션은 현재 Runtime Primitives를 통해 액세스하는 원격 시뮬레이터 및 실제 백엔드에 사용할 수 있다. 자세한 내용은 이 튜토리얼 을 참조하라.

[14]:
import qiskit.tools.jupyter

%qiskit_version_table
%qiskit_copyright

Version Information

Qiskit SoftwareVersion
qiskit-terra0.22.2
qiskit-aer0.11.1
qiskit-ignis0.7.1
qiskit-ibmq-provider0.19.2
qiskit0.39.2
System information
Python version3.10.2
Python compilerClang 13.0.0 (clang-1300.0.29.30)
Python buildv3.10.2:a58ebcc701, Jan 13 2022 14:50:16
OSDarwin
CPUs8
Memory (Gb)64.0
Fri Nov 18 01:03:00 2022 CET

This code is a part of Qiskit

© Copyright IBM 2017, 2022.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.

Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.