Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
take the tuto myself, and add how to categorize tasks in S4U
[simgrid.git] / docs / source / tuto_s4u.rst
1 .. _usecase_simalgo:
2
3 Simulating Algorithms
4 =====================
5
6 SimGrid was conceived as a tool to study distributed algorithms. Its
7 modern S4U interface makes it easy to assess Cloud, P2P, HPC, IoT and
8 similar settings.
9
10 A typical SimGrid simulation is composed of several **Actors**
11 |api_s4u_Actor|_ , that execute user-provided functions. The actors
12 have to explicitly use the S4U interface to express their computation,
13 communication, disk usage and other **Activities** |api_s4u_Activity|_
14 , so that they get reflected within the simulator. These activities
15 take place on **Resources** (CPUs, links, disks). SimGrid predicts the
16 time taken by each activity and orchestrates accordingly the actors
17 waiting for the completion of these activities.
18
19 .. |api_s4u_Actor| image:: /images/extlink.png
20    :align: middle
21    :width: 12
22 .. _api_s4u_Actor: api/classsimgrid_1_1s4u_1_1Actor.html#class-documentation
23
24 .. |api_s4u_Activity| image:: /images/extlink.png
25    :align: middle
26    :width: 12
27 .. _api_s4u_Activity: api/classsimgrid_1_1s4u_1_1Activity.html#class-documentation
28
29
30 Each actor executes a user-provided function on a simulated **Host**
31 |api_s4u_Host|_ with which it can interact. Communications are not
32 directly sent to actors, but posted onto **Mailboxes**
33 |api_s4u_Mailbox|_ that serve as rendez-vous points between
34 communicating processes. 
35
36 .. |api_s4u_Host| image:: /images/extlink.png
37    :align: middle
38    :width: 12
39 .. _api_s4u_Host: api/classsimgrid_1_1s4u_1_1Host.html#class-documentation
40
41 .. |api_s4u_Mailbox| image:: /images/extlink.png
42    :align: middle
43    :width: 12
44 .. _api_s4u_Mailbox: api/classsimgrid_1_1s4u_1_1Mailbox.html#class-documentation
45
46
47 Discover the Master/Workers
48 ---------------------------
49
50 This section introduces a first example of SimGrid simulation. This
51 simple application is composed of two kind of actors: the **master**
52 is in charge of distributing some computational tasks to a set of
53 **workers** that execute them. 
54
55 .. image:: /tuto_s4u/img/intro.svg
56    :align: center
57
58 We first present a round-robin version of this application, where the
59 master dispatches the tasks to the workers, one after the other, until
60 all tasks are dispatched. Later in this tutorial, you will be given
61 the opportunity to improve this scheme.
62
63 The Actors
64 ..........
65
66 Let's start with the code of the worker. It is represented by the
67 *master* function below. This simple function takes at least 3
68 parameters (the amount of tasks to dispatch, their computational size
69 in flops to compute and their communication size in bytes to
70 exchange). Every parameter after the third one must be the name of an
71 host on which a worker is waiting for something to compute.
72
73 Then, the tasks are sent one after the other, each on a mailbox named
74 after the worker's hosts. On the other side, a given worker (which
75 code is given below) wait for incoming tasks on its own
76 mailbox.
77
78
79
80 At the end, once all tasks are dispatched, the master dispatches
81 another task per worker, but this time with a negative amount of flops
82 to compute. Indeed, this application decided by convention, that the
83 workers should stop when encountering such a negative compute_size.
84
85 At the end of the day, the only SimGrid specific functions used in
86 this example are :cpp:func:`simgrid::s4u::Mailbox::by_name` and
87 :cpp:func:`simgrid::s4u::Mailbox::put`. Also, :c:macro:`XBT_INFO` is used
88 as a replacement to printf() or to cout to ensure that the messages
89 are nicely logged along with the simulated time and actor name.
90  
91      
92 .. literalinclude:: ../../examples/s4u/app-masterworkers/s4u-app-masterworkers-fun.cpp
93    :language: c++
94    :start-after: master-begin
95    :end-before: master-end
96
97 Here comes the code of the worker actors. This function expects no
98 parameter from its vector of strings. Its code is very simple: it
99 expects messages on the mailbox that is named after its own host. As long as it gets valid
100 computation requests (whose compute_amount is positive), it compute
101 this task and waits for the next one.
102
103 The worker retrieves its own host with
104 :cpp:func:`simgrid::s4u::this_actor::get_host`. The
105 :ref:`simgrid::s4u::this_actor <namespace_simgrid__s4u__this_actor>`
106 namespace contains many such helping functions.
107
108 .. literalinclude:: ../../examples/s4u/app-masterworkers/s4u-app-masterworkers-fun.cpp
109    :language: c++
110    :start-after: worker-begin
111    :end-before: worker-end
112
113 Starting the Simulation
114 .......................
115                 
116 And this is it. In only a few lines, we defined the algorithm of our
117 master/workers examples.
118
119 That being said, an algorithm alone is not enough to define a
120 simulation: SimGrid is a library, not a program. So you need to define
121 your own ``main()`` function as follows. This function is in charge of
122 creating a SimGrid simulation engine (on line 3), register the actor
123 functions to the engine (on lines 7 and 8), load the virtual platform
124 from its description file (on line 11), map actors onto that platform
125 (on line 12) and run the simulation until its completion on line 15.
126
127 .. literalinclude:: ../../examples/s4u/app-masterworkers/s4u-app-masterworkers-fun.cpp
128    :language: c++
129    :start-after: main-begin
130    :end-before: main-end
131    :linenos:
132
133 As you can see, this also requires a platform file and a deployment
134 file.
135
136 Platform File
137 .............
138
139 Platform files define the virtual platform on which the provided
140 application will take place. In contains one or several **Network
141 Zone** |api_s4u_NetZone|_ that contain both **Host-** |api_s4u_Host|_
142 and **Link-** |api_s4u_Link|_ Resources, as well as routing
143 information.
144
145 Such files can get rather long and boring, so the example below is
146 only an excerpts of the full ``examples/platforms/small_platform.xml``
147 file. For example, most routing information are missing, and only the
148 route between the hosts Tremblay and Fafard is given. This path
149 traverses 6 links (named 4, 3, 2, 0, 1 and 8). There are several
150 examples of platforms in the archive under ``examples/platforms``.
151                 
152 .. |api_s4u_NetZone| image:: /images/extlink.png
153    :align: middle
154    :width: 12
155 .. _api_s4u_NetZone: api/classsimgrid_1_1s4u_1_1NetZone.html#class-documentation
156
157 .. |api_s4u_Link| image:: /images/extlink.png
158    :align: middle
159    :width: 12
160 .. _api_s4u_Link: api/classsimgrid_1_1s4u_1_1Link.html#class-documentation
161
162 .. literalinclude:: ../../examples/platforms/small_platform.xml
163    :language: xml
164    :lines: 1-10,12-20,56-62,192-
165    :caption: (excerpts of the small_platform.xml file)
166
167 Deployment File
168 ...............
169
170 Deployment files specify the execution scenario: it lists the actors
171 that should be started, along with their parameter. In the following
172 example, we start 6 actors: one master and 5 workers.
173
174 .. literalinclude:: ../../examples/s4u/app-masterworkers/s4u-app-masterworkers_d.xml
175    :language: xml
176
177 Execution Example
178 .................
179
180 This time, we have all parts: once the program is compiled, we can
181 execute it as follows. Note how the XBT_INFO() requests turned into
182 informative messages.
183               
184 .. literalinclude:: ../../examples/s4u/app-masterworkers/s4u-app-masterworkers.tesh
185    :language: shell
186    :start-after: s4u-app-masterworkers-fun
187    :prepend: $$$ ./masterworkers platform.xml deploy.xml
188    :append: $$$
189    :dedent: 2
190               
191
192 Improve it Yourself
193 -------------------
194
195 In this section, you will modify the example presented earlier to
196 explore the quality of the proposed algorithm. For now, it works and
197 the simulation prints things, but the truth is that we have no idea of
198 whether this is a good algorithm to dispatch tasks to the workers.
199 This very simple setting raises many interesting questions:
200
201 .. image:: /tuto_s4u/img/question.svg
202    :align: center
203
204 - Which algorithm should the master use? Or should the worker decide
205   by themselves?
206
207     Round Robin is not an efficient algorithm when all tasks are not
208     processed at the same speed.  It would probably be more efficient
209     if the workers were asking for tasks when ready.
210
211 - Should tasks be grouped in batches or sent separately?
212
213     The workers will starve if they don't get the tasks fast
214     enough. One possibility to reduce latency would be to send tasks
215     in pools instead of one by one. But if the pools are too big, the
216     load balancing will likely get uneven, in particular when
217     distributing the last tasks.
218
219 - How does the quality of such algorithm dependent on the platform
220   characteristics and on the task characteristics?
221
222     Whenever the input communication time is very small compared to
223     processing time and workers are homogeneous, it is likely that the
224     round-robin algorithm performs very well. Would it still hold true
225     when transfer time is not negligible? What if some tasks are
226     performed faster on some specific nodes?
227            
228 - The network topology interconnecting the master and the workers
229   may be quite complicated. How does such a topology impact the
230   previous result?
231
232     When data transfers are the bottleneck, it is likely that a good
233     modeling of the platform becomes essential. The SimGrid platform
234     models are particularly handy to account for complex platform
235     topologies.
236
237 - What is the best applicative topology?
238
239     Is a flat master worker deployment sufficient? Should we go for a
240     hierarchical algorithm, with some forwarders taking large pools of
241     tasks from the master, each of them distributing their tasks to a
242     sub-pool of workers? Or should we introduce super-peers,
243     dupplicating the master's role in a peer-to-peer manner?  Do the
244     algorithms require a perfect knowledge of the network?
245
246 - How is such an algorithm sensitive to external workload variation?
247
248     What if bandwidth, latency and computing speed can vary with no
249     warning?  Shouldn't you study whether your algorithm is sensitive
250     to such load variations?
251
252 - Although an algorithm may be more efficient than another, how does
253   it interfere with unrelated applications executing on the same
254   facilities?
255
256 **SimGrid was invented to answer such questions.** Do not believe the
257 fools saying that all you need to study such settings is a simple
258 discrete event simulator. Do you really want to reinvent the wheel,
259 debug and optimize your own tool, and validate its models against real
260 settings for ages, or do you prefer to sit on the shoulders of a
261 giant? With SimGrid, you can focus on your algorithm. The whole
262 simulation mechanism is already working.
263
264 Here is the visualization of a SimGrid simulation of two master worker
265 applications (one in light gray and the other in dark gray) running in
266 concurrence and showing resource usage over a long period of time. It
267 was obtained with the Triva software.
268
269 .. image:: /tuto_s4u/img/result.png
270    :align: center
271
272 Prerequisite
273 ............
274
275 Before your proceed, you need to :ref:`install SimGrid <install>`, a
276 C++ compiler and also ``pajeng`` to visualize the traces. You may want
277 to install `Vite <http://vite.gforge.inria.fr/>`_ to get a first
278 glance at the traces. The provided code template requires cmake to
279 compile. On Debian and Ubuntu for example, you can get them as
280 follows:
281
282 .. code-block:: shell
283
284    sudo apt install simgrid pajeng cmake g++ vite
285
286 An initial version of the source code is provided on framagit. This
287 template compiles with cmake. If SimGrid is correctly installed, you
288 should be able to clone the `repository
289 <https://framagit.org/simgrid/simgrid-template-s4u>`_ and recompile
290 everything as follows:
291
292 .. code-block:: shell
293
294    git clone git@framagit.org:simgrid/simgrid-template-s4u.git
295    cd simgrid-template-s4u/
296    cmake .
297    make
298
299 If you struggle with the compilation, then you should double check
300 your :ref:`SimGrid installation <install>`.  On need, please refer to
301 the :ref:`Troubleshooting your Project Setup
302 <install_yours_troubleshooting>` section.
303
304 Discovering the Provided Code
305 .............................
306
307 Please compile and execute the provided simulator as follows:
308
309
310 .. code-block:: shell
311
312    make master-workers
313    ./master-workers small_platform.xml master-workers_d.xml
314
315 For a more "fancy" output, you can use simgrid-colorizer. 
316
317 .. code-block:: shell
318
319    ./master-workers small_platform.xml master-workers_d.xml 2>&1 | simgrid-colorizer
320
321 If you installed SimGrid to a non-standard path, you may have to
322 specify the full path to simgrid-colorizer on the above line, such as
323 ``/opt/simgrid/bin/simgrid-colorizer``. If you did not install it at all,
324 you can find it in <simgrid_root_directory>/bin/colorize.
325
326 For a classical Gantt-Chart vizualisation, you can use `Vite
327 <http://vite.gforge.inria.fr/>`_ as follows:
328
329 .. code-block:: shell
330
331    ./master-workers small_platform.xml master-workers_d.xml --cfg=tracing:yes --cfg=tracing/msg/process:yes
332    vite simgrid.trace
333
334 .. image:: /tuto_s4u/img/vite-screenshot.png
335    :align: center
336    
337 But if you want the full power to visualize SimGrid traces, you need
338 to use R. As a start, you can download this `starter script
339 <https://framagit.org/simgrid/simgrid/raw/master/docs/source/tuto_s4u/draw_gantt.R>`_
340 and use it as follows:
341
342 .. code-block:: shell
343
344    ./master-workers small_platform.xml master-workers_d.xml --cfg=tracing:yes --cfg=tracing/msg/process:yes
345    pj_dump --ignore-incomplete-links simgrid.trace | grep STATE > gantt.csv
346    Rscript draw_gantt.R gantt.csv
347
348 It produces a ``Rplots.pdf`` with the following content:
349
350 .. image:: /tuto_s4u/img/Rscript-screenshot.png
351    :align: center
352
353
354 Lab 1: Simpler deployments
355 --------------------------
356
357 In the provided example, adding more workers quickly becomes a pain:
358 You need to start them (at the bottom of the file), and to inform the
359 master of its availability with an extra parameter. This is mandatory
360 if you want to inform the master of where the workers are running. But
361 actually, the master does not need to have this information.
362
363 We could leverage the mailbox mechanism flexibility, and use a sort of
364 yellow page system: Instead of sending data to the worker running on
365 Fafard, the master could send data to the third worker. Ie, instead of
366 using the worker location (which should be filled in two locations),
367 we could use their ID (which should be filled in one location
368 only).
369
370 This could be done with the following deployment file. It's clearly
371 not shorter than the previous one, but it's still simpler because the
372 information is only written once. It thus follows the `DRY
373 <https://en.wikipedia.org/wiki/Don't_repeat_yourself>`_ `SPOT
374 <http://wiki.c2.com/?SinglePointOfTruth>`_ design principle.
375
376 .. literalinclude:: tuto_s4u/deployment1.xml
377    :language: xml
378
379
380 Copy your ``master-workers.cpp`` into ``master-workers-lab1.cpp`` and
381 add a new executable into ``CMakeLists.txt``. Then modify your worker
382 function so that it gets its mailbox name not from the name of its
383 host, but from the string passed as ``args[1]``. The master will send
384 messages to all workers based on their number, for example as follows:
385
386 .. code-block:: cpp
387
388    for (int i = 0; i < tasks_count; i++) {
389      std::string worker_rank          = std::to_string(i % workers_count);
390      std::string mailbox_name         = std::string("worker-") + worker_rank;
391      simgrid::s4u::MailboxPtr mailbox = simgrid::s4u::Mailbox::by_name(mailbox_name);
392
393      mailbox->put(...);
394
395      ...
396    }
397    
398
399 Wrap up
400 .......
401
402 The mailboxes are a very powerful mechanism in SimGrid, allowing many
403 interesting application settings. They may feel surprising if you are
404 used to BSD sockets or other classical systems, but you will soon
405 appreciate their power. They are only used to match the
406 communications, but have no impact on the communication
407 timing. ``put()`` and ``get()`` are matched regardless of their
408 initiators' location and then the real communication occures between
409 the involved parties.
410
411 Please refer to the full `API of Mailboxes
412 <api/classsimgrid_1_1s4u_1_1Mailbox.html#class-documentation>`_
413 |api_s4u_Mailbox|_ for more details.
414
415
416 Lab 2: Using the whole platform
417 -------------------------------
418
419 It is now easier to add a new worker, but you still has to do it
420 manually. It would be much easier if the master could start the
421 workers on its own, one per available host in the platform. The new
422 deployment file should be as simple as:
423
424 .. literalinclude:: tuto_s4u/deployment2.xml
425    :language: xml
426
427
428 Creating the workers from the master
429 ....................................
430
431 For that, the master needs to retrieve the list of hosts declared in
432 the platform with :cpp:func:`simgrid::s4u::Engine::get_all_hosts`.
433 Then, the master should start the worker processes with
434 :cpp:func:`simgrid::s4u::Actor::create`.
435
436 ``Actor::create(name, host, func, params...)`` is a very flexible
437 function. Its third parameter is the function that the actor should
438 execute. This function can take any kind of parameter, provided that
439 you pass similar parameters to ``Actor::create()``. For example, you
440 could have something like this:
441
442 .. code-block:: cpp
443
444   void my_actor(int param1, double param2, std::string param3) {
445     ...
446   }
447   int main(int argc, char argv**) {
448      ...
449      simgrid::s4u::ActorPtr actor;
450      actor = simgrid::s4u::Actor::create("name", simgrid::s4u::Host::by_name("the_host"),
451                                          &my_actor, 42, 3.14, "thevalue");
452      ...
453   }
454
455
456 Master-Workers Communication
457 ............................
458
459 Previously, the workers got from their parameter the name of the
460 mailbox they should use. We can still do so: the master should build
461 such a parameter before using it in the ``Actor::create()`` call. The
462 master could even pass directly the mailbox as a parameter to the
463 workers. 
464
465 Since we want later to study concurrent applications, it is advised to
466 use a mailbox name that is unique over the simulation even if there is
467 more than one master. 
468
469 One possibility for that is to use the actor ID (aid) of each worker
470 as a mailbox name. The master can retrieve the aid of the newly
471 created actor with ``actor->get_pid()`` while the actor itself can
472 retrieve its own aid with ``simgrid::s4u::this_actor::get_pid()``.
473 The retrieved value is an ``aid_t``, which is an alias for ``long``.
474
475 Instead of having one mailbox per worker, you could also reorganize
476 completely your application to have only one mailbox per master. All
477 the workers of a given master would pull their work from the same
478 mailbox, which should be passed as parameter to the workers.  This
479 reduces the amount of mailboxes, but prevents the master from taking
480 any scheduling decision. It really depends on how you want to organize
481 your application and what you want to study with your simulator. In
482 this tutorial, that's probably not a good idea.
483
484 Wrap up
485 .......
486
487 In this exercise, we reduced the amount of configuration that our
488 simulator requests. This is both a good idea, and a dangerous
489 trend. This simplification is another application of the good old DRY/SPOT
490 programming principle (`Don't Repeat Yourself / Single Point Of Truth
491 <https://en.wikipedia.org/wiki/Don%27t_repeat_yourself>`_), and you
492 really want your programming artefacts to follow these software
493 engineering principles.
494
495 But at the same time, you should be careful in separating your
496 scientific contribution (the master/workers algorithm) and the
497 artefacts used to test it (platform, deployment and workload). This is
498 why SimGrid forces you to express your platform and deployment files
499 in XML instead of using a programming interface: it forces a clear
500 separation of concerns between things of very different nature.
501
502 Lab 3: Fixed experiment duration
503 --------------------------------
504
505 In the current version, the number of tasks is defined through the
506 worker arguments. Hence, tasks are created at the very beginning of
507 the simulation. Instead, have the master dispatching tasks for a
508 predetermined amount of time.  The tasks must now be created on demand
509 instead of beforehand.
510
511 Of course, usual time functions like ``gettimeofday`` will give you the
512 time on your real machine, which is prety useless in the
513 simulation. Instead, retrieve the time in the simulated world with
514 :cpp:func:`simgrid::s4u::Engine::get_clock`.
515
516 You can still stop your workers with a specific task as previously,
517 or you may kill them forcefully with
518 :cpp:func:`simgrid::s4u::Actor::kill` (if you already have a reference
519 to the actor you want to kill) or
520 :cpp:func:`simgrid::s4u::Actor::kill(aid_t)` (if you only have its ID).
521
522
523 Anyway, the new deployment `deployment3.xml` file should thus look
524 like this:
525
526 .. literalinclude:: tuto_s4u/deployment3.xml
527    :language: xml
528
529 Controlling the message verbosity
530 .................................
531
532 Not all messages are equally informative, so you probably want to
533 change some of the ``XBT_INFO`` into ``XBT_DEBUG`` so that they are
534 hidden by default. For example, you may want to use ``XBT_INFO`` once
535 every 100 tasks and ``XBT_DEBUG`` when sending all the other tasks. Or
536 you could show only the total number of tasks processed by
537 default. You can still see the debug messages as follows:
538
539 .. code-block:: shell
540
541    ./master-workers-lab3 small_platform.xml deployment3.xml --log=msg_test.thres:debug
542
543
544 Lab 4: Understanding competing applications
545 -------------------------------------------
546
547 It is now time to start several applications at once, with the following ``deployment4.xml`` file.
548
549 .. literalinclude:: tuto_s4u/deployment4.xml
550    :language: xml
551
552 Things happen when you do so, but it remains utterly difficult to
553 understand what's happening exactely. Even Gantt visualizations
554 contain too much information to be useful: it is impossible to
555 understand which task belong to which application. To fix this, we
556 will categorize the tasks.
557
558 Instead of starting the execution in one function call only with
559 ``simgrid::s4u::this_actor::execute(compute_cost)``, you need to
560 create the execution activity, set its tracing category and then start
561 it and wait for its completion, as follows:
562
563 .. code-block:: cpp
564
565    simgrid::s4u::ExecPtr exec = simgrid::s4u::this_actor::exec_init(compute_cost);
566    exec->set_tracing_category(category);
567    // exec->start() is optional here as wait() starts the activity on need
568    exec->wait();
569
570 You can make the same code shorter as follows:
571
572 .. code-block:: cpp
573
574    simgrid::s4u::this_actor::exec_init(compute_cost)->set_tracing_category(category)->wait();
575
576 The outcome can then be visualized as a Gantt-chart as follows:
577
578 .. code-block:: shell
579
580    ./master-workers-lab4 small_platform.xml deployment4.xml --cfg=tracing:yes --cfg=tracing/msg/process:yes
581    vite simgrid.trace
582
583 .. todo::
584
585    Make it work
586
587 Going further
588 .............
589
590 vite is not enough to understand the situation, because it does not
591 deal with categorization. That is why you should switch to R to
592 visualize your outcomes, as explained on `this page
593 <http://simgrid.gforge.inria.fr/contrib/R_visualization.php>`_.
594
595
596
597 ..  LocalWords:  SimGrid