StarPU Handbook
|
One may want to write multiple implementations of a codelet for a single type of device and let StarPU choose which one to run. As an example, we will show how to use SSE to scale a vector. The codelet can be written as follows:
Schedulers which are multi-implementation aware (only dmda
and pheft
for now) will use the performance models of all the implementations it was given, and pick the one that seems to be the fastest.
Some implementations may not run on some devices. For instance, some CUDA devices do not support double floating point precision, and thus the kernel execution would just fail; or the device may not have enough shared memory for the implementation being used. The field starpu_codelet::can_execute permits to express this. For instance:
This can be essential e.g. when running on a machine which mixes various models of CUDA devices, to take benefit from the new models without crashing on old models.
Note: the function starpu_codelet::can_execute is called by the scheduler each time it tries to match a task with a worker, and should thus be very fast. The function starpu_cuda_get_device_properties() provides a quick access to CUDA properties of CUDA devices to achieve such efficiency.
Another example is to compile CUDA code for various compute capabilities, resulting with two CUDA functions, e.g. scal_gpu_13
for compute capability 1.3, and scal_gpu_20
for compute capability 2.0. Both functions can be provided to StarPU by using starpu_codelet::cuda_funcs, and starpu_codelet::can_execute can then be used to rule out the scal_gpu_20
variant on a CUDA device which will not be able to execute it:
Note: the most generic variant should be provided first, as some schedulers are not able to try the different variants.
A full example showing how to use the profiling API is available in the StarPU sources in the directory examples/profiling/
.
An existing piece of data can be partitioned in sub parts to be used by different tasks, for instance:
The task submission then uses the function starpu_data_get_sub_data() to retrieve the sub-handles to be passed as tasks parameters.
Partitioning can be applied several times, see examples/basic_examples/mult.c
and examples/filters/
.
Wherever the whole piece of data is already available, the partitioning will be done in-place, i.e. without allocating new buffers but just using pointers inside the existing copy. This is particularly important to be aware of when using OpenCL, where the kernel parameters are not pointers, but handles. The kernel thus needs to be also passed the offset within the OpenCL buffer:
And the kernel has to shift from the pointer passed by the OpenCL driver:
StarPU provides various interfaces and filters for matrices, vectors, etc., but applications can also write their own data interfaces and filters, see examples/interface
and examples/filters/custom_mf
for an example.
To achieve good scheduling, StarPU scheduling policies need to be able to estimate in advance the duration of a task. This is done by giving to codelets a performance model, by defining a structure starpu_perfmodel and providing its address in the field starpu_codelet::model. The fields starpu_perfmodel::symbol and starpu_perfmodel::type are mandatory, to give a name to the model, and the type of the model, since there are several kinds of performance models. For compatibility, make sure to initialize the whole structure to zero, either by using explicit memset(), or by letting the compiler implicitly do it as examplified below.
Measured at runtime (model type STARPU_HISTORY_BASED). This assumes that for a given set of data input/output sizes, the performance will always be about the same. This is very true for regular kernels on GPUs for instance (<0.1% error), and just a bit less true on CPUs (~=1% error). This also assumes that there are few different sets of data input/output sizes. StarPU will then keep record of the average time of previous executions on the various processing units, and use it as an estimation. History is done per task size, by using a hash of the input and ouput sizes as an index. It will also save it in $STARPU_HOME/.starpu/sampling/codelets
for further executions, and can be observed by using the tool starpu_perfmodel_display
, or drawn by using the tool starpu_perfmodel_plot
(Performance Model Calibration). The models are indexed by machine name. To share the models between machines (e.g. for a homogeneous cluster), use export STARPU_HOSTNAME=some_global_name
. Measurements are only done when using a task scheduler which makes use of it, such as dmda
. Measurements can also be provided explicitly by the application, by using the function starpu_perfmodel_update_history().
The following is a small code example.
If e.g. the code is recompiled with other compilation options, or several variants of the code are used, the symbol string should be changed to reflect that, in order to recalibrate a new model from zero. The symbol string can even be constructed dynamically at execution time, as long as this is done before submitting any task using it.
Measured at runtime and refined by regression (model types STARPU_REGRESSION_BASED and STARPU_NL_REGRESSION_BASED). This still assumes performance regularity, but works with various data input sizes, by applying regression over observed execution times. STARPU_REGRESSION_BASED uses an a*n^b regression form, STARPU_NL_REGRESSION_BASED uses an a*n^b+c (more precise than STARPU_REGRESSION_BASED, but costs a lot more to compute).
For instance, tests/perfmodels/regression_based.c
uses a regression-based performance model for the function memset().
Of course, the application has to issue tasks with varying size so that the regression can be computed. StarPU will not trust the regression unless there is at least 10% difference between the minimum and maximum observed input size. It can be useful to set the environment variable STARPU_CALIBRATE to 1
and run the application on varying input sizes with STARPU_SCHED set to dmda
scheduler, so as to feed the performance model for a variety of inputs. The application can also provide the measurements explictly by using the function starpu_perfmodel_update_history(). The tools starpu_perfmodel_display
and starpu_perfmodel_plot
can be used to observe how much the performance model is calibrated (Performance Model Calibration); when their output look good, STARPU_CALIBRATE can be reset to 0
to let StarPU use the resulting performance model without recording new measures, and STARPU_SCHED can be set to dmda
to benefit from the performance models. If the data input sizes vary a lot, it is really important to set STARPU_CALIBRATE to 0
, otherwise StarPU will continue adding the measures, and result with a very big performance model, which will take time a lot of time to load and save.
For non-linear regression, since computing it is quite expensive, it is only done at termination of the application. This means that the first execution of the application will use only history-based performance model to perform scheduling, without using regression.
Provided as an estimation from the application itself (model type STARPU_COMMON and field starpu_perfmodel::cost_function), see for instance examples/common/blas_model.h
and examples/common/blas_model.c
.
.per_arch[arch][nimpl].cost_function
have to be filled with pointers to functions which return the expected duration of the task in micro-seconds, one per architecture. For STARPU_HISTORY_BASED, STARPU_REGRESSION_BASED, and STARPU_NL_REGRESSION_BASED, the total size of task data (both input and output) is used as an index by default. The field starpu_perfmodel::size_base however permits the application to override that, when for instance some of the data do not matter for task cost (e.g. mere reference table), or when using sparse structures (in which case it is the number of non-zeros which matter), or when there is some hidden parameter such as the number of iterations, or when the application actually has a very good idea of the complexity of the algorithm, and just not the speed of the processor, etc. The example in the directory examples/pi
uses this to include the number of iterations in the base.
StarPU will automatically determine when the performance model is calibrated, or rather, it will assume the performance model is calibrated until the application submits a task for which the performance can not be predicted. For STARPU_HISTORY_BASED, StarPU will require 10 (STARPU_CALIBRATE_MINIMUM) measurements for a given size before estimating that an average can be taken as estimation for further executions with the same size. For STARPU_REGRESSION_BASED and STARPU_NL_REGRESSION_BASED, StarPU will require 10 (STARPU_CALIBRATE_MINIMUM) measurements, and that the minimum measured data size is smaller than 90% of the maximum measured data size (i.e. the measurement interval is large enough for a regression to have a meaning). Calibration can also be forced by setting the STARPU_CALIBRATE environment variable to 1
, or even reset by setting it to 2
.
How to use schedulers which can benefit from such performance model is explained in Task Scheduling Policy.
The same can be done for task power consumption estimation, by setting the field starpu_codelet::power_model the same way as the field starpu_codelet::model. Note: for now, the application has to give to the power consumption performance model a name which is different from the execution time performance model.
The application can request time estimations from the StarPU performance models by filling a task structure as usual without actually submitting it. The data handles can be created by calling any of the functions starpu_*_data_register
with a NULL
pointer and -1
node and the desired data sizes, and need to be unregistered as usual. The functions starpu_task_expected_length() and starpu_task_expected_power() can then be called to get an estimation of the task cost on a given arch. starpu_task_footprint() can also be used to get the footprint used for indexing history-based performance models. starpu_task_destroy() needs to be called to destroy the dummy task afterwards. See tests/perfmodels/regression_based.c
for an example.
For kernels with history-based performance models (and provided that they are completely calibrated), StarPU can very easily provide a theoretical lower bound for the execution time of a whole set of tasks. See for instance examples/lu/lu_example.c
: before submitting tasks, call the function starpu_bound_start(), and after complete execution, call starpu_bound_stop(). starpu_bound_print_lp() or starpu_bound_print_mps() can then be used to output a Linear Programming problem corresponding to the schedule of your tasks. Run it through lp_solve
or any other linear programming solver, and that will give you a lower bound for the total execution time of your tasks. If StarPU was compiled with the library glpk
installed, starpu_bound_compute() can be used to solve it immediately and get the optimized minimum, in ms. Its parameter integer
allows to decide whether integer resolution should be computed and returned
The deps
parameter tells StarPU whether to take tasks, implicit data, and tag dependencies into account. Tags released in a callback or similar are not taken into account, only tags associated with a task are. It must be understood that the linear programming problem size is quadratic with the number of tasks and thus the time to solve it will be very long, it could be minutes for just a few dozen tasks. You should probably use lp_solve -timeout 1 test.pl -wmps test.mps
to convert the problem to MPS format and then use a better solver, glpsol
might be better than lp_solve
for instance (the –pcost
option may be useful), but sometimes doesn't manage to converge. cbc
might look slower, but it is parallel. For lp_solve
, be sure to try at least all the -B
options. For instance, we often just use lp_solve -cc -B1 -Bb -Bg -Bp -Bf -Br -BG -Bd -Bs -BB -Bo -Bc -Bi
, and the -gr
option can also be quite useful. The resulting schedule can be observed by using the tool starpu_lp2paje
, which converts it into the Paje format.
Data transfer time can only be taken into account when deps
is set. Only data transfers inferred from implicit data dependencies between tasks are taken into account. Other data transfers are assumed to be completely overlapped.
Setting deps
to 0 will only take into account the actual computations on processing units. It however still properly takes into account the varying performances of kernels and processing units, which is quite more accurate than just comparing StarPU performances with the fastest of the kernels being used.
The prio
parameter tells StarPU whether to simulate taking into account the priorities as the StarPU scheduler would, i.e. schedule prioritized tasks before less prioritized tasks, to check to which extend this results to a less optimal solution. This increases even more computation time.
StarPU provides the wrapper function starpu_insert_task() to ease the creation and submission of tasks.
Here the implementation of the codelet:
And the call to the function starpu_insert_task():
The call to starpu_insert_task() is equivalent to the following code:
Here a similar call using STARPU_DATA_ARRAY.
If some part of the task insertion depends on the value of some computation, the macro STARPU_DATA_ACQUIRE_CB can be very convenient. For instance, assuming that the index variable i
was registered as handle A_handle[i]
:
The macro STARPU_DATA_ACQUIRE_CB submits an asynchronous request for acquiring data i
for the main application, and will execute the code given as third parameter when it is acquired. In other words, as soon as the value of i
computed by the codelet which_index
can be read, the portion of code passed as third parameter of STARPU_DATA_ACQUIRE_CB will be executed, and is allowed to read from i
to use it e.g. as an index. Note that this macro is only avaible when compiling StarPU with the compiler gcc
.
In various cases, some piece of data is used to accumulate intermediate results. For instances, the dot product of a vector, maximum/minimum finding, the histogram of a photograph, etc. When these results are produced along the whole machine, it would not be efficient to accumulate them in only one place, incurring data transmission each and access concurrency.
StarPU provides a mode STARPU_REDUX, which permits to optimize that case: it will allocate a buffer on each memory node, and accumulate intermediate results there. When the data is eventually accessed in the normal mode STARPU_R, StarPU will collect the intermediate results in just one buffer.
For this to work, the user has to use the function starpu_data_set_reduction_methods() to declare how to initialize these buffers, and how to assemble partial results.
For instance, cg
uses that to optimize its dot product: it first defines the codelets for initialization and reduction:
and attaches them as reduction methods for its handle dtq
:
and dtq_handle
can now be used in mode STARPU_REDUX for the dot products with partitioned vectors:
During registration, we have here provided NULL
, i.e. there is no initial value to be taken into account during reduction. StarPU will thus only take into account the contributions from the tasks dot_kernel_cl
. Also, it will not allocate any memory for dtq_handle
before tasks dot_kernel_cl
are ready to run.
If another dot product has to be performed, one could unregister dtq_handle
, and re-register it. But one can also call starpu_data_invalidate_submit() with the parameter dtq_handle
, which will clear all data from the handle, thus resetting it back to the initial status register(NULL)
.
The example cg
also uses reduction for the blocked gemv kernel, leading to yet more relaxed dependencies and more parallelism.
STARPU_REDUX can also be passed to starpu_mpi_insert_task() in the MPI case. That will however not produce any MPI communication, but just pass STARPU_REDUX to the underlying starpu_insert_task(). It is up to the application to call starpu_mpi_redux_data(), which posts tasks that will reduce the partial results among MPI nodes into the MPI node which owns the data. For instance, some hypothetical application which collects partial results into data res
, then uses it for other computation, before looping again with a new reduction:
There are two kinds of temporary buffers: temporary data which just pass results from a task to another, and scratch data which are needed only internally by tasks.
Data can sometimes be entirely produced by a task, and entirely consumed by another task, without the need for other parts of the application to access it. In such case, registration can be done without prior allocation, by using the special memory node number -1
, and passing a zero pointer. StarPU will actually allocate memory only when the task creating the content gets scheduled, and destroy it on unregistration.
In addition to that, it can be tedious for the application to have to unregister the data, since it will not use its content anyway. The unregistration can be done lazily by using the function starpu_data_unregister_submit(), which will record that no more tasks accessing the handle will be submitted, so that it can be freed as soon as the last task accessing it is over.
The following code examplifies both points: it registers the temporary data, submits three tasks accessing it, and records the data for automatic unregistration.
The application may also want to see the temporary data initialized on the fly before being used by the task. This can be done by using starpu_data_set_reduction_methods() to set an initialization codelet (no redux codelet is needed).
Some kernels sometimes need temporary data to achieve the computations, i.e. a workspace. The application could allocate it at the start of the codelet function, and free it at the end, but that would be costly. It could also allocate one buffer per worker (similarly to How To Initialize A Computation Library Once For Each Worker?), but that would make them systematic and permanent. A more optimized way is to use the data access mode STARPU_SCRATCH, as examplified below, which provides per-worker buffers without content consistency.
StarPU will make sure that the buffer is allocated before executing the task, and make this allocation per-worker: for CPU workers, notably, each worker has its own buffer. This means that each task submitted above will actually have its own workspace, which will actually be the same for all tasks running one after the other on the same worker. Also, if for instance GPU memory becomes scarce, StarPU will notice that it can free such buffers easily, since the content does not matter.
The example examples/pi
uses scratches for some temporary buffer.
StarPU can leverage existing parallel computation libraries by the means of parallel tasks. A parallel task is a task which gets worked on by a set of CPUs (called a parallel or combined worker) at the same time, by using an existing parallel CPU implementation of the computation to be achieved. This can also be useful to improve the load balance between slow CPUs and fast GPUs: since CPUs work collectively on a single task, the completion time of tasks on CPUs become comparable to the completion time on GPUs, thus relieving from granularity discrepancy concerns. hwloc
support needs to be enabled to get good performance, otherwise StarPU will not know how to better group cores.
Two modes of execution exist to accomodate with existing usages.
In the Fork mode, StarPU will call the codelet function on one of the CPUs of the combined worker. The codelet function can use starpu_combined_worker_get_size() to get the number of threads it is allowed to start to achieve the computation. The CPU binding mask for the whole set of CPUs is already enforced, so that threads created by the function will inherit the mask, and thus execute where StarPU expected, the OS being in charge of choosing how to schedule threads on the corresponding CPUs. The application can also choose to bind threads by hand, using e.g. sched_getaffinity to know the CPU binding mask that StarPU chose.
For instance, using OpenMP (full source is available in examples/openmp/vector_scal.c
):
Other examples include for instance calling a BLAS parallel CPU implementation (see examples/mult/xgemm.c
).
In the SPMD mode, StarPU will call the codelet function on each CPU of the combined worker. The codelet function can use starpu_combined_worker_get_size() to get the total number of CPUs involved in the combined worker, and thus the number of calls that are made in parallel to the function, and starpu_combined_worker_get_rank() to get the rank of the current CPU within the combined worker. For instance:
Of course, this trivial example will not really benefit from parallel task execution, and was only meant to be simple to understand. The benefit comes when the computation to be done is so that threads have to e.g. exchange intermediate results, or write to the data in a complex but safe way in the same buffer.
To benefit from parallel tasks, a parallel-task-aware StarPU scheduler has to be used. When exposed to codelets with a flag STARPU_FORKJOIN or STARPU_SPMD, the schedulers pheft
(parallel-heft) and peager
(parallel eager) will indeed also try to execute tasks with several CPUs. It will automatically try the various available combined worker sizes (making several measurements for each worker size) and thus be able to avoid choosing a large combined worker if the codelet does not actually scale so much.
By default, StarPU creates combined workers according to the architecture structure as detected by hwloc
. It means that for each object of the hwloc
topology (NUMA node, socket, cache, ...) a combined worker will be created. If some nodes of the hierarchy have a big arity (e.g. many cores in a socket without a hierarchy of shared caches), StarPU will create combined workers of intermediate sizes. The variable STARPU_SYNTHESIZE_ARITY_COMBINED_WORKER permits to tune the maximum arity between levels of combined workers.
The combined workers actually produced can be seen in the output of the tool starpu_machine_display
(the environment variable STARPU_SCHED has to be set to a combined worker-aware scheduler such as pheft
or peager
).
Unfortunately, many environments and librairies do not support concurrent calls.
For instance, most OpenMP implementations (including the main ones) do not support concurrent pragma omp parallel
statements without nesting them in another pragma omp parallel
statement, but StarPU does not yet support creating its CPU workers by using such pragma.
Other parallel libraries are also not safe when being invoked concurrently from different threads, due to the use of global variables in their sequential sections for instance.
The solution is then to use only one combined worker at a time. This can be done by setting the field starpu_conf::single_combined_worker to 1
, or setting the environment variable STARPU_SINGLE_COMBINED_WORKER to 1
. StarPU will then run only one parallel task at a time (but other CPU and GPU tasks are not affected and can be run concurrently). The parallel task scheduler will however still however still try varying combined worker sizes to look for the most efficient ones.
StarPU provides several tools to help debugging aplications. Execution traces can be generated and displayed graphically, see Generating Traces With FxT.
Some gdb helpers are also provided to show the whole StarPU state:
(gdb) source tools/gdbinit (gdb) help starpu
Valgrind can be used on StarPU: valgrind.h just needs to be found at ./configure time, to tell valgrind about some known false positives and disable host memory pinning. Other known false positives can be suppressed by giving the suppression files in tools/valgrind/ *.suppr to valgrind's –suppressions option.
The STARPU_DISABLE_KERNELS environment variable can also be set to 1 to make StarPU do everything (schedule tasks, transfer memory, etc.) except actually calling the application-provided kernel functions, i.e. the computation will not happen. This permits to quickly check that the task scheme is working properly.
The Temanejo task debugger can also be used, see Using The Temanejo Task Debugger.
It may be interesting to represent the same piece of data using two different data structures: one that would only be used on CPUs, and one that would only be used on GPUs. This can be done by using the multiformat interface. StarPU will be able to convert data from one data structure to the other when needed. Note that the scheduler dmda
is the only one optimized for this interface. The user must provide StarPU with conversion codelets:
Kernels can be written almost as for any other interface. Note that STARPU_MULTIFORMAT_GET_CPU_PTR shall only be used for CPU kernels. CUDA kernels must use STARPU_MULTIFORMAT_GET_CUDA_PTR, and OpenCL kernels must use STARPU_MULTIFORMAT_GET_OPENCL_PTR. STARPU_MULTIFORMAT_GET_NX may be used in any kind of kernel.
A full example may be found in examples/basic_examples/multiformat.c
.
To add a new kind of device to the structure starpu_driver, one needs to:
_starpu_launch_drivers()
to make sure the driver is not always launched. _starpu_run_foobar()
in the corresponding driver. A full example showing how to define a new scheduling policy is available in the StarPU sources in the directory examples/scheduler/
.
Graphical-oriented applications need to draw the result of their computations, typically on the very GPU where these happened. Technologies such as OpenGL/CUDA interoperability permit to let CUDA directly work on the OpenGL buffers, making them thus immediately ready for drawing, by mapping OpenGL buffer, textures or renderbuffer objects into CUDA. CUDA however imposes some technical constraints: peer memcpy has to be disabled, and the thread that runs OpenGL has to be the one that runs CUDA computations for that GPU.
To achieve this with StarPU, pass the option --disable-cuda-memcpy-peer to ./configure
(TODO: make it dynamic), OpenGL/GLUT has to be initialized first, and the interoperability mode has to be enabled by using the field starpu_conf::cuda_opengl_interoperability, and the driver loop has to be run by the application, by using the field starpu_conf::not_launched_drivers to prevent StarPU from running it in a separate thread, and by using starpu_driver_run() to run the loop. The examples gl_interop
and gl_interop_idle
show how it articulates in a simple case, where rendering is done in task callbacks. The former uses glutMainLoopEvent
to make GLUT progress from the StarPU driver loop, while the latter uses glutIdleFunc
to make StarPU progress from the GLUT main loop.
Then, to use an OpenGL buffer as a CUDA data, StarPU simply needs to be given the CUDA pointer at registration, for instance:
and display it e.g. in the callback function.
Let's define a new data interface to manage complex numbers.
Registering such a data to StarPU is easily done using the function starpu_data_register(). The last parameter of the function, interface_complex_ops
, will be described below.
Different operations need to be defined for a data interface through the type starpu_data_interface_ops. We only define here the basic operations needed to run simple applications. The source code for the different functions can be found in the file examples/interface/complex_interface.c
.
Functions need to be defined to access the different fields of the complex interface from a StarPU data handle.
Similar functions need to be defined to access the different fields of the complex interface from a void *
pointer to be used within codelet implemetations.
Complex data interfaces can then be registered to StarPU.
and used by codelets.
The whole code for this complex data interface is available in the directory examples/interface/
.
The number of data a task can manage is fixed by the environment variable STARPU_NMAXBUFS which has a default value which can be changed through the configure option --enable-maxbuffers.
However, it is possible to define tasks managing more data by using the field starpu_task::dyn_handles when defining a task and the field starpu_codelet::dyn_modes when defining the corresponding codelet.
The whole code for this complex data interface is available in the directory examples/basic_examples/dynamic_handles.c
.
When executing a task on a GPU for instance, StarPU would normally copy all the needed data for the tasks on the embedded memory of the GPU. It may however happen that the task kernel would rather have some of the datas kept in the main memory instead of copied in the GPU, a pivoting vector for instance. This can be achieved by setting the starpu_codelet::specific_nodes flag to 1, and then fill the starpu_codelet::nodes array (or starpu_codelet::dyn_nodes when starpu_codelet::nbuffers is greater than STARPU_NMAXBUFS) with the node numbers where data should be copied to, or -1 to let StarPU copy it to the memory node where the task will be executed. For instance, with the following codelet:
the first data of the task will be kept in the main memory, while the second data will be copied to the CUDA GPU as usual.
More examples are available in the StarPU sources in the directory examples/
. Simple examples include:
incrementer/
basic_examples/
matvecmult/
axpy/
fortran/
More advanced examples include:
filters/
lu/
xlu_implicit.c
cholesky/
cholesky_implicit.c
.