# One executable per *_test.cpp, globbed, so adding a test is adding a file.
#
# The tiers are labels (docs/GUIDE.md §1.3 lists them with their times):
#   unit     a harness binary (rad_test.h) on the host backend
#   perf     a binary's perf_ cases, which assert wall-clock costs; RUN_SERIAL
#   slow     minutes: the kernel replays, the device selftest, the long sweeps
#   gpu      needs a card; RESOURCE_LOCK card
#   oot      rebuilds every bundled plugin out of tree against an install
#   r4d_emu  libr4d's kernel sources run on the host by the SIMT emulator
#   fast     every test with none of slow, gpu, oot and perf, set at the end of this file: the
#            inner loop (`ctest --preset fast`, or `ctest -L fast`)
#
# The tests named in RAD_TESTS_NO_CORE below do not link rad_core: they supply
# their own recording fake of the declare-phase C ABI (arch_fakes.h), so plugins are tested without
# depending on core/build/'s builder. With the archive linked, a new ABI call missing from the fake
# would pull in rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a
# single undefined reference.
set(RAD_TESTS_NO_CORE minimaxh3_limits_test wan_arch_test wan_vae_test wan_denoiser_test wan_conditioning_test arch_test bailing_hybrid_arch_test breeze_arch_test fishomni_arch_test flint_arch_test glm5next_test deepseek41_test museglimmer_test nemotron35_test spark25_arch_test nemotronh_test)

# fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and
# the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and
# kbench_mutant_test runs rad-kbench itself against known-bad kernel libraries. The tool sources are
# not a library (tools/CMakeLists.txt), so the tests compile them in.
set(RAD_TESTS_WITH_TOOLS fixture_test kbench_test kbench_mutant_test)

# tools_test tests tools/iface.cpp, the command-line plumbing the tools share, which is compiled
# into each tool rather than built as a library.
set(RAD_TESTS_WITH_IFACE tools_test)

# The tokenizer tests compare the encoder against the reference encoder, tools/tokref.
set(RAD_TESTS_WITH_TOKREF tokenizer_test tokenizer_perf_test)

# The GBNF oracle (upstream's candidate walk), which the mask engine must match bit for bit. Test
# code, compiled only into these tests and rad-gbnf-check, never into a serving binary.
set(RAD_TESTS_WITH_GBNF_ORACLE sample_test gbnf_test)

# The legacy reply parser as an oracle for core/text/chatparse.h: a whole-reply path built on
# llama.cpp's PEG parser and a hand-written call lifter. Its own archive, linked only into the
# comparing tests and rad-chatparse; core/ cannot reach it.
add_library(rad_legacy_toolparse STATIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy/toolparse_legacy.cpp
                                        ${CMAKE_CURRENT_SOURCE_DIR}/legacy/chatdiff.cpp)
target_link_libraries(rad_legacy_toolparse PUBLIC rad_core)
target_include_directories(rad_legacy_toolparse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy)
set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test chatparse_inkling2_test)

# relayout_parity_test checks each kernel library's relayout of libquant's planes against a
# recorded hash of the stored bytes. libr4d's layout sources are host-only, so they are compiled in,
# with -ffp-contract=off as libr4d uses, so scale conversions round identically.
# r4d_ar_links_test checks libr4d's header-only link reader, so it needs only the include path.
# relayout_iqr_test holds the IQR relayout to the stored form r4d_iqr.h describes, so it also
# compiles r4d_iqr_layout.cpp.
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test relayout_iqr_test)
add_executable(r3d_moe_iqr_host r3d_moe_iqr_host.cpp ../libr3d/r3dh_moe_iqr_layout.cpp)
target_link_libraries(r3d_moe_iqr_host PRIVATE radiance::abi)
add_test(NAME r3d_moe_iqr_host COMMAND r3d_moe_iqr_host)
set_tests_properties(r3d_moe_iqr_host PROPERTIES LABELS unit)
if(TARGET libr3d)
  get_target_property(r3d_targets libr3d HIP_ARCHITECTURES)
  if(r3d_targets STREQUAL "gfx1100")
    add_executable(r3d_moe_iqr_gpu r3d_moe_iqr_gpu.cpp ../core/util/rad_util.cpp)
    target_link_libraries(r3d_moe_iqr_gpu PRIVATE radiance::abi ${RAD_HIP_RUNTIME} ${CMAKE_DL_LIBS})
    target_compile_options(r3d_moe_iqr_gpu PRIVATE -ffp-contract=off)
    add_dependencies(r3d_moe_iqr_gpu libr3d)
    add_test(NAME r3d_moe_iqr_catalogue COMMAND r3d_moe_iqr_gpu $<TARGET_FILE:libr3d> --catalogue-only)
    set_tests_properties(r3d_moe_iqr_catalogue PROPERTIES LABELS unit)
    add_test(NAME r3d_moe_iqr_gpu COMMAND r3d_moe_iqr_gpu $<TARGET_FILE:libr3d>)
    set_tests_properties(r3d_moe_iqr_gpu PROPERTIES LABELS gpu RESOURCE_LOCK card SKIP_RETURN_CODE 77)
  endif()
endif()
# Their relayouts' vector loops, at every CPU level (libr4d/r4d_hsimd.h), built for these tests
# whether or not libr4d itself is.
include(${CMAKE_SOURCE_DIR}/cmake/RadSimdLevels.cmake)
rad_simd_level_objects(r4d_hsimd_test ${CMAKE_SOURCE_DIR}/libr4d/r4d_hsimd_kernels.cpp
                       R4D_HSIMD_TEST_OBJS DEFINE R4D_HSIMD_LEVEL
                       INCLUDES ${CMAKE_SOURCE_DIR}/libr4d)

# ref2va_pack_test checks the Ref2VA sequence packing (arch/minimaxh3/rad_ref2va_pack.cpp, a
# device-free TU of the plugin) against golden vectors generated from the reference implementation
# by tests/data/ref2va/gen_golden.py. It is pure host arithmetic, so like arch_test it links no
# core; only rad_json (the JSON DOM its golden reader uses).
set(RAD_TESTS_WITH_PACK ref2va_pack_test)

# vae_geom_test checks the encode geometry (arch/minimaxh3/rad_vae_geom.cpp) the same way: golden
# vectors generated by running the reference VAEs' own encoders on CPU
# (tests/data/vae_geom/gen_golden.py). Also device-free, also links no core.
set(RAD_TESTS_WITH_VAE_GEOM vae_geom_test)

# Chat templates (copied from the model repositories) and media samples, passed by absolute path so
# test binaries can run from anywhere.
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
set(RAD_MEDIA_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/media)
# Checked-in golden blobs (tests/data/golden), read at test time (tests/uocr_resample_golden.h).
set(RAD_GOLDEN_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/golden)

# libstdc++ before rad_core on every test's link line. lld extracts archive members to resolve a
# shared library's imports too: ROCm 10.1's libamdhip64 imports std::string::reserve, which g++-14
# emits weak in rad_graph.cpp.o, and that object pulls in dispatch.cpp.o, whose strong device calls
# silently replace the weak fakes sched_test, ref_test and runtime_test rely on.
set(RAD_TEST_CORE stdc++ rad_core)

# harness_test runs harness_fixture's cases through the harness's command line (rad_test.h).
set(RAD_TESTS_HARNESS harness_test)
add_executable(harness_fixture ${CMAKE_CURRENT_SOURCE_DIR}/harness_fixture.cpp)
set_target_properties(harness_fixture PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)

# Binaries registered as several entries, <bin>_shard<k> running `<bin> --shard k/n`, so their
# cases run in parallel and no entry is the fast tier's long pole.
set(RAD_TEST_SHARDS_gbnf_test 4)
set(RAD_TEST_SHARDS_mtp_rrs_test 14)  # chi-square statistics: ~5 CPU minutes in all (the adaptive depth's rules and their controls are ~2 of them); fourteen ctest entries of under a minute and a half each

# ------------------------------------------------------------------ the environment of every test
#
# OMP_WAIT_POLICY=passive and a team of 4: libref, libquant and libavx open OpenMP regions over
# small loops, and with libgomp's default wait every thread of a 32-thread team spins at each
# barrier. Beside other processes that costs 10-100x (a 0.2 s binary takes a minute). Four threads
# keep the multi-threaded paths, rows split across a team, under test.
#
# ROCR_VISIBLE_DEVICES=99 hides every card, so a unit test runs on the host backend on every
# machine: the same code everywhere, and nothing touches a card a server is using. The _card
# entries below run the device tests on a card.
#
# RAD_TEST_STRICT=1: a plugin or fixture this build makes is never legitimately absent, so a test
# that cannot find one fails rather than skips. RAD_TEST_TMPDIR puts radtest::tmpdir() in the build
# tree, on disk, where O_DIRECT works.
#
# RAD_TEST_CPU_BUDGET: a unit binary that spends more CPU seconds than this fails (rad_test.h), so
# a slow case or a spinning thread pool is caught when it lands. Sanitised and Debug builds run
# several times slower and have no budget.
set(RAD_TEST_OMP_THREADS 4)
set(RAD_TEST_TIMEOUT 120)
set(RAD_TEST_CPU_BUDGET 10)
set(RAD_TEST_SAN_ENV "")
if(RAD_ASAN)
  list(APPEND RAD_TEST_SAN_ENV "ASAN_OPTIONS=detect_leaks=1" "UBSAN_OPTIONS=print_stacktrace=1")
elseif(RAD_TSAN)
  # libgomp is not instrumented, so its synchronisation would read as races: one thread.
  set(RAD_TEST_OMP_THREADS 1)
  list(APPEND RAD_TEST_SAN_ENV "TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1")
endif()
if(RAD_ASAN OR RAD_TSAN OR CMAKE_BUILD_TYPE STREQUAL "Debug")
  set(RAD_TEST_TIMEOUT 600)
  set(RAD_TEST_CPU_BUDGET 0)
