basic-examples.texi 31 KB

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