• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

gpujs/gpu.js: GPU Accelerated JavaScript

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

gpujs/gpu.js

开源软件地址:

https://github.com/gpujs/gpu.js

开源编程语言:

JavaScript 98.5%

开源软件介绍:

Logo

GPU.js

GPU.js is a JavaScript Acceleration library for GPGPU (General purpose computing on GPUs) in JavaScript for Web and Node. GPU.js automatically transpiles simple JavaScript functions into shader language and compiles them so they run on your GPU. In case a GPU is not available, the functions will still run in regular JavaScript. For some more quick concepts, see Quick Concepts on the wiki.

Join the chat at https://gitter.im/gpujs/gpu.js Slack

What is this sorcery?

Creates a GPU accelerated kernel transpiled from a javascript function that computes a single element in the 512 x 512 matrix (2D array). The kernel functions are ran in tandem on the GPU often resulting in very fast computations! You can run a benchmark of this here. Typically, it will run 1-15x faster depending on your hardware. Matrix multiplication (perform matrix multiplication on 2 matrices of size 512 x 512) written in GPU.js:

Browser

<script src="dist/gpu-browser.min.js"></script>
<script>
    // GPU is a constructor and namespace for browser
    const gpu = new GPU();
    const multiplyMatrix = gpu.createKernel(function(a, b) {
        let sum = 0;
        for (let i = 0; i < 512; i++) {
            sum += a[this.thread.y][i] * b[i][this.thread.x];
        }
        return sum;
    }).setOutput([512, 512]);

    const c = multiplyMatrix(a, b);
</script>

CDN

https://unpkg.com/gpu.js@latest/dist/gpu-browser.min.js
https://cdn.jsdelivr.net/npm/gpu.js@latest/dist/gpu-browser.min.js

Node

const { GPU } = require('gpu.js');
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a, b) {
    let sum = 0;
    for (let i = 0; i < 512; i++) {
        sum += a[this.thread.y][i] * b[i][this.thread.x];
    }
    return sum;
}).setOutput([512, 512]);

const c = multiplyMatrix(a, b);

Typescript

import { GPU } from 'gpu.js';
const gpu = new GPU();
const multiplyMatrix = gpu.createKernel(function(a: number[][], b: number[][]) {
  let sum = 0;
  for (let i = 0; i < 512; i++) {
    sum += a[this.thread.y][i] * b[i][this.thread.x];
  }
  return sum;
}).setOutput([512, 512]);

const c = multiplyMatrix(a, b) as number[][];

Click here for more typescript examples.

Table of Contents

Notice documentation is off? We do try our hardest, but if you find something, please bring it to our attention, or become a contributor!

Demos

GPU.js in the wild, all around the net. Add yours here!

Installation

On Linux, ensure you have the correct header files installed: sudo apt install mesa-common-dev libxi-dev (adjust for your distribution)

npm

npm install gpu.js --save

yarn

yarn add gpu.js

npm package

Node

const { GPU } = require('gpu.js');
const gpu = new GPU();

Node Typescript New in V2!

import { GPU } from 'gpu.js';
const gpu = new GPU();

Browser

Download the latest version of GPU.js and include the files in your HTML page using the following tags:

<script src="dist/gpu-browser.min.js"></script>
<script>
    const gpu = new GPU();
</script>

GPU Settings

Settings are an object used to create an instance of GPU. Example: new GPU(settings)

  • canvas: HTMLCanvasElement. Optional. For sharing canvas. Example: use THREE.js and GPU.js on same canvas.
  • context: WebGL2RenderingContext or WebGLRenderingContext. For sharing rendering context. Example: use THREE.js and GPU.js on same rendering context.
  • mode: Defaults to 'gpu', other values generally for debugging:
    • 'dev' New in V2!: VERY IMPORTANT! Use this so you can breakpoint and debug your kernel! This wraps your javascript in loops but DOES NOT transpile your code, so debugging is much easier.
    • 'webgl': Use the WebGLKernel for transpiling a kernel
    • 'webgl2': Use the WebGL2Kernel for transpiling a kernel
    • 'headlessgl' New in V2!: Use the HeadlessGLKernel for transpiling a kernel
    • 'cpu': Use the CPUKernel for transpiling a kernel
  • onIstanbulCoverageVariable: Removed in v2.11.0, use v8 coverage
  • removeIstanbulCoverage: Removed in v2.11.0, use v8 coverage

