# libxe2 -- radiance's kernel library for Intel Xe2 GPUs (Battlemage; the Arc Pro B65), in SYCL.
# docs/SYCL_PORTING.md has the design, docs/SYCL_PROGRESS.md the state.
#
# Links radiance::abi and the SYCL runtime, nothing of radiance's. Built by icpx: in radiance's tree
# through the sycl/ sub-build, or standalone against an installed radiance:
#   cmake -S libxe2 -B build -DCMAKE_CXX_COMPILER=icpx -DCMAKE_PREFIX_PATH=<radiance prefix>
if(NOT COMMAND rad_add_plugin)
  cmake_minimum_required(VERSION 3.21)
  project(libxe2 LANGUAGES CXX)
  find_package(radiance REQUIRED)
  rad_plugin_defaults()
endif()

if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "IntelLLVM")
  message(FATAL_ERROR "libxe2 is SYCL and needs icpx (-DCMAKE_CXX_COMPILER=icpx); this configure "
                      "has ${CMAKE_CXX_COMPILER_ID}.")
endif()
if(NOT RAD_SYCL_TARGETS)
  set(RAD_SYCL_TARGETS "intel_gpu_bmg_g31")
endif()

file(GLOB XE2_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
# The sources whose kernels need the large register file, built apart (xe2_grf256, below).
set(XE2_GRF256_SRC ${CMAKE_CURRENT_SOURCE_DIR}/xe2_attn_flash_esimd.cpp)
list(REMOVE_ITEM XE2_SRC ${XE2_GRF256_SRC})
rad_add_plugin(libxe2 kernels SOURCES ${XE2_SRC})

# -ffp-contract=off is a correctness flag here as in libref: kernels are checked against it, so
# `a*b + c` rounds twice on both sides. It follows -ffp-model=precise, which would otherwise set
# contraction back on. -foffload-fp32-prec-div and -sqrt make device division and sqrt correctly
# rounded, as libref's are: a quantiser's scale is amax * (1/top), and a 1/top one ulp off moves
# codes that sit exactly on an E4M3 rounding tie, which bf16 inputs hit often.
# Device code is generated at link time (AOT), so every flag that shapes it goes to the link too;
# on the compile line alone it changes nothing on the card.
# SPV_INTEL_subgroup_matrix_multiply_accumulate: DPAS on operands in registers (xe2_common.h's
# dpas_f16), for kernels that decode a weight straight into the B operand.
# -options -ffp-contract=off: the ESIMD kernels' vector compiler forms mads from a multiply and an
# add unless its own option says strict, whatever the front end's -ffp-contract (probe fmac.cpp:
# t = (s * a) * b; c += t came back fused in 14062 of 65536 lanes, 0 with the option; SIMT kernels
# are unaffected either way). Without it an ESIMD epilogue that copies libref's chain is not exact.
set(_xe2_sycl -fsycl "-fsycl-targets=${RAD_SYCL_TARGETS}" -ffp-model=precise -ffp-contract=off
              -Wno-overriding-option -foffload-fp32-prec-div -foffload-fp32-prec-sqrt
              "SHELL:-Xspirv-translator -spirv-ext=+SPV_INTEL_subgroup_matrix_multiply_accumulate"
              "SHELL:-Xspirv-translator -spirv-ext=+SPV_INTEL_subgroup_matrix_multiply_accumulate")
set(_xe2_be "SHELL:-Xsycl-target-backend \"-options -ffp-contract=off\"")
target_compile_options(libxe2 PRIVATE ${_xe2_sycl} ${_xe2_be} -fvisibility=hidden)
get_filename_component(_xe2_icpx_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
get_filename_component(_xe2_oneapi_lib "${_xe2_icpx_bin}/../lib" ABSOLUTE)
target_link_options(libxe2 PRIVATE ${_xe2_sycl} ${_xe2_be} "LINKER:-rpath,${_xe2_oneapi_lib}"
                    "LINKER:--no-undefined")

# xe2_grf256: the kernels that need 256 registers a thread. A kernel's grf_size<256> property never
# reaches the card in this build: sycl-post-link records it on the device image (sycl-grf-size), but
# only the runtime's JIT reads that and adds the large-register option, and libxe2 compiles AOT at
# link time with one option string for every image (neither per-kernel device code split nor
# --offload-new-driver changes that, 2026.2). Every kernel got 128 registers and the 256-register
# ones spilled: prefill attention 4 KiB a thread, 66% of its stall samples on the scoreboard. So
# they are their own device link, with the large file forced, in a library libxe2 loads from
# kernels/libxe2.d (beside the plugins, not among them: the loader would take it for one). The
# auto-large-GRF mode over all of libxe2 instead also moved ~25 SIMT kernels that never spilled to
# 256 and half their threads (gdn_conv_prep 434 -> 687 us a call). Probe fa.cpp (24/4 heads,
# head_dim 256): 2048 tokens 7.3 -> 13.5 TFLOPS, 8192 tokens 8.3 -> 17.8, output identical.
# Its refusals go through libxe2's refuse(), exported for it and found in libxe2 at load time.
add_library(xe2_grf256 SHARED ${XE2_GRF256_SRC})
target_link_libraries(xe2_grf256 PRIVATE radiance::abi)
set(_xe2_be256 "SHELL:-Xsycl-target-backend \"-options '-ffp-contract=off -ze-opt-large-register-file'\"")
target_compile_options(xe2_grf256 PRIVATE ${_xe2_sycl} ${_xe2_be256})
target_link_options(xe2_grf256 PRIVATE ${_xe2_sycl} ${_xe2_be256} "LINKER:-rpath,${_xe2_oneapi_lib}")
set_target_properties(xe2_grf256 PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${RAD_PLUGIN_OUT}/kernels/libxe2.d)
target_link_libraries(libxe2 PRIVATE xe2_grf256)
target_link_options(libxe2 PRIVATE "LINKER:-rpath,$ORIGIN/libxe2.d")
# Installed beside libxe2 wherever it goes: by this file standalone, by the main project from the
# sycl/ sub-build (which installs nothing itself).
if(NOT DEFINED RAD_PLUGIN_INSTALL OR RAD_PLUGIN_INSTALL)
  if(RAD_PLUGIN_INSTALL_HOME)
    install(TARGETS xe2_grf256 LIBRARY DESTINATION "${RAD_PLUGIN_INSTALL_HOME}/kernels/libxe2.d")
  else()
    install(TARGETS xe2_grf256 LIBRARY DESTINATION "${CMAKE_INSTALL_DATADIR}/radiance/kernels/libxe2.d")
  endif()
endif()

# oneMKL's SYCL BLAS for the prefill-sized fp16 GEMMs (xe2_gemm_xmx.cpp, xmx_f16_scaled): ~85-90
# TFLOPS at the 27B's shapes against ~25 for the hand-tiled kernel, deterministic run to run. Part
# of oneAPI, found beside icpx; without it the hand-tiled kernel serves (RAD_XE2_MKL=OFF forces that).
option(RAD_XE2_MKL "libxe2: oneMKL's SYCL GEMM for the prefill fp16 GEMMs" ON)
get_filename_component(_xe2_oneapi_root "${_xe2_icpx_bin}/../../.." ABSOLUTE)
find_library(_xe2_mkl_sycl_blas mkl_sycl_blas
             HINTS "$ENV{MKLROOT}/lib" "${_xe2_oneapi_root}/mkl/latest/lib" NO_DEFAULT_PATH)
find_path(_xe2_mkl_inc oneapi/mkl/blas.hpp
          HINTS "$ENV{MKLROOT}/include" "${_xe2_oneapi_root}/mkl/latest/include" NO_DEFAULT_PATH)
if(RAD_XE2_MKL AND _xe2_mkl_sycl_blas AND _xe2_mkl_inc)
  get_filename_component(_xe2_mkl_lib "${_xe2_mkl_sycl_blas}" DIRECTORY)
  message(STATUS "libxe2: oneMKL SYCL BLAS from ${_xe2_mkl_lib}")
  target_compile_definitions(libxe2 PRIVATE XE2_HAVE_MKL=1 MKL_ILP64)
  target_include_directories(libxe2 SYSTEM PRIVATE "${_xe2_mkl_inc}")
  target_link_libraries(libxe2 PRIVATE "${_xe2_mkl_sycl_blas}" "${_xe2_mkl_lib}/libmkl_intel_ilp64.so"
                        "${_xe2_mkl_lib}/libmkl_sequential.so" "${_xe2_mkl_lib}/libmkl_core.so")
  target_link_options(libxe2 PRIVATE "LINKER:-rpath,${_xe2_mkl_lib}")
else()
  message(STATUS "libxe2: no oneMKL SYCL BLAS; the prefill GEMMs use the hand-tiled XMX kernel")
endif()
