HOME

TheInfoList



OR:

Because
matrix multiplication In mathematics, specifically in linear algebra, matrix multiplication is a binary operation that produces a matrix (mathematics), matrix from two matrices. For matrix multiplication, the number of columns in the first matrix must be equal to the n ...
is such a central operation in many
numerical algorithm Numerical analysis is the study of algorithms that use numerical approximation (as opposed to symbolic manipulations) for the problems of mathematical analysis (as distinguished from discrete mathematics). It is the study of numerical methods t ...
s, much work has been invested in making matrix multiplication algorithms efficient. Applications of matrix multiplication in computational problems are found in many fields including
scientific computing Computational science, also known as scientific computing, technical computing or scientific computation (SC), is a division of science, and more specifically the Computer Sciences, which uses advanced computing capabilities to understand and s ...
and
pattern recognition Pattern recognition is the task of assigning a class to an observation based on patterns extracted from data. While similar, pattern recognition (PR) is not to be confused with pattern machines (PM) which may possess PR capabilities but their p ...
and in seemingly unrelated problems such as counting the paths through a
graph Graph may refer to: Mathematics *Graph (discrete mathematics), a structure made of vertices and edges **Graph theory, the study of such graphs and their properties *Graph (topology), a topological space resembling a graph in the sense of discret ...
. Many different algorithms have been designed for multiplying matrices on different types of hardware, including parallel and distributed systems, where the computational work is spread over multiple processors (perhaps over a network). Directly applying the mathematical definition of matrix multiplication gives an algorithm that takes time on the order of field operations to multiply two matrices over that field ( in
big O notation Big ''O'' notation is a mathematical notation that describes the asymptotic analysis, limiting behavior of a function (mathematics), function when the Argument of a function, argument tends towards a particular value or infinity. Big O is a memb ...
). Better asymptotic bounds on the time required to multiply matrices have been known since the Strassen's algorithm in the 1960s, but the optimal time (that is, the
computational complexity of matrix multiplication In theoretical computer science, the computational complexity of matrix multiplication dictates Analysis of algorithms, how quickly the operation of matrix multiplication can be performed. Matrix multiplication algorithms are a central subroutine ...
) remains unknown. , the best announced bound on the asymptotic complexity of a matrix multiplication algorithm is time, given by Williams, Xu, Xu, and Zhou. This improves on the bound of time, given by Alman and Williams. However, this algorithm is a galactic algorithm because of the large constants and cannot be realized practically.


Iterative algorithm

The definition of matrix multiplication is that if for an matrix and an matrix , then is an matrix with entries :c_ = \sum_^m a_ b_. From this, a simple algorithm can be constructed which loops over the indices from 1 through and from 1 through , computing the above using a nested loop: * Input: matrices and * Let be a new matrix of the appropriate size * For from 1 to : ** For from 1 to : *** Let *** For from 1 to : **** Set *** Set * Return This algorithm takes
time Time is the continuous progression of existence that occurs in an apparently irreversible process, irreversible succession from the past, through the present, and into the future. It is a component quantity of various measurements used to sequ ...
(in
asymptotic notation Big ''O'' notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. Big O is a member of a family of notations invented by German mathematicians Pau ...
). A common simplification for the purpose of algorithm analysis is to assume that the inputs are all square matrices of size , in which case the running time is , i.e., cubic in the size of the dimension.


Cache behavior

The three loops in iterative matrix multiplication can be arbitrarily swapped with each other without an effect on correctness or asymptotic running time. However, the order can have a considerable impact on practical performance due to the memory access patterns and cache use of the algorithm; which order is best also depends on whether the matrices are stored in row-major order, column-major order, or a mix of both. In particular, in the idealized case of a fully associative cache consisting of bytes and bytes per cache line (i.e. cache lines), the above algorithm is sub-optimal for and stored in row-major order. When , every iteration of the inner loop (a simultaneous sweep through a row of and a column of ) incurs a cache miss when accessing an element of . This means that the algorithm incurs cache misses in the worst case. , the speed of memories compared to that of processors is such that the cache misses, rather than the actual calculations, dominate the running time for sizable matrices. The optimal variant of the iterative algorithm for and in row-major layout is a '' tiled'' version, where the matrix is implicitly divided into square tiles of size by : * Input: matrices and * Let be a new matrix of the appropriate size * Pick a tile size * For from 1 to in steps of : ** For from 1 to in steps of : *** For from 1 to in steps of : **** Multiply and into , that is: **** For from to : ***** For from to : ****** Let ****** For from to : ******* Set ****** Set * Return In the idealized cache model, this algorithm incurs only cache misses; the divisor amounts to several orders of magnitude on modern machines, so that the actual calculations dominate the running time, rather than the cache misses.


Divide-and-conquer algorithm

An alternative to the iterative algorithm is the
divide-and-conquer algorithm In computer science, divide and conquer is an algorithm design paradigm. A divide-and-conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved dir ...
for matrix multiplication. This relies on the block partitioning :C = \begin C_ & C_ \\ C_ & C_ \\ \end,\, A = \begin A_ & A_ \\ A_ & A_ \\ \end,\, B = \begin B_ & B_ \\ B_ & B_ \\ \end, which works for all square matrices whose dimensions are powers of two, i.e., the shapes are for some . The matrix product is now :\begin C_ & C_ \\ C_ & C_ \\ \end = \begin A_ & A_ \\ A_ & A_ \\ \end \begin B_ & B_ \\ B_ & B_ \\ \end = \begin A_ B_ + A_ B_ & A_ B_ + A_ B_\\ A_ B_ + A_ B_ & A_ B_ + A_ B_\\ \end which consists of eight multiplications of pairs of submatrices, followed by an addition step. The divide-and-conquer algorithm computes the smaller multiplications recursively, using the
scalar multiplication In mathematics, scalar multiplication is one of the basic operations defining a vector space in linear algebra (or more generally, a module in abstract algebra). In common geometrical contexts, scalar multiplication of a real Euclidean vector ...
as its base case. The complexity of this algorithm as a function of is given by the recurrence :T(1) = \Theta(1); :T(n) = 8T(n/2) + \Theta(n^2), accounting for the eight recursive calls on matrices of size and to sum the four pairs of resulting matrices element-wise. Application of the master theorem for divide-and-conquer recurrences shows this recursion to have the solution , the same as the iterative algorithm.


Non-square matrices

A variant of this algorithm that works for matrices of arbitrary shapes and is faster in practice splits matrices in two instead of four submatrices, as follows. Splitting a matrix now means dividing it into two parts of equal size, or as close to equal sizes as possible in the case of odd dimensions. * Inputs: matrices of size , of size . * Base case: if is below some threshold, use an unrolled version of the iterative algorithm. * Recursive cases: :* If , split horizontally: ::C = \begin A_1 \\ A_2 \end = \begin A_1 B \\ A_2 B \end :* Else, if , split vertically: ::C = A \begin B_1 & B_2 \end = \begin A B_1 & A B_2 \end :* Otherwise, . Split vertically and horizontally: ::C = \begin A_1 & A_2 \end \begin B_1 \\ B_2 \end = A_1 B_1 + A_2 B_2


Cache behavior

The cache miss rate of recursive matrix multiplication is the same as that of a tiled iterative version, but unlike that algorithm, the recursive algorithm is cache-oblivious: there is no tuning parameter required to get optimal cache performance, and it behaves well in a
multiprogramming In computing, multitasking is the concurrent execution of multiple tasks (also known as processes) over a certain period of time. New tasks can interrupt already started ones before they finish, instead of waiting for them to end. As a result ...
environment where cache sizes are effectively dynamic due to other processes taking up cache space. (The simple iterative algorithm is cache-oblivious as well, but much slower in practice if the matrix layout is not adapted to the algorithm.) The number of cache misses incurred by this algorithm, on a machine with lines of ideal cache, each of size bytes, is bounded by :\Theta \left(m + n + p + \frac + \frac \right)


Sub-cubic algorithms

