Debian Codegraph @

HOWTOs/Parallel-APL.asciidoc

raw
1 = Parallel GNU APL
2 :Author: Jürgen Sauermann, GNU APL
3 :page-width: 120em
4 :toc:
5 :toclevels: 4
6 :iconsdir: /usr/share/asciidoc/icons
7 :icons:
8
9 == Abstract
10
11 This document briefly describes parallel execution in GNU APL
12
13 == Configuration
14
15 Parallel execution of APL primitives needs to be *./configure*'d explicitly.
16 Without such configuration GNU APL executes sequentially. In freshly installed
17 GNU APL sources (i.e. after an SVN checkout or after unpacking the GNU APL tar
18 file), the configuration is:
19
20 ----
21 ./configure --enable-maintainer-mode \
22 VALUE_CHECK_WANTED=no \
23 VALUE_HISTORY_WANTED=no \
24 PERFORMANCE_COUNTERS_WANTED=yes \
25 DYNAMIC_LOG_WANTED=yes \
26 ASSERT_LEVEL_WANTED=0 \
27 CORE_COUNT_WANTED=-3
28 ----
29
30 If the sources were already *./configure*'d then two make targets achieve
31 the same:
32
33 ----
34 make parallel
35 make parallel1
36 ----
37
38 The first make target *parallel* is the setting for maximum performance, while
39 the second make target *parallel1* is like *parallel* but with internal
40 performance counters enabled. The performance counters are needed for
41 benchmarking of the GNU APL performance via *FIO∆get_statistics* in workspace
42 *5 FILE_IO* and *⎕FIO[201]* respectively.
43
44 CAUTION: Parallel execution is an entirely experimental feature that should
45 not be used in mission-critical applications. Support for bugs caused by
46 this feature is rather limited.
47
48 == Controlling the Core Count
49
50 The number of cores that are used in parallel APL execution can be
51 controlled in several ways.
52
53 === The ./configure Option CORE_COUNT_WANTED
54
55 The first way to control the (maximum) core count is at the point in time when
56 the interpreter source code is being ./configure'd. The configure option
57 CORE_COUNT_WANTED defines how the interpreter chooses the number of cores
58 (see *README-2-configure*):
59
60 * CORE_COUNT_WANTED=0: sequential
61 * CORE_COUNT_WANTED=1: parallel (but using only 1 core)
62 * CORE_COUNT_WANTED=2: parallel on 2 cores
63 * ...
64 * CORE_COUNT_WANTED=N: parallel on N cores
65 * CORE_COUNT_WANTED=-1: parallel on all existing cores
66 * CORE_COUNT_WANTED=-2: parallel; the core count is determined by the command
67 line argument -cc of the interpreter
68 * CORE_COUNT_WANTED=-3: parallel; the core count is determined at interpreter
69 run-time via ⎕SYL;
70
71 NOTE: The command line option -cc works only if CORE_COUNT_WANTED=-2. For
72 CORE_COUNT_WANTED > 1 or -2, it is the responsibility of the user to ensure
73 that the desired number of cores actually exist (i.e. this is not checked
74 because some platforms cannot do that).
75
76 *CORE_COUNT_WANTED=-3* is the most useful setting, because it allows changing
77 the core count at run-time of an APL program (e.g. in a benchmarking workspace
78 like *Scalar2.apl*).
79
80 === Changing the Core Count at Run-time
81
82 If *CORE_COUNT_WANTED=-3* (the default) then the system variable *⎕SYL*, in
83 particular *⎕SYL[24 25 26;]* control the number of cores being used:
84
85 ----
86 ⎕SYL[24 25 26;]
87 CORE_COUNT_WANTED (per ./configure) ¯3
88 cores available 12
89 cores used 1
90 ----
91
92 ==== ⎕SYL[24;2]
93
94 *⎕SYL[24;2])* is a read-only value pertaining to the value used for
95 *CORE_COUNT_WANTED* in *./configure*.
96
97 ==== ⎕SYL[25;2]
98
99 *⎕SYL[25;2])* is the number of cores either chosen by ⎕SYL[24;2] or else as
100 indicated by the platform. The value 12 above as reported on a i7-8700
101 Intel CPU with 6 physical cores and 2 core threads per physical core.
102
103 ==== ⎕SYL[26;2]
104
105 *⎕SYL[26;2])* is the number of cores used by the interpreter. Setting:
106
107 *⎕SYL[26;2])←0* chooses sequential operation of the interpreter.
108 *⎕SYL[26;2])←N* with *N≥1 chooses parallel operation on *N* cores.
109 * Other values trigger a *DOMAIN ERROR*.
110
111 NOTE: *⎕SYL[26;2])←1* could be useful for benchmarking to see the difference
112 between parallel and sequential code, but without distributing the
113 computational load over several cores.
114
115 Setting *⎕SYL[26;2]* with a proper value in APL calls
116 *Parallel::set_core_count()* in *Parallel.cc*.
117
118 == The Initialization of the Parallel Subsystem
119
120 Parallel execution is initialized as follows:
121
122 * the initialization is performed automatically when the interpreter is
123 started (function *Parallel::init()*). If the interpreter is ./configured
124 with *DYNAMIC_LOG_WANTED=yes* then logging of the initialization can be
125 enabled with command line option *-l 41*.
126
127 * *Parallel::init()* initializes semaphores related to parallel execution
128 and then calls *CPU_pool::init()*. *CPU_pool::init()* determines, which CPUs
129 can be used by the interpreter and stores them in its vector *the_CPUs*.
130 If *CORE_COUNT_WANTED* is *≥ 0* or *-2* then the CPUs in the vector are
131 determined by *CORE_COUNT_WANTED* or by the *-cc* command line option
132 (no checks are performed to verify that the CPUs chosen are correct).
133 Otherwise, i.e. (*CORE_COUNT_WANTED* is -1 or -3) the cores available to
134 the interpreter are determined by *pthread_getaffinity_np()* and all CPUs
135 that are available to the interpreter are stored in the vector.
136
137 * Then *Parallel::init()* creates a thread pool with
138 *Thread_context::init_parallel*, with one thread for each CPU
139 in *CPU_pool::the_CPUs*. If *CORE_COUNT_WANTED = -3* then only the first
140 thread is activated (and the user needs to use ⎕SYL in order to activate
141 more cores. Otherwise all threads are activated (and ⎕SYL cannot be used).
142 Finally *Parallel::init()* brings all threads into their initial state.
143
144 At any point in time, a thread can be in one of 2 states:
145
146 * BLKD: Blocked on its private semaphore *Thread_context::pool_sema*, or
147 * RUN: Running.
148
149 A thread in state RUN can further be in 2 sub-states:
150
151 * busy-waiting for more work to become available, or
152 * computing the current job.
153
154 The first thread in the pool, aka. the *master*, is always in state *RUN* and
155 is never busy-waiting (instead it executes the APL interpreter).
156
157 The remaining threads, aka. the *workers*, are in state *BLKD* as long as
158 they are inactive (this can only happen if ⎕SYL is being used and the worker
159 is above the value set with ⎕SYL). Otherwise the worker is in state *RUN*. A
160 worker in state *RUN* is not necessarily computing, e.g. if the joblists are
161 empty and the worker is busy-waiting for more work.
162
163 When the interpreter (i.e. the master) needs to compute a primitive scalar
164 function (or an inner or outer product of a primitive scalar function) with
165 a sufficiently large argument, then it unleashes the workers
166 (*Thread_context::M_fork()*), performs its own share of the work, and waits
167 for all workers to complete their share of the work
168 (*Thread_context::M_join()*).
169
170 At the same time, the workers wait for the master's *M_fork()* in
171 *Thread_context::PF_fork()*, perform their share of the work, indicate that
172 their work is complete, and wait for all others to complete as well
173 (*Thread_context::M_join()*).
174
175 == The Operation of the Parallel Subsystem
176
177 After initialization, the parallel subsystem works (see *Thread_context.cc/hh*)
178 as follows.
179
180 * worker thread in state BLKD do nothing. This case can only occur with
181 *CORE_COUNT_WANTED=-3*, and the transition between states BLKD and RUN can
182 (after the initialization) only occur by setting ⎕SYL[26;2].
183
184 * every thread maintains a variable *job_number* which is initially 0 for both
185 the master and every worker:
186
187 ----
188 Thread_context::Thread_context()
189 : N(CNUM_INVALID),
190 thread(0),
191 *job_number(0)*,
192 job_name("no-job-name"),
193 blocked(false)
194 {
195 }
196 ----
197
198 * As long as the *Thread_context::job_number* of the master is equal to the
199 *Thread_context::job_number* number of a worker, that worker busy-waits
200 until both numbers differ. The master also increments the static variable
201 *busy_worker_count*:
202
203 ----
204 /// start parallel execution of work in a worker
205 void PF_fork()
206 {
207 while (get_master().job_number == job_number)
208 /* busy wait until the master has increased job_number */ ;
209 }
210 ----
211
212 * When the master finds new work (e.g. after interpreting a scalar APL
213 function) then it inserts that work into the proper *Parallel_job_list<>* of
214 each worker and increments its own *Thread_context::job_number* (in
215 *Thread_context::M_fork()*). This causes all workers to begin their share of
216 the work:
217
218 ----
219 /// start parallel execution of work at the master
220 static void M_fork(const char * jname)
221 {
222 get_master().job_name = jname;
223 atomic_add(busy_worker_count, active_core_count - 1);
224 ++get_master().job_number;
225 }
226 ----
227
228 * The workers perform their work and, after finishing it, increment their
229 *Thread_context::job_number* and decrement *busy_worker_count*.again:
230
231 ----
232 /// end parallel execution of work in a worker
233 void PF_join()
234 {
235 atomic_add(busy_worker_count, -1); // we are ready
236 ++job_number; // we reached master job_number
237
238 // wait until all workers finished or new job from master
239 while (atomic_read(busy_worker_count) != 0 &&
240 get_master().job_number == job_number)
241 /* busy wait */ ;
242 }
243 ----
244
245
246 image::./APL1.png[APL1,300,150,role="text-center"]
247
248 The synchronization scheme above was designed such that as little interaction
249 between threads is needed and heavier constructs like semaphores could be
250 avoided.
251
252 == Notation
253
254 In the context of parallel execution, the prefix *M_* designates functions
255 that are only called from the master thread, while the prefix *PF_* (for pool
256 function) designates functions that are called from a worker thread.
257
258 Master functions only exist in class *Thread_context*, while pool functions
259 exist in classes *Thread_context*, *ScalarFunction*, *Bif_OPER2_INNER*, and
260 *Bif_OPER2_OUTER*. Note that the master thread itself acts like a worker
261 thread after returning from *M_fork()* and before calling *M_join()*.
262
263 == Benchmarking of the Parallel Execution
264
265 === The Theory ...
266
267 If a scalar APL function, is computed on a single core, then the time (most
268 conveniently expressed in terms of CPU cycles) to compute it for an APL array
269 with a ravel of length N is:
270
271 T~seq~(N) = ⍺~seq~ + β~seq~ × N.
272
273 In theory, the parallel computation of the same function on a number of cores
274 requires time:
275
276 T~par~(N) = ⍺~par~ + β~par~ × N.
277
278 The terms ⍺~seq~ and ⍺~par~ are the start-up times for the computation, while
279 the terms β~seq~ and β~par~ are the per-item times for the computation.
280
281 Under normal circumstance one has:
282
283 * ⍺~seq~ ≤ ⍺~par~
284 * β~seq~ ≥ β~par~
285
286 Under ideal circumstances one even has
287
288 β~par~ = β~seq~ ÷ C, or: β~seq~ ÷ β~par~ = C.
289
290 where C is the number of cores involved. The quotient *β~seq~ ÷ β~par~* is
291 commonly known as the *speed-up* of the parallel execution. The difference
292 ⍺~par~ - ⍺~seq~ is primarily caused by functions like M_fork(), PF_fork(),
293 M_join() and PF_join() above, but also by the overhead caused by the
294 joblist mechanism that is required to efficiently parallelize scalar
295 operation on nested APL values.
296
297 The equations above can be used to compute a break-even length N~BE~ so
298 that:
299
300 * T~seq~(N) < T~par~(N) for N < N~BE~
301 * T~seq~(N) > T~par~(N) for N > N~BE~.
302
303 That simply means that the computation for arrays with a short ravel (i.e. of
304 less than N~BE~ items) it is faster to compute sequentially, while for longer
305 ravels it is faster to compute in parallel.
306
307 The above formulae are easier to interpret if one plots the execution times
308 (on the Y axis) vs. the vector length (on the X axis). For example, if
309
310 * ⍺~seq~ = 10, ⍺~par~ = 10, i.e. T~seq~(N) = 10 + 10×N (green plot line)
311 * β~seq~ = 30, β~par~ = 5, i.e. T~par~(N) = 30 + 5 (red plot line)
312
313 then the theory predicts the following execution times:
314
315 image::./APL2.png[APL2,300,150,role="text-center"]
316
317 As one can see, the intersection of the Y-axis (i.e. N=0) and the plot line
318 T~seq~(N) and T~par~(N) is the start-up time ⍺~seq~ and ⍺~par~ respectively.
319 The break-even length in this example is the intersection of the two plot
320 lines at N=4.
321
322 === ... and the Practice
323
324 As *Benjamin Brewster* stated in 1882: _In theory there is no difference
325 between theory and practice, while in practice there is_.
326
327 This statement is particularly true for benchmarking. Until about 1990, given
328 some piece of assembler code, it was feasible (and was actually done) to
329 compute the number of CPU cycles that the execution of that code would take.
330
331 Since then a number of optimizations, both in hardware and in software, have
332 made it practically impossible to predict the execution time of any given code.
333 Even worse, these days the same code, executed again and again, typically
334 results in rather different cycle counts for each execution pass. Even if
335 "no" other processes execute on the same CPU on which a benchmark measurement
336 is performed (where "no other process" means not counting the typically 250 or
337 so operating system processes that are sitting idle on the CPU) the results
338 can differ substantially between different measurements of the same code.
339
340 So in practice, lets discuss the results of a benchmark:
341
342 image::./APL3.png[APL3,300,150,role="text-center"]
343
344 This benchmark measured the time to compute Z←¯6 ○ MixIRC for different vector
345 lengths, ranging from N=200 to N=4000. MixIRC is a random mix of integer,
346 real and complex arguments of ¯6○ aka. *arccosh*. The benchmark worked well in
347 the sense that the measured numbers of CPU cycles were very much in line with
348 the theory. The thick lines are those that have the smallest squared
349 differences from the measurement points (the line that best matches the
350 measurement points).
351
352 To be on the safe side, lets repeat *the same* benchmark:
353
354 image::./APL4.png[APL4,300,150,role="text-center"]
355
356 This one went less well. One difference from the previous one is that the
357 deviations of the measurement points are considerably larger than in the
358 previous run. If one runs the benchmark many times, then it looks like the
359 deviations in the sequential execution are larger than in the parallel
360 execution. More importantly, the sequential start-up time ⍺~seq~ is now
361 larger than the parallel start-up time ⍺~par~.
362
363 These two examples are only meant to highlight some the problems that may occur
364 if one tries to determine the parameters ⍺ and β. The following is a summary
365 of findings after having performed many such measurements with GNU APL and
366 different core counts, vector lengths, and primitive functions:
367
368 * every measurement needs to be visualized (plotted) to rule out too many
369 or too large outliers.
370 * for determining the start-up costs ⍺~seq~ and ⍺~par~ it seems to be better
371 to use fewer vector lengths and also shorter vectors.
372 * for determining the per-item costs β~seq~ and β~par~ it is better to
373 use longer vectors.
374 * scalar functions with a low β (like A+B) tend to give more obscure results
375 (and lower speed-ups) than scalar functions with a higher β. This is
376 primarily caused by the fact that all cores share the same interface to the
377 (shared) main memory of the machine.
378 * The speed-up of additional virtual cores (compared to physical ones) seems
379 to be rather low. That is, for example, the speed-up of 12 virtual cores (on
380 a hyper-threaded CPU with 6 physical cores) is only marginally higher than on
381 6 physical cores. GNU APL addresses this fact by distributing the load over
382 the physical cores before placing hyper-threads on the physical cores.
383
384 === The Benchmark Workspace Scalar2.apl
385
386 The workspace *workspaces/Scalar2.apl* can be used to measure the execution
387 times of scalar functions. GNU APL provides a number of internal performance
388 counters. These counters need to be enabled with
389 *PERFORMANCE_COUNTERS_WANTED=yes* in *./configure*, and the CPU must have a
390 cycle counter and an instruction to read it (currently only Intel CPUs can use
391 this feature). The cycle counter of the CPU is read before and after the
392 computation of a scalar function, and the difference can be read in APL via
393 *⎕FIO[200]* and *⎕FIO[201]*. Measuring execution times this way is far more
394 precise than old-fashioned measurements using ⎕TS at the APL level.
395
396 Scalar2.apl is most conveniently called from the command line, and what is
397 being measured can be controlled via command line arguments. For example
398 (from the top-level directory of GNU APL):
399
400 ----
401 make parallel1 # runs ./configure with suitable options
402 src/apl -f workspaces/Scalar2.apl -- -c 3,6 -d 200×⍳20
403 ----
404
405 The *Scalar2.apl* workspace understands the following command line options:
406
407 .Table Scalar2.apl command line options (after --)
408 [width="75%", cols="18,30,^12,^12", options="header"]
409 |===
410 |Option |Effect |Example |Default
411 |-c core-counts |set the number of cores |-c 2,3 |2
412 |-d vector-lengths|set the vector lengths (N-axis)|-d 200×⍳2|⍳20
413 |-f function |select the function to measure |-f 20 | 39
414 |===
415
416 For every core count, *Scalar2.apl* displays a separate plot window with the
417 measurement results for sequential execution and for the parallel execution
418 with the given core count.
419
420 == Recursive Parallelization
421
422 The purpose of the joblist mentioned above is as follows. Consider the
423 APL expression below, computed in parallel on 4 cores:
424
425 ----
426 Z←1 2 (⍳1000) 4 + 1 (20 21 22) 3 4
427 ----
428
429 The 4 ravel elements of the left and right arguments of dyadic + are stored in
430 4 consecutive Cells, which are distributed in a round-robin fashion over the
431 cores. That is:
432
433 ----
434 Core #1 computes: 1 + 1 (1 addition)
435 Core #2 computes: 2 + 20 21 22 (3 additions)
436 Core #3 computes: (⍳1000) + 3 (1000 additions)
437 Core #4 computes: 4 + 4 (1 addition)
438 ----
439
440 Therefore cores #1 and #4 compute one sum, core #2 computes 3 sums, and
441 core #3 computes 1000 sums. This is obviously not optimal since cores #1, #2,
442 and #3 are most of the time idle, waiting for core #3 to finish.
443
444 To avoid this case, GNU APL parallelizes scalar functions recursively with the
445 following algorithm.
446
447 . the interpreter starts with an empty joblist.
448 . when the interpreter evaluates a scalar function, then it puts a new job
449 into the joblist. The job describes the relevant parameters (essentially
450 the scalar function to be computed and the address(es) of its argument(s).
451 . LOOP: while the joblist is not empty:
452
453 .. remove the first job from the list
454
455 .. perform the computation defined in the job in parallel
456
457 .. if a core comes across a nested ravel item, then:
458 * if the item (and hence the result) is small: compute it immediately
459 * if the item is large: create a new APL value whose ravel is un-initialized
460 (this operation takes constant time) and add a new entry into the joblist
461 (for computing the ravel of the nested result later on).
462
463 For performance reasons, there are actually two such joblists:
464 *Thread_context::joblist_B* for monadic scalar functions, and
465 *Thread_context::joblist_AB* for dyadic scalar functions (and
466 inner and outer products of them).
467
468 == Setting Thresholds
469
470 One purpose of benchmarking is to find the break-even lengths for
471 scalar functions. After that length is found, one can inform the APL
472 interpreter about the break-even lengths. This is done via a configuration
473 file, normally */usr/local/etc/gnu-apl.d/parallel_thresholds*.
474
475 This file is installed by 'make install', but the values in the file
476 are usually not optimal. One can, however, enter better values manually.
477 Consider a few non-empty lines in the file:
478
479 ----
480 perfo_1(F12_PLUS, _B, "+ B", 8888888888888888888ULL)
481 perfo_1(F12_POWER, _B, "⋆ B", 12 )
482 perfo_2(F12_TIMES, _AB, "A × B", 33 )
483 ----
484
485 The first line above sets the break-even point of *monadic +* to
486 8888888888888888888ULL, which is a value so large that parallel execution will
487 never happen for monadic +.
488
489 The second line sets the break-even point of *monadic ** to 12. Arrays (of any
490 rank) with fewer than 12 ravel items will be computed sequentially, but longer
491 arrays in parallel.
492
493 The third line sets the break-even point of *dyadic ×* to 33. Arrays (of any
494 rank) with fewer than 33 ravel items will be computed sequentially, but longer
495 arrays in parallel.
496
497 In general, the fewer cycles a function needs, the higher should the threshold
498 be set.
499
500 == The Optimal vs. the Maximal Core Count
501
502 The last plot window shown by the *Scalar2* workspace summarizes the speed-ups
503 that were achieved for the different core counts that were selected with the
504 -c option.
505
506 image::./APL5.png[APL5,300,150,role="text-center"]
507
508 NOTE: leave at least one of the available cores unused because otherwise the
509 operating system could grab one of the cores for its own purposes and that
510 core would then become much slower than the others. The operating system is
511 usually smart enough to locate an unused core for its own purposes, but that
512 must fail if all cores are fully loaded with APL work.
513
514 The speed-ups plotted in the last window are usually reasonable if:
515
516 * the APL function that is being bench-marked (as selected by the -f option)
517 is not too lightweight, and
518 * the vector lengths (-d option) are not too short.
519
520 The measurement shown above was executed on a 6-core i7-8700 CPU. The CPU has
521 6 (physical) cores with 12 (logical) core threads where the 12 core threads
522 are mapped to 12 "CPUs" in the operating system as (per */proc/cpuinfo*).
523
524 The benchmark command used was:
525
526 ----
527 src/apl -f workspaces/Scalar2.apl -- -c ⍳11 -d 5000×⍳20 -f 39
528 ----
529
530 which means that:
531
532 * *-f 39* : selects *Z←¯6○B* aka. *arccosh(B)* as the benchmarking function
533 with a mix of Integer, Real, and Complex numbers,
534 * *-d 5000×⍳20* : use vector lengths ⍴B = 5,000, 10,000, 15,000 ... 100,000, and
535 * *-c ⍳11* : use core counts of 1, 2, 3, ... and 11.
536
537 The 11 different core counts and 20 different vector lengths above
538 amounted to a total of 220 (= 11×20) individual measurements in the benchmark
539 plotted above.
540
541 Had we run the benchmark with *-c ⍳12* instead of *-c ⍳11* then the
542 measurement with 12 cores would have shown a rather bad speed-up (try it
543 yourself with *-c* set to the number of cores on your computer).
544
545 *Corollary:* the optimal performance is achieved when the number of cores used
546 for parallel APL is slightly smaller than the number of cores available. The
547 number of cores available is also influenced by other (even idle) processes on
548 the machine because they also influence the scheduling of the threads that
549 perform the APL work.
550