4

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.

RandN88
  • 101
  • 8
  • May want to show your code. – DrC Sep 22 '16 at 17:42
  • The question is not code specific but rather architecture specific. However, I've added sample code to make it more clear :) – RandN88 Sep 22 '16 at 17:45
  • ctx is equal to 'context' by the way. It may be more readable to put it this way: context = cl.Context([device]) – Harry Apr 13 '20 at 17:14

3 Answers3

3

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()
jprice
  • 9,755
  • 1
  • 28
  • 32
1

The kernel code can also be stored in a .c file as foo.c. That way its easier to edit in editors like xcode. It can be read the same way

prg = cl.Program(ctx, open('foo.c').read()).build()
Aseem
  • 5,848
  • 7
  • 45
  • 69
1

If you have split your kernel code into multiple files then you also have to pass options to the cl.Program.build() function.

So for example if your kernel is called 'kernel.cl' and it includes 'functions.h' then OpenCL compiler will exit with error that it cannot find 'functions.h'. To fix this pass '-I' option to build() as below:

kernel_location = dirname(__file__)
kernel = open(join(kernel_location, 'kernel.cl').read()
program = cl.Program(context, kernel).build(options=['-I', kernels_location])

This assumes that your python code, 'kernel.cl' and 'functions.h' are in the same directory.

SpaceKees
  • 31
  • 3