// Copyright © 2023-2025 Advanced Micro Devices, Inc.
// SPDX-License-Identifier: MIT

#include "../shim.bwd_kernel_fuse.h"
#include <aotriton/_internal/triton_kernel.h>
#include <aotriton/_internal/kernel_cluster.h>
#include <aotriton/_internal/log.h>
#include <aotriton/cpp_tune.h>
#include <assert.h>
#include <string_view>

#define CURRENT_ENTRY_PUBLIC Autotune_bwd_kernel_fuse__A0__F6

#define ARRAY_SIZE(array)  (sizeof(array) / sizeof(array[0]))

namespace { // Anonymous namespace

using namespace std::literals::string_view_literals;

#if AOTRITON_BUILD_FOR_TUNING
// PSels and Copts in JSON String
static const char* kernel_psels[] = {
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 64})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 64})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 64})xyzw"
};
static const char* kernel_copts[] = {
  R"xyzw({"waves_per_eu": 1, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 2, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 2, "num_stages": 1})xyzw"
};
#endif

struct PerfFields {
  int16_t BLOCK_M;
    int16_t BLOCK_N;
};

static PerfFields image_perf_list [] = {
    { .BLOCK_M = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 16 },
    { .BLOCK_M = 64, .BLOCK_N = 64 },
    { .BLOCK_M = 64, .BLOCK_N = 64 },
    { .BLOCK_M = 64, .BLOCK_N = 64 }
};

// u8R generates char8_t which is poorly supported almost everywhere.
// TODO: deduplicate FLATZIP_PATH via shim.cc packed_string
constexpr pstring_view FLATZIP_PATH
#if defined(_WIN32)
{ LR"xyzw(amd-gfx950/flash/bwd_kernel_fuse.zip)xyzw" };
#else
{ R"xyzw(amd-gfx950/flash/bwd_kernel_fuse.zip)xyzw" };
#endif
constexpr std::string_view FUNC_NAME   { R"xyzw(Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0)xyzw"   };
constexpr std::string_view ARCH_NAME { R"xyzw(gfx950)xyzw" };

// Checksum can be confirmed with `echo -n '<string>' | b2sum -l 64`
// For example:
//   $ echo -n 'amd-gfx110x/flash/attn_fwd/FONLY__^bf16@16,128,False,False,0,0___gfx1100__P__32_32_0_2_False__CO__wave3_warp2_stg1-Gpu-gfx1100' | b2sum -l 64
//   c4b51ee645d79580  -
static AOTRITON_NS::TritonKernelCompactMeta meta_list[] = {
    { 0x7cc8ce55u, 0x1a1196dcu, 0, 22 }, // 7cc8ce551a1196dc = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=2;num_stages=1;;arch=gfx950
    { 0x01ce1886u, 0xa5595e5cu, 0, 124 }, // 01ce1886a5595e5c = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=2;num_stages=1;;arch=gfx950
    { 0x8fe4d24du, 0x8ee749b4u, 0, 204 }, // 8fe4d24d8ee749b4 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=2;num_stages=1;;arch=gfx950
    { 0xaccc2812u, 0x270c9a10u, 0, 62 }, // accc2812270c9a10 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=2;num_stages=1;;arch=gfx950
    { 0x583719c3u, 0x45646902u, 102, 22 }, // 583719c345646902 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=2;num_stages=1;;arch=gfx950
    { 0x3a8efb0du, 0x1955ef7au, 102, 350 }, // 3a8efb0d1955ef7a = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx950
    { 0x92bf3ad1u, 0x2764da68u, 102, 124 }, // 92bf3ad12764da68 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=2;num_stages=1;;arch=gfx950
    { 0x9eef5fafu, 0x81d5d25bu, 102, 164 }, // 9eef5faf81d5d25b = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx950
    { 0x3ad8fb5bu, 0xcfb993ecu, 102, 204 }, // 3ad8fb5bcfb993ec = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=2;num_stages=1;;arch=gfx950
    { 0x457fdd84u, 0x919b64ceu, 102, 244 }, // 457fdd84919b64ce = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx950
    { 0x7bc1998cu, 0x51e563dfu, 102, 62 }, // 7bc1998c51e563df = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=2;num_stages=1;;arch=gfx950
    { 0xfcb0ed5fu, 0x83f78dc4u, 102, 390 }, // fcb0ed5f83f78dc4 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=4;num_stages=1;;arch=gfx950
    { 0xb1ee5454u, 0xd1a824b1u, 306, 22 }, // b1ee5454d1a824b1 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=64;;#CO;waves_per_eu=1;num_warps=2;num_stages=1;;arch=gfx950
    { 0xf70fa126u, 0xbd4b8251u, 306, 124 }, // f70fa126bd4b8251 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=64;;#CO;waves_per_eu=2;num_warps=2;num_stages=1;;arch=gfx950
    { 0x97a0cf55u, 0x22e7cc89u, 306, 204 }, // 97a0cf5522e7cc89 = b2sum -l 64 <<< amd-gfx950/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=16;CAUSAL_TYPE=0;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=64;;#CO;waves_per_eu=3;num_warps=2;num_stages=1;;arch=gfx950
};

