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.27k stars 585 forks source link

[BUG] Multiple `qml.probs` with varying num of wires errors when using a shot vector #2130

Open antalszava opened 2 years ago

antalszava commented 2 years ago

Expected behavior

The following example executes with either the autograd, tf or torch interface:

dev = qml.device("default.qubit", wires=3, shots=(2,2)) # <--- using a shot vector

@qml.qnode(dev,interface='autograd')
def circuit(a, b):
    qml.RY(a, wires=0)
    qml.RX(b, wires=0)
    return qml.probs(wires=[0]), qml.probs(wires=[1,2])  # <--- multiple probs return with different number of wires

circuit(0,3).shape

Actual behavior

An error is raised when stacking the results in the batch execution pipeline:

~/xanadu/pennylane/pennylane/_qubit_device.py in execute(self, circuit, **kwargs)
    226             if not multiple_sampled_jobs:
    227                 # Can only stack single element outputs
--> 228                 results = qml.math.stack(results)

Additional information

The cause for this issue is very similar to https://github.com/PennyLaneAI/pennylane/issues/2129, it's mainly just another use case and becomes relevant at another point in the code base.

Source code

No response

Tracebacks

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-83-a02461cf1147> in <module>
      7     return qml.probs(wires=[0]), qml.probs(wires=[1,2])
      8 
----> 9 circuit(0,3).shape

~/xanadu/pennylane/pennylane/qnode.py in __call__(self, *args, **kwargs)
    547         self.construct(args, kwargs)
    548 
--> 549         res = qml.execute(
    550             [self.tape],
    551             device=self.device,

~/xanadu/pennylane/pennylane/interfaces/batch/__init__.py in execute(tapes, device, gradient_fn, interface, mode, gradient_kwargs, cache, cachesize, max_diff, override_shots, expand_fn, max_expansion, device_batch_transform)
    400         ) from e
    401 
--> 402     res = _execute(
    403         tapes, device, execute_fn, gradient_fn, gradient_kwargs, _n=1, max_diff=max_diff, mode=_mode
    404     )

~/xanadu/pennylane/pennylane/interfaces/batch/autograd.py in execute(tapes, device, execute_fn, gradient_fn, gradient_kwargs, _n, max_diff, mode)
     62     )
     63 
