basic-examples.texi 30 KB

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