basic_examples.doxy 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. /*
  2. * This file is part of the StarPU Handbook.
  3. * Copyright (C) 2009--2011 Universit@'e de Bordeaux 1
  4. * Copyright (C) 2010, 2011, 2012, 2013 Centre National de la Recherche Scientifique
  5. * Copyright (C) 2011, 2012 Institut National de Recherche en Informatique et Automatique
  6. * See the file version.doxy for copying conditions.
  7. */
  8. /*! \page BasicExamples Basic Examples
  9. \section HelloWorldUsingTheCExtension Hello World Using The C Extension
  10. This section shows how to implement a simple program that submits a task
  11. to StarPU using the StarPU C extension (\ref cExtensions). The complete example, and additional examples,
  12. is available in the <c>gcc-plugin/examples</c> directory of the StarPU
  13. distribution. A similar example showing how to directly use the StarPU's API is shown
  14. in \ref HelloWorldUsingStarPUAPI.
  15. GCC from version 4.5 permit to use the StarPU GCC plug-in (\ref cExtensions). This makes writing a task both simpler and less error-prone.
  16. In a nutshell, all it takes is to declare a task, declare and define its
  17. implementations (for CPU, OpenCL, and/or CUDA), and invoke the task like
  18. a regular C function. The example below defines <c>my_task</c> which
  19. has a single implementation for CPU:
  20. \snippet hello_pragma.c To be included
  21. The code can then be compiled and linked with GCC and the <c>-fplugin</c> flag:
  22. \verbatim
  23. $ gcc `pkg-config starpu-1.1 --cflags` hello-starpu.c \
  24. -fplugin=`pkg-config starpu-1.1 --variable=gccplugin` \
  25. `pkg-config starpu-1.1 --libs`
  26. \endverbatim
  27. The code can also be compiled without the StarPU C extension and will
  28. behave as a normal sequential code.
  29. \verbatim
  30. $ gcc hello-starpu.c
  31. hello-starpu.c:33:1: warning: ‘task’ attribute directive ignored [-Wattributes]
  32. $ ./a.out
  33. Hello, world! With x = 42
  34. \endverbatim
  35. As can be seen above, the C extensions allows programmers to
  36. use StarPU tasks by essentially annotating ``regular'' C code.
  37. \section HelloWorldUsingStarPUAPI Hello World Using StarPU's API
  38. This section shows how to achieve the same result as in the previous
  39. section using StarPU's standard C API.
  40. \subsection RequiredHeaders Required Headers
  41. The header starpu.h should be included in any code using StarPU.
  42. \code{.c}
  43. #include <starpu.h>
  44. \endcode
  45. \subsection DefiningACodelet Defining A Codelet
  46. \code{.c}
  47. struct params
  48. {
  49. int i;
  50. float f;
  51. };
  52. void cpu_func(void *buffers[], void *cl_arg)
  53. {
  54. struct params *params = cl_arg;
  55. printf("Hello world (params = {%i, %f} )\n", params->i, params->f);
  56. }
  57. struct starpu_codelet cl =
  58. {
  59. .where = STARPU_CPU,
  60. .cpu_funcs = { cpu_func, NULL },
  61. .nbuffers = 0
  62. };
  63. \endcode
  64. A codelet is a structure that represents a computational kernel. Such a codelet
  65. may contain an implementation of the same kernel on different architectures
  66. (e.g. CUDA, x86, ...). For compatibility, make sure that the whole
  67. structure is properly initialized to zero, either by using the
  68. function starpu_codelet_init(), or by letting the
  69. compiler implicitly do it as examplified above.
  70. The field starpu_codelet::nbuffers specifies the number of data buffers that are
  71. manipulated by the codelet: here the codelet does not access or modify any data
  72. that is controlled by our data management library. Note that the argument
  73. passed to the codelet (the field starpu_task::cl_arg) does not count
  74. as a buffer since it is not managed by our data management library,
  75. but just contain trivial parameters.
  76. \internal
  77. TODO need a crossref to the proper description of "where" see bla for more ...
  78. \endinternal
  79. We create a codelet which may only be executed on the CPUs. The field
  80. starpu_codelet::where is a bitmask that defines where the codelet may
  81. be executed. Here, the value ::STARPU_CPU means that only CPUs can
  82. execute this codelet. Note that field starpu_codelet::where is
  83. optional, when unset its value is automatically set based on the
  84. availability of the different fields <c>XXX_funcs</c>.
  85. When a CPU core executes a codelet, it calls the function
  86. <c>cpu_func</c>, which \em must have the following prototype:
  87. \code{.c}
  88. void (*cpu_func)(void *buffers[], void *cl_arg);
  89. \endcode
  90. In this example, we can ignore the first argument of this function which gives a
  91. description of the input and output buffers (e.g. the size and the location of
  92. the matrices) since there is none.
  93. The second argument is a pointer to a buffer passed as an
  94. argument to the codelet by the means of the field starpu_task::cl_arg.
  95. \internal
  96. TODO rewrite so that it is a little clearer ?
  97. \endinternal
  98. Be aware that this may be a pointer to a
  99. \em copy of the actual buffer, and not the pointer given by the programmer:
  100. if the codelet modifies this buffer, there is no guarantee that the initial
  101. buffer will be modified as well: this for instance implies that the buffer
  102. cannot be used as a synchronization medium. If synchronization is needed, data
  103. has to be registered to StarPU, see \ref VectorScalingUsingStarPUAPI.
  104. \subsection SubmittingATask Submitting A Task
  105. \code{.c}
  106. void callback_func(void *callback_arg)
  107. {
  108. printf("Callback function (arg %x)\n", callback_arg);
  109. }
  110. int main(int argc, char **argv)
  111. {
  112. /* initialize StarPU */
  113. starpu_init(NULL);
  114. struct starpu_task *task = starpu_task_create();
  115. task->cl = &cl; /* Pointer to the codelet defined above */
  116. struct params params = { 1, 2.0f };
  117. task->cl_arg = &params;
  118. task->cl_arg_size = sizeof(params);
  119. task->callback_func = callback_func;
  120. task->callback_arg = 0x42;
  121. /* starpu_task_submit will be a blocking call */
  122. task->synchronous = 1;
  123. /* submit the task to StarPU */
  124. starpu_task_submit(task);
  125. /* terminate StarPU */
  126. starpu_shutdown();
  127. return 0;
  128. }
  129. \endcode
  130. Before submitting any tasks to StarPU, starpu_init() must be called. The
  131. <c>NULL</c> argument specifies that we use default configuration. Tasks cannot
  132. be submitted after the termination of StarPU by a call to
  133. starpu_shutdown().
  134. In the example above, a task structure is allocated by a call to
  135. starpu_task_create(). This function only allocates and fills the
  136. corresponding structure with the default settings, but it does not
  137. submit the task to StarPU.
  138. \internal
  139. not really clear ;)
  140. \endinternal
  141. The field starpu_task::cl is a pointer to the codelet which the task will
  142. execute: in other words, the codelet structure describes which computational
  143. kernel should be offloaded on the different architectures, and the task
  144. structure is a wrapper containing a codelet and the piece of data on which the
  145. codelet should operate.
  146. The optional field starpu_task::cl_arg field is a pointer to a buffer
  147. (of size starpu_task::cl_arg_size) with some parameters for the kernel
  148. described by the codelet. For instance, if a codelet implements a
  149. computational kernel that multiplies its input vector by a constant,
  150. the constant could be specified by the means of this buffer, instead
  151. of registering it as a StarPU data. It must however be noted that
  152. StarPU avoids making copy whenever possible and rather passes the
  153. pointer as such, so the buffer which is pointed at must kept allocated
  154. until the task terminates, and if several tasks are submitted with
  155. various parameters, each of them must be given a pointer to their
  156. buffer.
  157. Once a task has been executed, an optional callback function is be called.
  158. While the computational kernel could be offloaded on various architectures, the
  159. callback function is always executed on a CPU. The pointer
  160. starpu_task::callback_arg is passed as an argument of the callback
  161. function. The prototype of a callback function must be:
  162. \code{.c}
  163. void (*callback_function)(void *);
  164. \endcode
  165. If the field starpu_task::synchronous is non-zero, task submission
  166. will be synchronous: the function starpu_task_submit() will not return
  167. until the task was executed. Note that the function starpu_shutdown()
  168. does not guarantee that asynchronous tasks have been executed before
  169. it returns, starpu_task_wait_for_all() can be used to that effect, or
  170. data can be unregistered (starpu_data_unregister()), which will
  171. implicitly wait for all the tasks scheduled to work on it, unless
  172. explicitly disabled thanks to
  173. starpu_data_set_default_sequential_consistency_flag() or
  174. starpu_data_set_sequential_consistency_flag().
  175. \subsection ExecutionOfHelloWorld Execution Of Hello World
  176. \verbatim
  177. $ make hello_world
  178. cc $(pkg-config --cflags starpu-1.1) $(pkg-config --libs starpu-1.1) hello_world.c -o hello_world
  179. $ ./hello_world
  180. Hello world (params = {1, 2.000000} )
  181. Callback function (arg 42)
  182. \endverbatim
  183. \section VectorScalingUsingTheCExtension Vector Scaling Using the C Extension
  184. The previous example has shown how to submit tasks. In this section,
  185. we show how StarPU tasks can manipulate data.
  186. We will first show how to use the C language extensions provided by
  187. the GCC plug-in (\ref cExtensions). The complete example, and
  188. additional examples, is available in the <c>gcc-plugin/examples</c>
  189. directory of the StarPU distribution. These extensions map directly
  190. to StarPU's main concepts: tasks, task implementations for CPU,
  191. OpenCL, or CUDA, and registered data buffers. The standard C version
  192. that uses StarPU's standard C programming interface is given in the
  193. next section (\ref VectorScalingUsingStarPUAPI).
  194. First of all, the vector-scaling task and its simple CPU implementation
  195. has to be defined:
  196. \code{.c}
  197. /* Declare the `vector_scal' task. */
  198. static void vector_scal (unsigned size, float vector[size],
  199. float factor)
  200. __attribute__ ((task));
  201. /* Define the standard CPU implementation. */
  202. static void
  203. vector_scal (unsigned size, float vector[size], float factor)
  204. {
  205. unsigned i;
  206. for (i = 0; i < size; i++)
  207. vector[i] *= factor;
  208. }
  209. \endcode
  210. Next, the body of the program, which uses the task defined above, can be
  211. implemented:
  212. \snippet hello_pragma2.c To be included
  213. The <c>main</c> function above does several things:
  214. <ul>
  215. <li>
  216. It initializes StarPU.
  217. </li>
  218. <li>
  219. It allocates <c>vector</c> in the heap; it will automatically be freed
  220. when its scope is left. Alternatively, good old <c>malloc</c> and
  221. <c>free</c> could have been used, but they are more error-prone and
  222. require more typing.
  223. </li>
  224. <li>
  225. It registers the memory pointed to by <c>vector</c>. Eventually,
  226. when OpenCL or CUDA task implementations are added, this will allow
  227. StarPU to transfer that memory region between GPUs and the main memory.
  228. Removing this <c>pragma</c> is an error.
  229. </li>
  230. <li>
  231. It invokes the <c>vector_scal</c> task. The invocation looks the same
  232. as a standard C function call. However, it is an asynchronous
  233. invocation, meaning that the actual call is performed in parallel with
  234. the caller's continuation.
  235. </li>
  236. <li>
  237. It waits for the termination of the <c>vector_scal</c>
  238. asynchronous call.
  239. </li>
  240. <li>
  241. Finally, StarPU is shut down.
  242. </li>
  243. </ul>
  244. The program can be compiled and linked with GCC and the <c>-fplugin</c>
  245. flag:
  246. \verbatim
  247. $ gcc `pkg-config starpu-1.1 --cflags` vector_scal.c \
  248. -fplugin=`pkg-config starpu-1.1 --variable=gccplugin` \
  249. `pkg-config starpu-1.1 --libs`
  250. \endverbatim
  251. And voilà!
  252. \subsection AddingAnOpenCLTaskImplementation Adding an OpenCL Task Implementation
  253. Now, this is all fine and great, but you certainly want to take
  254. advantage of these newfangled GPUs that your lab just bought, don't you?
  255. So, let's add an OpenCL implementation of the <c>vector_scal</c> task.
  256. We assume that the OpenCL kernel is available in a file,
  257. <c>vector_scal_opencl_kernel.cl</c>, not shown here. The OpenCL task
  258. implementation is similar to that used with the standard C API
  259. (\ref DefinitionOfTheOpenCLKernel). It is declared and defined
  260. in our C file like this:
  261. \code{.c}
  262. /* The OpenCL programs, loaded from 'main' (see below). */
  263. static struct starpu_opencl_program cl_programs;
  264. static void vector_scal_opencl (unsigned size, float vector[size],
  265. float factor)
  266. __attribute__ ((task_implementation ("opencl", vector_scal)));
  267. static void
  268. vector_scal_opencl (unsigned size, float vector[size], float factor)
  269. {
  270. int id, devid, err;
  271. cl_kernel kernel;
  272. cl_command_queue queue;
  273. cl_event event;
  274. /* VECTOR is GPU memory pointer, not a main memory pointer. */
  275. cl_mem val = (cl_mem) vector;
  276. id = starpu_worker_get_id ();
  277. devid = starpu_worker_get_devid (id);
  278. /* Prepare to invoke the kernel. In the future, this will be largely automated. */
  279. err = starpu_opencl_load_kernel (&kernel, &queue, &cl_programs,
  280. "vector_mult_opencl", devid);
  281. if (err != CL_SUCCESS)
  282. STARPU_OPENCL_REPORT_ERROR (err);
  283. err = clSetKernelArg (kernel, 0, sizeof (size), &size);
  284. err |= clSetKernelArg (kernel, 1, sizeof (val), &val);
  285. err |= clSetKernelArg (kernel, 2, sizeof (factor), &factor);
  286. if (err)
  287. STARPU_OPENCL_REPORT_ERROR (err);
  288. size_t global = 1, local = 1;
  289. err = clEnqueueNDRangeKernel (queue, kernel, 1, NULL, &global,
  290. &local, 0, NULL, &event);
  291. if (err != CL_SUCCESS)
  292. STARPU_OPENCL_REPORT_ERROR (err);
  293. clFinish (queue);
  294. starpu_opencl_collect_stats (event);
  295. clReleaseEvent (event);
  296. /* Done with KERNEL. */
  297. starpu_opencl_release_kernel (kernel);
  298. }
  299. \endcode
  300. The OpenCL kernel itself must be loaded from <c>main</c>, sometime after
  301. the <c>initialize</c> pragma:
  302. \code{.c}
  303. starpu_opencl_load_opencl_from_file ("vector_scal_opencl_kernel.cl",
  304. &cl_programs, "");
  305. \endcode
  306. And that's it. The <c>vector_scal</c> task now has an additional
  307. implementation, for OpenCL, which StarPU's scheduler may choose to use
  308. at run-time. Unfortunately, the <c>vector_scal_opencl</c> above still
  309. has to go through the common OpenCL boilerplate; in the future,
  310. additional extensions will automate most of it.
  311. \subsection AddingACUDATaskImplementation Adding a CUDA Task Implementation
  312. Adding a CUDA implementation of the task is very similar, except that
  313. the implementation itself is typically written in CUDA, and compiled
  314. with <c>nvcc</c>. Thus, the C file only needs to contain an external
  315. declaration for the task implementation:
  316. \code{.c}
  317. extern void vector_scal_cuda (unsigned size, float vector[size],
  318. float factor)
  319. __attribute__ ((task_implementation ("cuda", vector_scal)));
  320. \endcode
  321. The actual implementation of the CUDA task goes into a separate
  322. compilation unit, in a <c>.cu</c> file. It is very close to the
  323. implementation when using StarPU's standard C API (\ref DefinitionOfTheCUDAKernel).
  324. \code{.c}
  325. /* CUDA implementation of the `vector_scal' task, to be compiled with `nvcc'. */
  326. #include <starpu.h>
  327. #include <stdlib.h>
  328. static __global__ void
  329. vector_mult_cuda (unsigned n, float *val, float factor)
  330. {
  331. unsigned i = blockIdx.x * blockDim.x + threadIdx.x;
  332. if (i < n)
  333. val[i] *= factor;
  334. }
  335. /* Definition of the task implementation declared in the C file. */
  336. extern "C" void
  337. vector_scal_cuda (size_t size, float vector[], float factor)
  338. {
  339. unsigned threads_per_block = 64;
  340. unsigned nblocks = (size + threads_per_block - 1) / threads_per_block;
  341. vector_mult_cuda <<< nblocks, threads_per_block, 0,
  342. starpu_cuda_get_local_stream () >>> (size, vector, factor);
  343. cudaStreamSynchronize (starpu_cuda_get_local_stream ());
  344. }
  345. \endcode
  346. The complete source code, in the <c>gcc-plugin/examples/vector_scal</c>
  347. directory of the StarPU distribution, also shows how an SSE-specialized
  348. CPU task implementation can be added.
  349. For more details on the C extensions provided by StarPU's GCC plug-in,
  350. \ref cExtensions.
  351. \section VectorScalingUsingStarPUAPI Vector Scaling Using StarPU's API
  352. This section shows how to achieve the same result as explained in the
  353. previous section using StarPU's standard C API.
  354. The full source code for
  355. this example is given in \ref FullSourceCodeVectorScal.
  356. \subsection SourceCodeOfVectorScaling Source Code of Vector Scaling
  357. Programmers can describe the data layout of their application so that StarPU is
  358. responsible for enforcing data coherency and availability across the machine.
  359. Instead of handling complex (and non-portable) mechanisms to perform data
  360. movements, programmers only declare which piece of data is accessed and/or
  361. modified by a task, and StarPU makes sure that when a computational kernel
  362. starts somewhere (e.g. on a GPU), its data are available locally.
  363. Before submitting those tasks, the programmer first needs to declare the
  364. different pieces of data to StarPU using the functions
  365. <c>starpu_*_data_register</c>. To ease the development of applications
  366. for StarPU, it is possible to describe multiple types of data layout.
  367. A type of data layout is called an <b>interface</b>. There are
  368. different predefined interfaces available in StarPU: here we will
  369. consider the <b>vector interface</b>.
  370. The following lines show how to declare an array of <c>NX</c> elements of type
  371. <c>float</c> using the vector interface:
  372. \code{.c}
  373. float vector[NX];
  374. starpu_data_handle_t vector_handle;
  375. starpu_vector_data_register(&vector_handle, 0, (uintptr_t)vector, NX,
  376. sizeof(vector[0]));
  377. \endcode
  378. The first argument, called the <b>data handle</b>, is an opaque pointer which
  379. designates the array in StarPU. This is also the structure which is used to
  380. describe which data is used by a task. The second argument is the node number
  381. where the data originally resides. Here it is 0 since the <c>vector array</c> is in
  382. the main memory. Then comes the pointer <c>vector</c> where the data can be found in main memory,
  383. the number of elements in the vector and the size of each element.
  384. The following shows how to construct a StarPU task that will manipulate the
  385. vector and a constant factor.
  386. \code{.c}
  387. float factor = 3.14;
  388. struct starpu_task *task = starpu_task_create();
  389. task->cl = &cl; /* Pointer to the codelet defined below */
  390. task->handles[0] = vector_handle; /* First parameter of the codelet */
  391. task->cl_arg = &factor;
  392. task->cl_arg_size = sizeof(factor);
  393. task->synchronous = 1;
  394. starpu_task_submit(task);
  395. \endcode
  396. Since the factor is a mere constant float value parameter,
  397. it does not need a preliminary registration, and
  398. can just be passed through the pointer starpu_task::cl_arg like in the previous
  399. example. The vector parameter is described by its handle.
  400. starpu_task::handles should be set with the handles of the data, the
  401. access modes for the data are defined in the field
  402. starpu_codelet::modes (::STARPU_R for read-only, ::STARPU_W for
  403. write-only and ::STARPU_RW for read and write access).
  404. The definition of the codelet can be written as follows:
  405. \code{.c}
  406. void scal_cpu_func(void *buffers[], void *cl_arg)
  407. {
  408. unsigned i;
  409. float *factor = cl_arg;
  410. /* length of the vector */
  411. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  412. /* CPU copy of the vector pointer */
  413. float *val = (float *)STARPU_VECTOR_GET_PTR(buffers[0]);
  414. for (i = 0; i < n; i++)
  415. val[i] *= *factor;
  416. }
  417. struct starpu_codelet cl =
  418. {
  419. .cpu_funcs = { scal_cpu_func, NULL },
  420. .nbuffers = 1,
  421. .modes = { STARPU_RW }
  422. };
  423. \endcode
  424. The first argument is an array that gives
  425. a description of all the buffers passed in the array starpu_task::handles. The
  426. size of this array is given by the field starpu_codelet::nbuffers. For
  427. the sake of genericity, this array contains pointers to the different
  428. interfaces describing each buffer. In the case of the <b>vector
  429. interface</b>, the location of the vector (resp. its length) is
  430. accessible in the starpu_vector_interface::ptr (resp.
  431. starpu_vector_interface::nx) of this interface. Since the vector is
  432. accessed in a read-write fashion, any modification will automatically
  433. affect future accesses to this vector made by other tasks.
  434. The second argument of the function <c>scal_cpu_func</c> contains a
  435. pointer to the parameters of the codelet (given in
  436. starpu_task::cl_arg), so that we read the constant factor from this
  437. pointer.
  438. \subsection ExecutionOfVectorScaling Execution of Vector Scaling
  439. \verbatim
  440. $ make vector_scal
  441. cc $(pkg-config --cflags starpu-1.1) $(pkg-config --libs starpu-1.1) vector_scal.c -o vector_scal
  442. $ ./vector_scal
  443. 0.000000 3.000000 6.000000 9.000000 12.000000
  444. \endverbatim
  445. \section VectorScalingOnAnHybridCPUGPUMachine Vector Scaling on an Hybrid CPU/GPU Machine
  446. Contrary to the previous examples, the task submitted in this example may not
  447. only be executed by the CPUs, but also by a CUDA device.
  448. \subsection DefinitionOfTheCUDAKernel Definition of the CUDA Kernel
  449. The CUDA implementation can be written as follows. It needs to be compiled with
  450. a CUDA compiler such as nvcc, the NVIDIA CUDA compiler driver. It must be noted
  451. that the vector pointer returned by ::STARPU_VECTOR_GET_PTR is here a
  452. pointer in GPU memory, so that it can be passed as such to the
  453. <c>vector_mult_cuda</c> kernel call.
  454. \code{.c}
  455. #include <starpu.h>
  456. static __global__ void vector_mult_cuda(unsigned n, float *val,
  457. float factor)
  458. {
  459. unsigned i = blockIdx.x*blockDim.x + threadIdx.x;
  460. if (i < n)
  461. val[i] *= factor;
  462. }
  463. extern "C" void scal_cuda_func(void *buffers[], void *_args)
  464. {
  465. float *factor = (float *)_args;
  466. /* length of the vector */
  467. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  468. /* CUDA copy of the vector pointer */
  469. float *val = (float *)STARPU_VECTOR_GET_PTR(buffers[0]);
  470. unsigned threads_per_block = 64;
  471. unsigned nblocks = (n + threads_per_block-1) / threads_per_block;
  472. vector_mult_cuda<<<nblocks,threads_per_block, 0, starpu_cuda_get_local_stream()>>>
  473. (n, val, *factor);
  474. cudaStreamSynchronize(starpu_cuda_get_local_stream());
  475. }
  476. \endcode
  477. \subsection DefinitionOfTheOpenCLKernel Definition of the OpenCL Kernel
  478. The OpenCL implementation can be written as follows. StarPU provides
  479. tools to compile a OpenCL kernel stored in a file.
  480. \code{.c}
  481. __kernel void vector_mult_opencl(int nx, __global float* val, float factor)
  482. {
  483. const int i = get_global_id(0);
  484. if (i < nx) {
  485. val[i] *= factor;
  486. }
  487. }
  488. \endcode
  489. Contrary to CUDA and CPU, ::STARPU_VECTOR_GET_DEV_HANDLE has to be used,
  490. which returns a <c>cl_mem</c> (which is not a device pointer, but an OpenCL
  491. handle), which can be passed as such to the OpenCL kernel. The difference is
  492. important when using partitioning, see \ref PartitioningData.
  493. \code{.c}
  494. #include <starpu.h>
  495. extern struct starpu_opencl_program programs;
  496. void scal_opencl_func(void *buffers[], void *_args)
  497. {
  498. float *factor = _args;
  499. int id, devid, err; /* OpenCL specific code */
  500. cl_kernel kernel; /* OpenCL specific code */
  501. cl_command_queue queue; /* OpenCL specific code */
  502. cl_event event; /* OpenCL specific code */
  503. /* length of the vector */
  504. unsigned n = STARPU_VECTOR_GET_NX(buffers[0]);
  505. /* OpenCL copy of the vector pointer */
  506. cl_mem val = (cl_mem) STARPU_VECTOR_GET_DEV_HANDLE(buffers[0]);
  507. { /* OpenCL specific code */
  508. id = starpu_worker_get_id();
  509. devid = starpu_worker_get_devid(id);
  510. err = starpu_opencl_load_kernel(&kernel, &queue, &programs,
  511. "vector_mult_opencl", devid); /* Name of the codelet defined above */
  512. if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err);
  513. err = clSetKernelArg(kernel, 0, sizeof(n), &n);
  514. err |= clSetKernelArg(kernel, 1, sizeof(val), &val);
  515. err |= clSetKernelArg(kernel, 2, sizeof(*factor), factor);
  516. if (err) STARPU_OPENCL_REPORT_ERROR(err);
  517. }
  518. { /* OpenCL specific code */
  519. size_t global=n;
  520. size_t local=1;
  521. err = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &global, &local, 0, NULL, &event);
  522. if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err);
  523. }
  524. { /* OpenCL specific code */
  525. clFinish(queue);
  526. starpu_opencl_collect_stats(event);
  527. clReleaseEvent(event);
  528. starpu_opencl_release_kernel(kernel);
  529. }
  530. }
  531. \endcode
  532. \subsection DefinitionOfTheMainCode Definition of the Main Code
  533. The CPU implementation is the same as in the previous section.
  534. Here is the source of the main application. You can notice that the fields
  535. starpu_codelet::cuda_funcs and starpu_codelet::opencl_funcs are set to
  536. define the pointers to the CUDA and OpenCL implementations of the
  537. task.
  538. \snippet vector_scal_c.c To be included
  539. \subsection ExecutionOfHybridVectorScaling Execution of Hybrid Vector Scaling
  540. The Makefile given at the beginning of the section must be extended to
  541. give the rules to compile the CUDA source code. Note that the source
  542. file of the OpenCL kernel does not need to be compiled now, it will
  543. be compiled at run-time when calling the function
  544. starpu_opencl_load_opencl_from_file().
  545. \verbatim
  546. CFLAGS += $(shell pkg-config --cflags starpu-1.1)
  547. LDFLAGS += $(shell pkg-config --libs starpu-1.1)
  548. CC = gcc
  549. vector_scal: vector_scal.o vector_scal_cpu.o vector_scal_cuda.o vector_scal_opencl.o
  550. %.o: %.cu
  551. nvcc $(CFLAGS) $< -c $@
  552. clean:
  553. rm -f vector_scal *.o
  554. \endverbatim
  555. \verbatim
  556. $ make
  557. \endverbatim
  558. and to execute it, with the default configuration:
  559. \verbatim
  560. $ ./vector_scal
  561. 0.000000 3.000000 6.000000 9.000000 12.000000
  562. \endverbatim
  563. or for example, by disabling CPU devices:
  564. \verbatim
  565. $ STARPU_NCPU=0 ./vector_scal
  566. 0.000000 3.000000 6.000000 9.000000 12.000000
  567. \endverbatim
  568. or by disabling CUDA devices (which may permit to enable the use of OpenCL,
  569. see \ref EnablingOpenCL) :
  570. \verbatim
  571. $ STARPU_NCUDA=0 ./vector_scal
  572. 0.000000 3.000000 6.000000 9.000000 12.000000
  573. \endverbatim
  574. */