1#version 450
 2
 3#extension GL_EXT_control_flow_attributes : enable
 4
 5#include "generic_head.glsl"
 6#include "types.glsl"
 7
 8layout(constant_id = 0) const uint BLOCK_SIZE = 32;
 9layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
10
11// In this shader Y = softmax(X) and X is not provided as input.
12
13layout (binding = 0) readonly buffer G {A_TYPE data_g[];};
14layout (binding = 1) readonly buffer Y {B_TYPE data_y[];};
15layout (binding = 2) buffer D {D_TYPE data_d[];};
16
17shared FLOAT_TYPE sum_yg[BLOCK_SIZE];
18
19void main() {
20    const uint row = gl_WorkGroupID.z * 262144 + gl_WorkGroupID.y * 512 + gl_WorkGroupID.x;
21    const uint tid = gl_LocalInvocationID.x;
22
23    if (row >= p.KY) {
24        return;
25    }
26
27    FLOAT_TYPE scale = p.param1;
28
29    // partial sums for thread in warp
30    sum_yg[tid] = FLOAT_TYPE(0.0f);
31
32    [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
33        const FLOAT_TYPE gi = FLOAT_TYPE(data_g[row*p.KX + col]);
34        const FLOAT_TYPE yi = FLOAT_TYPE(data_y[row*p.KX + col]);
35        sum_yg[tid] += yi * gi;
36    }
37
38    // sum up partial sums and write back result
39    barrier();
40    [[unroll]] for (uint s = BLOCK_SIZE / 2; s > 0; s >>= 1) {
41        if (tid < s) {
42            sum_yg[tid] += sum_yg[tid + s];
43        }
44        barrier();
45    }
46
47    const FLOAT_TYPE dot_yg = sum_yg[0];
48
49    [[unroll]] for (uint col = tid; col < p.KX; col += BLOCK_SIZE) {
50        data_d[row*p.KX + col] = D_TYPE(scale
51            * (FLOAT_TYPE(data_g[row*p.KX + col]) - dot_yg)
52            * FLOAT_TYPE(data_y[row*p.KX + col]));
53    }
54}