Files
final-qibotn/examples/quimb_intro/quimb_introduction.ipynb

609 lines
19 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "656bb283-ac6d-48d2-a029-3c417c9961f8",
"metadata": {},
"source": [
"## Introduction to Quimb backend in QiboTN\n",
"\n",
"#### Some imports"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "6722d94e-e311-48f9-b6df-c6d829bf67fb",
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"import numpy as np\n",
"# from scipy import stats\n",
"\n",
"# import qibo\n",
"from qibo import Circuit, gates, hamiltonians\n",
"from qibo.backends import construct_backend"
]
},
{
"cell_type": "markdown",
"id": "a009a5e0-cfd4-4a49-9f7c-e82f252c6147",
"metadata": {},
"source": [
"#### Some hyper parameters"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b0a1da82",
"metadata": {},
"outputs": [],
"source": [
"import cotengra as ctg\n",
"ctg_opt = ctg.ReusableHyperOptimizer(\n",
" max_time=10,\n",
" minimize='combo',\n",
" slicing_opts=None,\n",
" parallel=True,\n",
" progbar=True\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "64162116-1555-4a68-811c-01593739d622",
"metadata": {},
"outputs": [],
"source": [
"# construct qibotn backend\n",
"quimb_backend = construct_backend(backend=\"qibotn\", platform=\"quimb\")\n",
"\n",
"# set number of qubits\n",
"nqubits = 4\n",
"\n",
"# set numpy random seed\n",
"np.random.seed(42)\n",
"\n",
"quimb_backend.setup_backend_specifics(\n",
" qimb_backend=\"jax\", \n",
" optimizer='auto-hq'\n",
" )"
]
},
{
"cell_type": "markdown",
"id": "252f5cd1-5932-4de6-8076-4a357d50ebad",
"metadata": {},
"source": [
"#### Constructing a parametric quantum circuit"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4a22a172-f50d-411d-afa3-fa61937c7b3a",
"metadata": {},
"outputs": [],
"source": [
"def build_circuit(nqubits, nlayers):\n",
" \"\"\"Construct a parametric quantum circuit.\"\"\"\n",
" circ = Circuit(nqubits)\n",
" for _ in range(nlayers):\n",
" for q in range(nqubits):\n",
" circ.add(gates.RY(q=q, theta=0.))\n",
" circ.add(gates.RZ(q=q, theta=0.))\n",
" [circ.add(gates.CNOT(q%nqubits, (q+1)%nqubits) for q in range(nqubits))]\n",
" circ.add(gates.M(*range(nqubits)))\n",
" return circ"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "76f23c57-6d08-496b-9a27-52fb63bbfcb1",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0: ─RY─RZ─o─────X─RY─RZ─o─────X─RY─RZ─o─────X─M─\n",
"1: ─RY─RZ─X─o───|─RY─RZ─X─o───|─RY─RZ─X─o───|─M─\n",
"2: ─RY─RZ───X─o─|─RY─RZ───X─o─|─RY─RZ───X─o─|─M─\n",
"3: ─RY─RZ─────X─o─RY─RZ─────X─o─RY─RZ─────X─o─M─\n"
]
}
],
"source": [
"circuit = build_circuit(nqubits=nqubits, nlayers=3)\n",
"circuit.draw()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "07b2c097-cea2-42ec-8f1d-b4bbb5b71d98",
"metadata": {},
"outputs": [],
"source": [
"# Setting random parameters\n",
"circuit.set_parameters(\n",
" parameters=np.random.uniform(-np.pi, np.pi, len(circuit.get_parameters())),\n",
")"
]
},
{
"cell_type": "markdown",
"id": "fd0cea52-03f5-4366-a01a-a5a84aa8ebc7",
"metadata": {},
"source": [
"#### Setting up the tensor network simulator\n",
"\n",
"Depending on the simulator, various parameters can be set. One can customize the tensor network execution via the `backend.configure_tn_simulation` function, whose face depends on the specific backend provider."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "2ee03e94-d794-4a51-9e76-01e8d8a259ba",
"metadata": {},
"outputs": [],
"source": [
"# Customization of the tensor network simulation in the case of quimb backend\n",
"# Here we use only some of the possible arguments\n",
"quimb_backend.configure_tn_simulation(\n",
" #ansatz=\"MPS\",\n",
" max_bond_dimension=10\n",
")"
]
},
{
"cell_type": "markdown",
"id": "648d85b8-445d-4081-aeed-1691fbae67be",
"metadata": {},
"source": [
"#### Executing through the backend\n",
"\n",
"The `backend.execute_circuit` method can be used then. We can simulate results in three ways:\n",
"1. reconstruction of the final state only if `return_array` is set to `True`;\n",
"2. computation of the relevant probabilities of the final state.\n",
"3. reconstruction of the relevant state's frequencies (only if `nshots` is not `None`)."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "35a244c3-adba-4b8b-b28c-0ab592b0f7cf",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/mattia/main_env/lib/python3.12/site-packages/quimb/tensor/circuit.py:215: SyntaxWarning: Unsupported operation ignored: creg\n",
" warnings.warn(\n",
"/home/mattia/main_env/lib/python3.12/site-packages/quimb/tensor/circuit.py:215: SyntaxWarning: Unsupported operation ignored: measure\n",
" warnings.warn(\n",
"/home/mattia/main_env/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
},
{
"data": {
"text/plain": [
"{'nqubits': 4,\n",
" 'backend': qibotn (quimb),\n",
" 'measures': Counter({'0011': 8,\n",
" '0010': 12,\n",
" '0111': 4,\n",
" '1011': 7,\n",
" '0000': 8,\n",
" '1110': 14,\n",
" '0101': 4,\n",
" '1010': 4,\n",
" '1000': 14,\n",
" '1111': 8,\n",
" '0100': 6,\n",
" '1101': 8,\n",
" '1100': 1,\n",
" '0110': 2}),\n",
" 'measured_probabilities': {'1110': np.float64(0.07174919872959985),\n",
" '1000': np.float64(0.11330883548333587),\n",
" '0010': np.float64(0.09466860481989385),\n",
" '0011': np.float64(0.07571277233522114),\n",
" '0000': np.float64(0.08390937969317269),\n",
" '1111': np.float64(0.10184806171791962),\n",
" '1101': np.float64(0.12331159869893256),\n",
" '1011': np.float64(0.053499396925872744),\n",
" '0100': np.float64(0.07142939529687138),\n",
" '0111': np.float64(0.04029185074729259),\n",
" '0101': np.float64(0.05622305772698622),\n",
" '1010': np.float64(0.03872758515126756),\n",
" '0110': np.float64(0.05146064807369214),\n",
" '1100': np.float64(0.013605984872668404)},\n",
" 'prob_type': 'default',\n",
" 'statevector': Array([[ 0.08809624-0.27594998j],\n",
" [-0.05174781+0.04471217j],\n",
" [ 0.00470147+0.30764672j],\n",
" [-0.27208942+0.0409893j ],\n",
" [ 0.18807822+0.18988408j],\n",
" [ 0.2237706 +0.07842042j],\n",
" [-0.18900308+0.12545314j],\n",
" [ 0.17105256-0.10503749j],\n",
" [ 0.24859734-0.22695419j],\n",
" [-0.0411739 -0.06230037j],\n",
" [ 0.17371392-0.09247189j],\n",
" [-0.22748128+0.0418529j ],\n",
" [ 0.09444095+0.06846087j],\n",
" [-0.21784972-0.2754144j ],\n",
" [-0.17359753+0.20399286j],\n",
" [-0.01729754-0.31866732j]], dtype=complex64)}"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# # Simple execution (defaults)\n",
"outcome = quimb_backend.execute_circuit(circuit=circuit, nshots=100, return_array=True)\n",
"\n",
"# # Print outcome\n",
"vars(outcome)"
]
},
{
"cell_type": "markdown",
"id": "84ec0b48-f6b4-495c-93b8-8e42d1a8b0df",
"metadata": {},
"source": [
"---\n",
"\n",
"One can access to the specific contents of the simulation outcome."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "c0443efc-21ef-4ed5-9cf4-785d204a1881",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Probabilities:\n",
" {'1110': np.float64(0.07174919872959985), '1000': np.float64(0.11330883548333587), '0010': np.float64(0.09466860481989385), '0011': np.float64(0.07571277233522114), '0000': np.float64(0.08390937969317269), '1111': np.float64(0.10184806171791962), '1101': np.float64(0.12331159869893256), '1011': np.float64(0.053499396925872744), '0100': np.float64(0.07142939529687138), '0111': np.float64(0.04029185074729259), '0101': np.float64(0.05622305772698622), '1010': np.float64(0.03872758515126756), '0110': np.float64(0.05146064807369214), '1100': np.float64(0.013605984872668404)}\n",
"\n",
"State:\n",
" [[ 0.08809624-0.27594998j]\n",
" [-0.05174781+0.04471217j]\n",
" [ 0.00470147+0.30764672j]\n",
" [-0.27208942+0.0409893j ]\n",
" [ 0.18807822+0.18988408j]\n",
" [ 0.2237706 +0.07842042j]\n",
" [-0.18900308+0.12545314j]\n",
" [ 0.17105256-0.10503749j]\n",
" [ 0.24859734-0.22695419j]\n",
" [-0.0411739 -0.06230037j]\n",
" [ 0.17371392-0.09247189j]\n",
" [-0.22748128+0.0418529j ]\n",
" [ 0.09444095+0.06846087j]\n",
" [-0.21784972-0.2754144j ]\n",
" [-0.17359753+0.20399286j]\n",
" [-0.01729754-0.31866732j]]\n",
"\n"
]
}
],
"source": [
"print(f\"Probabilities:\\n {outcome.probabilities()}\\n\")\n",
"print(f\"State:\\n {outcome.state()}\\n\")"
]
},
{
"cell_type": "markdown",
"id": "dd84f1f3-7aa5-4ad1-ae09-81e0aff75b5b",
"metadata": {},
"source": [
"### Compute expectation values\n",
"\n",
"Another important feature of this backend is the `expectation` function. In fact, we can compute expectation values of given observables thorugh a Qibo-friendly interface.\n",
"\n",
"---\n",
"\n",
"Let's start by importing some symbols, thanks to which we can build our observable."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "37385485-e8a3-4ab0-ad44-bcc4e9da24ca",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0: ─RY─RZ─o─────X─RY─RZ─o─────X─RY─RZ─o─────X─M─\n",
"1: ─RY─RZ─X─o───|─RY─RZ─X─o───|─RY─RZ─X─o───|─M─\n",
"2: ─RY─RZ───X─o─|─RY─RZ───X─o─|─RY─RZ───X─o─|─M─\n",
"3: ─RY─RZ─────X─o─RY─RZ─────X─o─RY─RZ─────X─o─M─\n"
]
}
],
"source": [
"# We are going to compute the expval of an Hamiltonian\n",
"# On the state prepared by the following circuit\n",
"circuit.draw()\n",
"\n",
"circuit.set_parameters(\n",
" np.random.randn(len(circuit.get_parameters()))\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "ddecc910-7804-4199-8577-a7db38a16db8",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[Qibo 0.2.20|INFO|2025-09-20 16:43:42]: Using qibojit (numba) backend on /CPU:0\n"
]
},
{
"data": {
"text/latex": [
"$\\displaystyle - 1.5 X_{0} Z_{2} + 0.5 Z_{0} Z_{1} + Z_{3}$"
],
"text/plain": [
"-1.5*X0*Z2 + 0.5*Z0*Z1 + Z3"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from qibo.symbols import Z, X, I\n",
"# We can create a symbolic Hamiltonian\n",
"form = 0.5 * Z(0) * Z(1) +- 1.5 * X(0) * Z(2) + Z(3)\n",
"hamiltonian = hamiltonians.SymbolicHamiltonian(form)\n",
"\n",
"# Let's show it\n",
"hamiltonian.form"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "163b70a3-814a-4a62-a98a-2ffca933a544",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Expectation value: 0.7143489122390747\n",
"Elapsed time: 12.4550 seconds\n"
]
}
],
"source": [
"start = time.time()\n",
"expval = quimb_backend.expectation(\n",
" circuit=circuit,\n",
" observable=hamiltonian,\n",
")\n",
"elapsed = time.time() - start\n",
"print(f\"Expectation value: {expval}\")\n",
"print(f\"Elapsed time: {elapsed:.4f} seconds\")"
]
},
{
"cell_type": "markdown",
"id": "90663e28",
"metadata": {},
"source": [
"Try with Qibo (which is by default using the Qibojit backend)\n"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "e2d05707",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Expectation value: 0.7143570920618565\n",
"Elapsed time: 0.5871 seconds\n"
]
}
],
"source": [
"start = time.time()\n",
"result = hamiltonian.expectation(circuit().state())\n",
"elapsed = time.time() - start\n",
"print(f\"Expectation value: {result}\")\n",
"print(f\"Elapsed time: {elapsed:.4f} seconds\")"
]
},
{
"cell_type": "markdown",
"id": "94df291c-9ddc-4b2e-8442-5fca00784bd8",
"metadata": {},
"source": [
"They match! 🥳"
]
},
{
"cell_type": "markdown",
"id": "d2d119fc",
"metadata": {},
"source": [
"### Derivative of the extimation function"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "8df55c5f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0: ─RY─RZ─o─────X─RY─RZ─o─────X─RY─RZ─o─────X─M─\n",
"1: ─RY─RZ─X─o───|─RY─RZ─X─o───|─RY─RZ─X─o───|─M─\n",
"2: ─RY─RZ───X─o─|─RY─RZ───X─o─|─RY─RZ───X─o─|─M─\n",
"3: ─RY─RZ─────X─o─RY─RZ─────X─o─RY─RZ─────X─o─M─\n"
]
}
],
"source": [
"# grad of this circuit returning nan for some reason...\n",
"\n",
"def build_circuit(nqubits, nlayers):\n",
" \"\"\"Construct a parametric quantum circuit.\"\"\"\n",
" circ = Circuit(nqubits)\n",
" for _ in range(nlayers):\n",
" for q in range(nqubits):\n",
" circ.add(gates.RY(q=q, theta=0.))\n",
" circ.add(gates.RZ(q=q, theta=0.))\n",
" [circ.add(gates.CNOT(q%nqubits, (q+1)%nqubits) for q in range(nqubits))]\n",
" circ.add(gates.M(*range(nqubits)))\n",
" return circ\n",
"\n",
"circuit = build_circuit(nqubits=nqubits, nlayers=3)\n",
"circuit.draw()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b02de56b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0: ─RY─RZ─RX─o─x─────────RY─RZ─RX─o─x─────────RY─RZ─RX─o─x─────────M─\n",
"1: ─RY─RZ─RX─X─x─o─x─────RY─RZ─RX─X─x─o─x─────RY─RZ─RX─X─x─o─x─────M─\n",
"2: ─RY─RZ─RX─────X─x─o─x─RY─RZ─RX─────X─x─o─x─RY─RZ─RX─────X─x─o─x─M─\n",
"3: ─RY─RZ─RX─────────X─x─RY─RZ─RX─────────X─x─RY─RZ─RX─────────X─x─M─\n"
]
}
],
"source": [
"def build_circuit(nqubits, nlayers):\n",
" circ = Circuit(nqubits)\n",
" for _ in range(nlayers):\n",
" for q in range(nqubits):\n",
" circ.add(gates.RY(q=q, theta=0.))\n",
" circ.add(gates.RZ(q=q, theta=0.))\n",
" circ.add(gates.RX(q=q, theta=0.))\n",
" for q in range(nqubits - 1):\n",
" circ.add(gates.CNOT(q, q + 1))\n",
" circ.add(gates.SWAP(q, q + 1))\n",
" circ.add(gates.M(*range(nqubits)))\n",
" return circ\n",
"\n",
"circuit = build_circuit(nqubits=nqubits, nlayers=3)\n",
"circuit.draw()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "b803250f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Array(1.4999985, dtype=float32)"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"quimb_backend.expectation(\n",
" circuit=circuit, \n",
" observable=hamiltonian,\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "0943482e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(Array(0.4465402, dtype=float32), Array([-1.5755819e-01, 9.7801067e-02, -1.2350259e-01, 1.3670625e-01,\n",
" 3.6954228e-03, -1.7437905e-02, 2.7746204e-01, -1.0357879e-01,\n",
" 1.1504190e-01, -4.5175910e-02, -4.8447326e-02, 1.4743687e-01,\n",
" -3.0708680e-01, 2.0652822e-01, 1.9298886e-01, 5.1306009e-02,\n",
" -3.3362946e-01, -7.5548244e-01, -3.0034758e-02, -5.2868712e-01,\n",
" 4.8458660e-01, -2.9802322e-08, 8.0767423e-02, 0.0000000e+00], dtype=float32))\n"
]
}
],
"source": [
"import jax\n",
"\n",
"def f(params):\n",
" circuit.set_parameters(params)\n",
" return quimb_backend.expectation(\n",
" circuit=circuit,\n",
" observable=hamiltonian,\n",
" )\n",
"\n",
"parameters = np.random.uniform(-np.pi, np.pi, size=len(circuit.get_parameters()))\n",
"print(jax.value_and_grad(f)(parameters))\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "main_env",
"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.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}