310_data_management.doxy 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /* StarPU --- Runtime system for heterogeneous multicore architectures.
  2. *
  3. * Copyright (C) 2010-2019 CNRS
  4. * Copyright (C) 2009-2011,2014-2019 Université de Bordeaux
  5. * Copyright (C) 2011,2012 Inria
  6. *
  7. * StarPU is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation; either version 2.1 of the License, or (at
  10. * your option) any later version.
  11. *
  12. * StarPU is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  15. *
  16. * See the GNU Lesser General Public License in COPYING.LGPL for more details.
  17. */
  18. /*! \page DataManagement Data Management
  19. TODO: intro which mentions consistency among other things
  20. \section DataInterface Data Interface
  21. StarPU provides several data interfaces for programmers to describe
  22. the data layout of their application. There are predefined interfaces
  23. already available in StarPU. Users can define new data interfaces as
  24. explained in \ref DefiningANewDataInterface. All functions provided by
  25. StarPU are documented in \ref API_Data_Interfaces. You will find a
  26. short list below.
  27. \subsection VariableDataInterface Variable Data Interface
  28. A variable is a given-size byte element, typically a scalar. Here an
  29. example of how to register a variable data to StarPU by using
  30. starpu_variable_data_register().
  31. \code{.c}
  32. float var = 42.0;
  33. starpu_data_handle_t var_handle;
  34. starpu_variable_data_register(&var_handle, STARPU_MAIN_RAM, (uintptr_t)&var, sizeof(var));
  35. \endcode
  36. \subsection VectorDataInterface Vector Data Interface
  37. A vector is a fixed number of elements of a given size. Here an
  38. example of how to register a vector data to StarPU by using
  39. starpu_vector_data_register().
  40. \code{.c}
  41. float vector[NX];
  42. starpu_data_handle_t vector_handle;
  43. starpu_vector_data_register(&vector_handle, STARPU_MAIN_RAM, (uintptr_t)vector, NX, sizeof(vector[0]));
  44. \endcode
  45. Vectors can be partitioned into pieces by using
  46. starpu_vector_filter_block(). They can also be partitioned with some overlapping
  47. by using starpu_vector_filter_block_shadow(). By default StarPU
  48. uses the same size for each piece. If different sizes are desired,
  49. starpu_vector_filter_list() or starpu_vector_filter_list_long() can be used
  50. instead. To just divide in two pieces, starpu_vector_filter_divide_in_2() can be used.
  51. \subsection MatrixDataInterface Matrix Data Interface
  52. To register 2-D matrices with a potential padding, one can use the
  53. matrix data interface. Here an example of how to register a matrix
  54. data to StarPU by using starpu_matrix_data_register().
  55. \code{.c}
  56. float *matrix;
  57. starpu_data_handle_t matrix_handle;
  58. matrix = (float*)malloc(width * height * sizeof(float));
  59. starpu_matrix_data_register(&matrix_handle, STARPU_MAIN_RAM, (uintptr_t)matrix, width, width, height, sizeof(float));
  60. \endcode
  61. 2D matrices can be partitioned into 2D matrices along the x dimension by
  62. using starpu_matrix_filter_block(), and along the y dimension by using
  63. starpu_matrix_filter_vertical_block(). They can also be partitioned
  64. with some overlapping by using starpu_matrix_filter_block_shadow() and
  65. starpu_matrix_filter_vertical_block_shadow().
  66. \subsection BlockDataInterface Block Data Interface
  67. To register 3-D matrices with potential paddings on Y and Z dimensions,
  68. one can use the block data interface. Here an example of how to
  69. register a block data to StarPU by using starpu_block_data_register().
  70. \code{.c}
  71. float *block;
  72. starpu_data_handle_t block_handle;
  73. block = (float*)malloc(nx*ny*nz*sizeof(float));
  74. starpu_block_data_register(&block_handle, STARPU_MAIN_RAM, (uintptr_t)block, nx, nx*ny, nx, ny, nz, sizeof(float));
  75. \endcode
  76. 3D matrices can be partitioned along the x dimension by
  77. using starpu_block_filter_block(), or along the y dimension
  78. by using starpu_block_filter_vertical_block, or along the
  79. z dimension by using starpu_block_filter_depth_block. They
  80. can also be partitioned with some overlapping by using
  81. starpu_block_filter_block_shadow(), starpu_block_filter_vertical_block_shadow(),
  82. or starpu_block_filter_depth_block_shadow().
  83. \subsection BCSRDataInterface BCSR Data Interface
  84. BCSR (Blocked Compressed Sparse Row Representation) sparse matrix data
  85. can be registered to StarPU using the bcsr data interface. Here an
  86. example on how to do so by using starpu_bcsr_data_register().
  87. \code{.c}
  88. /*
  89. * We use the following matrix:
  90. *
  91. * +----------------+
  92. * | 0 1 0 0 |
  93. * | 2 3 0 0 |
  94. * | 4 5 8 9 |
  95. * | 6 7 10 11 |
  96. * +----------------+
  97. *
  98. * nzval = [0, 1, 2, 3] ++ [4, 5, 6, 7] ++ [8, 9, 10, 11]
  99. * colind = [0, 0, 1]
  100. * rowptr = [0, 1, 3]
  101. * r = c = 2
  102. */
  103. /* Size of the blocks */
  104. int R = 2;
  105. int C = 2;
  106. int NROWS = 2;
  107. int NNZ_BLOCKS = 3; /* out of 4 */
  108. int NZVAL_SIZE = (R*C*NNZ_BLOCKS);
  109. int nzval[NZVAL_SIZE] =
  110. {
  111. 0, 1, 2, 3, /* First block */
  112. 4, 5, 6, 7, /* Second block */
  113. 8, 9, 10, 11 /* Third block */
  114. };
  115. uint32_t colind[NNZ_BLOCKS] =
  116. {
  117. 0, /* block-column index for first block in nzval */
  118. 0, /* block-column index for second block in nzval */
  119. 1 /* block-column index for third block in nzval */
  120. };
  121. uint32_t rowptr[NROWS+1] =
  122. {
  123. 0, / * block-index in nzval of the first block of the first row. */
  124. 1, / * block-index in nzval of the first block of the second row. */
  125. NNZ_BLOCKS /* number of blocks, to allow an easier element's access for the kernels */
  126. };
  127. starpu_data_handle_t bcsr_handle;
  128. starpu_bcsr_data_register(&bcsr_handle,
  129. STARPU_MAIN_RAM,
  130. NNZ_BLOCKS,
  131. NROWS,
  132. (uintptr_t) nzval,
  133. colind,
  134. rowptr,
  135. 0, /* firstentry */
  136. R,
  137. C,
  138. sizeof(nzval[0]));
  139. \endcode
  140. StarPU provides an example on how to deal with such matrices in
  141. <c>examples/spmv</c>.
  142. BCSR data handles can be partitioned into its dense matrix blocks by using
  143. starpu_bcsr_filter_canonical_block().
  144. \subsection CSRDataInterface CSR Data Interface
  145. TODO
  146. CSR data handles can be partitioned into vertical CSR matrices by using
  147. starpu_csr_filter_vertical_block().
  148. \subsection VariableSizeDataInterface Data Interface with Variable Size
  149. Tasks are actually allowed to change the size of data interfaces.
  150. The simplest case is just changing the amount of data actually used within the
  151. allocated buffer. This is for instance implemented for the matrix interface: one
  152. can set the new NX/NY values with STARPU_MATRIX_SET_NX(), STARPU_MATRIX_SET_NY(), and STARPU_MATRIX_SET_LD()
  153. at the end of the task implementation. Data transfers achieved by StarPU will
  154. then use these values instead of the whole allocated size. The values of course
  155. need to be set within the original allocation. To reserve room for increasing
  156. the NX/NY values, one can use starpu_matrix_data_register_allocsize() instead of
  157. starpu_matrix_data_register(), to specify the allocation size to be used instead
  158. of the default NX*NY*ELEMSIZE. To support this, the data interface
  159. has to implement the starpu_data_interface_ops::alloc_footprint and
  160. starpu_data_interface_ops::alloc_compare methods, for proper StarPU allocation
  161. management.
  162. A more involved case is changing the amount of allocated data.
  163. The task implementation can just reallocate the buffer during its execution, and
  164. set the proper new values in the interface structure, e.g. nx, ny, ld, etc. so
  165. that the StarPU core knows the new data layout. The starpu_data_interface_ops
  166. structure however then needs to have the starpu_data_interface_ops::dontcache
  167. field set to 1, to prevent StarPU from trying to perform any cached allocation,
  168. since the allocated size will vary. An example is available in
  169. <c>tests/datawizard/variable_size.c</c>
  170. \section DataManagement Data Management
  171. When the application allocates data, whenever possible it should use
  172. the starpu_malloc() function, which will ask CUDA or OpenCL to make
  173. the allocation itself and pin the corresponding allocated memory, or to use the
  174. starpu_memory_pin() function to pin memory allocated by other ways, such as local arrays. This
  175. is needed to permit asynchronous data transfer, i.e. permit data
  176. transfer to overlap with computations. Otherwise, the trace will show
  177. that the <c>DriverCopyAsync</c> state takes a lot of time, this is
  178. because CUDA or OpenCL then reverts to synchronous transfers.
  179. The application can provide its own allocation function by calling
  180. starpu_malloc_set_hooks(). StarPU will then use them for all data handle
  181. allocations in the main memory.
  182. By default, StarPU leaves replicates of data wherever they were used, in case they
  183. will be re-used by other tasks, thus saving the data transfer time. When some
  184. task modifies some data, all the other replicates are invalidated, and only the
  185. processing unit which ran this task will have a valid replicate of the data. If the application knows
  186. that this data will not be re-used by further tasks, it should advise StarPU to
  187. immediately replicate it to a desired list of memory nodes (given through a
  188. bitmask). This can be understood like the write-through mode of CPU caches.
  189. \code{.c}
  190. starpu_data_set_wt_mask(img_handle, 1<<0);
  191. \endcode
  192. will for instance request to always automatically transfer a replicate into the
  193. main memory (node <c>0</c>), as bit <c>0</c> of the write-through bitmask is being set.
  194. \code{.c}
  195. starpu_data_set_wt_mask(img_handle, ~0U);
  196. \endcode
  197. will request to always automatically broadcast the updated data to all memory
  198. nodes.
  199. Setting the write-through mask to <c>~0U</c> can also be useful to make sure all
  200. memory nodes always have a copy of the data, so that it is never evicted when
  201. memory gets scarse.
  202. Implicit data dependency computation can become expensive if a lot
  203. of tasks access the same piece of data. If no dependency is required
  204. on some piece of data (e.g. because it is only accessed in read-only
  205. mode, or because write accesses are actually commutative), use the
  206. function starpu_data_set_sequential_consistency_flag() to disable
  207. implicit dependencies on this data.
  208. In the same vein, accumulation of results in the same data can become a
  209. bottleneck. The use of the mode ::STARPU_REDUX permits to optimize such
  210. accumulation (see \ref DataReduction). To a lesser extent, the use of
  211. the flag ::STARPU_COMMUTE keeps the bottleneck (see \ref DataCommute), but at least permits
  212. the accumulation to happen in any order.
  213. Applications often need a data just for temporary results. In such a case,
  214. registration can be made without an initial value, for instance this produces a vector data:
  215. \code{.c}
  216. starpu_vector_data_register(&handle, -1, 0, n, sizeof(float));
  217. \endcode
  218. StarPU will then allocate the actual buffer only when it is actually needed,
  219. e.g. directly on the GPU without allocating in main memory.
  220. In the same vein, once the temporary results are not useful any more, the
  221. data should be thrown away. If the handle is not to be reused, it can be
  222. unregistered:
  223. \code{.c}
  224. starpu_data_unregister_submit(handle);
  225. \endcode
  226. actual unregistration will be done after all tasks working on the handle
  227. terminate.
  228. If the handle is to be reused, instead of unregistering it, it can simply be invalidated:
  229. \code{.c}
  230. starpu_data_invalidate_submit(handle);
  231. \endcode
  232. the buffers containing the current value will then be freed, and reallocated
  233. only when another task writes some value to the handle.
  234. \section DataPrefetch Data Prefetch
  235. The scheduling policies <c>heft</c>, <c>dmda</c> and <c>pheft</c>
  236. perform data prefetch (see \ref STARPU_PREFETCH):
  237. as soon as a scheduling decision is taken for a task, requests are issued to
  238. transfer its required data to the target processing unit, if needed, so that
  239. when the processing unit actually starts the task, its data will hopefully be
  240. already available and it will not have to wait for the transfer to finish.
  241. The application may want to perform some manual prefetching, for several reasons
  242. such as excluding initial data transfers from performance measurements, or
  243. setting up an initial statically-computed data distribution on the machine
  244. before submitting tasks, which will thus guide StarPU toward an initial task
  245. distribution (since StarPU will try to avoid further transfers).
  246. This can be achieved by giving the function starpu_data_prefetch_on_node() the
  247. handle and the desired target memory node. The
  248. starpu_data_idle_prefetch_on_node() variant can be used to issue the transfer
  249. only when the bus is idle.
  250. Conversely, one can advise StarPU that some data will not be useful in the
  251. close future by calling starpu_data_wont_use(). StarPU will then write its value
  252. back to its home node, and evict it from GPUs when room is needed.
  253. \section PartitioningData Partitioning Data
  254. An existing piece of data can be partitioned in sub parts to be used by different tasks, for instance:
  255. \code{.c}
  256. #define NX 1048576
  257. #define PARTS 16
  258. int vector[NX];
  259. starpu_data_handle_t handle;
  260. /* Declare data to StarPU */
  261. starpu_vector_data_register(&handle, STARPU_MAIN_RAM, (uintptr_t)vector, NX, sizeof(vector[0]));
  262. /* Partition the vector in PARTS sub-vectors */
  263. struct starpu_data_filter f =
  264. {
  265. .filter_func = starpu_vector_filter_block,
  266. .nchildren = PARTS
  267. };
  268. starpu_data_partition(handle, &f);
  269. \endcode
  270. The task submission then uses the function starpu_data_get_sub_data()
  271. to retrieve the sub-handles to be passed as tasks parameters.
  272. \code{.c}
  273. /* Submit a task on each sub-vector */
  274. for (i=0; i<starpu_data_get_nb_children(handle); i++)
  275. {
  276. /* Get subdata number i (there is only 1 dimension) */
  277. starpu_data_handle_t sub_handle = starpu_data_get_sub_data(handle, 1, i);
  278. struct starpu_task *task = starpu_task_create();
  279. task->handles[0] = sub_handle;
  280. task->cl = &cl;
  281. task->synchronous = 1;
  282. task->cl_arg = &factor;
  283. task->cl_arg_size = sizeof(factor);
  284. starpu_task_submit(task);
  285. }
  286. \endcode
  287. Partitioning can be applied several times, see
  288. <c>examples/basic_examples/mult.c</c> and <c>examples/filters/</c>.
  289. Wherever the whole piece of data is already available, the partitioning will
  290. be done in-place, i.e. without allocating new buffers but just using pointers
  291. inside the existing copy. This is particularly important to be aware of when
  292. using OpenCL, where the kernel parameters are not pointers, but \c cl_mem handles. The
  293. kernel thus needs to be also passed the offset within the OpenCL buffer:
  294. \code{.c}
  295. void opencl_func(void *buffers[], void *cl_arg)
  296. {
  297. cl_mem vector = (cl_mem) STARPU_VECTOR_GET_DEV_HANDLE(buffers[0]);
  298. unsigned offset = STARPU_BLOCK_GET_OFFSET(buffers[0]);
  299. ...
  300. clSetKernelArg(kernel, 0, sizeof(vector), &vector);
  301. clSetKernelArg(kernel, 1, sizeof(offset), &offset);
  302. ...
  303. }
  304. \endcode
  305. And the kernel has to shift from the pointer passed by the OpenCL driver:
  306. \code{.c}
  307. __kernel void opencl_kernel(__global int *vector, unsigned offset)
  308. {
  309. block = (__global void *)block + offset;
  310. ...
  311. }
  312. \endcode
  313. When the sub-data is not of the same type as the original data, the
  314. starpu_data_filter::get_child_ops field needs to be set appropriately for StarPU
  315. to know which type should be used.
  316. StarPU provides various interfaces and filters for matrices, vectors, etc.,
  317. but applications can also write their own data interfaces and filters, see
  318. <c>examples/interface</c> and <c>examples/filters/custom_mf</c> for an example,
  319. and see \ref DefiningANewDataInterface and \ref DefiningANewDataFilter
  320. for documentation.
  321. \section AsynchronousPartitioning Asynchronous Partitioning
  322. The partitioning functions described in the previous section are synchronous:
  323. starpu_data_partition() and starpu_data_unpartition() both wait for all the tasks
  324. currently working on the data. This can be a bottleneck for the application.
  325. An asynchronous API also exists, it works only on handles with sequential
  326. consistency. The principle is to first plan the partitioning, which returns
  327. data handles of the partition, which are not functional yet. When submitting
  328. tasks, one can mix using the handles of the partition, of the whole data. One
  329. can even partition recursively and mix using handles at different levels of the
  330. recursion. Of course, StarPU will have to introduce coherency synchronization.
  331. <c>fmultiple_submit_implicit</c> is a complete example using this technique.
  332. One can also look at <c>fmultiple_submit_readonly</c> which contains the
  333. explicit coherency synchronization which are automatically introduced by StarPU
  334. for <c>fmultiple_submit_implicit</c>.
  335. In short, we first register a matrix and plan the partitioning:
  336. \code{.c}
  337. starpu_matrix_data_register(&handle, STARPU_MAIN_RAM, (uintptr_t)matrix, NX, NX, NY, sizeof(matrix[0]));
  338. struct starpu_data_filter f_vert =
  339. {
  340. .filter_func = starpu_matrix_filter_block,
  341. .nchildren = PARTS
  342. };
  343. starpu_data_partition_plan(handle, &f_vert, vert_handle);
  344. \endcode
  345. starpu_data_partition_plan() returns the handles for the partition in <c>vert_handle</c>.
  346. One can then submit tasks working on the main handle, and tasks working on
  347. <c>vert_handle</c> handles. Between using the main handle and <c>vert_handle</c>
  348. handles, StarPU will automatically call starpu_data_partition_submit() and
  349. starpu_data_unpartition_submit().
  350. All this code is asynchronous, just submitting which tasks, partitioning and
  351. unpartitioning will be done at runtime.
  352. Planning several partitioning of the same data is also possible, StarPU will
  353. unpartition and repartition as needed when mixing accesses of different
  354. partitions. If data access is done in read-only mode, StarPU will allow the
  355. different partitioning to coexist. As soon as a data is accessed in read-write
  356. mode, StarPU will automatically unpartition everything and activate only the
  357. partitioning leading to the data being written to.
  358. For instance, for a stencil application, one can split a subdomain into
  359. its interior and halos, and then just submit a task updating the whole
  360. subdomain, then submit MPI sends/receives to update the halos, then submit
  361. again a task updating the whole subdomain, etc. and StarPU will automatically
  362. partition/unpartition each time.
  363. \section ManualPartitioning Manual Partitioning
  364. One can also handle partitioning by hand, by registering several views on the
  365. same piece of data. The idea is then to manage the coherency of the various
  366. views through the common buffer in the main memory.
  367. <c>fmultiple_manual</c> is a complete example using this technique.
  368. In short, we first register the same matrix several times:
  369. \code{.c}
  370. starpu_matrix_data_register(&handle, STARPU_MAIN_RAM, (uintptr_t)matrix, NX, NX, NY, sizeof(matrix[0]));
  371. for (i = 0; i < PARTS; i++)
  372. starpu_matrix_data_register(&vert_handle[i], STARPU_MAIN_RAM, (uintptr_t)&matrix[0][i*(NX/PARTS)], NX, NX/PARTS, NY, sizeof(matrix[0][0]));
  373. \endcode
  374. Since StarPU is not aware that the two handles are actually pointing to the same
  375. data, we have a danger of inadvertently submitting tasks to both views, which
  376. will bring a mess since StarPU will not guarantee any coherency between the two
  377. views. To make sure we don't do this, we invalidate the view that we will not
  378. use:
  379. \code{.c}
  380. for (i = 0; i < PARTS; i++)
  381. starpu_data_invalidate(vert_handle[i]);
  382. \endcode
  383. Then we can safely work on <c>handle</c>.
  384. When we want to switch to the vertical slice view, all we need to do is bring
  385. coherency between them by running an empty task on the home node of the data:
  386. \code{.c}
  387. void empty(void *buffers[], void *cl_arg)
  388. { }
  389. struct starpu_codelet cl_switch =
  390. {
  391. .cpu_funcs = {empty},
  392. .nbuffers = STARPU_VARIABLE_NBUFFERS,
  393. };
  394. ret = starpu_task_insert(&cl_switch, STARPU_RW, handle,
  395. STARPU_W, vert_handle[0],
  396. STARPU_W, vert_handle[1],
  397. 0);
  398. \endcode
  399. The execution of the <c>switch</c> task will get back the matrix data into the
  400. main memory, and thus the vertical slices will get the updated value there.
  401. Again, we prefer to make sure that we don't accidentally access the matrix through the whole-matrix handle:
  402. \code{.c}
  403. starpu_data_invalidate_submit(handle);
  404. \endcode
  405. And now we can start using vertical slices, etc.
  406. \section DefiningANewDataFilter Defining A New Data Filter
  407. StarPU provides a series of predefined filters in \ref API_Data_Partition, but
  408. additional filters can be defined by the application. The principle is that the
  409. filter function just fills the memory location of the <c>i-th</c> subpart of a data.
  410. Examples are provided in <c>src/datawizard/interfaces/*_filters.c</c>,
  411. and see \ref starpu_data_filter::filter_func for the details.
  412. The starpu_filter_nparts_compute_chunk_size_and_offset() helper can be used to
  413. compute the division of pieces of data.
  414. \section DataReduction Data Reduction
  415. In various cases, some piece of data is used to accumulate intermediate
  416. results. For instances, the dot product of a vector, maximum/minimum finding,
  417. the histogram of a photograph, etc. When these results are produced along the
  418. whole machine, it would not be efficient to accumulate them in only one place,
  419. incurring data transmission each and access concurrency.
  420. StarPU provides a mode ::STARPU_REDUX, which permits to optimize
  421. this case: it will allocate a buffer on each memory node, and accumulate
  422. intermediate results there. When the data is eventually accessed in the normal
  423. mode ::STARPU_R, StarPU will collect the intermediate results in just one
  424. buffer.
  425. For this to work, the user has to use the function
  426. starpu_data_set_reduction_methods() to declare how to initialize these
  427. buffers, and how to assemble partial results.
  428. For instance, <c>cg</c> uses that to optimize its dot product: it first defines
  429. the codelets for initialization and reduction:
  430. \code{.c}
  431. struct starpu_codelet bzero_variable_cl =
  432. {
  433. .cpu_funcs = { bzero_variable_cpu },
  434. .cpu_funcs_name = { "bzero_variable_cpu" },
  435. .cuda_funcs = { bzero_variable_cuda },
  436. .nbuffers = 1,
  437. }
  438. static void accumulate_variable_cpu(void *descr[], void *cl_arg)
  439. {
  440. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  441. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  442. *v_dst = *v_dst + *v_src;
  443. }
  444. static void accumulate_variable_cuda(void *descr[], void *cl_arg)
  445. {
  446. double *v_dst = (double *)STARPU_VARIABLE_GET_PTR(descr[0]);
  447. double *v_src = (double *)STARPU_VARIABLE_GET_PTR(descr[1]);
  448. cublasaxpy(1, (double)1.0, v_src, 1, v_dst, 1);
  449. cudaStreamSynchronize(starpu_cuda_get_local_stream());
  450. }
  451. struct starpu_codelet accumulate_variable_cl =
  452. {
  453. .cpu_funcs = { accumulate_variable_cpu },
  454. .cpu_funcs_name = { "accumulate_variable_cpu" },
  455. .cuda_funcs = { accumulate_variable_cuda },
  456. .nbuffers = 1,
  457. }
  458. \endcode
  459. and attaches them as reduction methods for its handle <c>dtq</c>:
  460. \code{.c}
  461. starpu_variable_data_register(&dtq_handle, -1, NULL, sizeof(type));
  462. starpu_data_set_reduction_methods(dtq_handle, &accumulate_variable_cl, &bzero_variable_cl);
  463. \endcode
  464. and <c>dtq_handle</c> can now be used in mode ::STARPU_REDUX for the
  465. dot products with partitioned vectors:
  466. \code{.c}
  467. for (b = 0; b < nblocks; b++)
  468. starpu_task_insert(&dot_kernel_cl,
  469. STARPU_REDUX, dtq_handle,
  470. STARPU_R, starpu_data_get_sub_data(v1, 1, b),
  471. STARPU_R, starpu_data_get_sub_data(v2, 1, b),
  472. 0);
  473. \endcode
  474. During registration, we have here provided <c>NULL</c>, i.e. there is
  475. no initial value to be taken into account during reduction. StarPU
  476. will thus only take into account the contributions from the tasks
  477. <c>dot_kernel_cl</c>. Also, it will not allocate any memory for
  478. <c>dtq_handle</c> before tasks <c>dot_kernel_cl</c> are ready to run.
  479. If another dot product has to be performed, one could unregister
  480. <c>dtq_handle</c>, and re-register it. But one can also call
  481. starpu_data_invalidate_submit() with the parameter <c>dtq_handle</c>,
  482. which will clear all data from the handle, thus resetting it back to
  483. the initial status <c>register(NULL)</c>.
  484. The example <c>cg</c> also uses reduction for the blocked gemv kernel,
  485. leading to yet more relaxed dependencies and more parallelism.
  486. ::STARPU_REDUX can also be passed to starpu_mpi_task_insert() in the MPI
  487. case. This will however not produce any MPI communication, but just pass
  488. ::STARPU_REDUX to the underlying starpu_task_insert(). It is up to the
  489. application to call starpu_mpi_redux_data(), which posts tasks which will
  490. reduce the partial results among MPI nodes into the MPI node which owns the
  491. data. For instance, some hypothetical application which collects partial results
  492. into data <c>res</c>, then uses it for other computation, before looping again
  493. with a new reduction:
  494. \code{.c}
  495. for (i = 0; i < 100; i++)
  496. {
  497. starpu_mpi_task_insert(MPI_COMM_WORLD, &init_res, STARPU_W, res, 0);
  498. starpu_mpi_task_insert(MPI_COMM_WORLD, &work, STARPU_RW, A, STARPU_R, B, STARPU_REDUX, res, 0);
  499. starpu_mpi_redux_data(MPI_COMM_WORLD, res);
  500. starpu_mpi_task_insert(MPI_COMM_WORLD, &work2, STARPU_RW, B, STARPU_R, res, 0);
  501. }
  502. \endcode
  503. \section DataCommute Commute Data Access
  504. By default, the implicit dependencies computed from data access use the
  505. sequential semantic. Notably, write accesses are always serialized in the order
  506. of submission. In some applicative cases, the write contributions can actually
  507. be performed in any order without affecting the eventual result. In this case
  508. it is useful to drop the strictly sequential semantic, to improve parallelism
  509. by allowing StarPU to reorder the write accesses. This can be done by using
  510. the ::STARPU_COMMUTE data access flag. Accesses without this flag will however
  511. properly be serialized against accesses with this flag. For instance:
  512. \code{.c}
  513. starpu_task_insert(&cl1, STARPU_R, h, STARPU_RW, handle, 0);
  514. starpu_task_insert(&cl2, STARPU_R, handle1, STARPU_RW|STARPU_COMMUTE, handle, 0);
  515. starpu_task_insert(&cl2, STARPU_R, handle2, STARPU_RW|STARPU_COMMUTE, handle, 0);
  516. starpu_task_insert(&cl3, STARPU_R, g, STARPU_RW, handle, 0);
  517. \endcode
  518. The two tasks running <c>cl2</c> will be able to commute: depending on whether the
  519. value of <c>handle1</c> or <c>handle2</c> becomes available first, the corresponding task
  520. running <c>cl2</c> will start first. The task running <c>cl1</c> will however always be run
  521. before them, and the task running <c>cl3</c> will always be run after them.
  522. If a lot of tasks use the commute access on the same set of data and a lot of
  523. them are ready at the same time, it may become interesting to use an arbiter,
  524. see \ref ConcurrentDataAccess.
  525. \section ConcurrentDataAccess Concurrent Data Accesses
  526. When several tasks are ready and will work on several data, StarPU is faced with
  527. the classical Dining Philosophers problem, and has to determine the order in
  528. which it will run the tasks.
  529. Data accesses usually use sequential ordering, so data accesses are usually
  530. already serialized, and thus by default StarPU uses the Dijkstra solution which
  531. scales very well in terms of overhead: tasks will just acquire data one by one
  532. by data handle pointer value order.
  533. When sequential ordering is disabled or the ::STARPU_COMMUTE flag is used, there
  534. may be a lot of concurrent accesses to the same data, and the Dijkstra solution
  535. gets only poor parallelism, typically in some pathological cases which do happen
  536. in various applications. In this case, one can use a data access arbiter, which
  537. implements the classical centralized solution for the Dining Philosophers
  538. problem. This is more expensive in terms of overhead since it is centralized,
  539. but it opportunistically gets a lot of parallelism. The centralization can also
  540. be avoided by using several arbiters, thus separating sets of data for which
  541. arbitration will be done. If a task accesses data from different arbiters, it
  542. will acquire them arbiter by arbiter, in arbiter pointer value order.
  543. See the <c>tests/datawizard/test_arbiter.cpp</c> example.
  544. Arbiters however do not support the ::STARPU_REDUX flag yet.
  545. \section TemporaryBuffers Temporary Buffers
  546. There are two kinds of temporary buffers: temporary data which just pass results
  547. from a task to another, and scratch data which are needed only internally by
  548. tasks.
  549. \subsection TemporaryData Temporary Data
  550. Data can sometimes be entirely produced by a task, and entirely consumed by
  551. another task, without the need for other parts of the application to access
  552. it. In such case, registration can be done without prior allocation, by using
  553. the special memory node number <c>-1</c>, and passing a zero pointer. StarPU will
  554. actually allocate memory only when the task creating the content gets scheduled,
  555. and destroy it on unregistration.
  556. In addition to this, it can be tedious for the application to have to unregister
  557. the data, since it will not use its content anyway. The unregistration can be
  558. done lazily by using the function starpu_data_unregister_submit(),
  559. which will record that no more tasks accessing the handle will be submitted, so
  560. that it can be freed as soon as the last task accessing it is over.
  561. The following code examplifies both points: it registers the temporary
  562. data, submits three tasks accessing it, and records the data for automatic
  563. unregistration.
  564. \code{.c}
  565. starpu_vector_data_register(&handle, -1, 0, n, sizeof(float));
  566. starpu_task_insert(&produce_data, STARPU_W, handle, 0);
  567. starpu_task_insert(&compute_data, STARPU_RW, handle, 0);
  568. starpu_task_insert(&summarize_data, STARPU_R, handle, STARPU_W, result_handle, 0);
  569. starpu_data_unregister_submit(handle);
  570. \endcode
  571. The application may also want to see the temporary data initialized
  572. on the fly before being used by the task. This can be done by using
  573. starpu_data_set_reduction_methods() to set an initialization codelet (no redux
  574. codelet is needed).
  575. \subsection ScratchData Scratch Data
  576. Some kernels sometimes need temporary data to achieve the computations, i.e. a
  577. workspace. The application could allocate it at the start of the codelet
  578. function, and free it at the end, but this would be costly. It could also
  579. allocate one buffer per worker (similarly to \ref HowToInitializeAComputationLibraryOnceForEachWorker),
  580. but this would
  581. make them systematic and permanent. A more optimized way is to use
  582. the data access mode ::STARPU_SCRATCH, as examplified below, which
  583. provides per-worker buffers without content consistency. The buffer is
  584. registered only once, using memory node <c>-1</c>, i.e. the application didn't allocate
  585. memory for it, and StarPU will allocate it on demand at task execution.
  586. \code{.c}
  587. starpu_vector_data_register(&workspace, -1, 0, sizeof(float));
  588. for (i = 0; i < N; i++)
  589. starpu_task_insert(&compute, STARPU_R, input[i], STARPU_SCRATCH, workspace, STARPU_W, output[i], 0);
  590. \endcode
  591. StarPU will make sure that the buffer is allocated before executing the task,
  592. and make this allocation per-worker: for CPU workers, notably, each worker has
  593. its own buffer. This means that each task submitted above will actually have its
  594. own workspace, which will actually be the same for all tasks running one after
  595. the other on the same worker. Also, if for instance memory becomes scarce,
  596. StarPU will notice that it can free such buffers easily, since the content does
  597. not matter.
  598. The example <c>examples/pi</c> uses scratches for some temporary buffer.
  599. \section TheMultiformatInterface The Multiformat Interface
  600. It may be interesting to represent the same piece of data using two different
  601. data structures: one only used on CPUs, and one only used on GPUs.
  602. This can be done by using the multiformat interface. StarPU
  603. will be able to convert data from one data structure to the other when needed.
  604. Note that the scheduler <c>dmda</c> is the only one optimized for this
  605. interface. The user must provide StarPU with conversion codelets:
  606. \snippet multiformat.c To be included. You should update doxygen if you see this text.
  607. Kernels can be written almost as for any other interface. Note that
  608. ::STARPU_MULTIFORMAT_GET_CPU_PTR shall only be used for CPU kernels. CUDA kernels
  609. must use ::STARPU_MULTIFORMAT_GET_CUDA_PTR, and OpenCL kernels must use
  610. ::STARPU_MULTIFORMAT_GET_OPENCL_PTR. ::STARPU_MULTIFORMAT_GET_NX may
  611. be used in any kind of kernel.
  612. \code{.c}
  613. static void
  614. multiformat_scal_cpu_func(void *buffers[], void *args)
  615. {
  616. struct point *aos;
  617. unsigned int n;
  618. aos = STARPU_MULTIFORMAT_GET_CPU_PTR(buffers[0]);
  619. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  620. ...
  621. }
  622. extern "C" void multiformat_scal_cuda_func(void *buffers[], void *_args)
  623. {
  624. unsigned int n;
  625. struct struct_of_arrays *soa;
  626. soa = (struct struct_of_arrays *) STARPU_MULTIFORMAT_GET_CUDA_PTR(buffers[0]);
  627. n = STARPU_MULTIFORMAT_GET_NX(buffers[0]);
  628. ...
  629. }
  630. \endcode
  631. A full example may be found in <c>examples/basic_examples/multiformat.c</c>.
  632. \section DefiningANewDataInterface Defining A New Data Interface
  633. This section proposes an example how to define your own interface, when the
  634. StarPU-provided interface do not fit your needs. Here we take a dumb example of
  635. an array of complex numbers represented by two arrays of double values.
  636. Let's thus define a new data interface to manage arrays of complex numbers:
  637. \code{.c}
  638. /* interface for complex numbers */
  639. struct starpu_complex_interface
  640. {
  641. double *real;
  642. double *imaginary;
  643. int nx;
  644. };
  645. \endcode
  646. That structure stores enough to describe <b>one</b> buffer of such kind of
  647. data. It is used for the buffer stored in the main memory, another instance
  648. is used for the buffer stored in a GPU, etc. A <i>data handle</i> is thus a
  649. collection of such structures, to remember each buffer on each memory node.
  650. Note: one should not take pointers into such structures, because StarPU needs
  651. to be able to copy over the content of it to various places, for instance to
  652. efficiently migrate a data buffer from one data handle to another data handle.
  653. Registering such a data to StarPU is easily done using the function
  654. starpu_data_register(). The last
  655. parameter of the function, <c>interface_complex_ops</c>, will be
  656. described below.
  657. \code{.c}
  658. void starpu_complex_data_register(starpu_data_handle_t *handle,
  659. unsigned home_node, double *real, double *imaginary, int nx)
  660. {
  661. struct starpu_complex_interface complex =
  662. {
  663. .real = real,
  664. .imaginary = imaginary,
  665. .nx = nx
  666. };
  667. if (interface_complex_ops.interfaceid == STARPU_UNKNOWN_INTERFACE_ID)
  668. {
  669. interface_complex_ops.interfaceid = starpu_data_interface_get_next_id();
  670. }
  671. starpu_data_register(handleptr, home_node, &complex, &interface_complex_ops);
  672. }
  673. \endcode
  674. The <c>struct starpu_complex_interface complex</c> is here used just to store the
  675. parameters that the user provided to <c>starpu_complex_data_register</c>.
  676. starpu_data_register() will first allocate the handle, and
  677. then pass the <c>starpu_complex_interface</c> structure to the
  678. starpu_data_interface_ops::register_data_handle method, which records them
  679. within the data handle (it is called once per node by starpu_data_register()):
  680. \code{.c}
  681. static void complex_register_data_handle(starpu_data_handle_t handle, unsigned home_node, void *data_interface)
  682. {
  683. struct starpu_complex_interface *complex_interface = (struct starpu_complex_interface *) data_interface;
  684. unsigned node;
  685. for (node = 0; node < STARPU_MAXNODES; node++)
  686. {
  687. struct starpu_complex_interface *local_interface = (struct starpu_complex_interface *)
  688. starpu_data_get_interface_on_node(handle, node);
  689. local_interface->nx = complex_interface->nx;
  690. if (node == home_node)
  691. {
  692. local_interface->real = complex_interface->real;
  693. local_interface->imaginary = complex_interface->imaginary;
  694. }
  695. else
  696. {
  697. local_interface->real = NULL;
  698. local_interface->imaginary = NULL;
  699. }
  700. }
  701. }
  702. \endcode
  703. If the application provided a home node, the corresponding pointers will be
  704. recorded for that node. Others have no buffer allocated yet.
  705. Different operations need to be defined for a data interface through
  706. the type starpu_data_interface_ops. We only define here the basic
  707. operations needed to run simple applications. The source code for the
  708. different functions can be found in the file
  709. <c>examples/interface/complex_interface.c</c>, the details of the hooks to be
  710. provided are documented in \ref starpu_data_interface_ops .
  711. \code{.c}
  712. static struct starpu_data_interface_ops interface_complex_ops =
  713. {
  714. .register_data_handle = complex_register_data_handle,
  715. .allocate_data_on_node = complex_allocate_data_on_node,
  716. .copy_methods = &complex_copy_methods,
  717. .get_size = complex_get_size,
  718. .footprint = complex_footprint,
  719. .interfaceid = STARPU_UNKNOWN_INTERFACE_ID,
  720. .interface_size = sizeof(struct starpu_complex_interface),
  721. };
  722. \endcode
  723. Functions need to be defined to access the different fields of the
  724. complex interface from a StarPU data handle.
  725. \code{.c}
  726. double *starpu_complex_get_real(starpu_data_handle_t handle)
  727. {
  728. struct starpu_complex_interface *complex_interface =
  729. (struct starpu_complex_interface *) starpu_data_get_interface_on_node(handle, STARPU_MAIN_RAM);
  730. return complex_interface->real;
  731. }
  732. double *starpu_complex_get_imaginary(starpu_data_handle_t handle);
  733. int starpu_complex_get_nx(starpu_data_handle_t handle);
  734. \endcode
  735. Similar functions need to be defined to access the different fields of the
  736. complex interface from a <c>void *</c> pointer to be used within codelet
  737. implemetations.
  738. \snippet complex.c To be included. You should update doxygen if you see this text.
  739. Complex data interfaces can then be registered to StarPU.
  740. \code{.c}
  741. double real = 45.0;
  742. double imaginary = 12.0;
  743. starpu_complex_data_register(&handle1, STARPU_MAIN_RAM, &real, &imaginary, 1);
  744. starpu_task_insert(&cl_display, STARPU_R, handle1, 0);
  745. \endcode
  746. and used by codelets.
  747. \code{.c}
  748. void display_complex_codelet(void *descr[], void *_args)
  749. {
  750. int nx = STARPU_COMPLEX_GET_NX(descr[0]);
  751. double *real = STARPU_COMPLEX_GET_REAL(descr[0]);
  752. double *imaginary = STARPU_COMPLEX_GET_IMAGINARY(descr[0]);
  753. int i;
  754. for(i=0 ; i<nx ; i++)
  755. {
  756. fprintf(stderr, "Complex[%d] = %3.2f + %3.2f i\n", i, real[i], imaginary[i]);
  757. }
  758. }
  759. \endcode
  760. The whole code for this complex data interface is available in the
  761. directory <c>examples/interface/</c>.
  762. \section SpecifyingATargetNode Specifying A Target Node For Task Data
  763. When executing a task on a GPU for instance, StarPU would normally copy all the
  764. needed data for the tasks on the embedded memory of the GPU. It may however
  765. happen that the task kernel would rather have some of the datas kept in the
  766. main memory instead of copied in the GPU, a pivoting vector for instance.
  767. This can be achieved by setting the starpu_codelet::specific_nodes flag to
  768. <c>1</c>, and then fill the starpu_codelet::nodes array (or starpu_codelet::dyn_nodes when
  769. starpu_codelet::nbuffers is greater than \ref STARPU_NMAXBUFS) with the node numbers
  770. where data should be copied to, or ::STARPU_SPECIFIC_NODE_LOCAL to let
  771. StarPU copy it to the memory node where the task will be executed.
  772. ::STARPU_SPECIFIC_NODE_CPU can also be used to request data to be
  773. put in CPU-accessible memory (and let StarPU choose the NUMA node).
  774. ::STARPU_SPECIFIC_NODE_FAST and ::STARPU_SPECIFIC_NODE_SLOW can also be
  775. used
  776. For instance,
  777. with the following codelet:
  778. \code{.c}
  779. struct starpu_codelet cl =
  780. {
  781. .cuda_funcs = { kernel },
  782. .nbuffers = 2,
  783. .modes = {STARPU_RW, STARPU_RW},
  784. .specific_nodes = 1,
  785. .nodes = {STARPU_SPECIFIC_NODE_CPU, STARPU_SPECIFIC_NODE_LOCAL},
  786. };
  787. \endcode
  788. the first data of the task will be kept in the CPU memory, while the second
  789. data will be copied to the CUDA GPU as usual. A working example is available in
  790. <c>tests/datawizard/specific_node.c</c>
  791. With the following codelet:
  792. \code{.c}
  793. struct starpu_codelet cl =
  794. {
  795. .cuda_funcs = { kernel },
  796. .nbuffers = 2,
  797. .modes = {STARPU_RW, STARPU_RW},
  798. .specific_nodes = 1,
  799. .nodes = {STARPU_SPECIFIC_NODE_LOCAL, STARPU_SPECIFIC_NODE_SLOW},
  800. };
  801. \endcode
  802. The first data will be copied into fast (but probably size-limited) local memory
  803. while the second data will be left in slow (but large) memory. This makes sense
  804. when the kernel does not make so many accesses to the second data, and thus data
  805. being remote e.g. over a PCI bus is not a performance problem, and avoids
  806. filling the fast local memory with data which does not need the performance.
  807. In cases where the kernel is fine with some data being either local or in the
  808. main memory, ::STARPU_SPECIFIC_NODE_LOCAL_OR_CPU can be used. StarPU will then
  809. be free to leave the data in the main memory and let the kernel access it from
  810. accelerators, or to move it to the accelerator before starting the kernel, for
  811. instance:
  812. \code{.c}
  813. struct starpu_codelet cl =
  814. {
  815. .cuda_funcs = { kernel },
  816. .nbuffers = 2,
  817. .modes = {STARPU_RW, STARPU_R},
  818. .specific_nodes = 1,
  819. .nodes = {STARPU_SPECIFIC_NODE_LOCAL, STARPU_SPECIFIC_NODE_LOCAL_OR_CPU},
  820. };
  821. \endcode
  822. */