Home > database >  A thrust problem: How can I copy a host_vector to device_vector with a customized permutation order?
A thrust problem: How can I copy a host_vector to device_vector with a customized permutation order?

Time:01-20

I have an array in host, and I want to transfer it to device with a different order.

I have tried this toy code complied with nvc test.cpp -stdpar

$ cat test.cpp
#include <iostream>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/copy.h>
#include <thrust/sequence.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <array>

using Real = float;

int main(int argc, char* argv[]) {

        std::array<std::size_t,6> idx{0,1,2,3,5,4};


        thrust::host_vector<Real> hvec(6);

        thrust::sequence(hvec.begin(),hvec.end());

        typedef thrust::host_vector<Real>::iterator EleItor;
        typedef std::array<std::size_t,6>::iterator IdxItor;

        thrust::permutation_iterator<EleItor,IdxItor> itor(hvec.begin(),idx.begin());

        thrust::device_vector<Real> test;
        thrust::copy(itor,itor 6,test);  // error
        thrust::copy(itor,itor 6,std::ostream_iterator<Real>(std::cout," ");  

}

The problem is that thrust::copy does not allow copy from host to device, how can I bypass this restriction?

CodePudding user response:

According to the documentation is is possible to use thrust::copy to copy from host to device, but you need to pass the device iterator:

//-----------------------------vvvvvvvv--
thrust::copy(itor, itor 6, test.begin());

Note that before that you need to allocate memory for the device vector.
Fortunately the thrust::device_vector has a constructor taking a size that will allocate the required memory.
You can use something like:

thrust::device_vector<Real> test(host_vector.size());

Edit (credit goes to @paleonix):
There is another constructor taking iterators, i.e. one can do both allocation and copy as initialization in one line which also has the advantage of avoiding the unnecessary initialization of the memory to 0.0f.

thrust::device_vector<Real> test(itor, itor 6);
  • Related