Communication lower bounds and optimal algorithms for programs that reference arrays -- Part 1
Michael Christ, James Demmel, Nicholas Knight, Thomas Scanlon, Katherine Yelick
Introduction
Algorithms have two costs: computation (e.g., arithmetic) and communication, i.e., moving data between levels of a memory hierarchy or between processors over a network. Communication costs (measured in time or energy per operation) already greatly exceed computation costs, and the gap is growing over time following technological trends [FOSC, ComputerPerformanceNRC]. Thus it is important to design algorithms that minimize communication, and if possible attain communication lower bounds. In this work, we measure communication cost in terms of the number of words moved (a bandwidth cost), and will not discuss other factors like per-message latency, congestion, or costs associated with noncontiguous data. Our goal here is to establish new lower bounds on the communication cost of a much broader class of algorithms than possible before, and when possible describe how to attain these lower bounds.
Communication lower bounds have been a subject of research for a long time. Hong and Kung [hongkung] used an approach called pebbling to establish lower bounds for matrix multiplication and other algorithms. Irony, Tiskin and Toledo [ITT04] proved the result for matrix multiplication in a different, geometric way, and extended the results both to the parallel case and the case of using redundant copies of the data. In [BallardDemmelHoltzSchwartz11] this geometric approach was further generalized to include any algorithm that “geometrically resembled” matrix multiplication in a sense to be made clear later, but included most direct linear algebra algorithms (dense or sparse, sequential or parallel), and some graph algorithms as well. Of course lower bounds alone are not algorithms, so a great deal of additional work has gone into developing algorithms that attain these lower bounds, resulting in many faster algorithms as well as remaining open problems (we discuss attainability in Section LABEL:sec:attain).
Our geometric approach, following [ITT04, BallardDemmelHoltzSchwartz11], works as follows. We have a set of arithmetic operations to perform, and the amount of data available locally, i.e., without any communication, is words. For example, could be the cache size. Suppose we can upper bound the number of (useful) arithmetic operations that we can perform with just this data; call this bound . Letting denote the cardinality of a set, if the total number of arithmetic operations that we need to perform is (e.g., multiply-adds in the case of dense matrix multiplication on one processor), then we need to refill the cache at least times in order to perform all the operations. Since refilling the cache has a communication cost of moving words (e.g., writing at most words from cache back to slow memory, and reading at most new words into cache from slow memory), the total communication cost is words moved. This argument is formalized in Section 4.
The most challenging part of this argument is determining . Our approach, described in more detail in Sections 2–3, builds on the work in [ITT04, BallardDemmelHoltzSchwartz11]; in those papers, the algorithm is modeled geometrically using the iteration space of the loop nest, as sketched in the following example.
Our approach is based on a major generalization of [LW49] in [BCCT10] that lets us geometrically model a much larger class of algorithms with an arbitrary number of loops and array expressions involving affine functions of indices.
formalizes the argument that an upper bound on yields a lower bound on communication of the form . Some technical assumptions are required for this to work. Using the same approach as in [BallardDemmelHoltzSchwartz11], we need to eliminate the possibility that an algorithm could do an unbounded amount of work on a fixed amount of data without requiring any communication. We also describe how the bound applies to communication in a variety of computer architectures (sequential, parallel, heterogeneous, etc.).
summarizes our results, and outlines the contents of Part 2 of this paper. Part 2 will discuss how to compute lower bounds more efficiently and will include more cases where optimal algorithms are possible, including a discussion of loop dependencies.
This completes the outline of the paper. We note that it is possible to omit the detailed proofs in Sections 3 and 5 on a first reading; the rest of the paper is self-contained.
To conclude this introduction, we apply our theory to two examples (revisited later), and show how to derive communication-optimal sequential algorithms.
yielding the well-known blocked algorithm where the innermost three loops multiply –by– blocks of and and update a block of . We note that to have all three blocks fit in fast memory simultaneously, they would have to be slightly smaller than –by– by a constant factor. We will address this constant factor and others, which are important in practice, in Part 2 of this work (see Section LABEL:sec:conclusions).
Other examples appearing later include matrix-vector multiplication, tensor contractions, the direct –body algorithm, database join, and computing matrix powers .
Geometric Model
We begin by reviewing the geometric model of matrix multiplication introduced in [ITT04], describe how it was extended to more general linear algebra algorithms in [BallardDemmelHoltzSchwartz11], and finally show how to generalize it to the class of programs considered in this work.
We want a bound , where is any set of lattice points representing operations that can be performed just using data available in fast memory of size . Let , and be projections of onto faces of the cube representing all the required operands , and , resp., needed to perform the operations represented by . A special case of [LW49, Theorem 2] gives us the desired bound on :
Finally, since the entries represented by fit in fast memory by assumption (i.e., ), this yields the desired bound :
Irony et al. [ITT04] applied this approach to obtain a lower bound for matrix multiplication. Ballard et al. [BallardDemmelHoltzSchwartz11] extended this approach to programs of the form
and picked the iteration space , arrays , and binary operations and to represent many (dense or sparse) linear algebra algorithms. To make this generalization, Ballard et al. made several observations, which also apply to our case, below.
An instance of the geometric model is an abstract representation of an algorithm, taking the form
(We will be more concrete about what it means to ‘access a variable’ when we introduce our execution model in Section 4.)
Assuming that all variables are accessed in each iteration rules out certain optimizations, or requires us not to count certain inner loop iterations in our lower bound. For example, consider Boolean matrix multiplication, where the inner loop body is . As long as is false, does not need to be accessed. So we need either to exclude such optimizations, or not count such loop iterations. And once is true, its value cannot change, and no more values of and need to be accessed; if this optimization is performed, then these loop iterations would not occur and not be counted in the lower bound. In general, if there are data-dependent branches in the inner loop (e.g., ‘flip a coin…’), we may not know to which subset of all the loop iterations our model applies until the code has executed. We refer to a later example (database join) and [BallardDemmelHoltzSchwartz11, Section 3.2.1] for more examples and discussion of this assumption.
Following the approach for matrix multiplication, we need to bound where is a nonempty finite subset of . To execute , we need array entries . Analogous to the analysis of matrix multiplication, we need to bound in terms of the number of array entries needed: entries of , for .
Suppose there were nonnegative constants such that for any such ,
i.e., a generalization of Theorem 2.1. Then just as with matrix multiplication, if the number of entries of each array were bounded by , we could bound
The next section shows how to determine the constants such that inequality (2.3) holds. To give some rough intuition for the result, consider again the special case of Theorem 2.1, where can be interpreted as a volume, and each as an area. Thus one can think of as having units of, say, , and as having units of . Thus, for to have units of , we would expect the to satisfy . But if were a lower dimensional subset, lying say in a plane, then would have units and we would get a different constraint on the . This intuition is formalized in Theorem 3.2 below.
Upper bounds from HBL theory
As discussed above, we aim to establish an upper bound of the form (2.3) for , for any finite set of loop iterations. In this section we formulate and prove Theorem 3.2, which states that such a bound is valid if and only if the exponents satisfy a certain finite set of linear constraints, specified in (3.1) below.
The following theorem provides bounds which are fundamental to our application.
Conversely, if (3.2) holds for , then satisfies (3.1).
Note that if satisfies (3.1) or (3.2), then any where each does too. This is obvious for (3.1); in the case of (3.2), since is nonempty and finite, then for each , , so .
The following result demonstrates there is no loss of generality restricting , rather than in , in Theorem 3.2.
Whenever (3.1) or (3.2) holds for some , it holds for where for .
2 Generalizations
We will use the terminology HBL datum to refer to either of two types of structures; the first is defined as follows:
An Abelian group HBL datum is a –tuple
where and each are finitely generated Abelian groups, is torsion-free, each is a group homomorphism, and the notation on the left-hand side always implies that .
Consider an Abelian group HBL datum and . Suppose that
Conversely, if (3.5) holds for , then satisfies (3.8).
[BCCT10, Theorem 2.4] treats the more general situation in which is not required to be torsion-free, and establishes the conclusion (3.4) in the weaker form
where the constant depends only on and . The constant established here is optimal. Indeed, consider any single , and for each define to be , the indicator function for . Then both sides of the inequalities in (3.4) are equal to . In Remark 3.11, we will show that the constant is bounded above by the number of torsion elements of .
Necessity of (3.3) follows from an argument given in [BCCT10, Theorem 2.4].
On the other hand, for ,
where is a finite constant which depends on , on the structure of , and on the choice of , but not on . Indeed, it follows from the definition of rank that for each it is possible to permute the indices so that for each there exist integers and such that
The upper bound (3.7) follows from these relations.
where is independent of . By letting tend to infinity, we conclude that , as was to be shown. ∎
We show sufficiency in Theorem 3.6 in its full generality is a consequence of the special case in which all of the groups are torsion-free.
We are assuming validity of Theorem 3.6 in the torsion-free case. Its conclusion asserts that
Combining these inequalities gives the conclusion of Theorem 3.6. ∎
Our second generalization of Theorem 3.2 is as follows.
Consider a vector space HBL datum and . Suppose that
Thus the conclusion (3.4) of Theorem 3.6 is satisfied. ∎
Consider , an HBL datum with torsion, and . If (3.3) holds, then (3.6) holds with . In particular,
Conversely, if (3.11) holds for , then satisfies (3.3).
The first inequality is an application of Theorem 3.6. Summation with respect to gives the required bound.
The factor cannot be improved if the groups are torsion free, or more generally if is contained in the intersection of the kernels of all the homomorphisms ; this is seen by considering .
3 The polytope 𝒫𝒫\mathcal{P}
The constraints (3.3) and (3.8) are encoded by convex polytopes in .
For any Abelian group HBL datum , we denote the set of all which satisfy (3.3) by . For any vector space HBL datum , we denote the set of all which satisfy (3.8) by .
In the course of proving Theorem 3.6 above, we established the following result.
Now we prove Proposition 3.3, i.e., that there was no loss of generality in assuming each .
Proposition 3.3 concerns the case of Theorem 3.2, but in the course of its proof we will show that this result also applies to Theorems 3.6 and 3.10.
We first show the result concerning (3.1), by considering instead the set of inequalities (3.8). Suppose that a vector space HBL datum and satisfy (3.8), and suppose that for some . Define by for , and . Pick any subspace ; let and let be a supplement of in , i.e., and . Since ,
since satisfies (3.8) and , by (3.8) applied to ,
Next, we show the result concerning (3.2). Consider the following more general situation. Let be sets and be functions for . Let with some , and suppose that for any finite nonempty subset . Fix one such set . For each , let , the preimage of under \phi_{k}\big{|}_{E}; thus . By assumption, , so it follows that
Since can be written as the union of disjoint sets , we obtain
We claim that this result can be generalized to and , based on a comment in [BCCT10, Section 8] that it generalizes in the weaker case of (3.6). ∎
To prove Theorem 3.10, we show in Section 3.4 that if (3.9) holds at each extreme point of , then it holds for all . Then in Section 3.5, we show that when is an extreme point of , the hypothesis (3.8) can be restated in a special form. Finally in Section 3.7 we prove Theorem 3.10 (with restated hypothesis) when is any extreme point of , thus proving the theorem for all .
4 Interpolation between extreme points of 𝒫𝒫\mathcal{P}
One multilinear extension of the Riesz-Thörin theorem states the following (see, e.g., [bennettsharpley]).
Suppose that . Suppose that there exist such that
For each define exponents by
Here .
In the context of Theorem 3.10 with vector space HBL datum , we consider the multilinear map
representing the left-hand side in (3.9).
If (3.9) holds for every extreme point of , then it holds for every .
5 Critical subspaces and extreme points
Assume a fixed vector space HBL datum , and let continue to denote the set of all which satisfy (3.8).
Consider any . A subspace satisfying is said to be a critical subspace; one satisfying is said to be subcritical; and a subspace satisfying is said to be supercritical. is said to be strictly subcritical if .
In this language, the conditions (3.8) assert that that every subspace of , including and itself, is subcritical; equivalently, there are no supercritical subspaces. When more than one –tuple is under discussion, we sometimes say that is critical, subcritical, supercritical or strictly subcritical with respect to .
The goal of Section 3.5 is to establish the following:
Let be an extreme point of . Then some subspace is critical with respect to , or .
Note that these two possibilities are not mutually exclusive.
If is an extreme point of , and if is an index for which , then .
Suppose . If satisfies for all , then for all subspaces , so as well. If , then this contradicts the assumption that is an extreme point of . ∎
Let be an extreme point of . Suppose that no subspace is critical with respect to . Then .
Suppose to the contrary that for some index , . If satisfies for all and if is sufficiently close to , then . This again contradicts the assumption that is an extreme point. ∎
Let be an extreme point of . Suppose that there exists no subspace which is critical with respect to . Then there exists at most one index for which .
Whenever is sufficiently small, . Moreover, remains subcritical with respect to . If is sufficiently small, then every subspace remains strictly subcritical with respect to , because the set of all parameters which arise, is finite. Thus for all sufficiently small . Therefore is not an extreme point of . ∎
Let . Suppose that is critical with respect to . Suppose that there exists exactly one index for which . Then has a subspace which is supercritical with respect to .
By Lemma 3.19, . Let be the set of all indices for which . The hypothesis that is critical means that
Since and ,
Consider the subspace defined by
this intersection is interpreted to be if the index set is empty. necessarily has positive dimension. Indeed, is the kernel of the map , defined by , where denotes the direct sum of vector spaces. The image of is isomorphic to some subspace of , a vector space whose dimension is strictly less than . Therefore has dimension greater than or equal to . Since for all ,
Since and , is strictly less than , whence is supercritical. ∎
Suppose that there exists no critical subspace . By Lemma 3.20, either — in which case the proof is complete — or is critical. By Lemma 3.21, there can be at most one index for which . By Lemma 3.22, for critical , the existence of one single such index implies the presence of some supercritical subspace, contradicting the main hypothesis of Proposition 3.18. Thus again, . ∎
6 Factorization of HBL data
Let be a vector space HBL datum. To any subspace can be associated two HBL data:
Given the vector space HBL datum , for any subspace ,
Consider any subspace and some such that both s\in\mathcal{P}({W,({V_{j}}),({\phi_{j}\big{|}_{W}})}) and . Then
The last inequality is a consequence of the inclusions . The last equality is the relation , which holds for any subspaces of a vector space. Thus is subcritical. ∎
Given the vector space HBL datum , let . Let be a subspace which is critical with respect to . Then
With Lemma 3.24 in hand, it remains to show that is contained in the intersection of the other two polytopes.
Any subspace is also a subspace of . is subcritical with respect to when regarded as a subspace of , if and only if is subcritical when regarded as a subspace of . So s\in\mathcal{P}({W,({V_{j}}),({\phi_{j}\big{|}_{W}})}).
Now consider any subspace of ; we have and . Moreover,
Therefore since ,
by the subcriticality of , which holds because . Thus any is subcritical with respect to , so as well. ∎
7 Proof of Theorem 3.10
Recall we are given the vector space HBL datum ; we prove Theorem 3.10 by induction on the dimension of the ambient vector space . If then has a single element, and the result (3.9) is trivial.
To establish the inductive step, consider any extreme point of . According to Proposition 3.18, there are two cases which must be analyzed. We begin with the case in which there exists a critical subspace , which we prove in the following lemma. We assume that Theorem 3.10 holds for all HBL data for which the ambient vector space has strictly smaller dimension than is the case for the given datum.
Let be a vector space HBL datum, and let . Suppose that subspace is critical with respect to . Then (3.9) holds for this .
Consider any inequality in (3.9). We may assume that none of the exponents equal zero. For if , then for all , and therefore
If , then (3.9) holds with both sides . Otherwise we divide by to conclude that if and only if belongs to the polytope associated to the HBL datum . Thus the index can be eliminated. This reduction can be repeated to remove all indices which equal zero.
Let . By Lemma 3.25, s\in\mathcal{P}({W,({W_{j}}),({\phi_{j}\big{|}_{W}})}). Therefore by the inductive hypothesis, one of the inequalities in (3.9) is
Define to be the function
This quantity is a function of the coset alone, rather than of itself, because for any ,
by virtue of the substitution . Moreover,
To prove this, choose one element for each coset . Denoting by the set of all these representatives,
because the map is a bijection.
The inductive bound (3.14) can be equivalently written in the more general form
for any , by applying (3.14) to where .
Denote by a set of representatives of the cosets , and identify with . Then
This is a set of inequalities of exactly the form (3.9), with replaced by . By Lemma 3.25, , and since , we conclude directly from the inductive hypothesis that (3.17) holds, concluding the proof of Lemma 3.26. ∎
According to Proposition 3.18, in order to complete the proof of Theorem 3.10, it remains only to analyze the case where the extreme point . Let . Consider . Since is subcritical by hypothesis,
so , that is, . Therefore the map from to the Cartesian product is injective.
since for all . Thus it suffices to prove that
This is a special case of the following result.
Define by . The hypothesis is equivalent to being injective. The product can be expanded as the sum of products
where the sum is taken over all belonging to the Cartesian product . The quantity of interest,
is likewise a sum of such products. Each term of the latter sum appears as a term of the former sum, and by virtue of the injectivity of , appears only once. Since all summands are nonnegative, the former sum is greater than or equal to the latter. Therefore
Having shown sufficiency for extreme points of , we apply Lemma 3.16 to conclude sufficiency for all .
Communication lower bounds from Theorem 3.2
In addition to the concrete execution model and the geometric model, we use pseudocode in our examples. At a high level, these three different algorithm representations are related as follows:
A concrete execution is a sequence of instructions executed by the machine, according to the model detailed in Section 4.1. The concrete execution, unlike either the geometric model or pseudocode, contains explicit data movement operations between slow and fast memory.
The geometric model (Definition 2.2), is the most abstract, and is the foundation of the bounds in Section 3. Each instance (2.2) of the geometric model corresponds to a set of concrete executions, as detailed in Section 4.2.
The rest of this section is organized as follows. Section 4.1 describes the concrete execution model mentioned above, and Section 4.2 relates the concrete execution model to the geometric model. Section 4.3 states and proves the main communication lower bound result of this paper, Theorem 4.1. Section 4.4 presents a number of examples showing why the assumptions of Theorem 4.1 are in fact necessary to obtain a lower bound. Section 4.5 looks at one of these assumptions in more detail (“no loop splitting”), and shows that loop splitting can only improve (reduce) the lower bound. Finally, Section 4.6 discusses generalizations of the lower bound result to other machine models.
The hypothetical machine in our execution model has a two-level memory hierarchy: a slow memory of unbounded capacity and a fast memory that can store words (all data in our model have one-word width). Data movement between slow and fast memory is explicitly managed by software instructions (unlike a hardware cache), and data is copiedWe will use the word ‘copied’ but our analysis does not require that a copy remains, e.g., exclusive caches. at a one-word granularity (we will discuss spatial locality in Part 2 of this work). Every storage location in slow and fast memory (including the array elements ) has a unique memory address, called a variable; since the slow and fast memory address spaces (variable sets) are disjoint, we will distinguish between slow memory variables and fast memory variables. When a fast memory variable represents a copy of a slow memory variable , we refer to as a cached slow memory variable; in this case, we assume we can always identify the corresponding fast memory variable given , even if the copy is relocated to another fast memory location.
We define a sequential execution as a sequence of statements of the following types:
: allocates a location in fast memory and copies variable from slow to fast memory.
: copies variable from fast to slow memory and deallocates the location in fast memory.
is a statement accessing variables .
introduces variable in fast memory.
removes variable from fast memory.
A sequential execution defines a total order on the statements, and thereby a natural notion of when one statement succeeds or precedes another. We say that a Read or Allocate statement and a subsequent Write or Free statement are paired if the same variable appears as an operand in both and there are no intervening Reads, Allocates, Writes, or Frees of . A sequential execution is considered to be well formed if and only if
operands to Read (resp., Write) statements are uncached (resp., cached) slow memory variables,
operands to Allocate statements are uncached slow memory variables or fast memory variablesIf a fast memory variable in an statement already stores a cached slow memory variable, then we assume the system will first relocate the cached variable to an available location within fast memory),
operands to Free statements are cached slow memory variables or fast memory variables,
every Read, Allocate, Write, and Free statement is paired, and
every Compute statement involving variable interposes between paired Read/Allocate and Write/Free statements of , i.e., each operand in a Compute statements resides in fast memory before and after the statement.
Essentially, fast memory variables must be allocated and deallocated, either implicitly (Read/Write) or explicitly (Allocate/Free), while slow memory variables cannot be allocated/deallocated. Given the finite capacity of fast memory, we need an additional assumption to ensure the memory operations are well-defined. Given a well-formed sequential execution , we define to be the fast memory usage after executing statement in the program, i.e.,
Then is said to be –fit (for fast memory size ) if .
It is of practical interest to permit variables to reside in fast memory before and after the execution, e.g., to handle parallel code as described in the next paragraph; however, this violates our notion of well-formedness. Rather than redefine well-formedness to account for this possibility, we take a simpler approach: given an execution that is well formed except for the (‘input’) and (‘output’) variables which reside in fast memory before and after the execution, we insert up to Reads and Writes at the beginning and end of the execution so that all memory statements are paired, and then later reduce the lower bound (on Reads/Writes) by .
Although we will establish our bounds first for a sequential execution, they also apply to parallel executions as explained in Section 4.6. We define a parallel execution as a set of sequential executions, . In our parallel model, the global (‘slow’) memory for each processor is a subset of the union of the local (‘fast’) memories of the other processors. That is, for a given processor, each of its slow memory variables is really a fast memory variable for some other processor, and each of its fast memory variables is a slow memory variable for every other processor, unless it corresponds to a cached slow memory variable, in which case it is invisible to the other processors. (We could remove this last assumption by extending our model to distinguish between copies of a slow memory variable.) A parallel execution is well formed or (additionally) –fit if each of its serial executions is well formed or (additionally) –fit. Since well-formedness assumes no variables begin and end execution in fast/local memory, it seems impossible for there to be any nontrivial well-formed parallel execution. As mentioned above, we can always allow for a sequential execution with this property by inserting up to Reads/Writes, and later reducing the lower bound by this amount; we insert Reads/Writes in this manner to each sequential execution in a parallel execution.
2 Relation to the geometric model
Recall from Section 2 our geometric model (2.2):
Given an execution, we assume we can discern the expression from any variable which represents an array variable in the geometric model. The execution may contain additional variables that act as surrogates (or copies) of the variables specified in the program text. As an extreme example, an execution could use an array as a surrogate for the array in the computations, and then later set to . In such examples, one can always associate each surrogate variable with the ‘master’ copy, and there is no loss of generality in our analysis to assume all variables are in fact the master copies.
We say a legal sequential execution of an instance of the geometric model is a sequential execution whose subsequence of Compute statements can be partitioned into contiguous chunks in one-to-one correspondence with , and furthermore all array variables appear as operands in the chunk corresponding to . Given a possibly overlapping partition , a legal parallel execution is a parallel execution where each sequential execution is legal with respect to loop iterations . Legality restricts the set of possible concrete executions we consider (for a given instance of the geometric model), and in general is a necessary requirement for the lower bound to hold for all concrete executions. For example, transforming the classical algorithm for matrix multiplication into Strassen’s algorithm (which can move asymptotically less data) is illegal, since it exploits the distributive property to interleave computations, and any resulting execution cannot be partitioned contiguously according to the original iteration space . As another example, legality prevents loop splitting, an optimization which can invalidate the lower bound as discussed in Section 4.5.
We note that there are no assumptions about preserving dependencies in the original program or necessarily computing the correct answer. Restricting the set of executions further to ones that are correct may make the lower bound unattainable, but does not invalidate the bound.
3 Derivation of Communication Lower Bound
Now we present the more formal derivation of the communication lower bound, which was sketched in Section 2. The approach used here was introduced in [ITT04] and generalized in [BallardDemmelHoltzSchwartz11]. Here we generalize it again to deal with the more complicated algorithms considered in this paper.
Given an –fit legal sequential execution , we proceed as follows:
Break into –Read/Write segments of consecutive statements, where each segment (except possibly the last one) contains exactly Reads and/or Writes. Each segment (except the last) ends with the Read/Write and the next segment starts with whatever statement follows. The last segment may have statements other than Reads/Writes at the end to complete the execution. (We will simply refer to these as Read/Write segments when is clear from context.)
Independently, break into Compute segments of consecutive statements so that the Compute statements within a segment correspond to the same iteration . (It will not matter that this does not uniquely define the first and last statements of a Compute segment.) Our assumption of a legal execution guarantees that there is one Compute segment per iteration . We associate each Compute segment with the (unique) Read/Write segment that contains the Compute segment’s first Compute statement.
Using the limited availability of data in any one Read/Write segment, we will use Theorem 3.2 to establish an upper bound on the number of complete Compute segments that can be executed during one Read/Write segment (see below). This is an upper bound on the number of complete loop iterations that can be executed.
Now, we can bound below the number of complete Read/Write segments by . We add to to account for Compute segments that overlap two (or more) Read/Write segments. We need the floor function because the last Read/Write segment may not contain Reads/Writes. (Since we are doing asymptotic analysis, can often be replaced by the total number of Compute statements.)
Finally we bound below the total number of Reads/Writes by the lower bound on the number of complete Read/Write segments times the number of Reads/Writes per such segment, minus the number of Reads/Writes we inserted to account for variables residing in fast memory before/after the execution:
where we have applied our asymptotic assumption .
To determine an upper bound , we will use Theorem 3.2 to bound the amount of (useful) computation that can be done given only array variables. First, we discuss how to ensure that only a fixed number of array variables is available during a single Read/Write segment.
Given an –fit legal sequential execution, consider any –Read/Write segment. There are at most array variables in fast memory when the segment starts, at most array variables are read/written during the segment, and at most array variables remain in fast memory when the segment ends. If there are no Allocates of array variables, or if there are no Frees of array variables, then at most distinct array variables appear in the segment (at most may already reside in fast memory, and at most more can be read or allocated). More generally, if there are no paired Allocate/Free statements of array variables, then at most array variables appear in the segment (at most already reside in fast memory, at most can be read, and at most can be allocated). However, if we allow array variables to be allocated and subsequently freed, then it is possible to have an unbounded number of array variables contributing to computation in the same segment; this can occur in practice and we give concrete examples in the following section. Thus, we need an additional assumption in order to obtain a lower bound that is valid for all executions.
We will assume that the execution contains no paired Allocate/Free statements of array variables. However, we note that of these paired statements, we only need to avoid the ones where both statements occur within a given Read/Write segment; e.g., one could remove the preceding assumption by proving that at least Read/Write statements (of variables besides ) interpose every paired Allocate/Free of an array variable . (This weaker assumption is equivalent to an assumption in [BallardDemmelHoltzSchwartz11, Section 2] that there are no ‘R2/D2 operands.’)
The communication lower bound is now a straightforward application of Theorem 3.2.
When , i.e., the problem (iteration space) is not sufficiently large, the lower bound becomes , so the subtractive term may dominate and lead to zero communication; this is increasingly likely as the ratio goes to zero. The parallel case also demonstrates this behavior in the ‘strong scaling’ limit, when the problem is decomposed to the point that each processor’s working set fits in their local memory (see Section 4.6). In the regime , a memory-independent lower bound [BDHLS12] provides more insight than the bound above. Let be the (unknown) number of Reads/Writes performed, and let and be the numbers of input/output variables residing in fast memory before/after execution. Then
4 Examples
We give four examples to demonstrate why our assumptions in Theorem 4.1 are necessary. Then, we discuss how one can sometimes deal with the presence of imperfectly nested loops, paired Allocate/Free statements, and an infeasible linear program to compute a useful lower bound; we give an example of this approach.
The following simple modification of matrix multiplication demonstrates how paired Allocate/Frees can invalidate our lower bound.
Suppose we know the arrays do not alias each other. Clearly only depends on the data when , but we need to do all multiplications to compute correctly. But the same analysis from Section 3 applies to these loops as to matrix multiplication, suggesting a sequential communication lower bound of . However, it is clearly possible to execute all iterations moving only words, by hoisting the (unblocked) loop outside and blocking the and loops by , doing multiplications in a Read/Write segment using entries each of and , and (over)writing the values to a single location in fast memory, which is repeatedly Allocated and Freed. Only when would actually be written to slow memory. So in this case there are a total of paired Allocates/Frees, corresponding to the overwritten operands.
This example also demonstrates how paired Allocate/Frees can invalidate our lower bound. Consider the following code:
Again, suppose we know that the arrays do not alias each other. Toward a lower bound, we ignore the initialization of (first loop nest) and only look at the second loop nest, a matrix multiplication. However, by computing entries of on-the-fly from and discarding them (i.e., Allocating/Freeing them), one can beat the lower bound of words for matrix multiplication. That is, by hoisting the (unblocked) loop outside and blocking the and loops by , and finally writing each to slow memory when , we can instead move words. So, there are possible paired Allocate/Frees.
This example demonstrates how infeasibility of the linear constraints (3.1) of Theorem 3.2 can invalidate our lower bound. Consider the following code:
While infeasibility may be sufficient for there to be an unbounded number of array variables in a Read/Write segment, the previous two examples show that it is not necessary, since their linear programs are feasible. We will be more concrete about this relationship between infeasibility and unbounded data reuse in Part 2.
This example demonstrates how an execution which interleaves the inner loop bodies (an illegal execution) can invalidate our lower bound; see also Section 4.5. We will see in Section 4.5 that the lower bound for each split loop is no larger than the lower bound for the original loop. Consider splitting the two lines of the inner loop body in the Complicated Code example (see Section 1) into two disjoint loop nests (each over ). We assume and do not modify their arguments, and that the arrays do not alias — the two lines share only read accesses to one array, , so correctness is preserved. As will be seen later by using Theorem LABEL:thm6.1, the resulting two loop nests have lower bounds and , resp., both better than the of the original, and both these lower bounds are attainable.
Theorem 4.1 is enough for many direct linear algebra computations such as (dense or sparse) decomposition, which do not have paired Allocate/Frees, but not all algorithms for the decomposition or eigenvalue problems, which can potentially have large numbers of paired Allocates/Frees (see [BallardDemmelHoltzSchwartz11]). We can often deal with interleaving iterations, paired Allocates/Frees, and infeasibility of (3.1) by imposing Reads and Writes [BallardDemmelHoltzSchwartz11, Section 3.4]: we modify the algorithm to add (“impose”) Reads and Writes of array variables which are allocated/freed or repeatedly overwritten, apply the lower bound from Theorem 4.1, and then subtract the number of imposed Reads and Writes to get the final lower bound. (Note that we have already used a similar technique, above, to allow an execution to begin/end with a nonzero fast memory footprint.) We give an example of this approach (see also [BallardDemmelHoltzSchwartz11, Corollary 5.1]).
Consider computing using the following code, shown (for simplicity) for odd and initially :
This example also illustrates that our results will only be of interest for sufficiently large problems, certainly where the floor function in the lower bound (4.1) is at least .
The above approach covers many but not all algorithms of interest. We refer to reader to [BallardDemmelHoltzSchwartz11, Sections 3.4 and 5] for more examples of imposing Reads and Writes, and [BallardDemmelHoltzSchwartz11, Section 4] on orthogonal matrix factorizations for an important class of algorithms where a subtler analysis is required to deal with paired Allocates/Frees.
Imposing Reads and Writes may fundamentally alter the program, so the lower bound obtained for the modified code need not apply to the original code. In the example above, one could reorderFor simplicity, and without reducing data movement, this code performs additional operations. the original code to
5 Loop Splitting Can Only Help
Here we show that loop splitting can only reduce (improve) the communication lower bound expressed in Theorem 4.1. More formally, we state this as the following.
While loop splitting appears to always be worth attempting, in practice data dependencies limit our ability to perform this optimization; we will discuss the practical aspects of loop splitting further in Part 2 of this work.
6 Generalizing the machine model
Earlier we said the reader could think of a sequential algorithm where the fast memory consists of a cache of words, and slow memory is the main memory. In fact, the result can be extended to the following situations:
If a sequential machine has a memory hierarchy, i.e., multiple levels of cache (most do), where data may only move between adjacent levels, and arithmetic done only on the “top” level, then it is of interest to bound the data transferred between every pair of adjacent levels, say and , where is higher (faster and closer to the arithmetic unit) than . In this case we apply our model with representing the total memory available in levels 1 through , typically an increasing function of .
One may also ask what value of to use for each processor. Suppose that each processor has words of fast memory, and that the total problem size of all the array entries accessed is . So if each processor gets an equal share of the data we use . But the lower bound may still apply, and be smaller, if is larger than (but at most ). In some cases algorithms are known that attain these smaller lower bounds (e.g., matrix multiplication in [2.5D_EuroPar]), i.e., replicating data can reduce communication.
In Section 7.3, we discuss attainability of these parallel lower bounds, and reducing communication by replicating data.
The simplest possible hierarchical machine is the sequential one with multiple levels of memory discussed above. But real parallel machines are similar: each processor has its own memory organized in a hierarchy. So just as we applied our lower bound to measure memory traffic between levels and of cache on a sequential machine, we can similarly analyze the memory hierarchy on each processor in a parallel machine.
Finally, people are building heterogeneous parallel machines, where the various processors, memories, and interconnects can have different speeds or sizes. Since minimizing the total running time means minimizing the time when the last processor finishes, it may no longer make sense to assign an equal fraction of the work and equal subset of memory to each processor. Since our lower bounds apply to each processor independently, they can be used to formulate an optimization problem that will give the optimal amount of work to assign to each processor [Hetero_SPAA11].
(Un)decidability of the communication lower bound
In Section 3, we proved Theorem 3.2, which tells us that the exponents satisfy the inequalities (3.1), i.e.,
The proof of Theorem 5.1 is built upon several smaller results.
Generate a list of all nonempty subsets of having at most elements. Test each subset for linear independence, and discard all which fail to be independent. Output a list of those which remain. ∎
We do not require this list to be free of redundancies.
To the given family of inequalities, adjoin the inequalities and . is the convex polytope defined by all inequalities in the resulting enlarged family. Express these inequalities as for all , where is a finite nonempty index set.
Create a list of all subsets with cardinality equal to . There are finitely many such sets, since itself is finite. Delete each one for which is not linearly independent. For each subset not deleted, compute the unique solution of the system of equations for all . Include in the list of all extreme points, if and only if satisfies for all . ∎
There exists an algorithm which takes as input a vector space HBL datum , an element , and a subspace which is critical with respect to , and determines whether .
Theorem 5.1 and Proposition 5.5 will be proved inductively in tandem, according to the following induction scheme. The proof of Theorem 5.1 for HBL data in which has dimension , will rely on Proposition 5.5 for HBL data in which has dimension . The proof of Proposition 5.5 for HBL data in which has dimension and there are subspaces , will rely on Proposition 5.5 for HBL data in which has dimension strictly less than , on Theorem 5.1 for HBL data in which has dimension strictly less than , and also on Theorem 5.1 for HBL data in which has dimension and the number of subspaces is strictly less than . Thus there is no circularity in the reasoning.
Let and be given. Following Notation 3.23, consider the two HBL data ({W,({\phi_{j}(W)}),({\phi_{j}\big{|}_{W}})}) and , where are the quotient maps. From a basis for , bases for , a basis for , and corresponding matrix representations of , it is possible to compute the dimensions of, and bases for, and , via row operations on matrices. According to Lemma 3.25, if and only if t\in\mathcal{P}({W,({\phi_{j}(W)}),({\phi_{j}\big{|}_{W}})})\cap\mathcal{P}({V/W,({V_{j}/\phi_{j}(W)}),({[\phi_{j}]})}).
Because , both have dimensions strictly less than the dimension of . Therefore by Theorem 5.1 and the induction scheme, there exists an algorithm which computes both a finite list of inequalities characterizing \mathcal{P}({W,({\phi_{j}(W)}),({\phi_{j}\big{|}_{W}})}), and a finite list of inequalities characterizing . Testing each of these inequalities on determines whether belongs to these two polytopes, hence whether belongs to . ∎
Let HBL datum be given. Let . Let and suppose that . Let be the nullspace of . Define to be with the coordinate deleted. Then if and only if \widehat{s}\in\mathcal{P}({V^{\prime},({V_{j}})_{j\neq i},({\phi_{j}\big{|}_{V^{\prime}}})_{j\neq i}}).
For any subspace , since ,
So if then \widehat{s}\in\mathcal{P}({V^{\prime},({V_{j}})_{j\neq i},({\phi_{j}\big{|}_{V^{\prime}}})_{j\neq i}}).
Conversely, suppose that \widehat{s}\in\mathcal{P}({V^{\prime},({V_{j}})_{j\neq i},({\phi_{j}\big{|}_{V^{\prime}}})_{j\neq i}}). Let be any subspace of . Write where the subspace is a supplement to in , so that . Then
because is injective on . So . ∎
To prepare for the proof of Theorem 5.1, let be given. Let be the list of subspaces of produced by the algorithm of Lemma 5.3. Let . To each index is associated a linear inequality for elements , which we encode by an –tuple ; the inequality is . Define to be the polytope defined by this set of inequalities.
Moreover, there exists a positive integer such that for all .
The inclusion holds for every , because the set of inequalities defining is a subset of the set defining .
is specified by some finite set of inequalities, each specified by some subspace of . Choose one such subspace for each of these inequalities. Since is a list of all subspaces of , there exists such that each of these chosen subspaces belongs to . ∎
Let . If is an extreme point of , then either for some , or there exists for which is critical with respect to and .
For any extreme point , equality must hold in at least genuinely distinct inequalities among those defining . These inequalities are of three kinds: for , , and , with . If then specifies the tautologous inequality , so that index can be disregarded.
If none of the coordinates are equal to or , there must exist such that equality holds in at least two distinct inequalities associated to subspaces among those which are used to define . We have already discarded the subspace , so there must exist such that and specify distinct inequalities. Thus . ∎
Suppose that . Let be given. Let . Recursively apply the following procedure.
Replace by . Consider . Apply Lemma 5.4 to obtain a list of all extreme points of , and for each such which belongs to , a nonzero proper subspace which is critical with respect to .
Examine each of these extreme points , to determine whether . There are three cases. Firstly, if , then Proposition 5.5 may be invoked, using the critical subspace , to determine whether .
Secondly, if some component of equals , let be the nullspace of . Set
According to Lemma 5.6, if and only if . This polytope can be computed by the induction hypothesis, since the number of indices has been reduced by one.
Finally, if some component of equals , then because the term contributes nothing to sums , if and only if belongs to . To determine whether belongs to this polytope requires again only an application of the induction hypothesis.
If every extreme point of belongs to , then because is the convex hull of its extreme points, . The converse inclusion holds for every , so in this case . The algorithm halts, and returns the conclusion that , along with information already computed: a list of the inequalities specified by all the subspaces , and a list of extreme points of .
On the other hand, if at least one extreme point of fails to belong to , then . Then increment by one, and repeat the above steps.
Lemma 5.7 guarantees that this procedure will halt after finitely many steps. ∎
2 On Computation of the Constraints Defining 𝒫𝒫\mathcal{P}
There exists an effective algorithm for computing the set of constraints (3.1) defining if and only if there exists an effective algorithm to decide whether a system of polynomial equations with rational coefficients has a rational solution.
For a natural number and ring , we write to denote the ring of –by– matrices with entries from . (Note that elsewhere in this work we also use the notation to denote the set of –by– matrices with entries from .) We identify with the endomorphism ring of the –module and thus may write elements of as –linear maps rather than as matrices. Via the usual coordinates, we may identify with . We write to denote the ring of polynomials over in variables .
With the next lemma, we use a standard trick of replacing composite terms with single applications of the basic operations to put a general Diophantine set in a standard form (see, e.g., [Vak]).
for , and .
Let be the set containing and the polynomials for which .
For the remainder of this argument, we call a set enjoying the properties identified for (namely that each polynomial is either affine or of the form ) a basic set.
and the polynomials expressing multiplicative relations in as
Note that by scaling, we may assume that all of the coefficients are integers.
The map is constant taking the value .
The map is constant taking the value .
The map is constant taking the value .
The map is constant taking the value .
The map (for ) is constant taking the value .
The map (for ) is constant taking the value .
The map (for ) takes (written in lowest terms) to the linear map .
Visibly, .
For we have , the general element of has the form so we have that .
For , the general element of has the form . That is, .
The following is an implementation of row reduction. Let the elements and be a basis for . Since , at the cost of reversing and and multiplying by a scalar, we may assume that . Since , we may find a scalar for which . Set . Write . Since is linearly independent from and , we see that there is some scalar for which . Set . Using the fact that we see that . Set . ∎
For we have .
The image of under is where in lowest terms. Since , we have . That is, . ∎
For any , we have .
Recall in Section 5.2, we hoped to answer the following (possibly undecidable) question.
If such an exists, we know the linear constraint is one of the conditions (3.1), which define the polytope of feasible solutions . We now ask the related question,
There is an effective algorithm (the cylindrical algebraic decomposition [CAD]) to decide whether a system of real polynomial equations (e.g., that in Remark 5.12) has a real solution. ∎
In other words, it is Tarski-decidable to write down a communication lower bound, but it may be strictly smaller than the best lower bound implied by Theorem 3.2, and obtained by the approach in Section 5.1.
Easily computable communication lower bounds
There are variety of other situations in which we can effectively compute the communication lower bound, without applying the approach in Section 5.1. These are summarized in Section LABEL:sec:conclusions, and will appear in detail in Part 2 of this paper.
So in the remainder of this section, we assume that the group homomorphisms are distinct and nontrivial. The arrays however, may overlap in memory addresses; this possibility does not affect our asymptotic lower bound, given our assumption from Section 4 that is a constant, negligible compared to .
2 Trivial Cases
There are a few trivial cases where no work is required to find the communication lower bound: when the homomorphisms’ kernels have a nontrivial intersection, and when at least one homomorphism is an injection. These cover the cases where or . (When there are no arrays, and when there are no loops, cases we ignore.)
If and satisfies (3.1), then .
If not, then any nontrivial subgroup is supercritical with respect to . ∎
The following result, a companion to Theorem 3.2, gives a simpler necessary and sufficient condition for there to exist some exponent which satisfies (3.2).
There exists for which (3.2) holds if and only if
If , then Lemma 3.27 asserts that (3.2) holds with all equal to . Conversely, if is nontrivial, then for any finite nonempty subset , for every index , so . Thus the inequality (3.2) fails to hold for any of cardinality . ∎
If or , then either we fall into this case, or that of Section 6.2.2.
2.2 Injective Case
If one of the array references is an injection, then each loop iteration will require (at least) one unique operand, so at most iterations are possible with operands in cache. This observation is confirmed by the following lemma.
We see that by rewriting (3.1) as
As anticipated, the argument in Section 4 gives a lower bound , that is, no (asymptotic) data reuse is possible.
3 Product Case
all of which simply choose subsets of the loop indices . Similarly, for other linear algebra algorithms, tensor contractions, direct –body simulations, and other examples discussed below, the simply choose subsets of loop indices. In this case, one can straightforwardly write down a simple linear program for the optimal exponents of Theorem 3.2. We present this result as Theorem 6.6 below (this is a special case, with a simpler proof, of the more general result in [BCCT10, Proposition 7.1]). Using Theorem 6.6 we also give a number of concrete examples, some known (e.g., linear algebra) and some new.
Necessity follows from the fact that the constraints (6.2) are a subset of (3.1).
To show sufficiency, we rewrite hypothesis (6.2) as
We can generalize this to the case where the do not choose subsets of the indices , but rather subsets of suitable independent linear combinations of the indices, for example subsets of instead of subsets of . We will discuss recognizing the product case in more general array references in Part 2 of this paper.
We continue the example from Section 6.2.2, with , , and , or
The (simplest) code that accumulates the force on each particle (body) due to all particles is
We get , , and , or
which represents a generic “nested loop” database join algorithm of the sets of tuples and with and . We have a data-dependent branch in the inner loop, so we split the iteration space depending on the value of the predicate (we still assume that the predicate is evaluated for every ). This gives
an increasing function of (using the fact that ). When is close enough to zero, we have the ‘best’ lower bound , and when is close enough to 1, we have , the size of the output, a lower bound for any computation.
We outlined this result already in part 2/5 of this example (see Section 1). We have , , and , or
We already outlined this example in part 1/4 (see Section 1). The code given in part 1/4 leads to
We continue this example from part 2/4 (above), with , and as given there. So we have