[英]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。
J
可以產生一個排列。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.