5

I want to call a function written in CUDA(C++) from python and pass to it numpy arrays as input and get output arrays from this function. Is this possible? This is the sole objective of this question.

ps : As I understand if such a function were to be made into a proper program and compiled into an executable then it could be called from python as a shell command. However how could I pass and get arrays as inputs and outputs without using files?

2 Answers 2

13

PyCuda is provided by nvidia. it's also very easy to use. check it out https://developer.nvidia.com/pycuda

I suppose you want something like that:

import pycuda.autoinit
import pycuda.driver as drv
import numpy

from pycuda.compiler import SourceModule
mod = SourceModule("""
__global__ void multiply_them(float *dest, float *a, float *b)
{
  const int i = threadIdx.x;
  dest[i] = a[i] * b[i];
}
""")

multiply_them = mod.get_function("multiply_them")

a = numpy.random.randn(400).astype(numpy.float32)
b = numpy.random.randn(400).astype(numpy.float32)

dest = numpy.zeros_like(a)
multiply_them(
        drv.Out(dest), drv.In(a), drv.In(b),
        block=(400,1,1), grid=(1,1))

print dest-a*b
Sign up to request clarification or add additional context in comments.

Comments

0

There are a few libraries that might be helpful for this sort of task, but PyCuda seems the closest to what you're describing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.