gpu.createKernel Settings

Settings are an object used to create a kernel or kernelMap. Example: gpu.createKernel(settings)

  • output or kernel.setOutput(output): array or object that describes the output of kernel. When using kernel.setOutput() you can call it after the kernel has compiled if kernel.dynamicOutput is true, to resize your output. Example:
    • as array: [width], [width, height], or [width, height, depth]
    • as object: { x: width, y: height, z: depth }
  • pipeline or kernel.setPipeline(true) New in V2!: boolean, default = false
    • Causes kernel() calls to output a Texture. To get array's from a Texture, use:
    const result = kernel();
    result.toArray();
    • Can be passed directly into kernels, and is preferred:
    kernel(texture);
  • graphical or kernel.setGraphical(boolean): boolean, default = false
  • loopMaxIterations or kernel.setLoopMaxIterations(number): number, default = 1000
  • constants or kernel.setConstants(object): object, default = null
  • dynamicOutput or kernel.setDynamicOutput(boolean): boolean, default = false - turns dynamic output on or off
  • dynamicArguments or kernel.setDynamicArguments(boolean): boolean, default = false - turns dynamic arguments (use different size arrays and textures) on or off
  • optimizeFloatMemory or kernel.setOptimizeFloatMemory(boolean) New in V2!: boolean - causes a float32 texture to use all 4 channels rather than 1, using less memory, but consuming more GPU.
  • precision or kernel.setPrecision('unsigned' | 'single') New in V2!: 'single' or 'unsigned' - if 'single' output texture uses float32 for each colour channel rather than 8
  • fixIntegerDivisionAccuracy or kernel.setFixIntegerDivisionAccuracy(boolean) : boolean - some cards have accuracy issues dividing by factors of three and some other primes (most apple kit?). Default on for affected cards, disable if accuracy not required.
  • functions or kernel.setFunctions(array): array, array of functions to be used inside kernel. If undefined, inherits from GPU instance. Can also be an array of { source: function, argumentTypes: object, returnType: string }.
  • nativeFunctions or kernel.setNativeFunctions(array): object, defined as: { name: string, source: string, settings: object }. This is generally set via using GPU.addNativeFunction()
    • VERY IMPORTANT! - Use this to add special native functions to your environment when you need specific functionality is needed.
  • injectedNative or kernel.setInjectedNative(string) New in V2!: string, defined as: { functionName: functionSource }. This is for injecting native code before translated kernel functions.
  • subKernels or kernel.setSubKernels(array): array, generally inherited from GPU instance.
  • immutable or kernel.setImmutable(boolean): boolean, default = false
    • VERY IMPORTANT! - This was removed in v2.4.0 - v2.7.0, and brought back in v2.8.0 by popular demand, please upgrade to get the feature
  • strictIntegers or kernel.setStrictIntegers(boolean): boolean, default = false - allows undefined argumentTypes and function return values to use strict integer declarations.
  • useLegacyEncoder or kernel.setUseLegacyEncoder(boolean): boolean, default false - more info here.
  • tactic or kernel.setTactic('speed' | 'balanced' | 'precision') New in V2!: Set the kernel's tactic for compilation. Allows for compilation to better fit how GPU.js is being used (internally uses lowp for 'speed', mediump for 'balanced', and highp for 'precision'). Default is lowest resolution supported for output.

Creating and Running Functions

Depending on your output type, specify the intended size of your output. You cannot have an accelerated function that does not specify any output size.

Output size How to specify output size How to reference in kernel
1D [length] value[this.thread.x]
2D [width, height] value[this.thread.y][this.thread.x]
3D [width, height, depth] value[this.thread.z][this.thread.y][this.thread.x]
const settings = {
    output: [100]
};

