advanced-examples.texi 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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, 2013 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 example::
  14. * Insert Task Utility::
  15. * Data reduction::
  16. * Temporary buffers::
  17. * Parallel Tasks::
  18. * Debugging::
  19. * The multiformat interface::
  20. * Using the Driver API::
  21. * Defining a New Scheduling Policy::
  22. * On-GPU rendering::
  23. * Defining a New Data Interface::
  24. * Setting the Data Handles for a Task::
  25. * More examples:: More examples shipped with StarPU
  26. @end menu
  27. @node Using multiple implementations of a codelet
  28. @section Using multiple implementations of a codelet
  29. One may want to write multiple implementations of a codelet for a single type of
  30. device and let StarPU choose which one to run. As an example, we will show how
  31. to use SSE to scale a vector. The codelet can be written as follows:
  32. @cartouche
  33. @smallexample
  34. #include <xmmintrin.h>
  35. void scal_sse_func(void *buffers[], void *cl_arg)
  36. @{
  37. float *vector = (float *) STARPU_VECTOR_GET_PTR(buffers[0]);
  38. unsigned int n = STARPU_VECTOR_GET_NX(buffers[0]);
  39. unsigned int n_iterations = n/4;
  40. if (n % 4 != 0)
  41. n_iterations++;
  42. __m128 *VECTOR = (__m128*) vector;
  43. __m128 factor __attribute__((aligned(16)));
  44. factor = _mm_set1_ps(*(float *) cl_arg);
  45. unsigned int i;
  46. for (i = 0; i < n_iterations; i++)
  47. VECTOR[i] = _mm_mul_ps(factor, VECTOR[i]);
  48. @}
  49. @end smallexample
  50. @end cartouche
  51. @cartouche
  52. @smallexample
  53. struct starpu_codelet cl = @{
  54. .where = STARPU_CPU,
  55. .cpu_funcs = @{ scal_cpu_func, scal_sse_func, NULL @},
  56. .cpu_funcs_name = @{ "scal_cpu_func", "scal_sse_func", NULL @},
  57. .nbuffers = 1,
  58. .modes = @{ STARPU_RW @}
  59. @};
  60. @end smallexample
  61. @end cartouche
  62. Schedulers which are multi-implementation aware (only @code{dmda} and
  63. @code{pheft} for now) will use the performance models of all the
  64. implementations it was given, and pick the one that seems to be the fastest.
  65. @node Enabling implementation according to capabilities
  66. @section Enabling implementation according to capabilities
  67. Some implementations may not run on some devices. For instance, some CUDA
  68. devices do not support double floating point precision, and thus the kernel
  69. execution would just fail; or the device may not have enough shared memory for
  70. the implementation being used. The @code{can_execute} field of the @code{struct
  71. starpu_codelet} structure permits to express this. For instance:
  72. @cartouche
  73. @smallexample
  74. static int can_execute(unsigned workerid, struct starpu_task *task, unsigned nimpl)
  75. @{
  76. const struct cudaDeviceProp *props;
  77. if (starpu_worker_get_type(workerid) == STARPU_CPU_WORKER)
  78. return 1;
  79. /* Cuda device */
  80. props = starpu_cuda_get_device_properties(workerid);
  81. if (props->major >= 2 || props->minor >= 3)
  82. /* At least compute capability 1.3, supports doubles */
  83. return 1;
  84. /* Old card, does not support doubles */
  85. return 0;
  86. @}
  87. struct starpu_codelet cl = @{
  88. .where = STARPU_CPU|STARPU_CUDA,
  89. .can_execute = can_execute,
  90. .cpu_funcs = @{ cpu_func, NULL @},
  91. .cpu_funcs_name = @{ "cpu_func", NULL @},
  92. .cuda_funcs = @{ gpu_func, NULL @}
  93. .nbuffers = 1,
  94. .modes = @{ STARPU_RW @}
  95. @};
  96. @end smallexample
  97. @end cartouche
  98. This can be essential e.g. when running on a machine which mixes various models
  99. of CUDA devices, to take benefit from the new models without crashing on old models.
  100. Note: the @code{can_execute} function is called by the scheduler each time it
  101. tries to match a task with a worker, and should thus be very fast. The
  102. @code{starpu_cuda_get_device_properties} provides a quick access to CUDA
  103. properties of CUDA devices to achieve such efficiency.
  104. Another example is compiling CUDA code for various compute capabilities,
  105. resulting with two CUDA functions, e.g. @code{scal_gpu_13} for compute capability
  106. 1.3, and @code{scal_gpu_20} for compute capability 2.0. Both functions can be
  107. provided to StarPU by using @code{cuda_funcs}, and @code{can_execute} can then be
  108. used to rule out the @code{scal_gpu_20} variant on a CUDA device which
  109. will not be able to execute it:
  110. @cartouche
  111. @smallexample
  112. static int can_execute(unsigned workerid, struct starpu_task *task, unsigned nimpl)
  113. @{
  114. const struct cudaDeviceProp *props;
  115. if (starpu_worker_get_type(workerid) == STARPU_CPU_WORKER)
  116. return 1;
  117. /* Cuda device */
  118. if (nimpl == 0)
  119. /* Trying to execute the 1.3 capability variant, we assume it is ok in all cases. */
  120. return 1;
  121. /* Trying to execute the 2.0 capability variant, check that the card can do it. */
  122. props = starpu_cuda_get_device_properties(workerid);
  123. if (props->major >= 2 || props->minor >= 0)
  124. /* At least compute capability 2.0, can run it */
  125. return 1;
  126. /* Old card, does not support 2.0, will not be able to execute the 2.0 variant. */
  127. return 0;
  128. @}
  129. struct starpu_codelet cl = @{
  130. .where = STARPU_CPU|STARPU_CUDA,
  131. .can_execute = can_execute,
  132. .cpu_funcs = @{ cpu_func, NULL @},
  133. .cpu_funcs_name = @{ "cpu_func", NULL @},
  134. .cuda_funcs = @{ scal_gpu_13, scal_gpu_20, NULL @},
  135. .nbuffers = 1,
  136. .modes = @{ STARPU_RW @}
  137. @};
  138. @end smallexample
  139. @end cartouche
  140. Note: the most generic variant should be provided first, as some schedulers are
  141. not able to try the different variants.
  142. @node Task and Worker Profiling
  143. @section Task and Worker Profiling
  144. A full example showing how to use the profiling API is available in
  145. the StarPU sources in the directory @code{examples/profiling/}.
  146. @cartouche
  147. @smallexample
  148. struct starpu_task *task = starpu_task_create();
  149. task->cl = &cl;
  150. task->synchronous = 1;
  151. /* We will destroy the task structure by hand so that we can
  152. * query the profiling info before the task is destroyed. */
  153. task->destroy = 0;
  154. /* Submit and wait for completion (since synchronous was set to 1) */
  155. starpu_task_submit(task);
  156. /* The task is finished, get profiling information */
  157. struct starpu_profiling_task_info *info = task->profiling_info;
  158. /* How much time did it take before the task started ? */
  159. double delay += starpu_timing_timespec_delay_us(&info->submit_time, &info->start_time);
  160. /* How long was the task execution ? */
  161. double length += starpu_timing_timespec_delay_us(&info->start_time, &info->end_time);
  162. /* We don't need the task structure anymore */
  163. starpu_task_destroy(task);
  164. @end smallexample
  165. @end cartouche
  166. @cartouche
  167. @smallexample
  168. /* Display the occupancy of all workers during the test */
  169. int worker;
  170. for (worker = 0; worker < starpu_worker_get_count(); worker++)
  171. @{
  172. struct starpu_profiling_worker_info worker_info;
  173. int ret = starpu_profiling_worker_get_info(worker, &worker_info);
  174. STARPU_ASSERT(!ret);
  175. double total_time = starpu_timing_timespec_to_us(&worker_info.total_time);
  176. double executing_time = starpu_timing_timespec_to_us(&worker_info.executing_time);
  177. double sleeping_time = starpu_timing_timespec_to_us(&worker_info.sleeping_time);
  178. double overhead_time = total_time - executing_time - sleeping_time;
  179. float executing_ratio = 100.0*executing_time/total_time;
  180. float sleeping_ratio = 100.0*sleeping_time/total_time;
  181. float overhead_ratio = 100.0 - executing_ratio - sleeping_ratio;
  182. char workername[128];
  183. starpu_worker_get_name(worker, workername, 128);
  184. fprintf(stderr, "Worker %s:\n", workername);
  185. fprintf(stderr, "\ttotal time: %.2lf ms\n", total_time*1e-3);
  186. fprintf(stderr, "\texec time: %.2lf ms (%.2f %%)\n", executing_time*1e-3,
  187. executing_ratio);
  188. fprintf(stderr, "\tblocked time: %.2lf ms (%.2f %%)\n", sleeping_time*1e-3,
  189. sleeping_ratio);
  190. fprintf(stderr, "\toverhead time: %.2lf ms (%.2f %%)\n", overhead_time*1e-3,
  191. overhead_ratio);
  192. @}
  193. @end smallexample
  194. @end cartouche
  195. @node Partitioning Data
  196. @section Partitioning Data
  197. An existing piece of data can be partitioned in sub parts to be used by different tasks, for instance:
  198. @cartouche
  199. @smallexample
  200. int vector[NX];
  201. starpu_data_handle_t handle;
  202. /* Declare data to StarPU */
  203. starpu_vector_data_register(&handle, 0, (uintptr_t)vector,
  204. NX, sizeof(vector[0]));
  205. /* Partition the vector in PARTS sub-vectors */
  206. starpu_data_filter f =
  207. @{
  208. .filter_func = starpu_vector_filter_block,
  209. .nchildren = PARTS
  210. @};
  211. starpu_data_partition(handle, &f);
  212. @end smallexample
  213. @end cartouche
  214. The task submission then uses @code{starpu_data_get_sub_data} to retrieve the
  215. sub-handles to be passed as tasks parameters.
  216. @cartouche
  217. @smallexample
  218. /* Submit a task on each sub-vector */
  219. for (i=0; i<starpu_data_get_nb_children(handle); i++) @{
  220. /* Get subdata number i (there is only 1 dimension) */
  221. starpu_data_handle_t sub_handle = starpu_data_get_sub_data(handle, 1, i);
  222. struct starpu_task *task = starpu_task_create();
  223. task->handles[0] = sub_handle;
  224. task->cl = &cl;
  225. task->synchronous = 1;
  226. task->cl_arg = &factor;
  227. task->cl_arg_size = sizeof(factor);
  228. starpu_task_submit(task);
  229. @}
  230. @end smallexample
  231. @end cartouche
  232. Partitioning can be applied several times, see
  233. @code{examples/basic_examples/mult.c} and @code{examples/filters/}.
  234. Wherever the whole piece of data is already available, the partitioning will
  235. be done in-place, i.e. without allocating new buffers but just using pointers
  236. inside the existing copy. This is particularly important to be aware of when
  237. using OpenCL, where the kernel parameters are not pointers, but handles. The
  238. kernel thus needs to be also passed the offset within the OpenCL buffer:
  239. @cartouche
  240. @smallexample
  241. void opencl_func(void *buffers[], void *cl_arg)
  242. @{
  243. cl_mem vector = (cl_mem) STARPU_VECTOR_GET_DEV_HANDLE(buffers[0]);
  244. unsigned offset = STARPU_BLOCK_GET_OFFSET(buffers[0]);
  245. ...
  246. clSetKernelArg(kernel, 0, sizeof(vector), &vector);
  247. clSetKernelArg(kernel, 1, sizeof(offset), &offset);
  248. ...
  249. @}
  250. @end smallexample
  251. @end cartouche
  252. And the kernel has to shift from the pointer passed by the OpenCL driver:
  253. @cartouche
  254. @smallexample
  255. __kernel void opencl_kernel(__global int *vector, unsigned offset)
  256. @{
  257. block = (__global void *)block + offset;
  258. ...
  259. @}
  260. @end smallexample
  261. @end cartouche
  262. StarPU provides various interfaces and filters for matrices, vectors, etc.,
  263. but applications can also write their own data interfaces and filters, see
  264. @code{examples/interface} and @code{examples/filters/custom_mf} for an example.
  265. @node Performance model example
  266. @section Performance model example
  267. To achieve good scheduling, StarPU scheduling policies need to be able to
  268. estimate in advance the duration of a task. This is done by giving to codelets
  269. a performance model, by defining a @code{starpu_perfmodel} structure and
  270. providing its address in the @code{model} field of the @code{struct starpu_codelet}
  271. structure. The @code{symbol} and @code{type} fields of @code{starpu_perfmodel}
  272. are mandatory, to give a name to the model, and the type of the model, since
  273. there are several kinds of performance models. For compatibility, make sure to
  274. initialize the whole structure to zero, either by using explicit memset, or by
  275. letting the compiler implicitly do it as examplified below.
  276. @itemize
  277. @item
  278. Measured at runtime (@code{STARPU_HISTORY_BASED} model type). This assumes that for a
  279. given set of data input/output sizes, the performance will always be about the
  280. same. This is very true for regular kernels on GPUs for instance (<0.1% error),
  281. and just a bit less true on CPUs (~=1% error). This also assumes that there are
  282. few different sets of data input/output sizes. StarPU will then keep record of
  283. the average time of previous executions on the various processing units, and use
  284. it as an estimation. History is done per task size, by using a hash of the input
  285. and ouput sizes as an index.
  286. It will also save it in @code{$STARPU_HOME/.starpu/sampling/codelets}
  287. for further executions, and can be observed by using the
  288. @code{starpu_perfmodel_display} command, or drawn by using
  289. the @code{starpu_perfmodel_plot} (@pxref{Performance model calibration}). The
  290. models are indexed by machine name. To
  291. share the models between machines (e.g. for a homogeneous cluster), use
  292. @code{export STARPU_HOSTNAME=some_global_name}. Measurements are only done
  293. when using a task scheduler which makes use of it, such as
  294. @code{dmda}. Measurements can also be provided explicitly by the application, by
  295. using the @code{starpu_perfmodel_update_history} function.
  296. The following is a small code example.
  297. If e.g. the code is recompiled with other compilation options, or several
  298. variants of the code are used, the symbol string should be changed to reflect
  299. that, in order to recalibrate a new model from zero. The symbol string can even
  300. be constructed dynamically at execution time, as long as this is done before
  301. submitting any task using it.
  302. @cartouche
  303. @smallexample
  304. static struct starpu_perfmodel mult_perf_model = @{
  305. .type = STARPU_HISTORY_BASED,
  306. .symbol = "mult_perf_model"
  307. @};
  308. struct starpu_codelet cl = @{
  309. .where = STARPU_CPU,
  310. .cpu_funcs = @{ cpu_mult, NULL @},
  311. .cpu_funcs_name = @{ "cpu_mult", NULL @},
  312. .nbuffers = 3,
  313. .modes = @{ STARPU_R, STARPU_R, STARPU_W @},
  314. /* for the scheduling policy to be able to use performance models */
  315. .model = &mult_perf_model
  316. @};
  317. @end smallexample
  318. @end cartouche
  319. @item
  320. Measured at runtime and refined by regression (@code{STARPU_*REGRESSION_BASED}
  321. model type). This still assumes performance regularity, but works
  322. with various data input sizes, by applying regression over observed
  323. execution times. STARPU_REGRESSION_BASED uses an a*n^b regression
  324. form, STARPU_NL_REGRESSION_BASED uses an a*n^b+c (more precise than
  325. STARPU_REGRESSION_BASED, but costs a lot more to compute).
  326. For instance,
  327. @code{tests/perfmodels/regression_based.c} uses a regression-based performance
  328. model for the @code{memset} operation.
  329. Of course, the application has to issue
  330. tasks with varying size so that the regression can be computed. StarPU will not
  331. trust the regression unless there is at least 10% difference between the minimum
  332. and maximum observed input size. It can be useful to set the
  333. @code{STARPU_CALIBRATE} environment variable to @code{1} and run the application
  334. on varying input sizes with @code{STARPU_SCHED} set to @code{eager} scheduler,
  335. so as to feed the performance model for a variety of
  336. inputs. The application can also provide the measurements explictly by using
  337. @code{starpu_perfmodel_update_history}. The @code{starpu_perfmodel_display} and
  338. @code{starpu_perfmodel_plot}
  339. tools can be used to observe how much the performance model is calibrated (@pxref{Performance model calibration}); when
  340. their output look good, @code{STARPU_CALIBRATE} can be reset to @code{0} to let
  341. StarPU use the resulting performance model without recording new measures, and
  342. @code{STARPU_SCHED} can be set to @code{dmda} to benefit from the performance models. If
  343. the data input sizes vary a lot, it is really important to set
  344. @code{STARPU_CALIBRATE} to @code{0}, otherwise StarPU will continue adding the
  345. measures, and result with a very big performance model, which will take time a
  346. lot of time to load and save.
  347. For non-linear regression, since computing it
  348. is quite expensive, it is only done at termination of the application. This
  349. means that the first execution of the application will use only history-based
  350. performance model to perform scheduling, without using regression.
  351. @item
  352. Provided as an estimation from the application itself (@code{STARPU_COMMON} model type and @code{cost_function} field),
  353. see for instance
  354. @code{examples/common/blas_model.h} and @code{examples/common/blas_model.c}.
  355. @item
  356. Provided explicitly by the application (@code{STARPU_PER_ARCH} model type): the
  357. @code{.per_arch[arch][nimpl].cost_function} fields have to be filled with pointers to
  358. functions which return the expected duration of the task in micro-seconds, one
  359. per architecture.
  360. @end itemize
  361. For the @code{STARPU_HISTORY_BASED} and @code{STARPU_*REGRESSION_BASE},
  362. the total size of task data (both input and output) is used as an index by
  363. default. The @code{size_base} field of @code{struct starpu_perfmodel} however
  364. permits the application to override that, when for instance some of the data
  365. do not matter for task cost (e.g. mere reference table), or when using sparse
  366. structures (in which case it is the number of non-zeros which matter), or when
  367. there is some hidden parameter such as the number of iterations, etc. The
  368. @code{examples/pi} examples uses this to include the number of iterations in the
  369. base.
  370. How to use schedulers which can benefit from such performance model is explained
  371. in @ref{Task scheduling policy}.
  372. The same can be done for task power consumption estimation, by setting the
  373. @code{power_model} field the same way as the @code{model} field. Note: for
  374. now, the application has to give to the power consumption performance model
  375. a name which is different from the execution time performance model.
  376. The application can request time estimations from the StarPU performance
  377. models by filling a task structure as usual without actually submitting
  378. it. The data handles can be created by calling @code{starpu_*_data_register}
  379. functions with a @code{NULL} pointer and @code{-1} node and the
  380. desired data sizes, and need to be unregistered as usual. The
  381. @code{starpu_task_expected_length} and @code{starpu_task_expected_power}
  382. functions can then be called to get an estimation of the task cost on a given
  383. arch. @code{starpu_task_footprint} can also be used to get the footprint used
  384. for indexing history-based performance models.
  385. @code{starpu_task_destroy}
  386. needs to be called to destroy the dummy task afterwards. See
  387. @code{tests/perfmodels/regression_based.c} for an example.
  388. @node Theoretical lower bound on execution time example
  389. @section Theoretical lower bound on execution time
  390. For kernels with history-based performance models (and provided that they are completely calibrated), StarPU can very easily provide a theoretical lower
  391. bound for the execution time of a whole set of tasks. See for
  392. instance @code{examples/lu/lu_example.c}: before submitting tasks,
  393. call @code{starpu_bound_start}, and after complete execution, call
  394. @code{starpu_bound_stop}. @code{starpu_bound_print_lp} or
  395. @code{starpu_bound_print_mps} can then be used to output a Linear Programming
  396. problem corresponding to the schedule of your tasks. Run it through
  397. @code{lp_solve} or any other linear programming solver, and that will give you a
  398. lower bound for the total execution time of your tasks. If StarPU was compiled
  399. with the glpk library installed, @code{starpu_bound_compute} can be used to
  400. solve it immediately and get the optimized minimum, in ms. Its @code{integer}
  401. parameter allows to decide whether integer resolution should be computed
  402. and returned too.
  403. The @code{deps} parameter tells StarPU whether to take tasks, implicit data, and tag
  404. dependencies into account. Tags released in a callback or similar
  405. are not taken into account, only tags associated with a task are.
  406. It must be understood that the linear programming
  407. problem size is quadratic with the number of tasks and thus the time to solve it
  408. will be very long, it could be minutes for just a few dozen tasks. You should
  409. probably use @code{lp_solve -timeout 1 test.pl -wmps test.mps} to convert the
  410. problem to MPS format and then use a better solver, @code{glpsol} might be
  411. better than @code{lp_solve} for instance (the @code{--pcost} option may be
  412. useful), but sometimes doesn't manage to converge. @code{cbc} might look
  413. slower, but it is parallel. For @code{lp_solve}, be sure to try at least all the
  414. @code{-B} options. For instance, we often just use @code{lp_solve -cc -B1 -Bb
  415. -Bg -Bp -Bf -Br -BG -Bd -Bs -BB -Bo -Bc -Bi} , and the @code{-gr} option can
  416. also be quite useful. The resulting schedule can be observed by using the
  417. @code{starpu_lp2paje} tool, which converts it into the Paje format.
  418. Data transfer time can only be taken into account when @code{deps} is set. Only
  419. data transfers inferred from implicit data dependencies between tasks are taken
  420. into account. Other data transfers are assumed to be completely overlapped.
  421. Setting @code{deps} to 0 will only take into account the actual computations
  422. on processing units. It however still properly takes into account the varying
  423. performances of kernels and processing units, which is quite more accurate than
  424. just comparing StarPU performances with the fastest of the kernels being used.
  425. The @code{prio} parameter tells StarPU whether to simulate taking into account
  426. the priorities as the StarPU scheduler would, i.e. schedule prioritized
  427. tasks before less prioritized tasks, to check to which extend this results
  428. to a less optimal solution. This increases even more computation time.
  429. @node Insert Task Utility
  430. @section Insert Task Utility
  431. StarPU provides the wrapper function @code{starpu_insert_task} to ease
  432. the creation and submission of tasks. See the definition of the
  433. functions in @ref{Insert Task}.
  434. Here the implementation of the codelet:
  435. @cartouche
  436. @smallexample
  437. void func_cpu(void *descr[], void *_args)
  438. @{
  439. int *x0 = (int *)STARPU_VARIABLE_GET_PTR(descr[0]);
  440. float *x1 = (float *)STARPU_VARIABLE_GET_PTR(descr[1]);
  441. int ifactor;
  442. float ffactor;
  443. starpu_codelet_unpack_args(_args, &ifactor, &ffactor);
  444. *x0 = *x0 * ifactor;
  445. *x1 = *x1 * ffactor;
  446. @}
  447. struct starpu_codelet mycodelet = @{
  448. .where = STARPU_CPU,
  449. .cpu_funcs = @{ func_cpu, NULL @},
  450. .cpu_funcs_name = @{ "func_cpu", NULL @},
  451. .nbuffers = 2,
  452. .modes = @{ STARPU_RW, STARPU_RW @}
  453. @};
  454. @end smallexample
  455. @end cartouche
  456. And the call to the @code{starpu_insert_task} wrapper:
  457. @cartouche
  458. @smallexample
  459. starpu_insert_task(&mycodelet,
  460. STARPU_VALUE, &ifactor, sizeof(ifactor),
  461. STARPU_VALUE, &ffactor, sizeof(ffactor),
  462. STARPU_RW, data_handles[0], STARPU_RW, data_handles[1],
  463. 0);
  464. @end smallexample
  465. @end cartouche
  466. The call to @code{starpu_insert_task} is equivalent to the following
  467. code:
  468. @cartouche
  469. @smallexample
  470. struct starpu_task *task = starpu_task_create();
  471. task->cl = &mycodelet;
  472. task->handles[0] = data_handles[0];
  473. task->handles[1] = data_handles[1];
  474. char *arg_buffer;
  475. size_t arg_buffer_size;
  476. starpu_codelet_pack_args(&arg_buffer, &arg_buffer_size,
  477. STARPU_VALUE, &ifactor, sizeof(ifactor),
  478. STARPU_VALUE, &ffactor, sizeof(ffactor),
  479. 0);
  480. task->cl_arg = arg_buffer;
  481. task->cl_arg_size = arg_buffer_size;
  482. int ret = starpu_task_submit(task);
  483. @end smallexample
  484. @end cartouche
  485. Here a similar call using @code{STARPU_DATA_ARRAY}.
  486. @cartouche
  487. @smallexample
  488. starpu_insert_task(&mycodelet,
  489. STARPU_DATA_ARRAY, data_handles, 2,
  490. STARPU_VALUE, &ifactor, sizeof(ifactor),
  491. STARPU_VALUE, &ffactor, sizeof(ffactor),
  492. 0);
  493. @end smallexample
  494. @end cartouche
  495. If some part of the task insertion depends on the value of some computation,
  496. the @code{STARPU_DATA_ACQUIRE_CB} macro can be very convenient. For
  497. instance, assuming that the index variable @code{i} was registered as handle
  498. @code{i_handle}:
  499. @cartouche
  500. @smallexample
  501. /* Compute which portion we will work on, e.g. pivot */
  502. starpu_insert_task(&which_index, STARPU_W, i_handle, 0);
  503. /* And submit the corresponding task */
  504. STARPU_DATA_ACQUIRE_CB(i_handle, STARPU_R,
  505. starpu_insert_task(&work, STARPU_RW, A_handle[i], 0));
  506. @end smallexample
  507. @end cartouche
  508. The @code{STARPU_DATA_ACQUIRE_CB} macro submits an asynchronous request for
  509. acquiring data @code{i} for the main application, and will execute the code
  510. given as third parameter when it is acquired. In other words, as soon as the
  511. value of @code{i} computed by the @code{which_index} codelet can be read, the
  512. portion of code passed as third parameter of @code{STARPU_DATA_ACQUIRE_CB} will
  513. be executed, and is allowed to read from @code{i} to use it e.g. as an
  514. index. Note that this macro is only avaible when compiling StarPU with
  515. the compiler @code{gcc}.
  516. @node Data reduction
  517. @section Data reduction
  518. In various cases, some piece of data is used to accumulate intermediate
  519. results. For instances, the dot product of a vector, maximum/minimum finding,
  520. the histogram of a photograph, etc. When these results are produced along the
  521. whole machine, it would not be efficient to accumulate them in only one place,
  522. incurring data transmission each and access concurrency.
  523. StarPU provides a @code{STARPU_REDUX} mode, which permits to optimize
  524. that case: it will allocate a buffer on each memory node, and accumulate
  525. intermediate results there. When the data is eventually accessed in the normal
  526. @code{STARPU_R} mode, StarPU will collect the intermediate results in just one
  527. buffer.
  528. For this to work, the user has to use the
  529. @code{starpu_data_set_reduction_methods} to declare how to initialize these
  530. buffers, and how to assemble partial results.
  531. For instance, @code{cg} uses that to optimize its dot product: it first defines
  532. the codelets for initialization and reduction:
  533. @cartouche
  534. @smallexample
  535. struct starpu_codelet bzero_variable_cl =
  536. @{
  537. .cpu_funcs = @{ bzero_variable_cpu, NULL @},
  538. .cpu_funcs_name = @{ "bzero_variable_cpu", NULL @},
  539. .cuda_funcs = @{ bzero_variable_cuda, NULL @},
  540. .nbuffers = 1,
  541. @}
  542. static void accumulate_variable_cpu(void *descr[], void *cl_arg)
  543. @{
  544. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  545. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  546. *v_dst = *v_dst + *v_src;
  547. @}
  548. static void accumulate_variable_cuda(void *descr[], void *cl_arg)
  549. @{
  550. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  551. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  552. cublasaxpy(1, (double)1.0, v_src, 1, v_dst, 1);
  553. cudaStreamSynchronize(starpu_cuda_get_local_stream());
  554. @}
  555. struct starpu_codelet accumulate_variable_cl =
  556. @{
  557. .cpu_funcs = @{ accumulate_variable_cpu, NULL @},
  558. .cpu_funcs_name = @{ "accumulate_variable_cpu", NULL @},
  559. .cuda_funcs = @{ accumulate_variable_cuda, NULL @},
  560. .nbuffers = 1,
  561. @}
  562. @end smallexample
  563. @end cartouche
  564. and attaches them as reduction methods for its dtq handle:
  565. @cartouche
  566. @smallexample
  567. starpu_variable_data_register(&dtq_handle, -1, NULL, sizeof(type));
  568. starpu_data_set_reduction_methods(dtq_handle,
  569. &accumulate_variable_cl, &bzero_variable_cl);
  570. @end smallexample
  571. @end cartouche
  572. and @code{dtq_handle} can now be used in @code{STARPU_REDUX} mode for the dot products
  573. with partitioned vectors:
  574. @cartouche
  575. @smallexample
  576. for (b = 0; b < nblocks; b++)
  577. starpu_insert_task(&dot_kernel_cl,
  578. STARPU_REDUX, dtq_handle,
  579. STARPU_R, starpu_data_get_sub_data(v1, 1, b),
  580. STARPU_R, starpu_data_get_sub_data(v2, 1, b),
  581. 0);
  582. @end smallexample
  583. @end cartouche
  584. During registration, we have here provided NULL, i.e. there is no initial value
  585. to be taken into account during reduction. StarPU will thus only take into
  586. account the contributions from the @code{dot_kernel_cl} tasks. Also, it will not
  587. allocate any memory for @code{dtq_handle} before @code{dot_kernel_cl} tasks are
  588. ready to run.
  589. If another dot product has to be performed, one could unregister
  590. @code{dtq_handle}, and re-register it. But one can also use
  591. @code{starpu_data_invalidate_submit(dtq_handle)}, which will clear all data from the handle,
  592. thus resetting it back to the initial @code{register(NULL)} state.
  593. The @code{cg} example also uses reduction for the blocked gemv kernel, leading
  594. to yet more relaxed dependencies and more parallelism.
  595. STARPU_REDUX can also be passed to @code{starpu_mpi_insert_task} in the MPI
  596. case. That will however not produce any MPI communication, but just pass
  597. STARPU_REDUX to the underlying @code{starpu_insert_task}. It is up to the
  598. application to call @code{starpu_mpi_redux_data}, which posts tasks that will
  599. reduce the partial results among MPI nodes into the MPI node which owns the
  600. data. For instance, some hypothetical application which collects partial results
  601. into data @code{res}, then uses it for other computation, before looping again
  602. with a new reduction:
  603. @cartouche
  604. @smallexample
  605. for (i = 0; i < 100; i++) @{
  606. starpu_mpi_insert_task(MPI_COMM_WORLD, &init_res, STARPU_W, res, 0);
  607. starpu_mpi_insert_task(MPI_COMM_WORLD, &work, STARPU_RW, A,
  608. STARPU_R, B, STARPU_REDUX, res, 0);
  609. starpu_mpi_redux_data(MPI_COMM_WORLD, res);
  610. starpu_mpi_insert_task(MPI_COMM_WORLD, &work2, STARPU_RW, B, STARPU_R, res, 0);
  611. @}
  612. @end smallexample
  613. @end cartouche
  614. @node Temporary buffers
  615. @section Temporary buffers
  616. There are two kinds of temporary buffers: temporary data which just pass results
  617. from a task to another, and scratch data which are needed only internally by
  618. tasks.
  619. @subsection Temporary data
  620. Data can sometimes be entirely produced by a task, and entirely consumed by
  621. another task, without the need for other parts of the application to access
  622. it. In such case, registration can be done without prior allocation, by using
  623. the special -1 memory node number, and passing a zero pointer. StarPU will
  624. actually allocate memory only when the task creating the content gets scheduled,
  625. and destroy it on unregistration.
  626. In addition to that, it can be tedious for the application to have to unregister
  627. the data, since it will not use its content anyway. The unregistration can be
  628. done lazily by using the @code{starpu_data_unregister_submit(handle)} function,
  629. which will record that no more tasks accessing the handle will be submitted, so
  630. that it can be freed as soon as the last task accessing it is over.
  631. The following code examplifies both points: it registers the temporary
  632. data, submits three tasks accessing it, and records the data for automatic
  633. unregistration.
  634. @cartouche
  635. @smallexample
  636. starpu_vector_data_register(&handle, -1, 0, n, sizeof(float));
  637. starpu_insert_task(&produce_data, STARPU_W, handle, 0);
  638. starpu_insert_task(&compute_data, STARPU_RW, handle, 0);
  639. starpu_insert_task(&summarize_data, STARPU_R, handle, STARPU_W, result_handle, 0);
  640. starpu_data_unregister_submit(handle);
  641. @end smallexample
  642. @end cartouche
  643. @subsection Scratch data
  644. Some kernels sometimes need temporary data to achieve the computations, i.e. a
  645. workspace. The application could allocate it at the start of the codelet
  646. function, and free it at the end, but that would be costly. It could also
  647. allocate one buffer per worker (similarly to @ref{Per-worker library
  648. initialization}), but that would make them systematic and permanent. A more
  649. optimized way is to use the SCRATCH data access mode, as examplified below,
  650. which provides per-worker buffers without content consistency.
  651. @cartouche
  652. @smallexample
  653. starpu_vector_data_register(&workspace, -1, 0, sizeof(float));
  654. for (i = 0; i < N; i++)
  655. starpu_insert_task(&compute, STARPU_R, input[i],
  656. STARPU_SCRATCH, workspace, STARPU_W, output[i], 0);
  657. @end smallexample
  658. @end cartouche
  659. StarPU will make sure that the buffer is allocated before executing the task,
  660. and make this allocation per-worker: for CPU workers, notably, each worker has
  661. its own buffer. This means that each task submitted above will actually have its
  662. own workspace, which will actually be the same for all tasks running one after
  663. the other on the same worker. Also, if for instance GPU memory becomes scarce,
  664. StarPU will notice that it can free such buffers easily, since the content does
  665. not matter.
  666. The @code{examples/pi} example uses scratches for some temporary buffer.
  667. @node Parallel Tasks
  668. @section Parallel Tasks
  669. StarPU can leverage existing parallel computation libraries by the means of
  670. parallel tasks. A parallel task is a task which gets worked on by a set of CPUs
  671. (called a parallel or combined worker) at the same time, by using an existing
  672. parallel CPU implementation of the computation to be achieved. This can also be
  673. useful to improve the load balance between slow CPUs and fast GPUs: since CPUs
  674. work collectively on a single task, the completion time of tasks on CPUs become
  675. comparable to the completion time on GPUs, thus relieving from granularity
  676. discrepancy concerns. Hwloc support needs to be enabled to get good performance,
  677. otherwise StarPU will not know how to better group cores.
  678. Two modes of execution exist to accomodate with existing usages.
  679. @subsection Fork-mode parallel tasks
  680. In the Fork mode, StarPU will call the codelet function on one
  681. of the CPUs of the combined worker. The codelet function can use
  682. @code{starpu_combined_worker_get_size()} to get the number of threads it is
  683. allowed to start to achieve the computation. The CPU binding mask for the whole
  684. set of CPUs is already enforced, so that threads created by the function will
  685. inherit the mask, and thus execute where StarPU expected, the OS being in charge
  686. of choosing how to schedule threads on the corresponding CPUs. The application
  687. can also choose to bind threads by hand, using e.g. sched_getaffinity to know
  688. the CPU binding mask that StarPU chose.
  689. For instance, using OpenMP (full source is available in
  690. @code{examples/openmp/vector_scal.c}):
  691. @cartouche
  692. @smallexample
  693. void scal_cpu_func(void *buffers[], void *_args)
  694. @{
  695. unsigned i;
  696. float *factor = _args;
  697. struct starpu_vector_interface *vector = buffers[0];
  698. unsigned n = STARPU_VECTOR_GET_NX(vector);
  699. float *val = (float *)STARPU_VECTOR_GET_PTR(vector);
  700. #pragma omp parallel for num_threads(starpu_combined_worker_get_size())
  701. for (i = 0; i < n; i++)
  702. val[i] *= *factor;
  703. @}
  704. static struct starpu_codelet cl =
  705. @{
  706. .modes = @{ STARPU_RW @},
  707. .where = STARPU_CPU,
  708. .type = STARPU_FORKJOIN,
  709. .max_parallelism = INT_MAX,
  710. .cpu_funcs = @{scal_cpu_func, NULL@},
  711. .cpu_funcs_name = @{"scal_cpu_func", NULL@},
  712. .nbuffers = 1,
  713. @};
  714. @end smallexample
  715. @end cartouche
  716. Other examples include for instance calling a BLAS parallel CPU implementation
  717. (see @code{examples/mult/xgemm.c}).
  718. @subsection SPMD-mode parallel tasks
  719. In the SPMD mode, StarPU will call the codelet function on
  720. each CPU of the combined worker. The codelet function can use
  721. @code{starpu_combined_worker_get_size()} to get the total number of CPUs
  722. involved in the combined worker, and thus the number of calls that are made in
  723. parallel to the function, and @code{starpu_combined_worker_get_rank()} to get
  724. the rank of the current CPU within the combined worker. For instance:
  725. @cartouche
  726. @smallexample
  727. static void func(void *buffers[], void *args)
  728. @{
  729. unsigned i;
  730. float *factor = _args;
  731. struct starpu_vector_interface *vector = buffers[0];
  732. unsigned n = STARPU_VECTOR_GET_NX(vector);
  733. float *val = (float *)STARPU_VECTOR_GET_PTR(vector);
  734. /* Compute slice to compute */
  735. unsigned m = starpu_combined_worker_get_size();
  736. unsigned j = starpu_combined_worker_get_rank();
  737. unsigned slice = (n+m-1)/m;
  738. for (i = j * slice; i < (j+1) * slice && i < n; i++)
  739. val[i] *= *factor;
  740. @}
  741. static struct starpu_codelet cl =
  742. @{
  743. .modes = @{ STARPU_RW @},
  744. .where = STARP_CPU,
  745. .type = STARPU_SPMD,
  746. .max_parallelism = INT_MAX,
  747. .cpu_funcs = @{ func, NULL @},
  748. .cpu_funcs_name = @{ "func", NULL @},
  749. .nbuffers = 1,
  750. @}
  751. @end smallexample
  752. @end cartouche
  753. Of course, this trivial example will not really benefit from parallel task
  754. execution, and was only meant to be simple to understand. The benefit comes
  755. when the computation to be done is so that threads have to e.g. exchange
  756. intermediate results, or write to the data in a complex but safe way in the same
  757. buffer.
  758. @subsection Parallel tasks performance
  759. To benefit from parallel tasks, a parallel-task-aware StarPU scheduler has to
  760. be used. When exposed to codelets with a Fork or SPMD flag, the @code{pheft}
  761. (parallel-heft) and @code{peager} (parallel eager) schedulers will indeed also
  762. try to execute tasks with several CPUs. It will automatically try the various
  763. available combined worker sizes (making several measurements for each worker size)
  764. and thus be able to avoid choosing a large
  765. combined worker if the codelet does not actually scale so much.
  766. @subsection Combined workers
  767. By default, StarPU creates combined workers according to the architecture
  768. structure as detected by hwloc. It means that for each object of the hwloc
  769. topology (NUMA node, socket, cache, ...) a combined worker will be created. If
  770. some nodes of the hierarchy have a big arity (e.g. many cores in a socket
  771. without a hierarchy of shared caches), StarPU will create combined workers of
  772. intermediate sizes. The @code{STARPU_SYNTHESIZE_ARITY_COMBINED_WORKER} variable
  773. permits to tune the maximum arity between levels of combined workers.
  774. The combined workers actually produced can be seen in the output of the
  775. @code{starpu_machine_display} tool (the @code{STARPU_SCHED} environment variable
  776. has to be set to a combined worker-aware scheduler such as @code{pheft} or
  777. @code{peager}).
  778. @subsection Concurrent parallel tasks
  779. Unfortunately, many environments and librairies do not support concurrent
  780. calls.
  781. For instance, most OpenMP implementations (including the main ones) do not
  782. support concurrent @code{pragma omp parallel} statements without nesting them in
  783. another @code{pragma omp parallel} statement, but StarPU does not yet support
  784. creating its CPU workers by using such pragma.
  785. Other parallel libraries are also not safe when being invoked concurrently
  786. from different threads, due to the use of global variables in their sequential
  787. sections for instance.
  788. The solution is then to use only one combined worker at a time. This can be
  789. done by setting @code{single_combined_worker} to 1 in the @code{starpu_conf}
  790. structure, or setting the @code{STARPU_SINGLE_COMBINED_WORKER} environment
  791. variable to 1. StarPU will then run only one parallel task at a time (but other
  792. CPU and GPU tasks are not affected and can be run concurrently). The parallel
  793. task scheduler will however still however still try varying combined worker
  794. sizes to look for the most efficient ones.
  795. @node Debugging
  796. @section Debugging
  797. StarPU provides several tools to help debugging aplications. Execution traces
  798. can be generated and displayed graphically, see @ref{Generating traces}. Some
  799. gdb helpers are also provided to show the whole StarPU state:
  800. @smallexample
  801. (gdb) source tools/gdbinit
  802. (gdb) help starpu
  803. @end smallexample
  804. The Temanejo task debugger can also be used, see @ref{Task debugger}.
  805. @node The multiformat interface
  806. @section The multiformat interface
  807. It may be interesting to represent the same piece of data using two different
  808. data structures: one that would only be used on CPUs, and one that would only
  809. be used on GPUs. This can be done by using the multiformat interface. StarPU
  810. will be able to convert data from one data structure to the other when needed.
  811. Note that the dmda scheduler is the only one optimized for this interface. The
  812. user must provide StarPU with conversion codelets:
  813. @cartouche
  814. @smallexample
  815. #define NX 1024
  816. struct point array_of_structs[NX];
  817. starpu_data_handle_t handle;
  818. /*
  819. * The conversion of a piece of data is itself a task, though it is created,
  820. * submitted and destroyed by StarPU internals and not by the user. Therefore,
  821. * we have to define two codelets.
  822. * Note that for now the conversion from the CPU format to the GPU format has to
  823. * be executed on the GPU, and the conversion from the GPU to the CPU has to be
  824. * executed on the CPU.
  825. */
  826. #ifdef STARPU_USE_OPENCL
  827. void cpu_to_opencl_opencl_func(void *buffers[], void *args);
  828. struct starpu_codelet cpu_to_opencl_cl = @{
  829. .where = STARPU_OPENCL,
  830. .opencl_funcs = @{ cpu_to_opencl_opencl_func, NULL @},
  831. .nbuffers = 1,
  832. .modes = @{ STARPU_RW @}
  833. @};
  834. void opencl_to_cpu_func(void *buffers[], void *args);
  835. struct starpu_codelet opencl_to_cpu_cl = @{
  836. .where = STARPU_CPU,
  837. .cpu_funcs = @{ opencl_to_cpu_func, NULL @},
  838. .cpu_funcs_name = @{ "opencl_to_cpu_func", NULL @},
  839. .nbuffers = 1,
  840. .modes = @{ STARPU_RW @}
  841. @};
  842. #endif
  843. struct starpu_multiformat_data_interface_ops format_ops = @{
  844. #ifdef STARPU_USE_OPENCL
  845. .opencl_elemsize = 2 * sizeof(float),
  846. .cpu_to_opencl_cl = &cpu_to_opencl_cl,
  847. .opencl_to_cpu_cl = &opencl_to_cpu_cl,
  848. #endif
  849. .cpu_elemsize = 2 * sizeof(float),
  850. ...
  851. @};
  852. starpu_multiformat_data_register(handle, 0, &array_of_structs, NX, &format_ops);
  853. @end smallexample
  854. @end cartouche
  855. Kernels can be written almost as for any other interface. Note that
  856. STARPU_MULTIFORMAT_GET_CPU_PTR shall only be used for CPU kernels. CUDA kernels
  857. must use STARPU_MULTIFORMAT_GET_CUDA_PTR, and OpenCL kernels must use
  858. STARPU_MULTIFORMAT_GET_OPENCL_PTR. STARPU_MULTIFORMAT_GET_NX may be used in any
  859. kind of kernel.
  860. @cartouche
  861. @smallexample
  862. static void
  863. multiformat_scal_cpu_func(void *buffers[], void *args)
  864. @{
  865. struct point *aos;
  866. unsigned int n;
  867. aos = STARPU_MULTIFORMAT_GET_CPU_PTR(buffers[0]);
  868. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  869. ...
  870. @}
  871. extern "C" void multiformat_scal_cuda_func(void *buffers[], void *_args)
  872. @{
  873. unsigned int n;
  874. struct struct_of_arrays *soa;
  875. soa = (struct struct_of_arrays *) STARPU_MULTIFORMAT_GET_CUDA_PTR(buffers[0]);
  876. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  877. ...
  878. @}
  879. @end smallexample
  880. @end cartouche
  881. A full example may be found in @code{examples/basic_examples/multiformat.c}.
  882. @node Using the Driver API
  883. @section Using the Driver API
  884. @pxref{Running drivers}
  885. @cartouche
  886. @smallexample
  887. int ret;
  888. struct starpu_driver = @{
  889. .type = STARPU_CUDA_WORKER,
  890. .id.cuda_id = 0
  891. @};
  892. ret = starpu_driver_init(&d);
  893. if (ret != 0)
  894. error();
  895. while (some_condition) @{
  896. ret = starpu_driver_run_once(&d);
  897. if (ret != 0)
  898. error();
  899. @}
  900. ret = starpu_driver_deinit(&d);
  901. if (ret != 0)
  902. error();
  903. @end smallexample
  904. @end cartouche
  905. @node Defining a New Scheduling Policy
  906. @section Defining a New Scheduling Policy
  907. A full example showing how to define a new scheduling policy is available in
  908. the StarPU sources in the directory @code{examples/scheduler/}.
  909. @pxref{Scheduling Policy}
  910. @cartouche
  911. @smallexample
  912. static struct starpu_sched_policy dummy_sched_policy = @{
  913. .init_sched = init_dummy_sched,
  914. .deinit_sched = deinit_dummy_sched,
  915. .add_workers = dummy_sched_add_workers,
  916. .remove_workers = dummy_sched_remove_workers,
  917. .push_task = push_task_dummy,
  918. .push_prio_task = NULL,
  919. .pop_task = pop_task_dummy,
  920. .post_exec_hook = NULL,
  921. .pop_every_task = NULL,
  922. .policy_name = "dummy",
  923. .policy_description = "dummy scheduling strategy"
  924. @};
  925. @end smallexample
  926. @end cartouche
  927. @node On-GPU rendering
  928. @section On-GPU rendering
  929. Graphical-oriented applications need to draw the result of their computations,
  930. typically on the very GPU where these happened. Technologies such as OpenGL/CUDA
  931. interoperability permit to let CUDA directly work on the OpenGL buffers, making
  932. them thus immediately ready for drawing, by mapping OpenGL buffer, textures or
  933. renderbuffer objects into CUDA. CUDA however imposes some technical
  934. constraints: peer memcpy has to be disabled, and the thread that runs OpenGL has
  935. to be the one that runs CUDA computations for that GPU.
  936. To achieve this with StarPU, pass the @code{--disable-cuda-memcpy-peer} option
  937. to @code{./configure} (TODO: make it dynamic), OpenGL/GLUT has to be initialized
  938. first, and the interoperability mode has to
  939. be enabled by using the @code{cuda_opengl_interoperability} field of the
  940. @code{starpu_conf} structure, and the driver loop has to be run by
  941. the application, by using the @code{not_launched_drivers} field of
  942. @code{starpu_conf} to prevent StarPU from running it in a separate thread, and
  943. by using @code{starpu_driver_run} to run the loop. The @code{gl_interop} and
  944. @code{gl_interop_idle} examples shows how it articulates in a simple case, where
  945. rendering is done in task callbacks. The former uses @code{glutMainLoopEvent}
  946. to make GLUT progress from the StarPU driver loop, while the latter uses
  947. @code{glutIdleFunc} to make StarPU progress from the GLUT main loop.
  948. Then, to use an OpenGL buffer as a CUDA data, StarPU simply needs to be given
  949. the CUDA pointer at registration, for instance:
  950. @cartouche
  951. @smallexample
  952. /* Get the CUDA worker id */
  953. for (workerid = 0; workerid < starpu_worker_get_count(); workerid++)
  954. if (starpu_worker_get_type(workerid) == STARPU_CUDA_WORKER)
  955. break;
  956. /* Build a CUDA pointer pointing at the OpenGL buffer */
  957. cudaGraphicsResourceGetMappedPointer((void**)&output, &num_bytes, resource);
  958. /* And register it to StarPU */
  959. starpu_vector_data_register(&handle, starpu_worker_get_memory_node(workerid),
  960. output, num_bytes / sizeof(float4), sizeof(float4));
  961. /* The handle can now be used as usual */
  962. starpu_insert_task(&cl, STARPU_RW, handle, 0);
  963. /* ... */
  964. /* This gets back data into the OpenGL buffer */
  965. starpu_data_unregister(handle);
  966. @end smallexample
  967. @end cartouche
  968. and display it e.g. in the callback function.
  969. @node Defining a New Data Interface
  970. @section Defining a New Data Interface
  971. Let's define a new data interface to manage complex numbers.
  972. @cartouche
  973. @smallexample
  974. /* interface for complex numbers */
  975. struct starpu_complex_interface
  976. @{
  977. double *real;
  978. double *imaginary;
  979. int nx;
  980. @};
  981. @end smallexample
  982. @end cartouche
  983. Registering such a data to StarPU is easily done using the function
  984. @code{starpu_data_register} (@pxref{Basic Data Management API}). The last
  985. parameter of the function, @code{interface_complex_ops}, will be
  986. described below.
  987. @cartouche
  988. @smallexample
  989. void starpu_complex_data_register(starpu_data_handle_t *handle,
  990. unsigned home_node, double *real, double *imaginary, int nx)
  991. @{
  992. struct starpu_complex_interface complex =
  993. @{
  994. .real = real,
  995. .imaginary = imaginary,
  996. .nx = nx
  997. @};
  998. if (interface_complex_ops.interfaceid == STARPU_UNKNOWN_INTERFACE_ID)
  999. @{
  1000. interface_complex_ops.interfaceid = starpu_data_interface_get_next_id();
  1001. @}
  1002. starpu_data_register(handleptr, home_node, &complex, &interface_complex_ops);
  1003. @}
  1004. @end smallexample
  1005. @end cartouche
  1006. Different operations need to be defined for a data interface through
  1007. the type @code{struct starpu_data_interface_ops} (@pxref{Defining
  1008. Interface}). We only define here the basic operations needed to
  1009. run simple applications. The source code for the different functions
  1010. can be found in the file
  1011. @code{examples/interface/complex_interface.c}.
  1012. @cartouche
  1013. @smallexample
  1014. static struct starpu_data_interface_ops interface_complex_ops =
  1015. @{
  1016. .register_data_handle = complex_register_data_handle,
  1017. .allocate_data_on_node = complex_allocate_data_on_node,
  1018. .copy_methods = &complex_copy_methods,
  1019. .get_size = complex_get_size,
  1020. .footprint = complex_footprint,
  1021. .interfaceid = STARPU_UNKNOWN_INTERFACE_ID,
  1022. .interface_size = sizeof(struct starpu_complex_interface),
  1023. @};
  1024. @end smallexample
  1025. @end cartouche
  1026. Functions need to be defined to access the different fields of the
  1027. complex interface from a StarPU data handle.
  1028. @cartouche
  1029. @smallexample
  1030. double *starpu_complex_get_real(starpu_data_handle_t handle)
  1031. @{
  1032. struct starpu_complex_interface *complex_interface =
  1033. (struct starpu_complex_interface *) starpu_data_get_interface_on_node(handle, 0);
  1034. return complex_interface->real;
  1035. @}
  1036. double *starpu_complex_get_imaginary(starpu_data_handle_t handle);
  1037. int starpu_complex_get_nx(starpu_data_handle_t handle);
  1038. @end smallexample
  1039. @end cartouche
  1040. Similar functions need to be defined to access the different fields of the
  1041. complex interface from a @code{void *} pointer to be used within codelet
  1042. implemetations.
  1043. @cartouche
  1044. @smallexample
  1045. #define STARPU_COMPLEX_GET_REAL(interface) \
  1046. (((struct starpu_complex_interface *)(interface))->real)
  1047. #define STARPU_COMPLEX_GET_IMAGINARY(interface) \
  1048. (((struct starpu_complex_interface *)(interface))->imaginary)
  1049. #define STARPU_COMPLEX_GET_NX(interface) \
  1050. (((struct starpu_complex_interface *)(interface))->nx)
  1051. @end smallexample
  1052. @end cartouche
  1053. Complex data interfaces can then be registered to StarPU.
  1054. @cartouche
  1055. @smallexample
  1056. double real = 45.0;
  1057. double imaginary = 12.0;
  1058. starpu_complex_data_register(&handle1, 0, &real, &imaginary, 1);
  1059. starpu_insert_task(&cl_display, STARPU_R, handle1, 0);
  1060. @end smallexample
  1061. @end cartouche
  1062. and used by codelets.
  1063. @cartouche
  1064. @smallexample
  1065. void display_complex_codelet(void *descr[], __attribute__ ((unused)) void *_args)
  1066. @{
  1067. int nx = STARPU_COMPLEX_GET_NX(descr[0]);
  1068. double *real = STARPU_COMPLEX_GET_REAL(descr[0]);
  1069. double *imaginary = STARPU_COMPLEX_GET_IMAGINARY(descr[0]);
  1070. int i;
  1071. for(i=0 ; i<nx ; i++)
  1072. @{
  1073. fprintf(stderr, "Complex[%d] = %3.2f + %3.2f i\n", i, real[i], imaginary[i]);
  1074. @}
  1075. @}
  1076. @end smallexample
  1077. @end cartouche
  1078. The whole code for this complex data interface is available in the
  1079. directory @code{examples/interface/}.
  1080. @node Setting the Data Handles for a Task
  1081. @section Setting the Data Handles for a Task
  1082. The number of data a task can manage is fixed by the
  1083. @code{STARPU_NMAXBUFS} which has a default value which can be changed
  1084. through the configure option @code{--enable-maxbuffers} (see
  1085. @ref{--enable-maxbuffers}).
  1086. However, it is possible to define tasks managing more data by using
  1087. the field @code{dyn_handles} when defining a task and the field
  1088. @code{dyn_modes} when defining the corresponding codelet.
  1089. @cartouche
  1090. @smallexample
  1091. enum starpu_data_access_mode modes[STARPU_NMAXBUFS+1] = @{
  1092. STARPU_R, STARPU_R, ...
  1093. @};
  1094. struct starpu_codelet dummy_big_cl =
  1095. @{
  1096. .cuda_funcs = @{dummy_big_kernel, NULL@},
  1097. .opencl_funcs = @{dummy_big_kernel, NULL@},
  1098. .cpu_funcs = @{dummy_big_kernel, NULL@},
  1099. .cpu_funcs_name = @{"dummy_big_kernel", NULL@},
  1100. .nbuffers = STARPU_NMAXBUFS+1,
  1101. .dyn_modes = modes
  1102. @};
  1103. task = starpu_task_create();
  1104. task->cl = &dummy_big_cl;
  1105. task->dyn_handles = malloc(task->cl->nbuffers * sizeof(starpu_data_handle_t));
  1106. for(i=0 ; i<task->cl->nbuffers ; i++)
  1107. @{
  1108. task->dyn_handles[i] = handle;
  1109. @}
  1110. starpu_task_submit(task);
  1111. @end smallexample
  1112. @end cartouche
  1113. @cartouche
  1114. @smallexample
  1115. starpu_data_handle_t *handles = malloc(dummy_big_cl.nbuffers * sizeof(starpu_data_handle_t));
  1116. for(i=0 ; i<dummy_big_cl.nbuffers ; i++)
  1117. @{
  1118. handles[i] = handle;
  1119. @}
  1120. starpu_insert_task(&dummy_big_cl,
  1121. STARPU_VALUE, &dummy_big_cl.nbuffers, sizeof(dummy_big_cl.nbuffers),
  1122. STARPU_DATA_ARRAY, handles, dummy_big_cl.nbuffers,
  1123. 0);
  1124. @end smallexample
  1125. @end cartouche
  1126. The whole code for this complex data interface is available in the
  1127. directory @code{examples/basic_examples/dynamic_handles.c}.
  1128. @node More examples
  1129. @section More examples
  1130. More examples are available in the StarPU sources in the @code{examples/}
  1131. directory. Simple examples include:
  1132. @table @asis
  1133. @item @code{incrementer/}:
  1134. Trivial incrementation test.
  1135. @item @code{basic_examples/}:
  1136. Simple documented Hello world and vector/scalar product (as
  1137. shown in @ref{Basic Examples}), matrix
  1138. product examples (as shown in @ref{Performance model example}), an example using the blocked matrix data
  1139. interface, an example using the variable data interface, and an example
  1140. using different formats on CPUs and GPUs.
  1141. @item @code{matvecmult/}:
  1142. OpenCL example from NVidia, adapted to StarPU.
  1143. @item @code{axpy/}:
  1144. AXPY CUBLAS operation adapted to StarPU.
  1145. @item @code{fortran/}:
  1146. Example of Fortran bindings.
  1147. @end table
  1148. More advanced examples include:
  1149. @table @asis
  1150. @item @code{filters/}:
  1151. Examples using filters, as shown in @ref{Partitioning Data}.
  1152. @item @code{lu/}:
  1153. LU matrix factorization, see for instance @code{xlu_implicit.c}
  1154. @item @code{cholesky/}:
  1155. Cholesky matrix factorization, see for instance @code{cholesky_implicit.c}.
  1156. @end table