Logo AND Algorithmique Numérique Distribuée

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