Designing IA for AI - Information Architecture Conference 2024
Â
Introduction to OpenCL, 2010
1. Introduction to OpenCL
How to select OpenCL devices, initialise a compute context, allocate device memory,
compile and run kernels, output results
OpenCL Workshop | December 1, 2010 | Brisbane, Australia!
Tomasz Bednarz, CESRE!
2. OpenCL is a trademark of Apple, Inc.
Welcome to Open Computing Language (OpenCLTM)
â˘âŻ N-Body Simulation Demo"
â˘âŻ Khronos Group and OpenCL standard"
â˘âŻ OpenCL Anatomy"
â˘âŻ Platform Model"
â˘âŻ Execution Model"
â˘âŻ Memory Model"
â˘âŻ Short Introduction to OpenCL Programming "
â˘âŻ OpenCL C language"
â˘âŻ Supported data types"
â˘âŻ Synchronisation primitives"
â˘âŻ Additional information and resources."
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
4. N-Body Simulation
Lars Nyland, Mark Harris, Jan Prins âFast N-Body Simulation with CUDAâ. In Hubert
Nguyen, editor, GPU Gems 3, chapter 31, pages 677-695, Addison Wesley 2007.
â˘âŻ Applications"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
Molecular dynamics"
Astronomical and astrophysical simulations"
Fluid dynamics simulation"
Radiosity (Radiometric transfer)"
â˘âŻ N2 interactions to compute per time-step"
â˘âŻ For the brute force all-pairs approach
discussed here"
â˘âŻ Highly Parallel"
â˘âŻ High Arithmetic intensity"
Two of these galaxies
attract each other.
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
5. N-Body Simulation (http://developer.nvidia.com/gpugems3)
â˘âŻ N-Body simulation models the motion of particles subject to a
force due to the particle-particle interactions between all particles
in the system"
â˘âŻ Typical example: simulation of stars in a galaxy subject to the
gravitational force"
â˘âŻ Given N bodies with an initial position xj and velocity vj for 1â¤iâ¤N,
the force fij on body i caused by its gravitational attraction to body
j is given by the following:"
fij = G
mi m j
rij
2
!
rij
rij
Fi =
#
fij = Gmi
1! j!N
i" j
#
m j rij
1! j!N
i" j
rij
3
where mi and mj are the masses of bodies i and j."
â˘âŻ The acceleration is computed as:"
F
ai =
j
i
mi
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
i
rij = x j ! xi
6. N-Body Simulation
â˘âŻ As bodies approach each other, the force between
them grows without bound, therefore softening factor
e2>0 may be added"
Fi ! Gmi
#
1" j"N
m j rij
(
2
rij + e
2
)
3
2
â˘âŻ The softening factor limits the magnitude of the force
between the bodies, which is desirable for numerical
integration of the system state"
â˘âŻ Acceleration:"
F
ai = i ! G " $
mi
1# j#N
m j rij
(
2
rij + e
2
)
3
2
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
7. N-Body Simulation: parallel concept
single interaction
between i and j
Outer Loop (i)
Particle i
Particle j
Inner Loop (j)
â˘âŻ Particles i, j interact with each other"
â˘âŻ OpenCL can be used to compute acceleration on all bodies in parallel "
â˘âŻ N/p work groups of p work items process p bodies at a time"
â˘âŻ Every work item loads all other body positions from off-chip memory"
â˘âŻ N2 loads ⌠bandwidth bound = poor performance "
â˘âŻ Optimization (using tiles) to be presented in the afternoon session"
8. N-Body Simulation: body-body force calculation
Fi ! Gmi
#
1" j"N
ai =
Fi
! G" $
mi
1# j#N
m j rij
(
(
http://developer.download.nvidia.com/compute/opencl/sdk/website/samples.html#oclNbody
http://developer.apple.com/library/mac/#samplecode/OpenCL_NBody_Simulation_Example/Introduction/Intro.html
2
rij + e
2
m j rij
2
rij + e
2
)
)
3
3
2
2
13. http://www.khronos.org/opencl/
What is OpenCL?
OpenCL - Open Computing Language: open, royalty-free standard for programming
heterogeneous parallel computing at the intersection of GPU and multi-core CPU capabilities.
CPUs
Multiple cores driving
performance increases
Multi-processor
programming, threading
libraries - e.g. OpenMP
GPUs
Emerging
Intersection
Heterogeneous
Computing
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
Increasingly general
purpose data-parallel
computing
Graphics APIs and
Shading Languages,
Vendor Compute APIs
Courtesy of
14. What is OpenCL?
Roadmap convergence
OpenGL 4.0 and OpenGL ES 2.0
are both streamlined, programmable
pipelines. GL and ES working groups
are working on convergence. WebGL
is a positive pressure for portable 3D
content for all platforms.
Desktop Visual Computing
OpenGL and OpenCL have direct
interoperability. OpenCL objects can be
Created from OpenGL Textures, Buffer
Objects and Renderbuffers.
Parallel computing and
visualisation
OpenCL â the center of a
visual computing
ecosystem with parallel
computations, 3D, video,
audio, and image
processing on desktop,
embedded and mobile
systems!
Desktop 3D Ecosystem
Cross-platform
desktop 3D
3D for Web
Heterogeneous
Parallel Programing
Embedded 3D
Surface and
synch abstraction
Streaming Media and
Image Processing
Mobile Visual Computing
Compute, graphics and AV APIs
interoperate through EGL.
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
Hundreds of men
years invested by
industry experts in
coordinated
ecosystem!
Streamlined APIs for mobile and
embedded graphics, media and
compute acceleration
Based on http://www.khronos.org/opencl/
15. OpenCL Timeline
â˘âŻ OpenCL 1.0 was released six months after the proposal was created"
â˘âŻ OpenCL ships ďŹrst on AppleĘźs Mac OS X Snow Leopard"
â˘âŻ 18 month cadence between OpenCL 1.0 and OpenCL 1.1"
â˘âŻ Backward compatible to protect software investment"
Multiple conformant
implementations ship
across diverse OS and
platforms.!
Khronos releases
publicly OpenCL 1.1 as
royalty-free speciďŹcation.!
June 2008
May 2009
December 2008
OpenCL working group!
is proposed by Apple. !
Draft spec is contributed!
to Khronos.!
June 2010
2nd Half 2009
Khronos releases
OpenCL 1.0 conformance
tests to ensure highquality implementations.!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
OpenCL 1.1 spec is
released and ďŹrst
implementation ship.!
Based on http://www.khronos.org/opencl/
17. Design goals of OpenCL
â˘âŻ Enable all compute resources in system"
â˘âŻ CPUs, GPUs, and other processors enabled as peers"
â˘âŻ Data- and task- parallel compute model"
â˘âŻ EfďŹcient parallel programming model"
â˘âŻ ANSI C99 based kernel language"
â˘âŻ Low-level abstraction"
â˘âŻ Abstracts the speciďŹcs of the underlying hardware"
â˘âŻ High-performance, but device independent "
â˘âŻ DeďŹne precision requirements for all ďŹoating-point computations"
â˘âŻ Consistent results on all platforms and devices"
â˘âŻ Interoperability with Graphics APIs"
â˘âŻ Dedicated support for OpenGL, OpenGL ES and DirectX"
â˘âŻ Drive future hardware requirements"
â˘âŻ Applicable to both consumer and HPC applications"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
19. Itâs heterogeneous world
â˘âŻ Platform model encapsulates
compute resources"
â˘âŻ A modern platform includes:"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
One or more CPUs"
One or more GPUs"
Optional accelerators (e.g. DSPs)"
Other?"
Using OpenCL Programmers write a single portable
program that uses ALL resources !
in the heterogeneous platform!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
Based on http://www.khronos.org/opencl/
20. OpenCL Platform Model
â˘âŻ One Host connected to one or more Compute Devices"
â˘âŻ Compute device can be a CPU, GPU or other processor"
â˘âŻ Each Compute Device is composed of one or more Compute Units"
â˘âŻ Compute Unit can may be a core, multi-processor, etc."
â˘âŻ Each Compute Unit is further divided into one or more Processing Elements "
â˘âŻ Processing Elements execute code as SIMD or SPMD!
PROCESSING ELEMENT
âŚ.
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
.....
COMPUTE DEVICE
COMPUTE DEVICE
HOST!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
COMPUTE
UNIT
21. Anatomy of OpenCL Application
OpenCL Application
Device Code
- Written in OpenCL C
- Executes on the device
Host Code
- Written in C/C++
- Executes on the host
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE
UNIT
COMPUTE DEVICE
âŚ.
HOST!
COMPUTE
UNIT
COMPUTE
UNIT
.....
COMPUTE
DEVICES
COMPUTE
UNIT
COMPUTE DEVICE
â˘âŻ Host code sends commands to the Devices:"
â˘âŻ To transfer data between host memory and device memories!
â˘âŻ To execute device code!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
22. Anatomy of OpenCL Application
â˘âŻ Serial code executes in a Host (CPU) thread"
â˘âŻ Parallel code executes in many Device (GPU) threads across multiple processing elements"
OCL Application
Serial code
Parallel code
Serial code
Parallel code
Host = CPU
Device = GPU
âŚ
Host = CPU
Device = GPU
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
âŚ
24. OpenCL Execution Model
â˘âŻ OpenCL application runs on a Host which submits
work to the Compute Devices!
â˘âŻ Work item: the basic unit of work on an OpenCL device"
â˘âŻ Kernel: the code for a work item, which is basically C
function"
â˘âŻ Program: Collection of kernels and other functions
(analogous to a dynamic library). Managed by host."
â˘âŻ Context: The environment within which work-items
execute, which includes devices and their memories and
command queues (contains all resources for computation)"
â˘âŻ Command queue: A queue used by the Host application
to submit work to a Device (kernel execution instances)"
â˘âŻ Work is queued in-order, one queue per device"
â˘âŻ Work can be executed in-order or out of order"
â˘âŻ Events are used for synchronisation"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
MEMORY!
GPU!
CPU!
CONTEXT
GPU
&
CPU
Queues
COMMANDS
25. OpenCL Execution Model
â˘âŻ Portable execution model that allows a kernel to execute at each point in a
problem domain (N-dimensional computational domain) Ă ď decomposition of a
task into work-items!
Traditional loop as a function in C
OpenCL C kernel
void !
addVector(const float *A,!
const float *B,!
float *C,!
int N)!
{!
int index;!
__kernel void !
addVector(__global const float *A,!
__global const float *B,!
__global float *C,!
int N)!
{!
int index = get_global_id(0);!
!
!
for (index=0; index<N, index++)!
C[index] = A[index]+B[index];!
}!
if (index < N)!
C[index] = A[index]+B[index];!
}!
!
Work item: the basic unit of work on an OpenCL device
Kernel: the code for a work item, which is basically C function
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
26. Kernel Execution on Platform Model
Work-Item
Compute element
Work-Group
Compute unit
Kernel execution instance
â˘âŻ Each work-item is executed by a
compute element!
â˘âŻ Each work-group is executed on a
compute unit"
â˘âŻ Several concurrent work-groups can
reside on one compute unit depending
on work-groupĘźs memory requirements
and compute unitĘźs memory resources"
Compute device
âŚ
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
â˘âŻ Each kernel is executed on a compute
device!
27. Benefits of Work-Groups
â˘âŻ Automatic scalability across devices with different numbers of compute units"
â˘âŻ Work-groups can execute in any order, concurrently or sequentially"
â˘âŻ EfďŹcient cooperation between work-items of same work-group"
â˘âŻ Fast shared memory and synchronization"
â˘âŻ Independence between work-groups gives scalability:"
â˘âŻ A kernel scales across any number of compute units"
Device with 2 compute units
Kernel
Launch
Device with 4 compute units
Unit 0
Unit 1
Unit 0
Unit 1
Unit 2
Unit 3
Work-group 0!
Work-group 1!
Work-group 0!
Work-group 0!
Work-group 1!
Work-group 2!
Work-group 3!
Work-group 2!
Work-group 3!
Work-group 1!
Work-group 4!
Work-group 5!
Work-group 6!
Work-group 7!
Work-group 4!
Work-group 5!
Work-group 2!
Work-group 6!
Work-group 7!
Work-group 3!
Work-group 4!
Work-group 5!
Work-group 6!
Work-group 7!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
28. Work-group synchronisation
â˘âŻ Always deďŹne the best N-dimensional index
space (NDRange) for your algorithms
(currently 1D, 2D and 3D index spaces are
supported)"
â˘âŻ Kernels are executed across a global domain of
work-items!
â˘âŻ Work-items are single points of execution and
are grouped into local work-groups!
â˘âŻ Global Dimensions: 1024x1024 (whole problem space)"
â˘âŻ Local Dimensions: 32x32 (work-group)"
Cannot synchronise outside "
of work-groups"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
1024
1024
Synchronisation between work-items"
possible only within workgroups:"
barriers and memory fences!
29. Work-items and work-groups
â˘âŻ A kernel is a function executed in each point of a problem
domain (for each work-item)"
â˘âŻ Number of work items = 4096 (16 work-groups, 256 workitems each):"
get_group_id(0) = 2
DEVICE
__kernel void !
addVector(__global const float *A,!
__global const float *B,!
__global float *C,!
int N)!
{!
int index = get_global_id(0);!
!
if (index < N)!
C[index] = A[index]+B[index];!
}!
get_global_id(0) = 1792
NDRANGE
0
1
2
3
4
âŚ
15
get_global_size(0) = 4096
0
1
get_num_groups (0) = 16
âŚ
WORK GROUP
255
WORK ITEM
get_local_size(0) = 256
get_local_id(0) = 255
30. Work-items and work-groups in 2D
â˘âŻ Number of work items to execute 128 x 128 = 16384:" (A kernel is executed in each point of a problem domain)
get_group_id(0),get_group_id(1)
DEVICE
0,0 1,0 2,0
âŚ
7,0
0,0 1,0 2,0
0,1
1,1
0,2
0,2
âŚ
1,1
âŚ
15,0
4,1
âŚ
2,2
3,4
.
0,7
get_global_size(0)
get_global_id(0),get_global_id(1)
7,7
0,15
get_local_size(0)
get_local_id(0),get_local_id(1)
get_local_size(1)
get_global_size(1)
0,1
WORK ITEMS
WORK GROUP
NDRANGE
32. OpenCL Memory Model
â˘âŻ Address spaces"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
Private: read/write access for work-item only"
Local: read/write access for entire work-group"
Global/Constant: visible to all work-groups"
Host: accessible by the CPU"
â˘âŻ Synchronisation"
Private
Memory!
Private
Memory!
Private
Memory!
Private
Memory!
Work Item1
Work ItemJ
Work Item1
Work ItemJ
PE!
PE!
PE!
PE!
Compute Unit 1
Local Memory!
â˘âŻ All Synchronisation for all memory accesses
must be done explicitly"
Compute Unit N
Local Memory!
Global/Constant Memory!
Compute Device
Memory management is Explicit!
You must move data from host Ă ď global Ă ď local ⌠and back"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
Host Memory!
Host
35. OpenCL Language and API Highlights
â˘âŻ Platform Layer API (called from host)"
â˘âŻ Abstraction layer for diverse computational resources"
â˘âŻ Query, select and initialise compute devices"
â˘âŻ Create compute contexts and work-queues"
â˘âŻ Runtime API (called from host)"
â˘âŻ Launch compute kernels"
â˘âŻ Set kernel execution conďŹguration"
â˘âŻ Manage scheduling, compute, and memory resources"
â˘âŻ OpenCL language"
â˘âŻ To write C-based compute kernels for execution on a compute device"
â˘âŻ Includes rich set of build-in functions"
â˘âŻ Can be compiled JIT/Online or ofďŹine"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
36. OpenCL Language Highlights
â˘âŻ Function qualiďŹers"
__kernel void !
addVector(__global const float *A,!
__global const float *B,!
__global float *C,!
int N)!
{!
int index = get_global_id(0);!
â˘âŻ __kernel qualiďŹer declares a function as a kernel"
â˘âŻ Address space qualiďŹers"
!
if (index < N)!
C[index] = A[index]+B[index];!
}!
â˘âŻ __global, __local, __constant, __private"
â˘âŻ Work-item functions"
â˘âŻ get_work_dim(), get_global_id(), get_local_id(), get_group_id(), get_local_size()"
â˘âŻ Image functions"
â˘âŻ Images must be accessed through built-in functions"
â˘âŻ Read/writes performed through sampler objects from host or deďŹned in source"
â˘âŻ Synchronisation functions"
â˘âŻ Barriers â all work-items within a work-group must execute the barrier function
before any work-item in the work-group can continue"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
37. OpenCL Framework: Overview
â˘âŻ Platform layer: platform query and context creation"
â˘âŻ Compiler for OpenCL C"
â˘âŻ Runtime: memory management and command execution within a context"
CPU!
GPU!
CONTEXT!
KERNELS!
PROGRAMS!
__kernel void !
addVector(!
__global float *A,!
__global const float *B,!
__global float *C)!
{!
int i = get_global_id(0);!
C[i] = A[i]+B[i];!
}!
GPU binary!
addVector!
CPU binary!
MEMORY OBJECTS!
BUFFERS!
IMAGES!
arg[0] value!
IN
ORDER!
QUEUE!
OUT OF
ORDER
QUEUE!
arg[1] value!
arg[2] value!
COMPILE CODE!
COMMAND QUEUES!
CREATE ARGS AND DATA!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
COMPUTE DEVICE
SEND TO EXECUTION!
38. OpenCL Framework: Objects Types
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
cl_platform_id
"â identiďŹer for a speciďŹc platform"
cl_device_id
"â identiďŹer for a speciďŹc compute device "
cl_context
"â handle for a compute context"
cl_command_queue "â handle for a command queue (for a compute device)"
cl_mem
"â handle for a memory resource (managed by context)"
cl_program
"â handle for a program resource (library of kernels)"
cl_kernel
"â handle for a compute kernel "
â˘âŻ All object types are opaque handles"
â˘âŻ Enables cross-platform compatibility for complex data types"
â˘âŻ All objects are reference counted and garbage collected"
â˘âŻ When reference count reaches zero, object is deallocated"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
39. OpenCL Framework: Platform Layer
â˘âŻ To query platform information:"
â˘âŻ clGetPlatformIDs() Ă ď obtain the list of platforms available"
â˘âŻ clGetPlatformInfo() Ă ď platform proďŹle, version, name, vendor, extensions"
â˘âŻ To query Devices: "
â˘âŻ clGetDeviceIDs() Ă ď obtain the list of devices available on platform"
â˘âŻ clGetDeviceInfo() Ă ď type, capabilities, vendor, name, etc."
â˘âŻ Create an OpenCL context for one or more devices"
One or more devices!
cl_device_id!
Context!
cl_context!
Memory and device code shared by these devices!
cl_mem
!cl_program!
Command queues to send commands to these devices!
cl_command_queue!
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
40. Context creation: platform IDs
â˘âŻ SIMPLE EXAMPLE get the platform ID:!
"
// get ďŹrst OpenCL platform ID available"
cl_platform_id platform;"
err = clGetPlatformIDs(1, &platform, NULL);"
cl_int clGetPlatformIDs(!
cl_uint num_entries,"
cl_platform_id *platforms,"
cl_uint *num_platforms)"
â˘âŻ Get all platform IDs:!
"
// get number of OpenCL platforms available"
cl_int err;"
cl_uint num_platforms;"
std::vector<cl_platform_id> platformIDs;"
err = clGetPlatformIDs(NULL, NULL, &num_platforms);
if (err != CL_SUCCESS) { ⌠}
platformIDs.resize(num_platforms);
// get all OpenCL platform IDs
err = clGetPlatformIDs(num_platforms, &platformIDs[0], NULL);
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
If NULL, the arguments are ignored
41. Context creation: device IDs
â˘âŻ SIMPLE: get ďŹrst GPU associated with the platform:"
"
cl_device_id device;"
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);"
â˘âŻ Get all platform IDs:"
"
cl_uint nDevices;"
cl_device_type deviceType;"
vector<cl_device_id> deviceIDs;"
"
cl_int clGetDeviceIDs(!
cl_platform_id platform,"
cl_device_type device_type,"
cl_uint num_entries,"
cl_device_id *devices,"
cl_uint *num_devices)"
DEVICE TYPE:!
if (platformIDs.size() == 0) {"
CL_DEVICE_TYPE_CPU"
// get number of device IDs for default platform"
CL_DEVICE_TYPE_GPU"
CL_DEVICE_TYPE_ACCELERATOR"
err = clGetDeviceIDs(NULL, deviceType, 0, NULL, &nDevices); "
CL_DEVICE_TYPE_DEFAULT"
} else {"
CL_DEVICE_TYPE_ALL"
// get number of device IDs for selected platform"
err = clGetDeviceIDs(platformIDs[selectedPlatform], deviceType, 0, NULL, &nDevices); "
}"
deviceIDs.resize(nDevices);"
if (platformIDs.size() == 0) {"
// get default device IDs of default platform"
err = clGetDeviceIDs(NULL, deviceType, nDevices, &deviceIDs[0], NULL); "
} else {"
// get device IDs of selected platform"
err = clGetDeviceIDs(platformIDs[selectedPlatform], deviceType, nDevices, &deviceIDs[0], NULL); "
}"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
43. Error Handling and Resource Deallocation
â˘âŻ Error handling:"
â˘âŻ All host functions return an error code"
â˘âŻ Context error callback"
â˘âŻ The callback function may be called asynchronously by OpenCL and it is the applicationĘźs
responsibility to ensure that the callback function is thread-safe"
â˘âŻ Resource deallocation"
â˘âŻ Reference counting API: clRetain*(), clRelease*()"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
clRetainContext();"
clReleaseContext();"
clRetainMemObject();"
clReleaseMemObject();"
clRetainKernel();"
clReleaseKernel();"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
44. OpenCL C
â˘âŻ Derived from ISO C99!
â˘âŻ Features added to the language:!
â˘âŻ Work-items and work-groups"
â˘âŻ Vector types"
â˘âŻ Synchronisation"
â˘âŻ Address space qualiďŹers"
â˘âŻ Also includes a large set of built-in functions:!
â˘âŻ Image manipulation"
â˘âŻ Work-item manipulation"
â˘âŻ Math functions"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
45. OpenCL C
Language Restrictions:!
â˘âŻ No functions deďŹned in C99 standard headers"
â˘âŻ No recursion supported"
â˘âŻ Pointers to function are not permitted"
â˘âŻ Pointers to pointers allowed within a kernel, but not as an argument"
â˘âŻ No variable length arrays and structures"
â˘âŻ Bit ďŹelds are not supported"
â˘âŻ Writes to a pointer to a type less than 32 bits are not supported*"
â˘âŻ Double types are not supported, but reserved"
â˘âŻ 3D Image writes are not supported"
"
"
*Some restrictions are addressed through extensions
"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
46. OpenCL C Optional Extensions
â˘âŻ Extensions are optional features exposed through OpenCL"
â˘âŻ The OpenCL working group has already approved many extensions to the
OpenCL speciďŹcation:"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
Double precision ďŹoating-point types"
Built-in functions to support doubles"
Atomic functions*"
Byte-addressable stores (write to pointers to types < 32 bits)*"
3D Image writes"
Built-in functions to support half types"
* New core features in OpenCL 1.1
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
47. OpenCL C: Data Types
â˘âŻ Scalar data types"
â˘âŻ char, uchar, short, ushort, int, uint, long, ulong, ďŹoat"
â˘âŻ bool, intptr_t, ptrdiff_t, size_t, uintptr_t, void, half (storage)"
â˘âŻ Image types"
â˘âŻ Image2d_t, image3d_t, sampler_t, event_t"
â˘âŻ Vector data types"
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
â˘âŻ
Vector lengths 2, 3*, 4, 8, 16 (char2, ushort4, int8, ďŹoat16, double2^, âŚ)"
Endian safe"
Aligned at vector length"
Vector operations"
Built-in function "
* New core features in OpenCL 1.1
^ Double is optional type in OpenCL
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
48. OpenCL C: Synchronisation Primitives
â˘âŻ Built-in functions to order memory operations and synchronise execution:"
â˘âŻ mem_fence(CLK_LOCAL_MEM_FENCE and/or CLK_GLOBAL_MEM_FENCE)"
â˘âŻ Waits until all reads/writes to local and/or global memory made by calling work-item prior to
mem_fence() are visible to all threads in the work-group"
â˘âŻ barrier(CLK_LOCAL_MEM_FENCE and/or CLK_GLOBAL_MEM_FENCE)"
â˘âŻ Waits until all work-items in the work-group have reached this point and calls mem_fence
(CLK_LOCAL_MEM_FENCE and/or CLK_GLOBAL_MEM_FENCE)"
â˘âŻ Used to coordinate accesses to local or global memory shared among workitems "
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
50. Kernel Compilation
â˘âŻ We use cl_program object that encapsulates some source code and its last
successful build (it may contain several kernel functions): "
â˘âŻ clCreateProgramWithSource() Ă ď creates a program object for a context, and loads
the source code speciďŹed by the strings array into the program object"
â˘âŻ clCreateProgramWithBinary() Ă ď create program objects and loads the binary there"
â˘âŻ clBuildProgram() Ă ď compiles and links a program executable from program source
or binary"
â˘âŻ WeĘźll use also cl_kernel object which encapsulates the values of the kernelĘźs
arguments used when the kernel is executed: "
â˘âŻ clCreateKernel() Ă ď creates a kernel object from successfully compiled program "
â˘âŻ clSetKernelArg() Ă ď sets the argument value for a speciďŹc argument of a kernel"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
52. Memory Objects
â˘âŻ Memory objects (cl_mem) are categorized into two types:"
â˘âŻ Buffer objects"
â˘âŻ Image objects!
â˘âŻ Memory objects can be copied to host memory, from host memory, or to other
memory objects"
â˘âŻ Kernels take memory objects as input, and output to one or more memory
objects"
â˘âŻ Regions of a memory object can be accessed by host by mapping them into
the host address space"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
53. Memory Objects: Buffer Object
â˘âŻ A buffer object stored a one-dimensional collection of elements (1D array)"
â˘âŻ Elements of a buffer object can be:"
â˘âŻ Scalar data type (such as an int, ďŹoat)"
â˘âŻ Vector data type"
â˘âŻ User-deďŹned structure"
â˘âŻ Elements in a buffer are stored in sequential fashion and can be accessed
using pointer by a kernel executing on a device"
â˘âŻ Data is stored in the same format as it is accessed by the kernel"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
54. Memory Objects: Image Object
â˘âŻ Image object stores a two- or three-dimensional texture, frame-buffer or
image"
â˘âŻ Can be created from existing OpenGL texture or render-buffer"
â˘âŻ The elements of an image object are selected from a list of predeďŹned image
formats"
â˘âŻ Image elements are always a 4-component vector (each component can be a
ďŹoat or signed/unsigned integer) in a kernel"
â˘âŻ Accessed within device via built-in functions (storage format not exposed to
application)"
â˘âŻ Sampler objects are used to conďŹgure how built-in functions sample images
(addressing modes, ďŹltering modes)"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
55. Command Queue
â˘âŻ Memory, program and kernel objects Ă ď created using a context"
â˘âŻ Operations on objects performed using a command-queue"
â˘âŻ The command-queue used to schedule commands for execution on a device"
â˘âŻ En-queuing functions: clEnqueue*()"
â˘âŻ Multiple queues can execute on the same device"
â˘âŻ Modes of execution:"
â˘âŻ In-order: Each command in the queue executes only when the proceeding
command has completed (including memory writes) "
â˘âŻ Out-of-order: No guaranteed order of completion for commands"
â˘âŻ CL_QUEUE_PROFILING ENABLE: enable or disable proďŹling commands in the
command-queue"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
56. Command Queue
â˘âŻ Create command queue for a speciďŹc device"
cl_command_queue queue = clCreateCommandQueue(context, device, 0, NULL); "
cl_command_queue clCreateCommandQueue(!
cl_context context,"
cl_device_id device,"
cl_command_queue_properties properties,"
cl_int *errcode_ret)"
â˘âŻ Properties"
â˘âŻ CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE determines if command-queue are
executed in-order or out-of-order. If set, the commands are executed out-of-order."
â˘âŻ CL_QUEUE_PROFILING_ENABLE enables or disables proďŹling of commands in the
command-queue. If set, the proďŹling of commands is enabled. "
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
57. Data Transfer between Host and Device
â˘âŻ Create buffers on host and device
"
size_t size = 100000*sizeof(int);"
int *host_buffer = (int*)malloc(size); "
cl_mem devSrcA =
clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, NULL); "
cl_mem devSrcB =
clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, NULL);
âŚ"
â˘âŻ Write to buffer objects from host memory
"
clEnqueueWriteBuffer(queue, devSrcA, "
CL_FALSE, 0, size, host_buffer, 0, NULL, NULL); "
âŚ"
â˘âŻ Read from buffer object to host memory
"
clEnqueueReadBuffer(queue, devDst, "
CL_TRUE, 0, size, host_buffer, 0, NULL, NULL); "
âŚ"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
cl_mem clCreateBuffer(!
cl_context context,"
cl_mem_ďŹags ďŹags,"
size_t size,"
void *host_ptr,"
cl_int *errcode_ret)"
CL_MEM_READ_WRITE,!
CL_MEM_WRITE_ONLY,!
CL_MEM_READ_ONLY,!
âŚ"
cl_int clEnqueueWriteBuffer(!
cl_command_queue queue,"
cl_mem buffer,"
cl_bool blocking_write,"
size_t offset,"
size_t size,"
const void *ptr,"
cl_uint num_events_in_wait_list,!
const cl_event *event_wait_list,"
cl_event *event)"
58. Kernel Invocation over NDRange
â˘âŻ Host code invokes a kernel over an index space NDRange (1D, 2D or 3D)!
â˘âŻ Work-group dimensionality matches work-item dimensionality"
â˘âŻ Set number of work-items in a work-group"
size_t localWorkSize = 256;"
int numWorkGroups = (N+localWorkSize-1)/localWorkSize; // round up"
size_t globalWorkSize = numWorkGroups * localWorkSize; // must be divisible by localWorkSize
â˘âŻ Enqueue kernel"
clEnqueueNDRangeKernel("
queue, kernel 1, NULL, &globalWorkSize, &localWorkSize, 0, NULL, NULL); "
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
cl_int clEnqueueNDRangeKernel(!
cl_command_queue queue,"
cl_kernel kernel,"
Cl_uint work_dim,"
cont size_t *global_work_offset,"
cont size_t *global_work_size,"
cont size_t *local_work_offset,"
cl_uint num_events_in_wait_list,!
const cl_event *event_wait_list,"
cl_event *event)"
59. Command Synchronisation
â˘âŻ Queue barrier command: clEnqueueBarrier()"
â˘âŻ Commands after the barrier start executing only after all commands before the
barrier have completed"
â˘âŻ Events: a cl_event object can be associated with each command"
â˘âŻ Commands return evens and obey event waitlist"
â˘âŻ clEnqueue*(âŚ, num_events_in_waitlist, *event_waitlist, *event);"
â˘âŻ Any commands (or clWaitForEvents()) can wait on events before executing"
â˘âŻ Event object can be queried to track execution status of associated command and
get proďŹling information"
â˘âŻ Some clEnqueue*() calls can be optionally blocking"
â˘âŻ clEnqueueReadBuffer(âŚ, CL_TRUE, âŚ);"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
60. Synchronisation: Queues & Events
â˘âŻ You must explicitly synchronise between queues"
â˘âŻ Multiple devices each have their own queue (possibly multiple queues per device)"
â˘âŻ Use events to synchronise kernel executions between queues"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
61. OpenCL Resources
â˘âŻ OpenCL at Khronos"
â˘âŻ http://www.khronos.org/opencl (spec, registry, man, forums, reference card)"
â˘âŻ NVIDIA OpenCL website, forum"
â˘âŻ http://www.nvidia.com/object/cuda_opencl_new.html"
â˘âŻ http://developer.nvidia.com/object/opencl.html (drivers, proďŹler, code samples)"
â˘âŻ AMD Developer Central"
â˘âŻ http://developer.amd.com/gpu/atistreamsdk/pages/default.aspx"
â˘âŻ Intel OpenCL SDK"
â˘âŻ http://software.intel.com/en-us/articles/intel-opencl-sdk/"
â˘âŻ IBM OpenCL Development Kid for Linux on Power"
â˘âŻ http://www.alphaworks.ibm.com/tech/opencl"
â˘âŻ OpenCL Studio"
â˘âŻ http://www.opencldev.com (develop, visualize, prototype UIs)"
CSIRO. Introduction to OpenCL. OpenCL Workshop at the OzViz 2010, Brisbane, December 2010.
62. Earth Science and Resource Engineering
Tomasz P Bednarz
3D Visualisation Engineer
Mining Technology Team
Mobile: +61 429 153 274
Email: tomasz.bednarz(_at_)csiro.au
Web: www.tomaszbednarz.com
Acknowledgments
Mark Harris, Derek Gerstmann, Mike Houston, Justin Hensley, Jason Young, Dominik Behr, Con Caris,
John Taylor, Khronos Group, AMD, NVIDIA and all others for sharing publicly their GPGPU knowledge
(this presentation is based on)
Thank you âŚ
Contact us
Phone: 1300 363 400 or +61 3 9545 2176
Email: enquiries@csiro.au Web: www.csiro.au