cuda-quantum icon indicating copy to clipboard operation
cuda-quantum copied to clipboard

Allow torch tensors and cupy arrays as input to quantum kernels

Open zohimchandani opened this issue 10 months ago • 4 comments

Required prerequisites

  • [X] Consult the security policy. If reporting a security vulnerability, do not report the bug using this form. Use the process described in the policy to report the issue.
  • [X] Make sure you've read the documentation. Your issue may be addressed there.
  • [X] Search the issue tracker to verify that this hasn't already been reported. +1 or comment there if it has.
  • [X] If possible, make a PR with a failing test to give us a starting point to work on!

Describe the bug

Pytorch tensors and cupy arrays lie on GPU memory and we need to be able to input them into quantum kernels from GPU. Can we please add support for these?

The code snippet below works fine for numpy:

import cudaq 
from cudaq import spin 
import numpy as np 

n_samples = 5 
n_params = 2 

params = np.random.rand(n_samples, n_params)

@cudaq.kernel
def kernel(params: np.ndarray):
    
    qvector = cudaq.qvector(1)
    
    rx(params[0], qvector[0])
    ry(params[1], qvector[0])
                
result = cudaq.observe(kernel, spin.z(0), params)

result

It does not work for torch.Tensor inputs:


import cudaq 
from cudaq import spin 
import torch


n_samples = 5 
n_params = 2 

params = torch.rand(n_samples, n_params)

@cudaq.kernel
def kernel(params: torch.Tensor):
    
    qvector = cudaq.qvector(1)
    
    rx(params[0], qvector[0])
    ry(params[1], qvector[0])
                
result = cudaq.observe(kernel, spin.z(0), params)

result
CompilerError: 792851843.py:12: error: torch is not a supported type.
	 (offending source -> torch.Tensor)

and a similar error is shown for cupy arrays:

import cudaq 
from cudaq import spin 
import cupy as cp 

n_samples = 5 
n_params = 2 

params = cp.random.rand(n_samples, n_params)

@cudaq.kernel
def kernel(params: cp.ndarray):
    
    qvector = cudaq.qvector(1)
    
    rx(params[0], qvector[0])
    ry(params[1], qvector[0])
                
result = cudaq.observe(kernel, spin.z(0), params)

CompilerError: 1207908829.py:11: error: cp is not a supported type.
	 (offending source -> cp.ndarray)

Steps to reproduce the bug

NA

Expected behavior

NA

Is this a regression? If it is, put the last known working version (or commit) here.

Not a regression

Environment

  • CUDA Quantum version:
  • Python version:
  • C++ compiler:
  • Operating system:

Suggestions

No response

zohimchandani avatar Apr 05 '24 10:04 zohimchandani