הרצת עבודות ב-session
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
scipy~=1.16.3
Open Plan users cannot submit session jobs. Workloads must be run in job mode or batch mode.
השתמש ב-sessions כאשר אתה זקוק לגישה ייעודית ובלעדית ל-QPU.
הגדרה לשימוש ב-sessions
לפני תחילת session, עליך להגדיר את Qiskit Runtime ולאתחל אותו כשירות:
# Added by doQumentation — required packages for this notebook
!pip install -q numpy qiskit qiskit-ibm-runtime scipy
from qiskit_ibm_runtime import (
QiskitRuntimeService,
Session,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
)
service = QiskitRuntimeService()
פתיחת session
אתה יכול לפתוח runtime session באמצעות מנהל ההקשר with Session(...) או על ידי אתחול מחלקת Session.
כאשר אתה מתחיל session, עליך לציין QPU על ידי העברת אובייקט backend. ה-session מתחיל כשעבודתו הראשונה מתחילה לרוץ.
If you open a session but do not submit any jobs to it for 30 minutes, the session automatically closes.
מחלקת Session
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
backend = service.least_busy(operational=True, simulator=False)
session = Session(backend=backend)
estimator = Estimator(mode=session)
sampler = Sampler(mode=session)
# Close the session because no context manager was used.
session.close()
מנהל הקשר
מנהל ההקשר פותח וסוגר את ה-session אוטומטית.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
from qiskit_ibm_runtime import (
Session,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
)
backend = service.least_busy(operational=True, simulator=False)
with Session(backend=backend):
estimator = Estimator()
sampler = Sampler()
אורך ה-session
זמן ה מקסימום לחיות (TTL) של ה-session קובע כמה זמן ה-session יכול לרוץ. אתה יכול להגדיר ערך זה עם פרמטר max_time. ערך זה צריך לעלות על זמן הביצוע של העבודה הארוכה ביותר.
הטיימר מתחיל כשה-session מתחיל. כאשר הערך מגיע לסיומו, ה-session נסגר. כל עבודה שרצה תסתיים, אך עבודות שעדיין בתור יכשלו.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
with Session(backend=backend, max_time="25m"):
...
קיים גם ערך interactive time to live (interactive TTL) שלא ניתן לקביעה. אם אין עבודות session בתור בתוך אותה חלון, ה-session מושבת זמנית.
ערכי ברירת מחדל:
| סוג instance (Open או Premium Plan) | Interactive TTL | TTL מקסימאלי |
|---|---|---|
| Premium Plan | 60 שניות* | 8 שעות* |
| * ייתכן שחלק מ-instances של Premium Plan מוגדרים עם ערך שונה. |
כדי לקבוע את ה-TTL המקסימאלי או ה-interactive TTL של session, פעל לפי ההוראות בקביעת פרטי session וחפש את הערך max_time או interactive_timeout, בהתאמה.
סיום session
session מסתיים בנסיבות הבאות:
- ערך timeout המקסימאלי (TTL) הגיע לסיומו, מה שגורם לביטול כל העבודות בתור.
- ה-session בוטל ידנית, מה שגורם לביטול כל העבודות בתור.
- ה-session נסגר ידנית. ה-session מפסיק לקבל עבודות חדשות אך ממשיך להריץ עבודות בתור עם עדיפות.
- אם אתה משתמש ב-Session כמנהל הקשר, כלומר
with Session(), ה-session נסגר אוטומטית כאשר ההקשר מסתיים (אותה התנהגות כמו שימוש ב-session.close()).
סגירת session
ה-session נסגר אוטומטית כאשר הוא יוצא ממנהל ההקשר. כאשר מנהל הקשר ה-session יוצא, ה-session מועמד למצב "In progress, not accepting new jobs". פירוש הדבר שה-session מסיים לעבד את כל העבודות הרצות או בתור עד שיגיע לערך timeout המקסימאלי. לאחר השלמת כל העבודות, ה-session נסגר מיידית. זה מאפשר לתזמן להריץ את העבודה הבאה מבלי לחכות ל-interactive timeout של ה-session, ובכך מפחית את זמן התורים הממוצע של עבודות. אינך יכול לשלוח עבודות ל-session סגור.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
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()
# Create parameters and mapped observables to submit
params = np.random.uniform(size=(2, 3)).T
observables = [
SparsePauliOp(["XX", "IY"], [0.5, 0.5]),
SparsePauliOp("XX"),
SparsePauliOp("IY"),
]
mapped_observables = [
[observable.apply_layout(transpiled_circuit.layout)]
for observable in observables
]
sampler_pub = (transpiled_circuit_sampler, params)
estimator_pub = (transpiled_circuit_sampler, mapped_observables, params)
with Session(backend=backend) as session:
estimator = Estimator()
sampler = Sampler()
job1 = estimator.run([estimator_pub])
job2 = sampler.run([sampler_pub])
# The session 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 session to avoid unwanted cost. You can close a session as soon as you are done submitting jobs to it. When a session is closed with session.close(), it no longer accepts new jobs, but the already submitted jobs will still run until completion and their results can be retrieved.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
session = Session(backend=backend)
# If using qiskit-ibm-runtime earlier than 0.24.0, change `mode=` to `session=`
estimator = Estimator(mode=session)
sampler = Sampler(mode=session)
job1 = estimator.run([estimator_pub])
job2 = sampler.run([sampler_pub])
print(f"Result1: {job1.result()}")
print(f"Result2: {job2.result()}")
# Manually close the session. Running and queued jobs will run to completion.
session.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:53:15', stop='2026-01-15 07:53:21', size=24576>)])}, 'version': 2})
בדיקת מצב session
אתה יכול לשאול על מצב ה-session כדי להבין את מצבו הנוכחי באמצעות session.status() או על ידי צפייה בדף Workloads.
מצב session יכול להיות אחד מהבאים:
Pending: ה-session לא התחיל או שהושבת. עבודת ה-session הבאה צריכה לחכות בתור כמו עבודות אחרות.In progress, accepting new jobs: ה-session פעיל ומקבל עבודות חדשות.In progress, not accepting new jobs: ה-session פעיל אך אינו מקבל עבודות חדשות. שליחת עבודות ל-session נדחית, אך עבודות session פעילות ימשיכו לרוץ עד לסיום. ה-session נסגר אוטומטית לאחר סיום כל העבודות.Closed: ערך timeout המקסימאלי של ה-session הגיע לסיומו או ה-session נסגר במפורש.
קביעת פרטי session
לסקירה מקיפה של תצורת ה-session ומצבו, השתמש במתודה session.details().
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
from qiskit_ibm_runtime import (
QiskitRuntimeService,
Session,
EstimatorV2 as Estimator,
)
service = QiskitRuntimeService()
backend = service.least_busy(operational=True, simulator=False)
with Session(backend=backend) as session:
print(session.details())
{'id': 'be84569d-86b5-4a7f-be5e-7d33e80dc220', 'backend_name': 'ibm_torino', 'interactive_timeout': 60, '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': 'dedicated', 'usage_time': None}
דפוסי שימוש
sessions שימושיים במיוחד עבור אלגוריתמים הדורשים תקשורת תכופה בין משאבים קלאסיים וקוונטיים.
דוגמה: הרצת עומס עבודה איטרטיבי המשתמש ב-optimizer הקלאסי SciPy למזעור פונקציית עלות. במודל זה, SciPy משתמש בפלט של פונקציית העלות כדי לחשב את הקלט הבא שלה.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
from scipy.optimize import minimize
from qiskit.circuit.library import efficient_su2
def cost_func(params, ansatz, hamiltonian, estimator):
# Return estimate of energy from estimator
energy = sum(
estimator.run([(ansatz, hamiltonian, params)]).result()[0].data.evs
)
return energy
hamiltonian = SparsePauliOp.from_list(
[("YZ", 0.3980), ("ZI", -0.3980), ("ZZ", -0.0113), ("XX", 0.1810)]
)
su2_ansatz = efficient_su2(hamiltonian.num_qubits)
pm = generate_preset_pass_manager(backend=backend, optimization_level=3)
ansatz = pm.run(su2_ansatz)
mapped_hamiltonian = [
operator.apply_layout(ansatz.layout) for operator in hamiltonian
]
num_params = ansatz.num_parameters
x0 = 2 * np.pi * np.random.random(num_params)
session = Session(backend=backend)
# If using qiskit-ibm-runtime earlier than 0.24.0, change `mode=` to `session=`
estimator = Estimator(mode=session, options={"default_shots": int(1e4)})
res = minimize(
cost_func,
x0,
args=(ansatz, mapped_hamiltonian, estimator),
method="cobyla",
options={"maxiter": 25},
)
# Close the session because no context manager was used.
session.close()
הרצת שני אלגוריתמי VQE ב-session באמצעות threading
אתה יכול להפיק יותר מ-session על ידי הרצת מספר עומסי עבודה בו-זמנית. הדוגמה הבאה מראה כיצד ניתן להריץ שני אלגוריתמי VQE, כל אחד משתמש ב-optimizer קלאסי שונה, בו-זמנית בתוך session יחיד. תגיות עבודה משמשות גם להבדיל בין עבודות משני עומסי עבודה.
The following code block will return an error for users on the Open Plan because it uses sessions. Workloads on the Open Plan can run only in job mode or batch mode.
from concurrent.futures import ThreadPoolExecutor
from qiskit_ibm_runtime import EstimatorV2 as Estimator
def minimize_thread(estimator, method):
return minimize(
cost_func,
x0,
args=(ansatz, mapped_hamiltonian, estimator),
method=method,
options={"maxiter": 25},
)
with Session(backend=backend), ThreadPoolExecutor() as executor:
estimator1 = Estimator()
estimator2 = Estimator()
# Use different tags to differentiate the jobs.
estimator1.options.environment.job_tags = ["cobyla"]
estimator2.options.environment.job_tags = ["nelder-mead"]
# Submit the two workloads.
cobyla_future = executor.submit(minimize_thread, estimator1, "cobyla")
nelder_mead_future = executor.submit(
minimize_thread, estimator2, "nelder-mead"
)
# Get workload results.
cobyla_result = cobyla_future.result()
nelder_mead_result = nelder_mead_future.result()
השלבים ה באים
- Try an example in the Quantum approximate optimization algorithm (QAOA) tutorial.
- Review the Session API reference.
- Understand the Job limits when sending a job to an IBM® QPU.
- Review execution modes FAQs.