Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix message error in distributed circuit #543

Merged
merged 9 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions doc/source/code-examples/advancedexamples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Using multiple GPUs
Qibo supports distributed circuit execution on multiple GPUs. This feature can
be used as follows:

.. testcode::
.. code-block:: python

from qibo.models import Circuit
from qibo import gates
Expand All @@ -118,7 +118,7 @@ be used as follows:
# this will use the first GPU three times and the second one time
# leading to four total logical devices
# construct the distributed circuit for 32 qubits
# c = Circuit(32, accelerators)
c = Circuit(32, accelerators)

Gates can then be added normally using ``c.add`` and the circuit can be executed
using ``c()``. Note that a ``memory_device`` is passed in the distributed circuit
Expand Down Expand Up @@ -757,7 +757,7 @@ When Trotter decomposition is used, it is possible to execute the QAOA circuit
on multiple devices, by passing an ``accelerators`` dictionary when defining
the model. For example the previous example would have to be modified as:

.. testcode::
.. code-block:: python

from qibo import models, hamiltonians

Expand Down Expand Up @@ -801,7 +801,7 @@ function.
final_state = c().state()
fidelity = tf.math.abs(tf.reduce_sum(tf.math.conj(target_state) * final_state))
loss = 1 - fidelity
grads = tape.gradient(loss, params)
grads = tape.gradient(loss, params)
optimizer.apply_gradients(zip([grads], [params]))


Expand Down Expand Up @@ -834,7 +834,7 @@ For example:
final_state = c().state()
fidelity = tf.math.abs(tf.reduce_sum(tf.math.conj(target_state) * final_state))
loss = 1 - fidelity
grads = tape.gradient(loss, params)
grads = tape.gradient(loss, params)
optimizer.apply_gradients(zip([grads], [params]))

for _ in range(nepochs):
Expand Down
6 changes: 3 additions & 3 deletions src/qibo/backends/numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,16 +411,16 @@ def density_matrix_collapse(self, gate, state, result):
def on_cpu(self): # pragma: no cover
return self.device()

def cpu_tensor(self, x, dtype=None):
def cpu_tensor(self, x, dtype=None): # pragma: no cover
if dtype is None:
dtype = x.dtype
return self.np.asarray(x, dtype=dtype)

def cpu_cast(self, x, dtype='DTYPECPX'):
def cpu_cast(self, x, dtype='DTYPECPX'): # pragma: no cover
dtype = self._dtypes.get(dtype)
return self.np.array(x, dtype=dtype)

def cpu_assign(self, state, i, piece):
def cpu_assign(self, state, i, piece): # pragma: no cover
state.pieces[i] = self.to_numpy(piece)

def transpose_state(self, pieces, state, nqubits, order):
Expand Down
10 changes: 7 additions & 3 deletions src/qibo/core/distcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class DistributedCircuit(circuit.Circuit):
compilation and callbacks.

Example:
.. testcode::
.. code-block:: python

from qibo.models import Circuit
# The system has two GPUs and we would like to use each GPU twice
Expand All @@ -47,8 +47,12 @@ class DistributedCircuit(circuit.Circuit):

def __init__(self, nqubits: int, accelerators: Dict[str, int]):
if not K.supports_multigpu: # pragma: no cover
raise_error(NotImplementedError, "Distributed circuit is not supported "
f"by the {K.name} backend.")
if K.platform is None:
raise_error(NotImplementedError, "Distributed circuit is not supported "
f"by the {K.name} backend.")
else:
raise_error(NotImplementedError, "Distributed circuit is not supported "
f"by the {K.name} ({K.get_platform()}) backend.")
super().__init__(nqubits)
self.init_kwargs["accelerators"] = accelerators
self.ndevices = sum(accelerators.values())
Expand Down
6 changes: 3 additions & 3 deletions src/qibo/models/qgan.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ def __init__(self, latent_dim, layers=None, circuit=None, set_parameters=None, d

def define_discriminator(self, alpha=0.2, dropout=0.2):
"""Define the standalone discriminator model."""
from tensorflow.keras.models import Sequential # pylint: disable=E0611
from tensorflow.keras.optimizers import Adadelta # pylint: disable=E0611
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Reshape, LeakyReLU, Flatten # pylint: disable=E0611
from tensorflow.keras.models import Sequential # pylint: disable=E0611,E0401
from tensorflow.keras.optimizers import Adadelta # pylint: disable=E0611,E0401
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Reshape, LeakyReLU, Flatten # pylint: disable=E0611,E0401

model = Sequential()
model.add(Dense(200, use_bias=False, input_dim=self.nqubits))
Expand Down
11 changes: 6 additions & 5 deletions src/qibo/tests/test_models_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
from qibo.tests.utils import random_state


def test_circuit_constructor():
def test_circuit_constructor(backend):
from qibo.core.circuit import Circuit, DensityMatrixCircuit
from qibo.core.distcircuit import DistributedCircuit
c = models.Circuit(5)
assert isinstance(c, Circuit)
c = models.Circuit(5, density_matrix=True)
assert isinstance(c, DensityMatrixCircuit)
if not K.supports_multigpu: # pragma: no cover
if not K.supports_multigpu:
with pytest.raises(NotImplementedError):
c = models.Circuit(5, accelerators={"/GPU:0": 2})
else:
Expand Down Expand Up @@ -66,10 +66,11 @@ def test_qft_execution(backend, accelerators, nqubits, random):
K.assert_allclose(final_state, target_state)


def test_qft_errors():
def test_qft_errors(backend):
"""Check that ``_DistributedQFT`` raises error if not sufficient qubits."""
from qibo.models.circuit import _DistributedQFT
with pytest.raises(NotImplementedError):
c = _DistributedQFT(2, accelerators={"/GPU:0": 4})
with pytest.raises(NotImplementedError):
c = models.QFT(10, with_swaps=False, accelerators={"/GPU:0": 2})
if K.supports_multigpu:
with pytest.raises(NotImplementedError):
c = _DistributedQFT(2, accelerators={"/GPU:0": 4})
4 changes: 2 additions & 2 deletions src/qibo/tests/test_models_qgan.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ def test_qgan_custom_discriminator():
if not K.check_availability("tensorflow"): # pragma: no cover
pytest.skip("Skipping StyleQGAN test because tensorflow backend is not available.")

from tensorflow.keras.models import Sequential # pylint: disable=E0611
from tensorflow.keras.layers import Dense # pylint: disable=E0611
from tensorflow.keras.models import Sequential # pylint: disable=E0611,E0401
from tensorflow.keras.layers import Dense # pylint: disable=E0611,E0401
original_backend = qibo.get_backend()
qibo.set_backend("tensorflow")
reference_distribution = generate_distribution(10)
Expand Down