Algorithms exist that provide better running times than the straightforward ones. The first to be discovered was Strassen's algorithm, devised by Volker Strassen in 1969 and often referred to as "fast matrix multiplication". It is based on a way of multiplying two 2×2 matrices which requires only 7 multiplications (instead of the usual 8), at the expense of several additional addition and subtraction operations. Applying this recursively gives an algorithm with a multiplicative cost of O( n^) \approx O(n^). Strassen's algorithm is more complex, and the
numerical stability In the mathematical subfield of numerical analysis, numerical stability is a generally desirable property of numerical algorithms. The precise definition of stability depends on the context: one important context is numerical linear algebra, and ...
is reduced compared to the naïve algorithm, but it is faster in cases where or so and appears in several libraries, such as BLAS. It is very useful for large matrices over exact domains such as
finite field In mathematics, a finite field or Galois field (so-named in honor of Évariste Galois) is a field (mathematics), field that contains a finite number of Element (mathematics), elements. As with any field, a finite field is a Set (mathematics), s ...
s, where numerical stability is not an issue. Since Strassen's algorithm is actually used in practical numerical software and computer algebra systems, improving on the constants hidden in the
big-O notation Big ''O'' notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. Big O is a member of a family of notations invented by German mathematicians Pau ...
has its merits. A table that compares key aspects of the improved version based on recursive multiplication of 2×2-block matrices via 7 block matrix multiplications follows. As usual, n gives the dimensions of the matrix and M designates the memory size. It is known that a Strassen-like algorithm with a 2×2-block matrix step requires at least 7 block matrix multiplications. In 1976 Probert showed that such an algorithm requires at least 15 additions (including subtractions); however, a hidden assumption was that the blocks and the 2×2-block matrix are represented in the same basis. Karstadt and Schwartz computed in different bases and traded 3 additions for less expensive basis transformations. They also proved that one cannot go below 12 additions per step using different bases. In subsequent work Beniamini et el. applied this base-change trick to more general decompositions than 2×2-block matrices and improved the leading constant for their run times. It is an open question in
theoretical computer science Theoretical computer science is a subfield of computer science and mathematics that focuses on the Abstraction, abstract and mathematical foundations of computation. It is difficult to circumscribe the theoretical areas precisely. The Associati ...
how well Strassen's algorithm can be improved in terms of asymptotic complexity. The ''matrix multiplication exponent'', usually denoted \omega, is the smallest real number for which any n\times n matrix over a field can be multiplied together using n^ field operations. The current best bound on \omega is \omega < 2.371552, by Williams, Xu, Xu, and Zhou. This algorithm, like all other recent algorithms in this line of research, is a generalization of the Coppersmith–Winograd algorithm, which was given by Don Coppersmith and Shmuel Winograd in 1990. The conceptual idea of these algorithms is similar to Strassen's algorithm: a way is devised for multiplying two -matrices with fewer than multiplications, and this technique is applied recursively. However, the constant coefficient hidden by the
big-O notation Big ''O'' notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity. Big O is a member of a family of notations invented by German mathematicians Pau ...
is so large that these algorithms are only worthwhile for matrices that are too large to handle on present-day computers. Victor Pan proposed so-called feasible sub-cubic matrix multiplication algorithms with an exponent slightly above 2.77, but in return with a much smaller hidden constant coefficient. Freivalds' algorithm is a simple
Monte Carlo algorithm In computing, a Monte Carlo algorithm is a randomized algorithm whose output may be incorrect with a certain (typically small) probability. Two examples of such algorithms are the Karger–Stein algorithm and the Monte Carlo algorithm for mini ...
that, given matrices , and , verifies in time if .


AlphaTensor

In 2022,
DeepMind DeepMind Technologies Limited, trading as Google DeepMind or simply DeepMind, is a British–American artificial intelligence research laboratory which serves as a subsidiary of Alphabet Inc. Founded in the UK in 2010, it was acquired by Go ...
introduced AlphaTensor, a
neural network A neural network is a group of interconnected units called neurons that send signals to one another. Neurons can be either biological cells or signal pathways. While individual neurons are simple, many of them together in a network can perfor ...
that used a single-player game analogy to invent thousands of matrix multiplication algorithms, including some previously discovered by humans and some that were not. Operations were restricted to the (normal arithmetic) and finite field \mathbb Z/2\mathbb Z (mod 2 arithmetic). The best "practical" (explicit low-rank decomposition of a matrix multiplication tensor) algorithm found ran in O(n2.778). Finding low-rank decompositions of such tensors (and beyond) is NP-hard; optimal multiplication even for 3×3 matrices remains unknown, even in commutative field. On 4×4 matrices, AlphaTensor unexpectedly discovered a solution with 47 multiplication steps, an improvement over the 49 required with Strassen’s algorithm of 1969, albeit restricted to mod 2 arithmetic. Similarly, AlphaTensor solved 5×5 matrices with 96 rather than Strassen's 98 steps. Based on the surprising discovery that such improvements exist, other researchers were quickly able to find a similar independent 4×4 algorithm, and separately tweaked Deepmind's 96-step 5×5 algorithm down to 95 steps in mod 2 arithmetic and to 97 in normal arithmetic. Some algorithms were completely new: for example, (4, 5, 5) was improved to 76 steps from a baseline of 80 in both normal and mod 2 arithmetic.


Parallel and distributed algorithms


Shared-memory parallelism