static constexpr int kTotalNumKernels = ARRAY_SIZE(meta_list);

using AOTRITON_NS::v3::flash::autotune::bwd_kernel_fuse_packed_string;

static AOTRITON_NS::TritonKernelCluster<kTotalNumKernels>
kernel_cluster(meta_list,
               bwd_kernel_fuse_packed_string);

static int8_t lut[1][10][10] =
{
// GPU gfx950_mod0
{{ 2,10, 0, 3, 6, 4, 6,10,10,10},
 { 1,10, 0, 1, 4, 4, 6,10,10,10},
 { 2, 5, 0, 4, 4, 4, 6,10,10,10},
 { 5,11, 5,10, 4, 4, 6,10, 4, 4},
 { 9,11, 7, 4, 4, 6, 6,10,10, 6},
 { 7,11, 4, 4, 6, 1, 3, 3,14, 6},
 {11, 9, 6, 6, 6,10, 2,13,13,12},
 {10, 8, 8, 8,10,10,10,13,14,13},
 {10,10, 6,11,10,10,10,10,14,14},
 {10,10,10,10,10, 6, 8,10,14,14}}
// End of GPU gfx950_mod0
}
;

}; // End of anonymous namespace

namespace AOTRITON_NS::v3::flash::autotune {

// using AOTRITON_NS::v2::flash::BwdKernelFuseContext;

// Returns the selected kernel_index, or -1 when no valid kernel was selected.
// The kernel_index is logged by the caller (lookup_optimal in shim.cc) so the
// AOTRITON_LOG machinery is not duplicated across every generated autotune TU.
int CURRENT_ENTRY_PUBLIC(BwdKernelFuseContext& context, int mod_number) {
#if AOTRITON_BUILD_FOR_TUNING
    constexpr int kLutInTuningModeAlwaysReturnZero = 0;
    AOTRITON_LOG(LOG_DEBUG,
                 "Autotune_bwd_kernel_fuse__A0__F6 "
                 "kTotalNumKernels = %d _has_preferred_kernel = %d",
                 kTotalNumKernels, context._has_preferred_kernel);
#ifndef NDEBUG
    assert(bwd_kernel_fuse__lut_lambda__0(*context.params, mod_number, lut) == kLutInTuningModeAlwaysReturnZero);
#endif
    int preferred = context._has_preferred_kernel;
    int kernel_index = preferred < 0 ? kLutInTuningModeAlwaysReturnZero : preferred;
#else
    auto kernel_index = bwd_kernel_fuse__lut_lambda__0(*context.params, mod_number, lut);
#endif
    if (kernel_index < 0 || kernel_index >= kTotalNumKernels) {
        return -1;
    }
    context.kernel_on_device = kernel_cluster.get(kernel_index);
    context.pp_args_index = 2;
    context.flatzip_path = FLATZIP_PATH;
    // aks2_entry IS the func_name (supplied by f.unified_signature)
    context.aks2_entry   = FUNC_NAME;
    context.func_name = FUNC_NAME;
    context.arch_name = ARCH_NAME;
#if AOTRITON_BUILD_FOR_TUNING
    context._total_number_of_kernels = kTotalNumKernels;
    context._preferred_kernel_psels = kernel_psels[kernel_index];
    context._preferred_kernel_copts = kernel_copts[kernel_index];
#endif
    const auto& perf = image_perf_list[kernel_index];
    context.BLOCK_M = perf.BLOCK_M;
    context.BLOCK_N = perf.BLOCK_N;
    return kernel_index;
}

#undef CURRENT_ENTRY_PUBLIC
}

// Human-readable Signature 
// Q = "*fp16:16"
// sm_scale = "fp32"
// L = "*fp32:16"
// stride_bz = 0
// stride_bh = 0
// stride_bm = 0
// stride_dbz = 0
// stride_dbh = 0
// stride_dbm = 0
// num_head_q = "i32"
// cu_seqlens_q = "*i32:16"
// num_seqlens = "i32"
// dropout_p = "fp32"
// philox_seed_ptr = "*u64"
// philox_offset2 = "u64"
// Window_left = 0
// Window_right = 0
// BLOCK_DMODEL = 16
// CAUSAL_TYPE = 0
// ENABLE_DROPOUT = True
// PADDED_HEAD = True
// BIAS_TYPE = 0

// ('SELECT * FROM FLASH$bwd_kernel_fuse WHERE gpu IN (?) AND inputs$Q_dtype = ? AND inputs$BLOCK_DMODEL = ? AND inputs$CAUSAL_TYPE = ? AND inputs$ENABLE_DROPOUT = ? AND inputs$PADDED_HEAD = ? AND inputs$BIAS_TYPE = ?', ['gfx950_mod0', 'torch.float16', 16, 0, True, False, 0])

// vim: set fileencoding=utf-8

