# NEOWISE Q8 — portable INT8 (Q8_0) matmul variants for ggml's CUDA backend.
#
# App-agnostic: this directory knows nothing about the application consuming it.
# It injects its .cu files into whatever `ggml-cuda` target the parent project
# has already declared, so our kernels compile with exactly the same flags,
# include paths, and link dependencies as the rest of ggml-cuda.
#
# The ggml-cuda.cu dispatch hook itself is a small patch (patches/*.patch);
# in an integrated fork it is normally committed rather than applied at build time.
#
# Usage from a parent CMakeLists, AFTER the ggml subdirectory and the consuming
# targets are declared:
#
#     add_subdirectory(third_party/ggml)              # declares ggml-cuda
#     add_subdirectory(src)                           # declares the app targets
#     set(NEOWISE_Q8_CONSUMER_TARGETS pi05_core pi05)
#     add_subdirectory(third_party/neowise-q8)
#
# Knobs:
#     -DCUSTOM_KERNEL_VERSION=<1..6>         which variant the dispatch hook calls
#     -DCUTLASS_DIR=<path>                   defaults to the bundled submodule
#     -DCMAKE_CUDA_ARCHITECTURES=110a-real   REQUIRED for v=6 on Thor (TMA)
#     -DNEOWISE_Q8_AUTO_FALLBACK=ON|OFF      downgrade instead of failing (default ON)

if (NOT TARGET ggml-cuda)
    message(STATUS "neowise-q8: no ggml-cuda target found, skipping "
                   "(configure the parent project with CUDA enabled).")
    return()
endif()

# ----------------------------------------------------------------------------
# Which kernel variant the dispatch hook routes Q8_0 weights to.
#
#   1 = thai_vu  (per-call Q8_0 -> INT8 conversion)                    exp015
#   2 = amir_v1  (cached weight conversion)                            exp016
#   3 = amir_v2  (cached + coalesced INT32->FP32 dequant)              exp017
#   4 = amir_v3  (amir_v2 + load-time weight conversion)               exp018
#   5 = amir_v4  (CUTLASS 2.x EVT fused epilogue — REGRESSED on
#                 Blackwell, kept for the record)                      exp020
#   6 = amir_v5  (CUTLASS 3.x collective builder, Sm100 + TMA)         exp021  [default]
#
# Numbering is deliberately identical to the stable-diffusion.cpp study, so a
# variant number means the same thing in every project that consumes this.
# ----------------------------------------------------------------------------
set(CUSTOM_KERNEL_VERSION "6" CACHE STRING
    "Q8_0 matmul variant: 1=thai_vu, 2=amir_v1, 3=amir_v2, 4=amir_v3, 5=amir_v4, 6=amir_v5")
set_property(CACHE CUSTOM_KERNEL_VERSION PROPERTY STRINGS "1" "2" "3" "4" "5" "6")

option(NEOWISE_Q8_AUTO_FALLBACK
       "If the build cannot support the requested variant, fall back to variant 4 \
instead of failing the configure step." ON)

# ----------------------------------------------------------------------------
# CUTLASS — required by variants 5 and 6. Defaults to the pinned submodule so a
# recursive clone needs no extra flags.
# ----------------------------------------------------------------------------
set(CUTLASS_DIR "${CMAKE_CURRENT_LIST_DIR}/third_party/cutlass" CACHE PATH
    "Path to a CUTLASS checkout. Defaults to the pinned submodule.")

set(_neowise_have_cutlass FALSE)
if (CUTLASS_DIR AND EXISTS "${CUTLASS_DIR}/include/cutlass/cutlass.h")
    set(_neowise_have_cutlass TRUE)
endif()

