c++rdistancercpprcppparallel

RcppParallel Parallelizing distance computation: segfault


I have a matrix, for which I want to compute the distance (let's say Euclidean) between the ith row and every other row(i.e. I want the ith row of the pairwise distance matrix).

#include <Rcpp.h>
#include <cmath>
#include <algorithm>
#include <RcppParallel.h>
//#include <RcppArmadillo.h>
#include <queue>

using namespace std;
using namespace Rcpp;
using namespace RcppParallel;

// [[Rcpp::export]]
double dist_fun(NumericVector row1, NumericVector row2){
   double rval = 0;
   for (int i = 0; i < row1.length(); i++){
      rval += (row1[i] - row2[i]) * (row1[i] - row2[i]);
   }
   return rval;
}

// [[Rcpp::export]]
NumericVector dist_row(NumericMatrix mat, int i){
   NumericVector row(mat.nrow());

   NumericMatrix::Row row1 = mat.row(i - 1);
   for (int j = 0; j < mat.nrow(); j++){
      NumericMatrix::Row row2 = mat.row(j);

      row(j) = dist_fun(row1, row2);
   }
   return row;
}

// [[Rcpp::depends(RcppParallel)]]
struct JsDistance: public Worker {

   // input matrix to read from
   const NumericMatrix mat;
   int i;

   // output vector to write to
   NumericVector output;

   // initialize from Rcpp input and output matrixes (the RMatrix class
   // can be automatically converted to from the Rcpp matrix type)
   JsDistance(const NumericMatrix mat, int i, NumericVector output)
      : mat(mat), i(i), output(output) {}


   // function call operator that work for the specified range (begin/end)
    void operator()(std::size_t begin, std::size_t end) {
      NumericVector row1 = mat.row(i);
      for (std::size_t j = begin; j < end; j++) {

         NumericVector row2 = mat.row(j);
         output[j] = dist_fun(row1, row2);
      }
    }
};

// [[Rcpp::export]]
NumericVector parallel_dist_row(NumericMatrix mat, int i) {

   // allocate the matrix we will return
   NumericVector output(mat.nrow());

   // create the worker
   JsDistance JsDistance(mat, i, output);

   // call it with parallelFor
   parallelFor(0, mat.nrow(), JsDistance);
   return output;
}

The sequential way using Rcpp is the function 'row_dist' as written above. Yet the matrix I want to work with is very large so I want to parallelize it. But then I will run into a segfault error which I don't quite understand why. To trigger the error you can run the following code:

library(Rcpp)
library(RcppParallel)

setThreadOptions(numThreads = 20)


set.seed(42)
X = matrix(rnorm(10000 * 400), 10000, 400)
sourceCpp("question.cpp")


start1 = proc.time()
print(dist_row(X, 2)[1:30])
print(proc.time() - start1)

start2 = proc.time()
print(parallel_dist_row(X, 2)[1:30])
print(proc.time() - start2)

enter image description here

Can someone give me some hint about what I did wrong? Thanks in advance for your time!

=======================================================================

Edit:

inline double d(double a, double b){
   return fabs(a - b);
}

    // [[Rcpp::depends(RcppParallel)]
struct dtwDistance: public Worker {

  // Input matrix to read from must be of the RMatrix<T> form
  // if using Rcpp objects
  const RMatrix<double> mat;
  int i;

  // Output vector to write to must be of the RVector<T> form
  // if using Rcpp objects
  RVector<double> output;

  // initialize from Rcpp input and output matrixes (the RMatrix class
  // can be automatically converted to from the Rcpp matrix type)
  dtwDistance(const NumericMatrix mat, int i, NumericVector output)
    : mat(mat), i(i - 1), output(output) {}

  // Note the -1 ^^^^ to match results from prior function

  // Function call operator to iterate over a specified range (begin/end)
  void operator()(std::size_t begin, std::size_t end) {

    RMatrix<double>::Row row1 = mat.row(i);

    for (std::size_t j = begin; j < end; ++j) {

      RMatrix<double>::Row row2 = mat.row(j);

      size_t n = row1.length();
      size_t m = row2.length();
      NumericMatrix cost(n + 1, m + 1);

      for (int ii = 1; ii <= n; ii++){
        cost(i, 0) = numeric_limits<double>::infinity();
      }

      for (int jj = 1; jj <= m; jj++){
        cost(0, j) = numeric_limits<double>::infinity();
      }

      for (int ii = 1; ii <= n; ii++){
          for (int jj = 1; jj <= m; jj++){
            double dist = d(row1[ii - 1], row2[jj - 1]);
            cost(ii, jj) = dist + min(min(cost(ii - 1, jj), cost(ii, jj - 1)), cost(ii - 1, jj - 1));
            //cout << ii << ", " << jj << ", " << cost(ii, jj) << "\n";
          }
      }
      output[j] = cost(n, m);

    }
  }
};
// [[Rcpp::export]]
NumericVector parallel_dist_row_dtw(NumericMatrix mat, int i) {

   // allocate the matrix we will return
   //RMatrix<double> input(mat);
   NumericVector y(mat.nrow());
   //RVector<double> output(y);

   // create the worker
   dtwDistance dtwDistance(mat, i, y);

   // call it with parallelFor
   parallelFor(0, mat.nrow(), dtwDistance);
   return y;
}

The distance I needed to calculate is the dynamic time warping distance. I implemented it as above. Yet when running, it will give a 'stack imbalance' warning. And there will be a segfault after several runs. I'm wondering what is the problem now.

To trigger the problem, I did:

library(Rcpp)
library(RcppParallel)
setThreadOptions(numThreads = 4)
sourceCpp("scripts/chisq_dtw.cpp")
set.seed(42)
X = matrix(rnorm(1000), 100, 10)

parallel_dist_row_dtw(X, 1)
parallel_dist_row_dtw(X, 2)
parallel_dist_row_dtw(X, 3)
parallel_dist_row_dtw(X, 4)
parallel_dist_row_dtw(X, 5)

Solution

  • The issue is you are not using the thread-safe wrapper around R objects via RMatrix<T> and RVector<T>. These classes are important because of the parallelization being executed on a background thread, which is an area that is not safe to call R or Rcpp APIs. The official documentation emphasizes this in the Safe Accessors section.

    In particular, we have:

    To provide safe and convenient access to the arrays underlying R vectors and matrices RcppParallel introduces several accessor classes:

    RVector<T> — Wrap R vectors of various types

    RMatrix<T> — Wrap R matrices of various types (also includes Row and Column classes)

    To create a thread safe accessor for an Rcpp vector or matrix just construct an instance of RVector or RMatrix with it.


    Code Fix

    So, your work can be fixed by switching *Matrix to RMatrix<T> and *Vector to RVector<T>.

    struct JsDistance: public Worker {
    
      // Input matrix to read from must be of the RMatrix<T> form
      // if using Rcpp objects
      const RMatrix<double> mat;
      int i;
    
      // Output vector to write to must be of the RVector<T> form
      // if using Rcpp objects
      RVector<double> output;
    
      // initialize from Rcpp input and output matrixes (the RMatrix class
      // can be automatically converted to from the Rcpp matrix type)
      JsDistance(const NumericMatrix mat, int i, NumericVector output)
        : mat(mat), i(i - 1), output(output) {}
    
      // Note the -1 ^^^^ to match results from prior function
    
      // Function call operator to iterate over a specified range (begin/end)
      void operator()(std::size_t begin, std::size_t end) {
    
        RMatrix<double>::Row row1 = mat.row(i);
    
        for (std::size_t j = begin; j < end; ++j) {
    
          RMatrix<double>::Row row2 = mat.row(j);
    
          double rval = 0;
          for (unsigned int k = 0; k < row1.length(); ++k) {
            rval += (row1[k] - row2[k]) * (row1[k] - row2[k]);
          }
    
          output[j] = rval;
    
        }
      }
    };
    

    In particular, the data types used here are of the form RMatrix<double> even for accessing the matrix.

    Also, within the parallelized version there is a missing i-1 statement. To remedy this, I've opted to have it taken care of in the constructor of JSDistance.


    Test

    set.seed(42)
    X = matrix(rnorm(10000 * 400), 10000, 400)
    
    start1 = proc.time()
    
    print(dist_row(X, 2)[1:30])
    # [1] 811.8873   0.0000 799.8153 810.1442 720.3232 730.6083 797.8441 781.8066 827.1511 834.1863 842.9392 850.2476 724.5842 673.1428 775.0994
    # [16] 805.5752 804.9281 774.9770 799.7669 870.3187 815.1129 934.7581 726.1554 804.2097 758.4943 772.8931 806.6026 715.8257 847.8980 831.7555
    
    print(proc.time() - start1)
    # user  system elapsed 
    # 0.22    0.00    0.23 
    
    start2 = proc.time()
    
    print(parallel_dist_row(X, 2)[1:30])
    # [1] 811.8873   0.0000 799.8153 810.1442 720.3232 730.6083 797.8441 781.8066 827.1511 834.1863 842.9392 850.2476 724.5842 673.1428 775.0994
    # [16] 805.5752 804.9281 774.9770 799.7669 870.3187 815.1129 934.7581 726.1554 804.2097 758.4943 772.8931 806.6026 715.8257 847.8980 831.7555
    
    print(proc.time() - start2)
    #   user  system elapsed 
    #   0.28    0.00    0.06 
    
    all.equal(parallel_dist_row(X, 2), dist_row(X, 2))
    # [1] TRUE