---> 64     return _execute(
     65         parameters,
     66         tapes=tapes,

~/xanadu/autograd/autograd/tracer.py in f_wrapped(*args, **kwargs)
     46             return new_box(ans, trace, node)
     47         else:
---> 48             return f_raw(*args, **kwargs)
     49     f_wrapped.fun = f_raw
     50     f_wrapped._is_autograd_primitive = True

~/xanadu/pennylane/pennylane/interfaces/batch/autograd.py in _execute(parameters, tapes, device, execute_fn, gradient_fn, gradient_kwargs, _n, max_diff)
    106     """
    107     with qml.tape.Unwrap(*tapes):
--> 108         res, jacs = execute_fn(tapes, **gradient_kwargs)
    109 
    110     for i, r in enumerate(res):

~/xanadu/pennylane/pennylane/interfaces/batch/__init__.py in wrapper(tapes, **kwargs)
    166         else:
    167             # execute all unique tapes that do not exist in the cache
--> 168             res = fn(execution_tapes.values(), **kwargs)
    169 
    170         final_res = []

~/xanadu/pennylane/pennylane/interfaces/batch/__init__.py in fn(tapes, **kwargs)
    118         def fn(tapes, **kwargs):  # pylint: disable=function-redefined
    119             tapes = [expand_fn(tape) for tape in tapes]
--> 120             return original_fn(tapes, **kwargs)
    121 
    122     @wraps(fn)

~/anaconda3/lib/python3.8/contextlib.py in inner(*args, **kwds)
     73         def inner(*args, **kwds):
     74             with self._recreate_cm():
---> 75                 return func(*args, **kwds)
     76         return inner
     77 

~/xanadu/pennylane/pennylane/_qubit_device.py in batch_execute(self, circuits)
    280             self.reset()
    281 
--> 282             res = self.execute(circuit)
    283             results.append(res)
    284 

~/xanadu/pennylane/pennylane/_qubit_device.py in execute(self, circuit, **kwargs)
    226             if not multiple_sampled_jobs:
    227                 # Can only stack single element outputs
--> 228                 results = qml.math.stack(results)
    229 
    230         else:

~/xanadu/pennylane/pennylane/math/multi_dispatch.py in wrapper(*args, **kwargs)
    176             kwargs["like"] = interface
    177 
--> 178             return fn(*args, **kwargs)
    179 
    180         return wrapper

~/xanadu/pennylane/pennylane/math/multi_dispatch.py in stack(values, axis, like)
    541     """
    542     values = np.coerce(values, like=like)
--> 543     return np.stack(values, axis=axis, like=like)
    544 
    545 

~/anaconda3/lib/python3.8/site-packages/autoray/autoray.py in do(fn, like, *args, **kwargs)
     82         backend = infer_backend(like)
     83 
---> 84     return get_lib_fn(backend, fn)(*args, **kwargs)
     85 
     86 

<__array_function__ internals> in stack(*args, **kwargs)

~/anaconda3/lib/python3.8/site-packages/numpy/core/shape_base.py in stack(arrays, axis, out)
    425     shapes = {arr.shape for arr in arrays}
    426     if len(shapes) != 1:
--> 427         raise ValueError('all input arrays must have the same shape')
    428 
    429     result_ndim = arrays[0].ndim + 1

ValueError: all input arrays must have the same shape

System information

Name: PennyLane
Version: 0.21.0.dev0
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: https://github.com/XanaduAI/pennylane
Author: 
Author-email: 
License: Apache License 2.0
Location: /home/antal/xanadu/pennylane
Requires: numpy, scipy, networkx, retworkx, autograd, toml, appdirs, semantic_version, autoray, cachetools, pennylane-lightning
Required-by: PennyLane-Cirq, amazon-braket-pennylane-plugin, PennyLane-Orquestra, pennylane-qulacs, PennyLane-Honeywell, PennyLane-qiskit, PennyLane-AQT, PennyLane-PQ, PennyLane-Forest, PennyLane-qsharp, PennyLane-Qchem, PennyLane-IonQ, PennyLane-SF, PennyLane-Lightning
Platform info:           Linux-5.13.0-27-generic-x86_64-with-glibc2.10
Python version:          3.8.5
Numpy version:           1.19.2
Scipy version:           1.7.3
Installed devices:
- cirq.mixedsimulator (PennyLane-Cirq-0.19.0)
- cirq.pasqal (PennyLane-Cirq-0.19.0)
- cirq.qsim (PennyLane-Cirq-0.19.0)
- cirq.qsimh (PennyLane-Cirq-0.19.0)
- cirq.simulator (PennyLane-Cirq-0.19.0)
- braket.aws.qubit (amazon-braket-pennylane-plugin-1.5.3)
- braket.local.qubit (amazon-braket-pennylane-plugin-1.5.3)
- orquestra.forest (PennyLane-Orquestra-0.15.0)
- orquestra.ibmq (PennyLane-Orquestra-0.15.0)
- orquestra.qiskit (PennyLane-Orquestra-0.15.0)
- orquestra.qulacs (PennyLane-Orquestra-0.15.0)
- qulacs.simulator (pennylane-qulacs-0.17.0.dev0)
- honeywell.hqs (PennyLane-Honeywell-0.16.0.dev0)
- qiskit.aer (PennyLane-qiskit-0.18.0.dev0)
- qiskit.basicaer (PennyLane-qiskit-0.18.0.dev0)
- qiskit.ibmq (PennyLane-qiskit-0.18.0.dev0)
- aqt.noisy_sim (PennyLane-AQT-0.18.0)
- aqt.sim (PennyLane-AQT-0.18.0)
- projectq.classical (PennyLane-PQ-0.18.0.dev0)
- projectq.ibm (PennyLane-PQ-0.18.0.dev0)
- projectq.simulator (PennyLane-PQ-0.18.0.dev0)
- forest.numpy_wavefunction (PennyLane-Forest-0.18.0.dev0)
- forest.qvm (PennyLane-Forest-0.18.0.dev0)
- forest.wavefunction (PennyLane-Forest-0.18.0.dev0)
- microsoft.QuantumSimulator (PennyLane-qsharp-0.19.0)
- ionq.qpu (PennyLane-IonQ-0.17.0.dev0)
- ionq.simulator (PennyLane-IonQ-0.17.0.dev0)
- strawberryfields.fock (PennyLane-SF-0.20.0.dev0)
- strawberryfields.gaussian (PennyLane-SF-0.20.0.dev0)
- strawberryfields.gbs (PennyLane-SF-0.20.0.dev0)
- strawberryfields.remote (PennyLane-SF-0.20.0.dev0)
- strawberryfields.tf (PennyLane-SF-0.20.0.dev0)
- lightning.qubit (PennyLane-Lightning-0.21.0.dev0)
- default.gaussian (PennyLane-0.21.0.dev0)
- default.mixed (PennyLane-0.21.0.dev0)
- default.qubit (PennyLane-0.21.0.dev0)
- default.qubit.autograd (PennyLane-0.21.0.dev0)
- default.qubit.jax (PennyLane-0.21.0.dev0)
- default.qubit.tf (PennyLane-0.21.0.dev0)
- default.qubit.torch (PennyLane-0.21.0.dev0)

Existing GitHub issues

dwierichs commented 1 year ago

This issue is resolved by the new return type system, as far as my tests go. I suppose it can be closed once the old return type system is deprecated.

dwierichs commented 9 months ago

I think this issue can be closed. @rmoyard , do you have any thoughts on this one?

dwierichs commented 3 months ago

@trbromley good to close?