Skip to main content
IBM Quantum Platform

기본

qiskit.primitives

프리미티브는 대규모 애플리케이션에서 사용되는 계산 빌딩 블록으로, 프리미티브 통합 블록(PUB)이라고 하는 입력 단위가 효율적으로 출력을 생성하기 위해 양자 리소스를 필요로 합니다.

BaseEstimatorV2현재 두 가지 유형의 기본 요소가 있으며, 이들의 최신 버전에서 추상화는 와 에 의해 BaseSamplerV2 정의되어 있습니다. 샘플러는 양자 회로(또는 매개변수화된 회로에 대한 값의 스윕)를 입력으로 받아, 해당 회로의 고전적 출력 레지스터에서 샘플을 추출하는 역할을 합니다. 추정기는 회로와 관측 변수의 조합(또는 이에 대한 스윕)을 입력으로 받아 관측 변수의 기대값을 추정합니다.

Qiskit은 및 StatevectorEstimator 클래스를 StatevectorSampler 통해 이러한 각 추상화에 대한 참조 구현을 제공합니다.

BaseEstimatorV1샘플러 및 추정기 추상화의 이전 버전은 및 에 의해 BaseSamplerV1 정의됩니다. BaseEstimatorV2이러한 인터페이스들은 해당 run 메서드에 대해 서로 다르고 유연성이 떨어지는 입출력 형식을 따르며, 실제로는 와 로 BaseSamplerV2 대체된 지 오래입니다. 그러나 하위 호환성을 위해 원래의 추상 인터페이스 정의는 그대로 유지되었습니다. V1 과 V2 의 차이점에 대한 자세한 내용은 이 페이지의 ‘마이그레이션’ 섹션을 확인하세요.


EstimatorV2 개요

BaseEstimatorV2 주어진 양자 회로와 관측량 조합에 대한 기대값을 추정하는 기본 함수입니다.

구축이 완료된 후, 펍(Primitive Unified Blocs) 목록을 매개변수로 전달하여 해당 run() 메서드를 호출함으로써 에스티메이터를 사용합니다. 각 펍에는 세 가지 값이 포함되어 있으며, 이 값들이 결합되어 추정기가 완료해야 할 작업의 계산 단위를 정의합니다:

  • 매개변수가 포함될 수도 있는 단일 QuantumCircuit객체로, 그 최종 상태를 ψ(θ)\psi(\theta) 로 정의하며,
  • strPauliObservablesArrayLike추정할 기대값을 지정하는 하나 이상의 관측 가능량(, SparsePauliOp, 등을 포함하여 임의의 값으로 지정됨), 이를 HjH_j 로 표기하며,
  • 회로를 바인딩할 매개변수 값 집합의 모음, θk\theta_k.

추정기를 실행하면 객체가 BasePrimitiveJob 반환되며, 이 객체의 메서드를 result() 호출하면 각 pub에 대한 기대값 추정값과 메타데이터를 얻을 수 있습니다:

ψ(θk)Hjψ(θk)\langle\psi(\theta_k)|H_j|\psi(\theta_k)\rangle

퍼브의 관측 항목과 파라미터 값 부분은 표준 방송 규칙이 적용되는 임의의 차원으로 배열 값화할 수 있으므로, 각 퍼브의 예상 결과도 일반적으로 배열 값화됩니다. 자세한 내용은 여기를 참조하세요.

다음은 추정기를 사용하는 방법의 예입니다.

from qiskit.primitives import StatevectorEstimator as Estimator
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp

psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)

H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])

theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 1, 2, 3, 5, 8, 13]
theta3 = [1, 2, 3, 4, 5, 6]

estimator = Estimator()

# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
job = estimator.run([(psi1, H1, [theta1])])
job_result = job.result() # It will block until the job finishes.
print(f"The primitive-job finished with result {job_result}")

# calculate [ [<psi1(theta1)|H1|psi1(theta1)>,
#              <psi1(theta3)|H3|psi1(theta3)>],
#             [<psi2(theta2)|H2|psi2(theta2)>] ]
job2 = estimator.run(
    [
        (psi1, [H1, H3], [theta1, theta3]),
        (psi2, H2, theta2)
    ],
    precision=0.01
)
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}")

SamplerV2 개요

BaseSamplerV2 양자 회로의 출력을 샘플링하는 기본 연산자입니다.

구축이 완료된 후, 펍(Primitive Unified Blocs) 목록을 인수로 전달하여 해당 run() 메서드를 호출함으로써 샘플러를 사용합니다. 각 펍에는 샘플러가 수행해야 할 작업의 계산 단위를 정의하는 값들이 포함되어 있습니다:

  • 단일 QuantumCircuit매개변수로 설정할 수 있습니다.
  • 컬렉션 매개변수 값이 파라메트릭인 경우 회로를 바인딩할 집합 매개변수 값입니다.
  • 선택 사항으로, 설정하지 않은 경우 실행 방법에서 결정되는 샘플링할 샷 수입니다.

샘플러를 실행하면 객체가 BasePrimitiveJob 반환되며, 이 객체에서 메서드를 result() 호출하면 각 pub에 대한 출력 샘플과 메타데이터가 반환됩니다.

다음은 샘플러를 사용하는 방법의 예입니다.

from qiskit.primitives import StatevectorSampler as Sampler
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes

# create a Bell circuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()

# create two parameterized circuits
pqc = RealAmplitudes(num_qubits=2, reps=2)
pqc.measure_all()
pqc2 = RealAmplitudes(num_qubits=2, reps=3)
pqc2.measure_all()

theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 2, 3, 4, 5, 6, 7]

# initialization of the sampler
sampler = Sampler()

# collect 128 shots from the Bell circuit
job = sampler.run([bell], shots=128)
job_result = job.result()
print(f"The primitive-job finished with result {job_result}")

# run a sampler job on the parameterized circuits
job2 = sampler.run([(pqc, theta1), (pqc2, theta2)])
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}")

EstimatorV1 개요

현재 Qiskit에는 레거시 EstimatorV1 인터페이스의 구현체가 없습니다. 그러나 외부 구현에 대한 하위 호환성을 보장하기 위해, 에서 BaseEstimatorV1 정의된 추상 인터페이스 정의는 여전히 이 패키지의 일부로 남아 있습니다.

구현체는 EstimatorV1 빈 매개변수 집합으로 초기화됩니다. BaseEstimatorV1 다음 매개변수를 사용하여 해당 .run() 메서드를 호출할 수 있습니다:

  • 양자 회로 ( ψi(θ)\psi_i(\theta) ): (매개변수화된) 양자 회로 목록( QuantumCircuit 객체 목록).
  • observables ( HjH_j ): 객체들의 SparsePauliOp 목록.
  • 파라미터 값 ( θk\theta_k ): 양자 회로의 파라미터에 바인딩할 값의 집합 목록(실수 목록 목록).

이 메서드는 객체를 JobV1 반환해야 합니다. 이 함수를 호출하면 qiskit.providers.JobV1.result() 기대값 목록과 함께, 추정치에 대한 신뢰 구간과 같은 선택적 메타데이터가 반환됩니다.

ψi(θk)Hjψi(θk)\langle\psi_i(\theta_k)|H_j|\psi_i(\theta_k)\rangle

다음은 EstimatorV1 구현을 사용하는 방법의 예입니다. 현재 키스킷에는 레거시 EstimatorV1 인터페이스가 구현되어 있지 않다는 점에 유의하세요.

# This is a fictional import path.
# There are currently no EstimatorV1 implementations in Qiskit.
from estimator_v1_location import EstimatorV1
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp

psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)

H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])

theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 1, 2, 3, 5, 8, 13]
theta3 = [1, 2, 3, 4, 5, 6]

estimator = EstimatorV1()

# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
job = estimator.run([psi1], [H1], [theta1])
job_result = job.result() # It will block until the job finishes.
print(f"The primitive-job finished with result {job_result}")

# calculate [ <psi1(theta1)|H1|psi1(theta1)>,
#             <psi2(theta2)|H2|psi2(theta2)>,
#             <psi1(theta3)|H3|psi1(theta3)> ]
job2 = estimator.run(
    [psi1, psi2, psi1],
    [H1, H2, H3],
    [theta1, theta2, theta3]
)
job_result = job2.result()
print(f"The primitive-job finished with result {job_result}")

SamplerV1 개요

현재 Qiskit에는 레거시 SamplerV1 인터페이스의 구현체가 없습니다. 그러나 외부 구현에 대한 하위 호환성을 보장하기 위해, 에서 BaseSamplerV1 정의된 추상 인터페이스 정의는 여전히 이 패키지의 일부로 남아 있습니다.

샘플러 클래스는 양자 회로에서 비트 문자열의 확률 또는 준확률을 계산합니다.

A는 SamplerV1 빈 매개변수 집합으로 초기화됩니다. BaseSamplerV1 구현체는 다음 매개변수를 사용하여 메서드를 .run() 통해 호출할 수 있습니다:

  • 양자 회로 ( ψi(θ)\psi_i(\theta) ): (파라미터화된) 양자 회로 목록입니다. ( QuantumCircuit 객체)
  • 파라미터 값 ( θk\theta_k ): 양자 회로의 파라미터에 바인딩할 파라미터 값 집합의 목록입니다. (플로트 목록 목록)

.run() 객체를 JobV1 반환합니다. 이 함수를 호출하면 qiskit.providers.JobV1.result() 비트열의 확률 또는 준확률을 포함하며, 샘플의 오차 범위와 같은 선택적 메타데이터도 포함된 객체가 SamplerResult 반환됩니다.

다음은 SamplerV1 구현을 사용하는 방법의 예입니다. 현재 키스킷에는 레거시 SamplerV1 인터페이스가 구현되어 있지 않다는 점에 유의하세요.

# This is a fictional import path.
# There are currently no SamplerV1 implementations in Qiskit.
from sampler_v1_location import Sampler
from qiskit import QuantumCircuit
from qiskit.circuit.library import RealAmplitudes

# a Bell circuit
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()

# two parameterized circuits
pqc = RealAmplitudes(num_qubits=2, reps=2)
pqc.measure_all()
pqc2 = RealAmplitudes(num_qubits=2, reps=3)
pqc2.measure_all()

theta1 = [0, 1, 1, 2, 3, 5]
theta2 = [0, 1, 2, 3, 4, 5, 6, 7]

# initialization of the sampler
sampler = SamplerV1()

# Sampler runs a job on the Bell circuit
job = sampler.run(
    circuits=[bell], parameter_values=[[]], parameters=[[]]
)
job_result = job.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])

# Sampler runs a job on the parameterized circuits
job2 = sampler.run(
    circuits=[pqc, pqc2],
    parameter_values=[theta1, theta2],
    parameters=[pqc.parameters, pqc2.parameters])
job_result = job2.result()
print([q.binary_probabilities() for q in job_result.quasi_dists])

Primitives( V1 )에서 V2 로의 마이그레이션

Primitives V1 와 V2 API 간의 공식적인 차이점은 기본형 구현체가 상속받는 기본 클래스에 있으며, 이 목록은 모두 페이지 하단에 나와 있습니다. 그러나 개념적인 차원에서 볼 때, V1 에서 V2: 로 마이그레이션할 때 유의해야 할 몇 가지 중요한 차이점은 다음과 같습니다

  1. V2 프리미티브는 단일 회로를 벡터값(또는 더 일반적으로 배열값) 사양으로 그룹화할 수 있는 벡터화된 입력을 선호합니다. 각 그룹을 원시 통합 블록(퍼브)이라고 하며, 각 퍼브는 고유한 결과를 얻습니다. 예를 들어 견적서에서 다음과 같은 차이점을 비교할 수 있습니다:

    # Favoured V2 pattern. There is only one pub here, but there could be more.
    job = estimator_v2.run([(circuit, [obs1, obs2, obs3, obs4])])
    evs = job.result()[0].data.evs
    
    # V1 equivalent, where the same circuit must be provided four times.
    job = estimator_v1.run([circuit] * 4, [obs1, obs2, obs3, obs4])
    evs = job.result().values

    간결성을 위해 위의 예시에는 표시되지 않았지만, 회로는 매개변수 값 집합의 배열이 관측값 배열에 대해 브로드캐스트되는 매개변수형일 수 있습니다. 샘플러는 비슷하지만 관찰할 수 있는 항목이 없습니다:

    # Favoured V2 pattern. There is only one pub here, but there could be more.
    job = sampler_v2.run([(circuit, [vals1, vals2, vals3])])
    samples = job.result()[0].data
    
    # V1 equivalent, where the same circuit must be provided three times.
    sampler_v1.run([circuit] * 3, [vals1, vals2, vals3])
    quasi_dists = job.result().quasi_dists
  2. V2 샘플러는 측정된 샷 순서를 유지한 채 기존 결과의 샘플을 반환합니다. 이는 기존 결과에 대한 분포의 추정치인 준확률 분포를 출력하는 V1 샘플러와는 대조적입니다. 또한 V2 샘플러 결과 개체는 입력 회로의 클래식 레지스터 이름으로 데이터를 구성하므로 동적 회로와 자연스럽게 호환됩니다.

    V2 인터페이스에서 준확률 분포와 가장 유사한 것은 아래 예제에 표시된 메서드입니다 get_counts() . 그러나 유틸리티 규모 실험(100개 이상의 큐비트)의 경우, 동일한 비트열을 두 번 측정할 확률이 매우 낮기 때문에, 사전 형식으로 카운트를 그룹화하는 방식은 일반적으로 효율적인 데이터 처리 전략이 되지 못한다는 점을 강조하고 싶습니다.

    circuit = QuantumCircuit(QuantumRegister(2, "qreg"), ClassicalRegister(2, "alpha"))
    circuit.h(0)
    circuit.cx(0, 1)
    circuit.measure([0, 1], [0, 1])
    
    # V1 sampler usage
    result = sampler_v1.run([circuit]).result()
    quasi_dist = result.quasi_dists[0]
    
    # V2 sampler usage
    result = sampler_v2.run([circuit]).result()
    # these are the bit values from the alpha register, over all shots
    bitvals = result[0].data.alpha
    # we can use it to generate a Counts mapping, which is similar to a quasi prob distribution
    counts = bitvals.get_counts()
    # which can in turn be converted to the V1 type through normalization
    quasi_dist = QuasiDistribution({outcome: freq / shots for outcome, freq in counts.items()})
  3. V2 의 기본 요소들은 모든 양자 시스템에 내재된 확률적 특성으로 인해 발생하는 ‘샘플링 오버헤드’라는 개념을, 단순한 옵션에서 벗어나 API 자체에 직접 반영했습니다. shots샘플러의 경우, 이는 인수가 shots 이제 시그니처의 run() 일부가 되었음을 의미하며, 나아가 각 pub이 에 대한 자체 값을 지정할 수 있고, 이 값은 메서드에 주어진 어떤 값보다 우선한다는 것을 의미합니다. 이 추정기에는 기본 구현체가 기대값 추정 시 목표로 삼아야 할 오차 막대를 지정하는 유사한 precision 인자가 있습니다.

    이 개념은 V1 프리미티브의 API에는 없지만 V1 프리미티브의 모든 구현에는 옵션 어딘가에 관련 설정이 있습니다.

    # Sample two circuits at 128 shots each.
    sampler_v2.run([circuit1, circuit2], shots=128)
    
    # Sample two circuits at different amounts of shots. The "None"s are necessary as placeholders
    # for the lack of parameter values in this example.
    sampler_v2.run([(circuit1, None, 123), (circuit2, None, 456)])
    
    # Estimate expectation values for two pubs, both with 0.05 precision.
    estimator_v2.run([(circuit1, obs_array1), (circuit2, obs_array_2)], precision=0.05)

기본형 API

매개변수 V2

ParameterLike연합 타입을 나타냅니다
BindingsArray( [데이터, 모양] ). qiskit.QuantumCircuit에 대한 매개변수 바인딩 값 집합을 저장합니다.
BindingsArrayLike별명 `Mapping[ParameterLike

추정기 V2

BaseEstimatorV2()EstimatorV2 구현을 위한 베이스 클래스입니다.
StatevectorEstimator(*[, default_precision,...] )BaseEstimatorV2 전체 상태 벡터 시뮬레이션을 포함한 간단한 구현.
BackendEstimatorV2(*, 백엔드[, 옵션] )제공된 양자 회로와 관측 가능한 조합에 대한 기대값을 평가합니다.
EstimatorPub(회로, 관측 가능량[,...] )모든 Estimator 프라이머리타입에 대한 기본 통합 블록.
ObservablesArray(관측 가능 변수[, 큐비트 수,...] )원시 Estimator 연산자에 대한 헤르미트 관측량의 ND-배열.
ObservableLike연합 타입을 나타냅니다
EstimatorPubLike별칭 EstimatorPub
ObservablesArrayLike별명 `ObservableLike

샘플러 V2

BaseSamplerV2()SamplerV2 구현을 위한 베이스 클래스입니다.
StatevectorSampler(*[, default_shots, seed] )BaseSamplerV2 전체 상태 벡터 시뮬레이션을 이용한 간단한 구현.
BackendSamplerV2(*, 백엔드[, 옵션] )제공된 양자 회로에 대한 비트 문자열을 평가합니다
SamplerPub(회로[, 매개변수_값,...] )샘플러용 Pub(Primitive Unified Bloc).
SamplerPubLike별칭 SamplerPub

결과 V2

BitArray(배열, 비트 수)비트 값 배열을 저장합니다.
DataBin(*[, shape] )PubResult.에 속한 한 술집에서 수집된 주요 데이터입니다.
PrimitiveResult(pub_results[, metadata] )여러 게시 결과 및 글로벌 메타데이터를 위한 컨테이너입니다.
PubResult(데이터[, 메타데이터] )단일 pub(기본 통합 블록)에 대한 결과 객체.
SamplerPubResult(데이터[, 메타데이터] )샘플러 펍의 결과입니다.
BasePrimitiveJob(job_id, **kwargs)프리미티브 잡 추상 베이스 클래스.
PrimitiveJob(function, *args, **kwargs)Qiskit의 기본 함수 참조 구현체에서 작업에 대한 핸들.

추정기 V1

BaseEstimatorV1(*[, 옵션] )EstimatorV1 구현을 위한 베이스 클래스입니다.
EstimatorResult(값, 메타데이터)추정기 결과 V1.

샘플러 V1

BaseSamplerV1(*[, 옵션] )샘플러 V1 베이스 클래스
SamplerResult(quasi_dists, metadata)샘플러 결과 V1.
이 페이지가 도움이 되었습니까?
GitHub에서 버그, 오타를 보고하거나 컨텐츠를 요청하십시오.