QubitStateVector pennylane-qiskit error

I have the following code where I’m trying to encode a vector of 4 features into a 2-qubit quantum state on the qiskit.aer simulator backend.

import pennylane as qml
from pennylane import numpy as np
import pennylane_qiskit as pqis
import math,qiskit

dev = qml.device('qiskit.aer', wires=2, backend = 'statevector_simulator')


x = np.array([0.53896774,0.79503606,0.27826503,0.]) # n qubits to encode 2^n features
#x = np.array([1,0,0,0])

@qml.qnode(dev)
def test(x):

    qml.QubitStateVector(x,wires = [0,1])

    return qml.expval(qml.PauliZ(0))

print(test(x))


This outputs the following error:

QiskitError: 'Sum of amplitudes-squared does not equal one.'

I have obviously checked that this is True:

math.isclose(sum(np.absolute(x) ** 2), 1.0,abs_tol=1e-7)

could it be qiskit’s tolerance eps value?

Qiskit version 0.9.0
Pennylane qiskit plugin 0.5.1

Also I’m getting the expectation value of the Pauli Z opeartor of the first qubit , but I’m rather interested on the marginal probabilities of quantum state, is there a way to extract that from the quantum node dev?

Thank you very much pennylane community!

Hi @RicardoGaGu!

To extract the probabilities, you can use the dev.probabilities() method:

import pennylane as qml

dev = qml.device("qiskit.aer", wires=3)

@qml.qnode(dev)
def test(x):
    qml.RX(x, wires = [0])
    qml.CNOT(wires=[0, 1])
    qml.RX(x, wires=[2])
    return qml.expval(qml.PauliZ(0))

results = test(0.54)
# get the marginal probability of wires 0 and 1
prob = dev.probabilities(wires=[0, 1])

Printing the probability:

>>> print(prob)
OrderedDict([((0, 0), 0.9326171875),
             ((0, 1), 0.0),
             ((1, 0), 0.0),
             ((1, 1), 0.0673828125)])

Note that this method returns an ordered dictionary, so you can extract the values as a list or by using the event key:

>>> list(prob.values())                                                                                                                                                                                       
[0.9296875, 0.0, 0.0, 0.0703125]
>>> prob[(1, 1)]
0.0703125

In the case of the Qiskit error, it looks like this might be a tolerance issue with Qiskit. I will investigate further just to make sure.

HI @josh, have you had time to look into the tolerance issue? Thanks for the heads up on the .probabilities() method!

Thanks,

Ricardo

Hi @RicardoGaGu, thanks for your question!

In the qiskit/extensions/quantum_initializer/initializer.py file the _EPS = 1e-10 is defined.

Therefore later the following part raises the error:

if not math.isclose(sum(np.absolute(params) ** 2), 1.0, abs_tol=_EPS):
            raise QiskitError("Sum of amplitudes-squared does not equal one.")

It might be worth posting this as an issue for Qiskit repository.

In the meantime, you may go for using PennyLane’s default_qubit device:

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=2)

x = np.array([0.53896774,0.79503606,0.27826503,0.]) # n qubits to encode 2^n features

@qml.qnode(dev)
def test(x):
    qml.QubitStateVector(x,wires = [0,1])
    return qml.expval(qml.PauliZ(0))

print(test(x))

@josh i am having the same issue but with the default.qubit device. what do you suggest i do ?

“ValueError: Sum of amplitudes-squared does not equal one.”

I am trying to push a bunch of numpy arrays through a loop.

  num_qubits = 12
  dev = qml.device('default.qubit',wires=num_qubits)
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
   init_params = random_layers_uniform(n_layers=3, 
    n_wires=num_qubits, seed=2)
   
   @qml.qnode(dev, interface='torch')
def circuit(x=None, weights=None):
    AmplitudeEmbedding(x, list(range(num_qubits)), pad=0., normalize=True)
    RandomLayers(weights=weights, wires=list(range(num_qubits)))
    return qml.expval(qml.PauliZ(0))

Hi, just a gentle reminder i am really stuck here and require help. Is there a specific procedure to encode features into amplitude embeddings ?

Hi @vijpandaturtle, thanks for your question and for your patience!

Just to get a little bit more of an idea of what is happening, could you help out with including more details on the traceback that you are getting?

Also, it would be helpful to see what arguments you are passing to circuit, such that we can track down which part is giving the error (the shape of x could also be helpful if you wouldn’t like to include the real value of x).

General details related to AmplitudeEmbedding can be found at this page.

Could you also make sure that you are using the latest version of PennyLane (v0.8.0) and send the output that you get for qml.about()? :blush:

@antalszava sorry for the late reply :smile:
Yes I have the latest version of pennylane

based on the above code I posted there are 2 arguments I have, one is a torch tensor of around 27 decimal values, second is the params defined (random_layers_uniform)
Unfortunately, I am unable to post my exact input values right now.

This is the exact error i am getting

c:\users\owner\anaconda3\envs\quantum\lib\site-packages\pennylane\plugins\default_qubit.py in apply_state_vector(self, input_state, wires)
143 “”"
144 if not np.isclose(np.linalg.norm(input_state, 2), 1.0, atol=tolerance):
–> 145 raise ValueError(“Sum of amplitudes-squared does not equal one.”)
146
147 n_state_vector = input_state.shape[0]

