How to efficiently feed the output of a GPU JS function back into it?

249 Views Asked by At

I am attempting to use GPU JS to accelerate the performance of a dynamic programming algorithm.

Here is my current code:

let pixels = new Uint32Array(5 * 5);

for (let i = 0; i < pixels.length; i++) {
  pixels[i] = i;
}

function kFunction() {
  let width = this.output.x;
  let row = this.constants.row;
  let col = this.thread.x;

  let prevRow = (row - 1) * width;

  let base = (row * width) + col;
  let prevBase = (prevRow * width) + col;

  let nw = this.constants.pixels[prevBase - 1];
  let n = this.constants.pixels[prevBase];
  let ne = this.constants.pixels[prevBase + 1];

  return this.constants.pixels[base] + Math.min(Math.min(nw, n), ne);
}

var gpuKernel = gpu.createKernel(kFunction)
                   .setConstants({ pixels: pixels, row: 1 })
                   .setOutput([5, 5]);

console.log(gpuKernel());

This works, except I would like to have it run on each row, instead of just row 1.

The issue is that in order to run on the next row, the previous row has to be computed first (for rows n > 1 the nw, n, and ne values should be computed based on the previous row's value instead of pixels)

I could easily fix this by putting createKernel in a loop and running it on every row, but I believe that constantly returning the value from the GPU and sending it back is slow. I heard that Textures might be able to solve this, to maintain some sort of state, but I cannot find any relevant information on them.

Is what I'm asking to do possible? To have a single GPU function call to compute the entire cumulative sum table without passing data back and forth for each row computed?

0

There are 0 best solutions below