세션 내에서 작업을 실행하다
이 페이지의 코드는 다음 요구 사항을 사용하여 개발되었습니다. 이 버전 또는 그 이상의 버전을 사용하는 것을 권장합니다.
qiskit[all]~=2.5.2 qiskit-ibm-runtime~=0.47.0 scipy~=1.17.1
QPU에 대한 전용 및 독점 액세스가 필요한 경우 세션을 사용하세요.
세션 사용 설정
세션을 시작하기 전에, IBM Quantum Compute 클라이언트를 설정하고 이를 서비스로 초기화해야 합니다:
from qiskit_ibm_runtime import (
QiskitRuntimeService,
Session,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
Executor,
)
service = QiskitRuntimeService()세션 열기
컨텍스트 관리자 with Session(...) 를 사용하여 런타임 세션을 열거나 Session 클래스를 초기화할 수 있습니다. 세션을 시작할 때 backend 객체를 전달하여 QPU를 지정해야 합니다. 세션은 첫 번째 작업이 실행되기 시작하면 시작됩니다.
세션을 열었지만 30분 동안 작업을 제출하지 않으면 세션이 자동으로 닫힙니다.
Session 클래스
backend = service.least_busy(operational=True, simulator=False)
session = Session(backend=backend)
estimator = Estimator(mode=session)
sampler = Sampler(mode=session)
executor = Executor(mode=session)
# Close the session because no context manager was used.
session.close()컨텍스트 관리자
컨텍스트 관리자가 세션을 자동으로 열고 닫습니다.
from qiskit_ibm_runtime import (
Session,
SamplerV2 as Sampler,
EstimatorV2 as Estimator,
Executor,
)
backend = service.least_busy(operational=True, simulator=False)
with Session(backend=backend):
estimator = Estimator()
sampler = Sampler()
executor = Executor()세션 길이
최대 세션 지속 시간(TTL)에 따라 세션이 실행될 수 있는 시간이 결정됩니다. 이 값은 max_time 파라미터로 설정할 수 있습니다. 이는 가장 긴 작업의 실행 시간을 초과해야 합니다.
이 타이머는 세션이 시작될 때 시작됩니다. 이 값에 도달하면 세션이 닫힙니다. 실행 중인 모든 작업은 완료되지만 여전히 대기 중인 작업은 실패합니다.
with Session(backend=backend, max_time="25m"):
...또한 구성할 수 없는 대화형 TTL(대화형 라이브 시간) 값도 있습니다. 해당 기간 내에 대기 중인 세션 작업이 없으면 세션이 일시적으로 비활성화됩니다.
기본값:
인스턴스 유형(오픈 또는 프리미엄 요금제) | 대화형 TTL | 최대 TTL |
|---|---|---|
| Premium 플랜 | 60초* | 8 h* |
| * 특정 프리미엄 요금제 인스턴스는 다른 값을 갖도록 구성될 수 있습니다. |
세션의 최대 TTL 또는 대화형 TTL을 확인하려면 세션 세부 정보 확인의 안내에 따라 각각 max_time또는 interactive_timeout 값을 찾습니다.
세션 종료
세션은 다음과 같은 상황에서 종료됩니다:
- 최대 시간 초과(TTL) 값에 도달하여 대기 중인 모든 작업이 취소됩니다.
- 세션이 수동으로 취소되어 대기 중인 모든 작업이 취소됩니다.
- 세션이 수동으로 닫힙니다. 세션은 새 작업 수락을 중지하지만 대기 중인 작업은 우선순위로 계속 실행합니다.
- 세션을 컨텍스트 관리자로 사용하는 경우, 즉
with Session(), 컨텍스트가 종료되면 세션이 자동으로 닫힙니다(session.close())를 사용하는 것과 동일한 동작).
세션 닫기
컨텍스트 관리자를 종료하면 세션이 자동으로 닫힙니다. 세션 컨텍스트 관리자가 종료되면 세션은 '진행 중, 새 작업 수락 안 함' 상태가 됩니다. 즉, 세션이 최대 시간 초과 값에 도달할 때까지 실행 중이거나 대기 중인 모든 작업의 처리를 완료합니다. 모든 작업이 완료되면 세션이 즉시 종료됩니다. 이렇게 하면 스케줄러가 세션 대화형 시간 초과를 기다리지 않고 다음 작업을 실행할 수 있으므로 평균 작업 대기 시간을 줄일 수 있습니다. 비공개 세션에는 작업을 제출할 수 없습니다.
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()컨텍스트 관리자를 사용하지 않는 경우에는 원치 않는 비용을 피하기 위해 세션을 수동으로 닫으세요. 세션에 작업 제출을 완료하면 바로 세션을 닫을 수 있습니다. session.close() 으로 세션을 닫으면 더 이상 새 작업을 수락하지 않지만 이미 제출된 작업은 완료될 때까지 계속 실행되며 그 결과를 검색할 수 있습니다.
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()Output:
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=156>), shape=(3, 2)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-09-01 08:34:17', stop='2026-09-01 08:34:24', size=24576>)])}, 'version': 2})
세션 상태 확인
session.status() 또는 워크로드 페이지를 통해 세션의 상태를 쿼리하여 현재 상태를 파악할 수 있습니다.
세션 상태는 다음 중 하나일 수 있습니다:
Pending: 세션이 시작되지 않았거나 비활성화되었습니다. 다음 세션 작업은 다른 작업과 마찬가지로 대기열에서 대기해야 합니다.In progress, accepting new jobs: 세션이 활성화되어 새 작업을 수락하고 있습니다.In progress, not accepting new jobs: 세션이 활성화되어 있지만 새 작업을 수락하지 않습니다. 세션에 대한 작업 제출은 거부되지만 미결 세션 작업은 완료될 때까지 실행됩니다. 모든 작업이 완료되면 세션이 자동으로 닫힙니다.Closed: 세션의 최대 시간 초과 값에 도달했거나 세션이 명시적으로 닫혔습니다.
세션 세부 정보 확인
세션의 구성 및 상태에 대한 종합적인 개요를 보려면 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())Output:
{'id': 'ff7977a5-ae7b-4509-9c84-bd1d7ff9f619', 'backend_name': 'ibm_marrakesh', '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}
사용 패턴
세션은 클래식 리소스와 양자 리소스 간의 빈번한 통신이 필요한 알고리즘에 특히 유용합니다.
예제: 기존 SciPy 최적화 프로그램을 사용하여 비용 함수를 최소화하는 반복 워크로드를 실행합니다. 이 모델에서 SciPy 은 비용 함수의 출력을 사용하여 다음 입력을 계산합니다.
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 알고리즘을 실행합니다
여러 워크로드를 동시에 실행하여 세션에서 더 많은 것을 얻을 수 있습니다. 다음 예는 각각 다른 클래식 옵티마이저를 사용하여 단일 세션 내에서 두 개의 VQE 알고리즘을 동시에 실행하는 방법을 보여줍니다. 작업 태그는 각 워크로드에서 작업을 구분하는 데도 사용됩니다.
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()다음 단계
- 퀀텀 근사 최적화 알고리즘(QAOA) 튜토리얼에서 예제를 사용해 보세요.
- 세션 API 참조를 검토하세요.
- IBM® QPU로 작업을 보낼 때 작업 제한을 이해합니다.
- 실행 모드 검토 FAQ