GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing tnl-project.gitlab.io (truncated) — Template Numerical Library: Matrices
Toggle main menu visibility
Loading...
Searching...
No Matches
Matrices Table of Contents
IntroductionTNL offers several types of matrices like dense (TNL::Matrices::DenseMatrix), sparse (TNL::Matrices::SparseMatrix), tridiagonal (TNL::Matrices::TridiagonalMatrix), multidiagonal (TNL::Matrices::MultidiagonalMatrix) and lambda matrices (TNL::Matrices::LambdaMatrix). The sparse matrices can be symmetric to lower the memory requirements. The interfaces of given matrix types are designed to be as unified as possible to ensure that the user can easily switch between different matrix types while making no or only a little changes in the source code. All matrix types allows traversing all matrix elements and manipulate them using lambda functions as well as performing flexible reduction in matrix rows. The following text describes particular matrix types and their unified interface in details. Overview of matrix typesIn a lot of numerical algorithms either dense or sparse matrices are used. The dense matrix (TNL::Matrices::DenseMatrix) is such that all or at least most of its matrix elements are nonzero. On the other hand sparse matrix (TNL::Matrices::SparseMatrix) is a matrix which has most of the matrix elements equal to zero. From the implementation point of view, the data structures for the dense matrices allocates all matrix elements while formats for the sparse matrices aim to store explicitly only the nonzero matrix elements. The most popular format for storing the sparse matrices is CSR format. However, especially for better data alignment in memory of GPUs, many other formats were designed. In TNL, the user may choose between several different sparse matrix formats. There are also sparse matrices with specific pattern of the nonzero elements like tridiagonal matrices (TNL::Matrices::TridiagonalMatrix) which "has nonzero elements on the main diagonal, the first diagonal below this, and the first diagonal above the main diagonal only". An example of such matrix may look as follows: \[\left( \begin{array}{ccccccc} -2 & 1 & . & . & . & . \\ 1 & -2 & 1 & . & . & . \\ . & 1 & -2 & 1 & . & . \\ . & . & 1 & -2 & 1 & . \\ . & . & . & 1 & -2 & 1 \\ . & . & . & . & 1 & -2 \end{array} \right) \] Similar but more general type of matrices are multidiagonal matrices (TNL::Matrices::MultidiagonalMatrix) which have the nonzero matrix elements positioned only on lines parallel to the main diagonal like the following matrix: \[ \left( \begin{array}{ccccccc} -4 & 1 & . & 1 & . & . \\ 1 & -4 & 1 & . & 1 & . \\ . & 1 & -4 & 1 & . & 1 \\ 1 & . & 1 & -4 & 1 & . \\ . & 1 & . & 1 & -4 & 1 \\ . & . & 1 & . & 1 & -4 \end{array} \right) \] Finally, TNL offers so called lambda matrices (TNL::Matrices::LambdaMatrix) which are kind of "matrix-free matrices". They do not store the matrix elements explicitly in the memory, but rather evaluates them on-the-fly based on user defined lambda functions. In the following table we show comparison of expressing a tridiagonal matrix by means of different matrix types.
In the table:
Choosing the best matrix type can have tremendous impact on the performance but also on memory requirements. If we would treat each matrix as dense one we would not be able to to work with matrices larger than 50,000x50,000 on common personal computers, because we would need tens of gibabytes of memory. At the same time, we see that the other matrix types can do the same job with only few megabytes. In addition, other matrix types work with much less matrix elements and so operations like matrix-vector multiplication can be done with significantly less operations which means much faster. Since in the modern hardware architectures, the computing units are limited mainly by the performance of the memory chips (so called memory wall), transferring less data from the memory increases the performance even more. The following table shows the same as the one above but when storing a matrix which has only five nonzero elements in each row. Such matrices arise often from the finite difference method for solution of the partial differential equations:
There is no change in the dense matrix part of the table. The numbers grow proportionally in case of sparse and mutlidiagonal matrix. General sparse matrix formats need to store column indexes for each matrix element which is not true for the multidiagonal matrix. The following table shows how many bytes we need for storing of one matrix element with different matrix types depending on the type of the matrix elements (Real) and column indexes (Index):
In this table:
The multidiagonal matrix type is especially suitable for the finite difference method or similar numerical methods for solution of the partial differential equations. Indexing of nonzero matrix elements in sparse matricesThe sparse matrix formats usually, in the first step, compress the matrix rows by omitting the zero matrix elements as follows \[\left( \begin{array}{ccccc} 0 & 1 & 0 & 2 & 0 \\ 0 & 0 & 5 & 0 & 0 \\ 4 & 0 & 0 & 0 & 7 \\ 0 & 3 & 0 & 8 & 5 \\ 0 & 5 & 7 & 0 & 0 \end{array} \right) \rightarrow \left( \begin{array}{ccccc} 1 & 2 & . & . & . \\ 5 & . & . & . & . \\ 4 & 7 & . & . & . \\ 3 & 8 & 5 & . & . \\ 5 & 7 & . & . & . \end{array} \right) \] In such a form, it is more efficient to refer the nonzero matrix elements in given row by their rank in the compressed matrix row rather than by their column index in the original matrix. In methods for the sparse matrices, this parameter is called localIdx. Some sparse matrix formats add padding zeros for better alignment of data in memory. But if this is not the case, the variable localIdx of particular matrix elements would read as: \[\left( \begin{array}{ccccc} 0 & 1 & . & . & . \\ 0 & . & . & . & . \\ 0 & 1 & . & . & . \\ 0 & 1 & 2 & . & . \\ 0 & 1 & . & . & . \end{array} \right) \] Matrix viewMatrix views are small reference objects which help accessing the matrix in GPU kernels or lambda functions being executed on GPUs. We describe this in details in section about Shared pointers and views. The problem lies in fact that we cannot pass references to GPU kernels and we do not want to pass there deep copies of matrices. Matrix view is some kind of reference to a matrix. A copy of matrix view is always shallow and so it behaves like a reference. The following example shows how to obtain the matrix view by means of method getView and pass it to a lambda function: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/SparseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9getRowExample()
10{
11 /***
12 * Set the following matrix (dots represent zero matrix elements):
13 *
14 * / 2 . . . . \
15 * | 1 2 1 . . |
16 * | . 1 2 1. . |
17 * | . . 1 2 1 |
18 * \ . . . . 2 /
19 */
20 const int size = 5;
21 TNL::Matrices::SparseMatrix< double, Device > matrix( { 1, 3, 3, 3, 1 }, size );
23
24 /***
25 * Set the matrix elements.
26 */
28 {
30 if( rowIdx == 0 ) {
31 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
32 }
33 else if( rowIdx == size - 1 ) {
34 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
35 }
36 else {
37 row.setElement( 0, rowIdx - 1, 1.0 ); // elements below the diagonal
38 row.setElement( 1, rowIdx, 2.0 ); // diagonal element
39 row.setElement( 2, rowIdx + 1, 1.0 ); // elements above the diagonal
40 }
41 };
42 TNL::Algorithms::parallelFor< Device >( 0, matrix.getRows(), f );
44}
45
46int
47main( int argc, char* argv[] )
48{
50 getRowExample< TNL::Devices::Host >();
51
52#if defined( __CUDACC__ ) || defined( __HIP__ )
54 getRowExample< TNL::Devices::GPU >();
55#endif
56}
#define __cuda_callable__ This macro serves for annotating functions which are supposed to be called even from the GPU device. Definition Macros.h:50 __cuda_callable__ ConstRowView getRow(IndexType rowIdx) const Constant getter of simple structure for accessing given matrix row. Implementation of sparse matrix, i.e. matrix storing only non-zero elements. Definition SparseMatrix.h:59 ViewType getView() Returns a modifiable view of the sparse matrix. std::enable_if_t< std::is_integral_v< Begin > &&std::is_integral_v< End > > parallelFor(const Begin &begin, const End &end, typename Device::LaunchConfiguration launch_config, Function f, FunctionArgs... args) Parallel for-loop function for 1D range specified with integral values. Definition parallelFor.h:41 constexpr const char * getBackendName() Returns the name of the GPU backend: "CUDA", "HIP", or "none" when no GPU backend is available. Definition Functions.h:21 Here we create sparse matrix matrix on the line 11, and use the method getView to get the matrix view on the line 12. The view is then used in the lambda function on the line 15 where it is captured by value (see [=] in the definition of the lambda function f on the line 14). Allocation and setup of different matrix typesThere are several ways how to create a new matrix:
The following table shows pros and cons of particular methods:
Though it may seem that the later methods come with more cons than pros, they offer much higher performance and we believe that even they are still user friendly. On the other hand, if the matrix setup performance is not a priority, the use easy-to-use but slow method can still be a good choice. The following tables demonstrate the performance of different methods. The tests were performed with the following setup:
Dense matrixIn the test of dense matrices, we set each matrix element to value equal to rowIdx + columnIdx. The times in seconds obtained on CPU looks as follows:
Here:
And the same on GPU is in the following table:
Here:
You can see the source code of the previous benchmark in Appendix. Sparse matrixThe sparse matrices are tested on computation of matrix the discrete Laplace operator in 2D. This matrix has at most five nonzero elements in each row. The times for sparse matrix (with CSR format) on CPU in seconds look as follows:
Here:
We see, that the use of STL map makes sense only in situation when it is hard to estimate necessary row capacities. Otherwise very easy setup with setElement method is much faster. If the performance is the highest priority, getRow method should be preferred. The results for GPU are in the following table:
Here:
Here we see, that the setElement methods performs extremely bad because all matrix elements are transferred to GPU one-by-one. Even STL map is much faster. Note, that the times for STL map are not much higher compared to CPU which indicates that the transfer of the matrix on GPU is not dominant. Setup of the matrix on CPU by the means of setElement method and transfer on GPU is even faster. However, the best performance can be obtained only we creating the matrix directly on GPU by methods setElement, getRow and forElements. Note, however, that even if all of them perform the same way, for matrices with more nonzero matrix elements in a row, setElement could be slower compared to the getRow and forElements. You can see the source code of the previous benchmark in Appendix. Multidiagonal matrixFinally, the following tables show the times of the same test performed with multidiagonal matrix. Times on CPU in seconds looks as follows:
Here:
Note, that setup of multidiagonal matrix is faster compared to the same matrix stored in general sparse format. Results for GPU are in the following table:
Note that multidiagonal matrix performs better compared to general sparse matrix. One reason for it is the fact, that the multidiagonal type does not store explicitly column indexes of all matrix elements. Because of this, less data need to be transferred from the memory. You can see the source code of the previous benchmark in Appendix. In the following parts we will describe how to setup particular matrix types by means of the methods mentioned above. Dense matricesDense matrix (TNL::Matrices::DenseMatrix) is a templated class defined in the namespace TNL::Matrices. It has five template parameters:
The following examples show how to allocate the dense matrix and how to initialize the matrix elements. Initializer listSmall matrices can be created simply by the constructor with an initializer list. 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7initializerListExample()
8{
10 // clang-format off
11 { 1, 2, 3, 4, 5, 6 },
12 { 7, 8, 9, 10, 11, 12 },
13 { 13, 14, 15, 16, 17, 18 },
14 // clang-format on
15 };
16
18
19 TNL::Matrices::DenseMatrix< double, Device > triangularMatrix{
20 // clang-format off
21 { 1 },
22 { 2, 3 },
23 { 4, 5, 6 },
24 { 7, 8, 9, 10 },
25 { 11, 12, 13, 14, 15 },
26 // clang-format on
27 };
28
30}
31
32int
33main( int argc, char* argv[] )
34{
36 initializerListExample< TNL::Devices::Host >();
37
38#if defined( __CUDACC__ ) || defined( __HIP__ )
40 initializerListExample< TNL::Devices::GPU >();
41#endif
42}
Implementation of dense matrix, i.e. matrix storing explicitly all of its elements including zeros. Definition DenseMatrix.h:33 In fact, the constructor takes a list of initializer lists. Each embedded list defines one matrix row and so the number of matrix rows is given by the size of the outer initializer list. The number of matrix columns is given by the longest inner initializer lists. Shorter inner lists are filled with zeros from the right side. The result looks as follows: Creating matrices on CPU ...
General dense matrix:
Row: 0 -> 0:1 1:2 2:3 3:4 4:5 5:6
Row: 1 -> 0:7 1:8 2:9 3:10 4:11 5:12
Row: 2 -> 0:13 1:14 2:15 3:16 4:17 5:18
Triangular dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:2 1:3 2:0 3:0 4:0
Row: 2 -> 0:4 1:5 2:6 3:0 4:0
Row: 3 -> 0:7 1:8 2:9 3:10 4:0
Row: 4 -> 0:11 1:12 2:13 3:14 4:15
Creating matrices on GPU (CUDA) ...
General dense matrix:
Row: 0 -> 0:1 1:2 2:3 3:4 4:5 5:6
Row: 1 -> 0:7 1:8 2:9 3:10 4:11 5:12
Row: 2 -> 0:13 1:14 2:15 3:16 4:17 5:18
Triangular dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:2 1:3 2:0 3:0 4:0
Row: 2 -> 0:4 1:5 2:6 3:0 4:0
Row: 3 -> 0:7 1:8 2:9 3:10 4:0
Row: 4 -> 0:11 1:12 2:13 3:14 4:15
Methods setElement and addElementLarger matrices can be setup with methods setElement and addElement (TNL::Matrices::DenseMatrix::setElement, TNL::Matrices::DenseMatrix::addElement). The following example shows how to call these methods from the host. 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7addElements()
8{
9 TNL::Matrices::DenseMatrix< double, Device > matrix( 5, 5 );
10 auto matrixView = matrix.getView();
11
12 for( int i = 0; i < 5; i++ )
13 matrixView.setElement( i, i, i ); // or matrix.setElement
14
16
17 for( int i = 0; i < 5; i++ )
18 for( int j = 0; j < 5; j++ )
19 matrixView.addElement( i, j, 1.0, 5.0 ); // or matrix.addElement
20
22}
23
24int
25main( int argc, char* argv[] )
26{
28 addElements< TNL::Devices::Host >();
29
30#if defined( __CUDACC__ ) || defined( __HIP__ )
32 addElements< TNL::Devices::GPU >();
33#endif
34}
As we can see, both methods can be called from the host no matter where the matrix is allocated. If it is on GPU, each call of setElement or addElement (TNL::Matrices::DenseMatrix::setElement, TNL::Matrices::DenseMatrix::addElement) causes slow transfer of the data between CPU and GPU. Use this approach only if the performance is not a priority. The result looks as follows: Add elements on host:
Initial matrix is:
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0
Row: 2 -> 0:0 1:0 2:2 3:0 4:0
Row: 3 -> 0:0 1:0 2:0 3:3 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:4
Matrix after addition is:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:6 2:1 3:1 4:1
Row: 2 -> 0:1 1:1 2:11 3:1 4:1
Row: 3 -> 0:1 1:1 2:1 3:16 4:1
Row: 4 -> 0:1 1:1 2:1 3:1 4:21
Add elements on GPU (CUDA):
Initial matrix is:
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0
Row: 2 -> 0:0 1:0 2:2 3:0 4:0
Row: 3 -> 0:0 1:0 2:0 3:3 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:4
Matrix after addition is:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:6 2:1 3:1 4:1
Row: 2 -> 0:1 1:1 2:11 3:1 4:1
Row: 3 -> 0:1 1:1 2:1 3:16 4:1
Row: 4 -> 0:1 1:1 2:1 3:1 4:21
More efficient way of the matrix initialization on GPU consists of calling the methods setElement and addElement (TNL::Matrices::DenseMatrix::setElement, TNL::Matrices::DenseMatrix::addElement) directly from GPU, for example by means of lambda function and parallelFor. It is demonstrated in the following example (of course it works even on CPU): 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Containers/StaticArray.h>
4#include <TNL/Matrices/DenseMatrix.h>
5#include <TNL/Devices/Host.h>
6
7template< typename Device >
8void
9setElements()
10{
11 TNL::Matrices::DenseMatrix< double, Device > matrix( 5, 5 );
12 auto matrixView = matrix.getView();
13 for( int i = 0; i < 5; i++ )
14 matrixView.setElement( i, i, i ); // or matrix.setElement
15
18
20 {
21 matrixView.addElement( i[ 0 ], i[ 1 ], 5.0 );
22 };
23 TNL::Containers::StaticArray< 2, int > begin = { 0, 0 };
24 TNL::Containers::StaticArray< 2, int > end = { 5, 5 };
25 TNL::Algorithms::parallelFor< Device >( begin, end, f );
26
29}
30
31int
32main( int argc, char* argv[] )
33{
35 setElements< TNL::Devices::Host >();
36
37#if defined( __CUDACC__ ) || defined( __HIP__ )
39 setElements< TNL::Devices::GPU >();
40#endif
41}
Here we get the matrix view (TNL::Matrices::DenseMatrixView) (line 10) to make the matrix accessible in lambda function even on GPU (see Shared pointers and views ). We first call the setElement method from CPU to set the i-th diagonal element to i (lines 11-12). Next we iterate over the matrix rows with parallelFor (line 20) and for each row we call the lambda function f. This is done on the same device where the matrix is allocated and so it we get optimal performance even for matrices on GPU. In the lambda function we add one to each matrix element (line 18). The result looks as follows: Set elements on host:
Matrix set from the host:
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0
Row: 2 -> 0:0 1:0 2:2 3:0 4:0
Row: 3 -> 0:0 1:0 2:0 3:3 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:4
Matrix set from its native device:
Row: 0 -> 0:5 1:5 2:5 3:5 4:5
Row: 1 -> 0:5 1:6 2:5 3:5 4:5
Row: 2 -> 0:5 1:5 2:7 3:5 4:5
Row: 3 -> 0:5 1:5 2:5 3:8 4:5
Row: 4 -> 0:5 1:5 2:5 3:5 4:9
Set elements on GPU (CUDA):
Matrix set from the host:
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0
Row: 2 -> 0:0 1:0 2:2 3:0 4:0
Row: 3 -> 0:0 1:0 2:0 3:3 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:4
Matrix set from its native device:
Row: 0 -> 0:5 1:5 2:5 3:5 4:5
Row: 1 -> 0:5 1:6 2:5 3:5 4:5
Row: 2 -> 0:5 1:5 2:7 3:5 4:5
Row: 3 -> 0:5 1:5 2:5 3:8 4:5
Row: 4 -> 0:5 1:5 2:5 3:5 4:9
Method getRowThis method is available for the dense matrix (TNL::Matrices::DenseMatrix::getRow) mainly for two reasons:
Here we show an example: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/DenseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9getRowExample()
10{
11 const int size = 5;
12 TNL::Matrices::DenseMatrix< double, Device > matrix( size, size );
13
14 /***
15 * Create dense matrix view which can be captured by the following lambda
16 * function.
17 */
18 auto matrixView = matrix.getView();
19
21 {
22 auto row = matrixView.getRow( rowIdx );
23 if( rowIdx > 0 )
24 row.setValue( rowIdx - 1, -1.0 );
25 row.setValue( rowIdx, rowIdx + 1.0 );
26 if( rowIdx < size - 1 )
27 row.setValue( rowIdx + 1, -1.0 );
28 };
29
30 /***
31 * Set the matrix elements.
32 */
33 TNL::Algorithms::parallelFor< Device >( 0, matrix.getRows(), f );
35}
36
37int
38main( int argc, char* argv[] )
39{
41 getRowExample< TNL::Devices::Host >();
42
43#if defined( __CUDACC__ ) || defined( __HIP__ )
45 getRowExample< TNL::Devices::GPU >();
46#endif
47}
Here we create the matrix on the line 10 and get the matrix view on the line 16. Next we use parallelFor (line 31) to iterate over the matrix rows and call the lambda function f (lines 19-26) for each of them. In the lambda function, we first fetch the matrix row by means of the method getRow (TNL::Matrices::DenseMatrixView::getRow) and next we set the matrix elements by using the method setElement of the matrix row (TNL::Matrices::DenseMatrixRowView::setElement). For the compatibility with the sparse matrices, use the variant of setElement with the parameter localIdx. It has no effect here, it is only for compatibility of the interface. The result looks as follows: Getting matrix rows on host:
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-1 1:2 2:-1 3:0 4:0
Row: 2 -> 0:0 1:-1 2:3 3:-1 4:0
Row: 3 -> 0:0 1:0 2:-1 3:4 4:-1
Row: 4 -> 0:0 1:0 2:0 3:-1 4:5
Getting matrix rows on GPU (CUDA):
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-1 1:2 2:-1 3:0 4:0
Row: 2 -> 0:0 1:-1 2:3 3:-1 4:0
Row: 3 -> 0:0 1:0 2:-1 3:4 4:-1
Row: 4 -> 0:0 1:0 2:0 3:-1 4:5
Method forRowsThis method iterates in parallel over all matrix rows. In fact, it combines TNL::Algorithms::parallelFor and TNL::Matrices::DenseMatrix::getRow method in one. See the following example. It is even a bit simpler compared to the previous one: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8forRowsExample()
9{
11 using RowView = typename MatrixType::RowView;
12 const int size = 5;
13 MatrixType matrix( size, size );
14 auto view = matrix.getView();
15
16 /***
17 * Set the matrix elements.
18 */
20 {
21 const int& rowIdx = row.getRowIndex();
22 if( rowIdx > 0 )
23 row.setValue( rowIdx - 1, -1.0 );
24 row.setValue( rowIdx, rowIdx + 1.0 );
25 if( rowIdx < size - 1 )
26 row.setValue( rowIdx + 1, -1.0 );
27 };
30
31 /***
32 * Now divide each matrix row by its largest element - with the use of iterators.
33 */
34 view.forAllRows(
35 [] __cuda_callable__( RowView& row )
36 {
38 for( auto element : row )
39 largest = TNL::max( largest, element.value() );
40 for( auto element : row )
41 element.value() /= largest;
42 } );
45}
46
47int
48main( int argc, char* argv[] )
49{
51 forRowsExample< TNL::Devices::Host >();
52
53#if defined( __CUDACC__ ) || defined( __HIP__ )
55 forRowsExample< TNL::Devices::GPU >();
56#endif
57}
void forAllRows(Function &&function) Method for parallel iteration over all matrix rows. T lowest(T... args) constexpr ResultType max(const T1 &a, const T2 &b) This function returns maximum of two numbers. Definition Math.h:49 The lambda function f, which is called for each matrix row (lines 18-25), have to accept parameter row with type RowView. This type is defined inside each TNL matrix and in the case of the dense matrix, it is TNL::Matrices::DenseMatrixRowView. We use the method TNL::Matrices::DenseMatrixRowView::getRowIndex to get the index of the matrix row being currently processed and method TNL::Matrices::DenseMatrixRowView::setElement which sets the value of the element with given column index (the first parameter). Next, on the lines 32-38, we call another lambda function which firstly find the largest element in each row (lines 33-35) and then it divides the matrix row by its value (lines 36-37). The result looks as follows: Getting matrix rows on host:
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-1 1:2 2:-1 3:0 4:0
Row: 2 -> 0:0 1:-1 2:3 3:-1 4:0
Row: 3 -> 0:0 1:0 2:-1 3:4 4:-1
Row: 4 -> 0:0 1:0 2:0 3:-1 4:5
Divide each matrix row by its largest element...
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-0.5 1:1 2:-0.5 3:0 4:0
Row: 2 -> 0:0 1:-0.333333 2:1 3:-0.333333 4:0
Row: 3 -> 0:0 1:0 2:-0.25 3:1 4:-0.25
Row: 4 -> 0:0 1:0 2:0 3:-0.2 4:1
Getting matrix rows on GPU (CUDA):
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-1 1:2 2:-1 3:0 4:0
Row: 2 -> 0:0 1:-1 2:3 3:-1 4:0
Row: 3 -> 0:0 1:0 2:-1 3:4 4:-1
Row: 4 -> 0:0 1:0 2:0 3:-1 4:5
Divide each matrix row by its largest element...
Row: 0 -> 0:1 1:-1 2:0 3:0 4:0
Row: 1 -> 0:-0.5 1:1 2:-0.5 3:0 4:0
Row: 2 -> 0:0 1:-0.333333 2:1 3:-0.333333 4:0
Row: 3 -> 0:0 1:0 2:-0.25 3:1 4:-0.25
Row: 4 -> 0:0 1:0 2:0 3:-0.2 4:1
Method forElementsThe next example demonstrates the method forElements (TNL::Matrices::DenseMatrix::forElements) which works in very similar way as the method getRow but it is slightly easier to use. It is also compatible with sparse matrices. See the following example: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8forElementsExample()
9{
10 TNL::Matrices::DenseMatrix< double, Device > matrix( 5, 5 );
11 auto matrixView = matrix.getView();
12
14 int rowIdx, int columnIdx_, int columnIdx, double& value ) // columnIdx is the same as localIdx for dense matrix
15 {
16 if( columnIdx <= rowIdx )
17 value = rowIdx + columnIdx;
18 };
19
20 matrixView.forElements( 0, matrix.getRows(), f ); // or matrix.forElements
22}
23
24int
25main( int argc, char* argv[] )
26{
28 forElementsExample< TNL::Devices::Host >();
29
30#if defined( __CUDACC__ ) || defined( __HIP__ )
32 forElementsExample< TNL::Devices::GPU >();
33#endif
34}
We do not need any matrix view and instead of calling parallelFor we call just the method forElements (line 18). The lambda function f (line 11) must accept the following parameters:
The result looks as follows: Creating matrix on host:
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:0 1:0 2:0 3:0 4:0
Row: 2 -> 0:0 1:0 2:0 3:0 4:0
Row: 3 -> 0:0 1:0 2:0 3:0 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:0
Creating matrix on GPU (CUDA):
Row: 0 -> 0:0 1:0 2:0 3:0 4:0
Row: 1 -> 0:2 1:0 2:0 3:0 4:0
Row: 2 -> 0:4 1:0 2:0 3:0 4:0
Row: 3 -> 0:6 1:0 2:0 3:0 4:0
Row: 4 -> 0:8 1:0 2:0 3:0 4:0
Wrapping existing data to dense matrix viewIn case when you have already allocated data for dense matrix (for example in some other library), you may wrap it to dense matrix view with a function TNL::Matrices::wrapDenseMatrix . See the following example: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Matrices/MatrixWrapping.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9wrapMatrixView()
10{
11 const int rows = 3;
12 const int columns = 4;
13 TNL::Containers::Vector< double, Device > valuesVector{
14 // clang-format off
15 1, 2, 3, 4,
16 5, 6, 7, 8,
17 9, 10, 11, 12,
18 // clang-format on
19 };
21
22 /***
23 * Wrap the array `values` to dense matrix view
24 */
27}
28
29int
30main( int argc, char* argv[] )
31{
33 wrapMatrixView< TNL::Devices::Host >();
34
35#if defined( __CUDACC__ ) || defined( __HIP__ )
37 wrapMatrixView< TNL::Devices::GPU >();
38#endif
39}
__cuda_callable__ const Value * getData() const Returns a const-qualified raw pointer to the data. DenseMatrixView< Real, Device, Index, Organization > wrapDenseMatrix(const Index &rows, const Index &columns, Real *values) Function for wrapping an array of values into a dense matrix view. Definition MatrixWrapping.h:39 Here we create dense matrix having three rows and four columns. We use TNL vector (TNL::Containers::Vector) only for allocation of the matrix elements (lines 12-15) and we get a pointer to the allocated array immediately (line 16). Next we use just the array to get dense matrix view with proper matrix dimensions (line 21). Note that we must explicitly state the device type as a template parameter of the function wrapDenseMatrix (TNL::Matrices::wrapDenseMatrix). Finally, we print the matrix to see if it is correct (line 22). The result looks as follows: Wrapping matrix view on host:
Matrix reads as:
Row: 0 -> 0:1 1:2 2:3 3:4
Row: 1 -> 0:5 1:6 2:7 3:8
Row: 2 -> 0:9 1:10 2:11 3:12
Wrapping matrix view on GPU (CUDA):
Matrix reads as:
Row: 0 -> 0:1 1:4 2:7 3:10
Row: 1 -> 0:2 1:5 2:8 3:11
Row: 2 -> 0:3 1:6 2:9 3:12
Sparse matricesSparse matrices are extremely important in a lot of numerical algorithms. They are used at situations when we need to operate with matrices having majority of the matrix elements equal to zero. In this case, only the non-zero matrix elements are stored with possibly some padding zeros used for memory alignment. This is necessary mainly on GPUs. See the Overview of matrix types for the differences in memory requirements. Major disadvantage of sparse matrices is that there are a lot of different formats for their storage in memory. Though CSR (Compressed Sparse Row) format is the most popular of all, especially for GPUs, there are many other formats. Often their performance differ significantly for various matrices. So it is a good idea to test several sparse matrix formats if you want to get the best performance. In TNL, there is one templated class TNL::Matrices::SparseMatrix representing general sparse matrices. The change of underlying matrix format can be done just by changing one template parameter. The list of the template parameters is as follows:
If Real is set to bool, we get a binary matrix for which the non-zero elements can be equal only to one and so the matrix elements values are not stored explicitly in the memory. This can significantly reduce the memory requirements and also increase performance. In the following text we will show how to create and setup sparse matrices. Setting of row capacitiesLarger sparse matrices are created in two steps:
See the following example which creates lower triangular matrix like this one \[\left( \begin{array}{ccccc} 1 & 0 & 0 & 0 & 0 \\ 2 & 1 & 0 & 0 & 0 \\ 3 & 2 & 1 & 0 & 0 \\ 4 & 3 & 2 & 1 & 0 \\ 5 & 4 & 3 & 2 & 1 \end{array} \right). \] 1#include <iostream>
2#include <TNL/Containers/Vector.h>
3#include <TNL/Matrices/SparseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9setRowCapacitiesExample()
10{
11 TNL::Matrices::SparseMatrix< double, Device > matrix( 5, 5 );
12 TNL::Containers::Vector< int, Device > rowCapacities{ 1, 2, 3, 4, 5 };
13 matrix.setRowCapacities( rowCapacities );
14 for( int row = 0; row < 5; row++ )
15 for( int column = 0; column <= row; column++ )
16 matrix.setElement( row, column, row - column + 1 );
17
19}
20
21int
22main( int argc, char* argv[] )
23{
25 setRowCapacitiesExample< TNL::Devices::Host >();
26
27#if defined( __CUDACC__ ) || defined( __HIP__ )
29 setRowCapacitiesExample< TNL::Devices::GPU >();
30#endif
31}
The method TNL::Matrices::SparseMatrix::setRowCapacities reads the required capacities of the matrix rows from a vector (or similar container - TNL::Containers::Array, TNL::Containers::ArrayView, TNL::Containers::Vector and TNL::Containers::VectorView) which has the same number of elements as the number of matrix rows and each element defines the capacity of the related row. The result looks as follows: Creating matrix on CPU ...
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Creating matrix on GPU (CUDA) ...
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
There are constructors which also set the row capacities. The first one uses a vector: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Containers/Vector.h>
4#include <TNL/Devices/Host.h>
5
6template< typename Device >
7void
8initializerListExample()
9{
10 TNL::Containers::Vector< int, Device > rowCapacities{ 1, 2, 3, 4, 5 };
12 rowCapacities, // row capacities
13 6,
14 }; // number of matrix columns
15
17 for( int column = 0; column <= row; column++ )
18 matrix.setElement( row, column, row - column + 1 );
20}
21
22int
23main( int argc, char* argv[] )
24{
26 initializerListExample< TNL::Devices::Host >();
27
28#if defined( __CUDACC__ ) || defined( __HIP__ )
30 initializerListExample< TNL::Devices::GPU >();
31#endif
32}
__cuda_callable__ IndexType getRows() const Returns number of matrix rows. __cuda_callable__ void setElement(IndexType row, IndexType column, const RealType &value) Sets element at given row and column to given value. The second one uses an initializer list: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7initializerListExample()
8{
10 { 1, 2, 3, 4, 5 }, // row capacities
11 6,
12 }; // number of matrix columns
13
15 for( int column = 0; column <= row; column++ )
16 matrix.setElement( row, column, row - column + 1 );
18}
19
20int
21main( int argc, char* argv[] )
22{
24 initializerListExample< TNL::Devices::Host >();
25
26#if defined( __CUDACC__ ) || defined( __HIP__ )
28 initializerListExample< TNL::Devices::GPU >();
29#endif
30}
The result of both examples looks as follows: Creating matrices on CPU ...
General sparse matrix:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Creating matrices on GPU (CUDA) ...
General sparse matrix:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Initializer listSmall matrices can be initialized by a constructor with an initializer list. We assume having the following sparse matrix \[\left( \begin{array}{ccccc} 1 & 0 & 0 & 0 & 0 \\ -1 & 2 & -1 & 0 & 0 \\ 0 & -1 & 2 & -1 & 0 \\ 0 & 0 & -1 & 2 & -1 \\ 0 & 0 & 0 & -1 & 0 \end{array} \right). \] It can be created with the initializer list constructor like we shows in the following example: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7initializerListExample()
8{
10 // number of matrix rows
11 5,
12 // number of matrix columns
13 5,
14 // matrix elements definition
15 {
16 // clang-format off
17 { 0, 0, 2.0 },
18 { 1, 0, -1.0 }, { 1, 1, 2.0 }, { 1, 2, -1.0 },
19 { 2, 1, -1.0 }, { 2, 2, 2.0 }, { 2, 3, -1.0 },
20 { 3, 2, -1.0 }, { 3, 3, 2.0 }, { 3, 4, -1.0 },
21 { 4, 4, 2.0 },
22 // clang-format on
23 } );
24
26}
27
28int
29main( int argc, char* argv[] )
30{
32 initializerListExample< TNL::Devices::Host >();
33
34#if defined( __CUDACC__ ) || defined( __HIP__ )
36 initializerListExample< TNL::Devices::GPU >();
37#endif
38}
The constructor accepts the following parameters (lines 9-17):
The constructor also accepts Real and Index allocators (TNL::Allocators) but the default ones are used in this example. A method setElements (TNL::Matrices::SparseMatrix::setElements) works the same way: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8setElementsExample()
9{
11 // matrix elements definition
12 matrix.setElements(
13 {
14 // clang-format off
15 { 0, 0, 2.0 },
16 { 1, 0, -1.0 }, { 1, 1, 2.0 }, { 1, 2, -1.0 },
17 { 2, 1, -1.0 }, { 2, 2, 2.0 }, { 2, 3, -1.0 },
18 { 3, 2, -1.0 }, { 3, 3, 2.0 }, { 3, 4, -1.0 },
19 { 4, 4, 2.0 },
20 // clang-format on
21 } );
22
24}
25
26int
27main( int argc, char* argv[] )
28{
30 setElementsExample< TNL::Devices::Host >();
31
32#if defined( __CUDACC__ ) || defined( __HIP__ )
34 setElementsExample< TNL::Devices::GPU >();
35#endif
36}
void setElements(const std::initializer_list< std::tuple< Index, Index, Real > > &data, MatrixElementsEncoding encoding=MatrixElementsEncoding::Complete) This method sets the sparse matrix elements from initializer list. In this example, we create the matrix in two steps. Firstly we use constructor with only matrix dimensions as parameters (line 9) and next we set the matrix elements by setElements method (lines 10-15). The result of both examples looks as follows: Creating matrices on CPU ...
General sparse matrix:
Row: 0 -> 0:2
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 4:2
Creating matrices on GPU (CUDA) ...
General sparse matrix:
Row: 0 -> 0:2
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 4:2
STL mapThe constructor which creates the sparse matrix from std::map is useful especially in situations when you cannot estimate the matrix row capacities in advance. You can first store the matrix elements in std::map data structure in a COO format manner. It means that each entry of the map is the following pair: std::pair( std::pair( row_index, column_index ), element_value )
which defines one matrix element at given coordinates (row_index,column_index) with given value (element_value). Of course, you can insert such entries into the map in arbitrary order. When it is complete, you pass the map to the sparse matrix. See the following example: 1#include <iostream>
2#include <map>
3#include <utility>
4#include <TNL/Matrices/SparseMatrix.h>
5#include <TNL/Devices/Host.h>
6
7template< typename Device >
8void
9initializerListExample()
10{
23
24 TNL::Matrices::SparseMatrix< double, Device > matrix( 5, 5, map );
25
27}
28
29int
30main( int argc, char* argv[] )
31{
33 initializerListExample< TNL::Devices::Host >();
34
35#if defined( __CUDACC__ ) || defined( __HIP__ )
37 initializerListExample< TNL::Devices::GPU >();
38#endif
39}
T insert(T... args) T make_pair(T... args) The method setElements (TNL::Matrices::SparseMatrix::setElements) works the same way for already existing instances of sparse matrix: 1#include <iostream>
2#include <map>
3#include <utility>
4#include <TNL/Matrices/SparseMatrix.h>
5#include <TNL/Devices/Host.h>
6
7template< typename Device >
8void
9setElementsExample()
10{
23
24 TNL::Matrices::SparseMatrix< double, Device > matrix( 5, 5 );
25 matrix.setElements( map );
26
28}
29
30int
31main( int argc, char* argv[] )
32{
34 setElementsExample< TNL::Devices::Host >();
35
36#if defined( __CUDACC__ ) || defined( __HIP__ )
38 setElementsExample< TNL::Devices::GPU >();
39#endif
40}
The result of both examples looks as follows: Creating matrices on CPU ...
General sparse matrix:
Row: 0 -> 0:2
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 4:2
Creating matrices on GPU (CUDA) ...
General sparse matrix:
Row: 0 -> 0:2
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 4:2
Note, however, that the map can be constructed only on CPU and not on GPU. It requires allocation of additional memory on the host system (CPU) and if the target sparse matrix resided on GPU, the matrix elements must be copied on GPU. This is the reason, why this way of the sparse matrix setup is inefficient compared to other methods. Methods setElement and addElementAnother way of setting the sparse matrix is by means of the methods setElement and addElement (TNL::Matrices::SparseMatrix::setElement, TNL::Matrices::SparseMatrix::addElement). The method can be called from both host (CPU) and device (GPU) if the matrix is allocated there. Note, however, that if the matrix is allocated on GPU and the methods are called from CPU there will be significant performance drop because the matrix elements will be transferred one-by-one separately. However, if the matrix elements setup is not a critical part of your algorithm this can be an easy way how to do it. See the following example: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/SparseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9setElements()
10{
11 TNL::Matrices::SparseMatrix< double, Device > matrix( { 1, 1, 1, 1, 1 }, 5 );
12
13 /****
14 * Get the matrix view.
15 */
17 for( int i = 0; i < 5; i++ )
18 view.setElement( i, i, i );
19
22
24 {
25 view.setElement( i, i, -i );
26 };
27
28 TNL::Algorithms::parallelFor< Device >( 0, 5, f );
29
32}
33
34int
35main( int argc, char* argv[] )
36{
38 setElements< TNL::Devices::Host >();
39
40#if defined( __CUDACC__ ) || defined( __HIP__ )
42 setElements< TNL::Devices::GPU >();
43#endif
44}
We first allocate matrix with five rows (it is given by the size of the initializer list) and columns and we set capacity each row to one (line 12). The first for-loop (lines 17-19) runs on CPU no matter where the matrix is allocated. After printing the matrix (lines 21-22), we call the lambda function f (lines 24-26) with a help of parallelFor (line 28) which is device sensitive and so it runs on CPU or GPU depending on where the matrix is allocated. The result looks as follows: Set elements on host:
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 ->
Row: 1 -> 1:-1
Row: 2 -> 2:-2
Row: 3 -> 3:-3
Row: 4 -> 4:-4
Set elements on GPU (CUDA):
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 ->
Row: 1 -> 1:-1
Row: 2 -> 2:-2
Row: 3 -> 3:-3
Row: 4 -> 4:-4
The method addElement (TNL::Matrices::SparseMatrix::addElement) adds a value to specific matrix element. Otherwise, it behaves the same as setElement. See the following example: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7addElements()
8{
9 TNL::Matrices::SparseMatrix< double, Device > matrix( { 5, 5, 5, 5, 5 }, 5 );
10 auto matrixView = matrix.getView();
11
12 for( int i = 0; i < 5; i++ )
14
16
17 for( int i = 0; i < 5; i++ )
18 for( int j = 0; j < 5; j++ )
20
22}
23
24int
25main( int argc, char* argv[] )
26{
28 addElements< TNL::Devices::Host >();
29
30#if defined( __CUDACC__ ) || defined( __HIP__ )
32 addElements< TNL::Devices::GPU >();
33#endif
34}
__cuda_callable__ void addElement(IndexType row, IndexType column, const RealType &value, const RealType &thisElementMultiplicator=1.0) Add element at given row and column to given value. The result looks as follows: Add elements on host:
Initial matrix is:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix after addition is:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:6 2:1 3:1 4:1
Row: 2 -> 0:1 1:1 2:11 3:1 4:1
Row: 3 -> 0:1 1:1 2:1 3:16 4:1
Row: 4 -> 0:1 1:1 2:1 3:1 4:21
Add elements on GPU (CUDA):
Initial matrix is:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix after addition is:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:6 2:1 3:1 4:1
Row: 2 -> 0:1 1:1 2:11 3:1 4:1
Row: 3 -> 0:1 1:1 2:1 3:16 4:1
Row: 4 -> 0:1 1:1 2:1 3:1 4:21
Method getRowMore efficient method, especially for GPUs, is to combine getRow (TNL::Matrices::SparseMatrix::getRow) method with parallelFor and lambda function as the following example demonstrates: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/SparseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9getRowExample()
10{
11 /***
12 * Set the following matrix (dots represent zero matrix elements):
13 *
14 * / 2 . . . . \
15 * | 1 2 1 . . |
16 * | . 1 2 1. . |
17 * | . . 1 2 1 |
18 * \ . . . . 2 /
19 */
20 const int size = 5;
21 TNL::Matrices::SparseMatrix< double, Device > matrix( { 1, 3, 3, 3, 1 }, size );
22 auto view = matrix.getView();
23
24 /***
25 * Set the matrix elements.
26 */
28 {
30 if( rowIdx == 0 ) {
31 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
32 }
33 else if( rowIdx == size - 1 ) {
34 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
35 }
36 else {
37 row.setElement( 0, rowIdx - 1, 1.0 ); // elements below the diagonal
38 row.setElement( 1, rowIdx, 2.0 ); // diagonal element
39 row.setElement( 2, rowIdx + 1, 1.0 ); // elements above the diagonal
40 }
41 };
42 TNL::Algorithms::parallelFor< Device >( 0, matrix.getRows(), f );
44}
45
46int
47main( int argc, char* argv[] )
48{
50 getRowExample< TNL::Devices::Host >();
51
52#if defined( __CUDACC__ ) || defined( __HIP__ )
54 getRowExample< TNL::Devices::GPU >();
55#endif
56}
On the line 21, we create small matrix having five rows (number of rows is given by the size of the initializer list ) and columns (number of columns is given by the second parameter) and we set each row capacity to one or three (particular elements of the initializer list). On the line 41, we call parallelFor to iterate over all matrix rows. Each row is processed by the lambda function f (lines 24-36). In the lambda function, we first fetch a sparse matrix row (TNL::Matrices::SparseMatrixRowView) (line 25) which serves for accessing particular matrix elements in the matrix row. This object has a method setElement (TNL::Matrices::SparseMatrixRowView::setElement) accepting three parameters:
The result looks as follows: Getting matrix rows on host:
Row: 0 -> 0:2
Row: 1 -> 0:1 1:2 2:1
Row: 2 -> 1:1 2:2 3:1
Row: 3 -> 2:1 3:2 4:1
Row: 4 -> 4:2
Getting matrix rows on GPU (CUDA):
Row: 0 -> 0:2
Row: 1 -> 0:1 1:2 2:1
Row: 2 -> 1:1 2:2 3:1
Row: 3 -> 2:1 3:2 4:1
Row: 4 -> 4:2
Method forRowsThe method forRows (TNL::Matrices::SparseMatrix::forRows) calls the method getRow (TNL::Matrices::SparseMatrix::getRow) in parallel. See the following example which has the same effect as the previous one but it is slightly simpler: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8forRowsExample()
9{
10 /***
11 * Set the following matrix (dots represent zero matrix elements):
12 *
13 * / 2 . . . . \
14 * | 1 2 1 . . |
15 * | . 1 2 1. . |
16 * | . . 1 2 1 |
17 * \ . . . . 2 /
18 */
19 const int size( 5 );
21 using RowView = typename MatrixType::RowView;
22 MatrixType matrix( { 1, 3, 3, 3, 1 }, size );
23 auto matrixView = matrix.getView();
24
25 /***
26 * Set the matrix elements.
27 */
29 {
30 const int rowIdx = row.getRowIndex();
31 if( rowIdx == 0 ) {
32 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
33 }
34 else if( rowIdx == size - 1 ) {
35 row.setElement( 0, rowIdx, 2.0 ); // diagonal element
36 }
37 else {
38 row.setElement( 0, rowIdx - 1, 1.0 ); // elements below the diagonal
39 row.setElement( 1, rowIdx, 2.0 ); // diagonal element
40 row.setElement( 2, rowIdx + 1, 1.0 ); // elements above the diagonal
41 }
42 };
43 matrixView.forAllRows( f ); // or matrix.forAllRows
45
46 /***
47 * Divide each matrix row by a sum of all elements in the row - with use of iterators.
48 */
49 matrix.forAllRows(
50 [] __cuda_callable__( RowView& row )
51 {
52 double sum = 0.0;
53 for( auto element : row )
54 sum += element.value();
55 for( auto element : row )
56 element.value() /= sum;
57 } );
60}
61
62int
63main( int argc, char* argv[] )
64{
66 forRowsExample< TNL::Devices::Host >();
67
68#if defined( __CUDACC__ ) || defined( __HIP__ )
70 forRowsExample< TNL::Devices::GPU >();
71#endif
72}
The differences are:
On the lines 46-52, we call a lambda function which computes sum of all elements in a row (lines 47-49) and it divides the row by the sum then (lines 50-51). The result looks as follows: Getting matrix rows on host:
Row: 0 -> 0:2
Row: 1 -> 0:1 1:2 2:1
Row: 2 -> 1:1 2:2 3:1
Row: 3 -> 2:1 3:2 4:1
Row: 4 -> 4:2
Divide each matrix row by a sum of all elements in the row ...
Row: 0 -> 0:1
Row: 1 -> 0:0.25 1:0.5 2:0.25
Row: 2 -> 1:0.25 2:0.5 3:0.25
Row: 3 -> 2:0.25 3:0.5 4:0.25
Row: 4 -> 4:1
Getting matrix rows on GPU (CUDA):
Row: 0 -> 0:2
Row: 1 -> 0:1 1:2 2:1
Row: 2 -> 1:1 2:2 3:1
Row: 3 -> 2:1 3:2 4:1
Row: 4 -> 4:2
Divide each matrix row by a sum of all elements in the row ...
Row: 0 -> 0:1
Row: 1 -> 0:0.25 1:0.5 2:0.25
Row: 2 -> 1:0.25 2:0.5 3:0.25
Row: 3 -> 2:0.25 3:0.5 4:0.25
Row: 4 -> 4:1
Method forElementsFinally, another efficient way of setting the nonzero matrix elements, is use of the method forElements (TNL::Matrices::SparseMatrix::forElements). It requires indexes of the range of rows (begin and end) to be processed and a lambda function function which is called for each nonzero element. The lambda function provides the following data:
See the following example: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8forElementsExample()
9{
10 TNL::Matrices::SparseMatrix< double, Device > matrix( { 1, 2, 3, 4, 5 }, 5 );
11 auto matrixView = matrix.getView();
12
14 {
15 // This is important, some matrix formats may allocate more matrix elements
16 // than we requested. These padding elements are processed here as well.
17 if( rowIdx >= localIdx ) {
18 columnIdx = localIdx;
19 value = rowIdx + localIdx + 1;
20 }
21 };
22
25}
26
27int
28main( int argc, char* argv[] )
29{
31 forElementsExample< TNL::Devices::Host >();
32
33#if defined( __CUDACC__ ) || defined( __HIP__ )
35 forElementsExample< TNL::Devices::GPU >();
36#endif
37}
void forElements(IndexType begin, IndexType end, Function &&function) const Method for iteration over all matrix elements for (constant instances). On the line 9, we allocate a lower triangular matrix by setting the row capacities as {1,2,3,4,5}. On the line 11, we prepare lambda function f which we execute on the line 22 just by calling the method forElements (TNL::Matrices::SparseMatrix::forElements). This method takes the range of matrix rows as the first two parameters and the lambda function as the last parameter. The lambda function receives parameters mentioned above (see the line 11). We first check if the matrix element coordinates (rowIdx and localIdx) points to an element lying before the matrix diagonal or on the diagonal (line 12). In case of the lower triangular matrix in our example, the local index is in fact the same as the column index \[\left( \begin{array}{ccccc} 0 & . & . & . & . \\ 0 & 1 & . & . & . \\ 0 & 1 & 2 & . & . \\ 0 & 1 & 2 & 3 & . \\ 0 & 1 & 2 & 3 & 4 \end{array} \right) \] If we call the method forElements (TNL::Matrices::SparseMatrix::forElements) to setup the matrix elements for the first time, the parameter columnIdx has no sense because the matrix elements and their column indexes were not set yet. Therefore it is important that the test on the line 12 reads as if( rowIdx < localIdx )
because if( rowIdx < columnIdx )
would not make sense. If we pass through this test, the matrix element lies in the lower triangular part of the matrix and we may set the matrix elements which is done on the lines 17 and 18. The column index (columnIdx) is set to local index (line 17) and value is set on the line 18. The result looks as follows: Creating matrix on host:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:3
Row: 2 -> 0:3 1:4 2:5
Row: 3 -> 0:4 1:5 2:6 3:7
Row: 4 -> 0:5 1:6 2:7 3:8 4:9
Creating matrix on GPU (CUDA):
Row: 0 -> 0:1
Row: 1 -> 0:2 1:3
Row: 2 -> 0:3 1:4 2:5
Row: 3 -> 0:4 1:5 2:6 3:7
Row: 4 -> 0:5 1:6 2:7 3:8 4:9
Wrapping existing data to sparse matrix viewStandard sparse matrix format like CSR and Ellpack store the matrix elements in specifically defined arrays. In case that you have already allocated them (for example in some other library), they can be wrapped into a sparse matrix view with given matrix format. This can be done by means of functions TNL::Matrices::wrapCSRMatrix and TNL::Matrices::wrapEllpackMatrix . See the following example for demonstration of the CSR format: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Matrices/MatrixWrapping.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9wrapMatrixView()
10{
11 /***
12 * Encode the following matrix to CSR format...
13 *
14 * / 1 2 0 0 \.
15 * | 0 6 0 0 |
16 * | 9 0 0 0 |
17 * \ 0 0 15 16 /
18 */
19 const int rows = 4;
20 const int columns = 4;
21 TNL::Containers::Vector< double, Device > valuesVector{ 1, 2, 6, 9, 15, 16 };
22 TNL::Containers::Vector< int, Device > columnIndexesVector{ 0, 1, 1, 0, 2, 3 };
23 TNL::Containers::Vector< int, Device > rowPointersVector{ 0, 2, 3, 4, 6 };
24
28
29 /***
30 * Wrap the arrays `rowPointers, `values` and `columnIndexes` to sparse matrix view
31 */
32 auto matrix = TNL::Matrices::wrapCSRMatrix< Device >( rows, columns, rowPointers, values, columnIndexes );
33
35}
36
37int
38main( int argc, char* argv[] )
39{
41 wrapMatrixView< TNL::Devices::Host >();
42
43#if defined( __CUDACC__ ) || defined( __HIP__ )
45 wrapMatrixView< TNL::Devices::GPU >();
46#endif
47}
SparseMatrixView< Real, Device, Index, GeneralMatrix, Algorithms::Segments::CSRView > wrapCSRMatrix(const Index &rows, const Index &columns, Index *rowPointers, Real *values, Index *columnIndexes) Function for wrapping of arrays defining CSR format into a sparse matrix view. Definition MatrixWrapping.h:74 We create sparse matrix having four rows and four columns (line 19). We use TNL vector (TNL::Containers::Vector) to allocate arrays necessary for the CSR format:
Next we turn the vectors into C style pointers (lines 24-26) to wrap them into sparse matrix view (line 31). Note, that we must explicitly state the device on which the arrays are allocated. Finlay we print the matrix to check the correctness (line 33). The result looks as follows: Wrapping matrix view on host:
Matrix reads as:
Row: 0 -> 0:1 1:2
Row: 1 -> 1:6
Row: 2 -> 0:9
Row: 3 -> 2:15 3:16
Wrapping matrix view on GPU (CUDA):
Matrix reads as:
Row: 0 -> 0:1 1:2
Row: 1 -> 1:6
Row: 2 -> 0:9
Row: 3 -> 2:15 3:16
Wrapping data corresponding with the Ellpack format is very similar as we can see in the following example: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Matrices/MatrixWrapping.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9wrapMatrixView()
10{
11 /***
12 * Encode the following matrix to Ellpack format...
13 *
14 * / 1 2 0 0 \.
15 * | 0 6 0 0 |
16 * | 9 0 0 0 |
17 * \ 0 0 15 16 /
18 */
19 const int rows = 4;
20 const int columns = 4;
21 TNL::Containers::Vector< double, Device > valuesVector{ 1, 2, 6, 0, 9, 0, 15, 16 };
22 TNL::Containers::Vector< int, Device > columnIndexesVector{ 0, 1, 1, -1, 0, -1, 2, 3 };
23
26
27 /***
28 * Wrap the arrays `values` and `columnIndexes` to sparse matrix view
29 */
30 auto matrix = TNL::Matrices::wrapEllpackMatrix< Device, TNL::Algorithms::Segments::RowMajorOrder >(
31 rows, columns, 2, values, columnIndexes );
32
34}
35
36int
37main( int argc, char* argv[] )
38{
40 wrapMatrixView< TNL::Devices::Host >();
41
42#if defined( __CUDACC__ ) || defined( __HIP__ )
44 wrapMatrixView< TNL::Devices::GPU >();
45#endif
46}
auto wrapEllpackMatrix(const Index rows, const Index columns, const Index nonzerosPerRow, Real *values, Index *columnIndexes) -> decltype(EllpackMatrixWrapper< Device, Organization, Real, Index, Alignment >::wrap(rows, columns, nonzerosPerRow, values, columnIndexes)) Function for wrapping of arrays defining Ellpack format into a sparse matrix view. Definition MatrixWrapping.h:135 We encode the same sparse matrix as in the previous example. The essence of the Ellpack format is that we allocate the same number of matrix elements for each row which is two in our example. For some matrix rows we use the padding zeros for which we set the column index to -1 (line 21). Therefore the size of valuesVector and columnIndexesVector equals number of matrix rows times number of matrix elements allocated in each row. As before, we turn the vectors into C style pointers (lines 23-24) and wrap them into sparse matrix view with Ellpack format (line 29). Note that we must state the device on which the arrays are allocated explicitly and also the matrix elements organization, which is TNL::Algorithms::Segments::RowMajorOrder in this case. For Ellpack matrix stored on GPU, TNL::Algorithms::Segments::ColumnMajorOrder is preferred. The result looks as follows: Wrapping matrix view on host:
Matrix reads as:
Row: 0 -> 0:1 1:2
Row: 1 -> 1:6
Row: 2 -> 0:9
Row: 3 -> 2:15 3:16
Wrapping matrix view on GPU (CUDA):
Matrix reads as:
Row: 0 -> 0:1 1:2
Row: 1 -> 1:6
Row: 2 -> 0:9
Row: 3 -> 2:15 3:16
Symmetric sparse matricesFor sparse symmetric matrices, TNL offers a format storing only a half of the matrix elements. More precisely, only the matrix diagonal and the elements bellow are stored in the memory. The matrix elements above the diagonal are deduced from those bellow. If such a symmetric format is used on GPU, atomic operations must be used in some matrix operations. For this reason, symmetric matrices can be combined only with matrix elements values expressed in float or double type. An advantage of the symmetric formats is lower memory consumption. Since less data need to be transferred from the memory, better performance might be observed. In some cases, however, the use of atomic operations on GPU may cause performance drop. Mostly we can see approximately the same performance compared to general formats but we can profit from lower memory requirements which is appreciated especially on GPU. The following example shows how to create symmetric sparse matrix. 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7symmetricSparseMatrixExample()
8{
9 TNL::Matrices::SparseMatrix< double, Device, int, TNL::Matrices::SymmetricMatrix > symmetricMatrix(
10 5, // number of matrix rows
11 5, // number of matrix columns
12 {
13 // matrix elements definition
14 // clang-format off
15 { 0, 0, 1.0 },
16 { 1, 0, 2.0 }, { 1, 1, 1.0 },
17 { 2, 0, 3.0 }, { 2, 2, 1.0 },
18 { 3, 0, 4.0 }, { 3, 3, 1.0 },
19 { 4, 0, 5.0 }, { 4, 4, 1.0 },
20 // clang-format on
21 },
23
25
26 TNL::Containers::Vector< double, Device > inVector( 5, 1.0 );
27 TNL::Containers::Vector< double, Device > outVector( 5, 0.0 );
28 symmetricMatrix.vectorProduct( inVector, outVector );
30}
31
32int
33main( int argc, char* argv[] )
34{
36 symmetricSparseMatrixExample< TNL::Devices::Host >();
37
38#if defined( __CUDACC__ ) || defined( __HIP__ )
40 symmetricSparseMatrixExample< TNL::Devices::GPU >();
41#endif
42}
void vectorProduct(const InVector &inVector, OutVector &outVector, ComputeRealType matrixMultiplicator=1.0, ComputeRealType outVectorMultiplicator=0.0, IndexType begin=0, IndexType end=0, const Algorithms::Segments::LaunchConfiguration &launchConfig=Algorithms::Segments::LaunchConfiguration{}) const Computes product of matrix and vector. @ SymmetricLower Only lower part of the matrix is provided. Definition MatrixBase.h:36 We construct matrix of the following form \[\left( \begin{array}{ccccc} 1 & \color{grey}{2} & \color{grey}{3} & \color{grey}{4} & \color{grey}{5} \\ 2 & 1 & & & \\ 3 & & 1 & & \\ 4 & & & 1 & \\ 5 & & & & 1 \end{array} \right) \] The elements depicted in grey color are not stored in the memory. The main difference, compared to creation of general sparse matrix, is on line 9 where we state that the matrix is symmetric by setting the matrix type to TNL::Matrices::SymmetricMatrix. Next we set only the diagonal elements and those lying bellow the diagonal (lines 13-17). When we print the matrix (line 19) we can see also the symmetric part above the diagonal. Next we test product of matrix and vector (lines 21-23). The result looks as follows: Creating matrix on CPU ...
Symmetric sparse matrix:
Row: 0 -> 0:1 1:2 2:3 3:4 4:5
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 2:1
Row: 3 -> 0:4 3:1
Row: 4 -> 0:5 4:1
Product with vector [ 1, 1, 1, 1, 1 ] is [ 15, 3, 4, 5, 6 ]
Creating matrix on GPU (CUDA) ...
Symmetric sparse matrix:
Row: 0 -> 0:1 1:2 2:3 3:4 4:5
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 2:1
Row: 3 -> 0:4 3:1
Row: 4 -> 0:5 4:1
Product with vector [ 1, 1, 1, 1, 1 ] is [ 15, 3, 4, 5, 6 ]
When a reduction over a symmetric sparse matrix has to account for the implicit upper part, the fetch or keep lambda must mirror the stored lower-triangular elements into the result slot of the corresponding row. Since rows are reduced in parallel, such cross-row updates can run concurrently with the keep lambda of the target row and must be atomic, or accumulated in a separate array and combined after the reduction. Modifying the element passed to fetch does not need atomics, because each stored element is visited exactly once. See Symmetric Matrices for details. Warning: Assignment of symmetric sparse matrix to general sparse matrix does not give correct result, currently. Only the diagonal and the lower part of the matrix is assigned. Binary sparse matricesIf the matrix element value type (i.e. Real type) is set to bool the matrix elements can be only 1 or 0. So in the sparse matrix formats, where we do not store the zero matrix elements, explicitly stored elements can have only one possible value which is 1. Therefore we do not need to store the values, only the positions of the nonzero elements. The array values, which usually stores the matrix elements values, can be completely omitted and we can reduce the memory requirements. The following table shows how much we can reduce the memory consumption when using binary matrix instead of common sparse matrix using float or double types:
The following example demonstrates the use of binary matrix: 1#include <iostream>
2#include <TNL/Matrices/SparseMatrix.h>
3#include <TNL/Algorithms/Segments/CSR.h>
4#include <TNL/Devices/Host.h>
5
6template< typename Device >
7void
8binarySparseMatrixExample()
9{
10 TNL::Matrices::SparseMatrix< bool, Device, int > binaryMatrix(
11 // number of matrix rows
12 5,
13 // number of matrix columns
14 5,
15 // matrix elements definition
16 {
17 // clang-format off
18 { 0, 0, 1.0 }, { 0, 1, 2.0 }, { 0, 2, 3.0 }, { 0, 3, 4.0 }, { 0, 4, 5.0 },
19 { 1, 0, 2.0 }, { 1, 1, 1.0 },
20 { 2, 0, 3.0 }, { 2, 2, 1.0 },
21 { 3, 0, 4.0 }, { 3, 3, 1.0 },
22 { 4, 0, 5.0 }, { 4, 4, 1.0 },
23 // clang-format on
24 } );
25
27
28 TNL::Containers::Vector< double, Device > inVector( 5, 1.1 );
29 TNL::Containers::Vector< double, Device > outVector( 5, 0.0 );
30 binaryMatrix.vectorProduct( inVector, outVector );
32
34 binaryMatrix2;
35 binaryMatrix2 = binaryMatrix;
36 binaryMatrix2.vectorProduct( inVector, outVector );
37 std::cout << "Product with vector in double precision " << inVector << " is " << outVector << "\n\n";
38}
39
40int
41main( int argc, char* argv[] )
42{
44 binarySparseMatrixExample< TNL::Devices::Host >();
45
46#if defined( __CUDACC__ ) || defined( __HIP__ )
48 binarySparseMatrixExample< TNL::Devices::GPU >();
49#endif
50}
All we need to do is set the Real type to bool as we can see on the line 9. We can see that even though we set different values to different matrix elements (lines 14-18) at the end all of them are turned into ones (printing of the matrix on the line 20). There is an issue, however, which is demonstrated on the product of the matrix with a vector. Nonbinary matrices compute all operations using the Real type. If it is set to bool operations like SpMV would not get correct solution. Therefore sparse matrices use another type called ComputeReal which is the 6th template parameter of TNL::Matrices::SparseMatrix. By default it is set to Index type but it can be changed by the user. On the lines 26-29 we show how to change this type to double and what is the effect of it (correct result of matrix-vector multiplication). The result looks as follows: Creating matrix on CPU ...
Binary sparse matrix:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:1
Row: 2 -> 0:1 2:1
Row: 3 -> 0:1 3:1
Row: 4 -> 0:1 4:1
Product with vector [ 1.1, 1.1, 1.1, 1.1, 1.1 ] is [ 5, 2, 2, 2, 2 ]
Product with vector in double precision [ 1.1, 1.1, 1.1, 1.1, 1.1 ] is [ 5.5, 2.2, 2.2, 2.2, 2.2 ]
Creating matrix on GPU (CUDA) ...
Binary sparse matrix:
Row: 0 -> 0:1 1:1 2:1 3:1 4:1
Row: 1 -> 0:1 1:1
Row: 2 -> 0:1 2:1
Row: 3 -> 0:1 3:1
Row: 4 -> 0:1 4:1
Product with vector [ 1.1, 1.1, 1.1, 1.1, 1.1 ] is [ 5, 2, 2, 2, 2 ]
Product with vector in double precision [ 1.1, 1.1, 1.1, 1.1, 1.1 ] is [ 5.5, 2.2, 2.2, 2.2, 2.2 ]
Tridiagonal matricesTridiagonal matrix format serves for specific matrix pattern when the nonzero matrix elements can be placed only at the diagonal and immediately next to the diagonal. Here is an example: \[\left( \begin{array}{ccccccc} 2 & -1 & . & . & . & . \\ -1 & 2 & -1 & . & . & . \\ . & -1 & 2 & -1 & . & . \\ . & . & -1 & 2 & -1 & . \\ . & . & . & -1 & 2 & -1 \\ . & . & . & . & -1 & 2 \end{array} \right) \] An advantage is that we do not store the column indexes explicitly as it is in TNL::Matrices::SparseMatrix. This can reduce significantly the memory requirements which also means better performance. See the following table for the storage requirements comparison between TNL::Matrices::TridiagonalMatrix and TNL::Matrices::SparseMatrix.
Tridiagonal matrix is a templated class defined in the namespace TNL::Matrices. It has five template parameters:
For better alignment in the memory the tridiagonal format is organized like if there were three nonzero matrix elements in each row. This is not true for example in the first row where there is no matrix element on the left side of the diagonal. The same happens on the last row of the matrix. We have to add even the artificial matrix elements like this: \[\begin{array}{c} 0 \\ . \\ . \\ . \\ . \\ . \end{array} \left( \begin{array}{ccccccc} 2 & -1 & . & . & . & . \\ -1 & 2 & -1 & . & . & . \\ . & -1 & 2 & -1 & . & . \\ . & . & -1 & 2 & -1 & . \\ . & . & . & -1 & 2 & -1 \\ . & . & . & . & -1 & 2 \end{array} \right) \begin{array}{c} . \\ . \\ . \\ . \\ . \\ 0 \end{array} \] If the tridiagonal matrix has more rows then columns, we have to extend the last two rows with nonzero elements in this way \[\left( \begin{array}{ccccccc} 2 & -1 & . & . & . & . \\ -1 & 2 & -1 & . & . & . \\ . & -1 & 2 & -1 & . & . \\ . & . & -1 & 2 & -1 & . \\ . & . & . & -1 & 2 & -1 \\ . & . & . & . & -1 & 2 \\ . & . & . & . & . & -1 \end{array} \right) \rightarrow \begin{array}{c} 0 \\ . \\ . \\ . \\ . \\ . \\ . \end{array} \left( \begin{array}{ccccccc} 2 & -1 & . & . & . & . \\ -1 & 2 & -1 & . & . & . \\ . & -1 & 2 & -1 & . & . \\ . & . & -1 & 2 & -1 & . \\ . & . & . & -1 & 2 & -1 \\ . & . & . & . & -1 & 2 \\ . & . & . & . & . & -1 \end{array} \right) \begin{array}{cc} . & . \\ . & . \\ . & . \\ . & . \\ . & . \\ 0 & . \\ 0 & 0 \end{array} \] We also would like to remind the meaning of the local index (localIdx) of the matrix element within a matrix row. It is a rank of the nonzero matrix element in given row as we explained in section Indexing of nonzero matrix elements in sparse matrices. The values of the local index for tridiagonal matrix elements are as follows \[\left( \begin{array}{cccccc} 1 & 2 & & & & \\ 0 & 1 & 2 & & & \\ & 0 & 1 & 2 & & \\ & & 0 & 1 & 2 & \\ & & & 0 & 1 & 2 \\ & & & & 0 & 1 \end{array} \right) \] In the following text we show different methods for setup of tridiagonal matrices. Initializer listThe tridiagonal matrix can be initialized by the means of the constructor with initializer list. The matrix from the beginning of this section can be constructed as the following example demonstrates: 1#include <iostream>
2#include <TNL/Matrices/TridiagonalMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8createTridiagonalMatrix()
9{
10 const int matrixSize = 6;
11
12 /***
13 * Setup the following matrix (dots represent zeros):
14 *
15 * / 2 -1 . . . . \
16 * | -1 2 -1 . . . |
17 * | . -1 2 -1 . . |
18 * | . . -1 2 -1 . |
19 * | . . . -1 2 -1 |
20 * \ . . . . -1 2 /
21 *
22 */
24 matrixSize,
25 {
26 /***
27 * To set the matrix elements we first extend the diagonals to their full
28 * lengths even outside the matrix (dots represent zeros and zeros are
29 * artificial zeros used for memory alignment):
30 *
31 * 0 / 2 -1 . . . . \ -> { 0, 2, -1 }
32 * | -1 2 -1 . . . | -> { -1, 2, -1 }
33 * | . -1 2 -1 . . | -> { -1, 2, -1 }
34 * | . . -1 2 -1 . | -> { -1, 2, -1 }
35 * | . . . -1 2 -1 | -> { -1, 2, -1 }
36 * \ . . . . -1 2 / 0 -> { -1, 2, 0 }
37 *
38 */
39 { 0, 2, -1 },
40 { -1, 2, -1 },
41 { -1, 2, -1 },
42 { -1, 2, -1 },
43 { -1, 2, -1 },
44 { -1, 2, 0 },
45 } );
47}
48
49int
50main( int argc, char* argv[] )
51{
53 createTridiagonalMatrix< TNL::Devices::Host >();
54
55#if defined( __CUDACC__ ) || defined( __HIP__ )
56 std::cout << "Creating tridiagonal matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
57 createTridiagonalMatrix< TNL::Devices::GPU >();
58#endif
59}
Implementation of sparse tridiagonal matrix. Definition TridiagonalMatrix.h:56 The matrix elements values are defined on lines 39-44. Each matrix row is represented by embedded an initializer list. We set three values in each row including the padding zeros. The output of the example looks as: Creating tridiagonal matrix on CPU ...
The matrix reads as:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2 5:-1
Row: 5 -> 4:-1 5:2
Creating tridiagonal matrix on GPU (CUDA) ...
The matrix reads as:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2 5:-1
Row: 5 -> 4:-1 5:2
Methods setElement and addElementSimilar way of the tridiagonal matrix setup is offered by the method setElements (TNL::Matrices::TridiagonalMatrix::setElements) as the following example demonstrates: 1#include <iostream>
2#include <TNL/Matrices/TridiagonalMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8createTridiagonalMatrix()
9{
10 const int matrixSize = 6;
11
12 /***
13 * Setup the following matrix (dots represent zeros):
14 *
15 * / 2 -1 . . . . \
16 * | -1 2 -1 . . . |
17 * | . -1 2 -1 . . |
18 * | . . -1 2 -1 . |
19 * | . . . -1 2 -1 |
20 * \ . . . . -1 2 /
21 *
22 */
23 TNL::Matrices::TridiagonalMatrix< double, Device > matrix( matrixSize, matrixSize );
24 matrix.setElements(
25 {
26 /***
27 * To set the matrix elements we first extend the diagonals to their full
28 * lengths even outside the matrix (dots represent zeros and zeros are
29 * artificial zeros used for memory alignment):
30 *
31 * 0 / 2 -1 . . . . \ -> { 0, 2, -1 }
32 * | -1 2 -1 . . . | -> { -1, 2, -1 }
33 * | . -1 2 -1 . . | -> { -1, 2, -1 }
34 * | . . -1 2 -1 . | -> { -1, 2, -1 }
35 * | . . . -1 2 -1 | -> { -1, 2, -1 }
36 * \ . . . . -1 2 / 0 -> { -1, 2, 0 }
37 *
38 */
39 { 0, 2, -1 },
40 { -1, 2, -1 },
41 { -1, 2, -1 },
42 { -1, 2, -1 },
43 { -1, 2, -1 },
44 { -1, 2, 0 },
45 } );
47}
48
49int
50main( int argc, char* argv[] )
51{
53 createTridiagonalMatrix< TNL::Devices::Host >();
54
55#if defined( __CUDACC__ ) || defined( __HIP__ )
56 std::cout << "Creating tridiagonal matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
57 createTridiagonalMatrix< TNL::Devices::GPU >();
58#endif
59}
Here we create the matrix in two steps. Firstly, we setup the matrix dimensions by the appropriate constructor (line 24) and after that we setup the matrix elements (line 25-45). The result looks the same as in the previous example: Creating tridiagonal matrix on CPU ...
The matrix reads as:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2 5:-1
Row: 5 -> 4:-1 5:2
Creating tridiagonal matrix on GPU (CUDA) ...
The matrix reads as:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2 5:-1
Row: 5 -> 4:-1 5:2
In the following example we create tridiagonal matrix with 5 rows and 5 columns (line 12-14) by the means of a shared pointer (TNL::Pointers::SharedPointer) to make this work even on GPU. We set numbers 0,...,4 on the diagonal (line 16) and we print the matrix (line 18). Next we use a lambda function (lines 21-27) combined with parallelFor (line 35), to modify the matrix. The offdiagonal elements are set to 1 (lines 23 and 26) and for the diagonal elements, we change the sign (line 24). 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/TridiagonalMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9setElements()
10{
11 const int matrixSize( 5 );
13 Matrix matrix( matrixSize, matrixSize );
14 auto view = matrix.getView();
15
16 for( int i = 0; i < 5; i++ )
18
21
23 {
24 if( i > 0 )
25 view.setElement( i, i - 1, 1.0 );
26 view.setElement( i, i, -i );
27 if( i < matrixSize - 1 )
28 view.setElement( i, i + 1, 1.0 );
29 };
30
31 TNL::Algorithms::parallelFor< Device >( 0, matrixSize, f );
32
35}
36
37int
38main( int argc, char* argv[] )
39{
41 setElements< TNL::Devices::Host >();
42
43#if defined( __CUDACC__ ) || defined( __HIP__ )
45 setElements< TNL::Devices::GPU >();
46#endif
47}
The result looks as follows: Set elements on host:
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 -> 1:1
Row: 1 -> 0:1 1:-1 2:1
Row: 2 -> 1:1 2:-2 3:1
Row: 3 -> 2:1 3:-3 4:1
Row: 4 -> 3:1 4:-4
Set elements on GPU (CUDA):
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 -> 1:1
Row: 1 -> 0:1 1:-1 2:1
Row: 2 -> 1:1 2:-2 3:1
Row: 3 -> 2:1 3:-3 4:1
Row: 4 -> 3:1 4:-4
Method getRowA bit different way of setting up the matrix, is the use of tridiagonal matrix view and the method getRow (TNL::Matrices::TridiagonalMatrixView::getRow) as the following example demonstrates: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/TridiagonalMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9getRowExample()
10{
11 /***
12 * Set the following matrix (dots represent zero matrix elements and zeros are
13 * padding zeros for memory alignment):
14 *
15 * 0 / 2 -1 . . . \ -> { 0, 0, 1 }
16 * | -1 2 -1 . . | -> { 0, 2, 1 }
17 * | . -1 2 -1. . | -> { 3, 2, 1 }
18 * | . . -1 2 -1 | -> { 3, 2, 1 }
19 * \ . . . -1 2 / -> { 3, 2, 1 }
20 *
21 */
22
23 const int matrixSize( 5 );
25 MatrixType matrix(
26 matrixSize, // number of matrix rows
27 matrixSize // number of matrix columns
28 );
29 auto view = matrix.getView();
30
32 {
34
35 if( rowIdx > 0 )
36 row.setElement( 0, -1.0 ); // elements below the diagonal
37 row.setElement( 1, 2.0 ); // elements on the diagonal
38 if( rowIdx < matrixSize - 1 ) // elements above the diagonal
39 row.setElement( 2, -1.0 );
40 };
41
42 /***
43 * Set the matrix elements.
44 */
47}
48
49int
50main( int argc, char* argv[] )
51{
53 getRowExample< TNL::Devices::Host >();
54
55#if defined( __CUDACC__ ) || defined( __HIP__ )
57 getRowExample< TNL::Devices::GPU >();
58#endif
59}
We create a matrix with the same size (line 22-27). Next, we fetch the tridiagonal matrix view (ef TNL::Matrices::TridiagonalMatrixView ,line 28) which we use in the lambda function for matrix elements modification (lines 30-38). Inside the lambda function, we first get a matrix row by calling the method getRow (TNL::Matrices::TridiagonalMatrixView::getRow) using which we can access the matrix elements (lines 33-37). We would like to stress that the method setElement addresses the matrix elements with the localIdx parameter which is a rank of the nonzero element in the matrix row - see Indexing of nonzero matrix elements in sparse matrices. The lambda function is called by the parallelFor. The result looks as follows: Getting matrix rows on host:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Getting matrix rows on GPU (CUDA):
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Method forRowsThe method forRows (TNL::Matrices::TridiagonalMatrix::forRows) iterates in parallel over matrix rows and calls the user lambda with a row view object. It is the tridiagonal equivalent of the dense and sparse variants described above.
The full family of member functions consists of:
The same traversal is also available through the free function TNL::Matrices::forRows, which supports all five matrix types (see Free-function traverse and reduce API). The following example demonstrates the basic use: 1#include <iostream>
2#include <TNL/Matrices/TridiagonalMatrix.h>
3#include <TNL/Matrices/traverse.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9forRowsExample()
10{
12 /***
13 * Set the following matrix (dots represent zero matrix elements and zeros are
14 * padding zeros for memory alignment):
15 *
16 * 0 / 2 . . . . \ -> { 0, 0, 1 }
17 * | -1 2 -1 . . | -> { 0, 2, 1 }
18 * | . -1 2 -1. . | -> { 3, 2, 1 }
19 * | . . -1 2 -1 | -> { 3, 2, 1 }
20 * \ . . . . 2 / -> { 3, 2, 1 }
21 *
22 * The diagonals offsets are { -1, 0, 1 }.
23 */
24 const int size = 5;
25 MatrixType matrix( size, size );
26 auto view = matrix.getView();
27
29 {
30 const int& rowIdx = row.getRowIndex();
31 if( rowIdx > 0 )
32 row.setElement( 0, -1.0 ); // elements below the diagonal
33 row.setElement( 1, 2.0 ); // elements on the diagonal
34 if( rowIdx < size - 1 ) // elements above the diagonal
35 row.setElement( 2, -1.0 );
36 };
37 TNL::Matrices::forAllRows( view, f );
39}
40
41int
42main( int argc, char* argv[] )
43{
45 forRowsExample< TNL::Devices::Host >();
46
47#if defined( __CUDACC__ ) || defined( __HIP__ )
49 forRowsExample< TNL::Devices::GPU >();
50#endif
51}
void forAllRows(Matrix &matrix, Function &&function, Algorithms::Segments::LaunchConfiguration launchConfig=Algorithms::Segments::LaunchConfiguration()) Iterates in parallel over all matrix rows and applies the given lambda function to each row. The differences compared to getRow + parallelFor are:
Next, we compute sum of absolute values of matrix elements in each row and store it in a vector (lines 39-46). Firstly we create the vector sum_vector for storing the sums (line 39) and get a vector view sum_view to get access to the vector from a lambda function. On the lines 41-46, we call lambda function for each matrix row which iterates over all matrix elements and sum their absolute values. Finally we store the result to the output vector (line 45). The result looks as follows: Creating matrix on host:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Creating matrix on GPU (CUDA):
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Method forElementsThe method forElements (TNL::Matrices::TridiagonalMatrix::forElements) is the element-wise counterpart of forRows. It iterates in parallel over the matrix elements lying on the stored subdiagonals and passes the following data to the user lambda:
The full family of member functions consists of:
The free-function equivalents in TNL::Matrices support all five matrix types (see Free-function traverse and reduce API). The following example sets all elements on the three tridiagonal subdiagonals: 1#include <iostream>
2#include <TNL/Matrices/TridiagonalMatrix.h>
3#include <TNL/Matrices/traverse.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9forElementsExample()
10{
11 /***
12 * Set the following matrix (dots represent zero matrix elements and zeros are
13 * padding zeros for memory alignment):
14 *
15 * 0 / 2 1 . . . \ -> { 0, 2, 1 }
16 * | 3 2 1 . . | -> { 3, 2, 1 }
17 * | . 3 2 1 . | -> { 3, 2, 1 }
18 * | . . 3 2 1 | -> { 3, 2, 1 }
19 * \ . . . 3 2 / 0 -> { 3, 2, 0 }
20 */
22 5, // number of matrix rows
23 5 ); // number of matrix columns
24 auto view = matrix.getView();
25
27 {
28 /***
29 * 'forElements' method iterates only over matrix elements lying on given subdiagonals
30 * and so we do not need to check anything. The element value can be expressed
31 * by the 'localIdx' variable, see the following figure:
32 *
33 * 0 1 2 <- localIdx values
34 * -------
35 * 0 / 2 1 . . . \ -> { 0, 2, 1 }
36 * | 3 2 1 . . | -> { 3, 2, 1 }
37 * | . 3 2 1 . | -> { 3, 2, 1 }
38 * | . . 3 2 1 | -> { 3, 2, 1 }
39 * \ . . . 3 2 / 0 -> { 3, 2, 0 }
40 *
41 */
42 value = 3 - localIdx;
43 };
44 TNL::Matrices::forElements( view, 0, matrix.getRows(), f );
46}
47
48int
49main( int argc, char* argv[] )
50{
52 forElementsExample< TNL::Devices::Host >();
53
54#if defined( __CUDACC__ ) || defined( __HIP__ )
56 forElementsExample< TNL::Devices::GPU >();
57#endif
58}
void forElements(Matrix &matrix, IndexBegin begin, IndexEnd end, Function &&function, Algorithms::Segments::LaunchConfiguration launchConfig=Algorithms::Segments::LaunchConfiguration()) Iterates in parallel over all elements in the given range of matrix rows and applies the specified la... We call forElements (line 43) instead of parallelFor. This method iterates over all matrix rows and all nonzero matrix elements. The lambda function on line 25 receives the matrix row index, the local index of the matrix element (localIdx), the column index (columnIdx), and a reference to the element value (value) which we use for its modification. Note that the first and the last row contain padding artificial elements; their local indexes and values are iterated as well. The result looks as follows: Creating matrix on host:
Row: 0 -> 0:2 1:1
Row: 1 -> 0:3 1:2 2:1
Row: 2 -> 1:3 2:2 3:1
Row: 3 -> 2:3 3:2 4:1
Row: 4 -> 3:3 4:2
Creating matrix on GPU (CUDA):
Row: 0 -> 0:2 1:1
Row: 1 -> 0:3 1:2 2:1
Row: 2 -> 1:3 2:2 3:1
Row: 3 -> 2:3 3:2 4:1
Row: 4 -> 3:3 4:2
Multidiagonal matricesMultidiagonal matrices are generalization of the tridiagonal ones. It is a special type of sparse matrices with specific pattern of the nonzero matrix elements which are positioned only parallel along diagonal. See the following example: \[ \left( \begin{array}{ccccccc} 4 & -1 & . & -1 & . & . \\ -1 & 4 & -1 & . & -1 & . \\ . & -1 & 4 & -1 & . & -1 \\ -1 & . & -1 & 4 & -1 & . \\ . & -1 & . & -1 & 4 & -1 \\ . & . & -1 & . & -1 & 4 \end{array} \right) \] We can see that the matrix elements lay on lines parallel to the main diagonal. Such lines can be characterized by their offsets from the main diagonal. On the following figure, each such line is depicted in different color: \[\begin{array}{ccc} \color{green}{-3} & . & \color{cyan}{-1} \\ \hline \color{green}{*} & . & \color{cyan}{*} \\ . & \color{green}{*} & . \\ . & . & \color{green}{*} \\ . & . & . \\ . & . & . \\ . & . & . \end{array} \left( \begin{array}{ccccccc} \color{blue}{0} & \color{magenta}{1} & . & \color{red}{3} & . & . \\ \hline \color{blue}{4} & \color{magenta}{-1} & . & \color{red}{-1} & . & . \\ \color{cyan}{-1} & \color{blue}{4} & \color{magenta}{-1} & . & \color{red}{-1} & . \\ . & \color{cyan}{-1} & \color{blue}{4} & \color{magenta}{-1} & . & \color{red}{-1} \\ \color{green}{-1} & . & \color{cyan}{-1} & \color{blue}{4} & \color{magenta}{-1} & . \\ . & \color{green}{-1} & . & \color{cyan}{-1} & \color{blue}{4} & \color{magenta}{-1} \\ . & . & \color{green}{-1} & . & \color{cyan}{-1} & \color{blue}{4} \end{array} \right) \] In this matrix, the offsets reads as \(\{-3, -1, 0, +1, +3\}\). It also means that the column indexes on \(i-\)th row are \(\{i-3, i-1, i, i+1, i+3\}\) (where we accept only nonnegative indexes smaller than the number of matrix columns). An advantage is that, similar to the tridiagonal matrix (TNL::Matrices::TridiagonalMatrix), we do not store the column indexes explicitly as it is in TNL::Matrices::SparseMatrix. This can significantly reduce the memory requirements which also means better performance. See the following table for the storage requirements comparison between multidiagonal matrix (TNL::Matrices::MultidiagonalMatrix) and general sparse matrix (TNL::Matrices::SparseMatrix).
For the sake of better memory alignment and faster access to the matrix elements, we store all subdiagonals in complete form including the elements which are outside the matrix as depicted on the following figure where zeros stand for the padding artificial zero matrix elements \[\begin{array}{cccc} 0 & & & 0 \\ & 0 & & \\ & & 0 & \\ & & & 0 \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \end{array} \left( \begin{array}{cccccccccccccccc} 1 & 0 & & & 0 & & & & & & & & & & & \\ 0 & 1 & 0 & & & 0 & & & & & & & & & & \\ & 0 & 1 & 0 & & & 0 & & & & & & & & & \\ & & 0 & 1 & 0 & & & 0 & & & & & & & & \\ 0 & & & 0 & 1 & 0 & & & 0 & & & & & & & \\ & -1 & & & -1 & 1 & -1 & & & -1 & & & & & & \\ & & -1 & & & -1 & 1 & -1 & & & -1 & & & & & \\ & & & 0 & & & 0 & 1 & 0 & & & 0 & & & & \\ & & & & 0 & & & 0 & 1 & 0 & & & 0 & & & \\ & & & & & -1 & & & -1 & 1 & -1 & & & -1 & & \\ & & & & & & -1 & & & -1 & 1 & -1 & & & -1 & \\ & & & & & & & 0 & & & 0 & 1 & 0 & & & 0 \\ & & & & & & & & 0 & & & 0 & 1 & 0 & & \\ & & & & & & & & & 0 & & & 0 & 1 & 0 & \\ & & & & & & & & & & 0 & & & 0 & 1 & 0 \\ & & & & & & & & & & & 0 & & & 0 & 1 \end{array} \right) \begin{array} & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ 0 & & & \\ & 0 & & \\ & & 0 & \\ 0 & & & 0 \end{array} \] Multidiagonal matrix is a templated class defined in the namespace TNL::Matrices. It has six template parameters:
In the following text we show different methods how to setup multidiagonal matrices. Initializer listSmaller multidiagonal matrices can be created using the constructor with initializer lists (std::initializer_list) as we demonstrate in the following example: 1#include <iostream>
2#include <TNL/Matrices/MultidiagonalMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8createMultidiagonalMatrix()
9{
10 const int matrixSize = 6;
11
12 /*
13 * Setup the following matrix (dots represent zeros):
14 *
15 * / 4 -1 . -1 . . \
16 * | -1 4 -1 . -1 . |
17 * | . -1 4 -1 . -1 |
18 * | -1 . -1 4 -1 . |
19 * | . -1 . -1 4 -1 |
20 * \ . . 1 . -1 4 /
21 *
22 * The diagonals offsets are { -3, -1, 0, 1, 3 }.
23 */
25 matrixSize,
26 { -3, -1, 0, 1, 3 },
27 {
28 /*
29 * To set the matrix elements we first extend the diagonals to their full
30 * lengths even outside the matrix (dots represent zeros and zeros are
31 * artificial zeros used for memory alignment):
32 *
33 * 0 . 0 / 4 -1 . -1 . . \ -> { 0, 0, 4, -1, -1 }
34 * . 0 . | -1 4 -1 . -1 . | . -> { 0, -1, 4, -1, -1 }
35 * . . 0 | . -1 4 -1 . -1 | . . -> { 0, -1, 4, -1, -1 }
36 * . . | -1 . -1 4 -1 . | 0 . . -> { -1, -1, 4, -1, 0 }
37 * . | . -1 . -1 4 -1 | . 0 . . -> { -1, -1, 4, -1, 0 }
38 * \ . . 1 . -1 4 / 0 . 0 . . -> { -1, -1, 4, 0, 0 }
39 */
40 // clang-format off
41 { 0, 0, 4, -1, -1 },
42 { 0, -1, 4, -1, -1 },
43 { 0, -1, 4, -1, -1 },
44 { -1, -1, 4, -1, 0 },
45 { -1, -1, 4, -1, 0 },
46 { -1, -1, 4, 0, 0 },
47 // clang-format on
48 } );
50}
51
52int
53main( int argc, char* argv[] )
54{
56 createMultidiagonalMatrix< TNL::Devices::Host >();
57
58#if defined( __CUDACC__ ) || defined( __HIP__ )
59 std::cout << "Creating multidiagonal matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
60 createMultidiagonalMatrix< TNL::Devices::GPU >();
61#endif
62}
Implementation of sparse multidiagonal matrix. Definition MultidiagonalMatrix.h:64 Here, we create a matrix which looks as \[\left( \begin{array}{cccccc} 4 & -1 & & -1 & & \\ -1 & 4 & -1 & & -1 & \\ & -1 & 4 & -1 & & -1 \\ -1 & & -1 & 4 & -1 & \\ & -1 & & -1 & 4 & -1 \\ & & -1 & & -1 & 4 \\ \end{array} \right). \] On the lines 25-46, we call the constructor which, in addition to matrix dimensions and subdiagonals offsets, accepts also initializer list of initializer lists with matrix elements values. Each embedded list corresponds to one matrix row and it contains values of matrix elements on particular subdiagonals including those which lies out of the matrix. The result looks as follows: Create multidiagonal matrix on CPU ...
The matrix reads as:
Row: 0 -> 0:4 1:-1 3:-1
Row: 1 -> 0:-1 1:4 2:-1 4:-1
Row: 2 -> 1:-1 2:4 3:-1 5:-1
Row: 3 -> 0:-1 2:-1 3:4 4:-1
Row: 4 -> 1:-1 3:-1 4:4 5:-1
Row: 5 -> 2:-1 4:-1 5:4
Creating multidiagonal matrix on GPU (CUDA) ...
The matrix reads as:
Row: 0 -> 0:4 1:-1 3:-1
Row: 1 -> 0:-1 1:4 2:-1 4:-1
Row: 2 -> 1:-1 2:4 3:-1 5:-1
Row: 3 -> 0:-1 2:-1 3:4 4:-1
Row: 4 -> 1:-1 3:-1 4:4 5:-1
Row: 5 -> 2:-1 4:-1 5:4
Methods setElement and addElementAnother and more efficient way of setting the matrix elements is by means of the method setElement (TNL::Matrices::MultidiagonalMatrix::setElement). It is demonstrated in the following example: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Matrices/MultidiagonalMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6#include <TNL/Pointers/SharedPointer.h>
7#include <TNL/Pointers/SmartPointersRegister.h>
8
9template< typename Device >
10void
11setElements()
12{
13 const int matrixSize( 5 );
14 auto diagonalsOffsets = { -1, 0, 1 }; // offsets of tridiagonal matrix
16 Matrix matrix( matrixSize, matrixSize, diagonalsOffsets );
17 auto view = matrix.getView();
18
19 for( int i = 0; i < 5; i++ )
20 view.setElement( i, i, i );
21
24
26 {
27 if( i > 0 )
28 view.setElement( i, i - 1, 1.0 );
29 view.setElement( i, i, -i );
30 if( i < matrixSize - 1 )
31 view.setElement( i, i + 1, 1.0 );
32 };
33
34 TNL::Algorithms::parallelFor< Device >( 0, matrixSize, f );
35
38}
39
40int
41main( int argc, char* argv[] )
42{
44 setElements< TNL::Devices::Host >();
45
46#if defined( __CUDACC__ ) || defined( __HIP__ )
48 setElements< TNL::Devices::GPU >();
49#endif
50}
This examples shows that the method setElement can be used both on the host (CPU) (line 19) as well as in the lambda functions that can be called from GPU kernels (lines 25-29). For this purpose, we fetch a matrix view on the line 16. The result looks as follows: Set elements on host:
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 -> 1:1
Row: 1 -> 0:1 1:-1 2:1
Row: 2 -> 1:1 2:-2 3:1
Row: 3 -> 2:1 3:-3 4:1
Row: 4 -> 3:1 4:-4
Set elements on GPU (CUDA):
Matrix set from the host:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Matrix set from its native device:
Row: 0 -> 1:1
Row: 1 -> 0:1 1:-1 2:1
Row: 2 -> 1:1 2:-2 3:1
Row: 3 -> 2:1 3:-3 4:1
Row: 4 -> 3:1 4:-4
Method getRowSlightly more efficient way of the multidiagonal matrix setup is offered by the method getRow (TNL::Matrices::MultidiagonalMatrix::getRow). We will use it to create a matrix of the following form: \[\left( \begin{array}{cccccccccccccccc} 1 & . & & & . & & & & & & & & & & & \\ . & 1 & . & & & . & & & & & & & & & & \\ & . & 1 & . & & & . & & & & & & & & & \\ & & . & 1 & . & & & . & & & & & & & & \\ . & & & . & 1 & . & & & . & & & & & & & \\ & -1 & & & -1 & -4 & -1 & & & -1 & & & & & & \\ & & -1 & & & -1 & -4 & -1 & & & -1 & & & & & \\ & & & . & & & . & 1 & . & & & . & & & & \\ & & & & . & & & . & 1 & . & & & . & & & \\ & & & & & -1 & & & -1 & -4 & -1 & & & -1 & & \\ & & & & & & -1 & & & -1 & -4 & -1 & & & -1 & \\ & & & & & & & . & & & . & 1 & . & & & . \\ & & & & & & & & . & & & . & 1 & . & & \\ & & & & & & & & & . & & & . & 1 & . & \\ & & & & & & & & & & . & & & . & 1 & . \\ & & & & & & & & & & & . & & & . & 1 \end{array} \right) \] The matrices of this form arise from a discretization of the Laplace operator in 2D by the finite difference method. We use this example because it is a frequent numerical problem and the multidiagonal format is very suitable for such matrices. If the reader, however, is not familiar with the finite difference method, please, do not be scared, we will just create the matrix mentioned above. The code based on use of method getRow reads as: 1#include <iostream>
2#include <TNL/Algorithms/parallelFor.h>
3#include <TNL/Containers/StaticArray.h>
4#include <TNL/Matrices/MultidiagonalMatrix.h>
5#include <TNL/Devices/Host.h>
6#include <TNL/Devices/GPU.h>
7
8template< typename Device >
9void
10laplaceOperatorMatrix()
11{
12 /***
13 * Set matrix representing approximation of the Laplace operator on regular
14 * grid using the finite difference method.
15 */
16 const int gridSize( 4 );
17 const int matrixSize = gridSize * gridSize;
18 TNL::Containers::Vector< int, Device > offsets{ -gridSize, -1, 0, 1, gridSize };
19 TNL::Matrices::MultidiagonalMatrix< double, Device > matrix( matrixSize, matrixSize, offsets );
20 auto matrixView = matrix.getView();
22 {
23 const int elementIdx = i[ 1 ] * gridSize + i[ 0 ];
25 if( i[ 0 ] == 0 || i[ 1 ] == 0 || i[ 0 ] == gridSize - 1 || i[ 1 ] == gridSize - 1 ) {
26 row.setElement( 2, 1.0 ); // set matrix elements corresponding to boundary grid nodes
27 // and Dirichlet boundary conditions, i.e. 1 on the main diagonal
28 // which is the third one
29 }
30 else {
31 row.setElement( 0, -1.0 ); // set matrix elements corresponding to inner grid nodes, i.e.
32 row.setElement( 1, -1.0 ); // 4 on the main diagonal (the third one) and -1 to the other
33 row.setElement( 2, 4.0 ); // sub-diagonals
34 row.setElement( 3, -1.0 );
35 row.setElement( 4, -1.0 );
36 }
37 };
40 TNL::Algorithms::parallelFor< Device >( begin, end, f );
41
43}
44
45int
46main( int argc, char* argv[] )
47{
49 laplaceOperatorMatrix< TNL::Devices::Host >();
50
51#if defined( __CUDACC__ ) || defined( __HIP__ )
52 std::cout << "Creating Laplace operator matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
53 laplaceOperatorMatrix< TNL::Devices::GPU >();
54#endif
55}
T begin(T... args) T end(T... args) We firstly compute the matrix size (matrixSize) based on the numerical grid dimensions on the line 16. The subdiagonals offsets are defined by the numerical grid size and since it is four in this example the offsets read as \(\left\{-4,-1,0,1,4 \right\} \) or { -gridSize, -1, 0, 1, gridSize} (line 17). Here we store the offsets in vector (TNL::Containers::Vector) called offsets. Next we use a constructor with matrix dimensions and offsets passed via TNL vector (line 18) and we fetch a matrix view (TNL::Matrices::MultidiagonalMatrixView, line 19). The matrix is constructed by iterating over particular nodes of the numerical grid. Each node correspond to one matrix row. This is why the lambda function f (lines 20-35) take two indexes i and j (line 20). Their values are coordinates of the two-dimensional numerical grid. Based on these coordinates we compute index (elementIdx) of the corresponding matrix row (line 21). We fetch matrix row (row) by calling the getRow method (TNL::Matrices::MultidiagonalMatrix::getRow) (line 22). Depending on the grid node coordinates we set either the boundary conditions (lines 23-26) for the boundary nodes (those laying on the boundary of the grid and so their coordinates fulfil the condition i == 0 || j == 0 || i == gridSize - 1 || j == gridSize - 1 ) for which se set only the diagonal element to 1. The inner nodes of the numerical grid are handled on the lines 29-33 where we set coefficients approximating the Laplace operator. We use the method setElement of the matrix row (TNL::Matrices::MultidiagonalMatrixRowView::setElement) which takes the local index of the nonzero matrix element as the first parameter (see Indexing of nonzero matrix elements in sparse matrices) and the new value of the element as the second parameter. The local indexes, in fact, refer to particular subdiagonals as depicted on the following figure (in blue): \[\begin{array}{cccc} \color{blue}{-4} & & & \color{blue}{-1} \\ \hline . & & & . \\ & . & & \\ & & . & \\ & & & . \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \\ & & & \end{array} \left( \begin{array}{cccccccccccccccc} \color{blue}{0} & \color{blue}{1} & & & \color{blue}{4} & & & & & & & & & & & \\ \hline 1 & . & & & . & & & & & & & & & & & \\ . & 1 & . & & & . & & & & & & & & & & \\ & . & 1 & . & & & . & & & & & & & & & \\ & & . & 1 & . & & & . & & & & & & & & \\ . & & & . & 1 & . & & & . & & & & & & & \\ & -1 & & & -1 & 1 & -1 & & & -1 & & & & & & \\ & & -1 & & & -1 & 1 & -1 & & & -1 & & & & & \\ & & & . & & & . & 1 & . & & & . & & & & \\ & & & & . & & & . & 1 & . & & & . & & & \\ & & & & & -1 & & & -1 & 1 & -1 & & & -1 & & \\ & & & & & & -1 & & & -1 & 1 & -1 & & & -1 & \\ & & & & & & & . & & & . & 1 & . & & & . \\ & & & & & & & & . & & & . & 1 & . & & \\ & & & & & & & & & . & & & . & 1 & . & \\ & & & & & & & & & & . & & & . & 1 & . \\ & & & & & & & & & & & . & & & . & 1 \end{array} \right) \] We use parallelFor to iterate over all nodes of the numerical grid (line 36) and apply the lambda function. The result looks as follows: Creating Laplace operator matrix on CPU ...
Laplace operator matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:-1 4:-1 5:4 6:-1 9:-1
Row: 6 -> 2:-1 5:-1 6:4 7:-1 10:-1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:-1 8:-1 9:4 10:-1 13:-1
Row: 10 -> 6:-1 9:-1 10:4 11:-1 14:-1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Creating Laplace operator matrix on GPU (CUDA) ...
Laplace operator matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:-1 4:-1 5:4 6:-1 9:-1
Row: 6 -> 2:-1 5:-1 6:4 7:-1 10:-1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:-1 8:-1 9:4 10:-1 13:-1
Row: 10 -> 6:-1 9:-1 10:4 11:-1 14:-1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Method forRowsThe method forRows (TNL::Matrices::MultidiagonalMatrix::forRows) iterates in parallel over matrix rows and passes a row view to the user lambda. It is the multidiagonal equivalent of the dense and sparse variants described above.
The full family of member functions consists of:
The same traversal is also available through the free function TNL::Matrices::forRows, which supports all five matrix types (see Free-function traverse and reduce API). The following example demonstrates the basic use: 1#include <iostream>
2#include <TNL/Matrices/MultidiagonalMatrix.h>
3#include <TNL/Matrices/traverse.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9forRowsExample()
10{
12 /***
13 * Set the following matrix (dots represent zero matrix elements and zeros are
14 * padding zeros for memory alignment):
15 *
16 * 0 / 2 . . . . \ -> { 0, 0, 1 }
17 * | -1 2 -1 . . | -> { 0, 2, 1 }
18 * | . -1 2 -1. . | -> { 3, 2, 1 }
19 * | . . -1 2 -1 | -> { 3, 2, 1 }
20 * \ . . . . 2 / -> { 3, 2, 1 }
21 *
22 * The diagonals offsets are { -1, 0, 1 }.
23 */
24 const int size = 5;
25 MatrixType matrix(
26 size, // number of matrix rows
27 size, // number of matrix columns
28 { -1, 0, 1 } ); // matrix diagonals offsets
29 auto view = matrix.getView();
30
32 {
33 const int& rowIdx = row.getRowIndex();
34 if( rowIdx > 0 )
35 row.setElement( 0, -1.0 ); // elements below the diagonal
36 row.setElement( 1, 2.0 ); // elements on the diagonal
37 if( rowIdx < size - 1 ) // elements above the diagonal
38 row.setElement( 2, -1.0 );
39 };
40 TNL::Matrices::forAllRows( view, f );
42}
43
44int
45main( int argc, char* argv[] )
46{
48 forRowsExample< TNL::Devices::Host >();
49
50#if defined( __CUDACC__ ) || defined( __HIP__ )
52 forRowsExample< TNL::Devices::GPU >();
53#endif
54}
We call the method forAllRows (TNL::Matrices::MultidiagonalMatrix::forAllRows) (line 39) instead of parallelFor which is simpler since we do not have to state the device type explicitly. The method forAllRows calls the method forRows for all matrix rows so we do not have to state explicitly the interval of matrix rows neither. The lambda function f (lines 30-38) accepts one parameter row of the type RowView (TNL::Matrices::MultidiagonalMatrix::RowView which is TNL::Matrices::MultidiagonalMatrixRowView). At the beginning of the lambda function, we call the method geRowIndex (TNL::Matrices::MultidiagonalMatrixRowView::getRowIndex) to get the index of the matrix row (line 29). The row view also provides setElement(localIdx, value) to modify the element stored at the given local index. Next, we compute sum of absolute values of matrix elements in each row and store it in a vector (lines 39-46). Firstly we create the vector sum_vector for storing the sums (line 39) and get a vector view sum_view to get access to the vector from a lambda function. On the lines 41-46, we call lambda function for each matrix row which iterates over all matrix elements and sum their absolute values. Finally we store the result to the output vector (line 45). The result looks as follows: Creating matrix on host:
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Creating matrix on GPU (CUDA):
Row: 0 -> 0:2 1:-1
Row: 1 -> 0:-1 1:2 2:-1
Row: 2 -> 1:-1 2:2 3:-1
Row: 3 -> 2:-1 3:2 4:-1
Row: 4 -> 3:-1 4:2
Method forElementsThe method forElements (TNL::Matrices::MultidiagonalMatrix::forElements, TNL::Matrices::MultidiagonalMatrixView::forElements) is the element-wise counterpart of forRows. It iterates in parallel over the matrix elements lying on the stored subdiagonals and passes the following data to the user lambda:
The full family of member functions consists of:
The free-function equivalents in TNL::Matrices support all five matrix types (see Free-function traverse and reduce API). The following example demonstrates the basic use: 1#include <iostream>
2#include <TNL/Matrices/MultidiagonalMatrix.h>
3#include <TNL/Matrices/traverse.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9forElementsExample()
10{
11 /***
12 * Set the following matrix (dots represent zero matrix elements and zeros are
13 * padding zeros for memory alignment):
14 *
15 * 0 0 / 1 . . . . \ -> { 0, 0, 1 }
16 * 0 | 2 1 . . . | -> { 0, 2, 1 }
17 * | 3 2 1 . . | -> { 3, 2, 1 }
18 * | . 3 2 1 . | -> { 3, 2, 1 }
19 * \ . . 3 2 1 / -> { 3, 2, 1 }
20 *
21 * The diagonals offsets are { -2, -1, 0 }.
22 */
24 5, // number of matrix rows
25 5, // number of matrix columns
26 { -2, -1, 0 } ); // matrix diagonals offsets
27 auto view = matrix.getView();
28
30 {
31 /***
32 * 'forElements' method iterates only over matrix elements lying on given subdiagonals
33 * and so we do not need to check anything. The element value can be expressed
34 * by the 'localIdx' variable, see the following figure:
35 *
36 * 0 1 2 <- localIdx values
37 * -------
38 * 0 0 / 1 . . . . \ -> { 0, 0, 1 }
39 * 0 | 2 1 . . . | -> { 0, 2, 1 }
40 * | 3 2 1 . . | -> { 3, 2, 1 }
41 * | . 3 2 1 . | -> { 3, 2, 1 }
42 * \ . . 3 2 1 / -> { 3, 2, 1 }
43 *
44 */
45 value = 3 - localIdx;
46 };
47 TNL::Matrices::forElements( view, 0, matrix.getRows(), f );
49}
50
51int
52main( int argc, char* argv[] )
53{
55 forElementsExample< TNL::Devices::Host >();
56
57#if defined( __CUDACC__ ) || defined( __HIP__ )
59 forElementsExample< TNL::Devices::GPU >();
60#endif
61}
We provide a lambda function f (lines 28-45) which is called for each matrix element by the method forElements (line 46). In this example, the matrix element value depends only on the subdiagonal index localIdx (see Indexing of nonzero matrix elements in sparse matrices) as we can see on line 44. Padding artificial elements outside the matrix are iterated as well. The result looks as follows: Creating matrix on host:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 1:3 2:2 3:1
Row: 4 -> 2:3 3:2 4:1
Creating matrix on GPU (CUDA):
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 1:3 2:2 3:1
Row: 4 -> 2:3 3:2 4:1
Lambda matricesLambda matrix (TNL::Matrices::LambdaMatrix) is a special type of matrix which could be also called matrix-free matrix. The matrix elements are not stored in memory explicitly but they are evaluated on-the-fly by means of user defined lambda functions. If the matrix elements can be expressed by computationally not expansive formula, we can significantly reduce the memory consumption which is appreciated especially on GPUs. Since the memory accesses are quite expensive even on both CPU and GPU, we can get, at the end, even much faster code. The lambda matrix (TNL::Matrices::LambdaMatrix) is a templated class with the following template parameters:
The lambda function MatrixElementsLambda is supposed to have the following declaration: 1auto matrixElements = [=
2] __cuda_callable__( Index rows, Index columns, Index row, Index localIdx, Index& columnIdx, Real& value );
where the particular parameters have the following meaning:
The lambda function CompressedRowLengthsLambda (by compressed row length we mean the number of matrix elements in a row after ignoring/compressing the zero elements) is supposed to be declared like this: where the parameters can be described as follows:
The lambda function is supposed to return just the number of the nonzero matrix elements in given matrix row. Lambda matrix initiationHow to put the lambda functions together with the lambda matrix is demonstrated in the following example: 1#include <iostream>
2#include <TNL/Matrices/LambdaMatrix.h>
3
4int
5main( int argc, char* argv[] )
6{
7 /***
8 * Lambda functions defining the matrix.
9 */
10 auto compressedRowLengths = [ = ] __cuda_callable__( const int rows, const int columns, const int rowIdx ) -> int
11 {
12 return 1;
13 };
14 auto matrixElements1 =
15 [ = ] __cuda_callable__(
16 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
17 {
18 columnIdx = rowIdx;
19 value = 1.0;
20 };
21 auto matrixElements2 =
22 [ = ] __cuda_callable__(
23 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
24 {
25 columnIdx = rowIdx;
26 value = rowIdx;
27 };
28
29 const int size = 5;
30
31 /***
32 * Matrix construction with explicit type definition.
33 */
34 using MatrixType = decltype( TNL::Matrices::LambdaMatrixFactory< double, TNL::Devices::Host, int >::create(
35 matrixElements1, compressedRowLengths ) );
36 MatrixType m1( size, size, matrixElements1, compressedRowLengths );
37
38 /***
39 * Matrix construction using 'auto'.
40 */
41 auto m2 =
42 TNL::Matrices::LambdaMatrixFactory< double, TNL::Devices::Host, int >::create( matrixElements2, compressedRowLengths );
43 m2.setDimensions( size, size );
44
47}
static auto create(MatrixElementsLambda &matrixElementsLambda, CompressedRowLengthsLambda &compressedRowLengthsLambda) -> LambdaMatrix< MatrixElementsLambda, CompressedRowLengthsLambda, Real, Device, Index > Creates lambda matrix with given lambda functions. Definition LambdaMatrix.h:616 Here we create two simple diagonal matrices. Therefore they share the same lambda function compressedRowLengths telling the number of nonzero matrix elements in particular matrix rows which is always one (line 9). The first matrix, defined by the lambda function matrixElements1, is identity matrix and so its each diagonal element equals one. We set the matrix element value to 1.0 (line 12) and the column index equals the row index (line 15). The second matrix, defined by the lambda function matrixElements2, is also diagonal but not the identity matrix. The values of the diagonal elements equal to row index (line 16). With the same lambda functions we can define matrices with different dimensions. In this example, we set the matrix size to five (line 19). It could be quite difficult to express the lambda matrix type because it depends on the types of the lambda functions. To make this easier, one may use the lambda-matrix factory (TNL::Matrices::LambdaMatrixFactory). Using decltype one can deduce even the matrix type (line 24) followed by calling lambda matrix constructor with matrix dimensions and instances of the lambda functions (line 25). Or one can just simply employ the keyword auto (line 30) followed by setting the matrix dimensions (line 31). The result looks as follows: The first lambda matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
The second lambda matrix:
Row: 0 ->
Row: 1 -> 1:1
Row: 2 -> 2:2
Row: 3 -> 3:3
Row: 4 -> 4:4
Method forRowsThe method forRows (TNL::Matrices::LambdaMatrix::forRows, TNL::Matrices::LambdaMatrix::forAllRows) iterates in parallel over matrix rows. Because a lambda matrix does not store its elements explicitly, the traversal is read-only; the matrix elements cannot be changed through the row view.
The available member functions are:
The row view passed to the lambda offers the same read-only interface as for other matrix types: getRowIndex(), getSize(), getColumnIndex(localIdx), getValue(localIdx), and range-based iteration over the elements. The free-function TNL::Matrices::forRows also works with lambda matrices, but only through the const overloads (see Free-function traverse and reduce API). The following example shows how to copy the lambda matrix into a dense matrix and how to compute the sum of absolute values in each row: 1#include <iostream>
2#include <TNL/Matrices/LambdaMatrix.h>
3#include <TNL/Matrices/DenseMatrix.h>
4#include <TNL/Matrices/traverse.h>
5#include <TNL/Devices/Host.h>
6#include <TNL/Devices/GPU.h>
7
8template< typename Device >
9void
10forRowsExample()
11{
12 /***
13 * Set matrix representing approximation of the Laplace operator on regular
14 * grid using the finite difference method.
15 */
16 const int gridSize( 4 );
17 const int matrixSize = gridSize * gridSize;
18 auto rowLengths = [ = ] __cuda_callable__( const int rows, const int columns, const int rowIdx ) -> int
19 {
20 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
21 const int gridColumn = rowIdx % gridSize;
22 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
23 gridColumn == 0 || gridColumn == gridSize - 1 )
24 return 1;
25 return 5;
26 };
27 auto matrixElements =
28 [ = ] __cuda_callable__(
29 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
30 {
31 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
32 const int gridColumn = rowIdx % gridSize;
33 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
34 gridColumn == 0 || gridColumn == gridSize - 1 )
35 {
36 columnIdx = rowIdx; // diagonal element ....
37 value = 1.0; // ... is set to 1
38 }
39 else // interior grid node
40 {
41 switch( localIdx ) // set diagonal element to 4
42 { // and the others to -1
43 case 0:
44 columnIdx = rowIdx - gridSize;
45 value = 1;
46 break;
47 case 1:
48 columnIdx = rowIdx - 1;
49 value = 1;
50 break;
51 case 2:
52 columnIdx = rowIdx;
53 value = -4;
54 break;
55 case 3:
56 columnIdx = rowIdx + 1;
57 value = 1;
58 break;
59 case 4:
60 columnIdx = rowIdx + gridSize;
61 value = 1;
62 break;
63 }
64 }
65 };
66 auto matrix =
67 TNL::Matrices::LambdaMatrixFactory< double, Device, int >::create( matrixSize, matrixSize, matrixElements, rowLengths );
68 using MatrixType = decltype( matrix );
69 using RowView = typename MatrixType::RowView;
70
71 TNL::Matrices::DenseMatrix< double, Device > denseMatrix( matrixSize, matrixSize );
72 denseMatrix.setValue( 0.0 );
73 auto dense_view = denseMatrix.getView();
75 {
76 auto dense_row = dense_view.getRow( row.getRowIndex() );
77 for( int localIdx = 0; localIdx < row.getSize(); localIdx++ )
78 dense_row.setValue( row.getColumnIndex( localIdx ), row.getValue( localIdx ) );
79 };
80 TNL::Matrices::forAllRows( matrix, f );
81
84
85 /***
86 * Compute sum of elements in each row and store it into a vector.
87 */
88 TNL::Containers::Vector< double, Device > sum_vector( matrixSize );
89 auto sum_view = sum_vector.getView();
91 matrix,
93 {
94 double sum( 0.0 );
95 for( auto element : row )
96 sum += TNL::abs( element.value() );
97 sum_view[ row.getRowIndex() ] = sum;
98 } );
99
101}
102
103int
104main( int argc, char* argv[] )
105{
107 forRowsExample< TNL::Devices::Host >();
108
109#if defined( __CUDACC__ ) || defined( __HIP__ )
111 forRowsExample< TNL::Devices::GPU >();
112#endif
113}
__cuda_callable__ T abs(const T &n) This function returns absolute value of given number n. Definition Math.h:75 We start with the lambda functions (lines 17-61) defining the elements of the lambda matrix. Next, we create the lambda matrix matrix (lines 62-64) and the dense matrix denseMatrix (lines 67-68) together with the dense matrix view (line 69). The lambda function f (lines 70-74) serves for copying matrix elements from the lambda matrix to the dense matrix. The process of matrix elements copying is started by calling the method forAllRows (TNL::Matrices::LambdaMatrix::forRows, TNL::Matrices::LambdaMatrix::forAllRows) (line 75). Note, however, that use of the forElements method (TNL::Matrices::LambdaMatrix::forElements) would be more convenient for the copy operation. Next, we compute sum of absolute values of matrix elements in each row and store it in a vector (lines 83-90). Firstly we create the vector sum_vector for storing the sums (line 83) and get a vector view sum_view to get access to the vector from a lambda function. On the lines 85-90, we call lambda function for each matrix row which iterates over all matrix elements and sum their absolute values. Finally we store the result to the output vector (line 92). The result looks as follows: Running example on CPU ...
Laplace operator lambda matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:1 4:1 5:-4 6:1 9:1
Row: 6 -> 2:1 5:1 6:-4 7:1 10:1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:1 8:1 9:-4 10:1 13:1
Row: 10 -> 6:1 9:1 10:-4 11:1 14:1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Laplace operator dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 2 -> 0:0 1:0 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 3 -> 0:0 1:0 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:1 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 5 -> 0:0 1:1 2:0 3:0 4:1 5:-4 6:1 7:0 8:0 9:1 10:0 11:0 12:0 13:0 14:0 15:0
Row: 6 -> 0:0 1:0 2:1 3:0 4:0 5:1 6:-4 7:1 8:0 9:0 10:1 11:0 12:0 13:0 14:0 15:0
Row: 7 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 8 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:1 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 9 -> 0:0 1:0 2:0 3:0 4:0 5:1 6:0 7:0 8:1 9:-4 10:1 11:0 12:0 13:1 14:0 15:0
Row: 10 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:1 7:0 8:0 9:1 10:-4 11:1 12:0 13:0 14:1 15:0
Row: 11 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:1 12:0 13:0 14:0 15:0
Row: 12 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1 13:0 14:0 15:0
Row: 13 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:1 14:0 15:0
Row: 14 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:1 15:0
Row: 15 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:1
Sums in matrix rows = [ 1, 1, 1, 1, 1, 8, 8, 1, 1, 8, 8, 1, 1, 1, 1, 1 ]
Running example on GPU (CUDA) ...
Laplace operator lambda matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:1 4:1 5:-4 6:1 9:1
Row: 6 -> 2:1 5:1 6:-4 7:1 10:1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:1 8:1 9:-4 10:1 13:1
Row: 10 -> 6:1 9:1 10:-4 11:1 14:1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Laplace operator dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 1 -> 0:0 1:1 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 2 -> 0:0 1:0 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 3 -> 0:0 1:0 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:1 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 5 -> 0:0 1:1 2:0 3:0 4:1 5:-4 6:1 7:0 8:0 9:1 10:0 11:0 12:0 13:0 14:0 15:0
Row: 6 -> 0:0 1:0 2:1 3:0 4:0 5:1 6:-4 7:1 8:0 9:0 10:1 11:0 12:0 13:0 14:0 15:0
Row: 7 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 8 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:1 9:0 10:0 11:0 12:0 13:0 14:0 15:0
Row: 9 -> 0:0 1:0 2:0 3:0 4:0 5:1 6:0 7:0 8:1 9:-4 10:1 11:0 12:0 13:1 14:0 15:0
Row: 10 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:1 7:0 8:0 9:1 10:-4 11:1 12:0 13:0 14:1 15:0
Row: 11 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:1 12:0 13:0 14:0 15:0
Row: 12 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1 13:0 14:0 15:0
Row: 13 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:1 14:0 15:0
Row: 14 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:1 15:0
Row: 15 -> 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:1
Sums in matrix rows = [ 1, 1, 1, 1, 1, 8, 8, 1, 1, 8, 8, 1, 1, 1, 1, 1 ]
Method forElementsThe lambda matrix has the same element-wise interface as other matrix types, except that the matrix has no mutable storage. The available member functions are:
The lambda receives the row index, the local index, the column index, and a read-only value of the matrix element. Because the element value is evaluated on-the-fly, it is passed as const Real& regardless of whether the matrix object itself is const. The free-function TNL::Matrices::forElements supports lambda matrices through the const overloads only (see Free-function traverse and reduce API). The following example demonstrates the use of the method forElements (TNL::Matrices::LambdaMatrix::forElements) to copy the lambda matrix into the dense matrix: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Matrices/LambdaMatrix.h>
4#include <TNL/Matrices/traverse.h>
5#include <TNL/Devices/Host.h>
6#include <TNL/Devices/GPU.h>
7
8template< typename Device >
9void
10forElementsExample()
11{
12 /***
13 * Lambda functions defining the matrix.
14 */
15 auto rowLengths = [ = ] __cuda_callable__( const int rows, const int columns, const int rowIdx ) -> int
16 {
17 return columns;
18 };
19 auto matrixElements =
20 [ = ] __cuda_callable__(
21 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
22 {
23 columnIdx = localIdx;
24 value = TNL::max( rowIdx - columnIdx + 1, 0 );
25 };
26
28 auto matrix = MatrixFactory::create( 5, 5, matrixElements, rowLengths );
29
30 TNL::Matrices::DenseMatrix< double, Device > denseMatrix( 5, 5 );
31 auto denseView = denseMatrix.getView();
32
33 auto f = [ = ] __cuda_callable__( int rowIdx, int localIdx, int columnIdx, double value ) mutable
34 {
35 denseView.setElement( rowIdx, columnIdx, value );
36 };
37
38 TNL::Matrices::forElements( matrix, 0, matrix.getRows(), f );
41}
42
43int
44main( int argc, char* argv[] )
45{
47 forElementsExample< TNL::Devices::Host >();
48
49#if defined( __CUDACC__ ) || defined( __HIP__ )
51 forElementsExample< TNL::Devices::GPU >();
52#endif
53}
Helper class for creating instances of LambdaMatrix. Definition LambdaMatrix.h:597 Here, we treat the lambda matrix as if it was dense matrix and so the lambda function compressedRowLengths returns the number of the nonzero elements equal to the number of matrix columns (line 13). However, the lambda function matrixElements (lines 14-17), sets nonzero values only to lower triangular part of the matrix. The elements in the upper part are equal to zero (line 16). Next we create an instance of the lambda matrix with a help of the lambda matrix factory (TNL::Matrices::LambdaMatrixFactory) (lines 19-20) and an instance of the dense matrix (TNL::Matrices::DenseMatrix) (lines 22-23). Next we call the lambda function f by the method forElements (TNL::Matrices::LambdaMatrix::forElements) to set the matrix elements of the dense matrix denseMatrix (line 26) via the dense matrix view (denseView) (TNL::Matrices::DenseMatrixView). Note, that in the lambda function f we get the matrix element value already evaluated in the variable value as we are used to from other matrix types. So in fact, the same lambda function f would do the same job even for sparse matrix or any other. Also note, that in this case we iterate even over all zero matrix elements because the lambda function compressedRowLengths (line 13) tells so. The result looks as follows: Copying matrix on host:
Original lambda matrix:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:2 1:1 2:0 3:0 4:0
Row: 2 -> 0:3 1:2 2:1 3:0 4:0
Row: 3 -> 0:4 1:3 2:2 3:1 4:0
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Copying matrix on GPU (CUDA):
Original lambda matrix:
Row: 0 -> 0:1
Row: 1 -> 0:2 1:1
Row: 2 -> 0:3 1:2 2:1
Row: 3 -> 0:4 1:3 2:2 3:1
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
Dense matrix:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:2 1:1 2:0 3:0 4:0
Row: 2 -> 0:3 1:2 2:1 3:0 4:0
Row: 3 -> 0:4 1:3 2:2 3:1 4:0
Row: 4 -> 0:5 1:4 2:3 3:2 4:1
At the end of this part, we show two more examples, how to express a matrix approximating the Laplace operator: 1#include <iostream>
2#include <TNL/Matrices/LambdaMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8laplaceOperatorMatrix()
9{
10 /***
11 * Set matrix representing approximation of the Laplace operator on regular
12 * grid using the finite difference method.
13 */
14 const int gridSize( 4 );
15 const int matrixSize = gridSize * gridSize;
16 auto rowLengths = [ = ] __cuda_callable__( const int rows, const int columns, const int rowIdx ) -> int
17 {
18 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
19 const int gridColumn = rowIdx % gridSize;
20 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
21 gridColumn == 0 || gridColumn == gridSize - 1 )
22 return 1;
23 return 5;
24 };
25 auto matrixElements =
26 [ = ] __cuda_callable__(
27 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
28 {
29 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
30 const int gridColumn = rowIdx % gridSize;
31 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
32 gridColumn == 0 || gridColumn == gridSize - 1 )
33 {
34 columnIdx = rowIdx; // diagonal element ....
35 value = 1.0; // ... is set to 1
36 }
37 else // interior grid node
38 {
39 switch( localIdx ) // set diagonal element to 4
40 { // and the others to -1
41 case 0:
42 columnIdx = rowIdx - gridSize;
43 value = 1;
44 break;
45 case 1:
46 columnIdx = rowIdx - 1;
47 value = 1;
48 break;
49 case 2:
50 columnIdx = rowIdx;
51 value = -4;
52 break;
53 case 3:
54 columnIdx = rowIdx + 1;
55 value = 1;
56 break;
57 case 4:
58 columnIdx = rowIdx + gridSize;
59 value = 1;
60 break;
61 }
62 }
63 };
64 auto matrix =
65 TNL::Matrices::LambdaMatrixFactory< double, Device, int >::create( matrixSize, matrixSize, matrixElements, rowLengths );
67}
68
69int
70main( int argc, char* argv[] )
71{
73 laplaceOperatorMatrix< TNL::Devices::Host >();
74
75#if defined( __CUDACC__ ) || defined( __HIP__ )
76 std::cout << "Creating Laplace operator matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
77 laplaceOperatorMatrix< TNL::Devices::GPU >();
78#endif
79}
The following is another way of doing the same but with precomputed supporting vectors: 1#include <iostream>
2#include <TNL/Matrices/LambdaMatrix.h>
3#include <TNL/Devices/Host.h>
4#include <TNL/Devices/GPU.h>
5
6template< typename Device >
7void
8laplaceOperatorMatrix()
9{
10 /***
11 * Set matrix representing approximation of the Laplace operator on regular
12 * grid using the finite difference method.
13 */
14 const int gridSize( 4 );
15 const int matrixSize = gridSize * gridSize;
16 TNL::Containers::Vector< int, Device > columnOffsets{
17 0, -1, 0, 1, 0,
18 }; // helper vector for getting matrix elements column indexes
19 columnOffsets.setElement( 0, -gridSize );
20 columnOffsets.setElement( 4, gridSize );
22 TNL::Containers::Vector< double, Device > values{ 1, 1, -4, 1, 1 }; // helper vector for getting matrix elements values
24
25 auto rowLengths = [ = ] __cuda_callable__( const int rows, const int columns, const int rowIdx ) -> int
26 {
27 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
28 const int gridColumn = rowIdx % gridSize;
29
30 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
31 gridColumn == 0 || gridColumn == gridSize - 1 )
32 return 1;
33 return 5;
34 };
35
36 auto matrixElements =
37 [ = ] __cuda_callable__(
38 const int rows, const int columns, const int rowIdx, const int localIdx, int& columnIdx, double& value )
39 {
40 const int gridRow = rowIdx / gridSize; // coordinates in the numerical grid
41 const int gridColumn = rowIdx % gridSize;
42 if( gridRow == 0 || gridRow == gridSize - 1 || // boundary grid node
43 gridColumn == 0 || gridColumn == gridSize - 1 )
44 {
45 columnIdx = rowIdx; // diagonal element ....
46 value = 1.0; // ... is set to 1
47 }
48 else // interior grid node
49 {
50 columnIdx = rowIdx + columnOffsetsView[ localIdx ];
51 value = valuesView[ localIdx ];
52 }
53 };
54 auto matrix =
55 TNL::Matrices::LambdaMatrixFactory< double, Device, int >::create( matrixSize, matrixSize, matrixElements, rowLengths );
57}
58
59int
60main( int argc, char* argv[] )
61{
63 laplaceOperatorMatrix< TNL::Devices::Host >();
64
65#if defined( __CUDACC__ ) || defined( __HIP__ )
66 std::cout << "Creating Laplace operator matrix on GPU (" << TNL::Backend::getBackendName() << ") ...\n";
67 laplaceOperatorMatrix< TNL::Devices::GPU >();
68#endif
69}
__cuda_callable__ void setElement(IndexType i, ValueType value) Sets the value of the i-th element to v. ViewType getView(IndexType begin=0, IndexType end=0) Returns a modifiable view of the vector. The result of both examples looks as follows: Creating Laplace operator matrix on CPU ...
Laplace operator matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:1 4:1 5:-4 6:1 9:1
Row: 6 -> 2:1 5:1 6:-4 7:1 10:1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:1 8:1 9:-4 10:1 13:1
Row: 10 -> 6:1 9:1 10:-4 11:1 14:1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Creating Laplace operator matrix on GPU (CUDA) ...
Laplace operator matrix:
Row: 0 -> 0:1
Row: 1 -> 1:1
Row: 2 -> 2:1
Row: 3 -> 3:1
Row: 4 -> 4:1
Row: 5 -> 1:1 4:1 5:-4 6:1 9:1
Row: 6 -> 2:1 5:1 6:-4 7:1 10:1
Row: 7 -> 7:1
Row: 8 -> 8:1
Row: 9 -> 5:1 8:1 9:-4 10:1 13:1
Row: 10 -> 6:1 9:1 10:-4 11:1 14:1
Row: 11 -> 11:1
Row: 12 -> 12:1
Row: 13 -> 13:1
Row: 14 -> 14:1
Row: 15 -> 15:1
Distributed matricesTODO: Write documentation on distributed matrices. Traversing matrix rowsTODO: Add description of forRows and sequentialForRows. Flexible reduction in matrix rowsFlexible reduction in matrix rows is a powerful tool for many different matrix operations. It is represented by the method reduceRows (TNL::Matrices::DenseMatrixBase::reduceRows, TNL::Matrices::SparseMatrix::reduceRows, TNL::Matrices::TridiagonalMatrix::reduceRows, TNL::Matrices::MultidiagonalMatrix::reduceRows, TNL::Matrices::LambdaMatrix::reduceRows) and similar to the method forElements it iterates over particular matrix rows. However, it performs flexible parallel reduction in addition. For example, the matrix-vector product can be seen as a reduction of products of matrix elements with the input vector in particular matrix rows. The first element of the result vector ios obtained as: \[y_1 = a_{11} x_1 + a_{12} x_2 + \ldots + a_{1n} x_n = \sum_{j=1}^n a_{1j}x_j \] and in general i-th element of the result vector is computed as \[y_i = a_{i1} x_1 + a_{i2} x_2 + \ldots + a_{in} x_n = \sum_{j=1}^n a_{ij}x_j. \] We see that in i-th matrix row we have to compute the sum \(\sum_{j=1}^n a_{ij}x_j\) which is reduction of products \( a_{ij}x_j\). Similar to flexible parallel reduction (TNL::Algorithms::reduce) we just need to design proper lambda functions. There are three of them.
Lambda function fetchThis lambda function has the same purpose as the lambda function fetch in flexible parallel reduction for arrays and vectors (see Flexible Parallel Reduction). It is supposed to be declared as follows: The meaning of the particular parameters is as follows:
The lambda function returns a value of type Real based on the input data. Lambda function reduceThe lambda function reduce expresses reduction operation (sum, product, minimum, maximum etc.) which is supposed to be done during the flexible reduction. The meaning of the particular parameters is as follows:
Lambda function keepThe lambda function keep is new one compared to the flexible reduction for arrays, vectors or other linear structures. The reason is that the result consists of as many numbers as there are matrix rows. Result obtained for each matrix row is processed by this lambda function. It is declared as follows: The meaning of the particular parameters is as follows:
The method reduceRows (TNL::Matrices::DenseMatrixBase::reduceRows, TNL::Matrices::SparseMatrix::reduceRows, TNL::Matrices::TridiagonalMatrix::reduceRows, TNL::Matrices::MultidiagonalMatrix::reduceRows, TNL::Matrices::LambdaMatrix::reduceRows) accepts the following arguments:
Though the interface is the same for all matrix types, in the following part we will show several examples for different matrix types to better demonstrate possible ways of use of the flexible reduction for matrices. Dense matrices exampleThe following example demonstrates implementation of the dense matrix-vector product \( {\bf y} = A \vec {\bf x}\), i.e. \[ y_i = \sum_{j=0}^{columns - 1} a_{ij} x_j \text{ for } i = 0, \ldots, rows-1. \] 1#include <iostream>
2#include <functional>
3#include <TNL/Matrices/DenseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9reduceRows()
10{
11 // clang-format off
12 TNL::Matrices::DenseMatrix< double, Device > matrix {
13 { 1, 0, 0, 0, 0 },
14 { 1, 2, 0, 0, 0 },
15 { 0, 1, 8, 0, 0 },
16 { 0, 0, 1, 9, 0 },
17 { 0, 0, 0, 0, 1 },
18 };
19 // clang-format on
20 /***
21 * Allocate input and output vectors for matrix-vector product
22 */
25
26 /***
27 * Fill the input vectors with ones.
28 */
29 x = 1.0;
30
31 /***
32 * Prepare vector view for lambdas.
33 */
34 auto xView = x.getView();
35 auto yView = y.getView();
36
37 /***
38 * Fetch lambda just returns product of appropriate matrix elements and the
39 * input vector elements.
40 */
42 {
43 return xView[ columnIdx ] * value;
44 };
45
46 /***
47 * Keep lambda store the result of matrix-vector product to output vector y.
48 */
50 {
51 yView[ rowIdx ] = value;
52 };
53
54 /***
55 * Compute matrix-vector product.
56 */
58
62}
63
64int
65main( int argc, char* argv[] )
66{
68 reduceRows< TNL::Devices::Host >();
69
70#if defined( __CUDACC__ ) || defined( __HIP__ )
73 reduceRows< TNL::Devices::GPU >();
74#endif
75}
void reduceRows(IndexType begin, IndexType end, Fetch &&fetch, const Reduce &reduce, Keep &&keep, const FetchReal &identity) const Method for performing general reduction on matrix rows for constant instances. __cuda_callable__ IndexType getColumns() const Returns number of matrix columns. We set the following lambda functions:
The result looks as: Rows reduction on host:
The matrix reads as:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:1 1:2 2:0 3:0 4:0
Row: 2 -> 0:0 1:1 2:8 3:0 4:0
Row: 3 -> 0:0 1:0 2:1 3:9 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:1
The input vector is:[ 1, 1, 1, 1, 1 ]
Result of matrix-vector multiplication is: [ 1, 3, 9, 10, 1 ]
Rows reduction on GPU (CUDA):
The matrix reads as:
Row: 0 -> 0:1 1:0 2:0 3:0 4:0
Row: 1 -> 0:1 1:2 2:0 3:0 4:0
Row: 2 -> 0:0 1:1 2:8 3:0 4:0
Row: 3 -> 0:0 1:0 2:1 3:9 4:0
Row: 4 -> 0:0 1:0 2:0 3:0 4:1
The input vector is:[ 1, 1, 1, 1, 1 ]
Result of matrix-vector multiplication is: [ 1, 3, 9, 10, 1 ]
We will show one more example which is a computation of maximal absolute value in each matrix row. The results will be stored in a vector: \[y_i = \max_{j=1,\ldots,n} |a_{ij}|. \] See the following example: 1#include <iostream>
2#include <TNL/Matrices/DenseMatrix.h>
3#include <TNL/Devices/Host.h>
4
5template< typename Device >
6void
7reduceRows()
8{
9 // clang-format off
10 TNL::Matrices::DenseMatrix< double, Device > matrix {
11 { 1, 0, 0, 0, 0 },
12 { 1, 2, 0, 0, 0 },
13 { 0, 1, 8, 0, 0 },
14 { 0, 0, 1, 9, 0 },
15 { 0, 0, 0, 0, 1 },
16 };
17 // clang-format on
18 /***
19 * Find largest element in each row.
20 */
22
23 /***
24 * Prepare vector view for lambdas.
25 */
26 auto rowMaxView = rowMax.getView();
27
28 /***
29 * Fetch lambda just returns absolute value of matrix elements.
30 */
32 {
34 };
35
36 /***
37 * Reduce lambda return maximum of given values.
38 */
40 {
42 };
43
44 /***
45 * Keep lambda store the largest value in each row to the vector rowMax.
46 */
48 {
49 rowMaxView[ rowIdx ] = value;
50 };
51
52 /***
53 * Compute the largest values in each row.
54 */
55 matrix.reduceRows( 0, matrix.getRows(), fetch, reduce, keep, std::numeric_limits< double >::lowest() );
56
59}
60
61int
62main( int argc, char* argv[] )
63{
65 reduceRows< TNL::Devices::Host >();
66
67#if defined( __CUDACC__ ) || defined( __HIP__ )
69 reduceRows< TNL::Devices::GPU >();
70#endif
71}
Result reduce(Index begin, Index end, Fetch &&fetch, Reduction &&reduction, const Result &identity) reduce implements (parallel) reduction for vectors and arrays. Definition reduce.h:67 The lambda functions rare:
Note, that the identity value for the reduction is std::numeric_limits< double >::lowest. Of course, if we compute the maximum of all output vector elements, we get some kind of maximal matrix norm. The output looks as: Rows reduction on host:
Max. elements in rows are: [ 1, 2, 8, 9, 1 ]
Max. matrix norm is: 9
Rows reduction on GPU (CUDA):
Max. elements in rows are: [ 1, 2, 8, 9, 1 ]
Max. matrix norm is: 9
Sparse matrices exampleThe following example demonstrates sparse matrix-vector product: 1#include <iostream>
2#include <functional>
3#include <TNL/Matrices/SparseMatrix.h>
4#include <TNL/Devices/Host.h>
5#include <TNL/Devices/GPU.h>
6
7template< typename Device >
8void
9reduceRows()
10{
11 // clang-format off
12 TNL::Matrices::SparseMatrix< double, Device > matrix{ 5, 5,
13 {
14 { 0, 0, 1 },
15 { 1, 0, 1 }, { 1, 1, 2 },
16 { 2, 1, 1 }, { 2, 2, 8 },
17 { 3, 2, 1 }, { 3, 3, 9 },
18 { 4, 4, 1 },
19 },
20 };
21 // clang-format on
22
23 /***
24 * Allocate input and output vectors for matrix-vector product
25 */
28
29 /***
30 * Fill the input vectors with ones.
31 */
32 x = 1.0;
33
34 /***
35 * Prepare vector view for lambdas.
36 */
37 auto xView = x.getView();
38 auto yView = y.getView();
39
40 /***
41 * Fetch lambda just returns product of appropriate matrix elements and the
42 * input vector elements.
43 */
45 {
46 return xView[ columnIdx ] * value;
47 };
48
49 /***
50 * Keep lambda store the result of matrix-vector product to output vector y.
51 */
53 {
54 yView[ rowIdx ] = value;
55 };
56
57 /***
58 * Compute matrix-vector product.
59 */
61
65}
66
67int
68main( int argc, char* argv[] )
69{
71 reduceRows< TNL::Devices::Host >();
72
73#if defined( __CUDACC__ ) || defined( __HIP__ )
76 reduceRows< TNL::Devices::GPU >();
77#endif
78}
void reduceRows(IndexType begin, IndexType end, Fetch &&fetch, const Reduce &reduce, Keep &&keep, const FetchValue &identity, const Algorithms::Segments::LaunchConfiguration &launchConfig=Algorithms::Segments::LaunchConfiguration{}) const Method for performing general reduction on matrix rows for constant instances. On the lines 11-16 we set the following matrix: \[\left( \begin{array}{ccccc} 1 & . & . & . & . \\ 1 & 2 & . & . & . \\ . & 1 & 8 & . & . \\ . & . & 1 & 9 & . \\ . & . & . & . & 1 \end{array} \right) \] The lambda functions on the lines 39-48 are the same as in the example with the dense matrix. The result looks as follows: Rows reduction on host:
The matrix reads as:
Row: 0 -> 0:1
Row: 1 -> 0:1 1:2
Row: 2 -> 1:1 2:8
Row: 3 -> 2:1 3:9
Row: 4 -> 4:1
The input vector is: [ 1, 1, 1, 1, 1 ]
Result of matrix-vector multiplication is: [ 1, 3, 9, 10, 1 ]
Rows reduction on GPU (CUDA):
The matrix reads as:
Row: 0 -> 0:1
Row: 1 -> 0:1 1:2
Row: 2 -> 1:1 2:8
Row: 3 -> 2:1 3:9
Row: 4 -> 4:1
The input vector is: [ 1, 1, 1, 1, 1 ]
Result of matrix-vector multiplication is: [ 1, 3, 9, 10, 1 ]
Tridiagonal matrices exampleIn this example, we will compute maximal absolute value in each row of the following tridiagonal matrix: \[\left( \begin{array}{ccccc} 1 & 3 & & & & \\ 2 & 1 & 3 & & & \\ & 2 & 1 & 3 & & \\ & & 2 & 1 & 3 & \\ & & & 2 & 1 & 3 \end{array} \right). \] The source code reads as follows: 1#include <iostream>
2#include <TNL/Matrices/TridiagonalMatrix.h>
3#include <TNL/Matrices/reduce.h>
4#include <TNL/Devices/Host.h>
5
6template< typename Device >
7void
8reduceRows()
9{
10 /***
11 * Set the following matrix (dots represent zero matrix elements and zeros are
12 * padding zeros for memory alignment):
13 *
14 * 0 / 1 3 . . . \ -> { 0, 1, 3 }
15 * | 2 1 3 . . | -> { 2, 1, 3 }
16 * | . 2 1 3 . | -> { 2, 1, 3 }
17 * | . . 2 1 3 | -> { 2, 1, 3 }
18 * \ . . . 2 1 / 0 -> { 2, 1, 0 }
19 *
20 */
22 5, // number of matrix columns
23 {
24 { 0, 1, 3 }, // matrix elements
25 { 2, 1, 3 },
26 { 2, 1, 3 },
27 { 2, 1, 3 },
28 { 2, 1, 3 },
29 } );
31
32 /***
33 * Find largest element in each row.
34 */
36
37 /***
38 * Prepare vector view for lambdas.
39 */
40 auto rowMaxView = rowMax.getView();
41
42 /***
43 * Fetch lambda just returns absolute value of matrix elements.
44 */
46 {
48 };
49
50 /***
51 * Reduce lambda return maximum of given values.
52 */
54 {
56 };
57
58 /***
59 * Keep lambda store the largest value in each row to the vector rowMax.
60 */
62 {
63 rowMaxView[ rowIdx ] = value;
64 };
65
66 /***
67 * Compute the largest values in each row.
68 */
69 TNL::Matrices::reduceRows( view, 0, view.getRows(), fetch, reduce, keep, std::numeric_limits< double >::lowest() );
70
73}
74
75int
76main( int argc, char* argv[] )
77{
79 reduceRows< TNL::Devices::Host >();
80
81#if defined( __CUDACC__ ) || defined( __HIP__ )
83 reduceRows< TNL::Devices::GPU >();
84#endif
85}
void reduceRows(Matrix &matrix, IndexBegin begin, IndexEnd end, Fetch &&fetch, Reduction &&reduction, Store &&store, const FetchValue &identity, Algorithms::Segments::LaunchConfiguration launchConfig=Algorithms::Segments::LaunchConfiguration()) Performs parallel reduction within each matrix row over a given range of row indexes. Here we first set the tridiagonal matrix (lines 10-27). Next we allocate the vector rowMax where we will store the results (line 32). The lambda function are:
Note, that the identity value for the reduction is std::numeric_limits< double >::lowest. The results looks as follows: Rows reduction on host:
The matrix reads as:
Row: 0 -> 0:1 1:3
Row: 1 -> 0:2 1:1 2:3
Row: 2 -> 1:2 2:1 3:3
Row: 3 -> 2:2 3:1 4:3
Row: 4 -> 3:2 4:1
Max. elements in rows are: [ 3, 3, 3, 3, 2 ]
Rows reduction on GPU (CUDA):
The matrix reads as:
Row: 0 -> 0:1 1:3
Row: 1 -> 0:2 1:1 2:3
Row: 2 -> 1:2 2:1 3:3
Row: 3 -> 2:2 3:1 4:3
Row: 4 -> 3:2 4:1
Max. elements in rows are: [ 3, 3, 3, 3, 2 ]
Multidiagonal matrices exampleThe next example computes again the maximal absolute value in each row. Now, we do it for multidiagonal matrix the following form: \[\left( \begin{array}{ccccc} 1 & & & & \\ 2 & 1 & & & \\ 3 & 2 & 1 & & \\ & 3 & 2 & 1 & \\ & & 3 & 2 & 1 \end{array} \right) \] We first create vector rowMax into which we will store the results and fetch it view rowMaxView (line 39). Next we prepare necessary lambda functions:
Finally, we call the method reduceRows (TNL::Matrices::MultidiagonalMatrix::reduceRows) with parameters telling the interval of rows to be processed (the first a [Page truncated to keep GeezerVison snappy.] | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |