basic-examples.texi 31 KB

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