qiboteam / qibo

A framework for quantum computing
https://qibo.science
Apache License 2.0
291 stars 60 forks source link

Issue found at minimization #123

Closed AdrianPerezSalinas closed 4 years ago

AdrianPerezSalinas commented 4 years ago

Hi all,

I found the following problem when I tried to solve an optimization problem with the functions in this link https://www.tensorflow.org/probability/examples/Optimizers_in_TensorFlow_Probability

I found the error: tensorflow.python.framework.errors_impl.NotFoundError: Could not find valid device for node. Node:{{node AddV2}}

I have seen that this may have something to do with the matmul procedure, but I do not know anymore. Do you have any idea why this is happening?

scarrazza commented 4 years ago

Could you please post or send to us the code you are using?

AdrianPerezSalinas commented 4 years ago

Sure, I am using a VQE-like program and the only new lines added are

    elif method=='bfgs_tf':
        from qibo.tensorflow.gates import TensorflowGate
        circuit = self.circuit(self.domain[0])
        for gate in circuit.queue:
            if not isinstance(gate, TensorflowGate):
                raise RuntimeError('SGD VQE requires native Tensorflow '
                                   'gates because gradients are not '
                                   'supported in the custom kernels.')

        # proceed with the training
        from qibo.config import K
        vparams = K.Variable(self.params)

        def loss_gradient(x):
            return tfp.math.value_and_gradient(lambda x: self.cost_function(x), x)

        if compile:
            loss_gradient = K.function(loss_gradient)

        params_optimal = tfp.optimizer.lbfgs_minimize(
            loss_gradient, vparams)

        result = self.cost_function(params_optimal).numpy()
        parameters = params_optimal.numpy()

These lines are included in the minimize function of the VQE

Do you want me to upload the whole code? I can do it in a new branch for instance

scarrazza commented 4 years ago

Could you please paste here your self.cost_function?

AdrianPerezSalinas commented 4 years ago

This is my self.cost_function. h are hamiltonians as defined in the VQE

def cost_function_one_point(self, x, target):
    C = self.circuit(x)
    state = C.execute()
    outcomes = ([h.expectation(state) for h in self.hamiltonian])
    cf = 0
    for o, f in zip(outcomes, target):
        cf += (o - f) ** 2
    return cf

def cost_function(self, params, a=0.0):
    self.set_parameters(params)
    cf = 0
    for x, t in zip(self.domain, self.target):
        cf += self.cost_function_one_point(x, t)
    cf /= len(self.domain)
    return cf
scarrazza commented 4 years ago

Closing this issue as it is not related to the VQE in qibo.