OpenMP

In 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.

Resources

1.Bisqwit’s guide to OpenMP 2. Information on using Eigen with 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)
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)")

These settings can also be provided to Rcpp::cppFunction by specifying the includes and plugins arguments, but the above formulation translates better to putting this code in packages.

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(20)
##  [1] 0 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0

Matrix Multiplication

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 
##    8.23    0.00    8.24

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 
##  214.64    0.28  107.89
system.time({r2 <- multiply_matrices(A, B, 4)})
##    user  system elapsed 
##  237.07    0.39   60.51

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 
##  293.98    0.62   75.47

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 
##   10.02    0.32   10.35
system.time({r3 <- multiply_matrices3(A, B, 2)})
##    user  system elapsed 
##   10.47    0.53    5.80
system.time({r3 <- multiply_matrices3(A, B, 4)})
##    user  system elapsed 
##   16.11    0.64    4.86
system.time({r3 <- multiply_matrices3(A, B, 8)})
##    user  system elapsed 
##   42.30    0.51    7.11

Now we’re getting somewhere!

Let’s compare this manual parallelization to what Eigen can achieve. Compile the following code and examine the times:

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>")

t1 <- system.time({r4 <- multiply_matrices4(A, B, 1)})[3]
t2 <- system.time({r4 <- multiply_matrices4(A, B, 2)})[3]
t3 <- system.time({r4 <- multiply_matrices4(A, B, 4)})[3]
t4 <- system.time({r4 <- multiply_matrices4(A, B, 8)})[3]
plot(c(1,2,4,8), c(t1,t2,t3,t4), 
     main = "Runtime by Number of Threads", 
     xlab ="Threads", ylab = "Seconds", type = "b", ylim = c(0,4))

For an idea of how this speedup is achieved, review these slides and this Wikipedia article

Interestingly, a lot of this happens automatically when we use Eigen. Try compiling and running the following code - what does it say about Eigen’s default use of threads?

cppFunction("
Eigen::MatrixXd multiply_matrices(Eigen::MatrixXd A, Eigen::MatrixXd B){
  int n = Eigen::nbThreads( );
  Rcpp::Rcout << \"Threads: \" << n << std::endl;
  if (A.cols() != B.rows()){
    Rcpp::stop(\"Invalid dimensions\");
  }
  return(A*B);
}",depends = "RcppEigen")

system.time({multiply_matrices(A, B)})

Exercise

Read through and follow along with this tutorial. As you can see, this work has strong implications for challenge 5.

The homework for this lab is to 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. Specifically:

  1. On the UI research-git site, fork a copy of the ParallelExamples R package, and clone your fork to your local machine.
  2. Add your implementation of the Gompertz likelihood to the package. The function should be named “gompertz_likelihood_”, where your first name is substituted for “”.
  3. Make sure to add appropriate documentation to your function.
  4. Push your changes to your forked repository.
  5. Issue a merge request against the original repository, so we can put together a collection of solutions.
  6. Upload a compiled Rmd file to ICON which loads your version of the ParallelExamples R package and produces a graph demonstrating the tradeoff between execution time and data size.