basic-examples.texi 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. @c -*-texinfo-*-
  2. @c This file is part of the StarPU Handbook.
  3. @c Copyright (C) 2009--2011 Universit@'e de Bordeaux 1
  4. @c Copyright (C) 2010, 2011, 2012, 2013 Centre National de la Recherche Scientifique
  5. @c Copyright (C) 2011, 2012 Institut National de Recherche en Informatique et Automatique
  6. @c See the file starpu.texi for copying conditions.
  7. @menu
  8. * Hello World using the C Extension::
  9. * Hello World using StarPU's API::
  10. * Vector Scaling Using the C Extension::
  11. * Vector Scaling Using StarPU's API::
  12. * Vector Scaling on an Hybrid CPU/GPU Machine:: Handling Heterogeneous Architectures
  13. @end menu
  14. @node Hello World using the C Extension
  15. @section Hello World using the C Extension
  16. This section shows how to implement a simple program that submits a task
  17. to StarPU using the StarPU C extension (@pxref{C Extensions}). A
  18. similar example showing how to directly use the StarPU's API is shown
  19. in @ref{Hello World using StarPU's API}.
  20. GCC from version 4.5 permit to use the StarPU GCC plug-in (@pxref{C
  21. Extensions}). This makes writing a task both simpler and less error-prone.
  22. In a nutshell, all it takes is to declare a task, declare and define its
  23. implementations (for CPU, OpenCL, and/or CUDA), and invoke the task like
  24. a regular C function. The example below defines @code{my_task}, which
  25. has a single implementation for CPU:
  26. @cartouche
  27. @smallexample
  28. #include <stdio.h>
  29. /* @b{Task declaration.} */
  30. static void my_task (int x) __attribute__ ((task));
  31. /* @b{Definition of the CPU implementation of `my_task'.} */
  32. static void my_task (int x)
  33. @{
  34. printf ("Hello, world! With x = %d\n", x);
  35. @}
  36. int main ()
  37. @{
  38. /* @b{Initialize StarPU.} */
  39. #pragma starpu initialize
  40. /* @b{Do an asynchronous call to `my_task'.} */
  41. my_task (42);
  42. /* @b{Wait for the call to complete.} */
  43. #pragma starpu wait
  44. /* @b{Terminate.} */
  45. #pragma starpu shutdown
  46. return 0;
  47. @}
  48. @end smallexample
  49. @end cartouche
  50. @noindent
  51. The code can then be compiled and linked with GCC and the
  52. @code{-fplugin} flag:
  53. @example
  54. $ gcc `pkg-config starpu-1.0 --cflags` hello-starpu.c \
  55. -fplugin=`pkg-config starpu-1.0 --variable=gccplugin` \
  56. `pkg-config starpu-1.0 --libs`
  57. @end example
  58. The code can also be compiled without the StarPU C extension and will
  59. behave as a normal sequential code.
  60. @example
  61. $ gcc hello-starpu.c
  62. hello-starpu.c:33:1: warning: ‘task’ attribute directive ignored [-Wattributes]
  63. $ ./a.out
  64. Hello, world! With x = 42
  65. @end example
  66. As can be seen above, the C extensions allows programmers to
  67. use StarPU tasks by essentially annotating ``regular'' C code.
  68. @node Hello World using StarPU's API
  69. @section Hello World using StarPU's API
  70. This section shows how to achieve the same result as in the previous
  71. section using StarPU's standard C API.
  72. @menu
  73. * Required Headers::
  74. * Defining a Codelet::
  75. * Submitting a Task::
  76. * Execution of Hello World::
  77. @end menu
  78. @node Required Headers
  79. @subsection Required Headers
  80. The @code{starpu.h} header should be included in any code using StarPU.
  81. @cartouche
  82. @smallexample
  83. #include <starpu.h>
  84. @end smallexample
  85. @end cartouche
  86. @node Defining a Codelet
  87. @subsection Defining a Codelet
  88. @cartouche
  89. @smallexample
  90. struct params
  91. @{
  92. int i;
  93. float f;
  94. @};
  95. void cpu_func(void *buffers[], void *cl_arg)
  96. @{
  97. struct params *params = cl_arg;
  98. printf("Hello world (params = @{%i, %f@} )\n", params->i, params->f);
  99. @}
  100. struct starpu_codelet cl =
  101. @{
  102. .where = STARPU_CPU,
  103. .cpu_funcs = @{ cpu_func, NULL @},
  104. .nbuffers = 0
  105. @};
  106. @end smallexample
  107. @end cartouche
  108. A codelet is a structure that represents a computational kernel. Such a codelet
  109. may contain an implementation of the same kernel on different architectures
  110. (e.g. CUDA, x86, ...). For compatibility, make sure that the whole
  111. structure is initialized to zero, either by using memset, or by letting the
  112. compiler implicitly do it as examplified above.
  113. The @code{nbuffers} field specifies the number of data buffers that are
  114. manipulated by the codelet: here the codelet does not access or modify any data
  115. that is controlled by our data management library. Note that the argument
  116. passed to the codelet (the @code{cl_arg} field of the @code{starpu_task}
  117. structure) does not count as a buffer since it is not managed by our data
  118. management library, but just contain trivial parameters.
  119. @c TODO need a crossref to the proper description of "where" see bla for more ...
  120. We create a codelet which may only be executed on the CPUs. The @code{where}
  121. field is a bitmask that defines where the codelet may be executed. Here, the
  122. @code{STARPU_CPU} value means that only CPUs can execute this codelet
  123. (@pxref{Codelets and Tasks} for more details on this field). Note that
  124. the @code{where} field is optional, when unset its value is
  125. automatically set based on the availability of the different
  126. @code{XXX_funcs} fields.
  127. When a CPU core executes a codelet, it calls the @code{cpu_func} function,
  128. which @emph{must} have the following prototype:
  129. @code{void (*cpu_func)(void *buffers[], void *cl_arg);}
  130. In this example, we can ignore the first argument of this function which gives a
  131. description of the input and output buffers (e.g. the size and the location of
  132. the matrices) since there is none.
  133. The second argument is a pointer to a buffer passed as an
  134. argument to the codelet by the means of the @code{cl_arg} field of the
  135. @code{starpu_task} structure.
  136. @c TODO rewrite so that it is a little clearer ?
  137. Be aware that this may be a pointer to a
  138. @emph{copy} of the actual buffer, and not the pointer given by the programmer:
  139. if the codelet modifies this buffer, there is no guarantee that the initial
  140. buffer will be modified as well: this for instance implies that the buffer
  141. cannot be used as a synchronization medium. If synchronization is needed, data
  142. has to be registered to StarPU, see @ref{Vector Scaling Using StarPU's API}.
  143. @node Submitting a Task
  144. @subsection Submitting a Task
  145. @cartouche
  146. @smallexample
  147. void callback_func(void *callback_arg)
  148. @{
  149. printf("Callback function (arg %x)\n", callback_arg);
  150. @}
  151. int main(int argc, char **argv)
  152. @{
  153. /* @b{initialize StarPU} */
  154. starpu_init(NULL);
  155. struct starpu_task *task = starpu_task_create();
  156. task->cl = &cl; /* @b{Pointer to the codelet defined above} */
  157. struct params params = @{ 1, 2.0f @};
  158. task->cl_arg = &params;
  159. task->cl_arg_size = sizeof(params);
  160. task->callback_func = callback_func;
  161. task->callback_arg = 0x42;
  162. /* @b{starpu_task_submit will be a blocking call} */
  163. task->synchronous = 1;
  164. /* @b{submit the task to StarPU} */
  165. starpu_task_submit(task);
  166. /* @b{terminate StarPU} */
  167. starpu_shutdown();
  168. return 0;
  169. @}
  170. @end smallexample
  171. @end cartouche
  172. Before submitting any tasks to StarPU, @code{starpu_init} must be called. The
  173. @code{NULL} argument specifies that we use default configuration. Tasks cannot
  174. be submitted after the termination of StarPU by a call to
  175. @code{starpu_shutdown}.
  176. In the example above, a task structure is allocated by a call to
  177. @code{starpu_task_create}. This function only allocates and fills the
  178. corresponding structure with the default settings (@pxref{Codelets and
  179. Tasks, starpu_task_create}), but it does not submit the task to StarPU.
  180. @c not really clear ;)
  181. The @code{cl} field is a pointer to the codelet which the task will
  182. execute: in other words, the codelet structure describes which computational
  183. kernel should be offloaded on the different architectures, and the task
  184. structure is a wrapper containing a codelet and the piece of data on which the
  185. codelet should operate.
  186. The optional @code{cl_arg} field is a pointer to a buffer (of size
  187. @code{cl_arg_size}) with some parameters for the kernel
  188. described by the codelet. For instance, if a codelet implements a computational
  189. kernel that multiplies its input vector by a constant, the constant could be
  190. specified by the means of this buffer, instead of registering it as a StarPU
  191. data. It must however be noted that StarPU avoids making copy whenever possible
  192. and rather passes the pointer as such, so the buffer which is pointed at must
  193. kept allocated until the task terminates, and if several tasks are submitted
  194. with various parameters, each of them must be given a pointer to their own
  195. buffer.
  196. Once a task has been executed, an optional callback function is be called.
  197. While the computational kernel could be offloaded on various architectures, the
  198. callback function is always executed on a CPU. The @code{callback_arg}
  199. pointer is passed as an argument of the callback. The prototype of a callback
  200. function must be:
  201. @cartouche
  202. @example
  203. void (*callback_function)(void *);
  204. @end example
  205. @end cartouche
  206. If the @code{synchronous} field is non-zero, task submission will be
  207. synchronous: the @code{starpu_task_submit} function will not return until the
  208. task was executed. Note that the @code{starpu_shutdown} method does not
  209. guarantee that asynchronous tasks have been executed before it returns,
  210. @code{starpu_task_wait_for_all} can be used to that effect, or data can be
  211. unregistered (@code{starpu_data_unregister(vector_handle);}), which will
  212. implicitly wait for all the tasks scheduled to work on it, unless explicitly
  213. disabled thanks to @code{starpu_data_set_default_sequential_consistency_flag} or
  214. @code{starpu_data_set_sequential_consistency_flag}.
  215. @node Execution of Hello World
  216. @subsection Execution of Hello World
  217. @smallexample
  218. $ make hello_world
  219. cc $(pkg-config --cflags starpu-1.0) $(pkg-config --libs starpu-1.0) hello_world.c -o hello_world
  220. $ ./hello_world
  221. Hello world (params = @{1, 2.000000@} )
  222. Callback function (arg 42)
  223. @end smallexample
  224. @node Vector Scaling Using the C Extension
  225. @section Vector Scaling Using the C Extension
  226. The previous example has shown how to submit tasks. In this section,
  227. we show how StarPU tasks can manipulate data. The version of this
  228. example using StarPU's API is given in the next sections.
  229. @menu
  230. * Adding an OpenCL Task Implementation::
  231. * Adding a CUDA Task Implementation::
  232. @end menu
  233. The simplest way to get started writing StarPU programs is using the C
  234. language extensions provided by the GCC plug-in (@pxref{C Extensions}).
  235. These extensions map directly to StarPU's main concepts: tasks, task
  236. implementations for CPU, OpenCL, or CUDA, and registered data buffers.
  237. The example below is a vector-scaling program, that multiplies elements
  238. of a vector by a given factor@footnote{The complete example, and
  239. additional examples, is available in the @file{gcc-plugin/examples}
  240. directory of the StarPU distribution.}. For comparison, the standard C
  241. version that uses StarPU's standard C programming interface is given in
  242. the next section (@pxref{Vector Scaling Using StarPU's API, standard C
  243. version of the example}).
  244. First of all, the vector-scaling task and its simple CPU implementation
  245. has to be defined:
  246. @cartouche
  247. @smallexample
  248. /* @b{Declare the `vector_scal' task.} */
  249. static void vector_scal (unsigned size, float vector[size],
  250. float factor)
  251. __attribute__ ((task));
  252. /* @b{Define the standard CPU implementation.} */
  253. static void
  254. vector_scal (unsigned size, float vector[size], float factor)
  255. @{
  256. unsigned i;
  257. for (i = 0; i < size; i++)
  258. vector[i] *= factor;
  259. @}
  260. @end smallexample
  261. @end cartouche
  262. Next, the body of the program, which uses the task defined above, can be
  263. implemented:
  264. @cartouche
  265. @smallexample
  266. int
  267. main (void)
  268. @{
  269. #pragma starpu initialize
  270. #define NX 0x100000
  271. #define FACTOR 3.14
  272. @{
  273. float vector[NX]
  274. __attribute__ ((heap_allocated, registered));
  275. size_t i;
  276. for (i = 0; i < NX; i++)
  277. vector[i] = (float) i;
  278. vector_scal (NX, vector, FACTOR);
  279. #pragma starpu wait
  280. @} /* @b{VECTOR is automatically freed here.} */
  281. #pragma starpu shutdown
  282. return valid ? EXIT_SUCCESS : EXIT_FAILURE;
  283. @}
  284. @end smallexample
  285. @end cartouche
  286. @noindent
  287. The @code{main} function above does several things:
  288. @itemize
  289. @item
  290. It initializes StarPU.
  291. @item
  292. It allocates @var{vector} in the heap; it will automatically be freed
  293. when its scope is left. Alternatively, good old @code{malloc} and
  294. @code{free} could have been used, but they are more error-prone and
  295. require more typing.
  296. @item
  297. It @dfn{registers} the memory pointed to by @var{vector}. Eventually,
  298. when OpenCL or CUDA task implementations are added, this will allow
  299. StarPU to transfer that memory region between GPUs and the main memory.
  300. Removing this @code{pragma} is an error.
  301. @item
  302. It invokes the @code{vector_scal} task. The invocation looks the same
  303. as a standard C function call. However, it is an @dfn{asynchronous
  304. invocation}, meaning that the actual call is performed in parallel with
  305. the caller's continuation.
  306. @item
  307. It @dfn{waits} for the termination of the @code{vector_scal}
  308. asynchronous call.
  309. @item
  310. Finally, StarPU is shut down.
  311. @end itemize
  312. The program can be compiled and linked with GCC and the @code{-fplugin}
  313. flag:
  314. @example
  315. $ gcc hello-starpu.c \
  316. -fplugin=`pkg-config starpu-1.0 --variable=gccplugin` \
  317. `pkg-config starpu-1.0 --libs`
  318. @end example
  319. And voil@`a!
  320. @node Adding an OpenCL Task Implementation
  321. @subsection Adding an OpenCL Task Implementation
  322. Now, this is all fine and great, but you certainly want to take
  323. advantage of these newfangled GPUs that your lab just bought, don't you?
  324. So, let's add an OpenCL implementation of the @code{vector_scal} task.
  325. We assume that the OpenCL kernel is available in a file,
  326. @file{vector_scal_opencl_kernel.cl}, not shown here. The OpenCL task
  327. implementation is similar to that used with the standard C API
  328. (@pxref{Definition of the OpenCL Kernel}). It is declared and defined
  329. in our C file like this:
  330. @cartouche
  331. @smallexample
  332. /* @b{The OpenCL programs, loaded from 'main' (see below).} */
  333. static struct starpu_opencl_program cl_programs;
  334. static void vector_scal_opencl (unsigned size, float vector[size],
  335. float factor)
  336. __attribute__ ((task_implementation ("opencl", vector_scal)));
  337. static void
  338. vector_scal_opencl (unsigned size, float vector[size], float factor)
  339. @{
  340. int id, devid, err;
  341. cl_kernel kernel;
  342. cl_command_queue queue;
  343. cl_event event;
  344. /* @b{VECTOR is GPU memory pointer, not a main memory pointer.} */
  345. cl_mem val = (cl_mem) vector;
  346. id = starpu_worker_get_id ();
  347. devid = starpu_worker_get_devid (id);
  348. /* @b{Prepare to invoke the kernel. In the future, this will be largely
  349. automated.} */
  350. err = starpu_opencl_load_kernel (&kernel, &queue, &cl_programs,
  351. "vector_mult_opencl", devid);
  352. if (err != CL_SUCCESS)
  353. STARPU_OPENCL_REPORT_ERROR (err);
  354. err = clSetKernelArg (kernel, 0, sizeof (val), &val);
  355. err |= clSetKernelArg (kernel, 1, sizeof (size), &size);
  356. err |= clSetKernelArg (kernel, 2, sizeof (factor), &factor);
  357. if (err)
  358. STARPU_OPENCL_REPORT_ERROR (err);
  359. size_t global = 1, local = 1;
  360. err = clEnqueueNDRangeKernel (queue, kernel, 1, NULL, &global,
  361. &local, 0, NULL, &event);
  362. if (err != CL_SUCCESS)
  363. STARPU_OPENCL_REPORT_ERROR (err);
  364. clFinish (queue);
  365. starpu_opencl_collect_stats (event);
  366. clReleaseEvent (event);
  367. /* @b{Done with KERNEL.} */
  368. starpu_opencl_release_kernel (kernel);
  369. @}
  370. @end smallexample
  371. @end cartouche
  372. @noindent
  373. The OpenCL kernel itself must be loaded from @code{main}, sometime after
  374. the @code{initialize} pragma:
  375. @cartouche
  376. @smallexample
  377. starpu_opencl_load_opencl_from_file ("vector_scal_opencl_kernel.cl",
  378. &cl_programs, "");
  379. @end smallexample
  380. @end cartouche
  381. @noindent
  382. And that's it. The @code{vector_scal} task now has an additional
  383. implementation, for OpenCL, which StarPU's scheduler may choose to use
  384. at run-time. Unfortunately, the @code{vector_scal_opencl} above still
  385. has to go through the common OpenCL boilerplate; in the future,
  386. additional extensions will automate most of it.
  387. @node Adding a CUDA Task Implementation
  388. @subsection Adding a CUDA Task Implementation
  389. Adding a CUDA implementation of the task is very similar, except that
  390. the implementation itself is typically written in CUDA, and compiled
  391. with @code{nvcc}. Thus, the C file only needs to contain an external
  392. declaration for the task implementation:
  393. @cartouche
  394. @smallexample
  395. extern void vector_scal_cuda (unsigned size, float vector[size],
  396. float factor)
  397. __attribute__ ((task_implementation ("cuda", vector_scal)));
  398. @end smallexample
  399. @end cartouche
  400. The actual implementation of the CUDA task goes into a separate
  401. compilation unit, in a @file{.cu} file. It is very close to the
  402. implementation when using StarPU's standard C API (@pxref{Definition of
  403. the CUDA Kernel}).
  404. @cartouche
  405. @smallexample
  406. /* @b{CUDA implementation of the `vector_scal' task, to be compiled
  407. with `nvcc'.} */
  408. #include <starpu.h>
  409. #include <stdlib.h>
  410. static __global__ void
  411. vector_mult_cuda (float *val, unsigned n, float factor)
  412. @{
  413. unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
  414. if (i < n)
  415. val[i] *= factor;
  416. @}
  417. /* @b{Definition of the task implementation declared in the C file.} */
  418. extern "C" void
  419. vector_scal_cuda (size_t size, float vector[], float factor)
  420. @{
  421. unsigned threads_per_block = 64;
  422. unsigned nblocks = (size + threads_per_block - 1) / threads_per_block;
  423. vector_mult_cuda <<< nblocks, threads_per_block, 0,
  424. starpu_cuda_get_local_stream () >>> (vector, size, factor);
  425. cudaStreamSynchronize (starpu_cuda_get_local_stream ());
  426. @}
  427. @end smallexample
  428. @end cartouche
  429. The complete source code, in the @file{gcc-plugin/examples/vector_scal}
  430. directory of the StarPU distribution, also shows how an SSE-specialized
  431. CPU task implementation can be added.
  432. For more details on the C extensions provided by StarPU's GCC plug-in,
  433. @xref{C Extensions}.
  434. @node Vector Scaling Using StarPU's API
  435. @section Vector Scaling Using StarPU's API
  436. This section shows how to achieve the same result as explained in the
  437. previous section using StarPU's standard C API.
  438. The full source code for
  439. this example is given in @ref{Full source code for the 'Scaling a
  440. Vector' example}.
  441. @menu
  442. * Source Code of Vector Scaling::
  443. * Execution of Vector Scaling:: Running the program
  444. @end menu
  445. @node Source Code of Vector Scaling
  446. @subsection Source Code of Vector Scaling
  447. Programmers can describe the data layout of their application so that StarPU is
  448. responsible for enforcing data coherency and availability across the machine.
  449. Instead of handling complex (and non-portable) mechanisms to perform data
  450. movements, programmers only declare which piece of data is accessed and/or
  451. modified by a task, and StarPU makes sure that when a computational kernel
  452. starts somewhere (e.g. on a GPU), its data are available locally.
  453. Before submitting those tasks, the programmer first needs to declare the
  454. different pieces of data to StarPU using the @code{starpu_*_data_register}
  455. functions. To ease the development of applications for StarPU, it is possible
  456. to describe multiple types of data layout. A type of data layout is called an
  457. @b{interface}. There are different predefined interfaces available in StarPU:
  458. here we will consider the @b{vector interface}.
  459. The following lines show how to declare an array of @code{NX} elements of type
  460. @code{float} using the vector interface:
  461. @cartouche
  462. @smallexample
  463. float vector[NX];
  464. starpu_data_handle_t vector_handle;
  465. starpu_vector_data_register(&vector_handle, 0, (uintptr_t)vector, NX,
  466. sizeof(vector[0]));
  467. @end smallexample
  468. @end cartouche
  469. The first argument, called the @b{data handle}, is an opaque pointer which
  470. designates the array in StarPU. This is also the structure which is used to
  471. describe which data is used by a task. The second argument is the node number
  472. where the data originally resides. Here it is 0 since the @code{vector} array is in
  473. the main memory. Then comes the pointer @code{vector} where the data can be found in main memory,
  474. the number of elements in the vector and the size of each element.
  475. The following shows how to construct a StarPU task that will manipulate the
  476. vector and a constant factor.
  477. @cartouche
  478. @smallexample
  479. float factor = 3.14;
  480. struct starpu_task *task = starpu_task_create();
  481. task->cl = &cl; /* @b{Pointer to the codelet defined below} */
  482. task->handles[0] = vector_handle; /* @b{First parameter of the codelet} */
  483. task->cl_arg = &factor;
  484. task->cl_arg_size = sizeof(factor);
  485. task->synchronous = 1;
  486. starpu_task_submit(task);
  487. @end smallexample
  488. @end cartouche
  489. Since the factor is a mere constant float value parameter,
  490. it does not need a preliminary registration, and
  491. can just be passed through the @code{cl_arg} pointer like in the previous
  492. example. The vector parameter is described by its handle.
  493. There are two fields in each element of the @code{buffers} array.
  494. @code{handle} is the handle of the data, and @code{mode} specifies how the
  495. kernel will access the data (@code{STARPU_R} for read-only, @code{STARPU_W} for
  496. write-only and @code{STARPU_RW} for read and write access).
  497. The definition of the codelet can be written as follows:
  498. @cartouche
  499. @smallexample
  500. void scal_cpu_func(void *buffers[], void *cl_arg)
  501. @{
  502. unsigned i;
  503. float *factor = cl_arg;
  504. /* @b{length of the vector} */
  505. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  506. /* @b{CPU copy of the vector pointer} */
  507. float *val = (float *)STARPU_VECTOR_GET_PTR(buffers[0]);
  508. for (i = 0; i < n; i++)
  509. val[i] *= *factor;
  510. @}
  511. struct starpu_codelet cl = @{
  512. .where = STARPU_CPU,
  513. .cpu_funcs = @{ scal_cpu_func, NULL @},
  514. .nbuffers = 1,
  515. .modes = @{ STARPU_RW @}
  516. @};
  517. @end smallexample
  518. @end cartouche
  519. The first argument is an array that gives
  520. a description of all the buffers passed in the @code{task->handles}@ array. The
  521. size of this array is given by the @code{nbuffers} field of the codelet
  522. structure. For the sake of genericity, this array contains pointers to the
  523. different interfaces describing each buffer. In the case of the @b{vector
  524. interface}, the location of the vector (resp. its length) is accessible in the
  525. @code{ptr} (resp. @code{nx}) of this array. Since the vector is accessed in a
  526. read-write fashion, any modification will automatically affect future accesses
  527. to this vector made by other tasks.
  528. The second argument of the @code{scal_cpu_func} function contains a pointer to the
  529. parameters of the codelet (given in @code{task->cl_arg}), so that we read the
  530. constant factor from this pointer.
  531. @node Execution of Vector Scaling
  532. @subsection Execution of Vector Scaling
  533. @smallexample
  534. $ make vector_scal
  535. cc $(pkg-config --cflags starpu-1.0) $(pkg-config --libs starpu-1.0) vector_scal.c -o vector_scal
  536. $ ./vector_scal
  537. 0.000000 3.000000 6.000000 9.000000 12.000000
  538. @end smallexample
  539. @node Vector Scaling on an Hybrid CPU/GPU Machine
  540. @section Vector Scaling on an Hybrid CPU/GPU Machine
  541. Contrary to the previous examples, the task submitted in this example may not
  542. only be executed by the CPUs, but also by a CUDA device.
  543. @menu
  544. * Definition of the CUDA Kernel::
  545. * Definition of the OpenCL Kernel::
  546. * Definition of the Main Code::
  547. * Execution of Hybrid Vector Scaling::
  548. @end menu
  549. @node Definition of the CUDA Kernel
  550. @subsection Definition of the CUDA Kernel
  551. The CUDA implementation can be written as follows. It needs to be compiled with
  552. a CUDA compiler such as nvcc, the NVIDIA CUDA compiler driver. It must be noted
  553. that the vector pointer returned by STARPU_VECTOR_GET_PTR is here a pointer in GPU
  554. memory, so that it can be passed as such to the @code{vector_mult_cuda} kernel
  555. call.
  556. @cartouche
  557. @smallexample
  558. #include <starpu.h>
  559. static __global__ void vector_mult_cuda(float *val, unsigned n,
  560. float factor)
  561. @{
  562. unsigned i = blockIdx.x*blockDim.x + threadIdx.x;
  563. if (i < n)
  564. val[i] *= factor;
  565. @}
  566. extern "C" void scal_cuda_func(void *buffers[], void *_args)
  567. @{
  568. float *factor = (float *)_args;
  569. /* @b{length of the vector} */
  570. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  571. /* @b{CUDA copy of the vector pointer} */
  572. float *val = (float *)STARPU_VECTOR_GET_PTR(buffers[0]);
  573. unsigned threads_per_block = 64;
  574. unsigned nblocks = (n + threads_per_block-1) / threads_per_block;
  575. @i{ vector_mult_cuda<<<nblocks,threads_per_block, 0, starpu_cuda_get_local_stream()>>>}
  576. @i{ (val, n, *factor);}
  577. @i{ cudaStreamSynchronize(starpu_cuda_get_local_stream());}
  578. @}
  579. @end smallexample
  580. @end cartouche
  581. @node Definition of the OpenCL Kernel
  582. @subsection Definition of the OpenCL Kernel
  583. The OpenCL implementation can be written as follows. StarPU provides
  584. tools to compile a OpenCL kernel stored in a file.
  585. @cartouche
  586. @smallexample
  587. __kernel void vector_mult_opencl(__global float* val, int nx, float factor)
  588. @{
  589. const int i = get_global_id(0);
  590. if (i < nx) @{
  591. val[i] *= factor;
  592. @}
  593. @}
  594. @end smallexample
  595. @end cartouche
  596. Contrary to CUDA and CPU, @code{STARPU_VECTOR_GET_DEV_HANDLE} has to be used,
  597. which returns a @code{cl_mem} (which is not a device pointer, but an OpenCL
  598. handle), which can be passed as such to the OpenCL kernel. The difference is
  599. important when using partitioning, see @ref{Partitioning Data}.
  600. @cartouche
  601. @smallexample
  602. #include <starpu.h>
  603. @i{extern struct starpu_opencl_program programs;}
  604. void scal_opencl_func(void *buffers[], void *_args)
  605. @{
  606. float *factor = _args;
  607. @i{ int id, devid, err;}
  608. @i{ cl_kernel kernel;}
  609. @i{ cl_command_queue queue;}
  610. @i{ cl_event event;}
  611. /* @b{length of the vector} */
  612. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  613. /* @b{OpenCL copy of the vector pointer} */
  614. cl_mem val = (cl_mem) STARPU_VECTOR_GET_DEV_HANDLE(buffers[0]);
  615. @i{ id = starpu_worker_get_id();}
  616. @i{ devid = starpu_worker_get_devid(id);}
  617. @i{ err = starpu_opencl_load_kernel(&kernel, &queue, &programs,}
  618. @i{ "vector_mult_opencl", devid); /* @b{Name of the codelet defined above} */}
  619. @i{ if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err);}
  620. @i{ err = clSetKernelArg(kernel, 0, sizeof(val), &val);}
  621. @i{ err |= clSetKernelArg(kernel, 1, sizeof(n), &n);}
  622. @i{ err |= clSetKernelArg(kernel, 2, sizeof(*factor), factor);}
  623. @i{ if (err) STARPU_OPENCL_REPORT_ERROR(err);}
  624. @i{ @{}
  625. @i{ size_t global=n;}
  626. @i{ size_t local=1;}
  627. @i{ err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL,}
  628. @i{ &global, &local, 0, NULL, &event);}
  629. @i{ if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err);}
  630. @i{ @}}
  631. @i{ clFinish(queue);}
  632. @i{ starpu_opencl_collect_stats(event);}
  633. @i{ clReleaseEvent(event);}
  634. @i{ starpu_opencl_release_kernel(kernel);}
  635. @}
  636. @end smallexample
  637. @end cartouche
  638. @node Definition of the Main Code
  639. @subsection Definition of the Main Code
  640. The CPU implementation is the same as in the previous section.
  641. Here is the source of the main application. You can notice the value of the
  642. field @code{where} for the codelet. We specify
  643. @code{STARPU_CPU|STARPU_CUDA|STARPU_OPENCL} to indicate to StarPU that the codelet
  644. can be executed either on a CPU or on a CUDA or an OpenCL device.
  645. @cartouche
  646. @smallexample
  647. #include <starpu.h>
  648. #define NX 2048
  649. extern void scal_cuda_func(void *buffers[], void *_args);
  650. extern void scal_cpu_func(void *buffers[], void *_args);
  651. extern void scal_opencl_func(void *buffers[], void *_args);
  652. /* @b{Definition of the codelet} */
  653. static struct starpu_codelet cl = @{
  654. .where = STARPU_CPU|STARPU_CUDA|STARPU_OPENCL; /* @b{It can be executed on a CPU,} */
  655. /* @b{on a CUDA device, or on an OpenCL device} */
  656. .cuda_funcs = @{ scal_cuda_func, NULL @},
  657. .cpu_funcs = @{ scal_cpu_func, NULL @},
  658. .opencl_funcs = @{ scal_opencl_func, NULL @},
  659. .nbuffers = 1,
  660. .modes = @{ STARPU_RW @}
  661. @}
  662. #ifdef STARPU_USE_OPENCL
  663. /* @b{The compiled version of the OpenCL program} */
  664. struct starpu_opencl_program programs;
  665. #endif
  666. int main(int argc, char **argv)
  667. @{
  668. float *vector;
  669. int i, ret;
  670. float factor=3.0;
  671. struct starpu_task *task;
  672. starpu_data_handle_t vector_handle;
  673. starpu_init(NULL); /* @b{Initialising StarPU} */
  674. #ifdef STARPU_USE_OPENCL
  675. starpu_opencl_load_opencl_from_file(
  676. "examples/basic_examples/vector_scal_opencl_codelet.cl",
  677. &programs, NULL);
  678. #endif
  679. vector = malloc(NX*sizeof(vector[0]));
  680. assert(vector);
  681. for(i=0 ; i<NX ; i++) vector[i] = i;
  682. @end smallexample
  683. @end cartouche
  684. @cartouche
  685. @smallexample
  686. /* @b{Registering data within StarPU} */
  687. starpu_vector_data_register(&vector_handle, 0, (uintptr_t)vector,
  688. NX, sizeof(vector[0]));
  689. /* @b{Definition of the task} */
  690. task = starpu_task_create();
  691. task->cl = &cl;
  692. task->handles[0] = vector_handle;
  693. task->cl_arg = &factor;
  694. task->cl_arg_size = sizeof(factor);
  695. @end smallexample
  696. @end cartouche
  697. @cartouche
  698. @smallexample
  699. /* @b{Submitting the task} */
  700. ret = starpu_task_submit(task);
  701. if (ret == -ENODEV) @{
  702. fprintf(stderr, "No worker may execute this task\n");
  703. return 1;
  704. @}
  705. @c TODO: Mmm, should rather be an unregistration with an implicit dependency, no?
  706. /* @b{Waiting for its termination} */
  707. starpu_task_wait_for_all();
  708. /* @b{Update the vector in RAM} */
  709. starpu_data_acquire(vector_handle, STARPU_R);
  710. @end smallexample
  711. @end cartouche
  712. @cartouche
  713. @smallexample
  714. /* @b{Access the data} */
  715. for(i=0 ; i<NX; i++) @{
  716. fprintf(stderr, "%f ", vector[i]);
  717. @}
  718. fprintf(stderr, "\n");
  719. /* @b{Release the RAM view of the data before unregistering it and shutting down StarPU} */
  720. starpu_data_release(vector_handle);
  721. starpu_data_unregister(vector_handle);
  722. starpu_shutdown();
  723. return 0;
  724. @}
  725. @end smallexample
  726. @end cartouche
  727. @node Execution of Hybrid Vector Scaling
  728. @subsection Execution of Hybrid Vector Scaling
  729. The Makefile given at the beginning of the section must be extended to
  730. give the rules to compile the CUDA source code. Note that the source
  731. file of the OpenCL kernel does not need to be compiled now, it will
  732. be compiled at run-time when calling the function
  733. @code{starpu_opencl_load_opencl_from_file()} (@pxref{starpu_opencl_load_opencl_from_file}).
  734. @cartouche
  735. @smallexample
  736. CFLAGS += $(shell pkg-config --cflags starpu-1.0)
  737. LDFLAGS += $(shell pkg-config --libs starpu-1.0)
  738. CC = gcc
  739. vector_scal: vector_scal.o vector_scal_cpu.o vector_scal_cuda.o vector_scal_opencl.o
  740. %.o: %.cu
  741. nvcc $(CFLAGS) $< -c $@
  742. clean:
  743. rm -f vector_scal *.o
  744. @end smallexample
  745. @end cartouche
  746. @smallexample
  747. $ make
  748. @end smallexample
  749. and to execute it, with the default configuration:
  750. @smallexample
  751. $ ./vector_scal
  752. 0.000000 3.000000 6.000000 9.000000 12.000000
  753. @end smallexample
  754. or for example, by disabling CPU devices:
  755. @smallexample
  756. $ STARPU_NCPU=0 ./vector_scal
  757. 0.000000 3.000000 6.000000 9.000000 12.000000
  758. @end smallexample
  759. or by disabling CUDA devices (which may permit to enable the use of OpenCL,
  760. see @ref{Enabling OpenCL}):
  761. @smallexample
  762. $ STARPU_NCUDA=0 ./vector_scal
  763. 0.000000 3.000000 6.000000 9.000000 12.000000
  764. @end smallexample