メインコンテンツへスキップ

Qiskit Functionsを始める

# Added by doQumentation — required packages for this notebook
!pip install -q qiskit qiskit-ibm-catalog qiskit-ibm-runtime
# This cell is hidden from users
# It gets these details programmatically so we can test this notebook
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.circuit.random import random_circuit
from qiskit_ibm_catalog import QiskitFunctionsCatalog

service = QiskitRuntimeService()
instance = service.active_account()["instance"]
backend_name = service.least_busy().name
catalog = QiskitFunctionsCatalog(channel="ibm_quantum_platform")
qesem_function = catalog.load("qedma/qesem")
circuit = random_circuit(num_qubits=2, depth=2, seed=42)
observable = "Z" * circuit.num_qubits

Premium、Flex、および On-Prem(IBM Quantum Platform API 経由)プランのユーザーは、IBM Qiskit Functions を無料で利用開始できます。または、カタログに関数を提供しているパートナーからライセンスを購入することもできます。

サードパーティの Qiskit Functions の無料トライアルをリクエストする

無料トライアルをリクエストするには、Qiskit Functions カタログ に移動し、詳細パネルを確認します。Request a free trial をクリックし、IBM Cloud の AccessGroupId を含む、Functions パートナーが必要とする情報を入力します。

  1. IBM Cloud IAM に移動します。

  2. 適格性を確認します。

    • ヘッダーのメニューバーで、アカウントを次の形式のものに切り替えます: XXXXXXX - [Organization Name]

    • その組織が、お使いの Premium アカウントに関連付けられている組織と同じであることを確認します。

    • 「[Your Name]'s Account」と表示されている場合は、個人用 アカウントを使用しており、Premium アクセスの対象外です。

  3. アクセス・グループ ID を確認します。

    • グループ名をクリックします。

    • Details をクリックします。

    • アクセス・グループ ID をコピーします。AccessGroup- で始まっているはずです。

Qiskit Functions カタログ・クライアントをインストールする

  1. Qiskit Functions の使用を開始するには、IBM Qiskit Functions カタログ・クライアントをインストールします:

    pip install qiskit-ibm-catalog
  2. IBM Quantum Platform ダッシュボード から API キーを取得し、Python 仮想環境を有効化します。仮想環境をまだセットアップしていない場合は、インストール手順 を参照してください。

    If you are working in a trusted Python environment (such as on a personal laptop or workstation), use the save_account() method to save your credentials locally. (Skip to the next step if you are not using a trusted environment, such as a shared or public computer, to authenticate to IBM Quantum Platform.)

認証に使用するインスタンスでは、Qiskit Functionsへのアクセスが有効になっている必要があります。既存のインスタンスでこれを設定するには、インスタンスでQiskit Functionsアクセスを設定するを参照してください。

save_account() を使用するには、シェルで python を実行し、以下を入力します:

from qiskit_ibm_catalog import QiskitFunctionsCatalog

QiskitFunctionsCatalog.save_account(channel="ibm_quantum_platform", token="<your-token>", instance="<instance-crn>")

exit() と入力します。今後、サービスへの認証が必要になったときは、以下のコードで認証情報を読み込むことができます:

from qiskit_ibm_catalog import QiskitFunctionsCatalog
catalog = QiskitFunctionsCatalog()

例:

# Load saved credentials
from qiskit_ibm_catalog import QiskitFunctionsCatalog

catalog = QiskitFunctionsCatalog(channel="ibm_quantum_platform")

Avoid executing code on an untrusted machine or an external cloud Python environment to minimize security risks. If you must use an untrusted environment (on, for example, a public computer), change your API key after each use by deleting it on the IBM Cloud API keys page to reduce risk. Learn more in the Managing user API keys topic. To initialize the service in this situation, use this code:

from qiskit_ibm_catalog import QiskitFunctionsCatalog

# After using the following code, delete your API key on the
# IBM Quantum Platform home dashboard
catalog = QiskitFunctionsCatalog(token="<YOUR_API_KEY>") # Use the 44-character
# API_KEY you created and saved from the IBM Quantum Platform Home dashboard
API キーを保護する

API キーをソースコード、Python スクリプト、またはノートブック・ファイルに含めないでください。 コードを他の人と共有する場合は、API キーが Python スクリプト内に直接埋め込まれていないことを確認してください。代わりに、キーを含まないスクリプトを共有し、安全に設定するための手順を提供してください。

誤ってキーを他の人と共有してしまったり、Git などのバージョン管理に含めてしまったりした場合は、リスクを減らすために、IBM Cloud API キー ページで直ちにキーを削除して無効化してください。詳細については、ユーザー API キーの管理 のトピックを参照してください。

アクセス可能な関数を一覧表示する

