Hi!

After a whole morning of scratching my head because my code was giving slightly different results each time I executed it even if I was setting numpy’s seed before running any random-dependent process, I have just discovered that qml.qchem.molecular_hamiltonian, for some reason that I cannot fathom, uses numpy’s seed at some point. I have trying to find where in the code this happens (with no luck so far), but it is a fact that if I set numpy.random.seed before calling qml.qchem.molecular_hamiltonian then I always obtain the same Hamiltonian, but if I do not do it, then the Hamiltonian that I obtain is different every time (though very, very similar; differences arises in the 10th decimal of the coefficients or so).

I do not understand the reason for this use of a random source to calculate the Hamiltonian (one would expect it to be a completely deterministic process), but I think that this should be at least acknowledged at some point in the documentation, to avoid extremely confusing situations like the one I’ve lived this morning.

Thanks in advance.

Hi @combarro, I’m glad you found a way to fix your problem and thank you for pointing this out! This will help us improve PennyLane. Please let us know about any other suggestions that you may have!

Thanks! Any idea of what part of the process of computing the Hamiltonian requires randomness? I am little bit puzzled with this.

Hi @combarro and thank you very much for the nice feedback. Could you please give us a minimal code example that generates the random Hamiltonians? I will look into it asap and will give you an update. Thanks again.

As simple as this:

import pennylane as qml

from pennylane import numpy as np

symbols = [“H”, “H”]

coordinates = np.array([0.0, 0.0, -0.7, 0.0, 0.0, 0.7])

H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates)

print("Qubit Hamiltonian: ")

print(H)

If you don’t set a value for numpy.seed, every execution of this code leads to slightly different coefficients in the Hamiltonian. And, of course, even if you set it, subsequent executions in the same program lead to slightly different coefficients.

Thanks @combarro. The randomness, at the 12th digit after the decimal point, comes from this line which was added to fix an autograd failure in computing gradients of functions that perform matrix diagonalization for matrices with degenerate eigenvalues. For more details please see here. We are working to find another way to prevent that autograd failure. You can also find alternative ways to construct a Hamiltonian here. Thanks again for pointing to this and please feel free to let us know if you have any other questions.

Thanks so much for the info. This clarifies the issue for me. Thanks!

1 Like