REST API를 사용한 실행 모드
패키지 버전
이 페이지의 코드는 다음 요구 사항을 바탕으로 개발되었습니다. 이 버전 이상을 사용하시기를 권장합니다.
qiskit[all]~=2.3.0
IBM Quantum 의 기본 워크로드는 필요에 따라 ‘작업(job)’, ‘세션(session)’, ‘배치(batch)’의 세 가지 실행 모드 중 하나를 선택하여 REST API를 통해 실행할 수 있습니다. 이 주제에서는 이러한 모드들에 대해 설명합니다.
이 문서는 Python requests 모듈을 사용하여 IBM Quantum Compute 서비스의 REST API를 설명합니다. 그러나 이 워크플로는 REST API 처리를 지원하는 모든 언어나 프레임워크를 사용하여 실행할 수 있습니다. 자세한 내용은 API 참조 문서를 참조하십시오.
REST API를 통한 작업 모드
작업 모드에서는 컨텍스트 매니저 없이 Estimator 또는 Sampler에 대한 단일 기본 요청이 수행됩니다. 예시를 보려면 Estimator 와 Sampler를 사용하여 양자 회로를 실행하는 방법을 확인해 보세요.
REST API를 통한 세션 모드
세션은 양자 컴퓨터에서 다중 작업 반복 워크로드를 효율적으로 실행할 수 있게 해주는 기능입니다. 세션을 사용하면 각 작업을 개별적으로 대기열에 넣는 데서 발생하는 지연을 피할 수 있으며, 이는 고전 리소스와 양자 리소스 간의 빈번한 통신이 필요한 반복적 작업에 특히 유용할 수 있습니다. 세션에 대한 자세한 내용은 설명서를 참조하십시오.
오픈 플랜 사용자는 세션 작업을 제출할 수 없습니다.
세션 시작
먼저 세션을 만들고 세션 ID를 얻습니다.
import json
import requests
sessionsUrl = "https://quantum.cloud.ibm.com/api/v1/sessions"
auth_id = "Bearer <YOUR_BEARER_TOKEN>"
backend = "<BACKEND_NAME>"
crn = "<SERVICE-CRN>"
headersList = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": auth_id,
"Service-CRN": crn
}
payload = json.dumps({
"backend": backend,
"mode": 'dedicated',
})
response = requests.request("POST", sessionsUrl, data=payload, headers=headersList)
sessionId = response.json()['id']
print(response.json())출력
{'id': 'crw9s7cdbt40008jxesg'}세션 닫기
모든 작업이 완료되면 Session 을 닫는 것이 좋습니다. 이렇게 하면 후속 사용자의 대기 시간이 줄어듭니다.
closureURL="https://quantum.cloud.ibm.com/api/v1/sessions/"+sessionId+"/close"
headersList = {
"Accept": "application/json",
"Authorization": auth_id,
"Service-CRN": crn
}
closure_response = requests.request(
"DELETE",
closureURL,
headers=headersList
)
print("Session closure response ok?:",closure_response.ok,closure_response.text)출력
Session closure response ok?: TrueREST API를 통한 배치 모드
또는 요청 페이로드에 mode 를 지정하여 배치 작업을 제출할 수 있습니다. 처음부터 모든 작업을 제공할 수 있다면 배치 모드를 사용하면 처리 시간을 단축하는 데 도움이 될 수 있습니다. 실행 모드 안내서의 ‘배치 모드’ 섹션에서 자세히 알아보세요.
import json
import requests
sessionsUrl = "https://quantum.cloud.ibm.com/api/v1/sessions"
headersList = {
"Accept": "application/json",
"Authorization": auth_id,
"Service-CRN": crn,
'Content-Type': 'application/json'
}
payload = json.dumps({
"backend": backend,
"instance": "hub1/group1/project1",
"mode": "batch"
})
response = requests.request("POST", sessionsUrl, data=payload, headers=headersList)
sessionId = response.json()['id']세션에 제출된 작업의 예시
세션이 설정되면 세션 ID를 지정하여 하나 이상의 샘플러 또는 추정기 작업을 동일한 세션에 제출할 수 있습니다.
PUB 의 <parameter values> 은 단일 매개변수이거나 매개변수 목록일 수 있습니다. numpy 방송도 지원합니다.
세션 모드에서의 추정기 작업
job_input = {
'program_id': 'estimator',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm, [obs1, obs2, obs3, obs4]]], #primitive unified blocs (PUBs) containing one circuit each.
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
}job_input = {
'program_id': 'estimator',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm, [[obs1], [obs2], [obs3], [obs4]], [[vals1], [vals2]]]], #primitive unified blocs (PUBs) containing one circuit each
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
} job_input = {
'program_id': 'estimator',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm, obs1],[resulting_qasm, obs2]], #primitive unified blocs (PUBs) containing one circuit each
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
}샘플러 작업의 세션 모드
job_input = {
'program_id': 'sampler',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm]], #primitive unified blocs (PUBs) containing one circuit each
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
}job_input = {
'program_id': 'sampler',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm, [vals1, vals2, vals3]]], #primitive unified blocs (PUBs) containing one circuit each
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
} job_input = {
'program_id': 'sampler',
"backend": backend,
"session_id": sessionId, # This specifies the previously created Session
"params": {
"pubs": [[resulting_qasm, [val1]],[resulting_qasm,None,100]], #primitive unified blocs (PUBs) containing one circuit each
"options":{
"transpilation":{"optimization_level": 1},
"twirling": {"enable_gates": True,"enable_measure": True},
# "dynamical_decoupling": {"enable": True, "sequence_type": "XpXm"}, #(optional)
},
}
}