// 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__A6__F302

#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": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "BLOCK_N": 16})xyzw",
  R"xyzw({"BLOCK_M": 16, "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": 32, "BLOCK_N": 32})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 32})xyzw",
  R"xyzw({"BLOCK_M": 64, "BLOCK_N": 32})xyzw"
};
static const char* kernel_copts[] = {
  R"xyzw({"waves_per_eu": 1, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 1, "num_warps": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 3, "num_warps": 4, "num_stages": 1})xyzw"
};
#endif

struct PerfFields {
  int16_t BLOCK_M;
    int16_t BLOCK_N;
};

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

// 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-gfx115x/flash/bwd_kernel_fuse.zip)xyzw" };
#else
{ R"xyzw(amd-gfx115x/flash/bwd_kernel_fuse.zip)xyzw" };
#endif
constexpr std::string_view FUNC_NAME   { R"xyzw(Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0)xyzw"   };
constexpr std::string_view ARCH_NAME { R"xyzw(gfx1151)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[] = {
    { 0x71727d2eu, 0xd06a43b0u, 328, 350 }, // 71727d2ed06a43b0 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xe5040781u, 0x409d2f9bu, 328, 572 }, // e5040781409d2f9b = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=8;num_stages=1;;arch=gfx1151
    { 0xd75b5205u, 0x99c894a5u, 328, 164 }, // d75b520599c894a5 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xde3a6591u, 0x0c20d7efu, 328, 492 }, // de3a65910c20d7ef = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=8;num_stages=1;;arch=gfx1151
    { 0xb44c9565u, 0xc0445befu, 328, 244 }, // b44c9565c0445bef = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xd42dde3fu, 0x1d05e03au, 328, 452 }, // d42dde3f1d05e03a = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=8;num_stages=1;;arch=gfx1151
    { 0x5732a458u, 0xac6cc1f5u, 328, 390 }, // 5732a458ac6cc1f5 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xccdf7c90u, 0x615c6824u, 328, 532 }, // ccdf7c90615c6824 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=8;num_stages=1;;arch=gfx1151
    { 0xf42c5018u, 0x79a0fa90u, 0, 164 }, // f42c501879a0fa90 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x259eb52du, 0xf40a41c5u, 0, 492 }, // 259eb52df40a41c5 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=8;num_stages=1;;arch=gfx1151
    { 0x916133edu, 0xcb212cb4u, 0, 244 }, // 916133edcb212cb4 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x2deee18fu, 0x4a4323dbu, 430, 350 }, // 2deee18f4a4323db = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=32;BLOCK_N=32;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x3eea2b07u, 0x22edb5feu, 284, 350 }, // 3eea2b0722edb5fe = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x21af1f1fu, 0xd1a77d0cu, 284, 244 }, // 21af1f1fd1a77d0c = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*bf16:16';BLOCK_DMODEL=160;CAUSAL_TYPE=3;ENABLE_DROPOUT=True;PADDED_HEAD=True;BIAS_TYPE=0;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
};

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][8][8] =
{
// GPU gfx1151_mod0
{{ 7, 1, 4, 0, 2, 2, 1, 4},
 { 5, 6, 6, 0, 0, 4, 1, 4},
 { 3, 7, 7, 6, 2, 7, 7, 0},
 { 5, 7, 7, 6, 6, 7, 7, 4},
 {10,10, 5, 6, 6, 5, 6, 6},
 { 9, 8, 7, 8, 8, 6, 6, 6},
 { 8, 8, 8, 8, 8, 8,11, 6},
 { 8, 8, 8, 8, 8,12,13,11}}
// End of GPU gfx1151_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__A6__F302 "
                 "kTotalNumKernels = %d _has_preferred_kernel = %d",
                 kTotalNumKernels, context._has_preferred_kernel);
#ifndef NDEBUG
    assert(bwd_kernel_fuse__lut_lambda__2(*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__2(*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 = 5;
    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 = "*bf16: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 = "i32"
// Window_right = "i32"
// BLOCK_DMODEL = 160
// CAUSAL_TYPE = 3
// 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 = ?', ['gfx1100_mod0', 'torch.bfloat16', 160, 3, True, False, 0])

// vim: set fileencoding=utf-8