ValueError: Sum of amplitudes-squared does not equal one.

I used 12 qubits because my input size is likely to be variable. But do you think using such a large amount of qubits could lead to this issue ?
Thanks

Hi @vijpandaturtle,

Thanks for the details! This seems to be an error related to the tolerance value used with AmplitudeEmbedding.

A new addition by @Maria_Schuld solves this issue by adjusting the tolerance to the value used at other parts of the codebase.

If you check out the master branch of PennyLane, then your problem should be solved now. :blush:

Thanks so much for raising this issue!

Thank you for solving the issue :grin:

@antalszava since the default.qubit simulator is really slow I wanted to try with other quantum simulators. however, when I try to use the qiskit aer device i run into the same tolerance issue. has this been solved yet ?

Hi @vijpandaturtle, the fix has been merged into the master branch (it was not yet included in a release).

If the traceback that you are getting is exactly the same as before, then it is coming from PennyLane core (and not the PennyLane-Qiskit plugin). In this case, could you double-check that you were using the same PennyLane distribution in both cases?

(Note that if you change directories, it might be that a different PennyLane version will be used.)

Locally I gave it a try, and it worked for me when running with dafult.qubit and then simply changing to qiskit.aer.

If this would still not be coming around, could you share your PennyLane-Qiskit version, please? :slight_smile:

@antalszava okay in that case I may be doing something wrong
here is my qml.about()

Name: PennyLane
Version: 0.9.0.dev0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/XanaduAI/pennylane
Author: None
Author-email: None
License: Apache License 2.0
Location: c:\users\dorian-hp1\anaconda3\envs\quantum\lib\site-packages
Requires: numpy, autograd, semantic-version, scipy, appdirs, toml, networkx
Required-by: PennyLane-qiskit, PennyLane-Forest
Platform info: Windows-10-10.0.18362-SP0
Python version: 3.6.10
Numpy version: 1.18.1
Scipy version: 1.4.1
Installed devices:

  • default.gaussian (PennyLane-0.9.0.dev0)
  • default.qubit (PennyLane-0.9.0.dev0)
  • default.tensor (PennyLane-0.9.0.dev0)
  • default.tensor.tf (PennyLane-0.9.0.dev0)
  • qiskit.aer (PennyLane-qiskit-0.8.0)
  • qiskit.basicaer (PennyLane-qiskit-0.8.0)
  • qiskit.ibmq (PennyLane-qiskit-0.8.0)
  • forest.numpy_wavefunction (PennyLane-Forest-0.8.0)
  • forest.qpu (PennyLane-Forest-0.8.0)
  • forest.qvm (PennyLane-Forest-0.8.0)
  • forest.wavefunction (PennyLane-Forest-0.8.0)

there are some devices that have been updated to the latest version and some haven’t. this correct ?
code for my device

   dev = qml.device('qiskit.aer', wires=num_qubits, backend = 
                                         qasm_simulator')
  
   device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

QiskitError: ‘Sum of amplitudes-squared does not equal one.’

@vijpandaturtle thanks for the info! :blush: I did a reset of PennyLane to the commit where this problem was still around and now I’m also getting a QiskitError.

Could you please check that:

  • you did a git pull for PennyLane on the master branch and that
  • you ran pip install -e . from the directory where you have PennyLane cloned?

After this, could you also include what your output for pip freeze | grep PennyLane is?

It should look something like this:
-e git+https://github.com/XanaduAI/pennylane.git@a76140d842298845fa3623d3f5612af9eedf8d07#egg=PennyLane

where a76140d842298845fa3623d3f5612af9eedf8d07 is specific for the commit that you have currently.

(Also, just to double-check if you run the same script, but with dev = qml.device('default.qubit', wires=num_qubits), then no error was raised, correct?)

Let me know how these go! :blush: There will be soon a new minor release for PennyLane including the fix for this issue, so that will for sure solve your problem!

@antalszava yes I have pulled the master branch and logged the commit history. a76140d842298845fa3623d3f5612af9eedf8d07 this is the latest commit I believe so my lib is up to date i guess

the issue is that my quantum circuit is being called multiple times aka i’m passing in many vectors and generating outputs. so my circuit is too slow for me to find out if it is not creating an issue for any of my input vectors.
Which is why i wanted to try the aer device. Having said that, so far no issues with default.qubit !
Could you let me know whenever the release is out ? And thank you so much for the reply.

@vijpandaturtle I see!

One other thing you could try is to create a new conda environment and see if the problem persists. This can be done with the following commands:

conda create -n pennylane_1 python=3.6
conda activate pennylane_1
pip install numpy
pip install scipy
cd pennylane/
pip install -e .
pip install pennylane-qiskit
pip freeze | grep PennyLane
python this_is_my_script.py

For sure, we’ll let you know once the release is out! :blush:

@vijpandaturtle: PennyLane 0.8.1 is live on PyPi! :blush:

1 Like

@antalszava could not fix the error.
i even pulled pennylane-qiskit from github and run pip install e .

@vijpandaturtle, now PennyLane-Qiskit 0.8.1 is also live on PyPi!

In this release, the requirement for PennyLane has been increased to the version which solved the normalization issue (0.8.1).

Let me know if you are still experiencing problems! If so, we could also take the discussion to our Slack channel, such that we can discuss further details more quickly. :blush: