Skip to content

[python] Raise a clear error from to_cupy when CuPy is missing - #5530

Open
udsy19 wants to merge 1 commit into
NVIDIA:mainfrom
udsy19:fix/to-cupy-missing-cupy-nameerror
Open

udsy19 wants to merge 1 commit into
NVIDIA:mainfrom
udsy19:fix/to-cupy-missing-cupy-nameerror

Conversation

@udsy19

@udsy19 udsy19 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Summary

When CuPy is not installed, cudaq.to_cupy raises a confusing NameError about cp instead of the intended "please install CuPy" message.

Root cause

try:
    import cupy as cp
except ImportError:
    print('to_cupy not supported, CuPy not available. Please install CuPy.')

if dtype is None:
    ...
    dtype = cp.complex128 if ... else cp.complex64   # cp was never bound -> NameError

The except branch prints and then falls through, so the next use of cp raises NameError: name 'cp' is not defined, masking the real cause.

Fix

Raise a RuntimeError with the existing message (matching the RuntimeError already raised later in the same function for the not-on-GPU case), so the import guard fails clearly before anything else is touched.

Tests

Added python/tests/builder/test_to_cupy_missing_cupy.py, which forces the cupy import to fail (via __import__ monkeypatch) regardless of whether CuPy/GPU are present, and asserts a clear RuntimeError mentioning CuPy.

cudaq.to_cupy caught the `import cupy` ImportError, printed a message, and
then fell through the except block. The subsequent `cp.complex128` (when no
dtype is passed) dereferenced the never-bound local, so the user saw a
confusing `NameError: ... 'cp' ...` instead of the intended diagnostic.

Raise a RuntimeError carrying the existing message so the real cause -- CuPy
not being installed -- is reported directly. This matches the RuntimeError
already raised later in the same function for a non-GPU state.

Signed-off-by: Udaya Tejas <udayatejas2004@gmail.com>
@copy-pr-bot

copy-pr-bot Bot commented Oct 1, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the python-lang Anything related to the Python CUDA Quantum language implementation label Oct 1, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

python-lang Anything related to the Python CUDA Quantum language implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant