basic-examples.texi 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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
  18. Extensions})@footnote{The complete example, and additional examples,
  19. is available in the @file{gcc-plugin/examples} directory of the StarPU
  20. distribution.}. A similar example showing how to directly use the StarPU's API is shown
  21. in @ref{Hello World using StarPU's API}.
  22. GCC from version 4.5 permit to use the StarPU GCC plug-in (@pxref{C
  23. Extensions}). This makes writing a task both simpler and less error-prone.
  24. In a nutshell, all it takes is to declare a task, declare and define its
  25. implementations (for CPU, OpenCL, and/or CUDA), and invoke the task like
  26. a regular C function. The example below defines @code{my_task}, which
  27. has a single implementation for CPU:
  28. @cartouche
  29. @smallexample
  30. #include <stdio.h>
  31. /* @b{Task declaration.} */
  32. static void my_task (int x) __attribute__ ((task));
  33. /* @b{Definition of the CPU implementation of `my_task'.} */
  34. static void my_task (int x)
  35. @{
  36. printf ("Hello, world! With x = %d\n", x);
  37. @}
  38. int main ()
  39. @{
  40. /* @b{Initialize StarPU.} */
  41. #pragma starpu initialize
  42. /* @b{Do an asynchronous call to `my_task'.} */
  43. my_task (42);
  44. /* @b{Wait for the call to complete.} */
  45. #pragma starpu wait
  46. /* @b{Terminate.} */
  47. #pragma starpu shutdown
  48. return 0;
  49. @}
  50. @end smallexample
  51. @end cartouche
  52. @noindent
  53. The code can then be compiled and linked with GCC and the
  54. @code{-fplugin} flag:
  55. @example
  56. $ gcc `pkg-config starpu-1.1 --cflags` hello-starpu.c \
  57. -fplugin=`pkg-config starpu-1.1 --variable=gccplugin` \
  58. `pkg-config starpu-1.1 --libs`
  59. @end example
  60. The code can also be compiled without the StarPU C extension and will
  61. behave as a normal sequential code.
  62. @example
  63. $ gcc hello-starpu.c
  64. hello-starpu.c:33:1: warning: ‘task’ attribute directive ignored [-Wattributes]
  65. $ ./a.out
  66. Hello, world! With x = 42
  67. @end example
  68. As can be seen above, the C extensions allows programmers to
  69. use StarPU tasks by essentially annotating ``regular'' C code.
  70. @node Hello World using StarPU's API
  71. @section Hello World using StarPU's API
  72. This section shows how to achieve the same result as in the previous
  73. section using StarPU's standard C API.
  74. @menu
  75. * Required Headers::
  76. * Defining a Codelet::
  77. * Submitting a Task::
  78. * Execution of Hello World::
  79. @end menu
  80. @node Required Headers
  81. @subsection Required Headers
  82. The @code{starpu.h} header should be included in any code using StarPU.
  83. @cartouche
  84. @smallexample
  85. #include <starpu.h>
  86. @end smallexample
  87. @end cartouche
  88. @node Defining a Codelet
  89. @subsection Defining a Codelet
  90. @cartouche
  91. @smallexample
  92. struct params
  93. @{
  94. int i;
  95. float f;
  96. @};
  97. void cpu_func(void *buffers[], void *cl_arg)
  98. @{
  99. struct params *params = cl_arg;
  100. printf("Hello world (params = @{%i, %f@} )\n", params->i, params->f);
  101. @}
  102. struct starpu_codelet cl =
  103. @{
  104. .where = STARPU_CPU,
  105. .cpu_funcs = @{ cpu_func, NULL @},
  106. .nbuffers = 0
  107. @};
  108. @end smallexample
  109. @end cartouche
  110. A codelet is a structure that represents a computational kernel. Such a codelet
  111. may contain an implementation of the same kernel on different architectures
  112. (e.g. CUDA, x86, ...). For compatibility, make sure that the whole
  113. structure is properly initialized to zero, either by using the
  114. function starpu_codelet_init (@pxref{starpu_codelet_init}), or by letting the
  115. compiler implicitly do it as examplified above.
  116. The @code{nbuffers} field specifies the number of data buffers that are
  117. manipulated by the codelet: here the codelet does not access or modify any data
  118. that is controlled by our data management library. Note that the argument
  119. passed to the codelet (the @code{cl_arg} field of the @code{starpu_task}
  120. structure) does not count as a buffer since it is not managed by our data
  121. management library, but just contain trivial parameters.
  122. @c TODO need a crossref to the proper description of "where" see bla for more ...
  123. We create a codelet which may only be executed on the CPUs. The @code{where}
  124. field is a bitmask that defines where the codelet may be executed. Here, the
  125. @code{STARPU_CPU} value means that only CPUs can execute this codelet
  126. (@pxref{Codelets and Tasks} for more details on this field). Note that
  127. the @code{where} field is optional, when unset its value is
  128. automatically set based on the availability of the different
  129. @code{XXX_funcs} fields.
  130. When a CPU core executes a codelet, it calls the @code{cpu_func} function,
  131. which @emph{must} have the following prototype:
  132. @code{void (*cpu_func)(void *buffers[], void *cl_arg);}
  133. In this example, we can ignore the first argument of this function which gives a
  134. description of the input and output buffers (e.g. the size and the location of
  135. the matrices) since there is none.
  136. The second argument is a pointer to a buffer passed as an
  137. argument to the codelet by the means of the @code{cl_arg} field of the
  138. @code{starpu_task} structure.
  139. @c TODO rewrite so that it is a little clearer ?
  140. Be aware that this may be a pointer to a
  141. @emph{copy} of the actual buffer, and not the pointer given by the programmer:
  142. if the codelet modifies this buffer, there is no guarantee that the initial
  143. buffer will be modified as well: this for instance implies that the buffer
  144. cannot be used as a synchronization medium. If synchronization is needed, data
  145. has to be registered to StarPU, see @ref{Vector Scaling Using StarPU's API}.
  146. @node Submitting a Task
  147. @subsection Submitting a Task
  148. @cartouche
  149. @smallexample
  150. void callback_func(void *callback_arg)
  151. @{
  152. printf("Callback function (arg %x)\n", callback_arg);
  153. @}
  154. int main(int argc, char **argv)
  155. @{
  156. /* @b{initialize StarPU} */
  157. starpu_init(NULL);
  158. struct starpu_task *task = starpu_task_create();
  159. task->cl = &cl; /* @b{Pointer to the codelet defined above} */
  160. struct params params = @{ 1, 2.0f @};
  161. task->cl_arg = &params;
  162. task->cl_arg_size = sizeof(params);
  163. task->callback_func = callback_func;
  164. task->callback_arg = 0x42;
  165. /* @b{starpu_task_submit will be a blocking call} */
  166. task->synchronous = 1;
  167. /* @b{submit the task to StarPU} */
  168. starpu_task_submit(task);
  169. /* @b{terminate StarPU} */
  170. starpu_shutdown();
  171. return 0;
  172. @}
  173. @end smallexample
  174. @end cartouche
  175. Before submitting any tasks to StarPU, @code{starpu_init} must be called. The
  176. @code{NULL} argument specifies that we use default configuration. Tasks cannot
  177. be submitted after the termination of StarPU by a call to
  178. @code{starpu_shutdown}.
  179. In the example above, a task structure is allocated by a call to
  180. @code{starpu_task_create}. This function only allocates and fills the
  181. corresponding structure with the default settings (@pxref{Codelets and
  182. Tasks, starpu_task_create}), but it does not submit the task to StarPU.
  183. @c not really clear ;)
  184. The @code{cl} field is a pointer to the codelet which the task will
  185. execute: in other words, the codelet structure describes which computational
  186. kernel should be offloaded on the different architectures, and the task
  187. structure is a wrapper containing a codelet and the piece of data on which the
  188. codelet should operate.
  189. The optional @code{cl_arg} field is a pointer to a buffer (of size
  190. @code{cl_arg_size}) with some parameters for the kernel
  191. described by the codelet. For instance, if a codelet implements a computational
  192. kernel that multiplies its input vector by a constant, the constant could be
  193. specified by the means of this buffer, instead of registering it as a StarPU
  194. data. It must however be noted that StarPU avoids making copy whenever possible
  195. and rather passes the pointer as such, so the buffer which is pointed at must
  196. kept allocated until the task terminates, and if several tasks are submitted
  197. with various parameters, each of them must be given a pointer to their own
  198. buffer.
  199. Once a task has been executed, an optional callback function is be called.
  200. While the computational kernel could be offloaded on various architectures, the
  201. callback function is always executed on a CPU. The @code{callback_arg}
  202. pointer is passed as an argument of the callback. The prototype of a callback
  203. function must be:
  204. @cartouche
  205. @example
  206. void (*callback_function)(void *);
  207. @end example
  208. @end cartouche
  209. If the @code{synchronous} field is non-zero, task submission will be
  210. synchronous: the @code{starpu_task_submit} function will not return until the
  211. task was executed. Note that the @code{starpu_shutdown} method does not
  212. guarantee that asynchronous tasks have been executed before it returns,
  213. @code{starpu_task_wait_for_all} can be used to that effect, or data can be
  214. unregistered (@code{starpu_data_unregister(vector_handle);}), which will
  215. implicitly wait for all the tasks scheduled to work on it, unless explicitly
  216. disabled thanks to @code{starpu_data_set_default_sequential_consistency_flag} or
  217. @code{starpu_data_set_sequential_consistency_flag}.
  218. @node Execution of Hello World
  219. @subsection Execution of Hello World
  220. @smallexample
  221. $ make hello_world
  222. cc $(pkg-config --cflags starpu-1.1) $(pkg-config --libs starpu-1.1) hello_world.c -o hello_world
  223. $ ./hello_world
  224. Hello world (params = @{1, 2.000000@} )
  225. Callback function (arg 42)
  226. @end smallexample
  227. @node Vector Scaling Using the C Extension
  228. @section Vector Scaling Using the C Extension
  229. @menu
  230. * Adding an OpenCL Task Implementation::
  231. * Adding a CUDA Task Implementation::
  232. @end menu
  233. The previous example has shown how to submit tasks. In this section,
  234. we show how StarPU tasks can manipulate data.
  235. We will first show how to use the C language extensions provided by
  236. the GCC plug-in (@pxref{C Extensions})@footnote{The complete example, and
  237. additional examples, is available in the @file{gcc-plugin/examples}
  238. directory of the StarPU distribution.}. These extensions map directly
  239. to StarPU's main concepts: tasks, task implementations for CPU,
  240. OpenCL, or CUDA, and registered data buffers. The standard C version
  241. that uses StarPU's standard C programming interface is given in the
  242. 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 `pkg-config starpu-1.1 --cflags` vector_scal.c \
  316. -fplugin=`pkg-config starpu-1.1 --variable=gccplugin` \
  317. `pkg-config starpu-1.1 --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 (size), &size);
  355. err |= clSetKernelArg (kernel, 1, sizeof (val), &val);
  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 (unsigned n, float *val, 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 () >>> (size, vector, 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. @{
  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.1) $(pkg-config --libs starpu-1.1) 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(unsigned n, float *val,
  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{ (n, val, *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(int nx, __global float* val, 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(n), &n);}
  621. @i{ err |= clSetKernelArg(kernel, 1, sizeof(val), &val);}
  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 that the fields
  642. @code{cuda_funcs} and @code{opencl_funcs} of the codelet are set to
  643. define the pointers to the CUDA and OpenCL implementations of the
  644. task.
  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. @{
  655. .cuda_funcs = @{ scal_cuda_func, NULL @},
  656. .cpu_funcs = @{ scal_cpu_func, NULL @},
  657. .opencl_funcs = @{ scal_opencl_func, NULL @},
  658. .nbuffers = 1,
  659. .modes = @{ STARPU_RW @}
  660. @}
  661. #ifdef STARPU_USE_OPENCL
  662. /* @b{The compiled version of the OpenCL program} */
  663. struct starpu_opencl_program programs;
  664. #endif
  665. int main(int argc, char **argv)
  666. @{
  667. float *vector;
  668. int i, ret;
  669. float factor=3.0;
  670. struct starpu_task *task;
  671. starpu_data_handle_t vector_handle;
  672. starpu_init(NULL); /* @b{Initialising StarPU} */
  673. #ifdef STARPU_USE_OPENCL
  674. starpu_opencl_load_opencl_from_file(
  675. "examples/basic_examples/vector_scal_opencl_codelet.cl",
  676. &programs, NULL);
  677. #endif
  678. vector = malloc(NX*sizeof(vector[0]));
  679. assert(vector);
  680. for(i=0 ; i<NX ; i++) vector[i] = i;
  681. @end smallexample
  682. @end cartouche
  683. @cartouche
  684. @smallexample
  685. /* @b{Registering data within StarPU} */
  686. starpu_vector_data_register(&vector_handle, 0, (uintptr_t)vector,
  687. NX, sizeof(vector[0]));
  688. /* @b{Definition of the task} */
  689. task = starpu_task_create();
  690. task->cl = &cl;
  691. task->handles[0] = vector_handle;
  692. task->cl_arg = &factor;
  693. task->cl_arg_size = sizeof(factor);
  694. @end smallexample
  695. @end cartouche
  696. @cartouche
  697. @smallexample
  698. /* @b{Submitting the task} */
  699. ret = starpu_task_submit(task);
  700. if (ret == -ENODEV) @{
  701. fprintf(stderr, "No worker may execute this task\n");
  702. return 1;
  703. @}
  704. @c TODO: Mmm, should rather be an unregistration with an implicit dependency, no?
  705. /* @b{Waiting for its termination} */
  706. starpu_task_wait_for_all();
  707. /* @b{Update the vector in RAM} */
  708. starpu_data_acquire(vector_handle, STARPU_R);
  709. @end smallexample
  710. @end cartouche
  711. @cartouche
  712. @smallexample
  713. /* @b{Access the data} */
  714. for(i=0 ; i<NX; i++) @{
  715. fprintf(stderr, "%f ", vector[i]);
  716. @}
  717. fprintf(stderr, "\n");
  718. /* @b{Release the RAM view of the data before unregistering it and shutting down StarPU} */
  719. starpu_data_release(vector_handle);
  720. starpu_data_unregister(vector_handle);
  721. starpu_shutdown();
  722. return 0;
  723. @}
  724. @end smallexample
  725. @end cartouche
  726. @node Execution of Hybrid Vector Scaling
  727. @subsection Execution of Hybrid Vector Scaling
  728. The Makefile given at the beginning of the section must be extended to
  729. give the rules to compile the CUDA source code. Note that the source
  730. file of the OpenCL kernel does not need to be compiled now, it will
  731. be compiled at run-time when calling the function
  732. @code{starpu_opencl_load_opencl_from_file()} (@pxref{starpu_opencl_load_opencl_from_file}).
  733. @cartouche
  734. @smallexample
  735. CFLAGS += $(shell pkg-config --cflags starpu-1.1)
  736. LDFLAGS += $(shell pkg-config --libs starpu-1.1)
  737. CC = gcc
  738. vector_scal: vector_scal.o vector_scal_cpu.o vector_scal_cuda.o vector_scal_opencl.o
  739. %.o: %.cu
  740. nvcc $(CFLAGS) $< -c $@
  741. clean:
  742. rm -f vector_scal *.o
  743. @end smallexample
  744. @end cartouche
  745. @smallexample
  746. $ make
  747. @end smallexample
  748. and to execute it, with the default configuration:
  749. @smallexample
  750. $ ./vector_scal
  751. 0.000000 3.000000 6.000000 9.000000 12.000000
  752. @end smallexample
  753. or for example, by disabling CPU devices:
  754. @smallexample
  755. $ STARPU_NCPU=0 ./vector_scal
  756. 0.000000 3.000000 6.000000 9.000000 12.000000
  757. @end smallexample
  758. or by disabling CUDA devices (which may permit to enable the use of OpenCL,
  759. see @ref{Enabling OpenCL}):
  760. @smallexample
  761. $ STARPU_NCUDA=0 ./vector_scal
  762. 0.000000 3.000000 6.000000 9.000000 12.000000
  763. @end smallexample