if (CUSTOM_KERNEL_VERSION GREATER_EQUAL 5 AND NOT _neowise_have_cutlass)
    if (NEOWISE_Q8_AUTO_FALLBACK)
        message(WARNING
            "neowise-q8: variant ${CUSTOM_KERNEL_VERSION} needs CUTLASS but none was found at\n"
            "  ${CUTLASS_DIR}\n"
            "Falling back to variant 4 (amir_v3, no CUTLASS required).\n"
            "To get the fast path:  git submodule update --init --recursive")
        set(CUSTOM_KERNEL_VERSION 4)
    else()
        message(FATAL_ERROR
            "neowise-q8: variant ${CUSTOM_KERNEL_VERSION} requires CUTLASS, not found at\n"
            "  ${CUTLASS_DIR}\n"
            "Fix:  git submodule update --init --recursive\n"
            "  or: -DCUTLASS_DIR=/path/to/cutlass")
    endif()
endif()

# ----------------------------------------------------------------------------
# Blackwell TMA gate. amir_v5 needs CUTLASS's TMA paths, which are only enabled
# when the 'a' (all-features) architecture variant is compiled. Plain sm_110
# compiles fine and then aborts at RUNTIME with
#   "Trying to use TMA without CUTE_ARCH_TMA_SM90_ENABLED"
# which is impossible to diagnose from the outside -- so fail loudly here.
# ----------------------------------------------------------------------------
# NOTE: match "<digits>a", not bare "a" -- every arch spec we use ends in
# "-real"/"-virtual", which themselves contain an 'a', so a bare MATCHES "a"
# is always true and silently disables this whole check.
if (CUSTOM_KERNEL_VERSION EQUAL 6 AND NOT "${CMAKE_CUDA_ARCHITECTURES}" MATCHES "[0-9]+a")
    if (NEOWISE_Q8_AUTO_FALLBACK)
        message(WARNING
            "neowise-q8: variant 6 (amir_v5) needs an 'a' CUDA architecture, but "
            "CMAKE_CUDA_ARCHITECTURES='${CMAKE_CUDA_ARCHITECTURES}'.\n"
            "Falling back to variant 4 (amir_v3), which runs on any CUDA arch.\n"
            "For the fast path on AGX Thor:  -DCMAKE_CUDA_ARCHITECTURES=110a-real")
        set(CUSTOM_KERNEL_VERSION 4)
    else()
        message(FATAL_ERROR
            "neowise-q8: variant 6 (amir_v5) requires an 'a' CUDA architecture.\n"
            "  got:      CMAKE_CUDA_ARCHITECTURES='${CMAKE_CUDA_ARCHITECTURES}'\n"
            "  expected: 110a-real (AGX Thor) or 100a-real (B100/B200)\n"
            "Without it the kernel compiles but aborts at runtime without TMA.")
    endif()
endif()

# ----------------------------------------------------------------------------
# Sources — all variants are always compiled, so switching is a recompile of the
# dispatch hook only. Unused variants are dead code in the binary.
# ----------------------------------------------------------------------------
set(NEOWISE_Q8_SOURCES
    ${CMAKE_CURRENT_LIST_DIR}/src/int8_helpers.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/thai_vu.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/amir_v1.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/amir_v2.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/amir_v4.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/amir_v5.cu
    ${CMAKE_CURRENT_LIST_DIR}/src/preload.cu
)

target_sources(ggml-cuda PRIVATE ${NEOWISE_Q8_SOURCES})

# Our .cu files include ggml-cuda's own "common.cuh" etc., so they need
# ggml-cuda's source directory on the include path. Derive it from the target so
# this works regardless of where the parent project vendored ggml.
get_target_property(_neowise_ggml_srcs ggml-cuda SOURCES)
list(GET _neowise_ggml_srcs 0 _neowise_first_src)
get_filename_component(_neowise_ggml_dir "${_neowise_first_src}" DIRECTORY)
if (NOT IS_ABSOLUTE "${_neowise_ggml_dir}")
    get_target_property(_neowise_ggml_srcdir ggml-cuda SOURCE_DIR)
    set(_neowise_ggml_dir "${_neowise_ggml_srcdir}/${_neowise_ggml_dir}")
endif()

target_include_directories(ggml-cuda PRIVATE
    ${_neowise_ggml_dir}
    ${CMAKE_CURRENT_LIST_DIR}/src
    ${CMAKE_CURRENT_LIST_DIR}/include
)

target_compile_definitions(ggml-cuda PRIVATE CUSTOM_KERNEL_VERSION=${CUSTOM_KERNEL_VERSION})

if (_neowise_have_cutlass AND CUSTOM_KERNEL_VERSION GREATER_EQUAL 5)
    target_include_directories(ggml-cuda PRIVATE
        ${CUTLASS_DIR}/include
        ${CUTLASS_DIR}/tools/util/include
    )
    target_compile_definitions(ggml-cuda PRIVATE CUSTOM_KERNEL_HAVE_CUTLASS=1)
    message(STATUS "neowise-q8: CUTLASS at ${CUTLASS_DIR}")

    # ------------------------------------------------------------------------
    # Arch tag for the CUTLASS 2.x EVT path (variant 5 / amir_v4).
    #
    # That path's Sm80EVT visitors and its mma.sync.m16n8k32.s8.s8.s32 IMMA
    # instruction are Ampere-native. Tagging it Sm90 asks for Hopper features,
    # which is right on Hopper/Blackwell but wrong on Ampere -- notably AGX Orin
    # (sm_87), where variant 5 is the ONLY CUTLASS path available (the 3.x
    # collective builders that variant 6 needs start at Sm90).
    #
    # So: pick Sm80 when every requested architecture is below 90.
    # ------------------------------------------------------------------------
    set(_neowise_2x_arch "cutlass::arch::Sm90")
    if (CMAKE_CUDA_ARCHITECTURES)
        set(_neowise_max_arch 0)
        foreach (_a IN LISTS CMAKE_CUDA_ARCHITECTURES)
            string(REGEX MATCH "^[0-9]+" _a_num "${_a}")
            if (_a_num AND _a_num GREATER _neowise_max_arch)
                set(_neowise_max_arch ${_a_num})
            endif()
        endforeach()
        if (_neowise_max_arch GREATER 0 AND _neowise_max_arch LESS 90)
            set(_neowise_2x_arch "cutlass::arch::Sm80")
        endif()
    endif()
    target_compile_definitions(ggml-cuda PRIVATE
        NEOWISE_CUTLASS_2X_ARCH=${_neowise_2x_arch})
    message(STATUS "neowise-q8: CUTLASS 2.x arch tag = ${_neowise_2x_arch}")
endif()

# ----------------------------------------------------------------------------
# Propagate to application targets that call custom_kernels::preload_q8_0_weights.
# Optional -- every variant also fills its weight cache lazily on first use.
# ----------------------------------------------------------------------------
foreach (_neowise_consumer IN LISTS NEOWISE_Q8_CONSUMER_TARGETS)
    if (TARGET ${_neowise_consumer})
        target_compile_definitions(${_neowise_consumer} PRIVATE
            CUSTOM_KERNEL_VERSION=${CUSTOM_KERNEL_VERSION})
        target_include_directories(${_neowise_consumer} PRIVATE
            ${CMAKE_CURRENT_LIST_DIR}/include)
    else()
        message(WARNING "neowise-q8: consumer target '${_neowise_consumer}' does not exist.")
    endif()
endforeach()

message(STATUS "neowise-q8: active variant=${CUSTOM_KERNEL_VERSION} "
               "(1=thai_vu, 2=amir_v1, 3=amir_v2, 4=amir_v3, "
               "5=amir_v4[CUTLASS 2.x Sm90], 6=amir_v5[CUTLASS 3.x Sm100])")
if (CUSTOM_KERNEL_VERSION GREATER_EQUAL 1)
    message(STATUS "neowise-q8: NOTE — INT8 quantization changes numerical output. "
                   "See README.md 'Accuracy' before using this for control.")
endif()
