1#version 450
 2
 3#include "types.glsl"
 4#include "sum_rows.glsl"
 5
 6#extension GL_EXT_control_flow_attributes : enable
 7#extension GL_KHR_shader_subgroup_arithmetic : enable
 8#extension GL_KHR_shader_subgroup_basic : enable
 9
10layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
11
12layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
13layout (binding = 1) writeonly buffer D {D_TYPE data_d[];};
14layout (binding = 2) writeonly buffer T {D_TYPE data_t[];};
15
16layout (constant_id = 0) const uint BLOCK_SIZE = 128;
17layout (constant_id = 1) const uint SUBGROUP_SIZE = 32;
18
19#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
20
21shared FLOAT_TYPE partial[BLOCK_SIZE / SUBGROUP_SIZE];
22
23void main() {
24    const uint row = gl_WorkGroupID.y;
25    const uint tid = gl_LocalInvocationID.x;
26    const uint col = gl_GlobalInvocationID.x;
27
28    const uint i03 = fastdiv(row, p.ne0_12mp, p.ne0_12L);
29    const uint i03_offset = i03 * p.ne01*p.ne02;
30    const uint i02 = fastdiv(row - i03_offset, p.ne0_1mp, p.ne0_1L);
31    const uint i01 = row - i03_offset - i02*p.ne01;
32
33    const uint src_idx = get_aoffset() + i01 * p.nb01 + i02 * p.nb02 + i03 * p.nb03;
34    const uint dst_idx = get_doffset() + i01 * p.nb11 + i02 * p.nb12 + i03 * p.nb13;
35
36    uint subgroup_id = tid / SUBGROUP_SIZE;
37
38    FLOAT_TYPE v = 0;
39    if (col < p.n_cols) {
40        v = FLOAT_TYPE(data_a[src_idx + col]);
41    }
42    v = subgroupInclusiveAdd(v);
43
44    // Store the largest partial sum for each subgroup, then add the partials for all
45    // lower subgroups and the final partial sum from the previous iteration.
46    if (gl_SubgroupInvocationID == SUBGROUP_SIZE - 1) {
47        partial[subgroup_id] = v;
48    }
49    barrier();
50    for (int j = 0; j < subgroup_id; ++j) {
51        v += partial[j];
52    }
53    barrier();
54    if (tid == BLOCK_SIZE - 1) {
55        data_t[gl_WorkGroupID.x + gl_NumWorkGroups.x * row] = v;
56    }
57    if (col < p.n_cols) {
58        data_d[dst_idx + col] = D_TYPE(v);
59    }
60}