feat: changed backend generation mechanism + updated tutorial
This commit is contained in:
@@ -67,7 +67,7 @@
|
||||
"# set numpy random seed\n",
|
||||
"np.random.seed(42)\n",
|
||||
"\n",
|
||||
"quimb_backend.setup_backend_specifics(qimb_backend=\"jax\")"
|
||||
"quimb_backend.setup_backend_specifics(quimb_backend=\"jax\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -180,12 +180,10 @@
|
||||
"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",
|
||||
"/home/andrea/python_envs/3.11/lib/python3.11/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"
|
||||
"/home/andrea/python_envs/3.11/lib/python3.11/site-packages/quimb/tensor/circuit.py:215: SyntaxWarning: Unsupported operation ignored: measure\n",
|
||||
" warnings.warn(\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -193,49 +191,53 @@
|
||||
"text/plain": [
|
||||
"{'nqubits': 4,\n",
|
||||
" 'backend': qibotn (quimb),\n",
|
||||
" 'measures': Counter({'1010': 9,\n",
|
||||
" '0100': 8,\n",
|
||||
" '1101': 15,\n",
|
||||
" '1011': 4,\n",
|
||||
" '1111': 12,\n",
|
||||
" '1000': 13,\n",
|
||||
" 'measures': Counter({'1101': 14,\n",
|
||||
" '1000': 12,\n",
|
||||
" '0010': 11,\n",
|
||||
" '0011': 11,\n",
|
||||
" '0110': 9,\n",
|
||||
" '0000': 8,\n",
|
||||
" '0010': 6,\n",
|
||||
" '0011': 6,\n",
|
||||
" '0101': 8,\n",
|
||||
" '1110': 5,\n",
|
||||
" '0110': 5,\n",
|
||||
" '0111': 1}),\n",
|
||||
" 'measured_probabilities': {'1101': np.float64(0.12331159869893256),\n",
|
||||
" '1000': np.float64(0.11330883548333587),\n",
|
||||
" '1111': np.float64(0.10184806171791962),\n",
|
||||
" '1010': np.float64(0.03872758515126756),\n",
|
||||
" '0100': np.float64(0.07142939529687138),\n",
|
||||
" '0000': np.float64(0.08390937969317269),\n",
|
||||
" '0101': np.float64(0.05622305772698622),\n",
|
||||
" '0010': np.float64(0.09466860481989385),\n",
|
||||
" '0011': np.float64(0.07571277233522114),\n",
|
||||
" '1110': np.float64(0.07174919872959985),\n",
|
||||
" '0110': np.float64(0.05146064807369214),\n",
|
||||
" '1011': np.float64(0.053499396925872744),\n",
|
||||
" '0111': np.float64(0.04029185074729259)},\n",
|
||||
" '1010': 7,\n",
|
||||
" '1110': 6,\n",
|
||||
" '0100': 5,\n",
|
||||
" '1111': 5,\n",
|
||||
" '1011': 5,\n",
|
||||
" '0101': 4,\n",
|
||||
" '0111': 1,\n",
|
||||
" '0001': 1,\n",
|
||||
" '1100': 1}),\n",
|
||||
" 'measured_probabilities': {'1101': np.float64(0.12331159869893284),\n",
|
||||
" '1000': np.float64(0.11330883548333684),\n",
|
||||
" '0010': np.float64(0.0946686048198943),\n",
|
||||
" '0011': np.float64(0.07571277233522157),\n",
|
||||
" '0110': np.float64(0.051460648073692314),\n",
|
||||
" '0000': np.float64(0.08390937969317334),\n",
|
||||
" '1010': np.float64(0.03872758515126775),\n",
|
||||
" '1110': np.float64(0.07174919872960006),\n",
|
||||
" '0100': np.float64(0.07142939529687146),\n",
|
||||
" '1111': np.float64(0.10184806171791994),\n",
|
||||
" '1011': np.float64(0.053499396925872716),\n",
|
||||
" '0101': np.float64(0.05622305772698606),\n",
|
||||
" '0111': np.float64(0.040291850747292815),\n",
|
||||
" '0001': np.float64(0.004677011195208322),\n",
|
||||
" '1100': np.float64(0.013605984872668443)},\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)}"
|
||||
" 'statevector': Array([[ 0.08809626-0.27595j ],\n",
|
||||
" [-0.05174781+0.04471214j],\n",
|
||||
" [ 0.00470146+0.30764672j],\n",
|
||||
" [-0.27208942+0.04098931j],\n",
|
||||
" [ 0.18807825+0.1898841j ],\n",
|
||||
" [ 0.22377063+0.07842041j],\n",
|
||||
" [-0.18900302+0.12545316j],\n",
|
||||
" [ 0.17105258-0.10503745j],\n",
|
||||
" [ 0.24859732-0.22695422j],\n",
|
||||
" [-0.04117391-0.0623003j ],\n",
|
||||
" [ 0.17371394-0.09247189j],\n",
|
||||
" [-0.22748126+0.04185291j],\n",
|
||||
" [ 0.09444097+0.06846087j],\n",
|
||||
" [-0.21784975-0.2754144j ],\n",
|
||||
" [-0.17359754+0.20399287j],\n",
|
||||
" [-0.01729751-0.31866732j]], dtype=complex64)}"
|
||||
]
|
||||
},
|
||||
"execution_count": 8,
|
||||
@@ -272,25 +274,25 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Probabilities:\n",
|
||||
" {'1101': np.float64(0.12331159869893256), '1000': np.float64(0.11330883548333587), '1111': np.float64(0.10184806171791962), '1010': np.float64(0.03872758515126756), '0100': np.float64(0.07142939529687138), '0000': np.float64(0.08390937969317269), '0101': np.float64(0.05622305772698622), '0010': np.float64(0.09466860481989385), '0011': np.float64(0.07571277233522114), '1110': np.float64(0.07174919872959985), '0110': np.float64(0.05146064807369214), '1011': np.float64(0.053499396925872744), '0111': np.float64(0.04029185074729259)}\n",
|
||||
" {'1101': np.float64(0.12331159869893284), '1000': np.float64(0.11330883548333684), '0010': np.float64(0.0946686048198943), '0011': np.float64(0.07571277233522157), '0110': np.float64(0.051460648073692314), '0000': np.float64(0.08390937969317334), '1010': np.float64(0.03872758515126775), '1110': np.float64(0.07174919872960006), '0100': np.float64(0.07142939529687146), '1111': np.float64(0.10184806171791994), '1011': np.float64(0.053499396925872716), '0101': np.float64(0.05622305772698606), '0111': np.float64(0.040291850747292815), '0001': np.float64(0.004677011195208322), '1100': np.float64(0.013605984872668443)}\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",
|
||||
" [[ 0.08809626-0.27595j ]\n",
|
||||
" [-0.05174781+0.04471214j]\n",
|
||||
" [ 0.00470146+0.30764672j]\n",
|
||||
" [-0.27208942+0.04098931j]\n",
|
||||
" [ 0.18807825+0.1898841j ]\n",
|
||||
" [ 0.22377063+0.07842041j]\n",
|
||||
" [-0.18900302+0.12545316j]\n",
|
||||
" [ 0.17105258-0.10503745j]\n",
|
||||
" [ 0.24859732-0.22695422j]\n",
|
||||
" [-0.04117391-0.0623003j ]\n",
|
||||
" [ 0.17371394-0.09247189j]\n",
|
||||
" [-0.22748126+0.04185291j]\n",
|
||||
" [ 0.09444097+0.06846087j]\n",
|
||||
" [-0.21784975-0.2754144j ]\n",
|
||||
" [-0.17359754+0.20399287j]\n",
|
||||
" [-0.01729751-0.31866732j]]\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
@@ -338,7 +340,7 @@
|
||||
"quimb_backend = construct_backend(backend=\"qibotn\", platform=\"quimb\")\n",
|
||||
"\n",
|
||||
"quimb_backend.setup_backend_specifics(\n",
|
||||
" qimb_backend =\"jax\", \n",
|
||||
" quimb_backend =\"jax\", \n",
|
||||
" contractions_optimizer='auto-hq'\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
@@ -349,21 +351,21 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"execution_count": 18,
|
||||
"id": "b2a0decb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from qibo.symbols import X, Z, Y\n",
|
||||
"from qibo.hamiltonians import XXZ\n",
|
||||
"\n",
|
||||
"# define Hamiltonian\n",
|
||||
"operators = [\"xzy\", \"yxzy\", \"zy\"]\n",
|
||||
"qubits = [\"011\", \"0112\", \"01\"]\n",
|
||||
"coefficients = [\"1\", \"2\", \"j\"]\n",
|
||||
"hamiltonian = (operators, qubits, coefficients)"
|
||||
"hamiltonian = XXZ(4, dense=False, backend=quimb_backend)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"execution_count": 19,
|
||||
"id": "bd734be8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -407,19 +409,14 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Expectation value: 0.0\n",
|
||||
"Elapsed time: 0.1071 seconds\n"
|
||||
"Expectation value: 2.0\n",
|
||||
"Elapsed time: 0.0268 seconds\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"start = time.time()\n",
|
||||
"expval = quimb_backend.expectation(\n",
|
||||
" circuit=circuit,\n",
|
||||
" operators_list=hamiltonian[0],\n",
|
||||
" sites_list=hamiltonian[1],\n",
|
||||
" coeffs_list=hamiltonian[2]\n",
|
||||
" )\n",
|
||||
"expval = hamiltonian.expectation(circuit)\n",
|
||||
"\n",
|
||||
"elapsed = time.time() - start\n",
|
||||
"print(f\"Expectation value: {expval}\")\n",
|
||||
@@ -436,24 +433,29 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 22,
|
||||
"execution_count": 21,
|
||||
"id": "fb1436c8",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[Qibo 0.2.21|INFO|2025-10-27 16:24:00]: Using numpy backend on /CPU:0\n",
|
||||
"WARNING:root:Calculation of expectation values starting from the state is deprecated, use the ``expectation_from_state`` method if you really need it, or simply pass the circuit you want to calculate the expectation value from.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Expectation value: 1.5\n",
|
||||
"Elapsed time: 0.0501 seconds\n"
|
||||
"Expectation value: 2.0\n",
|
||||
"Elapsed time: 0.0360 seconds\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"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",
|
||||
"sym_hamiltonian = hamiltonians.SymbolicHamiltonian(form)\n",
|
||||
"sym_hamiltonian = XXZ(4, dense=False, backend=None)\n",
|
||||
"\n",
|
||||
"# Let's show it\n",
|
||||
"sym_hamiltonian.form\n",
|
||||
@@ -488,40 +490,52 @@
|
||||
"id": "6a3b26e4",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"/home/andrea/python_envs/3.11/lib/python3.11/site-packages/quimb/tensor/circuit.py:4927: UserWarning: Unsupported options for computing local_expectation with an MPS circuit supplied, ignoring: R, None, None, jax, None\n",
|
||||
" warnings.warn(\n",
|
||||
"/home/andrea/python_envs/3.11/lib/python3.11/site-packages/quimb/tensor/circuit.py:4927: UserWarning: Unsupported options for computing local_expectation with an MPS circuit supplied, ignoring: R, None, None, jax, None\n",
|
||||
" warnings.warn(\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[ 8.19939339e-10 -3.14190913e-08 -2.99498648e-09 -1.03641796e-07\n",
|
||||
" 8.48652704e-10 1.00297093e-07 -6.75429277e-08 -9.78565140e-09\n",
|
||||
" -5.11915417e-08 1.29225235e-08 -7.44280655e-08 -3.49115048e-08\n",
|
||||
" -4.98508879e-09 6.80729357e-08 -3.29755920e-08 4.20008526e-08\n",
|
||||
" -2.89742630e-08 1.18602941e-07 -2.88252178e-08 5.57985391e-09\n",
|
||||
" -3.17434115e-08 -1.03342952e-08 1.34079716e-08 -7.05437886e-09\n",
|
||||
" -4.34059650e-08 -2.18019203e-08 -5.36932561e-08 -6.38544009e-08\n",
|
||||
" 5.85312279e-08 8.45709067e-08 -1.12777876e-09 -6.41545981e-08\n",
|
||||
" 7.25317406e-08 4.10035668e-08 -1.29046382e-08 6.07501676e-08]\n"
|
||||
"[-0.24630009 0.8370421 -0.11103702 -0.12855841 0.41325414 -0.0628037\n",
|
||||
" 0.51638705 0.794163 -0.27972788 -1.0718998 0.02731732 1.0153619\n",
|
||||
" -0.34494495 1.5744264 0.26920277 -0.36333832 0.12331417 0.5196531\n",
|
||||
" 1.1294655 0.29257926 -0.18237355 0.8914014 -0.9471657 0.3492473\n",
|
||||
" -0.3477673 0.24325958 0.04818404 -0.87983793 0.47196424 0.36605012\n",
|
||||
" 1.005 0.65054715 -0.94860053 0.14459445 0.36571163 -0.2550101 ]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"def f(circuit, hamiltonian, params):\n",
|
||||
" circuit.set_parameters(params)\n",
|
||||
" return quimb_backend.expectation(\n",
|
||||
" return hamiltonian.expectation(\n",
|
||||
" circuit=circuit,\n",
|
||||
" operators_list=hamiltonian[0],\n",
|
||||
" sites_list=hamiltonian[1],\n",
|
||||
" coeffs_list=hamiltonian[2]\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"parameters = np.random.uniform(-np.pi, np.pi, size=len(circuit.get_parameters()))\n",
|
||||
"print(jax.grad(f, argnums=2)(circuit, hamiltonian, parameters))\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "aeafa5a6-2afa-429c-a101-effa84bac1d2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "main_env",
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
@@ -535,7 +549,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.3"
|
||||
"version": "3.11.12"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -4,7 +4,6 @@ from qibo.config import raise_error
|
||||
|
||||
from qibotn.backends.abstract import QibotnBackend
|
||||
from qibotn.backends.cutensornet import CuTensorNet # pylint: disable=E0401
|
||||
from qibotn.backends.quimb import QuimbBackend
|
||||
|
||||
PLATFORMS = ("cutensornet", "qutensornet", "qmatchatea")
|
||||
|
||||
@@ -26,9 +25,11 @@ class MetaBackend:
|
||||
if platform == "cutensornet": # pragma: no cover
|
||||
return CuTensorNet(runcard)
|
||||
elif platform == "quimb": # pragma: no cover
|
||||
import qibotn.backends.quimb as qmb
|
||||
|
||||
quimb_backend = kwargs.get("quimb_backend", "numpy")
|
||||
contraction_optimizer = kwargs.get("contraction_optimizer", "auto-hq")
|
||||
return QuimbBackend(
|
||||
return qmb.BACKENDS[quimb_backend](
|
||||
quimb_backend=quimb_backend, contraction_optimizer=contraction_optimizer
|
||||
)
|
||||
elif platform == "qmatchatea": # pragma: no cover
|
||||
|
||||
@@ -38,302 +38,306 @@ GATE_MAP = {
|
||||
}
|
||||
|
||||
|
||||
if not __name__ == "__main__":
|
||||
def __init__(self, quimb_backend="numpy", contraction_optimizer="auto-hq"):
|
||||
super(self.__class__, self).__init__()
|
||||
|
||||
def __init__(self, quimb_backend="numpy", contraction_optimizer="auto-hq"):
|
||||
super(self.__class__, self).__init__()
|
||||
self.name = "qibotn"
|
||||
self.platform = "quimb"
|
||||
self.backend = quimb_backend
|
||||
|
||||
self.name = "qibotn"
|
||||
self.platform = "quimb"
|
||||
self.backend = quimb_backend
|
||||
self.ansatz = None
|
||||
self.max_bond_dimension = None
|
||||
self.svd_cutoff = None
|
||||
self.n_most_frequent_states = None
|
||||
|
||||
self.ansatz = None
|
||||
self.max_bond_dimension = None
|
||||
self.svd_cutoff = None
|
||||
self.n_most_frequent_states = None
|
||||
self.configure_tn_simulation()
|
||||
self.setup_backend_specifics(
|
||||
quimb_backend=quimb_backend, contractions_optimizer=contraction_optimizer
|
||||
)
|
||||
|
||||
self.configure_tn_simulation()
|
||||
self.setup_backend_specifics(
|
||||
quimb_backend=quimb_backend, contractions_optimizer=contraction_optimizer
|
||||
|
||||
def configure_tn_simulation(
|
||||
self,
|
||||
ansatz: str = "mps",
|
||||
max_bond_dimension: Optional[int] = None,
|
||||
svd_cutoff: Optional[float] = 1e-10,
|
||||
n_most_frequent_states: int = 100,
|
||||
):
|
||||
"""
|
||||
Configure tensor network simulation.
|
||||
|
||||
Args:
|
||||
ansatz : str, optional
|
||||
The tensor network ansatz to use. Default is `None` and, in this case, a
|
||||
generic Circuit Quimb class is used.
|
||||
max_bond_dimension : int, optional
|
||||
The maximum bond dimension for the MPS ansatz. Default is 10.
|
||||
|
||||
Notes:
|
||||
- The ansatz determines the tensor network structure used for simulation. Currently, only "MPS" is supported.
|
||||
- The `max_bond_dimension` parameter controls the maximum allowed bond dimension for the MPS ansatz.
|
||||
"""
|
||||
self.ansatz = ansatz
|
||||
self.max_bond_dimension = max_bond_dimension
|
||||
self.svd_cutoff = svd_cutoff
|
||||
self.n_most_frequent_states = n_most_frequent_states
|
||||
|
||||
|
||||
@property
|
||||
def circuit_ansatz(self):
|
||||
if self.ansatz == "mps":
|
||||
return qtn.CircuitMPS
|
||||
return qtn.Circuit
|
||||
|
||||
|
||||
def setup_backend_specifics(
|
||||
self, quimb_backend="numpy", contractions_optimizer="auto-hq"
|
||||
):
|
||||
"""Setup backend specifics.
|
||||
Args:
|
||||
quimb_backend: str
|
||||
The backend to use for the quimb tensor network simulation.
|
||||
contractions_optimizer: str, optional
|
||||
The contractions_optimizer to use for the quimb tensor network simulation.
|
||||
"""
|
||||
# this is not really working because it does not change the inheritance
|
||||
if quimb_backend == "jax":
|
||||
import jax.numpy as jnp
|
||||
|
||||
self.np = jnp
|
||||
elif quimb_backend == "numpy":
|
||||
import numpy as np
|
||||
|
||||
self.np = np
|
||||
elif quimb_backend == "torch":
|
||||
import torch
|
||||
|
||||
self.np = torch
|
||||
else:
|
||||
raise_error(ValueError, f"Unsupported quimb backend: {quimb_backend}")
|
||||
|
||||
self.backend = quimb_backend
|
||||
self.contractions_optimizer = contractions_optimizer
|
||||
|
||||
|
||||
def execute_circuit(
|
||||
self,
|
||||
circuit: Circuit,
|
||||
initial_state=None,
|
||||
nshots=None,
|
||||
return_array=False,
|
||||
):
|
||||
"""
|
||||
Execute a quantum circuit using the specified tensor network ansatz and initial state.
|
||||
|
||||
Args:
|
||||
circuit : QuantumCircuit
|
||||
The quantum circuit to be executed.
|
||||
initial_state : array-like, optional
|
||||
The initial state of the quantum system. Only supported for Matrix Product States (MPS) ansatz.
|
||||
nshots : int, optional
|
||||
The number of shots for sampling the circuit. If None, no sampling is performed, and the full statevector is used.
|
||||
return_array : bool, optional
|
||||
If True, returns the statevector as a dense array. Default is False.
|
||||
|
||||
Returns:
|
||||
TensorNetworkResult
|
||||
An object containing the results of the circuit execution, including:
|
||||
- nqubits: Number of qubits in the circuit.
|
||||
- backend: The backend used for execution.
|
||||
- measures: The measurement frequencies if nshots is specified, otherwise None.
|
||||
- measured_probabilities: A dictionary of computational basis states and their probabilities.
|
||||
- prob_type: The type of probability computation used (currently "default").
|
||||
- statevector: The final statevector as a dense array if return_array is True, otherwise None.
|
||||
|
||||
Raises:
|
||||
ValueError
|
||||
If an initial state is provided but the ansatz is not "MPS".
|
||||
|
||||
Notes:
|
||||
- The ansatz determines the tensor network structure used for simulation. Currently, only "MPS" is supported.
|
||||
- If `initial_state` is provided, it must be compatible with the MPS ansatz.
|
||||
- The `nshots` parameter enables sampling from the circuit's output distribution. If not specified, the full statevector is computed.
|
||||
"""
|
||||
if initial_state is not None and self.ansatz == "MPS":
|
||||
initial_state = qtn.tensor_1d.MatrixProductState.from_dense(
|
||||
initial_state, 2
|
||||
) # 2 is the physical dimension
|
||||
elif initial_state is not None:
|
||||
raise_error(ValueError, "Initial state not None supported only for MPS ansatz.")
|
||||
|
||||
circ_quimb = self.circuit_ansatz.from_openqasm2_str(
|
||||
circuit.to_qasm(), psi0=initial_state
|
||||
)
|
||||
|
||||
if nshots:
|
||||
frequencies = Counter(circ_quimb.sample(nshots))
|
||||
main_frequencies = {
|
||||
state: count
|
||||
for state, count in frequencies.most_common(self.n_most_frequent_states)
|
||||
}
|
||||
computational_states = list(main_frequencies.keys())
|
||||
amplitudes = {
|
||||
state: circ_quimb.amplitude(state) for state in computational_states
|
||||
}
|
||||
measured_probabilities = {
|
||||
state: abs(amplitude) ** 2 for state, amplitude in amplitudes.items()
|
||||
}
|
||||
else:
|
||||
frequencies = None
|
||||
measured_probabilities = None
|
||||
|
||||
statevector = (
|
||||
circ_quimb.to_dense(backend=self.backend, optimize=self.contractions_optimizer)
|
||||
if return_array
|
||||
else None
|
||||
)
|
||||
return TensorNetworkResult(
|
||||
nqubits=circuit.nqubits,
|
||||
backend=self,
|
||||
measures=frequencies,
|
||||
measured_probabilities=measured_probabilities,
|
||||
prob_type="default",
|
||||
statevector=statevector,
|
||||
)
|
||||
|
||||
|
||||
def expectation_observable_symbolic(
|
||||
self, circuit, operators_list, sites_list, coeffs_list, nqubits
|
||||
):
|
||||
"""
|
||||
Compute the expectation value of a symbolic Hamiltonian on a quantum circuit using tensor network contraction.
|
||||
This method takes a Qibo circuit, converts it to a Quimb tensor network circuit, and evaluates the expectation value
|
||||
of a Hamiltonian specified by three lists of strings: operators, sites, and coefficients.
|
||||
The expectation value is computed by summing the contributions from each term in the Hamiltonian, where each term's
|
||||
expectation is calculated using Quimb's `local_expectation` function.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
circuit : qibo.models.Circuit
|
||||
The quantum circuit to evaluate, provided as a Qibo circuit object.
|
||||
operators_list : list of str
|
||||
List of operator strings representing the symbolic Hamiltonian terms.
|
||||
sites_list : list of str
|
||||
List of strings, each specifying the qubits (sites) the corresponding operator acts on.
|
||||
coeffs_list : list of str
|
||||
List of strings representing the coefficients for each Hamiltonian term.
|
||||
Returns
|
||||
-------
|
||||
float
|
||||
The real part of the expectation value of the Hamiltonian on the given circuit state.
|
||||
"""
|
||||
quimb_circuit = self._qibo_circuit_to_quimb(
|
||||
circuit,
|
||||
quimb_circuit_type=self.circuit_ansatz,
|
||||
gate_opts={"max_bond": self.max_bond_dimension, "cutoff": self.svd_cutoff},
|
||||
)
|
||||
|
||||
expectation_value = 0.0
|
||||
for opstr, sites, coeff in zip(operators_list, sites_list, coeffs_list):
|
||||
|
||||
ops = self._string_to_quimb_operator(opstr)
|
||||
coeff = coeff.real
|
||||
|
||||
exp_values = quimb_circuit.local_expectation(
|
||||
ops,
|
||||
where=sites,
|
||||
backend=self.backend,
|
||||
optimize=self.contractions_optimizer,
|
||||
simplify_sequence="R",
|
||||
)
|
||||
|
||||
def configure_tn_simulation(
|
||||
self,
|
||||
ansatz: str = "mps",
|
||||
max_bond_dimension: Optional[int] = None,
|
||||
svd_cutoff: Optional[float] = 1e-10,
|
||||
n_most_frequent_states: int = 100,
|
||||
):
|
||||
"""
|
||||
Configure tensor network simulation.
|
||||
expectation_value = expectation_value + coeff * exp_values
|
||||
|
||||
Args:
|
||||
ansatz : str, optional
|
||||
The tensor network ansatz to use. Default is `None` and, in this case, a
|
||||
generic Circuit Quimb class is used.
|
||||
max_bond_dimension : int, optional
|
||||
The maximum bond dimension for the MPS ansatz. Default is 10.
|
||||
return self.np.real(expectation_value)
|
||||
|
||||
Notes:
|
||||
- The ansatz determines the tensor network structure used for simulation. Currently, only "MPS" is supported.
|
||||
- The `max_bond_dimension` parameter controls the maximum allowed bond dimension for the MPS ansatz.
|
||||
"""
|
||||
self.ansatz = ansatz
|
||||
self.max_bond_dimension = max_bond_dimension
|
||||
self.svd_cutoff = svd_cutoff
|
||||
self.n_most_frequent_states = n_most_frequent_states
|
||||
|
||||
@property
|
||||
def circuit_ansatz(self):
|
||||
if self.ansatz == "mps":
|
||||
return qtn.CircuitMPS
|
||||
return qtn.Circuit
|
||||
def _qibo_circuit_to_quimb(
|
||||
self, qibo_circ, quimb_circuit_type=qtn.Circuit, **circuit_kwargs
|
||||
):
|
||||
"""
|
||||
Convert a Qibo Circuit to a Quimb Circuit. Measurement gates are ignored. If are given gates not supported by Quimb, an error is raised.
|
||||
|
||||
def setup_backend_specifics(
|
||||
self, quimb_backend="numpy", contractions_optimizer="auto-hq"
|
||||
):
|
||||
"""Setup backend specifics.
|
||||
Args:
|
||||
qimb_backend: str
|
||||
The backend to use for the quimb tensor network simulation.
|
||||
contractions_optimizer: str, optional
|
||||
The contractions_optimizer to use for the quimb tensor network simulation.
|
||||
"""
|
||||
# this is not really working because it does not change the inheritance
|
||||
if quimb_backend == "jax":
|
||||
import jax.numpy as jnp
|
||||
Parameters
|
||||
----------
|
||||
qibo_circ : qibo.models.circuit.Circuit
|
||||
The circuit to convert.
|
||||
quimb_circuit_type : type
|
||||
The Quimb circuit class to use (Circuit, CircuitMPS, etc).
|
||||
circuit_kwargs : dict
|
||||
Extra arguments to pass to the Quimb circuit constructor.
|
||||
|
||||
self.np = jnp
|
||||
elif quimb_backend == "numpy":
|
||||
import numpy as np
|
||||
Returns
|
||||
-------
|
||||
circ : quimb.tensor.circuit.Circuit
|
||||
The converted circuit.
|
||||
"""
|
||||
nqubits = qibo_circ.nqubits
|
||||
circ = quimb_circuit_type(nqubits, **circuit_kwargs)
|
||||
|
||||
self.np = np
|
||||
elif quimb_backend == "torch":
|
||||
import torch
|
||||
for gate in qibo_circ.queue:
|
||||
gname = getattr(gate, "name", None)
|
||||
qname = GATE_MAP.get(gname, None)
|
||||
if qname == "measure":
|
||||
continue
|
||||
if qname is None:
|
||||
raise_error(ValueError, f"Gate {gname} not supported in Quimb backend.")
|
||||
|
||||
self.np = torch
|
||||
params = getattr(gate, "parameters", ())
|
||||
qubits = getattr(gate, "qubits", ())
|
||||
|
||||
is_parametrized = isinstance(gate, ParametrizedGate) and getattr(
|
||||
gate, "trainable", True
|
||||
)
|
||||
if is_parametrized:
|
||||
circ.apply_gate(qname, *params, *qubits, parametrized=is_parametrized)
|
||||
else:
|
||||
raise_error(ValueError, f"Unsupported quimb backend: {quimb_backend}")
|
||||
|
||||
self.backend = quimb_backend
|
||||
self.contractions_optimizer = contractions_optimizer
|
||||
|
||||
def execute_circuit(
|
||||
self,
|
||||
circuit: Circuit,
|
||||
initial_state=None,
|
||||
nshots=None,
|
||||
return_array=False,
|
||||
):
|
||||
"""
|
||||
Execute a quantum circuit using the specified tensor network ansatz and initial state.
|
||||
|
||||
Args:
|
||||
circuit : QuantumCircuit
|
||||
The quantum circuit to be executed.
|
||||
initial_state : array-like, optional
|
||||
The initial state of the quantum system. Only supported for Matrix Product States (MPS) ansatz.
|
||||
nshots : int, optional
|
||||
The number of shots for sampling the circuit. If None, no sampling is performed, and the full statevector is used.
|
||||
return_array : bool, optional
|
||||
If True, returns the statevector as a dense array. Default is False.
|
||||
|
||||
Returns:
|
||||
TensorNetworkResult
|
||||
An object containing the results of the circuit execution, including:
|
||||
- nqubits: Number of qubits in the circuit.
|
||||
- backend: The backend used for execution.
|
||||
- measures: The measurement frequencies if nshots is specified, otherwise None.
|
||||
- measured_probabilities: A dictionary of computational basis states and their probabilities.
|
||||
- prob_type: The type of probability computation used (currently "default").
|
||||
- statevector: The final statevector as a dense array if return_array is True, otherwise None.
|
||||
|
||||
Raises:
|
||||
ValueError
|
||||
If an initial state is provided but the ansatz is not "MPS".
|
||||
|
||||
Notes:
|
||||
- The ansatz determines the tensor network structure used for simulation. Currently, only "MPS" is supported.
|
||||
- If `initial_state` is provided, it must be compatible with the MPS ansatz.
|
||||
- The `nshots` parameter enables sampling from the circuit's output distribution. If not specified, the full statevector is computed.
|
||||
"""
|
||||
if initial_state is not None and self.ansatz == "MPS":
|
||||
initial_state = qtn.tensor_1d.MatrixProductState.from_dense(
|
||||
initial_state, 2
|
||||
) # 2 is the physical dimension
|
||||
elif initial_state is not None:
|
||||
raise_error(
|
||||
ValueError, "Initial state not None supported only for MPS ansatz."
|
||||
circ.apply_gate(
|
||||
qname,
|
||||
*params,
|
||||
*qubits,
|
||||
)
|
||||
|
||||
circ_quimb = self.circuit_ansatz.from_openqasm2_str(
|
||||
circuit.to_qasm(), psi0=initial_state
|
||||
)
|
||||
|
||||
if nshots:
|
||||
frequencies = Counter(circ_quimb.sample(nshots))
|
||||
main_frequencies = {
|
||||
state: count
|
||||
for state, count in frequencies.most_common(self.n_most_frequent_states)
|
||||
}
|
||||
computational_states = list(main_frequencies.keys())
|
||||
amplitudes = {
|
||||
state: circ_quimb.amplitude(state) for state in computational_states
|
||||
}
|
||||
measured_probabilities = {
|
||||
state: abs(amplitude) ** 2 for state, amplitude in amplitudes.items()
|
||||
}
|
||||
else:
|
||||
frequencies = None
|
||||
measured_probabilities = None
|
||||
|
||||
statevector = (
|
||||
circ_quimb.to_dense(
|
||||
backend=self.backend, optimize=self.contractions_optimizer
|
||||
)
|
||||
if return_array
|
||||
else None
|
||||
)
|
||||
return TensorNetworkResult(
|
||||
nqubits=circuit.nqubits,
|
||||
backend=self,
|
||||
measures=frequencies,
|
||||
measured_probabilities=measured_probabilities,
|
||||
prob_type="default",
|
||||
statevector=statevector,
|
||||
)
|
||||
|
||||
def expectation_observable_symbolic(
|
||||
self, circuit, operators_list, sites_list, coeffs_list, nqubits
|
||||
):
|
||||
"""
|
||||
Compute the expectation value of a symbolic Hamiltonian on a quantum circuit using tensor network contraction.
|
||||
This method takes a Qibo circuit, converts it to a Quimb tensor network circuit, and evaluates the expectation value
|
||||
of a Hamiltonian specified by three lists of strings: operators, sites, and coefficients.
|
||||
The expectation value is computed by summing the contributions from each term in the Hamiltonian, where each term's
|
||||
expectation is calculated using Quimb's `local_expectation` function.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
circuit : qibo.models.Circuit
|
||||
The quantum circuit to evaluate, provided as a Qibo circuit object.
|
||||
operators_list : list of str
|
||||
List of operator strings representing the symbolic Hamiltonian terms.
|
||||
sites_list : list of str
|
||||
List of strings, each specifying the qubits (sites) the corresponding operator acts on.
|
||||
coeffs_list : list of str
|
||||
List of strings representing the coefficients for each Hamiltonian term.
|
||||
Returns
|
||||
-------
|
||||
float
|
||||
The real part of the expectation value of the Hamiltonian on the given circuit state.
|
||||
"""
|
||||
quimb_circuit = self._qibo_circuit_to_quimb(
|
||||
circuit,
|
||||
quimb_circuit_type=self.circuit_ansatz,
|
||||
gate_opts={"max_bond": self.max_bond_dimension, "cutoff": self.svd_cutoff},
|
||||
)
|
||||
|
||||
expectation_value = 0.0
|
||||
for opstr, sites, coeff in zip(operators_list, sites_list, coeffs_list):
|
||||
|
||||
ops = self._string_to_quimb_operator(opstr)
|
||||
coeff = coeff.real
|
||||
|
||||
exp_values = quimb_circuit.local_expectation(
|
||||
ops,
|
||||
where=sites,
|
||||
backend=self.backend,
|
||||
optimize=self.contractions_optimizer,
|
||||
simplify_sequence="R",
|
||||
)
|
||||
|
||||
expectation_value = expectation_value + coeff * exp_values
|
||||
|
||||
return self.np.real(expectation_value)
|
||||
|
||||
def _qibo_circuit_to_quimb(
|
||||
self, qibo_circ, quimb_circuit_type=qtn.Circuit, **circuit_kwargs
|
||||
):
|
||||
"""
|
||||
Convert a Qibo Circuit to a Quimb Circuit. Measurement gates are ignored. If are given gates not supported by Quimb, an error is raised.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
qibo_circ : qibo.models.circuit.Circuit
|
||||
The circuit to convert.
|
||||
quimb_circuit_type : type
|
||||
The Quimb circuit class to use (Circuit, CircuitMPS, etc).
|
||||
circuit_kwargs : dict
|
||||
Extra arguments to pass to the Quimb circuit constructor.
|
||||
|
||||
Returns
|
||||
-------
|
||||
circ : quimb.tensor.circuit.Circuit
|
||||
The converted circuit.
|
||||
"""
|
||||
nqubits = qibo_circ.nqubits
|
||||
circ = quimb_circuit_type(nqubits, **circuit_kwargs)
|
||||
|
||||
for gate in qibo_circ.queue:
|
||||
gname = getattr(gate, "name", None)
|
||||
qname = GATE_MAP.get(gname, None)
|
||||
if qname == "measure":
|
||||
continue
|
||||
if qname is None:
|
||||
raise_error(ValueError, f"Gate {gname} not supported in Quimb backend.")
|
||||
|
||||
params = getattr(gate, "parameters", ())
|
||||
qubits = getattr(gate, "qubits", ())
|
||||
|
||||
is_parametrized = isinstance(gate, ParametrizedGate) and getattr(
|
||||
gate, "trainable", True
|
||||
)
|
||||
if is_parametrized:
|
||||
circ.apply_gate(qname, *params, *qubits, parametrized=is_parametrized)
|
||||
else:
|
||||
circ.apply_gate(
|
||||
qname,
|
||||
*params,
|
||||
*qubits,
|
||||
)
|
||||
return circ
|
||||
|
||||
def _string_to_quimb_operator(self, op_str):
|
||||
"""
|
||||
Convert a Pauli string (e.g. 'xzy') to a Quimb operator using '&' chaining.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
op_str : str
|
||||
A string like 'xzy', where each character is one of 'x', 'y', 'z', 'i'.
|
||||
|
||||
Returns
|
||||
-------
|
||||
qu_op : quimb.Qarray
|
||||
The corresponding Quimb operator.
|
||||
"""
|
||||
op_str = op_str.lower()
|
||||
op = qu.pauli(op_str[0])
|
||||
for c in op_str[1:]:
|
||||
op = op & qu.pauli(c)
|
||||
return op
|
||||
return circ
|
||||
|
||||
|
||||
def QuimbBackend(
|
||||
quimb_backend: str = "numpy", contraction_optimizer="auto-hq"
|
||||
) -> QibotnBackend:
|
||||
def _string_to_quimb_operator(self, op_str):
|
||||
"""
|
||||
Convert a Pauli string (e.g. 'xzy') to a Quimb operator using '&' chaining.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
op_str : str
|
||||
A string like 'xzy', where each character is one of 'x', 'y', 'z', 'i'.
|
||||
|
||||
Returns
|
||||
-------
|
||||
qu_op : quimb.Qarray
|
||||
The corresponding Quimb operator.
|
||||
"""
|
||||
op_str = op_str.lower()
|
||||
op = qu.pauli(op_str[0])
|
||||
for c in op_str[1:]:
|
||||
op = op & qu.pauli(c)
|
||||
return op
|
||||
|
||||
|
||||
CLASSES_ROOTS = {"numpy": "Numpy", "torch": "PyTorch", "jax": "Jax"}
|
||||
|
||||
METHODS = {
|
||||
"__init__": __init__,
|
||||
"configure_tn_simulation": configure_tn_simulation,
|
||||
"setup_backend_specifics": setup_backend_specifics,
|
||||
"execute_circuit": execute_circuit,
|
||||
"expectation_observable_symbolic": expectation_observable_symbolic,
|
||||
"_qibo_circuit_to_quimb": _qibo_circuit_to_quimb,
|
||||
"_string_to_quimb_operator": _string_to_quimb_operator,
|
||||
"circuit_ansatz": circuit_ansatz,
|
||||
}
|
||||
|
||||
|
||||
def _generate_backend(quimb_backend: str = "numpy"):
|
||||
bases = (QibotnBackend,)
|
||||
methods = {
|
||||
"__init__": __init__,
|
||||
"configure_tn_simulation": configure_tn_simulation,
|
||||
"setup_backend_specifics": setup_backend_specifics,
|
||||
"execute_circuit": execute_circuit,
|
||||
"expectation_observable_symbolic": expectation_observable_symbolic,
|
||||
"_qibo_circuit_to_quimb": _qibo_circuit_to_quimb,
|
||||
"_string_to_quimb_operator": _string_to_quimb_operator,
|
||||
"circuit_ansatz": circuit_ansatz,
|
||||
}
|
||||
|
||||
if quimb_backend == "numpy":
|
||||
from qibo.backends import NumpyBackend
|
||||
|
||||
@@ -349,4 +353,22 @@ def QuimbBackend(
|
||||
else:
|
||||
raise_error(ValueError, f"Unsupported quimb backend: {quimb_backend}")
|
||||
|
||||
return type("QuimbBackend", bases, methods)(quimb_backend, contraction_optimizer)
|
||||
return type(f"Quimb{CLASSES_ROOTS[quimb_backend]}Backend", bases, METHODS)
|
||||
|
||||
|
||||
BACKENDS = {}
|
||||
for k, v in CLASSES_ROOTS.items():
|
||||
backend_name = f"Quimb{v}Backend"
|
||||
try:
|
||||
backend = _generate_backend(k)
|
||||
BACKENDS[k] = backend
|
||||
globals()[backend_name] = backend
|
||||
except ImportError:
|
||||
continue
|
||||
|
||||
|
||||
def __getattr__(name):
|
||||
try:
|
||||
return BACKENDS[name]
|
||||
except KeyError:
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
|
||||
|
||||
Reference in New Issue
Block a user