REST API を使用した Sampler
このトピックのステップでは、REST API を使用してワークロードを実行および設定する方法を説明し、任意のプログラムで呼び出す方法を示します。
このドキュメントでは、Qiskit Runtime REST API を示すために Python の requests モジュールを使用しています。ただし、このワークフローは REST API での作業をサポートする任意の言語やフレームワークを使用して実行できます。詳細については、API リファレンス・ドキュメントを参照してください。
1. アカウントの初期化
Qiskit Runtime Sampler はマネージド・サービスであるため、まずアカウントを初期化する必要があります。その後、計算を実行するデバイスを選択できます。
アカウントの初期化、利用可能なバックエンドの表示、トークンの操作方法の詳細については、REST API を使用して IBM Quantum Platform を設定するを参照してください。
2. QASM 回路の作成
Sampler プリミティブへの入力として、少なくとも 1 つの回路が必要です。
QASM 量子回路を定義します。
qasm_string='''
OPENQASM 3;
include "stdgates.inc";
qreg q[2];
creg c[2];
x q[0];
cx q[0], q[1];
c[0] = measure q[0];
c[1] = measure q[1];
'''
以下のコード・スニペットは、qasm_string が新しい文字列 resulting_qasm にトランスパイルされていることを前提としています。
3. Sampler V2 API を使用した量子回路の実行
以下のジョブは Qiskit Runtime V2 プリミティブを使用しています。SamplerV2 は 1 つ以上のプリミティブ統合ブロック(PUB)を入力として受け取ります。各 PUB は 1 つの回路とその回路にブロードキャストされるデータ(複数のパラメーターも可)を含むタプルであり、PUB ごとに 1 つの結果を返します。
import requests
url = 'https://quantum.cloud.ibm.com/api/v1/jobs'
auth_id = "Bearer <YOUR_BEARER_TOKEN>"
crn = "<SERVICE-CRN>"
backend = "<BACKEND_NAME>"
headers = {
'Content-Type': 'application/json',
'Authorization':auth_id,
'Service-CRN': crn
}
job_input = {
'program_id': 'sampler',
"backend": backend,
"params": {
# primitive unified blocs (PUBs) containing one circuit each:
"pubs": [[resulting_qasm],[resulting_qasm,None,500]]
}}
response = requests.post(url, headers=headers, json=job_input)
if response.status_code == 200:
job_id = response.json().get('id')
print("Job created:",response.text)
else:
print(f"Error: {response.status_code}")
4. ジョブのステータス確認と結果の取得
次に、job_id を API に渡します。
response_status_singlejob= requests.get(url+'/'+job_id, headers=headers)
response_status_singlejob.json().get('state')
出力
>>> Job ID: 58223448-5100-4dec-a47a-942fb30edced
>>> Job Status: JobStatus.RUNNING
ジョブ結果の取得:
response_result= requests.get(url+'/'+job_id+'/results', headers=headers)
res_dict=response_result.json()
# Get results for the first PUB
counts=res_dict['results'][0]['data']['c']['samples']
print(counts[:20])
出力
['0x3', '0x0', '0x2', '0x1', '0x0', '0x3', '0x0', '0x3', '0x1', '0x2', '0x2', '0x0', '0x2', '0x0', '0x3', '0x3', '0x2', '0x0', '0x1', '0x0']
5. Qiskit Runtime オプションの使用
エラー緩和技術を使用すると、実行時のデバイス・ノイズをモデリングすることで回路エラーを緩和できます。これにより通常、モデル・トレーニングに関連する量子前処理のオーバーヘッドと、生成されたモデルを使用して生の結果のエラーを緩和するための古典的な後処理オーバーヘッドが発生します。
プリミティブに組み込まれているエラー緩和技術は、高度なレジリエンス・オプションです。これらのオプションを指定するには、ジョブを送信する際に resilience_level オプションを使用します。
Sampler V2 はレジリエンス・レベルの指定をサポートしていません。ただし、個々のエラー緩和/抑制メソッドのオン/オフを切り替えることができます。
以下の例は、ダイナミカル・デカップリングとツワーリングのデフォルト・オプションを示しています。その他のオプションや詳細については、エラー緩和と抑制技術のトピックを参照してください。
ダイナミカル・デカップリング
import requests
url = 'https://quantum.cloud.ibm.com/api/v1/jobs'
auth_id = "Bearer <YOUR_BEARER_TOKEN>"
crn = "<SERVICE-CRN>"
backend = "<BACKEND_NAME>"
headers = {
'Content-Type': 'application/json',
'Authorization':auth_id,
'Service-CRN': crn
}
job_input = {
'program_id': 'sampler',
"backend": backend,
"params": {
# primitive unified blocs (PUBs) containing one circuit each:
"pubs": [[resulting_qasm]],
"options": {
"dynamical_decoupling": {
"enable": True,
"sequence_type": 'XpXm',
"extra_slack_distribution": 'middle',
"scheduling_method": 'alap',
},
},
}
}
response = requests.post(url, headers=headers, json=job_input)
if response.status_code == 200:
job_id = response.json().get('id')
print("Job created:",response.text)
else:
print(f"Error: {response.status_code}")
ツワーリング
import requests
url = 'https://quantum.cloud.ibm.com/api/v1/jobs'
auth_id = "Bearer <YOUR_BEARER_TOKEN>"
crn = "<SERVICE-CRN>"
backend = "<BACKEND_NAME>"
headers = {
'Content-Type': 'application/json',
'Authorization':auth_id,
'Service-CRN': crn
}
job_input = {
'program_id': 'sampler',
"backend": backend,
"params": {
# primitive unified blocs (PUBs) containing one circuit each:
"pubs": [[resulting_qasm]],
"options": {
"twirling": {
"enable_gates": True,
"enable_measure": True,
"num_randomizations": "auto",
"shots_per_randomization": "auto",
"strategy": "active-accum",
},
},
}
}
response = requests.post(url, headers=headers, json=job_input)
if response.status_code == 200:
job_id = response.json().get('id')
print("Job created:",response.text)
else:
print(f"Error: {response.status_code}")
パラメーター化された回路
1. アカウントの初期化
Qiskit Runtime はマネージド・サービスであるため、まずアカウントを初期化する必要があります。その後、計算を実行するデバイスを選択できます。
アカウントの初期化、利用可能なバックエンドの表示、トークンの無効化の方法の詳細については、このトピックを参照してください。
2. パラメーターの定義
import requests
import qiskit_ibm_runtime
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.transpiler import generate_preset_pass_manager
from qiskit.qasm3 import dumps
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit import transpile
service = QiskitRuntimeService(channel='ibm_quantum')
backend = service.backend("<SPECIFY BACKEND>")
pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
theta = Parameter('theta')
phi = Parameter('phi')
# In case we want to pass a dictionary:
parameter_values = {'theta': 1.57, 'phi': 3.14}
3. 量子回路の作成とパラメーター化されたゲートの追加
qc = QuantumCircuit(2)
# Add parameterized gates
qc.rx(theta, 0)
qc.ry(phi, 1)
qc.cx(0, 1)
qc.measure_all()
# Draw the original circuit
qc.draw('mpl')
# Get an ISA circuit
isa_circuit = pm.run(qc)
4. QASM 3 コードの生成
qasm_str = dumps(isa_circuit)
print("Generated QASM 3 code:")
print(qasm_str)
5. Sampler V2 API を使用した量子回路の実行
import requests
url = 'https://quantum.cloud.ibm.com/api/v1/jobs'
auth_id = "Bearer <YOUR_BEARER_TOKEN>"
crn = "<SERVICE-CRN>"
backend = "<BACKEND_NAME>"
headers = {
'Content-Type': 'application/json',
'Authorization':auth_id,
'Service-CRN': crn
}
job_input = {
'program_id': 'sampler',
"backend": backend,
"params": {
# Choose one option: direct parameter transfer or through a dictionary
# # primitive unified blocs (PUBs) containing one circuit each:
#"pubs": [[qasm_str,[1,2],500]],
# primitive unified blocs (PUBs) containing one circuit each:
"pubs": [[qasm_str,parameter_values,500]],
}}
response = requests.post(url, headers=headers, json=job_input)
if response.status_code == 200:
job_id = response.json().get('id')
print(f"Job created: {response.text}")
else:
print(f"Error: {response.status_code}")
print(response.text)
6. ジョブのステータス確認と結果の取得
次に、job_id を API に渡します。
response_status_singlejob = requests.get(f"{url}/{job_id}", headers=headers)
response_status_singlejob.json().get('state')
出力
{'status': 'Completed'}
ジョブ結果の取得:
response_result = requests.get(f"{url}/{job_id}/results", headers=headers)
res_dict=response_result.json()
# Get results for the first PUB
counts=res_dict['results'][0]['data']['c']['samples']
print(counts[:20])
出力
['0x1', '0x2', '0x1', '0x2', '0x1', '0x2', '0x0', '0x2', '0x1', '0x1', '0x2', '0x2', '0x1', '0x1', '0x1', '0x1', '0x1', '0x1', '0x1', '0x1']
次のステップ
- ワークロードの実行方法にはニーズに応じていくつかの方法があります:ジョブ・モード、Session モード、バッチ・モード。Session モードとバッチ・モードの操作方法については、実行モードのトピックを参照してください。なお、オープン・プランのユーザーは Session ジョブを送信できません。
- REST API でアカウントを初期化する方法を学びます。
- IBM Quantum Learning のコスト関数レッスンでプリミティブを使った練習をします。
- トランスパイルセクションでローカル・トランスパイルの方法を学びます。