All Projects → andreaferretti → nimcl

andreaferretti / nimcl

Licence: Apache-2.0 license
High level wrapper over OpenCL

Programming Languages

nim
578 projects

Nim OpenCL utilities

This is an attempt at a high level wrapper over OpenCL.

For now, things are added when needed and as such, they may not be perfectly coherent. Still, they should be enough to cover the simplest cases and get started.

Some API changes can also be expected as the library becomes more comprehensive.

Vector add example

The "hello, world!" of OpenCL:

const
  body = staticRead("vadd.cl")
  size = 1_000_000
var
  a = newSeq[float32](size)
  b = newSeq[float32](size)
  c = newSeq[float32](size)

for i in 0 .. a.high:
  a[i] = i.float32
  b[i] = (i * i).float32

let
  (device, context, queue) = singleDeviceDefaults()
  program = context.createAndBuild(body, device)
  add = program.createKernel("add_vector")
  gpuA = context.bufferLike(a)
  gpuB = context.bufferLike(b)
  gpuC = context.bufferLike(c)

add.args(gpuA, gpuB, gpuC, size.int32)

queue.write(a, gpuA)
queue.write(b, gpuB)
queue.run(add, size)
queue.read(c, gpuC)

echo c[1 .. 100]

# Clean up
release(queue)
release(add)
release(program)
release(gpuA)
release(gpuB)
release(gpuC)
release(context)

The kernel is just

__kernel void add_vector(__global float* a, __global float* b, __global float* c, int num_els) {
  int idx = get_global_id(0);
  if (idx < num_els) {
    c[idx] = a[idx] + b[idx];
  }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].