Example #1
0
    def initialize_circuit(self, *args, **kwargs):
        """
        return an empty circuit.
        Parameters
        ----------
        n_qubits: int, optional:
            an override parameter to decide how many qubits should be present in the initialized circuit
        args
        kwargs

        Returns
        -------
        qibo.tensorflow.circuit.TensorflowCircuit
            an empty, though initialized, circuit that can be executed or manipulated.
        """
        n_qubits = max(self.highest_qubit + 1, self.n_qubits,
                       self.abstract_circuit.max_qubit() + 1)
        if self.device is None:
            return Circuit(n_qubits)
        else:
            if isinstance(self.device, str):
                if not self.flag:
                    qibo.set_device(self.device)
                    self.flag = True  # don't reset the device every time; such as during measurement.
                return Circuit(n_qubits)
            elif isinstance(self.device, dict):
                acc = self.device['accelerators']
                mem = self.device['memory device']
                return Circuit(n_qubits, accelerators=acc, memory_device=mem)
Example #2
0
def test_set_device():
    """Check device switcher and errors in device name."""
    import qibo
    original_device = qibo.get_device()
    qibo.set_device("/CPU:0")
    with pytest.raises(ValueError):
        qibo.set_device("test")
    with pytest.raises(ValueError):
        qibo.set_device("/TPU:0")
    with pytest.raises(ValueError):
        qibo.set_device("/gpu:10")
    with pytest.raises(ValueError):
        qibo.set_device("/GPU:10")
    qibo.set_device(original_device)
Example #3
0
def main(nqubits,
         circuit_name,
         backend="custom",
         precision="double",
         nreps=1,
         nshots=None,
         transfer=False,
         fuse=False,
         device=None,
         accelerators=None,
         threadsafe=False,
         compile=False,
         get_branch=True,
         nlayers=None,
         gate_type=None,
         params={},
         filename=None):
    """Runs circuit simulation benchmarks for different circuits.

    See benchmark documentation for a description of arguments.
    """
    qibo.set_backend(backend)
    qibo.set_precision(precision)
    if device is not None:
        qibo.set_device(device)

    logs = BenchmarkLogger(filename)
    # Create log dict
    logs.append({
        "nqubits": nqubits,
        "circuit_name": circuit_name,
        "threading": "",
        "backend": qibo.get_backend(),
        "precision": qibo.get_precision(),
        "device": qibo.get_device(),
        "accelerators": accelerators,
        "nshots": nshots,
        "transfer": transfer,
        "fuse": fuse,
        "compile": compile,
    })
    if get_branch:
        logs[-1]["branch"] = get_active_branch_name()

    params = {k: v for k, v in params.items() if v is not None}
    kwargs = {"nqubits": nqubits, "circuit_name": circuit_name}
    if params: kwargs["params"] = params
    if nlayers is not None: kwargs["nlayers"] = nlayers
    if gate_type is not None: kwargs["gate_type"] = gate_type
    if accelerators is not None:
        kwargs["accelerators"] = accelerators
    logs[-1].update(kwargs)

    start_time = time.time()
    circuit = circuits.CircuitFactory(**kwargs)
    if nshots is not None:
        # add measurement gates
        circuit.add(qibo.gates.M(*range(nqubits)))
    if fuse:
        circuit = circuit.fuse()
    logs[-1]["creation_time"] = time.time() - start_time

    start_time = time.time()
    if compile:
        circuit.compile()
        # Try executing here so that compile time is not included
        # in the simulation time
        result = circuit(nshots=nshots)
        del (result)
    logs[-1]["compile_time"] = time.time() - start_time

    start_time = time.time()
    result = circuit(nshots=nshots)
    logs[-1]["dry_run_time"] = time.time() - start_time
    start_time = time.time()
    if transfer:
        result = result.numpy()
    logs[-1]["dry_run_transfer_time"] = time.time() - start_time
    del (result)

    simulation_times, transfer_times = [], []
    for _ in range(nreps):
        start_time = time.time()
        result = circuit(nshots=nshots)
        simulation_times.append(time.time() - start_time)
        start_time = time.time()
        if transfer:
            result = result.numpy()
        transfer_times.append(time.time() - start_time)
        logs[-1]["dtype"] = str(result.dtype)
        if nshots is None:
            del (result)

    logs[-1]["simulation_times"] = simulation_times
    logs[-1]["transfer_times"] = transfer_times
    logs[-1]["simulation_times_mean"] = np.mean(simulation_times)
    logs[-1]["simulation_times_std"] = np.std(simulation_times)
    logs[-1]["transfer_times_mean"] = np.mean(transfer_times)
    logs[-1]["transfer_times_std"] = np.std(transfer_times)

    start_time = time.time()
    if nshots is not None:
        freqs = result.frequencies()
    logs[-1]["measurement_time"] = time.time() - start_time

    if logs[-1]["backend"] == "qibojit" and qibo.K.get_platform() == "numba":
        from numba import threading_layer
        logs[-1]["threading"] = threading_layer()

    print()
    print(logs)
    print()
    logs.dump()
Example #4
0
def main(nqubits, type,
         backend="custom", precision="double",
         device=None, accelerators=None,
         nshots=None, fuse=False, compile=False,
         nlayers=None, gate_type=None, params={},
         filename=None):
    """Runs benchmarks for different circuit types.

    Args:
        nqubits (int): Number of qubits in the circuit.
        type (str): Type of Circuit to use.
            See ``benchmark_models.py`` for available types.
        device (str): Tensorflow logical device to use for the benchmark.
            If ``None`` the first available device is used.
        accelerators (dict): Dictionary that specifies the accelarator devices
            for multi-GPU setups.
        nshots (int): Number of measurement shots.
            Logs the time required to sample frequencies (no samples).
            If ``None`` no measurements are performed.
        fuse (bool): If ``True`` gate fusion is used for faster circuit execution.
        compile: If ``True`` then the Tensorflow graph is compiled using
            ``circuit.compile()``. Compilation time is logged in this case.
        nlayers (int): Number of layers for supremacy-like or gate circuits.
            If a different circuit is used ``nlayers`` is ignored.
        gate_type (str): Type of gate for gate circuits.
            If a different circuit is used ``gate_type`` is ignored.
        params (dict): Gate parameter for gate circuits.
            If a non-parametrized circuit is used then ``params`` is ignored.
        filename (str): Name of file to write logs.
            If ``None`` logs will not be saved.
    """
    qibo.set_backend(backend)
    qibo.set_precision(precision)
    if device is not None:
        qibo.set_device(device)

    if filename is not None:
        if os.path.isfile(filename):
            with open(filename, "r") as file:
                logs = json.load(file)
            print("Extending existing logs from {}.".format(filename))
        else:
            print("Creating new logs in {}.".format(filename))
            logs = []
    else:
        logs = []

    # Create log dict
    logs.append({
        "nqubits": nqubits, "circuit_type": type,
        "backend": qibo.get_backend(), "precision": qibo.get_precision(),
        "device": qibo.get_device(), "accelerators": accelerators,
        "nshots": nshots, "fuse": fuse, "compile": compile
        })

    params = {k: v for k, v in params.items() if v is not None}
    kwargs = {"nqubits": nqubits, "circuit_type": type}
    if params: kwargs["params"] = params
    if nlayers is not None: kwargs["nlayers"] = nlayers
    if gate_type is not None: kwargs["gate_type"] = gate_type
    if accelerators is not None:
        kwargs["accelerators"] = accelerators
        kwargs["device"] = device
    logs[-1].update(kwargs)

    start_time = time.time()
    circuit = circuits.CircuitFactory(**kwargs)
    if nshots is not None:
        # add measurement gates
        circuit.add(qibo.gates.M(*range(nqubits)))
    if fuse:
        circuit = circuit.fuse()
    logs[-1]["creation_time"] = time.time() - start_time

    if compile:
        start_time = time.time()
        circuit.compile()
        # Try executing here so that compile time is not included
        # in the simulation time
        result = circuit(nshots=nshots)
        logs[-1]["compile_time"] = time.time() - start_time

    start_time = time.time()
    result = circuit(nshots=nshots)
    logs[-1]["simulation_time"] = time.time() - start_time
    logs[-1]["dtype"] = str(result.dtype)

    if nshots is not None:
        start_time = time.time()
        freqs = result.frequencies()
        logs[-1]["measurement_time"] = time.time() - start_time

    print()
    for k, v in logs[-1].items():
        print("{}: {}".format(k, v))

    if filename is not None:
        with open(filename, "w") as file:
            json.dump(logs, file)