Run jobs in a session
Use sessions when you need dedicated and exclusive access to the QPU.
Session execution mode is not supported in the Open Plan. Jobs will run in job mode instead.
Set up to use sessions
Before starting a session, you must set up Qiskit Runtime and initialize it as a service:
from qiskit_ibm_runtime import QiskitRuntimeService, Session, SamplerV2 as Sampler, EstimatorV2 as Estimator
service = QiskitRuntimeService()
Open a session
You can open a runtime session by using the context manager with Session(...)
or by initializing the Session
class. When you start a session, you must specify a QPU by passing a backend
object. The session starts when its first job begins execution.
If you open a session but do not submit any jobs to it for 30 minutes, the session automatically closes.
Session class
from qiskit_ibm_runtime import Session, SamplerV2 as Sampler, EstimatorV2 as Estimator
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()
Context manager
The context manager automatically opens and closes the session.
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 length
The maximum session time to live (TTL) determines how long a session can run. You can set this value with the max_time
parameter. This should exceed the longest job's execution time.
This timer starts when the session starts. When the value is reached, the session is closed. Any jobs that are running will finish, but jobs still queued are failed.
with Session(backend=backend, max_time="25m"):
...
There is also an interactive time to live (interactive TTL) value that cannot be configured. If no session jobs are queued within that window, the session is temporarily deactivated.
Default values:
Instance type (Open or Premium Plan) | Interactive TTL | Maximum TTL |
---|---|---|
Premium Plan | 60 sec* | 8 h* |
Open Plan | sessions run in job mode | sessions run in job mode |
* Certain Premium Plan instances might be configured to have a different value.
To determine a session's max TTL or interactive TTL, follow the instructions in Determine session details and look for the max_time
or interactive_timeout
value, respectively.
End a session
A session ends in the following circumstances:
- The maximum timeout (TTL) value is reached, resulting in the cancellation of all queued jobs.
- The session is manually canceled, resulting in the cancellation of all queued jobs.
- The session is manually closed. The session stops accepting new jobs but continues to run queued jobs with priority.
- If you use Session as a context manager, that is,
with Session()
, the session is automatically closed when the context ends (the same behavior as usingsession.close()
).
Close a session
A session automatically closes when it exits the context manager. When the session context manager is exited, the session is put into "In progress, not accepting new jobs" status. This means that the session finishes processing all running or queued jobs until the maximum timeout value is reached. After all jobs are completed, the session is immediately closed. This allows the scheduler to run the next job without waiting for the session interactive timeout, thereby reducing the average job queuing time. You cannot submit jobs to a closed session.
with Session(backend=backend) as session:
estimator = Estimator()
job1 = estimator.run(...)
job2 = estimator.run(...)
# 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.
session = Session(backend=backend)
# If using qiskit-ibm-runtime earlier than 0.24.0, change `mode=` to `session=`
estimator = Estimator(mode=session)
job1 = estimator.run(...)
job2 = estimator.run(...)
print(f"Result1: {job1.result()}")
print(f"Result2: {job2.result()}")
# Manually close the session. Running and queued jobs will run to completion.
session.close()
Check session status
You can query a session's status to understand its current state by using session.status()
or by viewing the Jobs page for your channel.
Session status can be one of the following:
Pending
: The session has not started or has been deactivated. The next session job needs to wait in the queue like other jobs.In progress, accepting new jobs
: The session is active and accepting new jobs.In progress, not accepting new jobs
: The session is active but not accepting new jobs. Job submission to the session is rejected, but outstanding session jobs will run to completion. The session is automatically closed once all jobs finish.Closed
: The session's maximum timeout value has been reached or the session was explicitly closed.
Determine session details
For a comprehensive overview of a session's configuration and status, use the session.details() method
.
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())
Usage patterns
Sessions are especially useful for algorithms that require frequent communication between classical and quantum resources.
Example: Run an iterative workload that uses the classical SciPy optimizer to minimize a cost function. In this model, SciPy uses the output of the cost function to calculate its next input.
def cost_func(params, ansatz, hamiltonian, estimator):
# Return estimate of energy from estimator
energy = estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0]
return energy
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={"shots": int(1e4)})
res = minimize(cost_func, x0, args=(ansatz, hamiltonian, estimator), method="cobyla")
# Close the session because no context manager was used.
session.close()
Run two VQE algorithms in a session by using threading
You can get more out of a session by running multiple workloads simultaneously. The following example shows how you can run two VQE algorithms, each using a different classical optimizer, simultaneously inside a single session. Job tags are also used to differentiate jobs from each workload.
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, hamiltonian, estimator), method=method)
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()
Next steps
- 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.