advanced_examples.doxy 46 KB

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