認証後、アクセス可能な Qiskit Functions カタログの関数を一覧表示できます:

catalog.list()
[QiskitFunction(qunova/hivqe-chemistry),
QiskitFunction(global-data-quantum/quantum-portfolio-optimizer),
QiskitFunction(algorithmiq/tem),
QiskitFunction(qedma/qesem),
QiskitFunction(multiverse/singularity),
QiskitFunction(ibm/circuit-function),
QiskitFunction(q-ctrl/optimization-solver),
QiskitFunction(colibritd/quick-pde),
QiskitFunction(q-ctrl/performance-management),
QiskitFunction(kipu-quantum/iskay-quantum-optimizer)]

有効な関数を実行する

カタログ・オブジェクトがインスタンス化された後は、catalog.load("<provider/function-name>") を使用して関数を選択できます:

qesem_function = catalog.load("qedma/qesem")

各 Qiskit Function には、カスタムの入力、オプション、出力があります。詳細については、実行したい関数の特定のドキュメント・ページを確認してください。デフォルトでは、すべてのユーザーは一度に1つの関数ジョブしか実行できません:

from qiskit.quantum_info import SparsePauliOp

avg_magnetization = SparsePauliOp.from_sparse_list(
[("Z", [q], 1 / 5) for q in range(5)], num_qubits=5
)

job = qesem_function.run(
pubs=[(circuit, [avg_magnetization, observable])],
backend_name=backend_name, # example: "ibm_fez"
# options = {
# "estimate_time_only": "empirical",
# "default_precision": 0.2, # Default precision is applied to all pubs that don't have a precision specified, see API reference for more details
# "max_execution_time": 3600, # You can specify a maximum QPU time in seconds, see API reference for more details
# "transpilation_level": "standard", # "minimal_with_layout_opt" for minimal transpilation, see API reference for more details
# "parallel_execution": True, # True for parallel execution, see API reference for more details
# },
)
job.job_id
'7f08c9d5-471b-4da2-92e7-4f2cb94c23a8'
ヒント

run() は、ジョブを送信する前に、残りのキャパシティと Backend へのアクセスを確認します。インスタンスのキャパシティが不足している場合、または指定した Backend にアクセスできない場合、run() はジョブをキューで失敗させたままにするのではなく、即座にエラーを発生させます。キャパシティが少ない場合、run() は警告を出します。これを表示させないようにするには、suppress_low_usage_warning=True を渡します。

job = qesem_function.run(
pubs=[(circuit, [avg_magnetization, observable])],
backend_name=backend_name, # example: "ibm_fez"
suppress_low_usage_warning=True,
# options = {
# "estimate_time_only": "empirical",
# "default_precision": 0.2, # Default precision is applied to all pubs that don't have a precision specified, see API reference for more details
# "max_execution_time": 3600, # You can specify a maximum QPU time in seconds, see API reference for more details
# "transpilation_level": "standard", # "minimal_with_layout_opt" for minimal transpilation, see API reference for more details
# "parallel_execution": True, # True for parallel execution, see API reference for more details
# },
)

ジョブのステータスを確認する

Qiskit Function の job_id を使用すると、実行中のジョブのステータスを確認できます。これには以下のステータスが含まれます:

  • QUEUED: リモート・プログラムが Qiskit Function のキューに入っています。キューの優先順位は、Qiskit Functions の使用量に基づいて決まります。

  • INITIALIZING: リモート・プログラムが開始しています。これには、リモート環境のセットアップと依存関係のインストールが含まれます。

  • RUNNING: プログラムが実行中です。特定の関数でサポートされている場合、より詳細ないくつかのステータスも含まれます。

    • RUNNING: MAPPING: 関数が古典入力を量子入力にマッピングしています。

    • RUNNING: OPTIMIZING_FOR_HARDWARE: 関数が選択した QPU 向けに最適化しています。これには、回路のトランスパイル、QPU の特性評価、オブザーバブルの逆伝播などが含まれる場合があります。

    • RUNNING: WAITING_FOR_QPU: 関数が IBM Quantum Compute Service にジョブを送信し、キューで待機しています。

    • RUNNING: EXECUTING_QPU: 関数にアクティブな Quantum Compute ジョブがあります。

    • RUNNING: POST_PROCESSING: 関数が結果を後処理しています。これには、エラー緩和や量子結果の古典への変換などが含まれる場合があります。

  • DONE: プログラムが完了しており、job.result() で結果データを取得できます。

  • ERROR: 問題が発生したためプログラムの実行が停止しました。エラーメッセージを取得するには job.result() を使用します。

  • CANCELED: プログラムがユーザー、サービス、またはサーバーによってキャンセルされました。

job.status()
'QUEUED'

結果を取得する

