{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Dirac-3 Developer Beginner Guide\n", "\n", "Dirac-3 is the latest addition to QCi's Entropy Quantum Computing (EQC) product line, a unique quantum-hardware approach for tackling complex optimization problems. Dirac-3 uses qudits as its unit of quantum information, where each quantum state is represented by $d$ dimensions. This means that Dirac-3 can solve problems beyond binary (0,1), including integers and continuous numbers (all positive real rational numbers). For further information on qudits, please read through the [Qudit Primer](https://learn.quantumcomputinginc.com/learn/lessons/qudit-basics) to better understand the benefits of high-dimensional programming. This allows Dirac-3 to solve a variety of important problems including higher order polynomials as well as integer optimization problems. This tutorial will provide an introduction to how to formulate problems for Dirac-3. We will begin by discussing what types of problems Dirac-3 can solve, how to submit problems, and how to analyze results. \n", "\n", "To delve deeper into the underlying physics of EQC technology, refer to our paper: [An Open Quantum System for Discrete Optimization](https://arxiv.org/abs/2407.04512)\n", "\n", "**Prerequisites**: In order to begin running problems with Dirac-3 you will need to: \n", "- [Install qci-client](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/quick-start-on-cloud#installation)\n", "- [Obtained an API access token](https://quantumcomputinginc.com/learn/tutorials-and-use-cases/quick-start-on-cloud)\n", "\n", "## Dirac-3 as a Continuous Solver\n", "\n", "Dirac-3 solves problems of objective function minimization for optimization over discrete spaces by finding the ground state of a complex system with many inter-correlated variables. They correspond to minimizing the expected return of the following objective function:\n", "\n", "$$\n", "E = \\sum_{i=1}^{N} C_i V_i +\n", "\\sum_{i,j=1}^{N,N} J_{ij}V_i V_j +\n", "\\sum_{i,j,k=1}^{N,N,N} T_{ijk}V_i V_j V_k +\n", "\\sum_{i,j,k,l=1}^{N,N,N,N} Q_{ijkl}V_i V_j V_k V_l +\n", "\\sum_{i,j,k,l,m=1}^{N,N,N,N,N} P_{ijklm}V_i V_j V_k V_l V_m\n", "$$\n", "Where $V_{i}$ is the value of each continuous variable with the expected resolution of $\\frac{R}{\\text{dynamic range}}$, $C_{i}$ is the linear return of each variable which must be real numbers, $J_{ij}$ , $T_{ijk}$ , $Q_{ijkl}$ , $P_{ijklm}$ are joint returns of variables which must be real numbers, and $R$ is the constraint summation satisfying 1 ≤ $R$.\n", "Dirac-3 allows direct submission for minimization only. It is assumed that users perform a simple transformation before submitting the problem to handle maximization (i.e. multiply coefficients by -1). For additional information please refer to our [Dirac-3 User Guide](https://quantumcomputinginc.com/learn/spec-sheets/dirac-3-users-guide).\n", "\n", "## Formulating and Running Problems on Dirac-3 \n", "\n", "The following code block uses the qci-client which automatically requests a session token from the API. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from qci_client import QciClient\n", "import os\n", "\n", "api_url = \"https://api.qci-prod.com\"\n", "api_token = \"\"\n", "client = QciClient(api_token=api_token, url=api_url)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we'll share a basic problem for submission to Dirac-3. In order to illustrate a standard problem submission a simple polynomial problem will be utilized:\n", "$$\n", "E = 3x_4 + 2.1x^2_1 + 1.5^2_1 + 7.9^2_3 + x_2x_4^2 + x^3_3\n", "$$\n", "\n", "The first step is to extract the polynomial coefficients and format polynomial variable indices for each term in the equation. The polynomial coefficients will be represented as a list as follows:\n", "\n", "***poly_coefs = [3, 2.1, 1.5, 7.9, 1, 1]***\n", "\n", "The polynomial indices for the coefficients will be represented as follows in the same order as represented in the original equation:\n", "\n", "***poly_indices = [[0,0,4], [0,1,1], [0,2,2], [0,2,3], [2,4,4], [3,3,3]]***\n", "\n", "We'll use the poly_coefficients and poly_indices to generate the data file. We will then use the qci-client (client) that we generated to upload the file.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Let's consider a simple Hamiltonian problem\n", "poly_indices = [[0,0,4], [0,1,1], [0,2,2], [0,2,3], [2,4,4], [3,3,3]]\n", "poly_coefs = [3, 2.1, 1.5, 7.9, 1, 1]\n", "data = [{\"idx\": idx, \"val\": val} for idx, val in zip(poly_indices, poly_coefs)]\n", "file = {\n", " \"file_name\": \"dirac_3_example\",\n", " \"file_config\": {\n", " \"polynomial\": {\n", " \"num_variables\": 6,\n", " \"min_degree\": 1,\n", " \"max_degree\": 3,\n", " \"data\": data,\n", " }\n", " }\n", "}\n", "\n", "file_response = client.upload_file(file=file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Job Body Parameters\n", "\n", "Now we will build the job body with the following parameters:\n", "\n", "* **job type**: Specifies the type of job to be performed. In this case, ’sample-hamiltonian’ indicates that the job involves creating a Hamiltonian.\n", "\n", "* **job name**: An optional user-defined string that names the job. Here, it’s set to ’test hamiltonian job’.\n", "\n", "* **job tags**: An optional list of user-defined string identifiers to tag the job for easier reference and organization. In this example, the tags are [’tag1’, ’tag2’].\n", "\n", "* **job params**: A dictionary containing parameters for configuring the job and the device. The keys and values specify that the device type is ’dirac-3’, with a relaxation schedule of 1 and a sum constraint of 1.\n", " * ***sum_constraint***: a normalization constraint that is applied to the problem space meaning that solution variables from device must sum to provided value. Value must be between 1 and 10000.\n", " * ***relaxation_schedule***: four different schedules represented by an integer parameter. Higher values reduce the variation in the analog spin values and therefore lead to a better ground state for input problem. Accepts one of the values in the set {1, 2, 3, 4}\n", " * ***solution_precision***: optional parameter that specifies the level of precision to apply to the solutions. If specified a distillation method is applied to the continuous solutions to map them to the submitted solution_precision. R must be divisible by solution_precision. Also, solution_precision must meet following condition\n", "\n", "- **polynomial file id**: The unique identifier for the uploaded polynomial file, retrieved from the file response ’file id’. This ID links the job to the specific problem data.\n", "\n", "By preparing the job body in this manner, you set up all necessary configurations and metadata required by the QCi API to process the optimization task on the Dirac-3 device.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Build the job body to be submitted to the QCi API.\n", "# This is where the job type and the Dirac-3 device and its configuration are specified.\n", "job_body = client.build_job_body(\n", " job_type='sample-hamiltonian',\n", " job_name='test_hamiltonian_job', # user-defined string, optional\n", " job_tags=['tag1', 'tag2'], # user-defined list of string identifiers, optional\n", " job_params={'device_type': 'dirac-3', 'relaxation_schedule': 1, 'sum_constraint': 1},\n", " polynomial_file_id=file_response['file_id'],\n", ")\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Submitting Problems to the API\n", "\n", "Now using the job body that we just created we'll submit the job to the QCi API. After submission your job will progress through the following states:\n", "\n", "- **QUEUED**: waiting for the Dirac-3 to become available\n", "- **RUNNING**: the job has been submitted to the Dirac-3 and is running\n", "- **COMPLETED**: the job has completed and results are available for analysis\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Submit the job and await the result.\n", "job_response = client.process_job(job_body=job_body)\n", "assert job_response[\"status\"] == client.JobStatus.COMPLETED.value\n", "print(\n", " f\"solution: {job_response['results']['solutions'][0]} is \" \n", " f\"energy: {job_response['results']['energies'][0]}\"\n", ")\n", "\n", "# This should output something similar to:\n", "# 2024-05-15 10:59:49 - Dirac allocation balance = 600 s\n", "# 2024-05-15 10:59:49 - Job submitted: job_id='6644ea05d448b017e54f9663'\n", "# 2024-05-15 10:59:49 - QUEUED\n", "# 2024-05-15 10:59:52 - RUNNING\n", "# 2024-05-15 11:00:46 - COMPLETED\n", "# 2024-05-15 11:00:48 - Dirac allocation balance = 598 s\n", "# energy: 12924.37675\n", "# solution: [73.25, 16.75, 3.45, 6.55]\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the python code above we select to print only the energy and the solution for the job. Where energy and solution are defined as:\n", "* energy - objective value for best solution returned by the device\n", "* solution - a vector representing the solution to the problem from a given run on the Dirac hardware" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "{'job_info': {'job_id': '#######', 'organization_id': '#######', \n", " 'user_id': '#######', 'job_submission': {'job_name': 'hamiltonian_job_0', \n", " 'problem_config': {'normalized_qudit_hamiltonian_optimization': {\n", " 'hamiltonian_file_id': '#######'}}, \n", " 'device_config': {'dirac-3': {'num_samples': 1, 'relaxation_schedule': 2, 'sum_constraint': 1}}}, \n", " 'job_status': {'submitted_at_rfc3339nano': '2024-10-04T19:58:35.921Z', 'queued_at_rfc3339nano': \n", " '2024-10-04T19:58:35.922Z', 'running_at_rfc3339nano': '2024-10-04T19:58:36.556Z', \n", " 'completed_at_rfc3339nano': '2024-10-04T19:58:45.084Z'}, 'job_result': \n", " {'file_id': '670048f55e0855263226d8ac', 'device_usage_s': 8}}, 'status': 'COMPLETED', \n", " 'results': {'counts': [1], 'energies': [12924.37675], \n", " 'solutions': [[73.25, 16.75, 3.45, 6.55]]}}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to the energy and the solutions the job_response contains additional information that may be useful:\n", "- **job_id**: The hash id of the job that was run\n", "- **organization_id**: The orgagnization the user that ran the job belongs to\n", "- **user_id**: The hash id of the user running the job\n", "- **problem_config**: contains all the information about what device the job ran on, the parameters it ran with, and runtime information\n", "- **file_id**: The file_id that was used to run the job\n", "- **results**: The energies and solutions that were found for the user's job" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As an additional example we'll run **QPLIB18** a comprehensive benchmark library designed for evaluating the performance of optimization solvers on **quadratic programming (QP) problems**.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's start by importing the necessary python libraries. Next we'll initialize the client and we'll read in the poly_coefficients and poly_indicies for the problem. We'll use the **poly_coefs** and **poly_indices** to generate the data file. We will then use the qci-client (client) that we generated to upload the file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from qci_client import QciClient, JobStatus\n", "import pkg_resources\n", "import os\n", "\n", "api_url = \"https://api.qci-prod.com\"\n", "api_token = \"\"\n", "client = QciClient(api_token=api_token, url=api_url)\n", "\n", "with open('qplib_0018_coefficients.csv', 'r') as f:\n", " poly_coefs = [float(line.strip()) for line in f]\n", "\n", "with open('qplib_0018_indices.csv', 'r') as f:\n", " poly_indicies = [tuple(map(int, line.strip().split(','))) for line in f]\n", "\n", "data = [{\"idx\": idx, \"val\": val} for idx, val in zip(poly_indices, poly_coefs)]\n", "\n", "file = {\n", " \"file_name\": \"dirac_3_qplib18_example\",\n", " \"file_config\": {\n", " \"polynomial\": {\n", " \"num_variables\": 50,\n", " \"min_degree\": 1,\n", " \"max_degree\": 2,\n", " \"data\": data,\n", " }\n", " }\n", "}\n", "\n", "file_response = client.upload_file(file=file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've uploaded the file we can generate the job body. The parameters for the job body will be the same as those defined above in the **Job Body Parameters** section." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Build the job body to be submitted to the QCi API.\n", "# This is where the job type and the Dirac-3 device and its configuration are specified.\n", "job_body = client.build_job_body(\n", " job_type='sample-hamiltonian',\n", " job_name='test_qplib0018_job', # user-defined string, optional\n", " job_tags=['tag1', 'tag2'], # user-defined list of string identifiers, optional\n", " job_params={'device_type': 'dirac-3', 'relaxation_schedule': 1, 'sum_constraint': 1},\n", " polynomial_file_id=file_response['file_id'],\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now using the job body that we just created we'll submit the job to the QCi API. After submission your job will progress through the QUEUED, RUNNING, and COMPLETED states as defined above in the **Submitting Problems to the API** section." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Submit the job and await the result.\n", "job_response = client.process_job(job_body=job_body)\n", "print(job_response)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The job response for the QPLIB0018 problem should look something like this:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "{'job_info': \n", " {'job_id': '67057a80d18290207d13a48f', 'organization_id': '62e8109818e8fbebb2b8d953', \n", " 'user_id': '63efffebd9573deffdd4dd81', 'job_submission': {'job_name': 'test_qplib0018_job', \n", " 'job_tags': ['tag1', 'tag2'], \n", " 'problem_config': {\n", " 'normalized_qudit_hamiltonian_optimization': {\n", " 'polynomial_file_id': '67057a7f5e0855263226da8e'}\n", " }, \n", " 'device_config': {\n", " 'dirac-3': {\n", " 'num_samples': 1, \n", " 'relaxation_schedule': 1, \n", " 'sum_constraint': 1}\n", " }\n", " }, \n", " 'job_status': {\n", " 'submitted_at_rfc3339nano': '2024-10-08T18:31:28.057Z', \n", " 'queued_at_rfc3339nano': '2024-10-08T18:31:28.057Z', \n", " 'running_at_rfc3339nano': '2024-10-08T18:31:28.8Z', \n", " 'completed_at_rfc3339nano': '2024-10-08T18:31:46.397Z'\n", " }, 'job_result': {\n", " 'file_id': '67057a925e0855263226da90', 'device_usage_s': 2}\n", " }, \n", " 'status': 'COMPLETED', 'results': \n", " {\n", " 'counts': [1], \n", " 'energies': [-5.8639507], \n", " 'solutions': [[0, 0, 0, 0.0466387, 0, 0, 0, 0.215652, 0, 0, 0, 0, 0, \n", " 0.2257261, 1e-07, 0, 2e-07, 5e-07, 0, 0, 0, 0, 0, 0, 0, 0, 2e-07, \n", " 0, 0, 0, 8.54e-05, 0.2333704, 1e-07, 0, 0, 0, 0, 0, 8.76e-05, 0, \n", " 0.195923, 0, 0, 0, 0, 0, 0, 0.0825149, 0, 0]]\n", " }\n", "}" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.9.16" } }, "nbformat": 4, "nbformat_minor": 4 }