簡體   English   中英

如何使用 GPU.js 運行此 function?

[英]How do I run this function with GPU.js?

我想在 GPU 上運行這個排列 function。

function* permute(permutation) {
  var length = permutation.length;
  var c = Array(length).fill(0);
  var i = 1;
  var k;
  var p;

  yield permutation.slice();
  while (i < length) {
    if (c[i] < i) {
      k = i % 2 && c[i];
      p = permutation[i];
      permutation[i] = permutation[k];
      permutation[k] = p;
      ++c[i];
      i = 1;
      yield permutation.slice();
    } else {
      c[i] = 0;
      ++i;
    }
  }
}

要在 GPU 上運行它,我嘗試使用https://gpu.rocks/但我不明白他們關於如何設置線程的示例。 我應該如何編寫這個排列 function 以便我可以在 GPU 上的瀏覽器中運行它?

GPU.js 僅支持少數操作,因為它被轉換為着色器。 在此處的測試中,您不能使用它來生成超過 100k 個元素的輸出。

支持的操作非常有限,例如,您不能分配給數組元素,這是由於底層計算單元的性質造成的。 您還必須注意分支分歧

需要兩個步驟來實現您的 function 以使其可用於 kernel。

  1. 使其並行:您的實現是迭代的,每次迭代都會根據前一次迭代的結果構建一個新結果。 我創建的是一個 function,給定迭代數J可以產生一個排列。
  2. 使其成為標量且無需修改數組:function 用於計算排列交換數組上的元素,因此需要分配給數組元素。 為了防止我創建的是一個循環,我在其中跟蹤每個元素的位置。 如果給定元素以 position I結束,則返回該元素。 請注意,必須為每個排列中的每個元素調用一次此 function。

 const gpu = new GPU(); // For reference // This is the function to compute the J'th permutation // of N elements. Rewrited to create the kernel. function permutation(J, N) { const arr = [] for(let i = 0; i < N; ++i)arr[i] = i; let j = J; for(let i = 2; i <= N; ++i){ let e1 = j % i; const t = arr[e1]; arr[e1] = arr[i-1]; arr[i-1] = t; j = (j - e1) / i; } return arr; } function permuteAt() { const N = this.constants.length; let I = N - this.thread.x - 1; let J = this.thread.y; for(let d = 0; d < N; ++d){ // check if the I'th element of the J'th permutation is d let dPos = d; let j = J; let i = 0; for(let i = 2; i <= N; ++i){ let e1 = j % i; let e2 = i - 1; // track the movements element d if(e1 == dPos){ dPos = e2; }else if(e2 == dPos){ dPos = e1; } j = (j - e1) / i; } // element d ended at position i // console.log(JSON.stringify({dPos, I, J, N, t: this.thread})) if(dPos == I){ return d; } } return -1; } // Run it in javascript let result; const t0Js = Date.now() for(let i = 0; i < 1000; ++i){ result = [0,1,2,3,4,5,6,7,8,9].map(v => permuteAt.apply({ thread: {x: i, y: v}, constants: {length: 10} })) } const tfJs = Date.now(); console.log('time spend in javascript: ', (tfJs - t0Js)/10000); const generatePermutations = gpu.createKernel(permuteAt).setOutput([10, 10000]).setConstants({length: 10}); const t0GPU = Date.now() for(let i = 0; i < 100; ++i){ const c = generatePermutations(); } const tfGPU = Date.now(); console.log('time spend in gpu: ', (tfGPU - t0GPU)/10000/100);
 <script src="https://unpkg.com/gpu.js@latest/dist/gpu-browser.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM