배치로 작업 실행하기
패키지 버전
이 페이지의 코드는 다음 요구 사항을 사용하여 개발되었습니다. 아래 버전 이상을 사용하는 것을 권장합니다.
qiskit[all]~=2.3.0
qiskit-ibm-runtime~=0.43.1
배치 모드를 사용하여 여러 기본 작업을 동시에 제출할 수 있습니다. 다음은 배치 작업 예시들입니다.
배치 사용을 위한 설정
배치를 시작하기 전에 Qiskit Runtime 설정을 완료하고 서비스로 초기화해야 합니다:
# Added by doQumentation — required packages for this notebook
!pip install -q numpy qiskit qiskit-ibm-runtime
from qiskit_ibm_runtime import (
QiskitRuntimeService,
Batch,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
)
service = QiskitRuntimeService()
배치 열기
컨텍스트 매니저 with Batch(...)를 사용하거나 Batch 클래스를 초기화하여 런타임 배치를 열 수 있습니다. 배치를 시작할 때는 backend 객체를 전달하여 QPU를 지정해야 합니다. 배치는 첫 번째 작업이 실행되기 시작할 때 시작됩니다.
Batch 클래스
backend = service.least_busy(operational=True, simulator=False)
batch = Batch(backend=backend)
estimator = Estimator(mode=batch)
sampler = Sampler(mode=batch)
# Close the batch because no context manager was used.
batch.close()
컨텍스트 매니저
컨텍스트 매니저는 배치를 자동으로 열고 닫습니다.
from qiskit_ibm_runtime import (
Batch,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
)
backend = service.least_busy(operational=True, simulator=False)
with Batch(backend=backend):
estimator = Estimator()
sampler = Sampler()
배치 길이
max_time 매개변수를 사용하여 배치의 최대 유효 시간(TTL)을 정의할 수 있습니다. 이 값은 가장 오래 실행되는 작업의 실행 시간을 초과해야 합니다. 이 타이머는 배치가 시작될 때 시작됩니다. 값에 도달하면 배치가 닫힙니다. 실행 중인 작업은 완료되지만 아직 대기 중인 작업은 실패 처리됩니다.
with Batch(backend=backend, max_time="25m"):
...
구성할 수 없는 대화형 유효 시간(interactive TTL) 값도 있습니다(모든 플랜에서 1분). 해당 시간 내에 배치 작업이 대기열에 추가되지 않으면 배치가 일시적으로 비활성화됩니다.
기본 최대 TTL 값:
| 인스턴스 유형 | 기본 최대 TTL |
|---|---|
| 모든 유료 플랜 | 8시간 |
| Open | 10분 |
배치의 최대 TTL 또는 대화형 TTL을 확인하려면 배치 세부 정보 확인의 지침을 따르고 각각 max_time 또는 interactive_timeout 값을 찾으세요.
배치 닫기
배치는 컨텍스트 매니저가 종료될 때 자동으로 닫힙니다. 배치 컨텍스트 매니저가 종료되면 배치는 "진행 중, 새 작업 미허용" 상태가 됩 니다. 이는 배치가 최대 TTL 값에 도달할 때까지 실행 중이거나 대기 중인 모든 작업을 계속 처리한다는 것을 의미합니다. 모든 작업이 완료되면 배치가 즉시 닫힙니다. 닫힌 배치에는 작업을 제출할 수 없습니다.
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.transpiler import generate_preset_pass_manager
import numpy as np
# This cell is hidden from users
service = QiskitRuntimeService()
backend = service.least_busy()
# Define two circuits, each with one parameter with two parameters.
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.ry(Parameter("a"), 0)
circuit.cx(0, 1)
circuit.h(0)
circuit.measure_all()
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
transpiled_circuit = pm.run(circuit)
transpiled_circuit_sampler = transpiled_circuit
transpiled_circuit_sampler.measure_all()
params = np.random.uniform(size=(2, 3)).T
observables = [
[
SparsePauliOp(["XX", "IY"], [0.5, 0.5]).apply_layout(
transpiled_circuit.layout
)
],
[SparsePauliOp("XX").apply_layout(transpiled_circuit.layout)],
[SparsePauliOp("IY").apply_layout(transpiled_circuit.layout)],
]
sampler_pub = (transpiled_circuit_sampler, params)
estimator_pub = (transpiled_circuit_sampler, observables, params)
with Batch(backend=backend) as batch:
estimator = Estimator()
sampler = Sampler()
job1 = estimator.run([estimator_pub])
job2 = sampler.run([sampler_pub])
# The batch is no longer accepting jobs but the submitted job will run to completion.
result = job1.result()
result2 = job2.result()
컨텍스트 매니저를 사용하지 않는 경우 배치를 수동으로 닫으세요. 배치를 열어 둔 채로 나중에 추가 작업을 제출하면 최대 TTL에 도달하여 후속 작업이 시작되기 전에 취소될 수 있습니다. 작업 제출이 완료되는 즉시 배치를 닫을 수 있습니다. batch.close()로 배치를 닫으면 새 작업을 더 이상 허용하지 않지만, 이미 제출된 작업은 완료될 때까지 계속 실행되며 결과를 가져올 수 있습니다.
batch = Batch(backend=backend)
# If using qiskit-ibm-runtime earlier than 0.24.0, change `mode=` to `batch=`
estimator = Estimator(mode=batch)
sampler = Sampler(mode=batch)
job1 = estimator.run([estimator_pub])
job2 = sampler.run([sampler_pub])
print(f"Result1: {job1.result()}")
print(f"Result2: {job2.result()}")
# Manually close the batch. Running and queued jobs will run to completion.
batch.close()
Result1: PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(3, 2), dtype=float64>), stds=np.ndarray(<shape=(3, 2), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(3, 2), dtype=float64>), shape=(3, 2)), 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})
Result2: PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(3, 2), num_shots=4096, num_bits=2>), meas0=BitArray(<shape=(3, 2), num_shots=4096, num_bits=133>), shape=(3, 2)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-01-15 07:47:58', stop='2026-01-15 07:48:05', size=24576>)])}, 'version': 2})
배치 세부 정보 확인
대화형 및 최대 TTL을 포함한 배치의 구성 및 상태에 대한 포괄적인 개요를 보려면 batch.details() 메서드를 사용하세요.
from qiskit_ibm_runtime import (
QiskitRuntimeService,
batch,
SamplerV2 as Sampler,
)
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
with Batch(backend=backend) as batch:
print(batch.details())
{'id': 'ce8cf08d-b18e-4d56-ab51-eaff0b8190f4', 'backend_name': 'ibm_torino', 'interactive_timeout': 1, 'max_time': 28800, 'active_timeout': 28800, 'state': 'open', 'accepting_jobs': True, 'last_job_started': None, 'last_job_completed': None, 'started_at': None, 'closed_at': None, 'activated_at': None, 'mode': 'batch', 'usage_time': None}
병렬 처리를 위한 작업 재구성
배치가 제공하는 병렬 처리를 활용하기 위해 작업을 재구성하는 방법은 여러 가지가 있습니다. 다음 예시는 긴 Circuit 목록을 여러 작업으로 분할하고 배치로 실행하여 병렬 처리를 활용하는 방법을 보여줍니다.
from qiskit_ibm_runtime import SamplerV2 as Sampler, Batch
from qiskit.circuit.random import random_circuit
max_circuits = 100
circuits = [pm.run(random_circuit(5, 5)) for _ in range(5 * max_circuits)]
for circuit in circuits:
circuit.measure_active()
all_partitioned_circuits = []
for i in range(0, len(circuits), max_circuits):
all_partitioned_circuits.append(circuits[i : i + max_circuits])
jobs = []
start_idx = 0
with Batch(backend=backend):
sampler = Sampler()
for partitioned_circuits in all_partitioned_circuits:
job = sampler.run(partitioned_circuits)
jobs.append(job)
기본 요소에 backend=backend를 설정하면 배치 또는 세션 컨텍스트 내부에 있더라도 프로그램이 작업 모드로 실행됩니다. backend=backend 설정은 Qiskit Runtime v0.24.0부터 더 이상 사용되지 않습니다. 대신 mode 매개변수를 사용하세요.
다음 단계
- Estimator 기본 요소를 사용한 오류 완화 옵션 결합 튜토리얼에서 예시를 시험해 보세요.
- Batch API 참조 문서를 검토하세요.
- IBM QPU에 작업을 전송할 때의 작업 제한을 이해하세요.
- 실행 모드 FAQ를 검토하세요.