דלג לתוכן הראשי

הרצת עבודות ב-batch

Package versions

The code on this page was developed using the following requirements. We recommend using these versions or newer.

qiskit[all]~=2.3.0
qiskit-ibm-runtime~=0.43.1

השתמש במצב batch כדי לשלוח מספר עבודות primitive בו-זמנית. להלן דוגמאות לעבודה עם batches.

הגדרה לשימוש ב-batches

לפני תחילת batch, עליך להגדיר את 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()

פתיחת batch

אתה יכול לפתוח runtime batch באמצעות מנהל ההקשר with Batch(...) או על ידי אתחול מחלקת Batch. כאשר אתה מתחיל batch, עליך לציין QPU על ידי העברת אובייקט backend. ה-batch מתחיל כשעבודתו הראשונה מתחילה לרוץ.

מחלקת 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()

מנהל הקשר

מנהל ההקשר פותח וסוגר את ה-batch אוטומטית.

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()

אורך ה-batch

אתה יכול להגדיר את זמן המקסימום לחיות (TTL) של ה-batch באמצעות פרמטר max_time. ערך זה צריך לעלות על זמן הביצוע של העבודה הארוכה ביותר. הטיימר מתחיל כשה-batch מתחיל. כאשר הערך מגיע לסיומו, ה-batch נסגר. כל עבודה שרצה תסתיים, אך עבודות שעדיין בתור יכשלו.

with Batch(backend=backend, max_time="25m"):
...

קיים גם ערך interactive time to live (interactive TTL) שלא ניתן לקביעה (דקה אחת לכל התוכניות). אם אין עבודות batch בתור בתוך אותה חלון, ה-batch מושבת זמנית.

ערכי TTL מקסימאלי ברירת מחדל:

סוג instanceTTL מקסימאלי כברירת מחדל
כל התוכניות בתשלום8 שעות
Open10 דקות

כדי לקבוע את ה-TTL המקסימאלי או ה-interactive TTL של batch, פעל לפי ההוראות בקביעת פרטי batch וחפש את הערך max_time או interactive_timeout, בהתאמה.

סגירת batch

ה-batch נסגר אוטומטית כאשר הוא יוצא ממנהל ההקשר. כאשר מנהל הקשר ה-batch יוצא, ה-batch מועמד למצב "In progress, not accepting new jobs". פירוש הדבר שה-batch מסיים לעבד את כל העבודות הרצות או בתור עד שיגיע לערך ה-TTL המקסימאלי. לאחר השלמת כל העבודות, ה-batch נסגר מיידית. אינך יכול לשלוח עבודות ל-batch סגור.

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()
טיפ

If you are not using a context manager, manually close the batch. If you leave the batch open and submit more jobs to it later, it is possible that the maximum TTL will be reached before the subsequent jobs start running; causing them to be canceled. You can close a batch as soon as you are done submitting jobs to it. When a batch is closed with batch.close(), it no longer accepts new jobs, but the already submitted jobs will still run until completion and their results can be retrieved.

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})

קביעת פרטי batch

לסקירה מקיפה של תצורת ה-batch ומצבו, כולל ה-interactive TTL וה-max 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}

הגדרה מחדש של עבודות לעיבוד מקבילי

יש מספר דרכים להגדיר מחדש את עבודותיך כדי לנצל את העיבוד המקבילי שמספק batching. הדוגמה הבאה מראה כיצד ניתן לחלק רשימה ארוכה של Circuit-ים למספר עבודות ולהריץ אותן כ-batch כדי לנצל את העיבוד המקבילי.

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)
זהירות

If you set backend=backend in a primitive, the program is run in job mode, even if it's inside a batch or session context. Setting backend=backend is deprecated as of Qiskit Runtime v0.24.0. Instead, use the mode parameter.

השלבים הבאים

Recommendations