Skip to content

[BUG] IndexError in qml.math.stack when using keyword argumentsΒ #9140

@zczhong149-art

Description

@zczhong149-art

Expected behavior

The function should correctly handle arguments whether they are passed positionally or via keywords, consistent with standard Python behavior and numpy.stack.

Actual behavior

The execution fails within the decorator logic:
IndexError: tuple index out of range at pennylane/math/multi_dispatch.py in wrapper.

Additional information

The root cause is in pennylane/math/multi_dispatch.py. The wrapper function assumes that the argument index specified in argnum or tensor_list will always be present in the args tuple. When using stack(values=[...]), args is empty, leading to the crash.

Source code

import pennylane as qml
from pennylane import numpy as np

# Define sample tensors
tensor1 = np.array([[1, 2], [3, 4]])
tensor2 = np.array([[5, 6], [7, 8]])

# 1. This works (positional argument)
# result = qml.math.stack([tensor1, tensor2], axis=0)

# 2. This fails (keyword argument)
result = qml.math.stack(values=[tensor1, tensor2], axis=0)

# 3. This also fails (empty list via keyword)
# result_empty = qml.math.stack(values=[], axis=0)

Tracebacks

Traceback (most recent call last):
  File "/path/to/tmp.py", line 15, in <module>
    result_empty = qml.math.stack(values=[], axis=0)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/path/to/site-packages/pennylane/math/multi_dispatch.py", line 144, in wrapper
    if a in tensor_lists and isinstance(args[a], (list, tuple)):
                                        ~~~~^^^
IndexError: tuple index out of range

System information

Version: 0.44.0
Platform info: Linux-5.19.0-45-generic-x86_64-with-glibc2.35
Python version: 3.11.14
Numpy version: 2.3.3
Scipy version: 1.16.3

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions