qiskit-documentation/docs/guides/save-jobs.ipynb

265 lines
8.3 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "539f98fa-9ccc-472a-99da-ebe6382243dc",
"metadata": {},
"source": [
"# Save and retrieve jobs"
]
},
{
"cell_type": "markdown",
"id": "c4012cc3-8da9-4e81-afd9-42125f997d08",
"metadata": {
"tags": [
"version-info"
]
},
"source": [
"<details>\n",
"<summary><b>Package versions</b></summary>\n",
"\n",
"The code on this page was developed using the following requirements.\n",
"We recommend using these versions or newer.\n",
"\n",
"```\n",
"qiskit[all]~=1.2.4\n",
"qiskit-aer~=0.15.1\n",
"qiskit-ibm-runtime~=0.31.0\n",
"qiskit-serverless~=0.17.1\n",
"qiskit-ibm-catalog~=0.1\n",
"```\n",
"</details>"
]
},
{
"cell_type": "markdown",
"id": "923e6db4-89e1-4e1d-a526-a42454a4c238",
"metadata": {},
"source": [
"Quantum workflows often take a while to complete and can run over many sessions. Restarting your Python kernel means you'll lose any results stored in memory. To avoid loss of data, you can save results to file and retrieve results of past jobs from IBM Quantum&trade; so your next session can continue where you left off."
]
},
{
"cell_type": "markdown",
"id": "73f23256-6519-47ae-b9e3-700f52a76711",
"metadata": {},
"source": [
"## Retrieve jobs from IBM Quantum\n",
"\n",
"IBM Quantum automatically stores results from every job for you to retrieve at a later date. Use this feature to continue quantum programs across kernel restarts and review past results. You can get the ID of a job programmatically through its `job_id` method, or you can see all your submitted jobs and their IDs through the [Workloads dashboard](https://quantum.ibm.com/workloads).\n",
"\n",
"To find a job programatically, use the [`QiskitRuntimeService.jobs`](/api/qiskit-ibm-runtime/qiskit_ibm_runtime.QiskitRuntimeService#jobs) method. By default, this returns the most recent jobs, but you can also filter jobs by backend name, creation date, and more. The following cell finds any jobs submitted in the last three months. The `created_after` argument must be a [`datetime.datetime`](https://docs.python.org/3.8/library/datetime.html#datetime.datetime) object."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "da02c7ca-803a-4426-8dd0-bbe062c0e9e1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<RuntimeJob('cwj8a5r9r49g00893azg', 'sampler')>,\n",
" <RuntimeJob('cwj82600r6b0008psmrg', 'noise-learner')>,\n",
" <RuntimeJob('cwj7w400r6b0008psm4g', 'sampler')>]"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import datetime\n",
"from qiskit_ibm_runtime import QiskitRuntimeService\n",
"\n",
"three_months_ago = datetime.datetime.now() - datetime.timedelta(days=90)\n",
"\n",
"service = QiskitRuntimeService()\n",
"jobs_in_last_three_months = service.jobs(created_after=three_months_ago)\n",
"jobs_in_last_three_months[:3] # show first three jobs"
]
},
{
"cell_type": "markdown",
"id": "9aae5f5a-a543-493c-9bc5-5682ba846ab5",
"metadata": {},
"source": [
"You can also select by backend, job state, session, and more. For more information, see [`QiskitRuntimeService.jobs`](/api/qiskit-ibm-runtime/qiskit_ibm_runtime.QiskitRuntimeService#jobs) in the API documentation.\n",
"\n",
"Once you have the job ID, use the [`QiskitRuntimeService.job`](/api/qiskit-ibm-runtime/qiskit_ibm_runtime.QiskitRuntimeService#job) method to retrieve it."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "43d0f06e-f97f-4c19-b242-02cb0bd420a9",
"metadata": {
"tags": [
"ignore-warnings"
]
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/z_/6s4ntyps5lsb232v7f82201r0000gn/T/ipykernel_5474/2704799770.py:3: DeprecationWarning: In a future release of qiskit-ibm-runtime no sooner than 3 months after the release date of 0.30.0, RuntimeJob.status() will be returned as a string instead of an instance of `JobStatus`.\n",
" successful_job = next(j for j in service.jobs() if j.status().name == \"DONE\")\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"cwj8a5r9r49g00893azg\n"
]
}
],
"source": [
"# Get ID of most recent successful job for demonstration.\n",
"# This will not work if you've never successfully run a job.\n",
"successful_job = next(j for j in service.jobs() if j.status().name == \"DONE\")\n",
"job_id = successful_job.job_id()\n",
"print(job_id)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "90133394-3259-487f-96b2-3b50e0274064",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(100,), num_shots=4096, num_bits=2>), shape=(100,)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([SliceSpan(<start='2024-11-01 07:37:02', stop='2024-11-01 07:39:03', size=409600>)])}, 'version': 2})"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieved_job = service.job(job_id)\n",
"retrieved_job.result()"
]
},
{
"cell_type": "markdown",
"id": "1f50a889-63b1-4458-a5e5-bd2ef47dd3eb",
"metadata": {},
"source": [
"<CodeAssistantAdmonition\n",
" tagLine=\"Always forgetting how to retrieve a job? Try this prompt with Qiskit Code Assistant:\"\n",
" prompts={[\n",
" \"# Retrieve job JOB_ID from IBM Runtime and print the result\"\n",
" ]}\n",
"/>"
]
},
{
"cell_type": "markdown",
"id": "211b8c15-5aa3-43f6-82ee-2bd1d49ae8fc",
"metadata": {},
"source": [
"## Save results to disk\n",
"\n",
"You may also want to save results to disk. To do this, use Python's built-in JSON library with Qiskit Runtime's encoders."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "3a3ff817-01c1-47e8-94c6-1ecf2215ef7c",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"from qiskit_ibm_runtime import RuntimeEncoder\n",
"\n",
"with open(\"result.json\", \"w\") as file:\n",
" json.dump(retrieved_job.result(), file, cls=RuntimeEncoder)"
]
},
{
"cell_type": "markdown",
"id": "40a9d8e5-c876-47a7-862e-d2ce535a6052",
"metadata": {},
"source": [
"You can then load this array from disk in a separate kernel."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "316aa6f7-faee-4a05-a7b4-02d7bee4d58a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(100,), num_shots=4096, num_bits=2>), shape=(100,)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([SliceSpan(<start='2024-11-01 07:37:02', stop='2024-11-01 07:39:03', size=409600>)])}, 'version': 2})"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from qiskit_ibm_runtime import RuntimeDecoder\n",
"\n",
"with open(\"result.json\", \"r\") as file:\n",
" result = json.load(file, cls=RuntimeDecoder)\n",
"\n",
"result"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "eae94b73-157b-4751-8dd3-add4cc9efec6",
"metadata": {
"tags": [
"remove-cell"
]
},
"outputs": [],
"source": [
"# Cleanup the file we created (this cell should be hidden from the user)\n",
"import pathlib\n",
"\n",
"pathlib.Path(\"result.json\").unlink()"
]
}
],
"metadata": {
"description": "Store Qiskit objects on disk or in the cloud so you can continue where you left off",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3"
},
"title": "Save and retrieve Qiskit objects"
},
"nbformat": 4,
"nbformat_minor": 2
}