Skip to content

Commit

Permalink
Merge pull request #1479 from qiboteam/tf_migration
Browse files Browse the repository at this point in the history
Migrating TensorFlowBackend to Qiboml
  • Loading branch information
scarrazza authored Oct 28, 2024
2 parents 018075b + 65a20a2 commit 099d7a0
Show file tree
Hide file tree
Showing 29 changed files with 1,343 additions and 1,547 deletions.
35 changes: 16 additions & 19 deletions doc/source/code-examples/advancedexamples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,8 @@ or programmatically, during runtime, as follows:
# retrieve the current number of threads
current_threads = qibo.get_threads()

On the other hand, when using the ``tensorflow`` backend Qibo inherits
Tensorflow's defaults for CPU thread configuration.
Tensorflow allows restricting the number of threads as follows:

.. code-block:: python
import tensorflow as tf
tf.config.threading.set_inter_op_parallelism_threads(1)
tf.config.threading.set_intra_op_parallelism_threads(1)
import qibo
Note that this should be run during Tensorflow initialization in the beginning
of the script and before creating the qibo backend.
For similar wariness when using a machine learning backend (such as TensorFlow or Pytorch)
please refer to the Qiboml documentation.

Using multiple GPUs
^^^^^^^^^^^^^^^^^^^
Expand Down Expand Up @@ -707,13 +696,18 @@ circuit output matches a target state using the fidelity as the corresponding lo
Note that, as in the following example, the rotation angles have to assume real values
to ensure the rotational gates are representing unitary operators.

Qibo doesn't provide Tensorflow and Pytorch as native backends; Qiboml has to be
installed and used as provider of these quantum machine learning backends.

.. code-block:: python
import qibo
qibo.set_backend("tensorflow")
import tensorflow as tf
qibo.set_backend(backend="qiboml", platform="tensorflow")
from qibo import gates, models
backend = qibo.get_backend()
tf = backend.tf
# Optimization parameters
nepochs = 1000
optimizer = tf.keras.optimizers.Adam()
Expand All @@ -737,8 +731,9 @@ to ensure the rotational gates are representing unitary operators.
optimizer.apply_gradients(zip([grads], [params]))
Note that the ``"tensorflow"`` backend has to be used here because other custom
backends do not support automatic differentiation.
Note that the ``"tensorflow"`` backend has to be used here since it provides
automatic differentiation tools. To be constructed, the Qiboml package has to be
installed and used.

The optimization procedure may also be compiled, however in this case it is not
possible to use :meth:`qibo.circuit.Circuit.set_parameters` as the
Expand All @@ -748,10 +743,12 @@ For example:
.. code-block:: python
import qibo
qibo.set_backend("tensorflow")
import tensorflow as tf
qibo.set_backend(backend="qiboml", platform="tensorflow")
from qibo import gates, models
backend = qibo.get_backend()
tf = backend.tf
nepochs = 1000
optimizer = tf.keras.optimizers.Adam()
target_state = tf.ones(4, dtype=tf.complex128) / 2.0
Expand Down
4 changes: 2 additions & 2 deletions examples/anomaly_detection/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

import qibo
from qibo import Circuit, gates
Expand All @@ -22,7 +21,8 @@ def main(n_layers, train_size, filename, plot, save_loss):
save_loss (bool): save losses for standard and anomalous data (default False).
"""

qibo.set_backend("tensorflow")
qibo.set_backend(backend="qiboml", platform="tensorflow")
tf = qibo.get_backend().tf

# Circuit ansatz
def make_encoder(n_qubits, n_layers, params, q_compression):
Expand Down
4 changes: 2 additions & 2 deletions examples/anomaly_detection/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from pathlib import Path

import numpy as np
import tensorflow as tf

import qibo
from qibo import Circuit, gates
Expand All @@ -23,7 +22,8 @@ def main(n_layers, batch_size, nepochs, train_size, filename, lr_boundaries):
lr_boundaries (list): epochs when learning rate is reduced, 6 monotone growing values from 0 to nepochs (default [3,6,9,12,15,18]).
"""

qibo.set_backend("tensorflow")
qibo.set_backend(backend="qiboml", platform="tensorflow")
tf = qibo.get_backend().tf

# Circuit ansatz
def make_encoder(n_qubits, n_layers, params, q_compression):
Expand Down
5 changes: 4 additions & 1 deletion examples/benchmarks/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ def limit_gpu_memory(memory_limit=None):
Args:
memory_limit: Memory limit in MBs.
"""
import tensorflow as tf
import qibo

qibo.set_backend(backend="qiboml", platform="tensorflow")
tf = qibo.get_backend().tf

if memory_limit is None:
print("\nNo GPU memory limiter used.\n")
Expand Down
4 changes: 3 additions & 1 deletion examples/qclustering/minimization.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import math

import numpy as np
import tensorflow as tf
from grover import grover_qc
from oracle import create_oracle_circ

import qibo
from qibo import gates
from qibo.models import Circuit

Expand All @@ -23,6 +23,8 @@ def duerr_hoyer_algo(distances):
int
New cluster assigned for that point.
"""
qibo.set_backend(backend="qiboml", platform="tensorflow")
tf = qibo.get_backend().tf

k = len(distances)
n = int(math.floor(math.log2(k)) + 1)
Expand Down
4 changes: 3 additions & 1 deletion examples/reuploading_classifier/qlassifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from matplotlib.cm import get_cmap
from matplotlib.colors import Normalize

import qibo
from qibo import Circuit, gates


Expand Down Expand Up @@ -117,7 +118,8 @@ def minimize(self, method="BFGS", options=None, compile=True):
parameters = r[1].result.xbest

elif method == "sgd":
import tensorflow as tf
qibo.set_backend(backend="qiboml", platform="tensorflow")
tf = qibo.get_backend().tf

circuit = self.circuit(self.training_set[0])

Expand Down
Loading

0 comments on commit 099d7a0

Please sign in to comment.