This repository has been archived by the owner on Apr 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
overlap.tex
3451 lines (3214 loc) · 147 KB
/
overlap.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% vim: ts=4 sw=4 et ft=tex
\chapter{Overlap Analysis for Dependent AND-parallelism}
\label{chap:overlap}
\status{This is work in progress, some sections are ready for review.}
Introducing parallelism into a Mercury program is easy.
A programmer can use the parallel conjunction operator (an ampersand)
instead of the plain conjunction operator (a comma) to tell the compiler
that the conjuncts of the conjunction should be executed in parallel with
one another.
However,
in almost all places where parallelism can be introduced,
it will not be
profitable as it is not worthwhile parallelising small computations.
Making a task available to another CPU
may take thousands of instructions,
so spawning off a task that takes only a hundred instructions is clearly a
loss.
Even spawning off a task of a few thousand instructions is not a win;
it should only be done for computations
that take long enough to benefit from parallelism.
It is often difficult for a programmer to determine if parallelisation of
any particular computation is worthwhile.
Researchers have therefore worked towards automatic parallelisation.
Autoparallelising compilers have long tried to use granularity analysis to
ensure that they only spawn off computations whose cost will probably exceed
the spawn-off cost by a comfortable margin.
However, this is not enough to yield good results,
because data dependencies may \emph{also} limit
the usefulness of running computations in parallel.
If a spawned off computation blocks almost immediately
and can resume only after another computation has completed its work,
then the cost of parallelisation again exceeds the benefit.
%This chapter is based on and extends our paper:
%
%\begin{quote}
%\pubauthor{Paul Bone, Zoltan Somogyi and Peter Schachte.}
%% This spelling of parallelisation is okay.
%\pubtitle{Estimating the overlap between dependent computations for automatic
%parallelization}
%\pubhow{Theory and Practice of Logic Programming,}{11(4--5):575--591, 2011.}
%\end{quote}
%\noindent
This chapter presents a set of algorithms for recognising places in a
program where it is worthwhile to execute two or more computations in
parallel,
algorithms that pay attention to the second of these issues as well as the
first.
Our system uses profiling information to estimate the
times at which a procedure call is expected to consume the values of its
input arguments
and the times at which it is expected to produce the values of its output
arguments.
Given two calls that may be executed in parallel,
our system uses the estimated times of production and consumption
of the variables they share
to determine how much their executions are likely to overlap
when run in parallel,
and therefore whether executing them in parallel is a good idea or not.
We have implemented this technique for Mercury
in the form of a tool
that uses data from Mercury's deep profiler
to generate recommendations about what to parallelise.
The programmer can then execute the compiler with automatic parallelism
enabled and provide the recommendations to generate a parallel version of
the program.
An important benefit of profile-directed parallelisation is that
since programmers do not annotate the source program,
it can be re-parallelised easily after a change to the program
obsoletes some old parallelisation opportunities and creates others.
To do this, the programmer can re-profile the program to generate fresh
recommendations and recompile the program to apply those recommendations.
Nevertheless, if programmers want to parallelise some conjunctions manually,
they can do so: our system will not override the programmer.
We present preliminary results that show that
this technique can yield useful parallelisation speedups,
while requiring nothing more from the programmer
than representative input data for the profiling run.
The structure of this chapter is as follows.
Section~\ref{sec:overlap_aims} states our two aims for this chapter.
Then Section~\ref{sec:overlap_approach} outlines our general approach
including information about the call graph search for parallelisation
opportunities.
Section~\ref{sec:overlap_reccalls}
describes how we calculate information about recursive calls missing from
the profiling data.
Section~\ref{sec:overlap_coverage}
describes our change to coverage profiling, which provides more accurate
coverage data for the new call graph based search for parallelisation
opportunities.
Section~\ref{sec:overlap_overlap_alg} describes our algorithm for
calculating the execution overlap between two or more dependent conjuncts.
A conjunction with more than two conjuncts can be parallelised
in several different ways;
Section~\ref{sec:overlap_howto} shows how we choose the best way.
Section~\ref{sec:overlap_pragmatic} discusses some pragmatic issues.
Section~\ref{sec:overlap_perf} evaluates
how our system works in practice on some example programs, and
Section~\ref{sec:overlap_related} concludes
with comparisons to related work.
\section{Aims}
\label{sec:overlap_aims}
\status{This section is ready for proofreading by Peter S. or Micheal R.}
When parallelising Mercury programs,
the best parallelisation opportunities occur
where two goals take a significant and roughly similar amount of time to
execute.
Their execution time should be as large as possible
so that the relative costs of parallel execution are small,
and they should be independent to minimise synchronisation costs.
Unfortunately, goals expensive enough to be worth executing in parallel
are rarely independent.
For example, in the Mercury compiler itself,
there are 69 conjunctions containing two or more expensive goals,
goals with a cost above 10,000csc (call sequence counts),
but in only three of those conjunctions are the expensive goals independent.
This is why Mercury supports the parallel execution of dependent conjunctions
through the use of futures and a compiler transformation
\citep{wang:2006:hons, wang:2011:dep-par} (Section~\ref{sec:backgnd_deppar}).
If the \emph{consumer} of the variable attempts to retrieve the variable's value
before it has been produced, then its execution is blocked
until the \emph{producer} makes the variable available.
\picfigure{overlap_compare}{Ample vs smaller parallel overlap between \code{p} and \code{q}}
Dependent parallel conjunctions differ widely
in the amount of parallelism they have available.
Consider a parallel conjunction with two similarly-sized conjuncts,
\code{p} and \code{q}, that share a single variable \code{A}.
If \code{p} produces \code{A} late but \code{q} consumes it early,
as shown on the right side of Figure~\ref{fig:overlap_compare},
there will be little parallelism,
since \code{q} will be blocked soon after it starts,
and will be unblocked only when \code{p} is about to finish.
Alternatively, if \code{p} produces \code{A} early
and \code{q} consumes it late,
as shown on the left side of in Figure~\ref{fig:overlap_compare},
we would get much more parallelism.
The top part of each scenario
shows the execution of the sequential form of the conjunction.
Unfortunately, in real Mercury programs,
almost all conjunctions are dependent conjunctions,
and in most of them,
shared variables are produced very late and consumed very early.
Parallelising them would therefore yield slowdowns instead of speedups,
because the overheads of parallel execution would far outweigh the
benefit of the small amount of parallelism that is available.
We want to parallelise only conjunctions
in which any shared variables are produced early, consumed late,
or (preferably) both;
such computations expose more parallelism.
The first purpose of this chapter is to show how one can find these conjunctions.
\begin{figure}
\begin{center}
\begin{minipage}[b]{0.49\textwidth}
\subfigure[Sequential \mapfoldl]{%
\label{fig:map_foldl_seq}
{\small
\begin{tabular}{l}
\\
\\
\code{map\_foldl(\_, \_, [], Acc, Acc).} \\
\code{map\_foldl(M, F, [X $|$ Xs], Acc0, Acc) :-} \\
\code{~~~~M(X, Y),} \\
\code{~~~~F(Y, Acc0, Acc1),} \\
\code{~~~~map\_foldl(M, F, Xs, Acc1, Acc).} \\
\end{tabular}}
}
\end{minipage}
%
\begin{minipage}[b]{0.49\textwidth}
\subfigure[Parallel \mapfoldl with overlap]{%
\label{fig:map_foldl_par}
{\small
\begin{tabular}{l}
\code{map\_foldl(\_, \_, [], Acc, Acc).} \\
\code{map\_foldl(M, F, [X $|$ Xs], Acc0, Acc) :-} \\
\code{~~~~(} \\
\code{~~~~~~~~M(X, Y),} \\
\code{~~~~~~~~F(Y, Acc0, Acc1)} \\
\code{~~~~) \&} \\
\code{~~~~map\_foldl(M, F, Xs, Acc1, Acc).} \\
\end{tabular}}
}
\end{minipage}
\end{center}
\caption{Sequential and parallel \mapfoldl}
% the recursive call is less dependent
% on the conjunction of the first two calls.
\label{fig:map_foldl}
%\vspace{-2\baselineskip}
\end{figure}
\picfigure{mapfoldl-overlap}{Overlap of \mapfoldl
(Figure~\ref{fig:map_foldl_par})}
The second purpose of this chapter is to find the best way to parallelise
these conjunctions.
Consider the \mapfoldl predicate in Figure~\ref{fig:map_foldl_seq}.
The body of the recursive clause has three conjuncts.
We could make each conjunct execute in parallel,
or we could execute two conjuncts in sequence
(either the first and second, or the second and third),
and execute that sequential conjunction in parallel with the remaining conjunct.
In this case, there is little point in executing
the higher order calls to the \M and \F predicates
%(herein map and fold respectively)
in parallel with one another,
since in virtually all cases,
\M will generate \code{Y} very late and
\F will consume \code{Y} very early.
However, executing the sequential conjunction of the calls to \M and \F
in parallel with the recursive call \emph{will} be worthwhile
if \M is time-consuming,
because this implies that
a typical recursive call will consume its fourth argument late.
The recursive call processing the second element of the list
will have significant execution overlap (mainly the cost of \M)
with its parent processing the first element of the list
even if (as is typical) the fold predicate generates \code{Acc1} very late.
This parallel version of \mapfoldl is shown in
Figure~\ref{fig:map_foldl_par}.
A representation of the first three iterations of it
is shown in Figure~\ref{fig:mapfoldl-overlap}.
(This is the kind of computation that
Reform Prolog \citep{bevemyr:reform} was designed to parallelise.)
\section{Our general approach}
\label{sec:overlap_approach}
\status{This section is ready for proofreading by Peter S. or Micheal R.}
\plan{Goal}
We want to find the conjunctions in the program
whose parallelisation would be the most profitable.
This means finding the conjunctions with conjuncts
whose execution cost exceeds the spawning-off cost by the highest margin,
and whose interdependencies, if any,
allow their executions to overlap the most.
It is better to spawn off a medium-sized computation
whose execution can overlap almost completely
with the execution of another medium-sized computation,
than it is to spawn off a big computation
whose execution can overlap only slightly
with the execution of another big computation,
but it is better still to spawn off a big computation
whose execution can overlap almost completely
with the execution of another big computation.
Essentially, the more the tasks' executions can overlap with one another,
the greater the margin by which
the likely runtime of the parallel version of a conjunction beats
the likely runtime of the sequential version (speedup),
and the more beneficial parallelising that conjunction will be.
\plan{Profiler feedback}
To compute this likely benefit,
we need information
both about the likely cost of calls
and the execution overlap allowed by their dependencies.
A compiler may be able to estimate some cost information from static
analysis.
However, this will not be accurate;
static analysis cannot take into account sizes of data terms,
or other values that are only available at runtime.
It may be possible to provide this data by some other means,
such as by requiring the programmer to provide a
descriptions of the typical shapes and sizes of
their program's likely input data.
Programming folklore says that programmers are not good at estimating where
their programs' hotspots are.
Some of the reasons for this will affect a programmer's estimate of their
program's likely input data, making it inaccurate.
In fact, misunderstanding a program's typical input is one of the reasons
why a programmer is likely to mis-estimate the location of the
program's hotspots.
Our argument is that an estimate,
even a confident one, can only be verified by measurement,
but a measurement never needs estimation to back it up.
Therefore,
our automatic parallelisation system uses profiler feedback information.
This was introduced in Section~\ref{sec:backgnd_autopar},
which also includes a description of Mercury's deep profiler.
To generate the profiler feedback data,
we require programmers to follow this sequence of actions after they have
tested and debugged the program.
\begin{enumerate}
\item
Compile the program
with options asking for profiling
for automatic parallelisation.
\item
Run the program on a representative set of input data.
This will generate a profiling data file.
\item
Invoke our feedback tool on the profiling data file.
This will generate a parallelisation feedback file.
\item
Compile the program for parallel execution,
specifying the feedback file.
The file tells the compiler
\emph{which} sequential conjunctions to convert to parallel conjunctions,
and exactly \emph{how}.
For example, \code{c1, c2, c3} can be converted
into \code{c1 \& (c2, c3)},
into \code{(c1, c2) \& c3}, or
into \code{c1 \& c2 \& c3},
and as the \code{map\_foldl} example shows,
the speedups you get from them can be strikingly different.
\end{enumerate}
\noindent
A visual representation of such a workflow is shown in
Figure~\ref{fig:prof_fb} on page~\pageref{fig:prof_fb}.
It is up to the programmer using our system
to select training input for the profiling run in step 2.
Obviously, programmers should pick input that is as representative as
possible;
but even input data that is quite different from the training input can
generate useful parallelisation recommendations.
Variations in our input data will change the numerical results
that we use to decide whether something should be parallelised,
however they rarely change a ``should parallelise'' decision into a
``should not parallelise'' decision or vice-versa.
The other source of inaccuracy comes from mis-estimating the hardware's
performance on certain operations such as the cost of spawning off a new
task.
Such mis-estimations will have the same impact as variations in input data.
The main focus of this chapter is on step 3;
we give the main algorithms used by the feedback tool.
However, we will also touch on steps 1 and 4.
We believe that step 2 can only be addressed by the programmer,
as they understand what input is representative for their program.
\plan{DFS \& limits}
Our feedback tool looks for parallelisation opportunities
by doing a depth-first search of the call tree of the profiling run,
each node of which is an SCC (strongly connected component) of procedure
calls.
It explores the subtree below a node in the tree
only if the per-call cost of the subtree is greater than a configurable
threshold,
and if the amount of parallelism it has found at and above that node
is below another configurable threshold.
The first test lets us avoid looking at code
that would take more work to spawn off than to execute,
while the second test lets us avoid creating
more parallel work than the target machine can handle.
Together these tests dramatically reduce the portions of a program that need
analysis,
reducing the time required to search for parallelisation opportunities.
For each procedure in the call tree,
we search its body for conjunctions that contain two or more calls with
execution times above yet another configurable threshold.
This test also reduces the parts of the program that will be analysed
further;
it quickly rejects procedures that cannot contain any profitable
parallelism.
Parallelising a conjunction
requires partitioning the original conjuncts into two or more groups,
with the conjuncts in each group being executed sequentially
but different groups being executed in parallel.
Each group represents a hypothetical sequential conjunction,
and the set of groups represents a hypothetical parallel conjunction.
As this parallel conjunction represents a possible parallelisation of the
original conjunction, we call it a \emph{candidate parallelisation}.
Most conjunctions can be partitioned into several alternative candidate
parallelisations,
for example, we showed above that \mapfoldl has three alternative
parallelisations of its recursive branch.
We use the algorithms of Section~\ref{sec:overlap_overlap_alg}
to compute the expected parallel execution time of each parallelisation.
These algorithms take into account the runtime overheads of parallel execution.
Large conjunctions can have a very large number of
candidate parallelisations ($2^{n-1}$ for $n$ conjuncts).
Therefore,
we use the algorithms of Section~\ref{sec:overlap_howto}
to heuristically reduce the number of parallelisations whose expected
execution time we calculate.
If the best-performing parallelisation we find
shows a nontrivial speedup over sequential execution,
we remember that we want to perform that parallelisation on this conjunction.
A procedure can contain several conjunctions with two or more goals that we
consider parallelising,
therefore multiple candidate parallelisations may be generated for different
conjunctions in a procedure.
The same procedure may also appear more than once in the call graph.
Each time it occurs in the call graph its conjunctions may be parallelised
differently, or not at all,
therefore it is said to be \emph{polyvariant} (having multiple forms).
Currently our implementation compiles a single \emph{monovariant} procedure.
We discuss how the implementation chooses which candidate parallelisations to
include in Section~\ref{sec:overlap_pragmatic}.
% \section{Traversing the call graph}
% \label{sec:overlap_dfs}
%
% % XXX Further work.
% \paul{TODO: This feature is not yet implemented.}
% If the depth first search later finds
% some of the conjuncts to have parallelisable code inside them,
% we revisit this conjunction,
% this time using updated data about the cost of those conjuncts.
% Otherwise,
% we add a recommendation to perform the selected parallelisation
% to the feedback advice we generate for the compiler.
% \paul{This is not yet implemented and will not be for this version of the paper.}
% \peter{Then you need to say that.}
% GREEDY_SEARCH The top level algorithm of the feedback tool
% GREEDY_SEARCH is a traversal of the tree of cliques
% GREEDY_SEARCH recorded in the deep profiling data file.
% GREEDY_SEARCH Each clique has its own unique entry point,
% GREEDY_SEARCH which will be a call site in a higher clique;
% GREEDY_SEARCH this higher clique is the parent node of this clique.
% GREEDY_SEARCH Likewise, every call site
% GREEDY_SEARCH in every procedure in the clique
% GREEDY_SEARCH will be the entry point of another clique,
% GREEDY_SEARCH provided that
% GREEDY_SEARCH (a) it is actually executed and (b) the callee is not in this clique.
% GREEDY_SEARCH These lower cliques are the children of this clique.
% GREEDY_SEARCH % We will describe our traversal algorithm in detail
% GREEDY_SEARCH % in section \ref{sec:bestfirst},
% GREEDY_SEARCH % but for now, consider this traversal
% GREEDY_SEARCH % as operating on a \emph{candidates list},
% GREEDY_SEARCH % a list of cliques sorted on total cost.
% GREEDY_SEARCH Our traversal algorithm operates on a \emph{candidates list},
% GREEDY_SEARCH which contains a list of cliques sorted on total cost.
% GREEDY_SEARCH We start with the list containing only
% GREEDY_SEARCH the clique of the top level call to \code{main},
% GREEDY_SEARCH the predicate where every Mercury program starts execution.
% GREEDY_SEARCH Then, at each step,
% GREEDY_SEARCH \begin{itemize}
% GREEDY_SEARCH \item
% GREEDY_SEARCH we remove the clique at the start of the candidates list;
% GREEDY_SEARCH \item
% GREEDY_SEARCH we process this clique
% GREEDY_SEARCH by looking at the conjunctions in the clique's procedures
% GREEDY_SEARCH to see whether they should be parallelised; and then
% GREEDY_SEARCH \item
% GREEDY_SEARCH we insert the child cliques (if any) of this clique into the candidates list.
% GREEDY_SEARCH \end{itemize}
% GREEDY_SEARCH We stop when either even the highest cost candidate
% GREEDY_SEARCH is too cheap to be worth parallelising,
% GREEDY_SEARCH or we have achieved our target CPU utilisation
% GREEDY_SEARCH for all phases of the program's execution.
% GREEDY_SEARCH This is only an outline of our traversal algorithm.
% GREEDY_SEARCH In section \ref{sec:pragmatic}, we will describe it in detail,
% GREEDY_SEARCH together with our solutions to several issues that come up in practice.
% \zoltan{this is wrong: the overheads should be PART OF the parallel time}
% \begin{equation*}
% Speedup = \frac{Time_{Seq}}{Time_{Par} + ParOverheads}
% \end{equation*}
\section{The cost of recursive calls}
\label{sec:overlap_reccalls}
\status{This section is ready for proofreading by Peter S. or Micheal R.}
% leave discussion of granularity estimation by static analysis
% for the related work section;
% mention that this work has not extended to large programs.
The Mercury deep profiler gives us
the costs of all non-recursive call sites in a clique.
For recursive calls,
the costs of the callee are mingled together
with the costs of the caller,
which is either the same procedure as the callee,
or is mutually recursive with it.
Therefore if we want to know the cost of a recursive call site (and we do),
we have to infer this
from the cost of the clique as a whole,
the cost of each call site within the procedures of the clique,
the structures of the bodies of those procedures,
and the frequency of execution of each path through those bodies.
For now, we will restrict our attention to SCCs
that contain only a single procedure and where that procedure matches one of
the three recursion patterns below.
These are among the most commonly used recursion patterns and the
inference processes for them are also among the simplest.
Later, we will discuss how partial support could be added for mutually
recursive procedures.
{\bf Pattern 1: no recursion at all.}
This is not a very interesting pattern, but we support it completely.
We do not need to compute the costs of recursive calls if a procedure is not
recursive.
{\bf Pattern 2: simply recursive procedures.}
The first pattern consists of procedures whose bodies
have just two types of execution path through them:
base cases, and recursive cases containing a single recursive call site.
Our example for this category is \code{map\_foldl},
whose code is shown in Figure~\ref{fig:map_foldl}.
Let us say that of 100 calls to the procedure,
90 were from the recursive call site
and 10 were from a call site in the parent SCC.
Then we would calculate
that each non-recursive call
(from the parent SCC)
would on average yield nine recursive calls
(from within the SCC).
Note that there are actually ten levels of recursion so we add one for the
highest level of recursion (the call from the parent SCC).
We call this the average deepest recursion:
\begin{equation*}
AvgMaxDepth = Calls_{RecCallSites} / Calls_{ParentCallSite} + 1
\end{equation*}
The deepest recursive call site executes only the non-recursive path,
and incurs only its costs ($CostNonRec$).
We measure the costs of calls in \emph{call sequence counts} (csc),
a unit defined in Section~\ref{sec:backgnd_deep}.
The next deepest would take the recursive path,
and incur one copy of the non-recursive call costs along the recursive path
($CostNonRec$)
plus the cost of the recursive call itself ($1$)
plus the cost of the non-recursive branch ($CostNonRec$).
The third last would incur two copies of the costs
of the non-recursive calls along the recursive path,
plus the cost of the last call.
The formulas for each of these recursive call site costs is:
\[
\begin{array}{r @{}l @{}l}
cost(0)~&= CostNonRec \\
cost(1)~&= CostNonRec + CostRec + 1 \\
cost(2)~&= CostNonRec + 2{\times}CostRec + 2
\end{array}
\]
\noindent
By induction,
the cost of a recursive call site to depth $D$ (0 being the deepest)
is:
\begin{equation*}
cost(D) = CostNonRec + D(CostRec + 1)
\end{equation*}
We can now calculate the average cost of a call at any level of the
recursion.
Simply recursive procedures have a uniform number of calls at each depth of
the recursion.
The depth representing the typical use of such a procedure is half of
$AvgMaxDepth - 1$.
We subtract 1 as the first level of recursion is not reached by a recursive
call site.
This allows us to calculate the typical cost of a recursive call from this
call site.
The typical depth of this part of the call graph is $(10 - 1)/2 - 1 = 3.5$
The extra subtraction of 1 is necessary as we start counting depth from
zero.
For example, if \mapfoldl's non-recursive path cost is 10csc,
its recursive path cost is 10,000csc,
and its typical depth is $3.5$.
Then its typical cost is $10 + 3.5(10,000 + 1) = 35,013.5$ call sequence counts.
\begin{figure}[tb]
\begin{center}
\begin{minipage}[b][1.9in]{0.49\textwidth}
\subfigure[Accumulator quicksort]{%
\label{fig:quicksort_acc}
\begin{tabular}{l}
\code{quicksort([], Acc, Acc).} \\
\code{quicksort([Pivot $|$ Xs], Acc0, Acc) :-} \\
\code{~~~~partition(Pivot, Xs, Lows, Highs),} \\
\code{~~~~quicksort(Lows, Acc0, Acc1),} \\
\code{~~~~quicksort(Highs, [Pivot $|$ Acc1], Acc).} \\
% Add whitespace to shift the table upwards without also moving the caption.
\\
\\
\\
\end{tabular}
}
\hfill
\end{minipage}
\begin{minipage}[b][1.9in]{0.49\textwidth}
\subfigure[Call graph]{%
\includegraphics[width=0.98\textwidth]{pics/call_tree_dc}
\label{fig:quicksort_acc_callgraph}
}
\hfill
\end{minipage}
\end{center}
\vspace{-2ex}
\caption{Accumulator quicksort, definition and call graph}
\end{figure}
{\bf Pattern 3: Divide-and-conquer procedures.}
The third pattern consists of procedures whose bodies
also have just two types of execution path through them:
base cases, and recursive cases containing \emph{two} recursive call sites.
Our example for this category is an accumulator version of \quicksortacc,
whose code is shown in Figure~\ref{fig:quicksort_acc}.
Calculating the recursion depth of \quicksortacc can be more
problematic.
We know that if a good value for \code{Pivot} is chosen \quicksortacc runs
optimally,
dividing the list in half with each recursion.
Figure~\ref{fig:quicksort_acc_callgraph} shows the call graph for such an
invocation of \quicksortacc.
There are 15 nodes in \code{qs}'s call tree,
each node has exactly one call leading to it;
therefore there is one call from outside \quicksortacc's SCC
(the call from \code{main}),
and 14 calls within the SCC
(the calls from \code{qs} nodes).
By inspection, there are four complete levels of recursion.
There are always
$\ceil{\log_2(N+1)}$
%$\log_2(N+1)$
levels in a divide and conquer call graph of $N$ nodes when
the graph is a \emph{complete binary tree}
(we will cover non-complete binary trees later).
Since there are always $N-1$ calls from within the SCC for a graph with
$N$ nodes then it follows that
there are $\ceil{\log_2(C+2)}$ levels for a divide and conquer call graph
with $C$ recursive calls.
In this example, $C$ is 14 and therefore there are four levels of recursion
as we noted above.
If there were two invocations of \quicksortacc from \code{main/2} then there
would be two calls from outside the SCC and 28 calls from within,
in this case the depth is still four.
The average maximum recursion depth in terms of call counts for divide and
conquer code is therefore:
\begin{equation*}
AvgMaxDepth = \log_2
\left(\frac{Calls_{RecCallSites}}{Calls_{ParentCallSite}} + 2\right)
\end{equation*}
\noindent
This is the estimated depth of the tree so we omit the ceiling operator.
Non-complete binary trees can be divided into two cases:
\begin{description}
\item[Pathologically bad trees] (trees which resemble sticks)
are created when consistently worst-case pivots are chosen.
These are rare and are considered performance bugs;
programmers will usually want to remove such bugs in order to improve
sequential execution performance before they attempt to parallelise
their program.
\item[Slightly imbalanced trees] are more common,
such situations fall into the same class as those where the profiling
data is not quite representative of the optimised program's future.
In Section~\ref{sec:overlap_approach} we explained that these variations
are harmless.
\end{description}
\noindent
Therefore, we assume that all divide and conquer code is, on average,
evenly balanced.
As before, the deepest call executes only the non-recursive path,
and incurs only its costs.
The next deepest takes the recursive path,
it incurs the costs of the goals along that path,
plus the costs of the two calls to the base case,
plus twice the base case's cost itself.
The third deepest also takes the recursive path,
plus the costs of the two recursive calls' executions of the recursive path,
that is three times the cost of the recursive path ($3{RecCost}$);
plus the costs of the two recursive calls and the costs of the four calls to
the base case ($6$);
plus four times the base case's cost ($4{CostNonRec}$).
\[
\begin{array}{r @{}l @{}l}
cost(0)~&= CostNonRec \\
cost(1)~&= CostRec + 2 + 2{CostNonRec} \\
cost(2)~&= 3{CostRec} + 6 + 4{CostNonRec} \\
\end{array}
\]
\noindent
The cost of a recursive call in a perfectly balanced divide and conquer
procedure at depth $D$ is:
\begin{equation*}
cost(D) = (2^D-1)(CostRec + 2) + 2^D{CostNonRec}
\end{equation*}
\plan{interesting depth of d\&c}
Most of the execution of a divide and conquer algorithm occurs at deep
recursion levels as there are many more calls made at these levels than higher
levels.
However, for parallelism the high recursion levels are more interesting:
we know that parallelising the top of the algorithm's call graph can provide
ample coarse-grained parallelism.
We will show how to calculate the cost of a recursive call at the top of the
call graph.
First, depth is measured from zero in the equations above, so we must
subtract one from AvgMaxDepth.
Second, the recursive calls at the first level call the second level,
to compute the cost of calls to this level we must subtract one again.
Therefore we use the cost formula with $D = AvgMaxDepth - 2$.
\plan{quicksort example}
For example, let us compute the costs of the recursive calls at the top of
\quicksortacc's call graph.
In this example, we gathered data using Mercury's deep profiler on 10
executions of \quicksortacc sorting a list of 32,768 elements.
The profiler reports that there are 655,370 calls into this SCC,
10 of which come from the parent SCC, leaving 655,360 from the two call sites
within \quicksortacc's SCC.
Using the formulas above we find that the AvgMaxDepth is
$\log_{2}(655,360/10 + 2) \approx 16$.
The total per-call cost of the call site to \partition reported by the profiler
is an estimated 35.5csc,
it is the only other goal in either the base case or recursive case with a
non-zero cost.
We wish to compute the costs of the recursive calls at the
15\textsuperscript{th} level so $D$ must be 14.
The cost of these calls is
$(2^{14} - 1)(35.5 + 2) + 2^{14}\times0 \approx 614,363$.
This is the average cost of both of the two recursive calls;
assuming that the list was partitioned evenly.
Since the deep profiler reports that the total per-call cost of the
\quicksortacc SCC is 1,229,106csc,
and the two recursive calls cost 614,363csc each (their sum is 1,228,726csc)
plus the cost of \partition (35.5csc) is approximately 1,228,762.
This is reasonably close to the total cost of \quicksortacc,
especially given other uncertainties.
There are two ways in which this calculation can be inaccurate.
First, poorly chosen pivot values create imbalanced call graphs.
We have already discussed how this can affect the calculation of the
recursion depth.
This can also affect the cost calculation in much the same way,
and the same rebuttals apply.
There is one extra concern,
a pivot that is not perfect will result in two sublists of different sizes
and therefore the recursive calls will have different costs rather than the
same cost we computed above.
It is normal to use \emph{parallel slackness} to reduce the impact of
imbalances.
This means creating slightly more finely grained parallelism than is
necessary in order to increase the chance that a processor can find parallel
work.
This works because on average the computed costs will be close enough to the
real costs.
The second cause of inaccurate results comes from our assumption about
\partition's cost.
We assumed that partition always has the same cost at every level of
the call graph.
However \partition's cost is directly proportional to the size of its input
list which is itself directly proportional to the depth in \quicksortacc's call
graph.
This would seem to affect our calculations of the cost of recursive calls
different levels within the call tree.
However the rate at which \partition's cost increases with height in the tree
is linear, while at the same time the number of calls to \partition grows at
a power of two with the tree's hight.
Therefore as the tree becomes larger the \emph{average} cost of calls to
\partition within it asymptotically approaches a constant number.
So in significantly large trees the varying costs of \partition do not
matter.
%
%In our example we are using lists of integers and integer comparison costs
%1csc.
%The cost of the call to \partition is one (for the call itself) plus two
%times the lenght of the list (for the integer comparison and for the next
%recursive call within \partition):
%
%\begin{equation*}
%part\_cost(L) = 2L + 1 \\
%\end{equation*}
%
%\noindent
%As we move from the leaves to the root of \quicksortacc's call tree,
%the length of the list is double plus one.
%The costs of the calls to \partition in a tree is double the cost of the
%call in one of the calls in a child plus the cost of the call in the root
%node.
%And the number of calls to \partition in a tree is double the number of calls in
%either of its subtrees plus one, which is also $2^D - 1$
%
%\paul{XXX: Can I turn the second equation into an exponential rather than a
%recursive function?}
%\[
%\begin{array}{l @{}l @{}l}
%length(D) ~&= 2(D - 1) \\
%total\_part\_cost(D) ~&= part\_cost(length(D)) +
% \begin{cases}
% 2total\_part\_cost(D - 1) & \text{if}~ D > 1 \\
% 0 & \text{if}~ otherwise \\
% \end{cases} \\
%num\_part\_calls(D) ~&= 2^D - 1 \\
%\end{array}
%\]
%
%\noindent
%As above,
%these are accruate only when \quicksortacc's call graph is a complete binary
%tree.
%But now we can calculate the average cost of the calls to partition in any
%subtree begining at depth $D$:
%
%\begin{equation*}
%avg\_part\_cost(D) = \frac{total\_part\_cost(D)}{num\_part\_calls(D)}
%\end{equation*}
%
%\paul{This seems to approach 2 as D approaches $\inf$.
%If I knew how to remove the recursive definition above I could prove this
%and show that in a big enough tree inaccuracies does not matter.
%Also the computed average cost is way different to the measured cost, which
%is probably due to imperfect pivots, this is more of an issue when computing
%the cost of the recursive calls.
%}
\begin{figure}
\begin{center}
\begin{tabular}{rlrr}
\C{Line} & \C{Code} & \C{Coverage} & \C{Cost} \\
& \code{p(X, Y, ...) :-}& 100\% & \\
& \code{~~~~(} & & \\
& \code{~~~~~~~~X = a,} & 60\% & 0 \\
& \code{~~~~~~~~q(...)} & 60\% & 1,000 \\
5 & \code{~~~~;} & & \\
& \code{~~~~~~~~X = b,} & 20\% & 0 \\
& \code{~~~~~~~~r(...)} & 20\% & 2,000 \\
& \code{~~~~;} & & \\
& \code{~~~~~~~~X = c,} & 20\% & 0 \\
10 & \code{~~~~~~~~p(...)} & 20\% & \\
& \code{~~~~),} & & \\
& \code{~~~~(} & & \\
& \code{~~~~~~~~Y = d,} & 90\% & 0 \\
& \code{~~~~~~~~s(...)} & 90\% & 10,000 \\
15 & \code{~~~~;} & & \\
& \code{~~~~~~~~Y = e,} & 10\% & 0 \\
& \code{~~~~~~~~p(...)} & 10\% & \\
& \code{~~~~).} & & \\
\end{tabular}
\end{center}
\caption{Two recursive calls and six code paths.}
\label{fig:2_reccalls_4_paths}
\end{figure}
\plan{How we classify recursion type}
We classify recursion types with an algorithm that walks over the structure
of a procedure.
As it traverses the procedure,
it counts the number of recursive calls along each path,
the path's cost, and the number of times the path is executed.
The number of times a path is executed is generated using coverage
profiling, which is described in the next section.
When the algorithm finds a branching structure like an if-then-else or
switch,
it processes each branch independently and then merges its
results at the end of the branch.
If several branches have the same number of recursive calls (including zero)
they can be merged.
If several branches have different numbers of recursive calls they are all
added to the result set.
This means that the result of traversing a goal might include data for
several different recursion counts.
Consider the example in Figure~\ref{fig:2_reccalls_4_paths}.
The example code has been annotated with coverage information (in the
third column) and with cost information where it is available (fourth
column).
The conjunction on lines three and four does not contain a recursive call.
The result of processing it is a list containing a single tuple:
\code{[(reccalls: 0, coverage: 60\%, cost: 1,000)]}.
The result for the second switch arm (lines six and seven) is:
\code{[(reccalls: 0, coverage: 20\%, cost: 2,000)]}.
The third conjunction in the same switch (lines nine and ten) contains
a recursive call.
The result of processing it is:
\code{[(reccalls: 1, coverage: 20\%, cost: 0)]}.
When the algorithm is finished processing all the cases in the switch it
adds them together.
When adding tuples, we can add tuples together with the same number of
recursive calls by adding their coverage and adding their costs weighted by
coverage (these are per-call costs).
This simplifies multiple code paths with the same number of recursive calls
into a single ``code path''.
The result of processing the switch from line 2--11 is:
\noindent
\begin{center}
\begin{tabular}{l}
\code{[(reccalls: 0, coverage: 80\%, cost: 1,250),} \\
\code{~(reccalls: 1, coverage: 20\%, cost: ~~~~0)]}. \\
\end{tabular}
\end{center}
\noindent
In this way, the result of processing a goal represents all the possible
code paths through that goal. In this case there are three code paths
through the switch,
and the result has two entries, one represents the two base case code paths,
the other represents the single recursive case.
The result of processing the other switch in the example,
lines 12--18, is:
\noindent
\begin{center}
\begin{tabular}{l}
\code{[(reccalls: 0, coverage: 90\%, cost: 10,000),} \\
\code{~(reccalls: 1, coverage: 10\%, cost: ~~~~~0)]}. \\
\end{tabular}
\end{center}
\noindent
In order to compute the result for the whole procedure, we must compute the
product of these two results;
this computes all the possible paths through the two switches.
We do this by constructing pairs of tuples from the two lists.
Since each list has two entries there are four pairs:
\noindent
\begin{center}
\begin{tabular}{rcl}
\code{[ (rc: 0, cvg: 80\%, cost: ~1,250)} &
$\times$&
\code{(rc: 0, cvg: 90\%, cost: 10,000),}
\\
\code{ ~(rc: 0, cvg: 80\%, cost: ~1,250)} &
$\times$&
\code{(rc: 1, cvg: 10\%, cost: ~~~~~0),}
\\
\code{ ~(rc: 1, cvg: 20\%, cost: ~~~~~0)} &
$\times$&
\code{(rc: 0, cvg: 90\%, cost: 10,000),}
\\
\code{ ~(rc: 1, cvg: 20\%, cost: ~~~~~0)} &
$\times$&
\code{(rc: 1, cvg: 10\%, cost: ~~~~~0)]}
\\
\end{tabular}
\end{center}
\noindent
For each pair we compute a new tuple by adding the number of recursive
calls, averaging the coverage counts, and adding the costs.
\noindent
\begin{center}
\begin{tabular}{l}
\code{[ (rc: 0, cvg: 72\%, cost: 11,250),} \\
\code{ ~(rc: 1, cvg: ~8\%, cost: ~1,250),} \\
\code{ ~(rc: 1, cvg: 18\%, cost: 10,000),} \\
\code{ ~(rc: 2, cvg: ~2\%, cost: ~~~~~0),} \\
\end{tabular}
\end{center}
\noindent
Again, we merge the cases with the same numbers of recursive calls.
\noindent
\begin{center}
\begin{tabular}{l}
\code{[ (rc: 0, cvg: 72\%, cost: 11,250),} \\
\code{ ~(rc: 1, cvg: 26\%, cost: ~7,308),} \\
\code{ ~(rc: 2, cvg: ~2\%, cost: ~~~~~0)]} \\
\end{tabular}
\end{center}
\noindent
There are six paths through this procedure,
and two recursive calls.
The number of tuples needed is linear in the number of path types;
in this case we represent all six paths using three tuples.
This allows us to conveniently handle procedures of different forms as
rather simple recursion types such as ``simple recursion'' we saw above:
a procedure with two recursive paths with one call each can be handled as
if it has just one recursive path and one base case.