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

#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": 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": 32, "BLOCK_N": 32})xyzw",
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 32})xyzw",
  R"xyzw({"BLOCK_M": 32, "BLOCK_N": 32})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": 32})xyzw",
  R"xyzw({"BLOCK_M": 64, "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": 2, "num_warps": 4, "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": 4, "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": 4, "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": 4, "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": 4, "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": 4, "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": 4, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 2, "num_warps": 8, "num_stages": 1})xyzw",
  R"xyzw({"waves_per_eu": 4, "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 = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 32, .BLOCK_N = 16 },
    { .BLOCK_M = 32, .BLOCK_N = 32 },
    { .BLOCK_M = 32, .BLOCK_N = 32 },
    { .BLOCK_M = 32, .BLOCK_N = 32 },
    { .BLOCK_M = 32, .BLOCK_N = 32 },
    { .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 = 32 },
    { .BLOCK_M = 64, .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='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1)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[] = {
    { 0xf5f9d746u, 0x843193fbu, 328, 350 }, // f5f9d746843193fb = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x36e4c0aeu, 0xff5a5a68u, 328, 164 }, // 36e4c0aeff5a5a68 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=16;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x8989cda2u, 0x15bc821eu, 0, 164 }, // 8989cda215bc821e = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xc43c057cu, 0x0d37f7fbu, 0, 244 }, // c43c057c0d37f7fb = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x7aff6508u, 0xcc4a55cfu, 430, 350 }, // 7aff6508cc4a55cf = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=32;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x44d8ed63u, 0x097a7b15u, 430, 164 }, // 44d8ed63097a7b15 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=32;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x6382cc18u, 0x3b783e69u, 430, 244 }, // 6382cc183b783e69 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=32;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x6f2dd4dau, 0xbf0d9c58u, 430, 390 }, // 6f2dd4dabf0d9c58 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=32;BLOCK_N=32;;#CO;waves_per_eu=4;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xf4b8fa0fu, 0xea59e229u, 102, 350 }, // f4b8fa0fea59e229 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x7a0c8fdau, 0x33ae9eb5u, 102, 164 }, // 7a0c8fda33ae9eb5 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x25d1dbc4u, 0x69718f77u, 102, 244 }, // 25d1dbc469718f77 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=3;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x86759974u, 0x06435930u, 102, 390 }, // 8675997406435930 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=16;;#CO;waves_per_eu=4;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x808f92b0u, 0x741b944fu, 284, 350 }, // 808f92b0741b944f = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=1;num_warps=4;num_stages=1;;arch=gfx1151
    { 0xbfb68445u, 0xecaff09du, 284, 164 }, // bfb68445ecaff09d = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=2;num_warps=4;num_stages=1;;arch=gfx1151
    { 0x7eb3f1ddu, 0xbc8d8e58u, 284, 492 }, // 7eb3f1ddbc8d8e58 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=2;num_warps=8;num_stages=1;;arch=gfx1151
    { 0x1c5668b6u, 0x4f34ae38u, 284, 390 }, // 1c5668b64f34ae38 = b2sum -l 64 <<< amd-gfx115x/flash/bwd_kernel_fuse.zip;;#F;Q='*fp16:16';BLOCK_DMODEL=32;CAUSAL_TYPE=0;ENABLE_DROPOUT=False;PADDED_HEAD=True;BIAS_TYPE=1;;#P;BLOCK_M=64;BLOCK_N=32;;#CO;waves_per_eu=4;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
{{ 0, 6,14,12, 8, 8, 8, 8},
 { 5,11, 1, 2,12, 8, 8, 8},
 { 7,10, 3,10, 8, 8, 8, 8},
 { 9,10, 7, 3, 2,12, 8, 8},
 {10,11, 9,11, 3, 4, 8, 8},
 {11, 9, 5, 9, 5, 8, 8, 8},
 {10,11, 9, 9, 7, 8, 8, 4},
 {11,11,10,11, 8,13,15,12}}
// 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__F19 "
                 "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 = 1;
    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"
// num_head_q = "i32"
// cu_seqlens_q = "*i32:16"
// num_seqlens = "i32"
// dropout_p = 0
// philox_seed_ptr = 0
// philox_offset2 = 0
// Window_left = 0
// Window_right = 0
// BLOCK_DMODEL = 32
// CAUSAL_TYPE = 0
// ENABLE_DROPOUT = False
// PADDED_HEAD = True
// BIAS_TYPE = 1

// ('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.float16', 32, 0, False, False, 1])

// vim: set fileencoding=utf-8

