Experience

Code Location

You may test by yourself.
@yhyddr/images-by-gpu
@yhyddr/images

Performance

Kapture 2020-02-11 at 18.10.15.mp4 (5.58MB) It is foreseeable that the larger the image, the higher the GPU advantage.

Key Code

First get GPU

  1. adapter = navigator.gpu.requestAdapter()
  2. device = adapter.requestDevice()

image.png

Compute shader code

A syntax based on the C programming language. The following code is used in GPU to compute matrix.

  1. const computeShaderCode = `#version 450
  2. layout(std430, set = 0, binding = 0) readonly buffer FirstMatrix {
  3. vec2 size;
  4. float numbers[];
  5. } firstMatrix;
  6. layout(std430, set = 0, binding = 1) readonly buffer SecondMatrix {
  7. vec2 size;
  8. float numbers[];
  9. } secondMatrix;
  10. layout(std430, set = 0, binding = 2) buffer ResultMatrix {
  11. vec2 size;
  12. float numbers[];
  13. } resultMatrix;
  14. void main() {
  15. resultMatrix.size = vec2(firstMatrix.size.x, secondMatrix.size.y);
  16. ivec2 resultCell = ivec2(gl_GlobalInvocationID.x, gl_GlobalInvocationID.y);
  17. float result = 0.0;
  18. for (int i = 0; i < firstMatrix.size.y; i++) {
  19. int a = i + resultCell.x * int(firstMatrix.size.y);
  20. int b = resultCell.y + i * int(secondMatrix.size.y);
  21. result += firstMatrix.numbers[a] * secondMatrix.numbers[b];
  22. }
  23. int index = resultCell.y + resultCell.x * int(secondMatrix.size.y);
  24. resultMatrix.numbers[index] = result;
  25. }
  26. `;

Compiler

This is a GLSL-to-SPIR-V compiler for the Web and Node.js. It is a WebAssembly build of glslang.

  1. const glslangModule = await import('https://unpkg.com/@webgpu/glslang@0.0.13/dist/web-devel/glslang.js')
  2. const glslang = await glslangModule.default();

detail code link

Benchmark

Without GPU

image.png

With GPU

image.png

Test from get-started-with-gpu-compute-on-the-web

gpu-cpu-benchmark.jpg

Reference