PennyLaneAI / pennylane

PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
https://pennylane.ai
Apache License 2.0
2.35k stars 603 forks source link

`qml.mutual_info` and `qml.vn_entropy` error with certain shot vectors (requires tomography) #2819

Open antalszava opened 2 years ago

antalszava commented 2 years ago

Expected behavior

qml.mutual_info and qml.vn_entropy work with any type of shot vectors.

Actual behavior

Multiple copies of the same shot number raise an error. The issue is that the QubitDevice method for these methods do not consider the shot_range and bin_size arguments of the statistics method, as other methods called by statistics do.

For that reason, a scalar value is generated internally, whereas the logic for multiple shot number copies would at one point expect an iterable (i.e., array). This causes the error.

Additional information

No response

Source code

import pennylane as qml

dev = qml.device("default.qubit", wires=2, shots=[1, 10, 10, 1000])

@qml.qnode(device=dev)
def circuit(x):
    qml.Hadamard(wires=[0])
    qml.CRX(x, wires=[0, 1])
    return qml.vn_entropy(wires=[0])

circuit(0.5)

Tracebacks

~/xanadu/pennylane/pennylane/_qubit_device.py in batch_execute(self, circuits)
    360             self.reset()
    361 
--> 362             res = self.execute(circuit)
    363             results.append(res)
    364 

~/pennylane/_qubit_device.py in execute(self, circuit, **kwargs)
    287                     results.append(r)
    288                 elif shot_tuple.copies > 1:
--> 289                     results.extend(r.T)
    290                 else:
    291                     results.append(r.T)

TypeError: iteration over a 0-d array

System information

Current master branch

Existing GitHub issues

antalszava commented 2 years ago

Note: this requires dedicated logic to be added and will not be resolved by other fixes (e.g., new return types).

antalszava commented 2 years ago

The above-described scenario now raises NotImplementedError. Computing these quantities with finite shots emits a warning and in practice, analytic computations are performed. Using a shot vector would simply mean duplicating a single result N times for a shot vector of length N and hence seems not to be useful as is.

Alternatively, if qml.mutual_info and qml.vn_entropy instead of depending on state information would be estimated using state tomography, then information about shots could be useful along with using a shot vector.

josh146 commented 2 years ago

Perhaps rewriting them to support state tomography -- or perhaps even better, native quantum algorithms for measuring these quantities -- would be the best overall solution