Skip to main content
IBM Quantum Platform

견적기의 입력 및 출력

  • 이 페이지의 코드는 다음 요구 사항을 바탕으로 개발되었습니다. 이 버전 이상을 사용하시기를 권장합니다.

    qiskit[all]~=2.5.2
    qiskit-ibm-runtime~=0.47.0
    

이 페이지에서는 IBM Quantum® 컴퓨팅 리소스에서 워크로드를 실행하는 ‘ IBM Quantum ’ 에스티메이터 프리미티브의 입력 및 출력에 대한 개요를 제공합니다. Estimator를 사용하면 ‘Primitive Unified Bloc( PUB ) ’이라는 데이터 구조를 활용하여 벡터화된 워크로드를 효율적으로 정의할 수 있습니다. 이들은 Estimator 프리미티브의 run() 메서드에 입력으로 사용되며, 이 메서드는 정의된 워크로드를 작업으로 실행합니다. 그런 다음, 작업이 완료되면 결과는 사용된 PUB와 프리미티브에서 지정된 런타임 옵션 모두에 따라 달라지는 형식으로 반환됩니다.


입력

각 PUB 파일은 다음과 같은 형식을 따릅니다:

(<single circuit>, <one or more observables>, <optional one or more parameter values>, <optional precision>),

선택적 매개변수는 리스트이거나 parameter values 단일 매개변수일 수 있습니다. ‘기본 입력 및 출력 ’ 항목에 설명된 대로, 관측 가능 객체(observables)의 요소와 매개변수 값은 NumPy 의 브로드캐스팅 규칙에 따라 결합되며, 브로드캐스팅된 형상의 각 요소에 대해 하나의 기대값 추정치가 반환됩니다.

입력값에 측정값이 포함되어 있으면 무시됩니다.

Estimator 기본 요소의 경우, PUB 에는 최대 네 개의 값을 포함할 수 있습니다:

  • 하나 이상의 Parameter 객체를 포함할 수 있는 단일 QuantumCircuit객체
  • 추정할 기대값을 지정하는 하나 이상의 관측값 목록으로, 배열 형태로 배열된 것(예를 들어, 단일 관측값은 0차원 배열로, 관측값 목록은 1차원 배열로 표현되는 등). 데이터는, SparsePauliOp, PauliList, 또는 Pauli 등의 형식 ObservablesArrayLikestr하나를 가질 수 있습니다.
    통근 관련 관측 변수
    • 이 방법을 사용하면 동일한 PUB 에 속한 이동 관측값들이 한데 묶입니다.
    • 서로 다른 PUB에 있는 통근 관측값은, 비록 동일한 회로를 공유하더라도, 동일한 측정값을 사용하여 추정되지 않습니다. 각 PUB 는 서로 다른 측정 기준을 나타내므로, 각 PUB 에 대해 별도의 측정이 필요합니다.
    • 통근 관측값들이 동일한 측정값을 사용하여 추정되도록 하려면, 이를 동일한 PUB 내에 그룹화하십시오.
  • 회로를 바인딩할 매개변수 값들의 모음. 이는 단일 배열형 객체로 지정할 수 있으며, 이 객체의 마지막 인덱스는 회로 Parameter 객체 수를 초과하거나, 회로에 객체가 Parameter 없는 경우 생략되거나(또는 동일하게 설정됨 None) 합니다.
  • (선택 사항) 추정할 기대값의 목표 정밀도

다음 코드는 프라이머리 Estimator (primitive)에 대한 벡터화된 입력 예시를 보여주고, 이를 IBM® 백엔드에서 단일 RuntimeJobV2 객체로 실행합니다.

from qiskit.circuit import (
    Parameter,
    QuantumCircuit,
)
from qiskit.transpiler import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp

from qiskit_ibm_runtime import (
    QiskitRuntimeService,
    EstimatorV2 as Estimator,
)

import numpy as np

# Instantiate runtime service and get
# the least busy backend
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)

# Define a circuit with two parameters.
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.ry(Parameter("a"), 0)
circuit.rz(Parameter("b"), 0)
circuit.cx(0, 1)
circuit.h(0)

# Transpile the circuit
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
transpiled_circuit = pm.run(circuit)
layout = transpiled_circuit.layout

# Now define a sweep over parameter values, the last axis of dimension 2 is
# for the two parameters "a" and "b"
params = np.vstack(
    [
        np.linspace(-np.pi, np.pi, 100),
        np.linspace(-4 * np.pi, 4 * np.pi, 100),
    ]
).T

# Define three observables. The inner length-1 lists cause this array of
# observables to have shape (3, 1), rather than shape (3,) if they were
# omitted.
observables = [
    [SparsePauliOp(["XX", "IY"], [0.5, 0.5])],
    [SparsePauliOp("XX")],
    [SparsePauliOp("IY")],
]
# Apply the same layout as the transpiled circuit.
observables = [
    [observable.apply_layout(layout) for observable in observable_set]
    for observable_set in observables
]

