basic-examples.texi 30 KB

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