or

// You can also use x, y, and z
const settings = {
    output: { x: 100 }
};

Create the function you want to run on the GPU. The first input parameter to createKernel is a kernel function which will compute a single number in the output. The thread identifiers, this.thread.x, this.thread.y or this.thread.z will allow you to specify the appropriate behavior of the kernel function at specific positions of the output.

const kernel = gpu.createKernel(function() {
    return this.thread.x;
}, settings);

The created function is a regular JavaScript function, and you can use it like one.

kernel();
// Result: Float32Array[0, 1, 2, 3, ... 99]

Note: Instead of creating an object, you can use the chainable shortcut methods as a neater way of specifying settings.

const kernel = gpu.createKernel(function() {
    return this.thread.x;
}).setOutput([100]);

kernel();
// Result: Float32Array[0, 1, 2, 3, ... 99]

Declaring variables/functions within kernels

GPU.js makes variable declaration inside kernel functions easy. Variable types supported are:

  • Number (Integer or Number), example: let value = 1 or let value = 1.1
  • Boolean, example: let value = true
  • Array(2), example: let value = [1, 1]
  • Array(3), example: let value = [1, 1, 1]
  • Array(4), example: let value = [1, 1, 1, 1]
  • private Function, example: function myFunction(value) { return value + 1; }

Number kernel example:

const kernel = gpu.createKernel(function() {
 const i = 1;
 const j = 0.89;
 return i + j;
}).setOutput([100]);

Boolean kernel example:

const kernel = gpu.createKernel(function() {
  const i = true;
  if (i) return 1;
  return 0;
}).setOutput([100]);

Array(2) kernel examples: Using declaration

const kernel = gpu.createKernel(function() {
 const array2 = [0.08, 2];
 return array2;
}).setOutput([100]);

Directly returned

const kernel = gpu.createKernel(function() {
 return [0.08, 2];
}).setOutput([100]);

Array(3) kernel example: Using declaration

const kernel = gpu.createKernel(function() {
 const array2 = [0.08, 2, 0.1];
 return array2;
}).setOutput([100]);

Directly returned

const kernel = gpu.createKernel(function() {
 return [0.08, 2, 0.1];
}).setOutput([100]);

Array(4) kernel example: Using declaration

const kernel = gpu.createKernel(function() {
 const array2 = [0.08, 2, 0.1, 3];
 return array2;
}).setOutput([100]);

Directly returned

const kernel = gpu.createKernel(function() {
 return [0.08, 2, 0.1, 3];
}).setOutput([100]);

private Function kernel example:

const kernel = gpu.createKernel(function() {
  function myPrivateFunction() {
    return [0.08, 2, 0.1, 3];
  }
  
  return myPrivateFunction(); // <-- type inherited here
}).setOutput([100]);

Debugging

Debugging can be done in a variety of ways, and there are different levels of debugging.

  • Debugging kernels with breakpoints can be done with new GPU({ mode: 'dev' })
    • This puts GPU.js into development mode. Here you can insert breakpoints, and be somewhat liberal in how your kernel is developed.
    • This mode does not actually "compile" (parse, and eval) a kernel, it simply iterates on your code.
    • You can break a lot of rules here, because your kernel's function still has context of the state it came from.
    • PLEASE NOTE: Mapped kernels are not supported in this mode. They simply cannot work because of context.
    • Example:
      const gpu = new GPU({ mode: 'dev' });
      const kernel = gpu.createKernel(function(arg1, time) {
          // put a breakpoint on the next line, and watch it get hit
          const v = arg1[this.thread.y][this.thread.x * time];
          return v;
      }, { output: [100, 100] });
  • Debugging actual kernels on CPU with debugger:
    • This will cause "breakpoint" like behaviour, but in an actual CPU kernel. You'll peer into the compiled kernel here, for a CPU.
    • Example:
      const gpu = ne 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ReactiveX/rxjs: A reactive programming library for JavaScript发布时间:2022-07-07
下一篇:
learn-co-students/javascript-objects-bootcamp-prep-000发布时间:2022-07-07
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap