# metal/ - Strata on Apple Silicon (Metal), MAC-PLAN.md.  Its own CMake project like sycl/, macOS only, never part of
# the CUDA / HIP / SYCL builds.
#
# Two parts:
#   * the kernel tree (mac-kern): the runtime face src/mtl_rt.*, the MSL kernels kernels/*.metal (compiled at run time),
#     CPU references src/ref_*.cpp and the parity / bench programs tests/*.cpp;
#   * the engine (mac-design): the shared host sources from ../src, UNCHANGED - include/metal_compat goes first on the
#     include path and gives them the CUDA runtime names on Metal, as include/strata/hip_compat does on HIP - over
#     the Metal device runtime src/gpu/runtime.cpp (metal-cpp) and the kernel library src/engine/*.
#
#   cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release -DMETAL_CPP_DIR=... [-DSTRATA_ORACLE_GGML_DIR=... (tests only)]
#   ninja -C build-metal
cmake_minimum_required(VERSION 3.24)
set(CMAKE_OSX_DEPLOYMENT_TARGET "15.0" CACHE STRING "the oldest macOS the binaries run on")
project(strata_metal LANGUAGES C CXX OBJCXX)
include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/strata_symbols.cmake)   # -DSTRATA_KEEP_SYMBOLS=ON: host debug information, same machine code
include(${CMAKE_CURRENT_SOURCE_DIR}/../cmake/strata_geometry.cmake)   # -DSTRATA_GEOMETRY=<name> (default flash_next, no flag added)

if(NOT APPLE)
  message(FATAL_ERROR "metal/ builds on macOS only")
endif()

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_OBJCXX_STANDARD 20)
if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Release)
endif()
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
set(CMAKE_OBJCXX_FLAGS_RELEASE "-O2")

get_filename_component(STRATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)
set(GGML_COMMON "${STRATA_ROOT}/include/strata/quant/strata-quant-common.h")   # the quant header's text, generated by tools/gen_quant_header.py (third_party/ggml/ggml-common.h forwards to it)

# ---- the kernel tree (mac-kern) ------------------------------------------------------------------------------------
# mtl_rt_core: the runtime face and the GGUF reader, with no quant arithmetic.  The hy4-flash targets (opt-in, below) link ONLY this.
add_library(mtl_rt_core STATIC src/mtl_rt.mm src/gguf_lite.cpp)
target_include_directories(mtl_rt_core PUBLIC src ${STRATA_ROOT}/include)
target_compile_options(mtl_rt_core PRIVATE $<$<COMPILE_LANGUAGE:OBJCXX>:-fobjc-arc>)
target_compile_definitions(mtl_rt_core PRIVATE
  STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}"
  STRATA_METAL_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/kernels")
target_link_libraries(mtl_rt_core PUBLIC "-framework Metal" "-framework Foundation")
# mtl_rt: the core plus main's reference quant table (ref_quant) and the gguf::type_geometry answer built on it; what the Qwen /
# DeepSeek engines, their parity programs and the kernel tree link.
add_library(mtl_rt STATIC src/ref_quant.cpp src/gguf_geometry_ref.cpp)
target_include_directories(mtl_rt PUBLIC ${STRATA_ROOT}/third_party/ggml)
target_compile_definitions(mtl_rt PRIVATE STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}")
target_link_libraries(mtl_rt PUBLIC mtl_rt_core)

# The hy4-flash (GGUF) Metal engine is opt-in: nothing of it is configured, built or linked unless asked for.
option(STRATA_BUILD_HY4_FLASH_METAL "Build the HY4-Flash GGUF Metal engine (opt-in until its gates pass)" OFF)

file(GLOB STRATA_METAL_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cpp)
list(REMOVE_ITEM STRATA_METAL_TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/runtime_hello.cpp
     ${CMAKE_CURRENT_SOURCE_DIR}/tests/hy4_own_quant_test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/tests/hy4_quant_gpu_test.cpp)
enable_testing()
foreach(src ${STRATA_METAL_TESTS})
  get_filename_component(t ${src} NAME_WE)
  add_executable(${t} ${src})
  target_link_libraries(${t} PRIVATE mtl_rt)
  # moe_tile_grid_test is a host test: no device, no model, nothing to load, so it is the one the others cannot be -
  # registered with ctest, and it runs on a configured tree whether or not there is a Metal device to run on
  if(t STREQUAL "moe_tile_grid_test")
    add_test(NAME moe_tile_grid COMMAND moe_tile_grid_test)
  endif()
endforeach()

# tqp_parity: the TQP5/6/7 pair trellis against the agention fork's CPU reference, compiled straight out of
# the fork's ggml-quants.c (STRATA_FORK_GGML_SRC = the fork checkout's ggml/src) - no fork ggml build; without
# it, the in-repo ref/tqp/tqp_ref_c.c supplies the same entry points.
set(STRATA_FORK_GGML_SRC "" CACHE PATH "the agention llama.cpp fork's ggml/src (for the TQP reference)")
if(EXISTS "${STRATA_FORK_GGML_SRC}/ggml-quants.c")
  set(TQP_REF "${CMAKE_BINARY_DIR}/tqp_ref.c")
  add_custom_command(OUTPUT ${TQP_REF}
    COMMAND python3 ${CMAKE_CURRENT_SOURCE_DIR}/tools/gen_tqp_ref.py ${STRATA_FORK_GGML_SRC} ${TQP_REF}
    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tools/gen_tqp_ref.py ${STRATA_FORK_GGML_SRC}/ggml-quants.c)
  target_sources(tqp_parity PRIVATE ${TQP_REF})
else()
  # no fork checkout: the in-repo copy of the same decoder (ref/tqp/tqp_ref_c.c, verbatim from the fork)
  set_source_files_properties(${STRATA_ROOT}/../terminal/ref/tqp/tqp_ref_c.c PROPERTIES COMPILE_DEFINITIONS TQP_REF_LIB=1)
  target_sources(tqp_parity PRIVATE ${STRATA_ROOT}/../terminal/ref/tqp/tqp_ref_c.c)
endif()

find_package(Python3 COMPONENTS Interpreter QUIET)
if(Python3_Interpreter_FOUND)
  add_test(NAME prompt_workspace_growth
    COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_prompt_workspace.py"
      --cxx "${CMAKE_OBJCXX_COMPILER}" --runtime "$<TARGET_FILE:mtl_rt>"
      --build-dir "${CMAKE_BINARY_DIR}/prompt-workspace-test")
  set_tests_properties(prompt_workspace_growth PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77)
endif()

if(STRATA_BUILD_HY4_FLASH_METAL)
# ---- the hy4-flash engine ------------------------------------------------------------------------------------------
# Its own target beside the Qwen and DeepSeek engines, on mtl_rt and the hy4-flash host code of ../src that does not use
# CUDA.  Deliberately NOT linked against strata_metal_host: that library pulls in core/device.cu and some forty other
# files through include/metal_compat, none of which this engine calls.  And deliberately NOT placed in src/engine/,
# whose *.cpp are collected with file(GLOB) into both existing engines - a file dropped there would be linked into
# them.  Every source is named, so a new one has to be added here on purpose.
set(STRATA_HY4_FLASH_METAL_HOST_SOURCES
  ${STRATA_ROOT}/src/hy4flash_gguf/geometry.cpp ${STRATA_ROOT}/src/hy4flash_gguf/engram.cpp
  ${STRATA_ROOT}/src/hy4flash_gguf/engram_io.cpp ${STRATA_ROOT}/src/hy4flash_gguf/sampler.cpp
  ${STRATA_ROOT}/src/kernels/ngram.cpp ${STRATA_ROOT}/src/ngram/ple_reader.cpp
  ${STRATA_ROOT}/src/platform/direct_file.cpp ${STRATA_ROOT}/src/platform/memory.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/engine/stream.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/dispatch.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/model.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/experts.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/engram.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/forward.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/dump.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/mtp.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/prefill_snap.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/serve.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/vision.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/vis_tower.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/vis_pos.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/vis_bundle.cpp)
list(APPEND STRATA_HY4_FLASH_METAL_HOST_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/own_quant.cpp)
add_library(strata_hy4_flash_metal_host STATIC ${STRATA_HY4_FLASH_METAL_HOST_SOURCES})
target_include_directories(strata_hy4_flash_metal_host PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf
                           ${CMAKE_CURRENT_SOURCE_DIR}/src/engine)
# The MSL the engine compiles at run time: msl/hy4_flash_kernels.h reads STRATA_METAL_HY4_FLASH_KERNELS, else this.
target_compile_definitions(strata_hy4_flash_metal_host PUBLIC
  STRATA_METAL_HY4_FLASH_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/msl")
target_include_directories(strata_hy4_flash_metal_host PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/msl)
target_compile_options(strata_hy4_flash_metal_host PRIVATE -Wno-unused-parameter -Wno-deprecated-declarations)
target_link_libraries(strata_hy4_flash_metal_host PUBLIC mtl_rt_core)   # not mtl_rt: no ref_quant (nor ggml-common) behind this engine

# The standalone engine answers gguf::type_geometry from own_quant (FORMAT-SPEC); inside the strata binary mtl_rt answers it.
add_executable(strata_hy4_flash_metal ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/main.cpp
               ${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/gguf_geometry_own.cpp)
target_link_libraries(strata_hy4_flash_metal PRIVATE strata_hy4_flash_metal_host)

# hy4_own_quant_test: own_quant.* against the golden vectors of FORMAT-SPEC.md; a plain host program (no device, no model).
add_executable(hy4_own_quant_test tests/hy4_own_quant_test.cpp src/hy4flash_gguf/own_quant.cpp)
target_include_directories(hy4_own_quant_test PRIVATE src/hy4flash_gguf)
target_compile_definitions(hy4_own_quant_test PRIVATE HY4_VECTOR_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/hy4_format_vectors")
enable_testing()
add_test(NAME hy4_own_quant COMMAND hy4_own_quant_test)

# hy4_quant_gpu_test: every format of the hy4-flash library (msl/hy4_flash_quant.metal, _units, _gemv) through the dense GEMV
# on the golden vectors, against a float64 dot product.  Needs a Metal device; no model.
add_executable(hy4_quant_gpu_test tests/hy4_quant_gpu_test.cpp src/hy4flash_gguf/own_quant.cpp
               src/hy4flash_gguf/gguf_geometry_own.cpp)
target_include_directories(hy4_quant_gpu_test PRIVATE src/hy4flash_gguf src/hy4flash_gguf/msl)
target_compile_definitions(hy4_quant_gpu_test PRIVATE
  HY4_VECTOR_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/hy4_format_vectors"
  STRATA_METAL_HY4_FLASH_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/src/hy4flash_gguf/msl")
target_link_libraries(hy4_quant_gpu_test PRIVATE mtl_rt_core)
endif()

# ---- the device runtime and the engine (mac-design) ---------------------------------------------------------------
set(METAL_CPP_DIR "" CACHE PATH "metal-cpp headers (https://developer.apple.com/metal/cpp/), e.g. metal-cpp_26")
if(NOT EXISTS "${METAL_CPP_DIR}/Metal/Metal.hpp")
  message(STATUS "strata metal: METAL_CPP_DIR is not set: the device runtime and the engine are not built")
  return()
endif()

add_library(strata_gpu_metal STATIC src/gpu/runtime.cpp)
target_include_directories(strata_gpu_metal BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/metal_compat
                           ${CMAKE_CURRENT_SOURCE_DIR}/include ${STRATA_ROOT}/include)
target_include_directories(strata_gpu_metal SYSTEM PUBLIC ${METAL_CPP_DIR})
target_compile_definitions(strata_gpu_metal PUBLIC STRATA_GPU_METAL=1)
target_link_libraries(strata_gpu_metal PUBLIC "-framework Metal" "-framework Foundation" "-framework QuartzCore")

add_library(strata_core_metal STATIC ${STRATA_ROOT}/src/core/graph.cpp)
target_link_libraries(strata_core_metal PUBLIC strata_gpu_metal)
add_executable(runtime_hello tests/runtime_hello.cpp)
target_link_libraries(runtime_hello PRIVATE strata_core_metal)
enable_testing()
add_test(NAME runtime_hello COMMAND runtime_hello)

# The engine: ggml (the native expert formats' type traits and ggml-cpu) from the tree vendored in third_party/strata-ggml (frozen at the
# commit the PC build pins, 3cf03257).  -DSTRATA_ORACLE_GGML_DIR=<llama.cpp checkout> builds the TEST oracle from that checkout instead (a test oracle only: it needs STRATA_BUILD_TESTS=ON).
option(STRATA_METAL_ENGINE "Build the engine (strata) for Metal" ON)
if(NOT STRATA_METAL_ENGINE)
  return()
endif()
include(${STRATA_ROOT}/cmake/strata_ggml.cmake)        # -DSTRATA_ORACLE_GGML_DIR (tests only), or the vendored third_party/strata-ggml
include(${STRATA_ROOT}/cmake/backends/metal.cmake)
# OWN-2N: the CPU expert rows and the --mtp-q4 requantizer on the Strata quant layer (src/quant, its Arm NEON tier, no ggml-cpu
# call from the pool) instead of ggml-cpu's type traits.  ON by default since 0.2.16 (bit-exact against ggml-cpu's NEON dots under Apple Clang,
# tests/quant/run_oracle.sh, OWN-2N); -DSTRATA_OWN_CPU_QUANT=OFF builds the ggml-cpu pool (kept selectable for two releases).
option(STRATA_OWN_CPU_QUANT "CPU expert pool and --mtp-q4 on the Strata quant layer instead of ggml-cpu's type traits" ON)
option(STRATA_BUILD_TESTS "Build the quant layer's self-test and ggml oracle test (needs STRATA_OWN_CPU_QUANT)" OFF)
# ggml-base / ggml-cpu only where something links them: the ggml-cpu pool and the tests (ggml as the oracle).  The default engine has no ggml.
if(NOT STRATA_OWN_CPU_QUANT OR STRATA_BUILD_TESTS)
  strata_ggml_resolve("${STRATA_ROOT}")
  if(NOT EXISTS "${_strata_ggml_root}/ggml/CMakeLists.txt")
    message(FATAL_ERROR "ggml sources not found in '${_strata_ggml_root}' (third_party/strata-ggml, or the -DSTRATA_ORACLE_GGML_DIR checkout)")
  endif()
  strata_metal_ggml()
else()
  set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)   # (what strata_metal_ggml sets for the whole project)
  message(STATUS "Strata Metal: no ggml in this build (own CPU pool, tests off)")
endif()
if(STRATA_OWN_CPU_QUANT)
  set(STRATA_QUANT_ROOT ${STRATA_ROOT})
  set(STRATA_CPU_X86 OFF)
  include(${STRATA_ROOT}/cmake/backends/quant.cmake)
  strata_quant_layer()
endif()

set(S ${STRATA_ROOT}/src)
set(STRATA_METAL_HOST_SOURCES
  ${S}/core/device.cu ${S}/core/pinned.cu ${S}/platform/memory.cpp ${S}/core/graph.cpp ${S}/core/weights.cpp ${S}/core/layout.cpp
  ${S}/core/layer.cpp ${S}/core/session.cpp ${S}/core/expert_source.cpp ${S}/core/remote_experts.cpp ${S}/core/expert_cache.cpp
  ${S}/core/native_head.cpp ${S}/core/native_dense.cpp ${S}/core/verify.cpp ${S}/core/mtp.cpp
  ${S}/core/conversation_snapshot.cpp ${S}/core/conversation_state.cpp ${S}/core/conversation_memory.cpp
  ${S}/core/peer_experts.cpp ${S}/core/arch_defaults.cpp ${S}/core/vmm.cpp ${S}/core/conversation_file.cpp
  ${S}/kernels/ngram.cpp ${S}/ngram/ple_reader.cpp ${S}/platform/direct_file.cpp ${S}/platform/io_priority.cpp
  ${S}/prefill/prefill.cpp
  ${S}/spec/suffix_drafter.cpp ${S}/spec/controller.cpp ${S}/spec/draft_policy.cpp ${S}/spec/draft_source.cpp
  ${S}/kernels/cpu/pool.cpp ${S}/kernels/cpu/expert_layout.cpp ${S}/kernels/cpu/native_expert.cpp
  ${S}/kernels/cpu/hadamard.cpp ${S}/kernels/cpu/tq_cpu.cpp)   # Gyro: the Hadamard rotation, the scalar trellis rows
set_source_files_properties(${S}/core/device.cu ${S}/core/pinned.cu
                            PROPERTIES LANGUAGE CXX)

# The kernel library: Metal implementations (src/engine/*.cpp) and, for every entry point not ported yet, a stub
# that stops the engine with the entry point's name (src/engine/stubs.cpp, generated by tools/gen_stubs.py).
file(GLOB STRATA_METAL_ENGINE_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/engine/*.cpp)

add_library(strata_metal_host STATIC ${STRATA_METAL_HOST_SOURCES})
target_include_directories(strata_metal_host PUBLIC ${STRATA_ROOT}/include ${S}/core ${STRATA_ROOT}/third_party/ggml)
target_compile_definitions(strata_metal_host PUBLIC STRATA_NATIVE_EXPERTS=1 STRATA_HAVE_DFLASH2=1 STRATA_VERSION="0.1.73-metal")
target_compile_options(strata_metal_host PRIVATE -Wno-unused-parameter -Wno-deprecated-declarations)
target_link_libraries(strata_metal_host PUBLIC strata_gpu_metal)
if(TARGET ggml-base)   # the ggml-cpu pool (STRATA_OWN_CPU_QUANT=OFF) or a test build: ggml's headers and libraries, as before
  target_include_directories(strata_metal_host PUBLIC ${_strata_ggml_root}/ggml/include ${_strata_ggml_root}/ggml/src ${_strata_ggml_root}/ggml/src/ggml-cpu)
  target_link_libraries(strata_metal_host PUBLIC ggml-cpu ggml-base)
endif()
if(STRATA_OWN_CPU_QUANT)
  target_link_libraries(strata_metal_host PUBLIC strata_quant)
  target_compile_definitions(strata_metal_host PUBLIC STRATA_OWN_CPU_QUANT=1)
endif()

add_library(strata_metal_kernels STATIC ${STRATA_METAL_ENGINE_SOURCES})
target_include_directories(strata_metal_kernels PRIVATE src ${STRATA_ROOT}/third_party/ggml)
target_compile_definitions(strata_metal_kernels PRIVATE
  STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}" STRATA_METAL_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/kernels"
  STRATA_METAL_ENGINE_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/src/engine/msl"
  STRATA_METAL_DATA_DEFAULT="${STRATA_ROOT}/../terminal/data")
target_link_libraries(strata_metal_kernels PUBLIC strata_metal_host mtl_rt)

add_executable(strata ${S}/program/generate.cpp)
target_link_libraries(strata PRIVATE strata_metal_kernels strata_metal_host strata_metal_kernels)
# The hy4-flash family switch in generate.cpp is build-guarded; defining this takes it off the refusal path and onto
# src/hy4flash_gguf/serve.cpp's request loop (opt-in: -DSTRATA_BUILD_HY4_FLASH_METAL=ON).  `strata --families` stays silent about
# hy_v4_flash until STRATA_HY4_FLASH_RUNS is defined as well: setup and the launch catalog read that list.
if(STRATA_BUILD_HY4_FLASH_METAL)
  target_link_libraries(strata PRIVATE strata_hy4_flash_metal_host)
  target_compile_definitions(strata PRIVATE STRATA_HAVE_HY4_FLASH=1)
endif()
# the decode window on its own (probe/window_probe.cpp): the engine's process state without the engine, for looking at a Metal fault
add_executable(window_probe probe/window_probe.cpp)
target_link_libraries(window_probe PRIVATE strata_metal_kernels strata_metal_host strata_metal_kernels)
