Matrix multiplication. RGBA16F textures + transposed B


"WebGL2" HALF_FLOAT matrix multiplication C = A x B (HGEMM) demo.
All A, B elements are random (0 - 1). Error "er1" is calculated as the sum of |CCPU - CGPU |/(M*N) for all matrix elements. er2 = max(|CCPU - CGPU |). M is arbitrary, K and N are multiple of 4 (else we need paddings). You can change them in the source. See also benchmark.

Fragment shader

4x4 sub-matrix multiplication algorithm is used. Inspired by Cedric Nugteren (and Nvidia I think). See also the page source for details. Matrices are stored in row-major order (rows in the x-direction for textures). Matrix B is supposed transposed (it is not very important for random matrices).
#version 300 es
precision mediump float;
  uniform mediump sampler2D samp0;
  uniform mediump sampler2D samp1;
  out vec4 fragColor;
  uniform int K4;   // K/4
void main(void) {
  vec4 acc = vec4(0.);
  int id = 4*int(gl_FragCoord.x);
  for(int k=0; k< K4; k++){
    vec4 a = texelFetch(samp0, ivec2(k, gl_FragCoord.y), 0);
    acc.x += dot(a, texelFetch(samp1, ivec2(k, id    ), 0));
    acc.y += dot(a, texelFetch(samp1, ivec2(k, id + 1), 0));
    acc.z += dot(a, texelFetch(samp1, ivec2(k, id + 2), 0));
    acc.w += dot(a, texelFetch(samp1, ivec2(k, id + 3), 0));
  fragColor = acc;
Thanks to Jeff Gilbert (from Mozilla), only one more operator needs to be changed for HALF_FLOAT textures.
   gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA16F, I,J)

WebGL2-compute vs. WebGL?     updated 27 Apr 2019