Last class, we introduced OpenMP in the ‘ParallelExamples’ R package. While it’s usually advisable to use this low-level functionality from within a package, we can also use Rcpp’s ‘cppFunction’ to compile and run functions utilizing OpenMP.
Just as in the R-package world, we need to make sure that the compiler knows we want to depend on OpenMP functionality. In a package, these instructions are placed into the Makevars file. When compiling functions in open R code, we need to set some environment variables by hand:
library(Rcpp)
## Warning: package 'Rcpp' was built under R version 3.4.2
library(RcppEigen)
Sys.setenv("PKG_CXXFLAGS"="-std=c++11 $(SHLIB_OPENMP_CXXFLAGS)")
Sys.setenv("PKG_CFLAGS"= "$(SHLIB_OPENMP_CFLAGS")
Sys.setenv("PKG_LIBS" = "$(SHLIB_OPENMP_CFLAGS)")
We can now compile and run multithreaded programs:
cppFunction("
Eigen::VectorXd example1(int n){
Eigen::VectorXd out = Eigen::VectorXd::Zero(n);
#pragma omp parallel
{
int thread_idx = omp_get_thread_num();
if (thread_idx >= 0 && thread_idx < out.size()){
out[thread_idx] = thread_idx;
}
}
return(out);
}",depends = "RcppEigen", includes = "#include <omp.h>")
example1(10)
## [1] 0 1 2 3 4 5 6 7 0 0
Let’s consider matrix multiplication again. Consider the following task:
A <- matrix(rnorm(100000*1000), ncol = 100000)
B <- matrix(rnorm(100000*100), nrow = 100000)
system.time({r <- A %*% B})
## user system elapsed
## 5.84 0.00 5.83
This is a pretty challenging matrix multiplication problem, so we might consider parallelizing it. At the end of last class, we discussed the following algorithm:
cppFunction("
Eigen::MatrixXd multiply_matrices(Eigen::MatrixXd A, Eigen::MatrixXd B, int nthreads){
Eigen::initParallel(); // Optional for modern Eigen and C++ 11
omp_set_num_threads(nthreads);
if (A.cols() != B.rows()){
Rcpp::stop(\"Invalid dimensions\");
}
Eigen::MatrixXd out = Eigen::MatrixXd::Zero(A.rows(), B.cols());
const int n = out.rows();
const int p = out.cols();
#pragma omp parallel
{
// Create the output object:
#pragma omp for
for (int i = 0; i < n*p; i++){
int arow = i % n;
int bcol = i/n;
out(arow, bcol) = A.row(arow).dot(B.col(bcol));
}
}
return(out);
}",depends = "RcppEigen", includes = "#include <omp.h>")
Unfortunately, this represents a pretty bad tradeoff between parallel overhead and computation:
system.time({r2 <- multiply_matrices(A, B, 2)})
## user system elapsed
## 130.07 0.12 65.38
system.time({r2 <- multiply_matrices(A, B, 4)})
## user system elapsed
## 148.48 0.20 37.89
We could consider simplifying our code to avoid having to compute the row and column indices, but this isn’t enough to make our code competative with the serial version provided by R:
cppFunction("
Eigen::MatrixXd multiply_matrices2(Eigen::MatrixXd A, Eigen::MatrixXd B, int nthreads){
omp_set_num_threads(nthreads);
Eigen::initParallel(); // Optional for modern Eigen and C++ 11
if (A.cols() != B.rows()){
Rcpp::stop(\"Invalid dimensions\");
}
Eigen::MatrixXd out = Eigen::MatrixXd::Zero(A.rows(), B.cols());
const int n = out.rows();
const int p = out.cols();
#pragma omp parallel
{
// Create the output object:
#pragma omp for collapse(2)
for (int i = 0; i < n; i++){
for (int j = 0; j < p; j++){
out(i, j) = A.row(i).dot(B.col(j));
}
}
}
return(out);
}",depends = "RcppEigen", includes = "#include <omp.h>")
system.time({r3 <- multiply_matrices2(A, B, 4)})
## user system elapsed
## 142.64 0.13 36.24
One thing we can consider is changing the ratio between the number of total tasks and the amount of computation in each task:
cppFunction("
Eigen::MatrixXd multiply_matrices3(Eigen::MatrixXd A, Eigen::MatrixXd B, int nthreads){
omp_set_num_threads(nthreads);
Eigen::initParallel(); // Optional for modern Eigen and C++ 11
if (A.cols() != B.rows()){
Rcpp::stop(\"Invalid dimensions\");
}
Eigen::MatrixXd out = Eigen::MatrixXd::Zero(A.rows(), B.cols());
const int n = out.rows();
#pragma omp parallel
{
// Create the output object:
#pragma omp for
for (int i = 0; i < n; i++){
out.row(i) = A.row(i) * B;
}
}
return(out);
}",depends = "RcppEigen", includes = "#include <omp.h>")
system.time({r3 <- multiply_matrices3(A, B, 1)})
## user system elapsed
## 7.27 0.11 7.38
system.time({r3 <- multiply_matrices3(A, B, 2)})
## user system elapsed
## 7.99 0.30 4.30
system.time({r3 <- multiply_matrices3(A, B, 4)})
## user system elapsed
## 9.44 0.34 2.79
system.time({r3 <- multiply_matrices3(A, B, 8)})
## user system elapsed
## 17.82 0.45 2.82
Now we’re getting somewhere!
Let’s compare this manual parallelization to what Eigen can achieve:
cppFunction("
Eigen::MatrixXd multiply_matrices4(Eigen::MatrixXd A, Eigen::MatrixXd B, int nthreads){
Eigen::initParallel(); // Optional for modern Eigen and C++ 11
omp_set_num_threads(nthreads);
Eigen::setNbThreads(nthreads);
if (A.cols() != B.rows()){
Rcpp::stop(\"Invalid dimensions\");
}
return(A*B);
}",depends = "RcppEigen", includes = "#include <omp.h>")
system.time({r4 <- multiply_matrices4(A, B, 1)})
## user system elapsed
## 1.62 0.16 1.78
system.time({r4 <- multiply_matrices4(A, B, 2)})
## user system elapsed
## 1.69 0.15 1.06
system.time({r4 <- multiply_matrices4(A, B, 4)})
## user system elapsed
## 2.34 0.13 0.82
system.time({r4 <- multiply_matrices4(A, B, 8)})
## user system elapsed
## 8.86 0.17 1.53
For an idea of how this speedup is achieved, review these slides and this Wikipedia article
Read through and follow along with this tutorial. As you can see, this work has strong implications for challenge 5. Write a version of the challenge-5 likelihood which uses OpenMP, and produce a graph which explores execution time by number of threads and data size.