I have to implement the following algorithm in GPU
for(int I = 0; I < 1000; I++){
VAR1[I+1] = VAR1[I] + VAR2[2*K+(I-1)];//K is a constant
}
Each iteration is dependent on previous so the parallelizing is difficult. I am not sure if atomic operation is valid here. What can I do?
EDIT:
The VAR1 and VAR2 both are 1D array.
VAR1[0] = 1
This is in a category of problems called recurrence relations. Depending on the structure of the recurrence relation, there may exist closed form solutions that describe how to compute each element individually (i.e. in parallel, without recursion). One of the early seminal papers (on parallel computation) was Kogge and Stone, and there exist recipes and strategies for parallelizing specific forms.
Sometimes recurrence relations are so simple that we can identify a closed-form formula or algorithm with a little bit of "inspection". This short tutorial gives a little bit more treatment of this idea.
In your case, let's see if we can spot anything just by mapping out what the first few terms of
VAR1
should look like, substituting previous terms into newer terms:Hopefully what jumps out at you is that the
VAR2[]
terms above follow a pattern of a prefix sum.This means one possible solution method could be given by:
Now, a prefix sum can be done in parallel (this is not truly a fully independent operation, but it can be parallelized. I don't want to argue too much about terminology or purity here. I'm offering one possible method of parallelization for your stated problem, not the only way to do it.) To do a prefix sum in parallel on the GPU, I would use a library like CUB or Thrust. Or you can write your own although I wouldn't recommend it.
Notes:
the use of -1 or -2 as an offset to
i
for the prefix sum may be dictated by your use of aninclusive
orexclusive
scan or prefix sum operation.VAR2
must be defined over an appropriate domain to make this sensible. However that requirement is implicit in your problem statement.Here is a trivial worked example. In this case, since the
VAR2
indexing term2K+(I-1)
just represents a fixed offset toI
(2K-1
), we are simply using an offset of 0 for demonstration purposes, soVAR2
is just a simple array over the same domain asVAR1
. And I am definingVAR2
to just be an array of all1
, for demonstration purposes. The gpu parallel computation occurs in theVAR1
vector, the CPU equivalent computation is just computed on-the-fly in thecpu
variable for validation purposes:For an additional reference particular to the usage of scan operations to solve linear recurrence problems, refer to Blelloch's paper here section 1.4.