advanced-examples.texi 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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 Institut National de Recherche en Informatique et Automatique
  6. @c See the file starpu.texi for copying conditions.
  7. @menu
  8. * Using multiple implementations of a codelet::
  9. * Enabling implementation according to capabilities::
  10. * Task and Worker Profiling::
  11. * Partitioning Data::
  12. * Performance model example::
  13. * Theoretical lower bound on execution time::
  14. * Insert Task Utility::
  15. * Data reduction::
  16. * Parallel Tasks::
  17. * Debugging::
  18. * The multiformat interface::
  19. * On-GPU rendering::
  20. * More examples:: More examples shipped with StarPU
  21. @end menu
  22. @node Using multiple implementations of a codelet
  23. @section Using multiple implementations of a codelet
  24. One may want to write multiple implementations of a codelet for a single type of
  25. device and let StarPU choose which one to run. As an example, we will show how
  26. to use SSE to scale a vector. The codelet can be written as follows:
  27. @cartouche
  28. @smallexample
  29. #include <xmmintrin.h>
  30. void scal_sse_func(void *buffers[], void *cl_arg)
  31. @{
  32. float *vector = (float *) STARPU_VECTOR_GET_PTR(buffers[0]);
  33. unsigned int n = STARPU_VECTOR_GET_NX(buffers[0]);
  34. unsigned int n_iterations = n/4;
  35. if (n % 4 != 0)
  36. n_iterations++;
  37. __m128 *VECTOR = (__m128*) vector;
  38. __m128 factor __attribute__((aligned(16)));
  39. factor = _mm_set1_ps(*(float *) cl_arg);
  40. unsigned int i;
  41. for (i = 0; i < n_iterations; i++)
  42. VECTOR[i] = _mm_mul_ps(factor, VECTOR[i]);
  43. @}
  44. @end smallexample
  45. @end cartouche
  46. @cartouche
  47. @smallexample
  48. struct starpu_codelet cl = @{
  49. .where = STARPU_CPU,
  50. .cpu_funcs = @{ scal_cpu_func, scal_sse_func, NULL @},
  51. .nbuffers = 1,
  52. .modes = @{ STARPU_RW @}
  53. @};
  54. @end smallexample
  55. @end cartouche
  56. Schedulers which are multi-implementation aware (only @code{dmda}, @code{heft}
  57. and @code{pheft} for now) will use the performance models of all the
  58. implementations it was given, and pick the one that seems to be the fastest.
  59. @node Enabling implementation according to capabilities
  60. @section Enabling implementation according to capabilities
  61. Some implementations may not run on some devices. For instance, some CUDA
  62. devices do not support double floating point precision, and thus the kernel
  63. execution would just fail; or the device may not have enough shared memory for
  64. the implementation being used. The @code{can_execute} field of the @code{struct
  65. starpu_codelet} structure permits to express this. For instance:
  66. @cartouche
  67. @smallexample
  68. static int can_execute(unsigned workerid, struct starpu_task *task, unsigned nimpl)
  69. @{
  70. const struct cudaDeviceProp *props;
  71. if (starpu_worker_get_type(workerid) == STARPU_CPU_WORKER)
  72. return 1;
  73. /* Cuda device */
  74. props = starpu_cuda_get_device_properties(workerid);
  75. if (props->major >= 2 || props->minor >= 3)
  76. /* At least compute capability 1.3, supports doubles */
  77. return 1;
  78. /* Old card, does not support doubles */
  79. return 0;
  80. @}
  81. struct starpu_codelet cl = @{
  82. .where = STARPU_CPU|STARPU_CUDA,
  83. .can_execute = can_execute,
  84. .cpu_funcs = @{ cpu_func, NULL @},
  85. .cuda_funcs = @{ gpu_func, NULL @}
  86. .nbuffers = 1,
  87. .modes = @{ STARPU_RW @}
  88. @};
  89. @end smallexample
  90. @end cartouche
  91. This can be essential e.g. when running on a machine which mixes various models
  92. of CUDA devices, to take benefit from the new models without crashing on old models.
  93. Note: the @code{can_execute} function is called by the scheduler each time it
  94. tries to match a task with a worker, and should thus be very fast. The
  95. @code{starpu_cuda_get_device_properties} provides a quick access to CUDA
  96. properties of CUDA devices to achieve such efficiency.
  97. Another example is compiling CUDA code for various compute capabilities,
  98. resulting with two CUDA functions, e.g. @code{scal_gpu_13} for compute capability
  99. 1.3, and @code{scal_gpu_20} for compute capability 2.0. Both functions can be
  100. provided to StarPU by using @code{cuda_funcs}, and @code{can_execute} can then be
  101. used to rule out the @code{scal_gpu_20} variant on a CUDA device which
  102. will not be able to execute it:
  103. @cartouche
  104. @smallexample
  105. static int can_execute(unsigned workerid, struct starpu_task *task, unsigned nimpl)
  106. @{
  107. const struct cudaDeviceProp *props;
  108. if (starpu_worker_get_type(workerid) == STARPU_CPU_WORKER)
  109. return 1;
  110. /* Cuda device */
  111. if (nimpl == 0)
  112. /* Trying to execute the 1.3 capability variant, we assume it is ok in all cases. */
  113. return 1;
  114. /* Trying to execute the 2.0 capability variant, check that the card can do it. */
  115. props = starpu_cuda_get_device_properties(workerid);
  116. if (props->major >= 2 || props->minor >= 0)
  117. /* At least compute capability 2.0, can run it */
  118. return 1;
  119. /* Old card, does not support 2.0, will not be able to execute the 2.0 variant. */
  120. return 0;
  121. @}
  122. struct starpu_codelet cl = @{
  123. .where = STARPU_CPU|STARPU_CUDA,
  124. .can_execute = can_execute,
  125. .cpu_funcs = @{ cpu_func, NULL @},
  126. .cuda_funcs = @{ scal_gpu_13, scal_gpu_20, NULL @},
  127. .nbuffers = 1,
  128. .modes = @{ STARPU_RW @}
  129. @};
  130. @end smallexample
  131. @end cartouche
  132. Note: the most generic variant should be provided first, as some schedulers are
  133. not able to try the different variants.
  134. @node Task and Worker Profiling
  135. @section Task and Worker Profiling
  136. A full example showing how to use the profiling API is available in
  137. the StarPU sources in the directory @code{examples/profiling/}.
  138. @cartouche
  139. @smallexample
  140. struct starpu_task *task = starpu_task_create();
  141. task->cl = &cl;
  142. task->synchronous = 1;
  143. /* We will destroy the task structure by hand so that we can
  144. * query the profiling info before the task is destroyed. */
  145. task->destroy = 0;
  146. /* Submit and wait for completion (since synchronous was set to 1) */
  147. starpu_task_submit(task);
  148. /* The task is finished, get profiling information */
  149. struct starpu_task_profiling_info *info = task->profiling_info;
  150. /* How much time did it take before the task started ? */
  151. double delay += starpu_timing_timespec_delay_us(&info->submit_time, &info->start_time);
  152. /* How long was the task execution ? */
  153. double length += starpu_timing_timespec_delay_us(&info->start_time, &info->end_time);
  154. /* We don't need the task structure anymore */
  155. starpu_task_destroy(task);
  156. @end smallexample
  157. @end cartouche
  158. @cartouche
  159. @smallexample
  160. /* Display the occupancy of all workers during the test */
  161. int worker;
  162. for (worker = 0; worker < starpu_worker_get_count(); worker++)
  163. @{
  164. struct starpu_worker_profiling_info worker_info;
  165. int ret = starpu_worker_get_profiling_info(worker, &worker_info);
  166. STARPU_ASSERT(!ret);
  167. double total_time = starpu_timing_timespec_to_us(&worker_info.total_time);
  168. double executing_time = starpu_timing_timespec_to_us(&worker_info.executing_time);
  169. double sleeping_time = starpu_timing_timespec_to_us(&worker_info.sleeping_time);
  170. float executing_ratio = 100.0*executing_time/total_time;
  171. float sleeping_ratio = 100.0*sleeping_time/total_time;
  172. char workername[128];
  173. starpu_worker_get_name(worker, workername, 128);
  174. fprintf(stderr, "Worker %s:\n", workername);
  175. fprintf(stderr, "\ttotal time: %.2lf ms\n", total_time*1e-3);
  176. fprintf(stderr, "\texec time: %.2lf ms (%.2f %%)\n", executing_time*1e-3,
  177. executing_ratio);
  178. fprintf(stderr, "\tblocked time: %.2lf ms (%.2f %%)\n", sleeping_time*1e-3,
  179. sleeping_ratio);
  180. @}
  181. @end smallexample
  182. @end cartouche
  183. @node Partitioning Data
  184. @section Partitioning Data
  185. An existing piece of data can be partitioned in sub parts to be used by different tasks, for instance:
  186. @cartouche
  187. @smallexample
  188. int vector[NX];
  189. starpu_data_handle_t handle;
  190. /* Declare data to StarPU */
  191. starpu_vector_data_register(&handle, 0, (uintptr_t)vector, NX, sizeof(vector[0]));
  192. /* Partition the vector in PARTS sub-vectors */
  193. starpu_filter f =
  194. @{
  195. .filter_func = starpu_block_filter_func_vector,
  196. .nchildren = PARTS
  197. @};
  198. starpu_data_partition(handle, &f);
  199. @end smallexample
  200. @end cartouche
  201. The task submission then uses @code{starpu_data_get_sub_data} to retrive the
  202. sub-handles to be passed as tasks parameters.
  203. @cartouche
  204. @smallexample
  205. /* Submit a task on each sub-vector */
  206. for (i=0; i<starpu_data_get_nb_children(handle); i++) @{
  207. /* Get subdata number i (there is only 1 dimension) */
  208. starpu_data_handle_t sub_handle = starpu_data_get_sub_data(handle, 1, i);
  209. struct starpu_task *task = starpu_task_create();
  210. task->handles[0] = sub_handle;
  211. task->cl = &cl;
  212. task->synchronous = 1;
  213. task->cl_arg = &factor;
  214. task->cl_arg_size = sizeof(factor);
  215. starpu_task_submit(task);
  216. @}
  217. @end smallexample
  218. @end cartouche
  219. Partitioning can be applied several times, see
  220. @code{examples/basic_examples/mult.c} and @code{examples/filters/}.
  221. Wherever the whole piece of data is already available, the partitioning will
  222. be done in-place, i.e. without allocating new buffers but just using pointers
  223. inside the existing copy. This is particularly important to be aware of when
  224. using OpenCL, where the kernel parameters are not pointers, but handles. The
  225. kernel thus needs to be also passed the offset within the OpenCL buffer:
  226. @cartouche
  227. @smallexample
  228. void opencl_func(void *buffers[], void *cl_arg)
  229. @{
  230. cl_mem vector = (cl_mem) STARPU_VECTOR_GET_DEV_HANDLE(buffers[0]);
  231. unsigned offset = STARPU_BLOCK_GET_OFFSET(buffers[0]);
  232. ...
  233. clSetKernelArg(kernel, 0, sizeof(vector), &vector);
  234. clSetKernelArg(kernel, 1, sizeof(offset), &offset);
  235. ...
  236. @}
  237. @end smallexample
  238. @end cartouche
  239. And the kernel has to shift from the pointer passed by the OpenCL driver:
  240. @cartouche
  241. @smallexample
  242. __kernel void opencl_kernel(__global int *vector, unsigned offset)
  243. @{
  244. block = (__global void *)block + offset;
  245. ...
  246. @}
  247. @end smallexample
  248. @end cartouche
  249. @node Performance model example
  250. @section Performance model example
  251. To achieve good scheduling, StarPU scheduling policies need to be able to
  252. estimate in advance the duration of a task. This is done by giving to codelets
  253. a performance model, by defining a @code{starpu_perfmodel} structure and
  254. providing its address in the @code{model} field of the @code{struct starpu_codelet}
  255. structure. The @code{symbol} and @code{type} fields of @code{starpu_perfmodel}
  256. are mandatory, to give a name to the model, and the type of the model, since
  257. there are several kinds of performance models.
  258. @itemize
  259. @item
  260. Measured at runtime (@code{STARPU_HISTORY_BASED} model type). This assumes that for a
  261. given set of data input/output sizes, the performance will always be about the
  262. same. This is very true for regular kernels on GPUs for instance (<0.1% error),
  263. and just a bit less true on CPUs (~=1% error). This also assumes that there are
  264. few different sets of data input/output sizes. StarPU will then keep record of
  265. the average time of previous executions on the various processing units, and use
  266. it as an estimation. History is done per task size, by using a hash of the input
  267. and ouput sizes as an index.
  268. It will also save it in @code{~/.starpu/sampling/codelets}
  269. for further executions, and can be observed by using the
  270. @code{starpu_perfmodel_display} command, or drawn by using
  271. the @code{starpu_perfmodel_plot}. The models are indexed by machine name. To
  272. share the models between machines (e.g. for a homogeneous cluster), use
  273. @code{export STARPU_HOSTNAME=some_global_name}. Measurements are only done when using a task scheduler which makes use of it, such as @code{heft} or @code{dmda}.
  274. The following is a small code example.
  275. If e.g. the code is recompiled with other compilation options, or several
  276. variants of the code are used, the symbol string should be changed to reflect
  277. that, in order to recalibrate a new model from zero. The symbol string can even
  278. be constructed dynamically at execution time, as long as this is done before
  279. submitting any task using it.
  280. @cartouche
  281. @smallexample
  282. static struct starpu_perfmodel mult_perf_model = @{
  283. .type = STARPU_HISTORY_BASED,
  284. .symbol = "mult_perf_model"
  285. @};
  286. struct starpu_codelet cl = @{
  287. .where = STARPU_CPU,
  288. .cpu_funcs = @{ cpu_mult, NULL @},
  289. .nbuffers = 3,
  290. .modes = @{ STARPU_R, STARPU_R, STARPU_W @},
  291. /* for the scheduling policy to be able to use performance models */
  292. .model = &mult_perf_model
  293. @};
  294. @end smallexample
  295. @end cartouche
  296. @item
  297. Measured at runtime and refined by regression (@code{STARPU_*REGRESSION_BASED}
  298. model type). This still assumes performance regularity, but works
  299. with various data input sizes, by applying regression over observed
  300. execution times. STARPU_REGRESSION_BASED uses an a*n^b regression
  301. form, STARPU_NL_REGRESSION_BASED uses an a*n^b+c (more precise than
  302. STARPU_REGRESSION_BASED, but costs a lot more to compute). For instance,
  303. @code{tests/perfmodels/regression_based.c} uses a regression-based performance
  304. model for the @code{memset} operation. Of course, the application has to issue
  305. tasks with varying size so that the regression can be computed. StarPU will not
  306. trust the regression unless there is at least 10% difference between the minimum
  307. and maximum observed input size. For non-linear regression, since computing it
  308. is quite expensive, it is only done at termination of the application. This
  309. means that the first execution uses history-based performance model to perform
  310. scheduling.
  311. @item
  312. Provided as an estimation from the application itself (@code{STARPU_COMMON} model type and @code{cost_function} field),
  313. see for instance
  314. @code{examples/common/blas_model.h} and @code{examples/common/blas_model.c}.
  315. @item
  316. Provided explicitly by the application (@code{STARPU_PER_ARCH} model type): the
  317. @code{.per_arch[arch][nimpl].cost_function} fields have to be filled with pointers to
  318. functions which return the expected duration of the task in micro-seconds, one
  319. per architecture.
  320. @end itemize
  321. For the @code{STARPU_HISTORY_BASED} and @code{STARPU_*REGRESSION_BASE},
  322. the total size of task data (both input and output) is used as an index by
  323. default. The @code{size_base} field of @code{struct starpu_perfmodel} however
  324. permits the application to override that, when for instance some of the data
  325. do not matter for task cost (e.g. mere reference table), or when using sparse
  326. structures (in which case it is the number of non-zeros which matter), or when
  327. there is some hidden parameter such as the number of iterations, etc.
  328. How to use schedulers which can benefit from such performance model is explained
  329. in @ref{Task scheduling policy}.
  330. The same can be done for task power consumption estimation, by setting the
  331. @code{power_model} field the same way as the @code{model} field. Note: for
  332. now, the application has to give to the power consumption performance model
  333. a name which is different from the execution time performance model.
  334. The application can request time estimations from the StarPU performance
  335. models by filling a task structure as usual without actually submitting
  336. it. The data handles can be created by calling @code{starpu_data_register}
  337. functions with a @code{NULL} pointer (and need to be unregistered as usual)
  338. and the desired data sizes. The @code{starpu_task_expected_length} and
  339. @code{starpu_task_expected_power} functions can then be called to get an
  340. estimation of the task duration on a given arch. @code{starpu_task_destroy}
  341. needs to be called to destroy the dummy task afterwards. See
  342. @code{tests/perfmodels/regression_based.c} for an example.
  343. @node Theoretical lower bound on execution time
  344. @section Theoretical lower bound on execution time
  345. For kernels with history-based performance models, StarPU can very easily provide a theoretical lower
  346. bound for the execution time of a whole set of tasks. See for
  347. instance @code{examples/lu/lu_example.c}: before submitting tasks,
  348. call @code{starpu_bound_start}, and after complete execution, call
  349. @code{starpu_bound_stop}. @code{starpu_bound_print_lp} or
  350. @code{starpu_bound_print_mps} can then be used to output a Linear Programming
  351. problem corresponding to the schedule of your tasks. Run it through
  352. @code{lp_solve} or any other linear programming solver, and that will give you a
  353. lower bound for the total execution time of your tasks. If StarPU was compiled
  354. with the glpk library installed, @code{starpu_bound_compute} can be used to
  355. solve it immediately and get the optimized minimum, in ms. Its @code{integer}
  356. parameter allows to decide whether integer resolution should be computed
  357. and returned too.
  358. The @code{deps} parameter tells StarPU whether to take tasks and implicit data
  359. dependencies into account. It must be understood that the linear programming
  360. problem size is quadratic with the number of tasks and thus the time to solve it
  361. will be very long, it could be minutes for just a few dozen tasks. You should
  362. probably use @code{lp_solve -timeout 1 test.pl -wmps test.mps} to convert the
  363. problem to MPS format and then use a better solver, @code{glpsol} might be
  364. better than @code{lp_solve} for instance (the @code{--pcost} option may be
  365. useful), but sometimes doesn't manage to converge. @code{cbc} might look
  366. slower, but it is parallel. Be sure to try at least all the @code{-B} options
  367. of @code{lp_solve}. For instance, we often just use
  368. @code{lp_solve -cc -B1 -Bb -Bg -Bp -Bf -Br -BG -Bd -Bs -BB -Bo -Bc -Bi} , and
  369. the @code{-gr} option can also be quite useful.
  370. Setting @code{deps} to 0 will only take into account the actual computations
  371. on processing units. It however still properly takes into account the varying
  372. performances of kernels and processing units, which is quite more accurate than
  373. just comparing StarPU performances with the fastest of the kernels being used.
  374. The @code{prio} parameter tells StarPU whether to simulate taking into account
  375. the priorities as the StarPU scheduler would, i.e. schedule prioritized
  376. tasks before less prioritized tasks, to check to which extend this results
  377. to a less optimal solution. This increases even more computation time.
  378. Note that for simplicity, all this however doesn't take into account data
  379. transfers, which are assumed to be completely overlapped.
  380. @node Insert Task Utility
  381. @section Insert Task Utility
  382. StarPU provides the wrapper function @code{starpu_insert_task} to ease
  383. the creation and submission of tasks.
  384. @deftypefun int starpu_insert_task (struct starpu_codelet *@var{cl}, ...)
  385. Create and submit a task corresponding to @var{cl} with the following
  386. arguments. The argument list must be zero-terminated.
  387. The arguments following the codelets can be of the following types:
  388. @itemize
  389. @item
  390. @code{STARPU_R}, @code{STARPU_W}, @code{STARPU_RW}, @code{STARPU_SCRATCH}, @code{STARPU_REDUX} an access mode followed by a data handle;
  391. @item
  392. the specific values @code{STARPU_VALUE}, @code{STARPU_CALLBACK},
  393. @code{STARPU_CALLBACK_ARG}, @code{STARPU_CALLBACK_WITH_ARG},
  394. @code{STARPU_PRIORITY}, followed by the appropriated objects as
  395. defined below.
  396. @end itemize
  397. Parameters to be passed to the codelet implementation are defined
  398. through the type @code{STARPU_VALUE}. The function
  399. @code{starpu_codelet_unpack_args} must be called within the codelet
  400. implementation to retrieve them.
  401. @end deftypefun
  402. @defmac STARPU_VALUE
  403. this macro is used when calling @code{starpu_insert_task}, and must be
  404. followed by a pointer to a constant value and the size of the constant
  405. @end defmac
  406. @defmac STARPU_CALLBACK
  407. this macro is used when calling @code{starpu_insert_task}, and must be
  408. followed by a pointer to a callback function
  409. @end defmac
  410. @defmac STARPU_CALLBACK_ARG
  411. this macro is used when calling @code{starpu_insert_task}, and must be
  412. followed by a pointer to be given as an argument to the callback
  413. function
  414. @end defmac
  415. @defmac STARPU_CALLBACK_WITH_ARG
  416. this macro is used when calling @code{starpu_insert_task}, and must be
  417. followed by two pointers: one to a callback function, and the other to
  418. be given as an argument to the callback function; this is equivalent
  419. to using both @code{STARPU_CALLBACK} and
  420. @code{STARPU_CALLBACK_WITH_ARG}
  421. @end defmac
  422. @defmac STARPU_PRIORITY
  423. this macro is used when calling @code{starpu_insert_task}, and must be
  424. followed by a integer defining a priority level
  425. @end defmac
  426. @deftypefun void starpu_codelet_pack_args ({char **}@var{arg_buffer}, {size_t *}@var{arg_buffer_size}, ...)
  427. Pack arguments of type @code{STARPU_VALUE} into a buffer which can be
  428. given to a codelet and later unpacked with the function
  429. @code{starpu_codelet_unpack_args} defined below.
  430. @end deftypefun
  431. @deftypefun void starpu_codelet_unpack_args ({void *}@var{cl_arg}, ...)
  432. Retrieve the arguments of type @code{STARPU_VALUE} associated to a
  433. task automatically created using the function
  434. @code{starpu_insert_task} defined above.
  435. @end deftypefun
  436. Here the implementation of the codelet:
  437. @smallexample
  438. void func_cpu(void *descr[], void *_args)
  439. @{
  440. int *x0 = (int *)STARPU_VARIABLE_GET_PTR(descr[0]);
  441. float *x1 = (float *)STARPU_VARIABLE_GET_PTR(descr[1]);
  442. int ifactor;
  443. float ffactor;
  444. starpu_codelet_unpack_args(_args, &ifactor, &ffactor);
  445. *x0 = *x0 * ifactor;
  446. *x1 = *x1 * ffactor;
  447. @}
  448. struct starpu_codelet mycodelet = @{
  449. .where = STARPU_CPU,
  450. .cpu_funcs = @{ func_cpu, NULL @},
  451. .nbuffers = 2,
  452. .modes = @{ STARPU_RW, STARPU_RW @}
  453. @};
  454. @end smallexample
  455. And the call to the @code{starpu_insert_task} wrapper:
  456. @smallexample
  457. starpu_insert_task(&mycodelet,
  458. STARPU_VALUE, &ifactor, sizeof(ifactor),
  459. STARPU_VALUE, &ffactor, sizeof(ffactor),
  460. STARPU_RW, data_handles[0], STARPU_RW, data_handles[1],
  461. 0);
  462. @end smallexample
  463. The call to @code{starpu_insert_task} is equivalent to the following
  464. code:
  465. @smallexample
  466. struct starpu_task *task = starpu_task_create();
  467. task->cl = &mycodelet;
  468. task->handles[0] = data_handles[0];
  469. task->handles[1] = data_handles[1];
  470. char *arg_buffer;
  471. size_t arg_buffer_size;
  472. starpu_codelet_pack_args(&arg_buffer, &arg_buffer_size,
  473. STARPU_VALUE, &ifactor, sizeof(ifactor),
  474. STARPU_VALUE, &ffactor, sizeof(ffactor),
  475. 0);
  476. task->cl_arg = arg_buffer;
  477. task->cl_arg_size = arg_buffer_size;
  478. int ret = starpu_task_submit(task);
  479. @end smallexample
  480. If some part of the task insertion depends on the value of some computation,
  481. the @code{STARPU_DATA_ACQUIRE_CB} macro can be very convenient. For
  482. instance, assuming that the index variable @code{i} was registered as handle
  483. @code{i_handle}:
  484. @smallexample
  485. /* Compute which portion we will work on, e.g. pivot */
  486. starpu_insert_task(&which_index, STARPU_W, i_handle, 0);
  487. /* And submit the corresponding task */
  488. STARPU_DATA_ACQUIRE_CB(i_handle, STARPU_R, starpu_insert_task(&work, STARPU_RW, A_handle[i], 0));
  489. @end smallexample
  490. The @code{STARPU_DATA_ACQUIRE_CB} macro submits an asynchronous request for
  491. acquiring data @code{i} for the main application, and will execute the code
  492. given as third parameter when it is acquired. In other words, as soon as the
  493. value of @code{i} computed by the @code{which_index} codelet can be read, the
  494. portion of code passed as third parameter of @code{STARPU_DATA_ACQUIRE_CB} will
  495. be executed, and is allowed to read from @code{i} to use it e.g. as an
  496. index. Note that this macro is only avaible when compiling StarPU with
  497. the compiler @code{gcc}.
  498. @node Data reduction
  499. @section Data reduction
  500. In various cases, some piece of data is used to accumulate intermediate
  501. results. For instances, the dot product of a vector, maximum/minimum finding,
  502. the histogram of a photograph, etc. When these results are produced along the
  503. whole machine, it would not be efficient to accumulate them in only one place,
  504. incurring data transmission each and access concurrency.
  505. StarPU provides a @code{STARPU_REDUX} mode, which permits to optimize
  506. that case: it will allocate a buffer on each memory node, and accumulate
  507. intermediate results there. When the data is eventually accessed in the normal
  508. @code{STARPU_R} mode, StarPU will collect the intermediate results in just one
  509. buffer.
  510. For this to work, the user has to use the
  511. @code{starpu_data_set_reduction_methods} to declare how to initialize these
  512. buffers, and how to assemble partial results.
  513. For instance, @code{cg} uses that to optimize its dot product: it first defines
  514. the codelets for initialization and reduction:
  515. @smallexample
  516. struct starpu_codelet bzero_variable_cl =
  517. @{
  518. .cpu_funcs = @{ bzero_variable_cpu, NULL @},
  519. .cuda_funcs = @{ bzero_variable_cuda, NULL @},
  520. .nbuffers = 1,
  521. @}
  522. static void accumulate_variable_cpu(void *descr[], void *cl_arg)
  523. @{
  524. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  525. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  526. *v_dst = *v_dst + *v_src;
  527. @}
  528. static void accumulate_variable_cuda(void *descr[], void *cl_arg)
  529. @{
  530. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  531. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  532. cublasaxpy(1, (double)1.0, v_src, 1, v_dst, 1);
  533. cudaStreamSynchronize(starpu_cuda_get_local_stream());
  534. @}
  535. struct starpu_codelet accumulate_variable_cl =
  536. @{
  537. .cpu_funcs = @{ accumulate_variable_cpu, NULL @},
  538. .cuda_funcs = @{ accumulate_variable_cuda, NULL @},
  539. .nbuffers = 1,
  540. @}
  541. @end smallexample
  542. and attaches them as reduction methods for its dtq handle:
  543. @smallexample
  544. starpu_data_set_reduction_methods(dtq_handle,
  545. &accumulate_variable_cl, &bzero_variable_cl);
  546. @end smallexample
  547. and dtq_handle can now be used in @code{STARPU_REDUX} mode for the dot products
  548. with partitioned vectors:
  549. @smallexample
  550. int dots(starpu_data_handle_t v1, starpu_data_handle_t v2,
  551. starpu_data_handle_t s, unsigned nblocks)
  552. @{
  553. starpu_insert_task(&bzero_variable_cl, STARPU_W, s, 0);
  554. for (b = 0; b < nblocks; b++)
  555. starpu_insert_task(&dot_kernel_cl,
  556. STARPU_RW, s,
  557. STARPU_R, starpu_data_get_sub_data(v1, 1, b),
  558. STARPU_R, starpu_data_get_sub_data(v2, 1, b),
  559. 0);
  560. @}
  561. @end smallexample
  562. The @code{cg} example also uses reduction for the blocked gemv kernel, leading
  563. to yet more relaxed dependencies and more parallelism.
  564. @node Parallel Tasks
  565. @section Parallel Tasks
  566. StarPU can leverage existing parallel computation libraries by the means of
  567. parallel tasks. A parallel task is a task which gets worked on by a set of CPUs
  568. (called a parallel or combined worker) at the same time, by using an existing
  569. parallel CPU implementation of the computation to be achieved. This can also be
  570. useful to improve the load balance between slow CPUs and fast GPUs: since CPUs
  571. work collectively on a single task, the completion time of tasks on CPUs become
  572. comparable to the completion time on GPUs, thus relieving from granularity
  573. discrepancy concerns. Hwloc support needs to be enabled to get good performance,
  574. otherwise StarPU will not know how to better group cores.
  575. Two modes of execution exist to accomodate with existing usages.
  576. @subsection Fork-mode parallel tasks
  577. In the Fork mode, StarPU will call the codelet function on one
  578. of the CPUs of the combined worker. The codelet function can use
  579. @code{starpu_combined_worker_get_size()} to get the number of threads it is
  580. allowed to start to achieve the computation. The CPU binding mask for the whole
  581. set of CPUs is already enforced, so that threads created by the function will
  582. inherit the mask, and thus execute where StarPU expected, the OS being in charge
  583. of choosing how to schedule threads on the corresponding CPUs. The application
  584. can also choose to bind threads by hand, using e.g. sched_getaffinity to know
  585. the CPU binding mask that StarPU chose.
  586. For instance, using OpenMP (full source is available in
  587. @code{examples/openmp/vector_scal.c}):
  588. @example
  589. void scal_cpu_func(void *buffers[], void *_args)
  590. @{
  591. unsigned i;
  592. float *factor = _args;
  593. struct starpu_vector_interface *vector = buffers[0];
  594. unsigned n = STARPU_VECTOR_GET_NX(vector);
  595. float *val = (float *)STARPU_VECTOR_GET_PTR(vector);
  596. #pragma omp parallel for num_threads(starpu_combined_worker_get_size())
  597. for (i = 0; i < n; i++)
  598. val[i] *= *factor;
  599. @}
  600. static struct starpu_codelet cl =
  601. @{
  602. .modes = @{ STARPU_RW @},
  603. .where = STARPU_CPU,
  604. .type = STARPU_FORKJOIN,
  605. .max_parallelism = INT_MAX,
  606. .cpu_funcs = @{scal_cpu_func, NULL@},
  607. .nbuffers = 1,
  608. @};
  609. @end example
  610. Other examples include for instance calling a BLAS parallel CPU implementation
  611. (see @code{examples/mult/xgemm.c}).
  612. @subsection SPMD-mode parallel tasks
  613. In the SPMD mode, StarPU will call the codelet function on
  614. each CPU of the combined worker. The codelet function can use
  615. @code{starpu_combined_worker_get_size()} to get the total number of CPUs
  616. involved in the combined worker, and thus the number of calls that are made in
  617. parallel to the function, and @code{starpu_combined_worker_get_rank()} to get
  618. the rank of the current CPU within the combined worker. For instance:
  619. @example
  620. static void func(void *buffers[], void *args)
  621. @{
  622. unsigned i;
  623. float *factor = _args;
  624. struct starpu_vector_interface *vector = buffers[0];
  625. unsigned n = STARPU_VECTOR_GET_NX(vector);
  626. float *val = (float *)STARPU_VECTOR_GET_PTR(vector);
  627. /* Compute slice to compute */
  628. unsigned m = starpu_combined_worker_get_size();
  629. unsigned j = starpu_combined_worker_get_rank();
  630. unsigned slice = (n+m-1)/m;
  631. for (i = j * slice; i < (j+1) * slice && i < n; i++)
  632. val[i] *= *factor;
  633. @}
  634. static struct starpu_codelet cl =
  635. @{
  636. .modes = @{ STARPU_RW @},
  637. .where = STARP_CPU,
  638. .type = STARPU_SPMD,
  639. .max_parallelism = INT_MAX,
  640. .cpu_funcs = @{ func, NULL @},
  641. .nbuffers = 1,
  642. @}
  643. @end example
  644. Of course, this trivial example will not really benefit from parallel task
  645. execution, and was only meant to be simple to understand. The benefit comes
  646. when the computation to be done is so that threads have to e.g. exchange
  647. intermediate results, or write to the data in a complex but safe way in the same
  648. buffer.
  649. @subsection Parallel tasks performance
  650. To benefit from parallel tasks, a parallel-task-aware StarPU scheduler has to
  651. be used. When exposed to codelets with a Fork or SPMD flag, the @code{pheft}
  652. (parallel-heft) and @code{pgreedy} (parallel greedy) schedulers will indeed also
  653. try to execute tasks with several CPUs. It will automatically try the various
  654. available combined worker sizes and thus be able to avoid choosing a large
  655. combined worker if the codelet does not actually scale so much.
  656. @subsection Combined worker sizes
  657. By default, StarPU creates combined workers according to the architecture
  658. structure as detected by hwloc. It means that for each object of the hwloc
  659. topology (NUMA node, socket, cache, ...) a combined worker will be created. If
  660. some nodes of the hierarchy have a big arity (e.g. many cores in a socket
  661. without a hierarchy of shared caches), StarPU will create combined workers of
  662. intermediate sizes.
  663. The user can give some hints to StarPU about combined workers sizes to favor.
  664. This can be done by using the environment variables STARPU_MIN_WORKERSIZE and
  665. STARPU_MAX_WORKERSIZE. When set, they will force StarPU to create the biggest
  666. combined workers possible without overstepping the defined boundaries.
  667. However, StarPU will create the remaining combined workers without abiding by
  668. the rules if not possible.
  669. For example : if the user specify a minimum and maximum combined workers size
  670. of 3 on a machine containing 8 CPUs, StarPU will create a combined worker of
  671. size 2 beside the combined workers of size 3.
  672. @subsection Concurrent parallel tasks
  673. Unfortunately, many environments and librairies do not support concurrent
  674. calls.
  675. For instance, most OpenMP implementations (including the main ones) do not
  676. support concurrent @code{pragma omp parallel} statements without nesting them in
  677. another @code{pragma omp parallel} statement, but StarPU does not yet support
  678. creating its CPU workers by using such pragma.
  679. Other parallel libraries are also not safe when being invoked concurrently
  680. from different threads, due to the use of global variables in their sequential
  681. sections for instance.
  682. The solution is then to use only one combined worker at a time. This can be
  683. done by setting @code{single_combined_worker} to 1 in the @code{starpu_conf}
  684. structure, or setting the @code{STARPU_SINGLE_COMBINED_WORKER} environment
  685. variable to 1. StarPU will then run only one parallel task at a time.
  686. @node Debugging
  687. @section Debugging
  688. StarPU provides several tools to help debugging aplications. Execution traces
  689. can be generated and displayed graphically, see @ref{Generating traces}. Some
  690. gdb helpers are also provided to show the whole StarPU state:
  691. @smallexample
  692. (gdb) source tools/gdbinit
  693. (gdb) help starpu
  694. @end smallexample
  695. @node The multiformat interface
  696. @section The multiformat interface
  697. It may be interesting to represent the same piece of data using two different
  698. data structures: one that would only be used on CPUs, and one that would only
  699. be used on GPUs. This can be done by using the multiformat interface. StarPU
  700. will be able to convert data from one data structure to the other when needed.
  701. Note that the heft scheduler is the only one optimized for this interface. The
  702. user must provide StarPU with conversion codelets:
  703. @cartouche
  704. @smallexample
  705. #define NX 1024
  706. struct point array_of_structs[NX];
  707. starpu_data_handle_t handle;
  708. /*
  709. * The conversion of a piece of data is itself a task, though it is created,
  710. * submitted and destroyed by StarPU internals and not by the user. Therefore,
  711. * we have to define two codelets.
  712. * Note that for now the conversion from the CPU format to the GPU format has to
  713. * be executed on the GPU, and the conversion from the GPU to the CPU has to be
  714. * executed on the CPU.
  715. */
  716. #ifdef STARPU_USE_OPENCL
  717. void cpu_to_opencl_opencl_func(void *buffers[], void *args);
  718. struct starpu_codelet cpu_to_opencl_cl = @{
  719. .where = STARPU_OPENCL,
  720. .opencl_funcs = @{ cpu_to_opencl_opencl_func, NULL @},
  721. .nbuffers = 1,
  722. .modes = @{ STARPU_RW @}
  723. @};
  724. void opencl_to_cpu_func(void *buffers[], void *args);
  725. struct starpu_codelet opencl_to_cpu_cl = @{
  726. .where = STARPU_CPU,
  727. .cpu_funcs = @{ opencl_to_cpu_func, NULL @},
  728. .nbuffers = 1,
  729. .modes = @{ STARPU_RW @}
  730. @};
  731. #endif
  732. struct starpu_multiformat_data_interface_ops format_ops = @{
  733. #ifdef STARPU_USE_OPENCL
  734. .opencl_elemsize = 2 * sizeof(float),
  735. .cpu_to_opencl_cl = &cpu_to_opencl_cl,
  736. .opencl_to_cpu_cl = &opencl_to_cpu_cl,
  737. #endif
  738. .cpu_elemsize = 2 * sizeof(float),
  739. ...
  740. @};
  741. starpu_multiformat_data_register(handle, 0, &array_of_structs, NX, &format_ops);
  742. @end smallexample
  743. @end cartouche
  744. Kernels can be written almost as for any other interface. Note that
  745. STARPU_MULTIFORMAT_GET_CPU_PTR shall only be used for CPU kernels. CUDA kernels
  746. must use STARPU_MULTIFORMAT_GET_CUDA_PTR, and OpenCL kernels must use
  747. STARPU_MULTIFORMAT_GET_OPENCL_PTR. STARPU_MULTIFORMAT_GET_NX may be used in any
  748. kind of kernel.
  749. @cartouche
  750. @smallexample
  751. static void
  752. multiformat_scal_cpu_func(void *buffers[], void *args)
  753. @{
  754. struct point *aos;
  755. unsigned int n;
  756. aos = STARPU_MULTIFORMAT_GET_CPU_PTR(buffers[0]);
  757. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  758. ...
  759. @}
  760. extern "C" void multiformat_scal_cuda_func(void *buffers[], void *_args)
  761. @{
  762. unsigned int n;
  763. struct struct_of_arrays *soa;
  764. soa = (struct struct_of_arrays *) STARPU_MULTIFORMAT_GET_CUDA_PTR(buffers[0]);
  765. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  766. ...
  767. @}
  768. @end smallexample
  769. @end cartouche
  770. A full example may be found in @code{examples/basic_examples/multiformat.c}.
  771. @node On-GPU rendering
  772. @section On-GPU rendering
  773. Graphical-oriented applications need to draw the result of their computations,
  774. typically on the very GPU where these happened. Technologies such as OpenGL/CUDA
  775. interoperability permit to let CUDA directly work on the OpenGL buffers, making
  776. them thus immediately ready for drawing, by mapping OpenGL buffer, textures or
  777. renderbuffer objects into CUDA. CUDA however imposes some technical
  778. constraints: peer memcpy has to be disabled, and the thread that runs OpenGL has
  779. to be the one that runs CUDA computations for that GPU.
  780. To achieve this with StarPU, pass the @code{--disable-cuda-memcpy-peer} option
  781. to @code{./configure} (TODO: make it dynamic), the interoperability mode has to
  782. be enabled by using the @code{cuda_opengl_interoperability} field of the
  783. @code{starpu_conf} structure, and the driver loop has to be run by
  784. the application, by using the @code{not_launched_drivers} field of
  785. @code{starpu_conf} to prevent StarPU from running it in a separate thread, and
  786. by using @code{starpu_run_driver} to run the loop. The @code{gl_interop} example
  787. shows how it articulates in a simple case, where rendering is done in task
  788. callbacks. TODO: provide glutIdleFunc alternative.
  789. Then, to use an OpenGL buffer as a CUDA data, StarPU simply needs to be given
  790. the CUDA pointer at registration, for instance:
  791. @cartouche
  792. @smallexample
  793. for (workerid = 0; workerid < starpu_worker_get_count(); workerid++)
  794. if (starpu_worker_get_type(workerid) == STARPU_CUDA_WORKER)
  795. break;
  796. cudaGraphicsResourceGetMappedPointer((void**)&output, &num_bytes, resource);
  797. starpu_vector_data_register(&handle, starpu_worker_get_memory_node(workerid), output, num_bytes / sizeof(float4), sizeof(float4));
  798. starpu_insert_task(&cl, STARPU_RW, handle, 0);
  799. @end smallexample
  800. @end cartouche
  801. and display it e.g. in the callback function.
  802. @node More examples
  803. @section More examples
  804. More examples are available in the StarPU sources in the @code{examples/}
  805. directory. Simple examples include:
  806. @table @asis
  807. @item @code{incrementer/}:
  808. Trivial incrementation test.
  809. @item @code{basic_examples/}:
  810. Simple documented Hello world (as shown in @ref{Hello World}), vector/scalar product (as shown
  811. in @ref{Vector Scaling on an Hybrid CPU/GPU Machine}), matrix
  812. product examples (as shown in @ref{Performance model example}), an example using the blocked matrix data
  813. interface, an example using the variable data interface, and an example
  814. using different formats on CPUs and GPUs.
  815. @item @code{matvecmult/}:
  816. OpenCL example from NVidia, adapted to StarPU.
  817. @item @code{axpy/}:
  818. AXPY CUBLAS operation adapted to StarPU.
  819. @item @code{fortran/}:
  820. Example of Fortran bindings.
  821. @end table
  822. More advanced examples include:
  823. @table @asis
  824. @item @code{filters/}:
  825. Examples using filters, as shown in @ref{Partitioning Data}.
  826. @item @code{lu/}:
  827. LU matrix factorization, see for instance @code{xlu_implicit.c}
  828. @item @code{cholesky/}:
  829. Cholesky matrix factorization, see for instance @code{cholesky_implicit.c}.
  830. @end table