basic-examples.texi 30 KB

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