Search code examples
c++cudathrust

thrust::exclusive_scan_by_key unexpected behavior


int data[ 10 ] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int keys[ 10 ] = { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
thrust::exclusive_scan_by_key( keys, keys + 10, data, data );

By the examples at Thrust Site I expected 0,0,1,1,2,2,3,3,4,4, but got 0,0,0,0,0,0,0,0,0 instead; Is it bug, or is there somewhere something the defines this behavior?

More importantly, assuming this is not a bug, is there a way to achieve this effect easily?


Solution

  • I don't think you understand what scan_by_key does. From the documentation:

    "Specifically, consecutive iterators i and i+1 in the range [first1, last1) belong to the same segment if binary_pred(*i, *(i+1)) is true, and belong to different segments otherwise"

    scan_by_key requires that your key array mark distinct segments using contiguous values:

    keys: 0 0 0 1 1 1 0 0 0 1 1 1
    seg#: 0 0 0 1 1 1 2 2 2 3 3 3
    

    thrust compares adjacent keys to determine segments.

    Your keys are producing a segment map like this:

    int keys[ 10 ] = { 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 };
              seg#:    0  1  2  3  4  5  6  7  8  9
    

    Since you are doing an exclusive scan, the correct answer to such a segment map (regardless of the data) would be all zeroes.

    It's not entirely clear what "this effect" is that you want to achieve, but you may want to do back-to-back stable sort by key operations, reversing the sense of keys and values, to rearrange this data to group the segments (i.e. keys 1 and 2) together.