Skip to content

[BUG] Code example in qml.measure docs containing impossible postselection fails #8480

@isaacdevlugt

Description

@isaacdevlugt

Expected behavior

I would expect an error in-line with #8389.

Actual behavior

(nan, nan) with one-shot, empty arrays with defer measurements, and ValueError: need at least one array to concatenate with tree-traversal

Additional information

No response

Source code

dev = qml.device("default.qubit")

@qml.qnode(dev)
def func(x):
    qml.RX(x, wires=0)
    m0 = qml.measure(0, postselect=1)
    qml.cond(m0, qml.X)(wires=1)
    return qml.sample(wires=1)

qml.set_shots(func, shots=[10, 10])(0.0)

Tracebacks

(array([], shape=(0, 2), dtype=int64), array([], shape=(0, 2), dtype=int64))

System information

module @circuit {
  func.func public @jit_circuit() -> tensor<i1> attributes {llvm.emit_c_interface} {
    %0 = call @circuit_0() : () -> tensor<i1>
    return %0 : tensor<i1>
  }
  func.func public @circuit_0() -> tensor<i1> attributes {diff_method = "adjoint", llvm.linkage = #llvm.linkage<internal>, qnode} {
    %cst = arith.constant 0.78539816339744828 : f64
    %cst_0 = arith.constant -1.5707963267948966 : f64
    %cst_1 = arith.constant 1.5707963267948966 : f64
    %c0_i64 = arith.constant 0 : i64
    quantum.device shots(%c0_i64) ["/Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages/pennylane_lightning/liblightning_qubit_catalyst.dylib", "LightningSimulator", "{'mcmc': False, 'num_burnin': 0, 'kernel_name': None}"]
    %0 = quantum.alloc( 2) : !quantum.reg
    %1 = quantum.extract %0[ 0] : !quantum.reg -> !quantum.bit
    %2 = quantum.extract %0[ 1] : !quantum.reg -> !quantum.bit
    %out_qubits = quantum.custom "Hadamard"() %2 : !quantum.bit
    %out_qubits_2:2 = quantum.custom "CNOT"() %out_qubits, %1 : !quantum.bit, !quantum.bit
    %out_qubits_3 = quantum.custom "RZ"(%cst_1) %out_qubits_2#1 : !quantum.bit
    %out_qubits_4:2 = quantum.custom "CNOT"() %out_qubits_2#0, %out_qubits_3 : !quantum.bit, !quantum.bit
    %out_qubits_5 = quantum.custom "Hadamard"() %out_qubits_4#0 : !quantum.bit
    %out_qubits_6 = quantum.custom "RZ"(%cst_0) %out_qubits_4#1 : !quantum.bit
    %out_qubits_7 = quantum.custom "Hadamard"() %out_qubits_5 : !quantum.bit
    %out_qubits_8 = quantum.custom "RZ"(%cst_0) %out_qubits_7 : !quantum.bit
    %out_qubits_9 = quantum.custom "Hadamard"() %out_qubits_8 : !quantum.bit
    %out_qubits_10 = quantum.custom "RZ"(%cst) %out_qubits_6 : !quantum.bit
    %mres, %out_qubit = quantum.measure %out_qubits_10 : i1, !quantum.bit
...
    quantum.finalize
    return
  }
}
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...


Name: pennylane
Version: 0.43.0.dev71
Summary: 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.
Home-page: 
Author: 
Author-email: 
License-Expression: Apache-2.0
Location: /Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages
Requires: appdirs, autograd, autoray, cachetools, diastatic-malt, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, tomlkit, typing_extensions
Required-by: amazon-braket-pennylane-plugin, pennylane_catalyst, pennylane_lightning, pennylane_lightning_kokkos