The
divide-and-conquer algorithm In computer science, divide and conquer is an algorithm design paradigm. A divide-and-conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved dir ...
sketched earlier can be parallelized in two ways for shared-memory multiprocessors. These are based on the fact that the eight recursive matrix multiplications in :\begin A_ B_ + A_ B_ & A_ B_ + A_ B_\\ A_ B_ + A_ B_ & A_ B_ + A_ B_\\ \end can be performed independently of each other, as can the four summations (although the algorithm needs to "join" the multiplications before doing the summations). Exploiting the full parallelism of the problem, one obtains an algorithm that can be expressed in fork–join style
pseudocode In computer science, pseudocode is a description of the steps in an algorithm using a mix of conventions of programming languages (like assignment operator, conditional operator, loop) with informal, usually self-explanatory, notation of actio ...
: Procedure : * Base case: if , set (or multiply a small block matrix). * Otherwise, allocate space for a new matrix of shape , then: ** Partition into , , , . ** Partition into , , , . ** Partition into , , , . ** Partition into , , , . ** Parallel execution: *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . ** ''Join'' (wait for parallel forks to complete). ** . ** Deallocate . Procedure adds into , element-wise: * Base case: if , set (or do a short loop, perhaps unrolled). * Otherwise: ** Partition into , , , . ** Partition into , , , . ** In parallel: *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . *** ''Fork'' . ** ''Join''. Here, ''fork'' is a keyword that signal a computation may be run in parallel with the rest of the function call, while ''join'' waits for all previously "forked" computations to complete. achieves its goal by pointer manipulation only. This algorithm has a critical path length of steps, meaning it takes that much time on an ideal machine with an infinite number of processors; therefore, it has a maximum possible
speedup In computer architecture, speedup is a number that measures the relative performance of two systems processing the same problem. More technically, it is the improvement in speed of execution of a task executed on two similar architectures with ...
of on any real computer. The algorithm isn't practical due to the communication cost inherent in moving data to and from the temporary matrix , but a more practical variant achieves speedup, without using a temporary matrix.


Communication-avoiding and distributed algorithms

On modern architectures with hierarchical memory, the cost of loading and storing input matrix elements tends to dominate the cost of arithmetic. On a single machine this is the amount of data transferred between RAM and cache, while on a distributed memory multi-node machine it is the amount transferred between nodes; in either case it is called the ''communication bandwidth''. The naïve algorithm using three nested loops uses communication bandwidth. Cannon's algorithm, also known as the ''2D algorithm'', is a communication-avoiding algorithm that partitions each input matrix into a block matrix whose elements are submatrices of size by , where is the size of fast memory. The naïve algorithm is then used over the block matrices, computing products of submatrices entirely in fast memory. This reduces communication bandwidth to , which is asymptotically optimal (for algorithms performing computation). In a distributed setting with processors arranged in a by 2D mesh, one submatrix of the result can be assigned to each processor, and the product can be computed with each processor transmitting words, which is asymptotically optimal assuming that each node stores the minimum elements. This can be improved by the ''3D algorithm,'' which arranges the processors in a 3D cube mesh, assigning every product of two input submatrices to a single processor. The result submatrices are then generated by performing a reduction over each row. This algorithm transmits words per processor, which is asymptotically optimal. However, this requires replicating each input matrix element times, and so requires a factor of more memory than is needed to store the inputs. This algorithm can be combined with Strassen to further reduce runtime. "2.5D" algorithms provide a continuous tradeoff between memory usage and communication bandwidth. On modern distributed computing environments such as
MapReduce MapReduce is a programming model and an associated implementation for processing and generating big data sets with a parallel and distributed algorithm on a cluster. A MapReduce program is composed of a ''map'' procedure, which performs filte ...
, specialized multiplication algorithms have been developed.


Algorithms for meshes

There are a variety of algorithms for multiplication on meshes. For multiplication of two ''n''×''n'' on a standard two-dimensional mesh using the 2D Cannon's algorithm, one can complete the multiplication in 3''n''-2 steps although this is reduced to half this number for repeated computations. The standard array is inefficient because the data from the two matrices does not arrive simultaneously and it must be padded with zeroes. The result is even faster on a two-layered cross-wired mesh, where only 2''n''-1 steps are needed. The performance improves further for repeated computations leading to 100% efficiency. The cross-wired mesh array may be seen as a special case of a non-planar (i.e. multilayered) processing structure. In a 3D mesh with ''n''3 processing elements, two matrices can be multiplied in \mathcal(\log n) using the DNS algorithm.


See also

* Computational complexity of mathematical operations *
Computational complexity of matrix multiplication In theoretical computer science, the computational complexity of matrix multiplication dictates Analysis of algorithms, how quickly the operation of matrix multiplication can be performed. Matrix multiplication algorithms are a central subroutine ...
* CYK algorithm § Valiant's algorithm * Matrix chain multiplication * Method of Four Russians * Multiplication algorithm *
Sparse matrix–vector multiplication Sparse matrix–vector multiplication (SpMV) of the form is a widely used computational kernel existing in many scientific applications. The input matrix is sparse. The input vector and the output vector are dense. In the case of a repeated ...


References


Further reading

* * *
How To Optimize GEMM
{{Numerical linear algebra Numerical linear algebra Matrix theory Articles with example pseudocode