endif()
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/tmp)
set(RAD_TEST_OMP_ENV "OMP_WAIT_POLICY=passive" "OMP_NUM_THREADS=${RAD_TEST_OMP_THREADS}")
set(RAD_TEST_CARD_ENV "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home" ${RAD_TEST_OMP_ENV}
                      "RAD_TEST_STRICT=1" "RAD_TEST_TMPDIR=${CMAKE_BINARY_DIR}/tmp"
                      ${RAD_TEST_SAN_ENV})
set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99")

# Binaries that need more CPU than the default budget, and what costs it. Lower an entry when its
# cost comes down, so the tripwire stays tight.
set(RAD_TEST_CPU_BUDGET_mtp_rrs_test 100)  # chi-square over 2e5..4e5 seeds a case
set(RAD_TEST_CPU_BUDGET_mtp_block_test 40)  # exact enumeration (g up to 4) plus ~1.6e6 chi-square steps over the real shared verify code
set(RAD_TEST_CPU_BUDGET_quant_ggml_test 25)  # llama.cpp's iq1_s and iq2_* grid searches, ~13 s
set(RAD_TEST_CPU_BUDGET_tokenizer_test 20)  # the reference encoder over every corpus: ~3 s built by GCC 16, ~10.5 s by GCC 14 (the image's Ubuntu)
set(RAD_TEST_CPU_BUDGET_arch_test 15)  # every plugin's graph declared; ~10.8 s with the batched-tower case
set(RAD_TEST_CPU_BUDGET_device_test 30)  # on a card, the paging and remap cases spin in stream waits: ~10 s; with no card (the image's test stage) they copy, write and compare on the host: 17-19 s
set(RAD_TEST_CPU_BUDGET_deepseek41_test 10)  # DeepSeek-V4.1's caches declared at bf16 and fp8, one and three ranks
set(RAD_TEST_CPU_BUDGET_glm5next_test 20)  # GLM-5.3-Flash's graphs and op schemas: ~4.8 s built by GCC 16, ~10.1 s by GCC 14 (the image's Ubuntu)
set(RAD_TEST_CPU_BUDGET_museglimmer_test 10)  # Muse Glimmer's trunk and tower graphs and steps: ~2 s built by GCC 14

# Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a
# team's worth of slots rather than one.
set(RAD_TESTS_THREADED quant_ggml_test relayout_parity_test)

# A harness binary as a ctest entry, `<bin> -perf_ ARGS...`, labelled unit. Its perf_ cases run in
# <bin>_perf instead (below).
function(rad_unit_test name bin)
  set(budget ${RAD_TEST_CPU_BUDGET})
  if(budget AND DEFINED RAD_TEST_CPU_BUDGET_${bin})
    set(budget ${RAD_TEST_CPU_BUDGET_${bin}})
  endif()
  add_test(NAME ${name} COMMAND ${bin} -perf_ ${ARGN})
  # 77 is the harness's "nothing was checked" (rad_test.h).
  set_tests_properties(${name} PROPERTIES
    LABELS unit
    SKIP_RETURN_CODE 77
    TIMEOUT ${RAD_TEST_TIMEOUT}
    ENVIRONMENT "${RAD_TEST_ENV};RAD_TEST_CPU_BUDGET=${budget}")
  if(bin IN_LIST RAD_TESTS_THREADED)
    set_tests_properties(${name} PROPERTIES PROCESSORS ${RAD_TEST_OMP_THREADS})
  endif()
endfunction()

# The script CTestTestfile.cmake includes to register the perf_ entries (below).
set(RAD_PERF_SCRIPT "set(RAD_TEST_ENV [==[${RAD_TEST_ENV}]==])\nset(RAD_TEST_TIMEOUT ${RAD_TEST_TIMEOUT})\n")
string(APPEND RAD_PERF_SCRIPT "include([==[${CMAKE_CURRENT_SOURCE_DIR}/perf_entries.cmake]==])\n")

# shipped_plugins_test loads the shipped architecture plugins, which bind the plugin-facing C ABI
# back to the host at dlopen, so like the engine it carries all of rad_core and exports it.
set(RAD_TESTS_WHOLE_CORE shipped_plugins_test generator_lora_engine_test)

file(GLOB RAD_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*_test.cpp)
if(NOT RAD_HIP_FOUND)
  list(FILTER RAD_TESTS EXCLUDE REGEX "/(dspark|attn_rel)_device_test\\.cpp$")
