// Lab harness: the trellis MMA kernel of ONE source tree behind a C ABI, launched as
// `ag_mma_launch` launches the single-linear arm. `q` is the CTAs a slice has on the band axis:
// the band count is one CTA a band; fewer is the slice-owning schedule.
#include <cuda_runtime.h>
#include "_gemv_mma.cuh"

template <int B, int C, int NT, bool LEAN>
static int go(cudaStream_t st, const void* A, const uint16_t* q, float* partial, void* out,
              const __half* suh, const __half* svh, int K, int N, int kc, int splits, int kst,
              int m, int* ctr, int lanes)
{
    typename Exl3GemvLoader<B, C>::LoaderTensors lt{suh, svh, nullptr};
    const int bands = N / AG_MMA_BAND;
    auto k = ag_mma_kernel<B, C, NT, 1, LEAN>;
#ifdef LAB_BASE
    const size_t smem = (size_t)ag_mma_smem_bytes(NT, 1, kst);
    if (smem + 1024 > 48 * 1024) cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem);
    dim3 grid(bands, splits, 1);
    k<<<grid, AG_MMA_THREADS, smem, st>>>(A, q, splits > 1 ? partial : nullptr, out, lt, K, N, kc,
                                          splits, kst, m, K, AG_IN_F16, AG_OUT_F16,
                                          splits > 1 ? ctr : nullptr, nullptr, 1);
#else
    const size_t smem = (size_t)ag_mma_smem_bytes(NT, 1, kst, lanes);
    if (smem + 1024 > 48 * 1024) cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)smem);
    dim3 grid(bands, splits, 1);
    k<<<grid, AG_MMA_THREADS, smem, st>>>(A, q, splits > 1 ? partial : nullptr, out, lt, K, N, kc,
                                          splits, kst, m, K, AG_IN_F16, AG_OUT_F16,
                                          splits > 1 ? ctr : nullptr, nullptr, 1, lanes);
#endif
    return (int)cudaGetLastError();
}

extern "C" int lab_launch(void* st, int bits, int cb, const void* A, const uint16_t* q,
                          float* partial, void* out, const void* suh, const void* svh, int K,
                          int N, int kc, int splits, int kst, int m, int* ctr, int lanes)
{
    const bool lean = kst * 128 >= kc;
#define ARM(B, C)                                                                              \
    if (bits == B && cb == C)                                                                  \
        return lean ? go<B, C, 1, true>((cudaStream_t)st, A, q, partial, out, (const __half*)suh, \
                                        (const __half*)svh, K, N, kc, splits, kst, m, ctr, lanes)  \
                    : go<B, C, 1, false>((cudaStream_t)st, A, q, partial, out, (const __half*)suh, \
                                         (const __half*)svh, K, N, kc, splits, kst, m, ctr, lanes);
    ARM(4, 2) ARM(4, 1) ARM(6, 1) ARM(6, 2)
    return -1;
}
