{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Executing Quantum Circuits \n", "\n", "In CUDA-Q, there are 3 ways in which one can execute quantum kernels: \n", "\n", "1. `sample`: yields measurement counts \n", "2. `observe`: yields expectation values \n", "3. `get_state`: yields the quantum statevector of the computation \n", "\n", "## Sample\n", "\n", "Quantum states collapse upon measurement and hence need to be sampled many times to gather statistics. The CUDA-Q `sample` call enables this: \n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " ╭───╮ \n", "q0 : ┤ h ├──●──\n", " ╰───╯╭─┴─╮\n", "q1 : ─────┤ x ├\n", " ╰───╯\n", "\n", "{ 11:506 00:494 }\n", "\n" ] } ], "source": [ "import cudaq\n", "import numpy as np \n", "\n", "qubit_count = 2\n", "\n", "# Define the simulation target.\n", "cudaq.set_target(\"qpp-cpu\")\n", "\n", "# Define a quantum kernel function.\n", "\n", "@cudaq.kernel\n", "def kernel(qubit_count: int):\n", " qvector = cudaq.qvector(qubit_count)\n", "\n", " # 2-qubit GHZ state.\n", " h(qvector[0])\n", " for i in range(1, qubit_count):\n", " x.ctrl(qvector[0], qvector[i])\n", "\n", " # If we dont specify measurements, all qubits are measured in\n", " # the Z-basis by default or we can manually specify it also \n", " # mz(qvector)\n", "\n", "\n", "print(cudaq.draw(kernel, qubit_count))\n", "\n", "result = cudaq.sample(kernel, qubit_count, shots_count=1000)\n", "\n", "print(result)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Note that there is a subtle difference between how `sample` is executed with the target device set to a simulator or with the target device set to a QPU. In simulation mode, the quantum state is built once and then sampled $s$ times where $s$ equals the `shots_count`. In hardware execution mode, the quantum state collapses upon measurement and hence needs to be rebuilt over and over again.\n", "\n", "There are a number of helpful tools that can be found in the API [here](https://nvidia.github.io/cuda-quantum/latest/api/languages/python_api.html#cudaq.SampleResult) to process the `Sample_Result` object produced by `sample`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Observe\n", "\n", "The `observe` function allows us to calculate expectation values. We must supply a spin operator in the form of a Hamiltonian, $H$, from which we would like to calculate $\\bra{\\psi}H\\ket{\\psi}$." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " = 0.0\n" ] } ], "source": [ "from cudaq import spin\n", "\n", "# Define a Hamiltonian in terms of Pauli Spin operators.\n", "hamiltonian = spin.z(0) + spin.y(1) + spin.x(0) * spin.z(0)\n", "\n", "# Compute the expectation value given the state prepared by the kernel.\n", "result = cudaq.observe(kernel, hamiltonian, qubit_count).expectation()\n", "\n", "print(' =', result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Get state\n", "\n", "The `get_state` function gives us access to the quantum statevector of the computation. Remember, that this is only feasible in simulation mode. " ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.70710678+0.j 0. +0.j 0. +0.j 0.70710678+0.j]\n" ] } ], "source": [ "# Compute the statevector of the kernel\n", "result = cudaq.get_state(kernel, qubit_count)\n", "\n", "print(np.array(result))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The statevector generated by the `get_state` command follows Big-endian convention for associating numbers with their binary representations, which places the least significant bit on the left. That is, for the example of a 2-bit system, we have the following translation between integers and bits:\n", "$$\\begin{matrix} \\text{Integer} & \\text{Binary representation}\\\\\n", "& \\text{least signinificant bit on left}\\\\\n", "0 =\\textcolor{red}{0}*2^0+\\textcolor{blue}{0}*2^1 & \\textcolor{red}{0}\\textcolor{blue}{0} \\\\\n", "1 = \\textcolor{red}{1}*2^0 + \\textcolor{blue}{0} *2^1 & \\textcolor{red}{1}\\textcolor{blue}{0}\\\\\n", "2 = \\textcolor{red}{0}*2^0 + \\textcolor{blue}{1}*2^1 & \\textcolor{red}{0}\\textcolor{blue}{1} \\\\\n", "3 = \\textcolor{red}{1}*2^0 + \\textcolor{blue}{1}*2^1 & \\textcolor{red}{1}\\textcolor{blue}{1} \\end{matrix}\n", "$$\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Parallelization Techniques\n", "\n", "The most intensive task in the computation is the execution of the quantum kernel hence each execution function: `sample`, `observe` and `get_state` can be parallelized given access to multiple quantum processing units (multi-QPU). \n", "\n", "Since multi-QPU platforms are not yet feasible, we emulate each QPU with a GPU.\n", "\n", "\n", "### Observe Async\n", "\n", "Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result. \n", "\n", "`observe` can be a time intensive task. We can parallelize the execution of `observe` via the arguments it accepts. " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.220446049250313e-16\n" ] } ], "source": [ "# Set the simulation target to a multi-QPU platform \n", "# cudaq.set_target(\"nvidia\", option = 'mqpu')\n", "\n", "# Measuring the expectation value of 2 different hamiltonians in parallel\n", "hamiltonian_1 = spin.x(0) + spin.y(1) + spin.z(0)*spin.y(1)\n", "# hamiltonian_2 = spin.z(1) + spin.y(0) + spin.x(1)*spin.x(0)\n", "\n", "# Asynchronous execution on multiple qpus via nvidia gpus.\n", "result_1 = cudaq.observe_async(kernel, hamiltonian_1, qubit_count, qpu_id=0)\n", "# result_2 = cudaq.observe_async(kernel, hamiltonian_2, qubit_count, qpu_id=1)\n", "\n", "# Retrieve results \n", "print(result_1.get().expectation())\n", "# print(result_2.get().expectation())" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Above we parallelized the `observe` call over the `hamiltonian` parameter however we can parallelize over any of the argument it accepts by just iterating obver the `qpu_id`." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Sample Async\n", "\n", "Similar to `observe_async` above, `sample` also supports asynchronous execution for the [arguments it accepts](https://nvidia.github.io/cuda-quantum/latest/api/languages/python_api.html#cudaq.sample_async:~:text=cudaq.sample_async(kernel%3A%20object%2C%20%5C*args%2C%20shots_count%3A%20int%20%3D%201000%2C%20qpu_id%3A%20int%20%3D%200)%E2%86%92%20cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.AsyncSampleResult). One can parallelize over various kernels, variational parameters or even distribute shots counts over multiple QPUs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Get State Async\n", "\n", "Similar to `sample_async` above, `get_state` also supports asynchronous execution for the [arguments it accepts](https://nvidia.github.io/cuda-quantum/latest/api/languages/python_api.html#cudaq.sample_async:~:text=cudaq.get_state(arg0%3A%20object%2C%20%5C*args)%E2%86%92%20cudaq.mlir._mlir_libs._quakeDialects.cudaq_runtime.State)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "CUDA-Q Version (https://github.com/NVIDIA/cuda-quantum 0eb6b444eb5b3a687e6fd64529ee9223aaa2870e)\n" ] } ], "source": [ "print(cudaq.__version__)\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.10.12" }, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 4 }