Platform info:           macOS-15.7.1-arm64-arm-64bit
Python version:          3.11.13
Numpy version:           2.3.1
Scipy version:           1.16.0
JAX version:             0.6.2
Installed devices:
- default.clifford (pennylane-0.43.0.dev71)
- default.gaussian (pennylane-0.43.0.dev71)
- default.mixed (pennylane-0.43.0.dev71)
- default.qubit (pennylane-0.43.0.dev71)
- default.qutrit (pennylane-0.43.0.dev71)
- default.qutrit.mixed (pennylane-0.43.0.dev71)
- default.tensor (pennylane-0.43.0.dev71)
- null.qubit (pennylane-0.43.0.dev71)
...
- oqc.cloud (pennylane_catalyst-0.13.0rc1)
- softwareq.qpp (pennylane_catalyst-0.13.0rc1)
- lightning.qubit (pennylane_lightning-0.43.0.dev40)
- lightning.kokkos (pennylane_lightning_kokkos-0.43.0.dev40)
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Name: pennylane
Version: 0.43.0.dev71
Summary: 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.
Home-page: 
Author: 
Author-email: 
License-Expression: Apache-2.0
Location: /Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages
Requires: appdirs, autograd, autoray, cachetools, diastatic-malt, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, tomlkit, typing_extensions
Required-by: amazon-braket-pennylane-plugin, pennylane_catalyst, pennylane_lightning, pennylane_lightning_kokkos

Platform info:           macOS-15.7.1-arm64-arm-64bit
Python version:          3.11.13
Numpy version:           2.3.1
Scipy version:           1.16.0
JAX version:             0.6.2
Installed devices:
- default.clifford (pennylane-0.43.0.dev71)
- default.gaussian (pennylane-0.43.0.dev71)
- default.mixed (pennylane-0.43.0.dev71)
- default.qubit (pennylane-0.43.0.dev71)
- default.qutrit (pennylane-0.43.0.dev71)
- default.qutrit.mixed (pennylane-0.43.0.dev71)
- default.tensor (pennylane-0.43.0.dev71)
- null.qubit (pennylane-0.43.0.dev71)
...
- oqc.cloud (pennylane_catalyst-0.13.0rc1)
- softwareq.qpp (pennylane_catalyst-0.13.0rc1)
- lightning.qubit (pennylane_lightning-0.43.0.dev40)
- lightning.kokkos (pennylane_lightning_kokkos-0.43.0.dev40)
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
{'state': array([0.+0.j, 1.+0.j]), 'execution_results': np.float64(-1.0)}
            0: ──H─────────────────────╭●───────────────────────╭●─────────────┤  <Z>
<DynamicWire>: ──Allocate──┤↗│  │0⟩────│──────────Deallocate────│──────────────┤     
<DynamicWire>: ──Allocate───║────────Z─╰X─────────Deallocate────│──────────────┤     
<DynamicWire>: ─────────────║────────║──Allocate──┤↗│  │0⟩──────│───Deallocate─┤     
<DynamicWire>: ─────────────║────────║──Allocate───║──────────Z─╰X──Deallocate─┤     
                            ╚════════╝             ╚══════════╝                      
The Kernel crashed while executing code in the current cell or a previous cell. 

Please review the code in the cell(s) to identify a possible cause of the failure. 

Click here for more info. 

View Jupyter log for further details.
0.0
0: ──┤↗├───────────────────────────────┤  <X>
1: ───║───RZ(1.57)──RY(1.57)──RZ(1.57)─┤     
      ╚═══╩═════════╩═════════╝              
['AvailableCompilers',
 'CompileError',
 'PL_CATALYST_MIN_VERSION',
 'Version',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_check_compiler_version',
 '_refresh_compilers',
 '_reload_compilers',
 'active',
 'active_compiler',
 'available',
 'available_compilers',
 'dataclasses',
 'defaultdict',
 'metadata',
 're',
 'reload',
 'sys',
 'version_info']
[[1]
 [1]
 [1]
 [1]
 [1]
 [1]
 [1]
 [1]
 [1]
 [1]]
/Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages/pennylane/workflow/qnode.py:759: UserWarning: The device's shots value does not match the QNode's shots value. This may lead to unexpected behavior. Use `set_shots` to update the QNode's shots.
  warnings.warn(
Name: pennylane
Version: 0.43.0.dev68
Summary: 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.
Home-page: 
Author: 
Author-email: 
License-Expression: Apache-2.0
Location: /Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages
Requires: appdirs, autograd, autoray, cachetools, diastatic-malt, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, tomlkit, typing_extensions
Required-by: amazon-braket-pennylane-plugin, pennylane_catalyst, pennylane_lightning, pennylane_lightning_kokkos

Platform info:           macOS-15.7-arm64-arm-64bit
Python version:          3.11.13
Numpy version:           2.3.1
Scipy version:           1.16.0
JAX version:             0.6.2
Installed devices:
- nvidia.custatevec (pennylane_catalyst-0.13.0.dev65)
- nvidia.cutensornet (pennylane_catalyst-0.13.0.dev65)
- oqc.cloud (pennylane_catalyst-0.13.0.dev65)
- softwareq.qpp (pennylane_catalyst-0.13.0.dev65)
- default.clifford (pennylane-0.43.0.dev68)
- default.gaussian (pennylane-0.43.0.dev68)
- default.mixed (pennylane-0.43.0.dev68)
- default.qubit (pennylane-0.43.0.dev68)
...
- braket.local.ahs (amazon-braket-pennylane-plugin-1.31.3)
- braket.local.qubit (amazon-braket-pennylane-plugin-1.31.3)
- lightning.kokkos (pennylane_lightning_kokkos-0.43.0.dev36)
- lightning.qubit (pennylane_lightning-0.43.0.dev36)
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
Array([6.123234e-17+0.j, 0.000000e+00-1.j], dtype=complex128)
[Array(-1., dtype=float64),
 Array(-1., dtype=float64),
 Array(-1., dtype=float64),
 Array(-1., dtype=float64)]
{'circuit_0': {'depth_pi8_ppr': 3, 'depth_ppm': 1, 'logical_qubits': 3, 'max_weight_pi8': 3, 'num_of_ppm': 3, 'pi8_ppr': 6}}
{'circuit_0': {'depth_pi8_ppr': 4, 'depth_ppm': 1, 'logical_qubits': 3, 'max_weight_pi8': 3, 'num_of_ppm': 3, 'pi8_ppr': 6}}
[Array(-1., dtype=float64),
 Array(-1., dtype=float64),
 Array(-1., dtype=float64),
 Array(-1., dtype=float64)]
2
None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[19], line 3
      1 import json
----> 3 print(json.dumps(specs, indent=2))

File /opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/__init__.py:238, in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    232 if cls is None:
    233     cls = JSONEncoder
    234 return cls(
    235     skipkeys=skipkeys, ensure_ascii=ensure_ascii,
    236     check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    237     separators=separators, default=default, sort_keys=sort_keys,
--> 238     **kw).encode(obj)

File /opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/encoder.py:202, in JSONEncoder.encode(self, o)
    200 chunks = self.iterencode(o, _one_shot=True)
    201 if not isinstance(chunks, (list, tuple)):
--> 202     chunks = list(chunks)
    203 return ''.join(chunks)

File /opt/homebrew/Cellar/[email protected]/3.11.13/Frameworks/Python.framework/Versions/3.11/lib/python3.11/json/encoder.py:439, in _make_iterencode.<locals>._iterencode(o, _current_indent_level)
    437         raise ValueError("Circular reference detected")
    438     markers[markerid] = o
--> 439 o = _default(o)
...
    179     """
--> 180     raise TypeError(f'Object of type {o.__class__.__name__} '
    181                     f'is not JSON serializable')

TypeError: Object of type Resources is not JSON serializable
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 3
      1 import pennylane as qml
      2 from functools import partial
----> 3 import catalyst
      5 @qml.register_resources({qml.ftqc.RotXZX: 1})
      6 def rot_to_xzx(phi, theta, omega, wires: qml.WiresLike):
      7     mat = qml.Rot.compute_matrix(phi, theta, omega)

File ~/Documents/catalyst/frontend/catalyst/__init__.py:78
     76 from catalyst.compiler import CompileOptions
     77 from catalyst.debug.assertion import debug_assert
---> 78 from catalyst.jit import QJIT, qjit
     79 from catalyst.passes.pass_api import pipeline
     80 from catalyst.utils.exceptions import (
     81     AutoGraphError,
     82     CompileError,
     83     DifferentiableCompileError,
     84     PlxprCaptureCFCompatibilityError,
     85 )

File ~/Documents/catalyst/frontend/catalyst/jit.py:35
     33 import catalyst
     34 from catalyst.autograph import run_autograph
...
---> 36 from catalyst.utils import wrapper
     37 from catalyst.utils.c_template import get_template, mlir_type_to_numpy_type
     38 from catalyst.utils.filesystem import Directory

ImportError: dlopen(/Users/isaac/Documents/catalyst/frontend/catalyst/utils/wrapper.so, 0x0002): symbol not found in flat namespace '_PyErr_GetRaisedException'
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
1.0
[0.70710678+0.j 0.        +0.j 0.        +0.j 0.70710678+0.j]
Name: pennylane
Version: 0.43.0.dev71
Summary: 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.
Home-page: 
Author: 
Author-email: 
License-Expression: Apache-2.0
Location: /Users/isaac/.virtualenvs/catalyst-latest/lib/python3.11/site-packages
Requires: appdirs, autograd, autoray, cachetools, diastatic-malt, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, tomlkit, typing_extensions
Required-by: amazon-braket-pennylane-plugin, pennylane_catalyst, pennylane_lightning, pennylane_lightning_kokkos

Platform info:           macOS-15.7.1-arm64-arm-64bit
Python version:          3.11.13
Numpy version:           2.3.1
Scipy version:           1.16.0
JAX version:             0.6.2
Installed devices:
- default.clifford (pennylane-0.43.0.dev71)
- default.gaussian (pennylane-0.43.0.dev71)
- default.mixed (pennylane-0.43.0.dev71)
- default.qubit (pennylane-0.43.0.dev71)
- default.qutrit (pennylane-0.43.0.dev71)
- default.qutrit.mixed (pennylane-0.43.0.dev71)
- default.tensor (pennylane-0.43.0.dev71)
- null.qubit (pennylane-0.43.0.dev71)
- reference.qubit (pennylane-0.43.0.dev71)
- braket.aws.ahs (amazon-braket-pennylane-plugin-1.31.3)
- braket.aws.qubit (amazon-braket-pennylane-plugin-1.31.3)
- braket.local.ahs (amazon-braket-pennylane-plugin-1.31.3)
- braket.local.qubit (amazon-braket-pennylane-plugin-1.31.3)
- nvidia.custatevec (pennylane_catalyst-0.13.0rc1)
- nvidia.cutensornet (pennylane_catalyst-0.13.0rc1)
- oqc.cloud (pennylane_catalyst-0.13.0rc1)
- softwareq.qpp (pennylane_catalyst-0.13.0rc1)
- lightning.qubit (pennylane_lightning-0.43.0.dev40)
- lightning.kokkos (pennylane_lightning_kokkos-0.43.0.dev40)
Name: pennylane
Version: 0.43.0
Summary: 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.
Home-page: 
Author: 
Author-email: 
License-Expression: Apache-2.0
Location: /Users/isaac/.virtualenvs/sss/lib/python3.13/site-packages
Requires: appdirs, autograd, autoray, cachetools, diastatic-malt, networkx, numpy, packaging, pennylane-lightning, requests, rustworkx, scipy, tomlkit, typing_extensions
Required-by: pennylane_catalyst, pennylane_lightning

Platform info:           macOS-15.7.1-arm64-arm-64bit-Mach-O
Python version:          3.13.5
Numpy version:           2.3.2
Scipy version:           1.16.1
JAX version:             0.6.2
Installed devices:
- nvidia.custatevec (pennylane_catalyst-0.13.0)
- nvidia.cutensornet (pennylane_catalyst-0.13.0)
- oqc.cloud (pennylane_catalyst-0.13.0)
- softwareq.qpp (pennylane_catalyst-0.13.0)
- default.clifford (pennylane-0.43.0)
- default.gaussian (pennylane-0.43.0)
- default.mixed (pennylane-0.43.0)
- default.qubit (pennylane-0.43.0)
- default.qutrit (pennylane-0.43.0)
- default.qutrit.mixed (pennylane-0.43.0)
- default.tensor (pennylane-0.43.0)
- null.qubit (pennylane-0.43.0)
- reference.qubit (pennylane-0.43.0)
- lightning.qubit (pennylane_lightning-0.43.0)

Existing GitHub issues

  • I have searched existing GitHub issues to make sure the issue does not already exist.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug 🐛Something isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions