Skip to content

Commit

Permalink
Copy over provider session & remove qiskit-ibm-provider (#1368)
Browse files Browse the repository at this point in the history
* Move provider's session & remove qiskit-ibm-provider

* fix black
  • Loading branch information
kt474 authored Feb 5, 2024
1 parent f4d2853 commit bf33ce8
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 5 deletions.
2 changes: 1 addition & 1 deletion qiskit_ibm_runtime/base_primitive.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from qiskit.providers.options import Options as TerraOptions

from qiskit_ibm_provider.session import get_cm_session as get_cm_provider_session
from .provider_session import get_cm_session as get_cm_provider_session

from .options import Options
from .options.utils import set_default_error_levels
Expand Down
4 changes: 2 additions & 2 deletions qiskit_ibm_runtime/ibm_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@
from qiskit.transpiler.target import Target

# temporary until we unite the 2 Session classes
from qiskit_ibm_provider.session import (
from .provider_session import (
Session as ProviderSession,
) # temporary until we unite the 2 Session classes
)

from .utils.utils import validate_job_tags
from . import qiskit_runtime_service # pylint: disable=unused-import,cyclic-import
Expand Down
132 changes: 132 additions & 0 deletions qiskit_ibm_runtime/provider_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Qiskit Runtime flexible session."""

from typing import Optional, Type, Union
from types import TracebackType
from contextvars import ContextVar

from .utils.converters import hms_to_seconds


class Session:
"""Class for creating a flexible Qiskit Runtime session.
A Qiskit Runtime ``session`` allows you to group a collection of iterative calls to
the quantum computer. A session is started when the first job within the session
is started. Subsequent jobs within the session are prioritized by the scheduler.
Data used within a session, such as transpiled circuits, is also cached to avoid
unnecessary overhead.
You can open a Qiskit Runtime session using this ``Session`` class
and submit one or more jobs.
For example::
from qiskit.test.reference_circuits import ReferenceCircuits
from qiskit_ibm_runtime import QiskitRuntimeService
circ = ReferenceCircuits.bell()
backend = QiskitRuntimeService().get_backend("ibmq_qasm_simulator")
backend.open_session()
job = backend.run(circ)
print(f"Job ID: {job.job_id()}")
print(f"Result: {job.result()}")
# Close the session only if all jobs are finished and
# you don't need to run more in the session.
backend.cancel_session()
Session can also be used as a context manager::
with backend.open_session() as session:
job = backend.run(ReferenceCircuits.bell())
"""

def __init__(
self,
max_time: Optional[Union[int, str]] = None,
):
"""Session constructor.
Args:
max_time: (EXPERIMENTAL setting, can break between releases without warning)
Maximum amount of time, a runtime session can be open before being
forcibly closed. Can be specified as seconds (int) or a string like "2h 30m 40s".
This value must be in between 300 seconds and the
`system imposed maximum
<https://qiskit.org/documentation/partners/qiskit_ibm_runtime/faqs/max_execution_time.html>`_.
Raises:
ValueError: If an input value is invalid.
"""
self._instance = None
self._session_id: Optional[str] = None
self._active = True

self._max_time = (
max_time
if max_time is None or isinstance(max_time, int)
else hms_to_seconds(max_time, "Invalid max_time value: ")
)

@property
def session_id(self) -> str:
"""Return the session ID.
Returns:
Session ID. None until a job runs in the session.
"""
return self._session_id

@property
def active(self) -> bool:
"""Return the status of the session.
Returns:
True if the session is active, False otherwise.
"""
return self._active

def cancel(self) -> None:
"""Set the session._active status to False"""
self._active = False

def __enter__(self) -> "Session":
set_cm_session(self)
return self

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
set_cm_session(None)


# Default session
_DEFAULT_SESSION: ContextVar[Optional[Session]] = ContextVar("_DEFAULT_SESSION", default=None)
_IN_SESSION_CM: ContextVar[bool] = ContextVar("_IN_SESSION_CM", default=False)


def set_cm_session(session: Optional[Session]) -> None:
"""Set the context manager session."""
_DEFAULT_SESSION.set(session)
_IN_SESSION_CM.set(session is not None)


def get_cm_session() -> Session:
"""Return the context managed session."""
return _DEFAULT_SESSION.get()
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@ python-dateutil>=2.8.0
websocket-client>=1.5.1
typing-extensions>=4.0.0
ibm-platform-services>=0.22.6
qiskit-ibm-provider>=0.8.0
1 change: 0 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
"python-dateutil>=2.8.0",
"websocket-client>=1.5.1",
"ibm-platform-services>=0.22.6",
"qiskit-ibm-provider>=0.8.0",
]

# Handle version.
Expand Down

0 comments on commit bf33ce8

Please sign in to comment.