Scrivi il tuo primo programma Qiskit Serverless
Versioni dei pacchetti
Il codice in questa pagina è stato sviluppato utilizzando i seguenti requisiti. Si consiglia di usare queste versioni o versioni più recenti.
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 è in fase di aggiornamento e le sue funzionalità stanno cambiando rapidamente. Durante questa fase di sviluppo, trovi le note di rilascio e la documentazione più recente nella pagina GitHub di Qiskit Serverless.
Questo esempio mostra come usare gli strumenti di qiskit-serverless per creare un programma di transpilazione parallela, e come poi utilizzare qiskit-ibm-catalog per caricare il tuo programma su IBM Quantum Platform e usarlo come servizio remoto riutilizzabile.
Panoramica del flusso di lavoro​
- Crea una directory locale e un file di programma vuoto (
./source_files/transpile_remote.py) - Aggiungi codice al tuo programma che, una volta caricato su Qiskit Serverless, eseguirà la transpilazione di un circuito
- Usa
qiskit-ibm-catalogper autenticarti su Qiskit Serverless - Carica il programma su Qiskit Serverless
Dopo aver caricato il tuo programma, puoi eseguirlo per traspilare il circuito seguendo la guida Esegui il tuo primo workload Qiskit Serverless in remoto.
# Added by doQumentation — required packages for this notebook
!pip install -q qiskit qiskit-ibm-catalog qiskit-ibm-runtime qiskit-serverless
Esempio: transpilazione remota con Qiskit Serverless​
Questo esempio ti guida nella creazione e nel completamento di un file di programma che, una volta caricato su Qiskit Serverless, transpilerà un circuit su un determinato backend e con un optimization_level target.
Qiskit Serverless richiede che i file .py del tuo workload siano organizzati in una directory dedicata. La struttura seguente è un esempio di buona pratica:
serverless_program
├── program_uploader.ipynb
└── source_files
├── transpile_remote.py
└── *.py
Serverless carica i contenuti di una directory specifica (in questo esempio, la directory source_files) per eseguirli in remoto. Una volta configurati, puoi modificare transpile_remote.py per recuperare gli input e restituire gli output.
Crea la directory e un file di programma vuoto​
Per prima cosa, crea una directory chiamata source_files, poi crea un file di programma nella directory in modo che il suo percorso sia ./source_files/transpile_remote.py. Questo è il file che caricherai su Qiskit Serverless.
Aggiungi codice al file di programma​
Popola il file di programma con il codice seguente, poi salvalo.
Se stai leggendo le celle di codice localmente in un notebook, vedrai il magic command %%writefile. L'esecuzione di celle con questo magic command le salva su disco anziché eseguirle.
# 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
Aggiungi codice per ottenere gli argomenti del programma​
Aggiungi ora il seguente codice al file di programma, che configura gli argomenti del programma.
Il tuo transpile_remote.py iniziale ha tre input: circuits, backend_name e optimization_level. Serverless al momento accetta solo input e output serializzabili. Per questo motivo non puoi passare backend direttamente, quindi usa backend_name come stringa.
%%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")
Aggiungi codice che chiama il backend​
Aggiungi il seguente codice al file di programma, che chiama il tuo backend con QiskitRuntimeService.
Il codice seguente presuppone che tu abbia già seguito la procedura per salvare le credenziali usando QiskitRuntimeService.save_account, e caricherà il tuo account salvato predefinito a meno che non specifichi diversamente. Consulta Salva le credenziali di accesso e Inizializza il tuo account del servizio Qiskit Runtime per maggiori informazioni.
%%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)
Aggiungi codice per la transpilazione​
Infine, aggiungi il seguente codice al file di programma. Questo codice esegue transpile_remote() su tutti i circuits passati e restituisce i transpiled_circuits come risultato:
%%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
})
Autenticati su Qiskit Serverless​
Usa qiskit-ibm-catalog per autenticarti su QiskitServerless con la tua chiave API (puoi usare la tua chiave API di QiskitRuntimeService, oppure creare una nuova chiave API sul pannello di IBM Quantum Platform).
from qiskit_ibm_catalog import QiskitServerless, QiskitFunction
# Authenticate to the remote cluster and submit the pattern for remote execution
serverless = QiskitServerless()
Esegui il codice per caricare​
Esegui il codice seguente per caricare il programma. Qiskit Serverless comprime i contenuti di working_dir (in questo caso, source_files) in un archivio tar, che viene caricato e poi rimosso. L'entrypoint identifica il file eseguibile principale che Qiskit Serverless deve eseguire.
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)
Verifica il caricamento​
Per verificare che il caricamento sia andato a buon fine, usa serverless.list(), come nel codice seguente:
# 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
Passi successivi​
- Scopri come passare input ed eseguire il tuo programma in remoto nell'argomento Esegui il tuo primo workload Qiskit Serverless in remoto.