basic-examples.texi 31 KB

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