openclpyopencl

pyopencl - how to use generic types?


I work Interchangeably with 32 bit floats and 32 bit integers. I want two kernels that do exactly the same thing, but one is for integers and one is for floats. At first I thought I could use templates or something, but it does not seem possible to specify two kernels with the same name but different argument types?

import pyopencl as cl
import numpy as np

ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)

prg = cl.Program(ctx, """
__kernel void arange(__global int *res_g)
{
  int gid = get_global_id(0);
  res_g[gid] = gid;
}

__kernel void arange(__global float *res_g)
{
  int gid = get_global_id(0);
  res_g[gid] = gid;
}
""").build()

Error:

<kernel>:8:15: error: conflicting types for 'arange'
__kernel void arange(__global float *res_g)
              ^
<kernel>:2:15: note: previous definition is here
__kernel void arange(__global int *res_g)

What is the most convenient way of doing this?


Solution

  • #define directive can be used for that:

    code = """ 
    __kernel void arange(__global TYPE *res_g)
    {
      int gid = get_global_id(0);
      res_g[gid] = gid;
    }
    """
    
    prg_int = cl.Program(ctx, code).build("-DTYPE=int")
    prg_float = cl.Program(ctx, code).build("-DTYPE=float")