バッチでジョブを実行する
Package versions
このページのコードは、以下の要件を使用して開発されました。 これらのバージョン以降を使用することを推奨します。
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"):
...
設定できないインタラクティブ生存時間(インタラクティブTTL)の値もあります(すべてのプランで1分間)。その時間内にバッチジョブがキューに入らない場合、バッチは一時的に非アクティブ化されます。
デフォルトの最大TTL値:
| インスタンスタイプ | デフォルトの最大TTL |
|---|---|
| すべての有料プラン | 8時間 |
| オープン | 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および最大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}
並列処理のためにジョブを再 構成する
バッチが提供する並列処理を活用するために、ジョブを再構成する方法は複数あります。以下の例では、長い回路リストを複数のジョブに分割し、バッチとして実行することで並列処理を活用する方法を示します。
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を確認してください。