プログラムが DONE になったら、job.result() を使用して結果を取得できます。この出力形式は関数ごとに異なるため、必ず該当のドキュメントに従ってください:

result = job.result()
print(result)
PrimitiveResult([PubResult(data=DataBin(evs=np.ndarray(<shape=(), dtype=float64>), stds=np.ndarray(<shape=(), dtype=float64>), ensemble_standard_error=np.ndarray(<shape=(), dtype=float64>)), metadata={'shots': 4096, 'target_precision': 0.015625, 'circuit_metadata': {}, 'resilience': {}, 'num_randomizations': 32})], metadata={'dynamical_decoupling': {'enable': True, '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})

また、いつでもジョブをキャンセルできます:

job.cancel()
'Job has been stopped.'

関連する Quantum Compute ジョブにアクセスする

Qiskit Function は実行中に、1つ以上の Quantum Compute ジョブを QPU に送信できます。それらのランタイム・ジョブの ID を取得するには、job.runtime_jobs() を使用します。これらの ID を使用して、QiskitRuntimeService インスタンスからランタイム・ジョブ・オブジェクトを取得したり、IBM Quantum® Platform ダッシュボードでワークロードを見つけたりできます。

runtime_job_ids = job.runtime_jobs()
runtime_job_ids

関数がランタイム・ジョブを Session やバッチにグループ化する場合は、job.runtime_sessions() を使用して Session ID を一覧表示します。1つの Session ID を job.runtime_jobs() に渡すと、その Session 内のランタイム・ジョブのみが返されます:

sessions = job.runtime_sessions()
if sessions:
session_runtime_jobs = job.runtime_jobs(runtime_session=sessions[0])
print(session_runtime_jobs)
else:
print("No runtime sessions for this job.")
備考

返されるリストは空の場合があります。ファンクションは、実行時に受け取るランタイムサービスを通じてジョブを送信した場合にのみそのランタイムジョブを報告します。また、一部のファンクションはランタイムジョブを直接送信しません。

ジョブ・ログを表示する

関数が実行中に生成するログ出力を取得するには、job.logs() を使用します。ログは、進捗の追跡や、ERROR 状態で終了したジョブのデバッグに役立ちます。

print(job.logs().splitlines())

多くのログ行を生成する長時間実行のジョブでは、job.filtered_logs() を使用して必要な行のみを取得できます。一致する行を残すには正規表現を include に渡し、一致する行を除外するには exclude に渡します:

print(job.filtered_logs(include="iteration"))

以前に実行した Qiskit Functions ジョブを一覧表示する

jobs() を使用すると、Qiskit Functions に送信されたすべてのジョブを一覧表示できます:

old_jobs = catalog.jobs()
old_jobs
[<Job | f6c29f49-4d5f-4fff-aca6-2e9a115b9763>,
<Job | 7f08c9d5-471b-4da2-92e7-4f2cb94c23a8>,
<Job | 62fe9176-d1e5-467e-b2bd-7a3f3c7be4e5>,
<Job | af525b2e-16b1-45a1-80bb-dbd94ce30258>,
<Job | b95a7a57-c1ad-4958-b7ac-953e4e1ee824>,
<Job | 7bfa33da-0f17-4e67-84b6-f556f7eeb436>,
<Job | ca46c191-9eb9-4de6-bfa7-b60d7eb29b5e>,
<Job | 6ac0ba93-3831-43fb-9fb9-760da2225e06>,
<Job | f0e38071-060d-47e8-988d-9cc1f69358e3>,
<Job | 629cf110-e490-4675-8a07-f6d298d166b0>]

結果を絞り込むには、フィルターを渡します。関数でフィルタリングするには function、ステータスでフィルタリングするには status、送信日でフィルタリングするには created_after を使用します。結果をページ分割するには limitoffset を使用します:

recent_errors = catalog.jobs(
function=qesem_function,
status="ERROR",
created_after="2024-01-01T00:00:00Z",
limit=5,
)
recent_errors

特定のジョブの ID をすでに持っている場合は、catalog.job() でそのジョブを取得できます:

# First, get the most recent job that has been executed.
latest_job = old_jobs[0]

# We can also get that same job with `catalog.job`
job_by_id = catalog.job(latest_job.job_id)

# Verify that the job is the same using both retrieval methods.
assert job_by_id.job_id == latest_job.job_id

# Print the job_id for this job.
print(job_by_id.job_id)
f6c29f49-4d5f-4fff-aca6-2e9a115b9763

エラーメッセージを取得する

プログラムのステータスが ERROR の場合は、以下のように job.error_message() を使用してエラーメッセージを取得します:

job.error_message()
qiskit.exceptions.QiskitError: 'Workflow execution failed -- https://docs.quantum.ibm.com/errors#9999'

次のステップ

推奨事項