Skip to content

Commit

Permalink
fix: small modifications to layers
Browse files Browse the repository at this point in the history
  • Loading branch information
BrunoLiegiBastonLiegi committed Jun 3, 2024
1 parent 0e8656b commit 2c79d18
Show file tree
Hide file tree
Showing 4 changed files with 118 additions and 34 deletions.
8 changes: 2 additions & 6 deletions src/qiboml/models/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from qibo import Circuit
from qibo.config import raise_error
from qibo.gates import abstract

from qiboml.backends import TensorflowBackend as JaxBackend

Expand All @@ -29,13 +30,8 @@ def __post_init__(self):
self.circuit = Circuit(self.nqubits)

@abstractmethod
def _feed_input(self, x):
pass

def forward(self, x):
"""Performs the forward pass: prepares the input and execute the circuit."""
self._feed_input(x)
return self.backend.execute_circuit(self.circuit)
pass

@abstractmethod
def backward(self, input_grad: "ndarray"):
Expand Down
9 changes: 3 additions & 6 deletions src/qiboml/models/ansatze.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@

class ReuploadingLayer(QuantumCircuitLayer):

def _feed_input(self, x):
if isinstance(x, Circuit):
self.circuit = self.circuit + x
else:
self.initial_state = x

def __post_init__(self):
super().__post_init__()
for q in self.qubits:
Expand All @@ -20,5 +14,8 @@ def __post_init__(self):
self.circuit.add(gates.CNOT(q0=q, q1=self.qubits[i + 1]))
self.circuit.add(gates.CNOT(q0=self.qubits[-1], q1=self.qubits[0]))

def forward(self, x: Circuit) -> Circuit:
return x + self.circuit

def backward(self):
raise_error(NotImplementedError, "TO DO")
49 changes: 27 additions & 22 deletions src/qiboml/models/encoding_decoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,22 @@ class QuantumEncodingLayer(QuantumCircuitLayer):
@dataclass
class BinaryEncodingLayer(QuantumEncodingLayer):

def _feed_input(self, x: "ndarray"):
def forward(self, x: "ndarray") -> Circuit:
if isinstance(x, Circuit):
raise_error(RuntimeError, "Passed a `Circuit` as input data.")
if x.shape[-1] != self.nqubits:
raise_error(
RuntimeError,
f"Invalid input dimension {x.shape[-1]}, but nqubits is {self.nqubits}.",
)
self.circuit = Circuit(self.nqubits)
for i, bit in enumerate(x):
circuit = self.circuit.copy()
for q, bit in zip(self.qubits, x):
if bit:
self.circuit.add(gates.X(i))
circuit.add(gates.X(q))
return circuit

def backward(self):
raise_error(NotImplementedError, "TO DO")
def backward(self, input_grad: "ndarray") -> "ndarray":
return input_grad


class PhaseEncodingLayer(QuantumEncodingLayer):
Expand All @@ -48,31 +51,33 @@ class AmplitudeEncodingLayer(QuantumEncodingLayer):
"""


class QuantumDecodingLayer(QuantumCircuitLayer):
pass


@dataclass
class ExpectationLayer(QuantumDecodingLayer):
class QuantumDecodingLayer(QuantumCircuitLayer):

observable: Union["ndarray", "qibo.models.Hamiltonian"]
nshots: int = 1000

def _feed_input(self, x):
if isinstance(x, Circuit):
self.circuit = x
def __post_init__(self):
super().__post_init__()
self.circuit.add(gates.M(*self.qubits))

def forward(self, x):
if isinstance(x, Circuit):
return self.observable.expectation_from_samples(
super().forward(x).frequencies()
)
else:
return self.observable.expectation(x)
def forward(self, x: Circuit) -> Circuit:
return self.backend.execute_circuit(x + self.circuit, nshots=self.nshots)

def backward(self):
raise_error(NotImplementedError, "TO DO")


@dataclass
class ExpectationLayer(QuantumDecodingLayer):

observable: Union["ndarray", "qibo.models.Hamiltonian"] = None

def forward(self, x: Circuit) -> "ndarray":
return self.observable.expectation_from_samples(
super().forward(x).frequencies()
)


"""
.
.
Expand Down
86 changes: 86 additions & 0 deletions tutorials/model_example.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "f929e9a9-d6c3-4857-b9b5-bc4f267955f0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"BinaryEncodingLayer(nqubits=3, qubits=range(0, 3), circuit=<qibo.models.circuit.Circuit object at 0x795ab0567f40>, initial_state=None, backend=tensorflow)\n",
"ReuploadingLayer(nqubits=3, qubits=range(0, 3), circuit=<qibo.models.circuit.Circuit object at 0x795a052328f0>, initial_state=None, backend=tensorflow)\n",
"QuantumDecodingLayer(nqubits=3, qubits=range(0, 3), circuit=<qibo.models.circuit.Circuit object at 0x795a052335e0>, initial_state=None, backend=tensorflow, nshots=1000)\n"
]
}
],
"source": [
"from qiboml.models.encoding_decoding import *\n",
"from qiboml.models.ansatze import *\n",
"\n",
"model = [BinaryEncodingLayer(nqubits=3), ReuploadingLayer(nqubits=3), QuantumDecodingLayer(nqubits=3)]\n",
"for m in model:\n",
" print(m)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "09cccd24-dece-4279-bcd2-7006582458c2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[<tf.Tensor: shape=(8,), dtype=float64, numpy=array([1., 0., 0., 0., 0., 0., 0., 0.])>, <tf.Tensor: shape=(8,), dtype=float64, numpy=array([0., 0., 1., 0., 0., 0., 0., 0.])>, <tf.Tensor: shape=(8,), dtype=float64, numpy=array([0., 0., 0., 0., 1., 0., 0., 0.])>]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"data = np.array([[0,0,0], [0,1,0], [1,1,0]])\n",
"result = []\n",
"\n",
"for d in data:\n",
" x = model[0].forward(d)\n",
" x = model[1].forward(x)\n",
" result.append(model[2].forward(x).probabilities())\n",
"\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "005b4456-baab-486d-901a-0834ee042f54",
"metadata": {},
"outputs": [],
"source": []
}
],
"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.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

0 comments on commit 2c79d18

Please sign in to comment.