#version 450

#define N_THREADS 256

layout(local_size_x = N_THREADS, local_size_y = 1, local_size_z = 1) in;

layout(constant_id = 0) const uint N_BATCHES = 32;

struct BatchInfo {
    uint inputOffset;
    uint inputSizeX;
    uint outputOffset;
    uint outputSizeX;
};

layout(binding = 0) readonly buffer inputBuffer { float x[]; };
layout(binding = 1) buffer outputBuffer { float y[]; };
layout(binding = 2) readonly uniform batchInfosBuffer { BatchInfo infos[N_BATCHES]; };

void main() {
    const uint threadIndex = gl_LocalInvocationID.x;
    const uint nWorkGroups = gl_NumWorkGroups.x;
    const uint batchIndex = gl_WorkGroupID.y;
    const uint workGroupIndex = gl_WorkGroupID.x;

    const BatchInfo info = infos[batchIndex];
    const uint slice = info.outputSizeX / nWorkGroups;
    const uint rest = info.outputSizeX % nWorkGroups;
    const uint offset = workGroupIndex * slice + min(rest, workGroupIndex);

    const uint dim = slice + (workGroupIndex < rest ? 1 : 0);
    const uint outputSizeX = info.outputSizeX;
    const uint parts = info.inputSizeX / info.outputSizeX;
    const uint xOffset = info.inputOffset + offset;
    const uint yOffset = info.outputOffset + offset;

    for (uint i = threadIndex; i < dim; i += N_THREADS) {
        float sum = 0.0;
        const uint iOffset = xOffset + i;
        const uint oOffset = yOffset + i;
        for (uint n = 0; n < parts; n++) {
            sum += x[n * outputSizeX + iOffset];
        }
        y[oOffset] += sum;
    }
}
