Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

EasyCL

> 编程语言
Open source

Easy to run kernels using OpenCL

188 stars0 likes1 views
WebsiteGitHub

About

Easy to run kernels using OpenCL

Table of Contents generated with DocToc

  • EasyCL
    • Example Usage
    • Examples
    • API
    • CLArray and CLWrapper objects
    • CLWrapper objects
    • CLArray objects
  • Kernel store
  • device dirty flag
  • kernel run-time templates
  • templated kernels (New!)
  • passing structs (New!)
    • How to build
      • Building on linux
        • Pre-requisites
        • Optional requirements
        • Procedure
      • Building on Windows
        • Pre-requisites
        • Optional requirements
        • Procedure
    • How to run self-tests
    • How to check my OpenCL installation/configuration?
    • What if I've found a bug?
    • What if I want a new feature?
    • What if I just have a question?
  • Recent changes
    • License

EasyCL

Easy to run kernels using OpenCL. (renamed from OpenCLHelper)

  • makes it easy to pass input and output arguments
  • handles much of the boilerplate
  • uses clew to load opencl dynamically

Example Usage

Imagine we have a kernel with the following signature, in the file /tmp/foo.cl:

kernel void my_kernel( int N, global float *one, global float *two, local float *one_local, global float *result ) {
    // kernel code here...
}

... then we can call it like:

#include "EasyCL.h"

if( !EasyCL::isOpenCLAvailable() ) {
    cout buildKernel("somekernelfile.cl", "test_function");
int in[5];
int out[5];
for( int i = 0; i in( 5, in );
kernel->out( 5, out );
kernel->run_1d( 5, 5 ); // global workgroup size = 5, local workgroup size = 5
delete kernel;
// use the results in 'out' array here

More generally, you can call on 2d and 3d workgroups by using the kernel->run method:

const size_t local_ws[1]; local_ws[0] = 512;
const size_t global_ws[1]; global_ws[0] = EasyCL::roundUp(local_ws[0], size);
kernel->run( 1, global_ws, local_ws ); // 1 is number of dimensions, could be 2, or 3

'Fluent' style is also possible, eg:

kernel->in(10)->in(5)->out( 5, outarray )->run_1d( 5, 5 );

If you use EasyCL::createForFirstGpu(), EasyCL will bind to the first OpenCL-enabled GPU (or accelerator), that it finds. If you want to use a different device, or an OpenCL-enabled CPU, you can use one of the following method:

cpp
EasyCL::createForIndexedGpu( int gpuindex ); // looks for opencl-enabled gpus, and binds to the (gpuindex+1)th one
EasyCL::createForFirstGpuOtherwiseCpu();
EasyCL::createForPlatformDeviceIndexes( int platformIndex, int deviceIndex );
EasyCL::createForPlatformDeviceIds( int platformId, int deviceId ); // you can get these ids by running `gpuinfo` first

You can run gpuinfo to get a list of platforms and devices on your system.

There are some examples in the test subdirectory.

Environment Vars

You can use the environment variable CL_GPUOFFSET to choose a GPU. It shifts the gpu numbering downwards by this offset, ie gpu index 1 becomes 0, index 2 becomes 1. For example, if a program uses gpu index 0 by default, setting CL_GPUOFFSET to 1 will choose the second gpu, and setting it to 2 will choose the third gpu.

Examples

There are some examples in the test subdirectory.

  • create a couple of Wrapper objects, pass them into a kernel, look at the results, see method testfloatwrapper, main ) of testfloatwrapper.cpp
  • (New!) to use with clBLAS, see testclblas.cpp

API

// constructor:
EasyCL::EasyCL();
// choose different gpu index
void EasyCL::gpu( int gpuindex );

// compile kernel
CLKernel *EasyCL::buildKernel( string kernelfilepath, string kernelname, string options = "" );

// Note that you pass `#define`s in through the `options` parameters, like `-D TANH`, or `-D TANH -D BIASED`

// passing arguments to kernel:

CLKernel::in( int integerinput );

CLKernel::in( int arraysize, const float *inputarray ); // size in number of floats
CLKernel::in( int arraysize, const int *inputarray ); // size in number of ints
CLKernel::out( int arraysize, float *outputarray ); // size in number of floats
CLKernel::out( int arraysize, int *outputarray ); // size in number of ints
CLKernel::inout( int arraysize, float *inoutarray ); // size in number of floats
CLKernel::inout( int arraysize, int *inoutarray ); // size in number of ints

// to allocate local arrays, as passed-in kernel parameters:
CLKernel::localFloats( int localarraysize ); // size in number of floats
CLKernel::localInts( int localarraysize ); // size in number of ints

// running kernel, getting result back, and cleaning up:
CLKernel::run_1d( int global_ws, int local_ws );
CLKernel::run( int number_dimensions, size_t *global_ws, size_t *local_ws );

// helper function:
EasyCL::roundUp( int quantizationSize, int desiredTotalSize );

CLArray and CLWrapper objects

To make it possible to reuse data between kernels, without moving back to PC main memory, and back onto the GPU, you can use CLWrapper objects.

These can be created on the GPU, or on the host, and moved backwards and forwards between each other, as required. They can be passed as an 'input' and 'output' to a CLKernel object. They can be reused between kernels.

There are two 'flavors':

  • CLArray: more automated, but more memory copying, since creates a new array on the host
  • CLWrapper: wraps an existing host array, you'll need to call copyToDevice() and copyToHost() yourself

CLArray objects are the first implementation. CLWrapper objects are the second implementation. You can use either, but note that CLWrapper objects are the ones that I use myself.

CLWrapper objects

Compared to CLArray objects, CLWrapper objects need less memory copying, since they wrap an existing native array, but you will need to call copyToDevice() and copyToHost() yourself.

cpp
if( !EasyCL::isOpenCLAvailable() ) {
    cout copyToDevice();
kernel->in( inwrapper );
kernel->out( outwrapper );
kernel->run_1d( 5, 5 );
outwrapper->copyToHost();
assertEquals( out[0] , 7 );
assertEquals( out[1] , 10 );
assertEquals( out[2] , 13 );
assertEquals( out[3] , 16 );
assertEquals( out[4] , 19 );
cout copyTo( wrapper2 );

CLWrapper objects are currently available as CLIntWrapper and CLFloatWrapper.

CLArray objects

Compared to CLWrapper objects, CLArray objects are more automated, but involve more memory copying.

cpp
EasyCL cl;

CLArrayFloat *one = cl.arrayFloat(10000); // create CLArray object for 10,000 floats
(*one)[0] = 5; // give some data...
(*one)[1] = 7;

CLArrayFloat *two = cl.arrayFloat(10000);

// pass to kernel:
kernel->in(one)->out(two);

You can then take the 'two' CLArray object, and pass it as the 'input' to a different kernel, or you can use operator[] to read values from it.

Currently, CLArray is available as 'CLArrayFloat' and 'CLArrayInt'.

Kernel store

You can store kernels in the store, under a unique name each, to facilitate kernel caching

cpp
// store:
cl->storeKernel( "mykernelname", somekernel ); // name must be not used yet

// check exists:
cl->kernelExists( "mykernelname" );

// retrieve:
CLKernel *kernel = cl->getKernel( "mykernelname" );

New: you can transfer kernel ownership to EasyCL object, by passing third parameter deleteWithCl = true. Then, when the EasyCL object is deleted, so will be the kernel.

cpp
// store:
cl->storeKernel( "mykernelname", somekernel, true ); // this kernel will be deleted when
                                                     // `cl` object is deleted

device dirty flag

For CLWrapper objects, if the wrapper is passed to a kernel via out or inout, and then that kernel is run, then isDeviceDirty() will return true, until ->copyToHost() is called. So, you can use this to determine whether you need to run ->copyToHost() prior to reading the host-side array.

The following methods will reset the flag to false:

  • copyToDevice()
  • copyToHost()

This is a new feature, as of May 15 2015, and might have some bugs prior to May 31 2015 (ie, about 2 weeks, long enough for me to find any bugs).

templated kernels

  • You can use templating with kernels, at runtime, using the build-in Lua engine
  • Simple variable substitution by using eg {{some_variable_name}}
  • Embed lua code, including loops, if statements etc, ... using eg {% for i=0,5 do %}... code here ... {% end %}
  • The magic is done using the [templates/TemplatedKernel.h](templates/TemplatedKernel.h] class
  • See examples in test/testTemplatedKernel.cpp
  • Note that this templating method is based on John Nachtimwald's work at https://john.nachtimwald.com/2014/08/06/using-lua-as-a-templating-engine/ ( MIT License )

passing structs

  • Simply #include new "CLKernel_structs.h" header, in order to be able to pass structs
  • See test/testStructs.cpp for an example

Profiling (New!)

  • Simply call cl->setProfiling(true);, then run your kernels as normal, then call cl->dumpProfiling to print the results
  • Timings are cumulative over multiple calls to the same kernel
  • Timings are grouped by kernel filename and kernelname
  • See test/testprofiling.cpp for an example

Using with clBLAS

  • You can call ->getBuffer() on a CLWrapper object, in order to pass it to clBLAS. You can see an example eg at THClBlas.cpp#L425

How to build

Build options

Option Description
`PROVIDE_LUA_ENGINE If you want to call EasyCL from within Lua, then choose option PROVIDE_LUA_ENGINE=OFF, otherwise leave it as ON
DEV_RUN_COG Only for EasyCL maintainers, leave as OFF otherwise
BUILD_TESTS whether to build unit tests

Building on Mac OS X

(tested on Travis https://travis-ci.org/hughperkins/EasyCL )

Pre-requisites

  • git
  • cmake
  • g++
  • (maybe) OpenCL (not sure if installed by default? Travis worked ok without explicitly installing it)

Procedure

bash
git clone --recursive https://github.com/hughperkins/EasyCL.git
cd EasyCL
mkdir build
cd build
cmake ..
make install
  • the executables will be in the ../dist/bin folder, and the .dylib files in ../dist/lib
  • Dont forget the --recursive, otherwise you will see odd errors about clew/src/clew.c missing
    • If this happens, you can try git submodule init and then git submodule update.

Building on linux

Pre-requisites

  • OpenCL needs to be installed, which means things like:
    • in linux, you'll need a libOpenCL.so installed, and
    • an OpenCL implementation, ie some kind of .so file, and
    • an appropriate text file at /etc/OpenCL/vendors/somename.icd , containing the full path to the Open CL implementation .so file
  • git (only needed to obtain the source-code)
  • cmake
  • g++

Procedure

bash
git clone --recursive https://github.com/hughperkins/EasyCL.git
cd EasyCL
mkdir build
cd build
cmake ..
make install
  • the executables will be in the `

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C++

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言