endif()
# A card test takes a plugin's path and is registered below, on the card only.
list(FILTER RAD_TESTS EXCLUDE REGEX "/sconv_device_test\\.cpp$")
list(FILTER RAD_TESTS EXCLUDE REGEX "/l2clip_device_test\\.cpp$")
list(FILTER RAD_TESTS EXCLUDE REGEX "/posemb_device_test\\.cpp$")
list(FILTER RAD_TESTS EXCLUDE REGEX "/r3d_iqr_device_test\\.cpp$")
foreach(t ${RAD_TESTS})
  get_filename_component(n ${t} NAME_WE)
  if(n IN_LIST RAD_TESTS_NO_CORE)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/core/util/rad_util.cpp)
    if(n STREQUAL "nemotron35_test")
      target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/core/mm/processor.cpp
                                 ${CMAKE_SOURCE_DIR}/core/util/rowpool.cpp
                                 ${CMAKE_SOURCE_DIR}/core/mm/item.cpp
                                 ${CMAKE_SOURCE_DIR}/core/mm/media.cpp
                                 ${CMAKE_SOURCE_DIR}/core/server/nemotron35.cpp
                                 ${CMAKE_SOURCE_DIR}/core/server/oai.cpp)
      # Exercise the actual request parser without pulling the unrelated core runtime into the
      # recording-builder test. Unused completion/response helpers are discarded at link time.
      target_compile_options(${n} PRIVATE -ffunction-sections -fdata-sections)
      target_link_options(${n} PRIVATE -Wl,--gc-sections)
      file(GLOB NEMOTRON_TEST_TOKENIZER CONFIGURE_DEPENDS
           ${CMAKE_SOURCE_DIR}/core/text/tokenizer*.cpp ${CMAKE_SOURCE_DIR}/core/text/unicode_norm*.cpp)
      target_sources(${n} PRIVATE ${NEMOTRON_TEST_TOKENIZER})
      # The tokenizer translation units call the dispatched SIMD helpers (core/util/simd.h),
      # which the no-core link would otherwise lack. oai.cpp reads request bodies with yyjson.
      target_link_libraries(${n} PRIVATE rad_vendor_llama rad_json rad_simd)
      target_link_libraries(${n} PRIVATE ${CMAKE_DL_LIBS})
      target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/vendor)
      add_dependencies(${n} libref)
      if(TARGET libavx)
        add_dependencies(${n} libavx)
        target_compile_definitions(${n} PRIVATE RAD_NEMOTRON_TEST_AVX=1)
      endif()
    endif()
  elseif(n STREQUAL "r3d_iqr_test")
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/libr3d/r3d_iqr_layout.cpp)
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr3d)
  elseif(n STREQUAL "r3d_iqr_selection_test")
    add_library(r3d_iqr_fixture MODULE r3d_iqr_fixture.cpp)
    target_link_libraries(r3d_iqr_fixture PRIVATE radiance::abi)
    if(TARGET libr3d)
      get_target_property(r3d_targets libr3d HIP_ARCHITECTURES)
    endif()
    if(r3d_targets STREQUAL "gfx1100")
      target_compile_definitions(r3d_iqr_fixture PRIVATE R3D_IQR_SHIPPED_CATALOGUE)
      target_link_libraries(r3d_iqr_fixture PRIVATE -Wl,--no-as-needed $<TARGET_FILE:libr3d> -Wl,--as-needed)
      add_dependencies(r3d_iqr_fixture libr3d)
    else()
      target_sources(r3d_iqr_fixture PRIVATE ${CMAKE_SOURCE_DIR}/libr3d/r3d_iqr_layout.cpp
                                              ${CMAKE_SOURCE_DIR}/libr3d/r3d_shapes.cpp)
      target_include_directories(r3d_iqr_fixture PRIVATE ${CMAKE_SOURCE_DIR}/libr3d)
      target_compile_definitions(r3d_iqr_fixture PRIVATE R3D_DENSE_IQR)
    endif()
    add_executable(${n} ${t})
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr3d)
    target_compile_definitions(${n} PRIVATE R3D_IQR_FIXTURE="$<TARGET_FILE:r3d_iqr_fixture>")
    add_dependencies(${n} r3d_iqr_fixture)
  elseif(n IN_LIST RAD_TESTS_HARNESS)
    add_executable(${n} ${t})
    add_dependencies(${n} harness_fixture)
    target_compile_definitions(${n} PRIVATE RAD_HARNESS_FIXTURE="$<TARGET_FILE:harness_fixture>")
  elseif(n IN_LIST RAD_TESTS_WITH_TOKREF)
    add_executable(${n} ${t})
    target_link_libraries(${n} PRIVATE rad_tokref ${RAD_TEST_CORE})
  elseif(n IN_LIST RAD_TESTS_WITH_TOOLS)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/tools/kfixture.cpp
                            ${CMAKE_SOURCE_DIR}/tools/opshapes.cpp
                            ${CMAKE_SOURCE_DIR}/tools/kbench_core.cpp)
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS})
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
  elseif(n IN_LIST RAD_TESTS_WITH_IFACE)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/tools/iface.cpp)
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
  elseif(n IN_LIST RAD_TESTS_WITH_R4D_HOST)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/libr4d/r4d_layout.cpp
                            ${CMAKE_SOURCE_DIR}/libr4d/r4d_fp8_layout.cpp
                            ${CMAKE_SOURCE_DIR}/libr4d/r4d_hsimd.cpp ${R4D_HSIMD_TEST_OBJS})
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS})
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d)
    target_compile_options(${n} PRIVATE -ffp-contract=off)
    # relayout_parity_test also holds tools/opshapes.cpp's fallback table to these hooks' byte
    # totals, so it needs the table's source too.
    if(n STREQUAL relayout_parity_test)
      target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools/opshapes.cpp)
      target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
    endif()
    if(n STREQUAL relayout_iqr_test)
      target_sources(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d/r4d_iqr_layout.cpp)
    endif()
  elseif(n IN_LIST RAD_TESTS_WITH_PACK)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_ref2va_pack.cpp)
    target_link_libraries(${n} PRIVATE rad_json)
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
                                            ${CMAKE_SOURCE_DIR}/vendor)
    target_compile_definitions(${n} PRIVATE
      RAD_REF2VA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/ref2va")
  elseif(n IN_LIST RAD_TESTS_WITH_VAE_GEOM)
    add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/arch/minimaxh3/rad_vae_geom.cpp)
    target_link_libraries(${n} PRIVATE rad_json)
    target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/arch/minimaxh3
                                            ${CMAKE_SOURCE_DIR}/vendor)
    target_compile_definitions(${n} PRIVATE
      RAD_VAE_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/vae_geom")
  elseif(n IN_LIST RAD_TESTS_WHOLE_CORE)
    add_executable(${n} ${t})
    target_link_libraries(${n} PRIVATE stdc++ "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
    set_target_properties(${n} PROPERTIES ENABLE_EXPORTS ON)
  elseif(n IN_LIST RAD_TESTS_WITH_GBNF_ORACLE)
    add_executable(${n} ${t} ${CMAKE_CURRENT_SOURCE_DIR}/gbnf_oracle.cpp)
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
    # Chat templates whose tool-call grammars are checked against the oracle (checked in; the
    # tokenizers are too large).
    target_compile_definitions(${n} PRIVATE
      RAD_GBNF_TEST_DATA="${CMAKE_CURRENT_SOURCE_DIR}/data/gbnf")
  else()
    add_executable(${n} ${t})
    target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
  endif()
  if(n IN_LIST RAD_TESTS_WITH_LEGACY)
    target_link_libraries(${n} PRIVATE rad_legacy_toolparse)
  endif()
  target_compile_definitions(${n} PRIVATE RAD_CHAT_FIXTURES="${RAD_CHAT_FIXTURES}"
                                          RAD_MEDIA_FIXTURES="${RAD_MEDIA_FIXTURES}"
                                          RAD_GOLDEN_FIXTURES="${RAD_GOLDEN_FIXTURES}")
  # Normally inherited from rad_core; tests that do not link it still need the ABI headers.
  target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi
                                          ${CMAKE_BINARY_DIR}/rad_include)
  set_target_properties(${n} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  # mem_test loads a kernel plugin that calls back into the device API, so it exports it like the
  # engine binary.
  if(n STREQUAL "mem_test")
    set_target_properties(${n} PROPERTIES ENABLE_EXPORTS ON)
  endif()
  if(n STREQUAL "spechub_device_test")
    # The device verify rows against their host rows: on a card, so it carries the gpu label and
    # the card environment (without either it would pass having checked nothing).
    if(RAD_HIP_FOUND AND TARGET spechub)
      add_test(NAME ${n} COMMAND ${n})
      set_tests_properties(${n} PROPERTIES
        LABELS gpu
        TIMEOUT ${RAD_TEST_TIMEOUT}
        ENVIRONMENT "${RAD_TEST_CARD_ENV}")
    endif()
  elseif(n STREQUAL "dspark_device_test")
    if(RAD_HIP_FOUND AND TARGET libr4d)
      add_dependencies(${n} libr4d)
      add_test(NAME ${n} COMMAND ${n} ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
      set_tests_properties(${n} PROPERTIES
        LABELS gpu
        SKIP_RETURN_CODE 77
        TIMEOUT ${RAD_TEST_TIMEOUT}
        ENVIRONMENT "${RAD_TEST_CARD_ENV}")
    endif()
  elseif(n STREQUAL "attn_rel_device_test")
    # attn_paged_rel's libr4d rows against libref on the card (tests/attn_rel_device_test.cpp).
    if(RAD_HIP_FOUND AND TARGET libr4d AND TARGET libref)
      add_dependencies(${n} libr4d libref)
      add_test(NAME ${n} COMMAND ${n} ${RAD_PLUGIN_OUT}/kernels/libr4d.so
                                 ${RAD_PLUGIN_OUT}/kernels/libref.so)
      set_tests_properties(${n} PROPERTIES
        LABELS gpu
        SKIP_RETURN_CODE 77
        TIMEOUT ${RAD_TEST_TIMEOUT}
        ENVIRONMENT "${RAD_TEST_CARD_ENV}")
    endif()
  else()
    if(DEFINED RAD_TEST_SHARDS_${n})
      math(EXPR last "${RAD_TEST_SHARDS_${n}} - 1")
      foreach(k RANGE ${last})
        rad_unit_test(${n}_shard${k} ${n} --shard ${k}/${RAD_TEST_SHARDS_${n}})
      endforeach()
    else()
      rad_unit_test(${n} ${n})
    endif()
    string(APPEND RAD_PERF_SCRIPT
           "rad_perf_entry(${n} [==[${t}]==] [==[${CMAKE_BINARY_DIR}/tests/${n}]==])\n")
  endif()
endforeach()

# quant_ggml_test holds the reader's IQ2 tables (core/format/ggml_iq2_tables.h) to libquant's. The
# test loads libquant as a plugin, which exports no tables, so it compiles libquant's table source.
if(TARGET quant_ggml_test)
  target_sources(quant_ggml_test PRIVATE ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_tables.cpp)
  target_include_directories(quant_ggml_test PRIVATE ${CMAKE_SOURCE_DIR}/libquant)
endif()

# ref_test and checkpoint_test hold the ggml ops and the plane decode to llama.cpp's blocks through
# libquant's definition of them (lq_ggml_planes, lq_ggml_dequant). Nothing exports it, so each test
# compiles its sources, as libref and libr4d do.
foreach(t ref_test checkpoint_test)
  if(TARGET ${t})
    target_sources(${t} PRIVATE ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_planes.cpp
                   ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_dequant.cpp
                   ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_tables.cpp)
    target_include_directories(${t} PRIVATE ${CMAKE_SOURCE_DIR}/libquant)
  endif()
endforeach()

# nemotronh_test compiles the plugin's source, which names a weight's llama.cpp block type
# through libquant's definition of the blocks (arch/common/rad_ggml.h), as the plugin's own
# build does (arch/nemotronh/CMakeLists.txt).
if(TARGET nemotronh_test)
  target_sources(nemotronh_test PRIVATE ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_planes.cpp
                 ${CMAKE_SOURCE_DIR}/libquant/lq_ggml_tables.cpp)
  target_include_directories(nemotronh_test PRIVATE ${CMAKE_SOURCE_DIR}/libquant)
  target_compile_definitions(nemotronh_test PRIVATE RAD_ARCH_HAVE_GGML=1)
endif()

# ================================================================== perf_ cases
#
# A case named perf_... asserts a wall-clock cost, which tests running beside it would distort. The
# unit entries leave those cases out, and <bin>_perf runs them alone (RUN_SERIAL, label perf).
# Which binaries have one is read from their sources whenever ctest loads the tests
# (perf_entries.cmake), so a new perf_ case is registered without reconfiguring.
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/rad_perf_tests.cmake "${RAD_PERF_SCRIPT}")
set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES
             ${CMAKE_CURRENT_BINARY_DIR}/rad_perf_tests.cmake)

if(TARGET libr3d)
  get_target_property(r3d_targets libr3d HIP_ARCHITECTURES)
  if(r3d_targets STREQUAL "gfx1100")
    add_executable(r3d_iqr_device_test r3d_iqr_device_test.cpp)
    target_link_libraries(r3d_iqr_device_test PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS})
    target_compile_options(r3d_iqr_device_test PRIVATE -ffp-contract=off)
    set_target_properties(r3d_iqr_device_test PROPERTIES ENABLE_EXPORTS ON RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
    add_dependencies(r3d_iqr_device_test libr3d)
    add_test(NAME r3d_iqr_catalogue_test COMMAND r3d_iqr_device_test $<TARGET_FILE:libr3d> --catalogue-only)
    set_tests_properties(r3d_iqr_catalogue_test PROPERTIES LABELS unit ENVIRONMENT "${RAD_TEST_ENV}")
    add_test(NAME r3d_iqr_device_test_card COMMAND r3d_iqr_device_test $<TARGET_FILE:libr3d>)
    set_tests_properties(r3d_iqr_device_test_card PROPERTIES LABELS gpu RESOURCE_LOCK card
      SKIP_RETURN_CODE 77 TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${RAD_TEST_CARD_ENV}")
  endif()
endif()

# sconv_res on the card: libr4d's exported launcher against the formula, over the model's shapes.
if(RAD_HIP_FOUND AND TARGET libr4d)
  add_executable(sconv_device_test ${CMAKE_CURRENT_SOURCE_DIR}/sconv_device_test.cpp)
  set_target_properties(sconv_device_test PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  target_link_libraries(sconv_device_test PRIVATE radiance::abi ${RAD_HIP_RUNTIME} ${CMAKE_DL_LIBS})
  add_dependencies(sconv_device_test libr4d)
  add_test(NAME sconv_device_test_card COMMAND sconv_device_test ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
  set_tests_properties(sconv_device_test_card PROPERTIES
    LABELS gpu
    RUN_SERIAL TRUE
    TIMEOUT ${RAD_TEST_TIMEOUT}
    ENVIRONMENT "${RAD_TEST_CARD_ENV}")
endif()

# l2_clip on the card: libr4d's exported launcher against the formula, at the model's shapes.
if(RAD_HIP_FOUND AND TARGET libr4d)
  add_executable(l2clip_device_test ${CMAKE_CURRENT_SOURCE_DIR}/l2clip_device_test.cpp)
  set_target_properties(l2clip_device_test PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  target_link_libraries(l2clip_device_test PRIVATE radiance::abi ${RAD_HIP_RUNTIME} ${CMAKE_DL_LIBS})
  add_dependencies(l2clip_device_test libr4d)
  add_test(NAME l2clip_device_test_card COMMAND l2clip_device_test ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
  set_tests_properties(l2clip_device_test_card PROPERTIES
    LABELS gpu
    RUN_SERIAL TRUE
    TIMEOUT ${RAD_TEST_TIMEOUT}
    ENVIRONMENT "${RAD_TEST_CARD_ENV}")
endif()

# posemb_resample on the card: libr4d's row against libref's over the vision tower's grids and the
# dtype pairs (tests/posemb_device_test.cpp).
if(RAD_HIP_FOUND AND TARGET libr4d AND TARGET libref)
  add_executable(posemb_device_test ${CMAKE_CURRENT_SOURCE_DIR}/posemb_device_test.cpp)
  set_target_properties(posemb_device_test PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  target_link_libraries(posemb_device_test PRIVATE radiance::abi ${RAD_HIP_RUNTIME} ${CMAKE_DL_LIBS})
  add_dependencies(posemb_device_test libr4d libref)
  add_test(NAME posemb_device_test_card COMMAND posemb_device_test ${RAD_PLUGIN_OUT}/kernels/libr4d.so
                                        ${RAD_PLUGIN_OUT}/kernels/libref.so)
  set_tests_properties(posemb_device_test_card PROPERTIES
    LABELS gpu
    RUN_SERIAL TRUE
    SKIP_RETURN_CODE 77
    TIMEOUT ${RAD_TEST_TIMEOUT}
    ENVIRONMENT "${RAD_TEST_CARD_ENV}")
endif()

# ================================================================== the device tests on a card
#
# The unit entries run on the host backend. These run the tests whose code differs on a card (the
# AQL backend, the driver's elastic commit, the mover's copies, libquant's trellis GPTQ) on the
# card, one at a time: a test that commits device memory fails beside another holding it, or beside
# a server.
target_compile_definitions(quant_ggml_gpu_test PRIVATE
  RAD_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data")
if(RAD_HIP_FOUND)
  foreach(n device_test mem_test place_test runtime_test quant_tcq_gpu_test glm_device_test quant_ggml_gpu_test)
    add_test(NAME ${n}_card COMMAND ${n} -perf_)
    set_tests_properties(${n}_card PROPERTIES
      LABELS gpu
      SKIP_RETURN_CODE 77
      TIMEOUT ${RAD_TEST_TIMEOUT}
      ENVIRONMENT "${RAD_TEST_CARD_ENV}")
  endforeach()
endif()

# glm_device_test holds the GLM plugin's fused device rows to libr4d's chains byte for byte on a
# card (skips without one, or without the device rows); it needs both libraries' paths.
if(TARGET glm AND TARGET glm_device_test)
  target_link_libraries(glm_device_test PRIVATE ${CMAKE_DL_LIBS})
  target_compile_definitions(glm_device_test PRIVATE
    RAD_GLM_LIB="${RAD_PLUGIN_OUT}/kernels/glm.so"
    RAD_R4D_LIB="${RAD_PLUGIN_OUT}/kernels/libr4d.so"
    RAD_REF_LIB="${RAD_PLUGIN_OUT}/kernels/libref.so")
  add_dependencies(glm_device_test glm)
  if(TARGET libref)
    add_dependencies(glm_device_test libref)
  endif()
  if(TARGET libr4d)
    add_dependencies(glm_device_test libr4d)
  endif()
endif()

# plugin_test's libr4d cases run against the shipped RDNA4 library. Only a build whose GPU
# targets name an RDNA4 card makes one; the define tells the test which kind of build it is in,
# so a one-card build for another family skips those cases instead of failing strict mode.
if(TARGET libr4d)
  target_compile_definitions(plugin_test PRIVATE RAD_TEST_HAS_LIBR4D=1)
  target_compile_definitions(shipped_plugins_test PRIVATE RAD_TEST_HAS_LIBR4D=1)
  add_dependencies(plugin_test libr4d)
endif()
# shipped_plugins_test loads the EXL3 device library beside the reference where the build makes it
# (exl3/kernels/exl3r4d, gfx1201 targets only).
if(TARGET exl3r4d)
  target_compile_definitions(shipped_plugins_test PRIVATE RAD_TEST_HAS_EXL3R4D=1)
endif()

# spechub_wiring_test dlopens the built spechub plugin and checks how its rows are classified: the
# device rows must be production kernels and the host oracle rows must stay reference. It needs the
# library path and the same RAD_SPECHUB_WITH_DEVICE answer the plugin was built with.
if(TARGET spechub)
  target_link_libraries(spechub_wiring_test PRIVATE ${CMAKE_DL_LIBS})
  target_compile_definitions(spechub_wiring_test PRIVATE
    RAD_SPECHUB_LIB="${RAD_PLUGIN_OUT}/kernels/spechub.so")
  if(RAD_HIP_FOUND)
    target_compile_definitions(spechub_wiring_test PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
  endif()
  add_dependencies(spechub_wiring_test spechub)
  # spechub_device_test runs the plugin's device verify rows against their host rows on a card
  # (skips without one); it needs the same library path.
  target_link_libraries(spechub_device_test PRIVATE ${CMAKE_DL_LIBS})
  target_compile_definitions(spechub_device_test PRIVATE
    RAD_SPECHUB_LIB="${RAD_PLUGIN_OUT}/kernels/spechub.so")
  add_dependencies(spechub_device_test spechub)
  # sample_test's coupling case declares a Sampler with draft_coupling set and needs the verify
  # op the spechub plugin carries (its host row); it skips when the library is absent.
  add_dependencies(sample_test spechub)
endif()

if(TARGET spark25_recipe_test)
  target_compile_definitions(spark25_recipe_test PRIVATE
    RAD_SPARK25_RECIPE_DIR="${CMAKE_SOURCE_DIR}/data/recipes")
endif()

# ================================================================== whole models on the CPU
#
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
# the host backend; convert_test runs rad-convert on the same checkpoints. Both start the built
# binaries as children, so they depend on them and on every plugin the checkpoints select
# (llama_fp8 for convert_test's --set of an fp8 quantization_config).
set(RAD_E2E_DEPS radiance rad-convert rad-sidecar libref libquant nemotron35_embed qwen35_bf16 lfm2_bf16 gemma4 gemma4_bf16
                 llama_dense_fp8 llama_fp8 qwenimage21)
if(TARGET libavx)
  list(APPEND RAD_E2E_DEPS libavx)
endif()
foreach(t engine_e2e_test convert_test clef_decision_test laya_decision_test spark25_convert_test)
  if(TARGET ${t})
    target_compile_definitions(${t} PRIVATE
      RAD_E2E_SERVER="$<TARGET_FILE:radiance>" RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>"
      RAD_E2E_SIDECAR="$<TARGET_FILE:rad-sidecar>"
      RAD_E2E_HOME="${RAD_PLUGIN_OUT}" RAD_E2E_RECIPES="${CMAKE_SOURCE_DIR}/data/recipes")
    if(t STREQUAL "spark25_convert_test")
      add_dependencies(${t} rad-convert libref spark25_bf16)
    elseif(t STREQUAL "clef_decision_test")
      # The tiny clef's golden (tests/mkclefgolden.py) and the one plugin a clef container selects.
      target_compile_definitions(${t} PRIVATE
        RAD_CLEF_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/clef_tiny.json")
      add_dependencies(${t} radiance rad-convert libref libquant clef_bf16)
    elseif(t STREQUAL "laya_decision_test")
      # The tiny Laya's golden (tests/mklayagolden.py) and the plugin a Laya container selects.
      target_compile_definitions(${t} PRIVATE
        RAD_LAYA_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/laya_tiny.json")
      add_dependencies(${t} radiance rad-convert libref libquant laya)
    else()
      add_dependencies(${t} ${RAD_E2E_DEPS})
    endif()
  endif()
endforeach()
# This test loads a tiny generator in process and holds real adapter slots through replacement
# and unload. Export its core callbacks and build only the model/plugin it exercises.
if(TARGET generator_lora_engine_test)
  target_compile_definitions(generator_lora_engine_test PRIVATE
    RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>" RAD_E2E_HOME="${RAD_PLUGIN_OUT}")
  add_dependencies(generator_lora_engine_test rad-convert libref libquant qwenimage21)
  set_tests_properties(generator_lora_engine_test PROPERTIES LABELS "e2e" TIMEOUT 90)
endif()
# 6 to 17 s by build type and load, mostly libref's GEMMs and decode steps and the engine's own
# startups, so labelled `e2e` and kept out of the fast tier; the host and full tiers run it.
if(TARGET engine_e2e_test)
  set_tests_properties(engine_e2e_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()
if(TARGET clef_decision_test)
  set_tests_properties(clef_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()
if(TARGET laya_decision_test)
  set_tests_properties(laya_decision_test PROPERTIES LABELS "e2e" TIMEOUT 300)
endif()

# abi_layout_test compares the ABI's struct layouts with a C translation unit's: abi_c_test.c
# includes every abi/ header as strict C11, so a header only C++ accepts fails the build.
if(TARGET abi_layout_test)
  target_sources(abi_layout_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/abi_c_test.c)
  set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/abi_c_test.c PROPERTIES
    COMPILE_OPTIONS "-std=c11;-pedantic-errors;-Wall;-Wextra")
endif()

# arch_test and nemotronh_test read libref's vocabulary from $RADIANCE_HOME/kernels to check that
# each architecture declares on it, and glm5next_test the loaded libraries' op schemas, so libref is
# built before them.
foreach(t arch_test breeze_arch_test glm5next_test deepseek41_test nemotronh_test)
  if(TARGET libref AND TARGET ${t})
    add_dependencies(${t} libref)
  endif()
endforeach()
# glm5next_test also loads plugin/glm's glm.so when it is configured, for its schemas and its
# machine check.
if(TARGET glm AND TARGET glm5next_test)
  add_dependencies(glm5next_test glm)
endif()

# kbench_mutant_test runs rad-kbench against the deliberately defective kernel libraries
# (core/plugin/testplugin/kbmutant.cc) on the host backend, so it needs the tool, libref and the
# mutants built.
if(TARGET kbench_mutant_test AND TARGET rad-kbench AND TARGET libref)
  target_compile_definitions(kbench_mutant_test PRIVATE
    RAD_KBENCH_BIN="$<TARGET_FILE:rad-kbench>" RAD_PLUGIN_DIR="${RAD_PLUGIN_OUT}")
  # It also loads a mutant in process, whose device rows call back into the device API.
  set_target_properties(kbench_mutant_test PROPERTIES ENABLE_EXPORTS ON)
  add_dependencies(kbench_mutant_test rad-kbench libref radtest_kbarch)
  foreach(m ${RAD_KBM_MUTANTS})
    add_dependencies(kbench_mutant_test kbm_${m})
  endforeach()
  # One case replays libavx's sampler stages against libref; it is reported missing without it.
  if(TARGET libavx)
    add_dependencies(kbench_mutant_test libavx)
  endif()
endif()

# ================================================================== the device selftest
#
# r4d_selftest is the only check of libr4d's fusion claims: rows declaring a fused kernel
# byte-identical to the ops it replaces, verified by memcmp against the unfused kernels on the same
# inputs. It needs a card and forks a child per row (about fifteen minutes on an R9700), so it is
# labelled `slow`; the default `ctest` still runs it.
if(RAD_HIP_FOUND AND TARGET r4d_selftest)
  add_test(NAME r4d_selftest
           COMMAND r4d_selftest ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
  set_tests_properties(r4d_selftest PROPERTIES
    LABELS "slow;gpu"
    TIMEOUT 2400
    ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
endif()

# ================================================================== the chained waits' scalar-cache flush
#
# A chained kernel whose wait is r4d_chain_wait_vec skips `s_dcache_inv` (libr4d/r4d_chain.h). This
# compiles every unit with a chained kernel to gfx1201 assembly with the build's own flags and fails
# on a kernel that skips it and has a scalar load, from anything but its argument segment, behind
# its acquire. No card needed; it recompiles the kernels (minutes), hence `slow`.
find_package(Python3 QUIET COMPONENTS Interpreter)
if(RAD_HIP_FOUND AND Python3_FOUND AND CMAKE_EXPORT_COMPILE_COMMANDS)
  add_test(NAME chain_scalar_audit
           COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/chain_scalar_audit.py
                   ${CMAKE_BINARY_DIR} ${CMAKE_BINARY_DIR}/chain_scalar_audit --check)
  set_tests_properties(chain_scalar_audit PROPERTIES LABELS "slow" TIMEOUT 1800)
endif()

# ================================================================== libhalo's interface parity
#
# libhalo serves gfx1151 behind libr4d's exact interface (libhalo/halo_parity.cpp): the same op
# schemas and rows, so every model plugin runs on either. Host-only (the tables, no device calls);
# present when one build produces both plugins. Labelled `parity`: it fails while libr4d has ops
# libhalo has not ported yet (every one printed as "only in libr4d"), which the image's test stage
# leaves out; a schema both declare must still agree, or the loader refuses the second library.
if(TARGET halo_parity)
  add_test(NAME halo_parity
           COMMAND halo_parity ${RAD_PLUGIN_OUT}/kernels/libr4d.so ${RAD_PLUGIN_OUT}/kernels/libhalo.so)
  set_tests_properties(halo_parity PROPERTIES LABELS "fast;parity" TIMEOUT 60)
endif()

# ================================================================== the device layer without SVM
#
# Without the KFD SVM API (e.g. a KVM guest whose amdgpu registered no device memory with HMM), ROCr
# cannot lock host memory in place, and the backend allocates pinned ranges from the host pool
# instead (core/device/aql.cpp, "pinned host memory, in pieces"). HSA_USE_SVM=0 forces that path, so
# device_test runs a second time on the card under it.
if(RAD_HIP_FOUND AND TARGET device_test)
  add_test(NAME device_test_nosvm COMMAND device_test -perf_)
  set_tests_properties(device_test_nosvm PROPERTIES
    LABELS gpu
    SKIP_RETURN_CODE 77
    TIMEOUT ${RAD_TEST_TIMEOUT}
    ENVIRONMENT "${RAD_TEST_CARD_ENV};HSA_USE_SVM=0")
endif()

# ================================================================== kernel arguments in host memory
#
# A card whose PCI BAR is smaller than its VRAM gets its kernel argument rings and recorded-pass
# argument blocks in pinned host memory (core/device/aql.cpp, init_devices). --host-kargs places
# them there on any card, so device_test and runtime_test run that path a second time.
if(RAD_HIP_FOUND)
  foreach(n device_test runtime_test)
    if(TARGET ${n})
      add_test(NAME ${n}_hostkargs COMMAND ${n} --host-kargs -perf_)
      set_tests_properties(${n}_hostkargs PROPERTIES
        LABELS gpu
        SKIP_RETURN_CODE 77
        TIMEOUT ${RAD_TEST_TIMEOUT}
        ENVIRONMENT "${RAD_TEST_CARD_ENV}")
    endif()
  endforeach()
endif()

# ================================================================== the host kernels
#
# rad-avx-check compares libavx with libref op by op at every ISA level the machine supports, and
# runs embed_lookup_q over a file-backed table with two ranks racing the read-ahead. The table is
# written beside the binary (filesystem reports a direct-I/O alignment) and in TMPDIR (a tmpfs
# reports none, so reads align by block size, as on btrfs).
if(TARGET libavx AND TARGET rad-avx-check)
  add_test(NAME avx_check
           COMMAND rad-avx-check --ref ${RAD_PLUGIN_OUT}/kernels/libref.so
                                 --avx ${RAD_PLUGIN_OUT}/kernels/libavx.so)
  set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV})
  set_tests_properties(avx_check PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}")
endif()

# The same checker on another host library (avx_subset_plugin.cpp: part of libref under another
# name): the ops it lacks are listed rather than failed, cases go to the row whose constraints admit
# them, and a declining row still fails.
if(TARGET rad-avx-check AND TARGET libref)
  add_library(avx_subset_plugin MODULE avx_subset_plugin.cpp)
  target_link_libraries(avx_subset_plugin PRIVATE radiance::abi ${CMAKE_DL_LIBS})
  add_test(NAME avx_check_general
           COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/avx_check_general.sh
                   $<TARGET_FILE:rad-avx-check> ${RAD_PLUGIN_OUT}/kernels/libref.so
                   $<TARGET_FILE:avx_subset_plugin>)
  set(env ${RAD_TEST_OMP_ENV} "ROCR_VISIBLE_DEVICES=99" ${RAD_TEST_SAN_ENV})
  set_tests_properties(avx_check_general PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "${env}")
endif()

# The ISA instruments' parsers, on fixtures in the script: no build tree, no card, no ROCm. The
# wave counts at the 24-VGPR boundaries and the waterfall back-edge detection are the parts that
# can be wrong without anything else noticing.
add_test(NAME isa_tools COMMAND sh ${CMAKE_SOURCE_DIR}/libr4d/isa/selftest.sh)
set_tests_properties(isa_tools PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT})

# ================================================================== libr4d's kernels, on the host
#
# Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design
# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of sixteen units
# written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins,
# expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile
# forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA
# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings, GLM's MoE decode
# fusions and GLM's DSA scoring split by query rows, whose kernels a card-less build otherwise
# never runs. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread is a fiber, and
# __syncthreads and cross-lane ops are barriers (one not reached uniformly is reported as a
# deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, the host
# arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, for the LoRA pair libref
# itself when the test can load it, for KDA libref itself, and for the DSA split the unsplit
# kernels. The other two, the M2XFP4 decode and tiled GEMMs, are checked against an f64 decode of
# the weight.
#
# Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang
# C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so
# libr4d's HIP build is unaffected). Otherwise a clang++ builds them through custom commands: the
# HIP compiler (ROCm's clang++) when there is one, else RAD_EMU_CLANG, the clang++ on PATH. A
# sanitised build also takes that route, since the emulator's fiber switches would confuse the
# sanitiser. With no clang at all the tests are not registered.
set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d)
set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu)
set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip
                ${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip
                ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
                ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_kda.hip
                ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
                ${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip
                ${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip
                ${R4D_DIR}/r4d_vit_muse.hip ${R4D_DIR}/r4d_posemb.hip ${R4D_DIR}/r4d_ple_conv_bf16.hip
                ${R4D_DIR}/r4d_l2_clip_bf16.hip ${R4D_DIR}/r4d_attn_rel.hip ${R4D_DIR}/r4d_attn_res.hip ${R4D_DIR}/r4d_situ.hip
                ${R4D_DIR}/r4d_inkling.hip ${R4D_DIR}/r4d_ds41_ggml_mr.hip
                ${R4D_DIR}/r4d_ds41_walk.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc kda mla moefuse kvres
                  dsa lili vit sconv l2clip rel attnres inkling ds41mr ds41walk)
set(R4D_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
  # No fiber switch for this ISA.
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT RAD_ASAN AND NOT RAD_TSAN)
  set_source_files_properties(${R4D_EMU_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++")
  add_library(r4d_emu_kernels OBJECT ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp
                                     ${R4D_EMU}/emu/emu.cpp)
  target_include_directories(r4d_emu_kernels PUBLIC ${R4D_EMU}/emu ${R4D_EMU} ${R4D_DIR})
  target_link_libraries(r4d_emu_kernels PUBLIC rad_abi)
  # As in libr4d: the joins must match the unfused chain bit for bit, so no FMA contraction.
  target_compile_options(r4d_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi)
  foreach(t ${R4D_EMU_TESTS})
    add_executable(r4d_emu_${t} ${R4D_EMU}/test_${t}.cpp)
    target_link_libraries(r4d_emu_${t} PRIVATE r4d_emu_kernels ${CMAKE_DL_LIBS})
    target_compile_options(r4d_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi)
    set_target_properties(r4d_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  endforeach()
  set(R4D_EMU_BUILT ON)
else()
  if(RAD_HIP_FOUND AND CMAKE_HIP_COMPILER_ID MATCHES "Clang")
    set(R4D_EMU_CXX ${CMAKE_HIP_COMPILER})
  elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    set(R4D_EMU_CXX ${CMAKE_CXX_COMPILER})
  else()
    find_program(RAD_EMU_CLANG NAMES clang++
                 DOC "clang++ that builds tests/r4d_emu when the C++ compiler is not clang")
    set(R4D_EMU_CXX ${RAD_EMU_CLANG})
  endif()
  if(R4D_EMU_CXX)
    set(dir ${CMAKE_CURRENT_BINARY_DIR}/r4d_emu)
    file(MAKE_DIRECTORY ${dir})
    set(flags -std=c++20 -O2 -ffp-contract=off -Wno-psabi -I${R4D_EMU}/emu -I${R4D_EMU}
              -I${CMAKE_SOURCE_DIR}/abi -I${R4D_DIR})
    set(objs "")
    foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp
                ${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp
                ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
                ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp
                ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_mla.cpp
                ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp
                ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp
                ${R4D_EMU}/test_vit.cpp ${R4D_EMU}/test_sconv.cpp
                ${R4D_EMU}/test_l2clip.cpp ${R4D_EMU}/test_rel.cpp ${R4D_EMU}/test_attnres.cpp
                ${R4D_EMU}/test_inkling.cpp ${R4D_EMU}/test_ds41mr.cpp
                ${R4D_EMU}/test_ds41walk.cpp)
      get_filename_component(stem ${src} NAME_WE)
      set(lang "")
      if(src MATCHES "\\.hip$")
        set(lang -x c++)
      endif()
      add_custom_command(OUTPUT ${dir}/${stem}.o
        COMMAND ${R4D_EMU_CXX} ${flags} -MD -MF ${dir}/${stem}.o.d ${lang} -c ${src}
                -o ${dir}/${stem}.o
        DEPENDS ${src}
        DEPFILE ${dir}/${stem}.o.d
        COMMENT "Building r4d_emu ${stem}.o with ${R4D_EMU_CXX}"
        VERBATIM)
      if(NOT stem MATCHES "^test_")
        list(APPEND objs ${dir}/${stem}.o)
      endif()
    endforeach()
    # test_lora and test_kda open libref with dlopen to hold the emulated kernels to it.
    set(dl "")
    foreach(l ${CMAKE_DL_LIBS})
      list(APPEND dl -l${l})
    endforeach()
    set(exes "")
    foreach(t ${R4D_EMU_TESTS})
      set(exe ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
      add_custom_command(OUTPUT ${exe}
        COMMAND ${R4D_EMU_CXX} ${dir}/test_${t}.o ${objs} ${dl} -o ${exe}
        DEPENDS ${dir}/test_${t}.o ${objs}
        COMMENT "Linking r4d_emu_${t}"
        VERBATIM)
      list(APPEND exes ${exe})
    endforeach()
    add_custom_target(r4d_emu ALL DEPENDS ${exes})
    set(R4D_EMU_BUILT ON)
  endif()
endif()
if(R4D_EMU_BUILT)
  foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili vit sconv l2clip rel attnres inkling ds41mr ds41walk)
    add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
  endforeach()
  # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
  # which three shards put in different entries.
  foreach(k 0 1 2)
    add_test(NAME r4d_emu_attn_shard${k}
             COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3)
  endforeach()
  set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick
                       r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
                       r4d_emu_dsa r4d_emu_lili r4d_emu_sconv r4d_emu_l2clip r4d_emu_rel r4d_emu_attnres
                       r4d_emu_inkling r4d_emu_ds41mr
                       PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
  # The DSpark walk (both kernel forms, 1-4 shards, the key gather's admission): a few minutes on the emulator.
  set_tests_properties(r4d_emu_ds41walk PROPERTIES LABELS "r4d_emu" TIMEOUT 900)
  # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can
  # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within
  # rounding, and that test needs it.
  set_tests_properties(r4d_emu_lora r4d_emu_kda PROPERTIES
                       ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
  # A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at
  # about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it.
  add_test(NAME r4d_emu_attn_sweep COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn sweep 40)
  set_tests_properties(r4d_emu_attn_sweep PROPERTIES LABELS "r4d_emu;slow" TIMEOUT 900)
  # QSA selection at serving sizes, seeded: about 15 s.
  add_test(NAME r4d_emu_qsa_sweep COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_qsa sweep 100)
  set_tests_properties(r4d_emu_qsa_sweep PROPERTIES LABELS "r4d_emu;slow" TIMEOUT 900)
endif()

# ================================================================== libhalo on the emulator
#
# tests/halo_emu runs libhalo units (gfx1151) on the same SIMT emulator through its gfx11 WMMA
# forms: the LDS-tiled prefill GEMMs against the narrow rows whose bytes they promise, and the
# MXFP4 decode's activation plane against its in-kernel decode (test_gemm.cpp says which). The
# units are the plugin's own sources, compiled as C++ the way r4d_emu compiles libr4d's, so a
# card-less build checks them on every run. Same toolchain rules as r4d_emu above.
set(HALO_DIR ${CMAKE_SOURCE_DIR}/libhalo)
set(HALO_EMU ${CMAKE_CURRENT_SOURCE_DIR}/halo_emu)
set(HALO_EMU_HIP ${HALO_DIR}/halo_gemm_fp8a8.hip ${HALO_DIR}/halo_gemm_mxfp4a8_tiled.hip
                 ${HALO_DIR}/halo_gemm_mxfp4a8_nt_m64.hip ${HALO_DIR}/halo_gemm_mxfp4a8_decode.hip
                 ${HALO_DIR}/halo_norm_join_bf16.hip ${HALO_DIR}/halo_expert_scale_bf16.hip
                 ${HALO_DIR}/halo_pair_argmax_f32.hip ${HALO_DIR}/halo_attn_paged_window.hip
                 ${HALO_DIR}/halo_qsa_select_bf16.hip ${HALO_DIR}/halo_lora_bf16.hip
                 ${HALO_DIR}/halo_glm.hip ${HALO_DIR}/halo_mhc.hip
                 ${HALO_DIR}/halo_gemm_fp8_f32scale.hip ${HALO_DIR}/halo_kda.hip
                 ${HALO_DIR}/halo_moe_mxfp4.hip ${HALO_DIR}/halo_mla.hip
                 ${HALO_DIR}/halo_quant_act_fp8.hip ${HALO_DIR}/halo_kv_resolve.hip
                 ${HALO_DIR}/halo_dsa.hip ${HALO_DIR}/halo_gemm_nt_f32.hip
                 ${HALO_DIR}/halo_router_sigmoid_topk_f32.hip ${HALO_DIR}/halo_router_scatter.hip
                 ${HALO_DIR}/halo_gen.hip ${HALO_DIR}/halo_audio.hip ${HALO_DIR}/halo_encoder_bf16.hip
                 ${HALO_DIR}/halo_model_bf16.hip ${HALO_DIR}/halo_hc_bf16.hip
                 ${HALO_DIR}/halo_p2p_copy2d.hip
                 ${HALO_DIR}/halo_attn_paged_gqa8.hip ${HALO_DIR}/halo_attn_paged_h128_gqa1.hip
                 ${HALO_DIR}/halo_attn_paged_h128_gqa2.hip ${HALO_DIR}/halo_attn_paged_h128_gqa2w.hip
                 ${HALO_DIR}/halo_attn_paged_h128_gqa4.hip ${HALO_DIR}/halo_attn_paged_h256_gqa2.hip
                 ${HALO_DIR}/halo_attn_paged_h256_gqa4.hip ${HALO_DIR}/halo_attn_paged_h256_gqa6.hip
                 ${HALO_DIR}/halo_gemm_bf16_nt_tiled.hip ${HALO_DIR}/halo_gemm_bf16_nt_m64.hip)
# gemm: test_gemm.cpp above. norm, escale, pick: r4d_emu's tests of the same three ops, renamed --
# the sandwich-norm joins, expert_scale and pair_argmax have no libref oracle by design (Gemma 4's
# trunk runs the joins every layer), so the unfused chain bit for bit is the only check they get.
# attn: r4d_emu's windowed paged attention test against its port of libref's ref_attn_paged --
# the h128/h256/h512 window rows Gemma 4 runs, prefill and decode, plus a seeded shape sweep.
# The rest are r4d_emu's other tests by the rename transform, over the libhalo ports of the same
# units: QSA selection, the LoRA pair, GLM's F32 routing projection and MoE decode fusions, mHC,
# the F32-scale E4M3 GEMM, KDA, the MXFP4 expert GEMM, MLA, kv_resolve and DSA's split.
# ref: the elementwise and data-movement rows no model fixture reaches and halo_selftest has no
# case for, each held to libref's row on operands drawn from libref's own descriptions.
# paged: every block-size-16 attn_paged decode and prefill row (the decode and prefill bodies through
# the units that own each geometry) against test_attn's reference.
set(HALO_EMU_TESTS gemm norm escale pick attn qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres
                   dsa ref paged)
set(HALO_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
  # No fiber switch for this ISA.
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND NOT RAD_ASAN AND NOT RAD_TSAN)
  set_source_files_properties(${HALO_EMU_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++")
  add_library(halo_emu_kernels OBJECT ${HALO_EMU_HIP} ${HALO_EMU}/cfg_host.cpp ${R4D_EMU}/ref_host.cpp
                                     ${R4D_EMU}/emu/emu.cpp)
  target_include_directories(halo_emu_kernels PUBLIC ${R4D_EMU}/emu ${R4D_EMU} ${HALO_DIR})
  target_link_libraries(halo_emu_kernels PUBLIC rad_abi)
  target_compile_options(halo_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi)
  foreach(t ${HALO_EMU_TESTS})
    add_executable(halo_emu_${t} ${HALO_EMU}/test_${t}.cpp)
    target_link_libraries(halo_emu_${t} PRIVATE halo_emu_kernels ${CMAKE_DL_LIBS})
    target_compile_options(halo_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi)
    set_target_properties(halo_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
  endforeach()
  set(HALO_EMU_BUILT ON)
elseif(R4D_EMU_CXX)
  set(dir ${CMAKE_CURRENT_BINARY_DIR}/halo_emu)
  file(MAKE_DIRECTORY ${dir})
  set(flags -std=c++20 -O2 -ffp-contract=off -Wno-psabi -I${R4D_EMU}/emu -I${R4D_EMU} -I${HALO_DIR}
            -I${CMAKE_SOURCE_DIR}/abi)
  set(objs "")
  set(srcs ${HALO_EMU_HIP} ${HALO_EMU}/cfg_host.cpp ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp)
  foreach(t ${HALO_EMU_TESTS})
    list(APPEND srcs ${HALO_EMU}/test_${t}.cpp)
  endforeach()
  foreach(src ${srcs})
    get_filename_component(stem ${src} NAME_WE)
    set(lang "")
    if(src MATCHES "\\.hip$")
      set(lang -x c++)
    endif()
    add_custom_command(OUTPUT ${dir}/${stem}.o
      COMMAND ${R4D_EMU_CXX} ${flags} -MD -MF ${dir}/${stem}.o.d ${lang} -c ${src}
              -o ${dir}/${stem}.o
      DEPENDS ${src}
      DEPFILE ${dir}/${stem}.o.d
      COMMENT "Building halo_emu ${stem}.o with ${R4D_EMU_CXX}"
      VERBATIM)
    if(NOT stem MATCHES "^test_")
      list(APPEND objs ${dir}/${stem}.o)
    endif()
  endforeach()
  # test_lora, test_kda and test_ref open libref with dlopen.
  set(dl "")
  foreach(l ${CMAKE_DL_LIBS})
    list(APPEND dl -l${l})
  endforeach()
  set(exes "")
  foreach(t ${HALO_EMU_TESTS})
    set(exe ${CMAKE_BINARY_DIR}/tests/halo_emu_${t})
    add_custom_command(OUTPUT ${exe}
      COMMAND ${R4D_EMU_CXX} ${dir}/test_${t}.o ${objs} ${dl} -o ${exe}
      DEPENDS ${dir}/test_${t}.o ${objs}
      COMMENT "Linking halo_emu_${t}"
      VERBATIM)
    list(APPEND exes ${exe})
  endforeach()
  add_custom_target(halo_emu ALL DEPENDS ${exes})
  set(HALO_EMU_BUILT ON)
endif()
if(HALO_EMU_BUILT)
  foreach(t gemm norm escale pick qsa lora f32 mhc fp8f32 kda mla moefuse kvres dsa ref paged)
    add_test(NAME halo_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/halo_emu_${t})
    set_tests_properties(halo_emu_${t} PROPERTIES LABELS "halo_emu;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
  endforeach()
  # As r4d_emu: the LoRA pair and KDA are held to libref itself when the test can load it.
  set_tests_properties(halo_emu_lora halo_emu_kda halo_emu_ref PROPERTIES
                       ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
  # As r4d_emu_attn: three shards of the fixed cases, and the seeded sweep as `slow`.
  foreach(k 0 1 2)
    add_test(NAME halo_emu_attn_shard${k} COMMAND ${CMAKE_BINARY_DIR}/tests/halo_emu_attn --shard ${k}/3)
    set_tests_properties(halo_emu_attn_shard${k} PROPERTIES LABELS "halo_emu;fast"
                         TIMEOUT ${RAD_TEST_TIMEOUT})
  endforeach()
  # libhalo's one MXFP4 expert kernel takes about 250 s here over the cases (libr4d's
  # shape-specialised forms 30 s), so eight shards hold a case or two each.
  foreach(k 0 1 2 3 4 5 6 7)
    add_test(NAME halo_emu_moemx_shard${k} COMMAND ${CMAKE_BINARY_DIR}/tests/halo_emu_moemx --shard ${k}/8)
    set_tests_properties(halo_emu_moemx_shard${k} PROPERTIES LABELS "halo_emu;slow" TIMEOUT 900)
  endforeach()
  add_test(NAME halo_emu_attn_sweep COMMAND ${CMAKE_BINARY_DIR}/tests/halo_emu_attn sweep 40)
  set_tests_properties(halo_emu_attn_sweep PROPERTIES LABELS "halo_emu;slow" TIMEOUT 900)
endif()

# ================================================================== the document as a test
#
# docs/OPS.md is the authoritative op table, so this test checks it against what the plugins dump
# (dropped optional operands, a missing `:inout`, parameters moved into `params`, undeclared
# parameters). Cheap, so in the fast tier. libr4d.so and glm.so are added when built; the script
# reports "  SKIP " rather than passing when a plugin will not dump.
set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so)
if(TARGET spechub)
  list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/spechub.so)
endif()
if(RAD_HIP_FOUND AND TARGET libr4d)
  list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
endif()
if(TARGET glm)
  list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/glm.so)
endif()
add_test(NAME ops_doc
         COMMAND ${CMAKE_SOURCE_DIR}/tools/ops_doc_check.sh
                 ${CMAKE_SOURCE_DIR}/docs/OPS.md $<TARGET_FILE:rad-schemas>
                 ${RAD_OPSDOC_PLUGINS})
set_tests_properties(ops_doc PROPERTIES
  SKIP_RETURN_CODE 77
  TIMEOUT ${RAD_TEST_TIMEOUT}
  ENVIRONMENT "ROCR_VISIBLE_DEVICES=99")

# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge can leave a
# library's "rows not reached" header from one run above a table from another. The counts must
# agree with each other and with the headline; cheap.
if(EXISTS ${CMAKE_SOURCE_DIR}/docs/KERNELS.md)
  add_test(NAME kernel_report_check
           COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/kernel_report_check.sh
                   ${CMAKE_SOURCE_DIR}/docs/KERNELS.md)
  set_tests_properties(kernel_report_check PROPERTIES
    LABELS "fast;unit"
    SKIP_RETURN_CODE 77
    TIMEOUT ${RAD_TEST_TIMEOUT})
endif()

# tools/rad-export. Its standard-library checks always run; the merge arithmetic runs where torch
# and safetensors import, and the PEFT comparison where peft and transformers do too.
find_program(RAD_PYTHON3 NAMES python3)

# core/server/dashboard_page.h is the build of dashboard/, committed because the engine's build has
# no Node. This fails while the page's sources and the header disagree.
if(RAD_PYTHON3 AND EXISTS ${CMAKE_SOURCE_DIR}/dashboard/package.json)
  add_test(NAME dashboard_page
           COMMAND ${RAD_PYTHON3} ${CMAKE_SOURCE_DIR}/tools/dashboard_embed.py check)
  set_tests_properties(dashboard_page PROPERTIES
    LABELS "fast;unit"
    TIMEOUT ${RAD_TEST_TIMEOUT})
endif()
# The header's digest proves sources and its own claim agree, nothing more: it cannot catch a
# tamper of the committed served bytes that rewrites that digest to match. This hashes the
# artifacts themselves from outside, so tampering with one alone fails.
add_test(NAME artifact_sums
         COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/artifact_sums.sh ${CMAKE_SOURCE_DIR})
set_tests_properties(artifact_sums PROPERTIES LABELS "fast;unit" TIMEOUT ${RAD_TEST_TIMEOUT})
# The page rules that were each broken in production and are not visible to any C++ test: a tile
# figure that goes stale, a drift clause that fires on a prefill sample, a tile that clips its own
# figures. Cheap, and it needs neither Node nor a browser.
add_test(NAME page_rules
         COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/page_rules.sh ${CMAKE_SOURCE_DIR})
set_tests_properties(page_rules PROPERTIES LABELS "fast;unit" TIMEOUT ${RAD_TEST_TIMEOUT})
if(RAD_PYTHON3)
  add_test(NAME vhead_test COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/vhead_test.py)
  set_tests_properties(vhead_test PROPERTIES LABELS "unit;fast" SKIP_RETURN_CODE 77 TIMEOUT ${RAD_TEST_TIMEOUT})
  add_test(NAME rad_export_test COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/rad_export_test.py)
  set_tests_properties(rad_export_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
  add_test(NAME spark25_validation_test
           COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/spark25_validation_test.py)
  set_tests_properties(spark25_validation_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
  add_test(NAME dspark_qos_regression_test
           COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/dspark_qos_regression_test.py)
  set_tests_properties(dspark_qos_regression_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
endif()

# ================================================================== the shipped plugins, out of tree
#
# Installs the build into a prefix, then configures, builds and installs every plugin directory
# standalone against it with find_package(radiance). The result must match the tree's plugins,
# vocabulary and registration, and serve rad-kbench's fixture through the installed tools
# (tests/oot_plugins.sh). The device libraries (libr4d, and plugin/exl3i on a gfx1201 build) are
# included when the tree built them, with the same HIP compiler, targets, build type and
# RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and
# takes minutes.
#
# An installed radiance finds ROCm through ROCM_PATH and HIP_PATH (radiance-config.cmake), so the
# test gets the root of the HIP runtime this tree links, and that root's tools first on PATH: the
# out-of-tree build then uses the tree's ROCm whatever the shell that runs ctest exports. Left to
# the caller's environment, a shell without them failed to find hip_runtime.h, and one naming
# another ROCm build linked the out-of-tree libr4d against that one's runtime.
set(RAD_OOT_COMPILER "")
set(RAD_OOT_TARGETS "")
set(RAD_OOT_ENV "")
if(RAD_HIP_FOUND AND RAD_HIP_RUNTIME)
  get_filename_component(RAD_OOT_ROCM "${RAD_HIP_RUNTIME}" DIRECTORY)
  get_filename_component(RAD_OOT_ROCM "${RAD_OOT_ROCM}" DIRECTORY)
  set(RAD_OOT_ENV "ROCM_PATH=${RAD_OOT_ROCM}" "HIP_PATH=${RAD_OOT_ROCM}"
                  "PATH=${RAD_OOT_ROCM}/bin:${RAD_OOT_ROCM}/lib/llvm/bin:$ENV{PATH}")
endif()
if(RAD_HIP_FOUND AND TARGET libr4d)
  get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES)
  string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}")
  set(RAD_OOT_COMPILER "${CMAKE_HIP_COMPILER}")
  set(RAD_OOT_TARGETS "${RAD_OOT_R4D_ARCH}")
endif()
add_test(NAME oot_plugins
         COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
                 ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot "${RAD_OOT_COMPILER}" "${RAD_OOT_TARGETS}"
                 "${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}" "${CMAKE_BUILD_TYPE}")
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
set_tests_properties(oot_plugins PROPERTIES
  LABELS "oot"
  TIMEOUT 3600
  RESOURCE_LOCK kbench_memory
  ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV};${RAD_OOT_ENV}")

# ================================================================== the kernel library, as a test
#
# rad-kbench replays data/kernels.rkb: every kernel of every loaded library against libref's
# recorded answers on seeded inputs, in guarded allocations. No model, oracle or network needed.
#
# kbench and kbench_moe check every library except the reference (--no-ref): its answers are what
# the fixture holds. --strict fails a stale fixture, and --coverage fails when a row a fixture
# reached (data/kbench_rows/) is no longer reached. Labelled `kbench`, which keeps them out of the
# fast tier (a replay takes seconds to minutes), and `gpu` only when libr4d is built, so
# `ctest -LE gpu` still runs them. `--max-cases 1` collapses a second seed of the same case; the
# depth sweep's cases differ in their operand shapes and all run. OpenMP waits passively: the host
# libraries' teams would otherwise spin between launches and starve what ctest -j runs beside them.
set(RAD_KBENCH_LABELS "kbench")
if(RAD_HIP_FOUND AND TARGET libr4d)
  set(RAD_KBENCH_LABELS "kbench;gpu")
endif()
set(RAD_KBENCH_ROWS ${CMAKE_SOURCE_DIR}/data/kbench_rows)
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels.rkb)
  add_test(NAME kbench
           COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --max-cases 1 --no-ref --strict
                   --coverage ${RAD_KBENCH_ROWS})
  # RESOURCE_LOCK: each replay budgets a fraction of the memory available when it starts, so two
  # at once would together exceed it. They would also share the last-level cache and skew --bench.
  set_tests_properties(kbench PROPERTIES
    LABELS "${RAD_KBENCH_LABELS}"
    TIMEOUT 1800
    RESOURCE_LOCK kbench_memory
    PROCESSORS 4
    ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()

# The same replay over the routed fixture, which covers the MoE ops, the gqa 8 attention dispatch
# and the MTP head (see the root CMakeLists). Separate tests, because a fixture records the one
# container it came from.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_moe.rkb)
  add_test(NAME kbench_moe
           COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --max-cases 1 --no-ref --strict
                   --coverage ${RAD_KBENCH_ROWS}
                   --fixture ${RAD_PLUGIN_OUT}/kernels_moe.rkb)
  set_tests_properties(kbench_moe PROPERTIES
    LABELS "${RAD_KBENCH_LABELS}"
    TIMEOUT 1800
    RESOURCE_LOCK kbench_memory
    PROCESSORS 4
    ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()

# libref against its own recordings, both fixtures, at tolerance zero: it is deterministic and
# machine-independent by construction, so any difference is a change in libref (or in the draw)
# that would otherwise become the next recording's target. This is the oracle's regression test.
# Its answers are cached under $RADIANCE_HOME/cache/kbench, keyed by libref's build-id and
# everything it links, the input bytes and the case, so an unchanged libref replays in seconds and
# a rebuilt one in full; the comparison runs either way. Labelled `slow` for the full run.
if(TARGET rad-kbench AND TARGET libref AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels.rkb AND
   EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_moe.rkb)
  add_test(NAME kbench_ref
           COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --kernels libref --max-cases 1 --strict
                   --coverage ${RAD_KBENCH_ROWS}
                   --fixture ${RAD_PLUGIN_OUT}/kernels.rkb
                   --fixture ${RAD_PLUGIN_OUT}/kernels_moe.rkb)
  set_tests_properties(kbench_ref PROPERTIES
    LABELS "kbench;slow"
    TIMEOUT 3600
    RESOURCE_LOCK kbench_memory
    PROCESSORS 4
    ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};OMP_WAIT_POLICY=passive")
endif()

# ================================================================== tiers
#
# `fast` goes on every test registered above that carries none of slow, gpu, oot, perf, e2e and
# kbench, so the inner loop's membership is decided here alone. Every `gpu` test takes the card lock: two tests
# that each commit device memory, or each time kernels, must not share a card. COST starts the
# longest tests first in a parallel run, so they are not left on the critical path.
get_property(RAD_ALL_TESTS DIRECTORY PROPERTY TESTS)
foreach(t ${RAD_ALL_TESTS})
  get_test_property(${t} LABELS labels)
  if(NOT labels)
    set(labels "")
  endif()
  if(NOT labels MATCHES "(^|;)(slow|gpu|oot|perf|e2e|kbench)(;|$)")
    set_property(TEST ${t} APPEND PROPERTY LABELS fast)
  endif()
  if(labels MATCHES "(^|;)gpu(;|$)")
    set_property(TEST ${t} APPEND PROPERTY RESOURCE_LOCK card)
  endif()
endforeach()
foreach(cost IN ITEMS kbench_ref:500 r4d_selftest:350 r4d_emu_attn_sweep:80 kbench:20
                      kbench_moe:15 engine_e2e_test:12 r4d_emu_attn_shard0:5 r4d_emu_attn_shard2:5)
  string(REPLACE ":" ";" cost ${cost})
  list(GET cost 0 t)
  list(GET cost 1 c)
  if(TEST ${t})
    set_tests_properties(${t} PROPERTIES COST ${c})
  endif()
endforeach()

# Model-local device kernels are checked on the actual engine queue against libref.
if(TARGET nemotron35_device_test)
  set_target_properties(nemotron35_device_test PROPERTIES ENABLE_EXPORTS ON)
  add_dependencies(nemotron35_device_test libref)
  if(TARGET libr4d)
    add_dependencies(nemotron35_device_test libr4d)
    add_test(NAME nemotron35_device_test_card COMMAND nemotron35_device_test)
    set_tests_properties(nemotron35_device_test_card PROPERTIES LABELS "gpu" RUN_SERIAL TRUE
      ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};RAD_TEST_CPU_BUDGET=0" TIMEOUT 180)
  endif()
endif()

# The ggml rows' decode band over IQ2_XXS and Q8_0 (r4d_ggml_wmma.hip): random llama.cpp blocks held to
# a double dequant reference, a row's bits at every M, and the moe rows equal to the gemm's.
if(TARGET r4d_ggml_wmma_device_test)
  set_target_properties(r4d_ggml_wmma_device_test PROPERTIES ENABLE_EXPORTS ON)
  if(TARGET libr4d)
    add_dependencies(r4d_ggml_wmma_device_test libr4d)
    add_test(NAME r4d_ggml_wmma_device_test_card COMMAND r4d_ggml_wmma_device_test)
    set_tests_properties(r4d_ggml_wmma_device_test_card PROPERTIES LABELS "gpu" RUN_SERIAL TRUE
      ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};RAD_TEST_CPU_BUDGET=0" TIMEOUT 600)
  endif()
endif()

# Large BF16 GEMMs require real device memory; ordinary host entries skip them.
if(TARGET r4d_bf16_capacity_test)
  set_target_properties(r4d_bf16_capacity_test PROPERTIES ENABLE_EXPORTS ON)
  if(TARGET libr4d)
    add_dependencies(r4d_bf16_capacity_test libr4d)
    add_test(NAME r4d_bf16_capacity_test_card COMMAND r4d_bf16_capacity_test)
    set_tests_properties(r4d_bf16_capacity_test_card PROPERTIES LABELS "gpu" RUN_SERIAL TRUE
      ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT};RAD_TEST_CPU_BUDGET=0" TIMEOUT 300)
  endif()
endif()

# The vendor record, verified: every file under vendor/ -- the lifts, the patch series, the record
# itself -- hashed against vendor/SHA256SUMS. A changed file the record does not carry, or one that
# arrived unrecorded, is an unrecorded change to a lifted dependency, which is the thing UPSTREAM
# exists to prevent and nothing else notices. It reads the source tree only: no build inputs, no
# machine state, so it runs wherever the suite runs.
add_test(NAME vendor_sums
         COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/vendor_sums.sh ${CMAKE_SOURCE_DIR})
set_tests_properties(vendor_sums PROPERTIES LABELS "fast;unit" TIMEOUT ${RAD_TEST_TIMEOUT})