# Estimate the expectation value for all 300 combinations of observables
# and parameter values, where the pub result will have shape (3, 100).
#
# This shape is due to our array of parameter bindings having shape
# (100, 2), combined with our array of observables having shape (3, 1).
estimator_pub = (transpiled_circuit, observables, params)

# Instantiate the new Estimator object, then run the transpiled circuit
# using the set of parameters and observables.
estimator = Estimator(mode=backend)
job = estimator.run([estimator_pub])
result = job.result()

출력

하나 이상의 PUB가 실행을 위해 QPU로 전송되고 작업이 성공적으로 완료되면, 데이터는 RuntimeJobV2.result() 메서드를 호출하여 액세스할 수 있는 PrimitiveResult 컨테이너 객체로 반환됩니다.

이 객체에는 각 PubResultPUB 에 대한 PrimitiveResult 실행 결과를 포함하는 객체들의 반복 가능한 목록이 포함되어 있습니다.

이 목록의 각 요소는 프라이머리(primitive)의 run() 메서드에 제출된 각 작업-유닛( PUB )에 해당합니다(예를 들어, 20개의 PUB로 제출된 작업은 각 작업-유닛( PUB )에 하나씩 대응하는 20개의 PubResult 객체 목록을 포함하는 객체를 PrimitiveResult 반환합니다).

각 Estimator PubResult 기본 객체에는 최소한 기대값 배열(PubResult.data.evs)과 관련 표준편차(사용된 resilience_level 에 따라 PubResult.data.ensemble_standard_error 또는 PubResult.data.stds )가 포함되지만, 지정된 오차 완화 옵션에 따라 더 많은 데이터를 포함할 수도 있습니다.

PubResult 객체는 속성과 data 속성을 metadata 모두 가지고 있습니다.

  • data 속성은 실제 측정값, 표준 편차 등을 포함하는 사용자 DataBin 정의된 데이터입니다.
  • 이 작업은 관련 작업 그룹( DataBinPUB )의 형태나 구조에 따라 다양한 속성을 가지며, 작업을 제출하는 데 사용된 기본 요소(primitive)에서 지정한 오류 완화 옵션(예: ZNE 또는 PEC )에 따라서도 달라집니다.
  • metadata 속성에는 사용된 런타임 및 오류 완화 옵션에 대한 정보가 포함되어 있습니다(이에 대해서는 이 페이지의 ‘결과 메타데이터 ’ 섹션에서 나중에 설명합니다).

다음은 Estimator 출력의 데이터 PrimitiveResult 구조에 대한 시각적 개요입니다:

└── PrimitiveResult
    ├── PubResult[0]
    │   ├── metadata
    │   └── data  ## In the form of a DataBin object
    │       ├── evs
    │       │   └── List of estimated expectation values in the shape
    |       |         specified by the first pub
    │       └── stds
    │           └── List of calculated standard deviations in the
    |                 same shape as above
    ├── PubResult[1]
    |   ├── metadata
    |   └── data  ## In the form of a DataBin object
    |       ├── evs
    |       │   └── List of estimated expectation values in the shape
    |       |        specified by the second pub
    |       └── stds
    |           └── List of calculated standard deviations in the
    |                same shape as above
    ├── ...
    ├── ...
    └── ...

간단히 말해, 하나의 작업은 객체를 PrimitiveResult 반환하며 하나 이상의 PubResult 객체로 구성된 목록을 포함합니다. 그런 다음 이 PubResult 객체들은 해당 작업에 제출된 각 PUB 에 대한 측정 데이터를 저장합니다.

아래 코드 조각은 앞서 생성한 작업의 (및 관련 PubResult``PrimitiveResult ) 형식을 설명합니다.

print(
    f"The result of the submitted job had {len(result)} "
    f"PUBs and has a value:\n {result}\n"
)
print(
    "The associated PubResult of this job has the following data bins:\n "
    "{result[0].data}\n"
)
print(f"And this DataBin has attributes: {result[0].data.keys()}")
print(
    "Recall that this shape is due to our array of parameter binding sets"
    "having shape (100, 2), where 2 is the number of parameters in the "
    "circuit, combined with our array of observables having shape (3, 1). \n"
)
with np.printoptions(threshold=200):
    print(
        "The expectation values measured from this PUB are: \n"
        "{result[0].data.evs}\n"
    )

Output:

