Search code examples
pythonopenclpycudapyopencl

Storing Kernel in Separate File - PyOpenCL


I'm trying to store the kernel part of the code, with the 3 """ , in a different file. I tried saving it as a text file and a bin file, and reading it in, but I didn't find success with it. It started giving me an error saying """ is missing, or ) is missing. "However, if i just copy paste the kernel code into cl.Program(, it works.

So, is there a way to abstract long kernel code out into another file? This is specific to python, thank you!

#Kernel function
prg = cl.Program(ctx, """
__kernel void sum(__global double *a, __global double *b, __global double *c)
{
  int gid = get_global_id(0);
  c[gid] = 1;

}
""").build()

So pretty much everything inside """ """, the second argument of cl.Program() function, I wan't to move into a different file.


Solution

  • Just put your kernel code in a plain text file, and then use open(...).read() to get the contents:

    foo.cl

    __kernel void sum(__global double *a, __global double *b, __global double *c)
    {
      int gid = get_global_id(0);
      c[gid] = 1;
    
    }
    

    Python code

    prg = cl.Program(ctx, open('foo.cl').read()).build()