첫 번째 Qiskit Serverless 프로그램 작성하기
Package versions
이 페이지의 코드는 다음 요구 사항을 사용하여 개발되었습니다. 이 버전 이상을 사용하길 권장합니다.
qiskit[all]~=1.3.1
qiskit-ibm-runtime~=0.34.0
qiskit-aer~=0.15.1
qiskit-serverless~=0.18.1
qiskit-ibm-catalog~=0.2
qiskit-addon-sqd~=0.8.1
qiskit-addon-utils~=0.1.0
qiskit-addon-mpf~=0.2.0
qiskit-addon-aqc-tensor~=0.1.2
qiskit-addon-obp~=0.1.0
scipy~=1.15.0
pyscf~=2.8.0
Qiskit Serverless가 업그레이드 중이며, 기능이 빠르게 변화하고 있습니다. 이 개발 단계 동안 릴리스 노트와 최신 문서는 Qiskit Serverless GitHub 페이지에서 확인하세요.
이 예제는 qiskit-serverless 도구를 사용하여 병렬 트랜스파일 프로그램을 생성하고, qiskit-ibm-catalog를 구현하여 프로그램을 IBM Quantum Platform에 업로드함으로써 재사용 가능한 원격 서비스로 활용하는 방법을 설명합니다.
워크플로우 개요
- 로컬 디렉토리와 빈 프로그램 파일(
./source_files/transpile_remote.py) 생성 - 업로드 시 Qiskit Serverless에서 회로를 트랜스파일할 코드를 프로그램에 추가
qiskit-ibm-catalog를 사용하여 Qiskit Serverless에 인증- Qiskit Serverless에 프로그램 업로드
프로그램을 업로드한 후에는 첫 번째 Qiskit Serverless 워크로드를 원격으로 실행하기 가이드를 따라 회로를 트랜스파일하도록 실행할 수 있습니다.
# Added by doQumentation — required packages for this notebook
!pip install -q qiskit qiskit-ibm-catalog qiskit-ibm-runtime qiskit-serverless
예제: Qiskit Serverless를 이용한 원격 트랜스파일
이 예제는 Qiskit Serverless에 업로드할 때 주어진 backend와 대상 optimization_level에 대해 circuit을 트랜스파일하는 프로그램 파일을 만들고 내용을 추가하는 과정을 안내합니다.
Qiskit Serverless를 사용하려면 워크로드의 .py 파일을 전용 디렉토리에 설정해야 합니다. 다음 구조는 모범 사례의 예시입니다:
serverless_program
├── program_uploader.ipynb
└── source_files
├── transpile_remote.py
└── *.py
Serverless는 특정 디렉토리(이 예제에서는 source_files 디렉토리)의 내용을 업로드하여 원격으로 실행합니다. 설정이 완료되면 transpile_remote.py를 수정하여 입력을 가져오고 출력을 반환할 수 있습니다.
디렉토리와 빈 프로그램 파일 생성
먼저 source_files라는 디렉토리를 만든 다음, 디렉토리에 프로그램 파일을 생성하여 경로가 ./source_files/transpile_remote.py가 되도록 합니다. 이 파일이 Qiskit Serverless에 업로드할 파일입니다.
프로그램 파일에 코드 추가하기
다음 코드로 프로그램 파일을 채운 다음 저장합니다.
노트북에서 코드 셀을 로컬로 읽는 경우 %%writefile 매직 명령이 표시됩니다. 이 매직 명령이 포함된 셀을 실행하면 실행되는 대신 디스크에 저장됩니다.
# This cell is hidden from users, it creates a new folder
from pathlib import Path
Path("./source_files").mkdir(exist_ok=True)
%%writefile ./source_files/transpile_remote.py
# If you include the preceding `%%writefile` command (visible only when you read this
# locally in a notebook), running this cell saves to disk rather than executing the code.
from qiskit.transpiler import generate_preset_pass_manager
def transpile_remote(circuit, optimization_level, backend):
"""Transpiles an abstract circuit into an ISA circuit for a given backend."""
pass_manager = generate_preset_pass_manager(
optimization_level=optimization_level,
backend=backend
)
isa_circuit = pass_manager.run(circuit)
return isa_circuit
프로그램 인수를 가져오는 코드 추가하기
이제 다음 코드를 프로그램 파일에 추가합니다. 이 코드는 프로그램 인수를 설정합니다.
초기 transpile_remote.py에는 circuits, backend_name, optimization_level 세 가지 입력이 있습니다. Serverless는 현재 직렬화 가능한 입력 및 출력만 허용하도록 제한되어 있습니다. 이러한 이유로 backend를 직접 전달할 수 없으므로, 대신 backend_name을 문자열로 사용합니다.
%%writefile --append ./source_files/transpile_remote.py
# If you include the preceding `%%writefile` command (visible only when you read this
# locally in a notebook), running this cell saves to disk rather than executing the code.
from qiskit_serverless import get_arguments, save_result, distribute_task, get
# Get program arguments
arguments = get_arguments()
circuits = arguments.get("circuits")
backend_name = arguments.get("backend_name")
optimization_level = arguments.get("optimization_level")
백엔드를 호출하는 코드 추가하기
다음 코드를 프로그램 파일에 추가합니다. 이 코드는 QiskitRuntimeService를 사용하여 백엔드를 호출합니다.
아래 코드는 QiskitRuntimeService.save_account를 사용하여 자격 증명을 저장하는 과정을 이미 완료했다고 가정하며, 별도로 지정하지 않는 한 기본으로 저장된 계정을 불러옵니다. 자세한 내용은 로그인 자격 증명 저장 및 Qiskit Runtime 서비스 계정 초기화를 참고하세요.
%%writefile --append ./source_files/transpile_remote.py
# If you include the preceding `%%writefile` command (visible only when you read this
# locally in a notebook), running this cell saves to disk rather than executing the code.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend(backend_name)
트랜스파일 코드 추가하기
마지막으로, 다음 코드를 프로그램 파일에 추가합니다. 이 코드는 전달된 모든 circuits에 대해 transpile_remote()를 실행하고 transpiled_circuits를 결과로 반환합니다.
%%writefile --append ./source_files/transpile_remote.py
# If you include the preceding `%%writefile` command (visible only when you read this
# locally in a notebook), running this cell saves to disk rather than executing the code.
# Each circuit is being transpiled and will populate the array
results = [
transpile_remote(circuit, 1, backend)
for circuit in circuits
]
save_result({
"transpiled_circuits": results
})
Qiskit Serverless에 인증하기
qiskit-ibm-catalog를 사용하여 API 키로 QiskitServerless에 인증합니다(QiskitRuntimeService API 키를 사용하거나 IBM Quantum Platform 대시보드에서 새 API 키를 생성할 수 있습니다).
from qiskit_ibm_catalog import QiskitServerless, QiskitFunction
# Authenticate to the remote cluster and submit the pattern for remote execution
serverless = QiskitServerless()
업로드 코드 실행하기
다음 코드를 실행하여 프로그램을 업로드합니다. Qiskit Serverless는 working_dir의 내용(이 경우 source_files)을 tar로 압축하여 업로드한 다음 정리합니다. entrypoint는 Qiskit Serverless가 실행할 기본 프로그램 실행 파일을 식별합니다.
transpile_remote_demo = QiskitFunction(
title="transpile_remote_serverless",
entrypoint="transpile_remote.py",
working_dir="./source_files/",
)
serverless.upload(transpile_remote_demo)
QiskitFunction(transpile_remote_serverless)
업로드 확인하기
업로드가 성공적으로 완료되었는지 확인하려면 다음 코드와 같이 serverless.list()를 사용합니다.
# Get program from serverless.list() that matches the title of the one we uploaded
next(
program
for program in serverless.list()
if program.title == "transpile_remote_serverless"
)
QiskitFunction(transpile_remote_serverless)
# This cell is hidden from users, it checks the program uploaded correctly
assert _.title == "transpile_remote_serverless" # noqa: F821
# This cell is hidden from users, it checks the program executes correctly
from time import sleep
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
transpile_remote_serverless = serverless.load("transpile_remote_serverless")
job = transpile_remote_serverless.run(
circuits=[qc],
backend="ibm_sherbrooke",
optimization_level=1,
)
while True:
sleep(5)
status = job.status()
if status not in ["QUEUED", "INITIALIZING", "RUNNING", "DONE"]:
raise Exception(
f"Unexpected job status: '{status}'\n"
+ "Here are the logs:\n"
+ job.logs()
)
if status == "DONE":
break
다음 단계
- 첫 번째 Qiskit Serverless 워크로드를 원격으로 실행하기 항목에서 입력을 전달하고 프로그램을 원격으로 실행하는 방법을 알아보세요.