The result of the submitted job had 1 PUBs and has a value:
 PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(3, 100), dtype=float64>), stds=np.ndarray(<shape=(3, 100), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(3, 100), dtype=float64>), shape=(3, 100)), metadata={'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32})], metadata={'dynamical_decoupling': {'enable': False, 'sequence_type': 'XX', 'extra_slack_distribution': 'middle', 'scheduling_method': 'alap'}, 'twirling': {'enable_gates': False, 'enable_measure': True, 'num_randomizations': 'auto', 'shots_per_randomization': 'auto', 'interleave_randomizations': True, 'strategy': 'active-accum'}, 'resilience': {'measure_mitigation': True, 'zne_mitigation': False, 'pec_mitigation': False}, 'version': 2})

The associated PubResult of this job has the following data bins:
 {result[0].data}

And this DataBin has attributes: dict_keys(['evs', 'stds', 'ensemble_standard_error'])
Recall that this shape is due to our array of parameter binding setshaving shape (100, 2), where 2 is the number of parameters in the circuit, combined with our array of observables having shape (3, 1). 

The expectation values measured from this PUB are: 
{result[0].data.evs}

Estimator 기본 요소가 오차를 계산하는 방식

Estimator는 입력 PUB에 전달된 관측값(의 DataBin필드 evs )의 평균을 추정하는 것 외에도, 해당 기대값과 관련된 오차의 추정치를 제공하려고 시도합니다. 모든 Estimator 쿼리는 각 기대값에 대해 평균의 표준오차와 같은 수치를 해당 stds 필드에 채워 넣지만, 일부 오차 완화 옵션은 와 같은 추가 정보를 ensemble_standard_error생성하기도 합니다.

단일 관측량 O\mathcal{O} 을 고려해 보자. ZNE가 없는 경우, 추정기 실행의 각 샷(shot)은 기대값 O\langle \mathcal{O} \rangle 에 대한 점 추정치를 제공하는 것으로 볼 수 있다. 만약 점 추정치들이 벡터에 포함되어 Os 있다면, 에서 반환되는 ensemble_standard_error 값은 다음과 같다(여기서 σO\sigma_{\mathcal{O}}기대값 추정치의 표준편차이고, NshotsN_{shots} 는 샷의 개수이다):

σONshots,\frac{ \sigma_{\mathcal{O}} }{ \sqrt{N_{shots}} },

모든 샷을 하나의 앙상블로 간주하는 방식이다. 게이트 트위링 (twirling.enable_gates = True)을 요청한 경우, O\langle \mathcal{O} \rangle 의 점별 추정치를 공통된 트위링을 공유하는 집합들로 분류할 수 있습니다. 이 추정값의 집합들을 라고 O_twirls 부르며, 그 개수는 num_randomizations (회전 횟수) 개이다. 이때 stds 는 의 평균의 표준오차이며, O_twirls다음과 같이 정의된다

σONtwirls,\frac{ \sigma_{\mathcal{O}} }{ \sqrt{N_{twirls}} },

여기서 σO\sigma_{\mathcal{O}} 는 의 표준편차이며, NtwirlsN_{twirls}O_twirls 는 회전 횟수이다. 트위링 기능을 활성화하지 않으면, stdsensemble_standard_error 는 동일합니다.

ZNE를 활성화하면, 앞서 설명한 stds 요소들은 외삽 모델에 대한 비선형 회귀 분석의 가중치로 사용됩니다. 이 경우 함수가 stds 최종적으로 반환하는 값은 잡음 계수가 0일 때 평가된 적합 모델의 불확실성입니다. 적합도가 낮거나 적합도에 큰 불확실성이 존재할 경우, 보고된 값이 매우 stds 커질 수 있다. ZNE가 활성화되면 와 pub_result.data.stds_noise_factors 값도 함께 pub_result.data.evs_noise_factors 채워지므로, 사용자가 직접 외삽을 수행할 수 있습니다.


결과 메타데이터

실행 결과 외에도, 및 PubResult PrimitiveResult 객체 모두 제출된 작업에 대한 메타데이터 속성을 포함하고 있습니다. 제출된 모든 PUB에 대한 정보(예: 사용 가능한 다양한 런타임 옵션 등)가 포함된 메타데이터는 에서 확인할 수 있으며 PrimitiveResult.metatada, 각 PUB 에 특화된 메타데이터는 에서 확인할 수 PubResult.metadata 있습니다.

Note

메타데이터 필드에서 기본 구현체는 자신과 관련된 실행 정보를 자유롭게 반환할 수 있으며, 기본 기본형에서 보장하는 키-값 쌍은 존재하지 않습니다. 따라서 메타데이터의 반환 결과는 각 기본 구현에 따라 다를 수 있습니다.

# Print out the results metadata
print("The metadata of the PrimitiveResult is:")
for key, val in result.metadata.items():
    print(f"'{key}' : {val},")

print("\nThe metadata of the PubResult result is:")
for key, val in result[0].metadata.items():
    print(f"'{key}' : {val},")

Output:

The metadata of the PrimitiveResult is:
'dynamical_decoupling' : {'enable': False, 'sequence_type': 'XX', 'extra_slack_distribution': 'middle', 'scheduling_method': 'alap'},
'twirling' : {'enable_gates': False, 'enable_measure': True, 'num_randomizations': 'auto', 'shots_per_randomization': 'auto', 'interleave_randomizations': True, 'strategy': 'active-accum'},
'resilience' : {'measure_mitigation': True, 'zne_mitigation': False, 'pec_mitigation': False},
'version' : 2,

The metadata of the PubResult result is:
'shots' : 4096,
'target_precision' : 0.015625,
'circuit_metadata' : {},
'resilience' : {},
'num_randomizations' : 32,
이 페이지가 도움이 되었습니까?
GitHub에서 버그, 오타를 보고하거나 컨텐츠를 요청하십시오.