Archived
Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port
102 upstream commits. Nine conflicts resolved. Fork side of the merge: - libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it from libavx and libref; the device libraries now each carry it). - plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table regenerated, kTableAbi = 42. Known before the PR: arch_test (MTP lint and pinned graph hashes for qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4b70a96378
850 files changed
+157819
-58519
No files matched your search
@@ -0,0 +1 @@
|
||||
599548556d97ca6ce7b8bc295853f76b4d7408cb2d44105920021176cc027aab core/server/dashboard_page.h
|
||||
+111
-31
@@ -10,12 +10,12 @@
|
||||
# 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`)
|
||||
#
|
||||
# arch_test, glm5next_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply
|
||||
# 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 arch_test glm5next_test nemotron35_test spark25_arch_test nemotronh_test)
|
||||
set(RAD_TESTS_NO_CORE arch_test bailing_hybrid_arch_test breeze_arch_test flint_arch_test glm5next_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
|
||||
@@ -47,12 +47,20 @@ set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test)
|
||||
# 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.
|
||||
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test)
|
||||
# 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)
|
||||
# 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; nlohmann comes straight from vendor/, which core reaches the same way.
|
||||
# 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
|
||||
@@ -81,6 +89,7 @@ set_target_properties(harness_fixture PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAK
|
||||
# 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 8) # chi-square statistics: eight ctest entries of under a minute each
|
||||
|
||||
# ------------------------------------------------------------------ the environment of every test
|
||||
#
|
||||
@@ -129,10 +138,14 @@ set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} ${RAD_TEST_HIDE_ENV})
|
||||
|
||||
# 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_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.
|
||||
@@ -175,6 +188,7 @@ foreach(t ${RAD_TESTS})
|
||||
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
|
||||
@@ -186,7 +200,9 @@ foreach(t ${RAD_TESTS})
|
||||
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})
|
||||
target_link_libraries(${n} PRIVATE rad_vendor_llama)
|
||||
# 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)
|
||||
@@ -214,7 +230,8 @@ foreach(t ${RAD_TESTS})
|
||||
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_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)
|
||||
@@ -224,14 +241,19 @@ foreach(t ${RAD_TESTS})
|
||||
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
|
||||
@@ -332,6 +354,14 @@ if(RAD_SYCL_FOUND)
|
||||
endforeach()
|
||||
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)
|
||||
add_dependencies(plugin_test libr4d)
|
||||
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.
|
||||
@@ -343,6 +373,12 @@ if(TARGET spechub)
|
||||
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)
|
||||
@@ -359,7 +395,7 @@ endif()
|
||||
# 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 libref libquant nemotron35_embed qwen35_bf16 lfm2_bf16 gemma4 gemma4_bf16
|
||||
set(RAD_E2E_DEPS radiance rad-convert libref libquant nemotron35_embed qwen35_bf16 lfm2_bf16 lfm3_bf16 gemma4 gemma4_bf16
|
||||
llama_dense_fp8 llama_fp8 qwenimage21)
|
||||
if(TARGET libavx)
|
||||
list(APPEND RAD_E2E_DEPS libavx)
|
||||
@@ -409,7 +445,7 @@ 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 glm5next_test nemotronh_test)
|
||||
foreach(t arch_test breeze_arch_test glm5next_test nemotronh_test)
|
||||
if(TARGET libref AND TARGET ${t})
|
||||
add_dependencies(${t} libref)
|
||||
endif()
|
||||
@@ -448,6 +484,20 @@ if(RAD_HIP_FOUND AND TARGET r4d_selftest)
|
||||
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
|
||||
@@ -556,21 +606,19 @@ 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_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
|
||||
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.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_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip
|
||||
${R4D_DIR}/r4d_lili.hip)
|
||||
# The M2XFP4 units' plugin entries call two cfg readers that r4d_rows.cpp defines, which is not in
|
||||
# this build: cfg_stub.cpp defines them at their axis defaults, in both arms below.
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres
|
||||
dsa m2xfp4 lili)
|
||||
${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip
|
||||
${R4D_DIR}/r4d_vit_muse.hip)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc kda mla moefuse kvres
|
||||
dsa lili vit)
|
||||
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}/cfg_stub.cpp
|
||||
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)
|
||||
@@ -602,11 +650,11 @@ else()
|
||||
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_fp8f32.cpp
|
||||
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.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_m2xfp4.cpp ${R4D_EMU}/test_lili.cpp
|
||||
${R4D_EMU}/cfg_stub.cpp)
|
||||
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp
|
||||
${R4D_EMU}/test_vit.cpp)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -643,7 +691,7 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
if(R4D_EMU_BUILT)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa m2xfp4 lili)
|
||||
foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili vit)
|
||||
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,
|
||||
@@ -654,7 +702,7 @@ if(R4D_EMU_BUILT)
|
||||
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_m2xfp4 r4d_emu_lili
|
||||
r4d_emu_dsa r4d_emu_lili
|
||||
PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
|
||||
# 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
|
||||
@@ -788,9 +836,12 @@ if(HALO_EMU_BUILT)
|
||||
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 160 s here (libr4d's shape-specialised forms 30 s).
|
||||
add_test(NAME halo_emu_moemx COMMAND ${CMAKE_BINARY_DIR}/tests/halo_emu_moemx)
|
||||
set_tests_properties(halo_emu_moemx PROPERTIES LABELS "halo_emu;slow" TIMEOUT 900)
|
||||
# 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()
|
||||
@@ -833,6 +884,22 @@ 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})
|
||||
if(RAD_PYTHON3)
|
||||
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})
|
||||
@@ -850,9 +917,23 @@ endif()
|
||||
# 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). libr4d is included when the tree built it, with the same HIP compiler,
|
||||
# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes.
|
||||
# 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}")
|
||||
@@ -862,10 +943,9 @@ 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}")
|
||||
"${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.
|
||||
# A SYCL build passes its icpx so libxe2 is rebuilt out of tree too.
|
||||
set(RAD_OOT_ENV "CMAKE_GENERATOR=${CMAKE_GENERATOR}" ${RAD_TEST_OMP_ENV})
|
||||
if(RAD_SYCL_FOUND)
|
||||
list(APPEND RAD_OOT_ENV "RAD_OOT_ICPX=${RAD_ICPX}")
|
||||
endif()
|
||||
@@ -873,7 +953,7 @@ set_tests_properties(oot_plugins PROPERTIES
|
||||
LABELS "oot"
|
||||
TIMEOUT 3600
|
||||
RESOURCE_LOCK kbench_memory
|
||||
ENVIRONMENT "${RAD_OOT_ENV}")
|
||||
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV};${RAD_OOT_ENV}")
|
||||
|
||||
# ================================================================== the kernel library, as a test
|
||||
#
|
||||
@@ -1027,4 +1107,4 @@ endif()
|
||||
# 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 120)
|
||||
set_tests_properties(vendor_sums PROPERTIES LABELS "fast;unit" TIMEOUT ${RAD_TEST_TIMEOUT})
|
||||
+39
-24
@@ -1,4 +1,4 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 37 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 42 and
|
||||
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
|
||||
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
|
||||
* from the test's printout only together with a version bump. */
|
||||
@@ -13,7 +13,7 @@
|
||||
{ "RadArchProbe", "gen_audio", 48, 4 },
|
||||
{ "RadArchProbe", "gen_ctx", 56, 8 },
|
||||
{ "RadArchProbe", "gen_video", 64, 4 },
|
||||
{ "RadArchProbe", "kv_quant_ok", 68, 4 },
|
||||
{ "RadArchProbe", "kv_fp8_ok", 68, 4 },
|
||||
{ "RadArchProbe", "chain_pays", 72, 4 },
|
||||
{ "RadArchProbe", "kv_stream_ok", 76, 4 },
|
||||
{ "RadArchProbe", "control_vector_ok", 80, 4 },
|
||||
@@ -126,24 +126,24 @@
|
||||
{ "RadBuildCtx", "max_out_rows", 80, 8 },
|
||||
{ "RadBuildCtx", "max_audio_frames", 88, 8 },
|
||||
{ "RadBuildCtx", "max_mixed_tok", 96, 8 },
|
||||
{ "RadBuildCtx", "kv_quant", 104, 4 },
|
||||
{ "RadBuildCtx", "attn_prefill_fp8", 108, 4 },
|
||||
{ "RadBuildCtx", "kv_resident_blocks", 112, 8 },
|
||||
{ "RadBuildCtx", "kv_stream_ok", 120, 4 },
|
||||
{ "RadBuildCtx", "cvec", 128, 8 },
|
||||
{ "RadBuildCtx", "tp_attn_rows", 136, 4 },
|
||||
{ "RadBuildCtx", "state_dtype", 140, 4 },
|
||||
{ "RadBuildCtx", "draft_coupling", 144, 4 },
|
||||
{ "RadBuildCtx", "weight_prefetch_off", 148, 4 },
|
||||
{ "RadBuildCtx", "draft_tree", 152, 8 },
|
||||
{ "RadBuildCtx", "calib_dir", 160, 8 },
|
||||
{ "RadBuildCtx", "calib_layer_lo", 168, 4 },
|
||||
{ "RadBuildCtx", "calib_layer_hi", 172, 4 },
|
||||
{ "RadBuildCtx", "calib_tokens", 176, 8 },
|
||||
{ "RadBuildCtx", "gen_max_pixels", 184, 8 },
|
||||
{ "RadBuildCtx", "gen_max_refs", 192, 8 },
|
||||
{ "RadBuildCtx", "expert_file_tier", 200, 4 },
|
||||
{ "RadAudioGenBatch", "", 0, 344 },
|
||||
{ "RadBuildCtx", "kv_resident_blocks", 104, 8 },
|
||||
{ "RadBuildCtx", "kv_stream_ok", 112, 4 },
|
||||
{ "RadBuildCtx", "cvec", 120, 8 },
|
||||
{ "RadBuildCtx", "tp_attn_rows", 128, 4 },
|
||||
{ "RadBuildCtx", "state_dtype", 132, 4 },
|
||||
{ "RadBuildCtx", "draft_coupling", 136, 4 },
|
||||
{ "RadBuildCtx", "weight_prefetch_off", 140, 4 },
|
||||
{ "RadBuildCtx", "draft_tree", 144, 8 },
|
||||
{ "RadBuildCtx", "calib_dir", 152, 8 },
|
||||
{ "RadBuildCtx", "calib_layer_lo", 160, 4 },
|
||||
{ "RadBuildCtx", "calib_layer_hi", 164, 4 },
|
||||
{ "RadBuildCtx", "calib_tokens", 168, 8 },
|
||||
{ "RadBuildCtx", "gen_max_pixels", 176, 8 },
|
||||
{ "RadBuildCtx", "gen_max_refs", 184, 8 },
|
||||
{ "RadBuildCtx", "expert_file_tier", 192, 4 },
|
||||
{ "RadBuildCtx", "slot_base", 196, 4 },
|
||||
{ "RadBuildCtx", "plain_norm", 200, 4 },
|
||||
{ "RadAudioGenBatch", "", 0, 352 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
{ "RadAudioGenBatch", "lane_h", 16, 8 },
|
||||
@@ -189,7 +189,8 @@
|
||||
{ "RadAudioGenBatch", "ref_cu_h", 320, 8 },
|
||||
{ "RadAudioGenBatch", "ref_frame", 328, 8 },
|
||||
{ "RadAudioGenBatch", "ref_frame_h", 336, 8 },
|
||||
{ "RadAudioGenDecl", "", 0, 280 },
|
||||
{ "RadAudioGenBatch", "prompt_cu_h", 344, 8 },
|
||||
{ "RadAudioGenDecl", "", 0, 296 },
|
||||
{ "RadAudioGenDecl", "name", 0, 8 },
|
||||
{ "RadAudioGenDecl", "tmpl", 8, 8 },
|
||||
{ "RadAudioGenDecl", "neg_token", 16, 4 },
|
||||
@@ -229,6 +230,8 @@
|
||||
{ "RadAudioGenDecl", "ref_hop", 256, 8 },
|
||||
{ "RadAudioGenDecl", "ref_max_samples", 264, 8 },
|
||||
{ "RadAudioGenDecl", "ref_max", 272, 4 },
|
||||
{ "RadAudioGenDecl", "tmpl_ref_instruct", 280, 8 },
|
||||
{ "RadAudioGenDecl", "neg_tmpl_ref", 288, 8 },
|
||||
{ "RadControlVector", "", 0, 32 },
|
||||
{ "RadControlVector", "dir", 0, 8 },
|
||||
{ "RadControlVector", "scales", 8, 8 },
|
||||
@@ -244,7 +247,7 @@
|
||||
{ "RadAudioFormat", "language_lead", 48, 8 },
|
||||
{ "RadAudioFormat", "languages", 56, 8 },
|
||||
{ "RadAudioFormat", "n_languages", 64, 4 },
|
||||
{ "RadChatFormat", "", 0, 208 },
|
||||
{ "RadChatFormat", "", 0, 216 },
|
||||
{ "RadChatFormat", "struct_size", 0, 4 },
|
||||
{ "RadChatFormat", "name", 8, 8 },
|
||||
{ "RadChatFormat", "reasoning_open", 16, 8 },
|
||||
@@ -275,6 +278,7 @@
|
||||
{ "RadChatFormat", "object_bare_keys", 192, 4 },
|
||||
{ "RadChatFormat", "reasoning_anywhere", 196, 4 },
|
||||
{ "RadChatFormat", "arg_json_value_prefix", 200, 8 },
|
||||
{ "RadChatFormat", "content_open", 208, 8 },
|
||||
{ "RadConstraint", "", 0, 32 },
|
||||
{ "RadConstraint", "key", 0, 8 },
|
||||
{ "RadConstraint", "op", 8, 4 },
|
||||
@@ -311,7 +315,7 @@
|
||||
{ "RadEncPlane", "kind", 28, 4 },
|
||||
{ "RadEncPlane", "block", 32, 16 },
|
||||
{ "RadEncPlane", "extent", 48, 16 },
|
||||
{ "RadEncoderDecl", "", 0, 56 },
|
||||
{ "RadEncoderDecl", "", 0, 64 },
|
||||
{ "RadEncoderDecl", "name", 0, 8 },
|
||||
{ "RadEncoderDecl", "modalities", 8, 4 },
|
||||
{ "RadEncoderDecl", "patch_dim", 16, 8 },
|
||||
@@ -320,6 +324,7 @@
|
||||
{ "RadEncoderDecl", "n_embd", 40, 8 },
|
||||
{ "RadEncoderDecl", "out", 48, 4 },
|
||||
{ "RadEncoderDecl", "one_grid", 52, 4 },
|
||||
{ "RadEncoderDecl", "bidirectional", 56, 4 },
|
||||
{ "RadEncoding", "", 0, 568 },
|
||||
{ "RadEncoding", "scheme", 0, 24 },
|
||||
{ "RadEncoding", "transform", 24, 24 },
|
||||
@@ -748,6 +753,12 @@
|
||||
{ "RadShapeGenDecl", "max_lanes", 176, 8 },
|
||||
{ "RadShapeGenDecl", "max_query", 184, 8 },
|
||||
{ "RadShapeGenDecl", "field_out", 192, 4 },
|
||||
{ "RadSyclStream", "", 0, 24 },
|
||||
{ "RadSyclStream", "magic", 0, 4 },
|
||||
{ "RadSyclStream", "version", 4, 4 },
|
||||
{ "RadSyclStream", "queue", 8, 8 },
|
||||
{ "RadSyclStream", "device", 16, 4 },
|
||||
{ "RadSyclStream", "reserved", 20, 4 },
|
||||
{ "RadTensor", "", 0, 112 },
|
||||
{ "RadTensor", "data", 0, 8 },
|
||||
{ "RadTensor", "dtype", 8, 4 },
|
||||
@@ -932,7 +943,7 @@
|
||||
{ "RadMtpCoupleDraw", "seq", 16, 8 },
|
||||
{ "RadMtpCoupleDraw", "card", 24, 4 },
|
||||
{ "RadMtpCoupleDraw", "mode", 28, 4 },
|
||||
{ "RadMtpCoupleState", "", 0, 152 },
|
||||
{ "RadMtpCoupleState", "", 0, 168 },
|
||||
{ "RadMtpCoupleState", "draw", 0, 32 },
|
||||
{ "RadMtpCoupleState", "pos", 32, 8 },
|
||||
{ "RadMtpCoupleState", "status", 40, 4 },
|
||||
@@ -941,3 +952,7 @@
|
||||
{ "RadMtpCoupleState", "count", 52, 4 },
|
||||
{ "RadMtpCoupleState", "ids", 56, 32 },
|
||||
{ "RadMtpCoupleState", "q", 88, 64 },
|
||||
{ "RadMtpCoupleState", "nkids", 152, 4 },
|
||||
{ "RadMtpCoupleState", "scheme", 156, 4 },
|
||||
{ "RadMtpCoupleState", "blk", 160, 4 },
|
||||
{ "RadMtpCoupleState", "pad_", 164, 4 },
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
|
||||
* struct's listed fields account for its size, so the list in rad_abi_layout_rows.h is complete; and
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 37 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 38 and RAD_FORMAT_VER 2. Under
|
||||
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
|
||||
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
|
||||
* headers: nothing else states the layout. When it disagrees the test prints the live table.
|
||||
@@ -59,8 +59,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 37 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 37, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 41 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 42, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -301,6 +301,58 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
|
||||
CHECK(cut_cases > 100);
|
||||
}
|
||||
|
||||
/* ================================================================== ADV_COMPACT */
|
||||
|
||||
/* An accepted path's rows move to their committed positions whole, in every layer and head, and
|
||||
* nothing else in the cache changes: at 512 bytes a row (bf16 and fp8 at head_dim 256 and 128)
|
||||
* and at 516 and 260 (the int8 cache's K, V and two f16 scales, which is never whole 16-byte
|
||||
* chunks). Run as the host backend does (one caller, every chunk) and as the kernel's 64 threads
|
||||
* split a row; the path crosses a block boundary. A row that sampled nothing keeps its cache. */
|
||||
TEST(a_trees_accepted_rows_move_whole_at_every_row_size) {
|
||||
for (int row_bytes : { 512, 516, 260, 1028 }) {
|
||||
for (int cstep : { 1, 64 }) {
|
||||
Slab s(ADV_ACCEPT);
|
||||
const int layers = 2, heads = 3, bs = 16, blocks = Slab::kPitch;
|
||||
const int64_t stride = (int64_t)blocks * heads * bs * row_bytes + 64;
|
||||
std::vector<uint32_t> cache((size_t)(layers * stride / 4));
|
||||
uint32_t rng = 0xc0a9ac7u + (uint32_t)row_bytes;
|
||||
for (uint32_t& v : cache) v = lcg(rng);
|
||||
std::vector<uint32_t> want = cache;
|
||||
|
||||
s.row(0, true, 0, 8, 0, /*card=*/3, 0, /*rout=*/0, 7);
|
||||
s.row(1, true, 8, 8, 0, /*card=*/5, 8, /*rout=*/-1, 7);
|
||||
const int32_t path[3] = { 2, 5, 7 }, base = 28;
|
||||
for (int card : { 3, 5 }) {
|
||||
StepSlot& S = s.st[card];
|
||||
S.acc = 3; S.npath = 3; S.head = base + 3;
|
||||
std::memcpy(S.path, path, sizeof path);
|
||||
}
|
||||
s.a.n_pool = 1;
|
||||
s.a.pool[0] = { reinterpret_cast<char*>(cache.data()), stride, layers, heads,
|
||||
row_bytes, 0 };
|
||||
|
||||
auto at = [&](std::vector<uint32_t>& c, int l, int h, int pos) {
|
||||
return reinterpret_cast<char*>(c.data()) + l * stride +
|
||||
(((int64_t)(pos / bs) * heads + h) * bs + pos % bs) * row_bytes;
|
||||
};
|
||||
for (int l = 0; l < layers; ++l)
|
||||
for (int h = 0; h < heads; ++h)
|
||||
for (int t = 0; t < 3; ++t)
|
||||
std::memcpy(at(want, l, h, base + t + 1), at(want, l, h, base + path[t]),
|
||||
(size_t)row_bytes);
|
||||
|
||||
CHECK_EQ(adv_compact_items(s.a), layers * heads);
|
||||
for (int i = 0; i < s.a.n_seq; ++i)
|
||||
for (int w = 0; w < adv_compact_items(s.a); ++w) {
|
||||
int p = 0, l = 0, h = 0;
|
||||
CHECK(adv_compact_item(s.a, w, &p, &l, &h));
|
||||
for (int c0 = 0; c0 < cstep; ++c0) adv_compact(s.a, i, p, l, h, c0, cstep);
|
||||
}
|
||||
CHECK(cache == want);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== ADV_TRUNK */
|
||||
|
||||
/* A verify step issued ahead takes its rows from the StepSlots: the bonus token and the head's
|
||||
@@ -356,6 +408,49 @@ TEST(a_step_issued_ahead_takes_every_rows_tokens_positions_and_slots_from_its_st
|
||||
for (int t = 0; t < 9; ++t) CHECK_EQ(s.slot(1, t), 0);
|
||||
}
|
||||
|
||||
/* --draft-depth adaptive (core/sched/draft_depth.h): the head ran for the deepest row of its step,
|
||||
* so a slot holds every round's proposal, but the step issued ahead verifies only the chain each row
|
||||
* really made -- its first d proposals, in 1 + d rows. The trunk advance takes exactly those (the
|
||||
* rows' count is the batch's, never the slot's) and the acceptance behind that verify can accept no
|
||||
* more than d, whatever the slot still holds past them. Two rows of one step differ in depth. */
|
||||
TEST(a_verify_of_a_chain_cut_short_takes_and_accepts_only_its_own_first_drafts) {
|
||||
Slab s(ADV_TRUNK);
|
||||
/* card 1 drafted five rounds and verifies two of them; card 3 verifies four */
|
||||
s.row(0, true, 0, 3, /*ctx bound=*/40, /*card=*/1, 0, 0, 2);
|
||||
s.row(1, true, 3, 5, 90, 3, 3, 3, 4);
|
||||
for (int j = 0; j <= 5; ++j) { s.st[1].tok[j] = 700 + j; s.st[3].tok[j] = 800 + j; }
|
||||
s.st[1].ctx = 20; s.st[1].n_acc = 3;
|
||||
s.st[3].ctx = 60; s.st[3].n_acc = 1;
|
||||
for (int t = 0; t < 8; ++t) s.w[Slab::TOK + t] = -5;
|
||||
s.w[Slab::TOK + 8] = -5;
|
||||
s.run();
|
||||
const int32_t tok[8] = { 700, 701, 702, 800, 801, 802, 803, 804 };
|
||||
const int32_t pos[8] = { 20, 21, 22, 60, 61, 62, 63, 64 };
|
||||
for (int t = 0; t < 8; ++t) {
|
||||
CHECK_EQ(s.w[Slab::TOK + t], tok[t]);
|
||||
CHECK_EQ(s.w[Slab::POS + t], pos[t]);
|
||||
CHECK_EQ(s.slot(0, t), pos[t]);
|
||||
}
|
||||
CHECK_EQ(s.w[Slab::TOK + 8], -5); /* nothing past the rows the step has */
|
||||
CHECK_EQ(s.used(0, 0), 23);
|
||||
CHECK_EQ(s.used(0, 1), 65);
|
||||
CHECK_EQ(s.w[Slab::ACC + 0], 3);
|
||||
CHECK_EQ(s.w[Slab::ACC + 1], 1);
|
||||
|
||||
/* The acceptance behind that verify: the target agrees with every proposal the slot holds, and
|
||||
* the row still accepts its own d only (the row descriptor's draft count), then emits the
|
||||
* target's token at the row after them. */
|
||||
Slab v(ADV_ACCEPT);
|
||||
v.row(0, true, 0, 3, 20, 1, 0, 0, 2);
|
||||
v.row(1, true, 3, 5, 60, 3, 3, 3, 4);
|
||||
for (int t = 0; t < 8; ++t) v.w[Slab::TOK + t] = tok[t];
|
||||
const int32_t y[8] = { 701, 702, 703, 801, 802, 803, 804, 805 };
|
||||
for (int t = 0; t < 8; ++t) v.src[t] = y[t];
|
||||
v.run();
|
||||
CHECK_EQ(v.st[1].acc, 2); CHECK_EQ(v.st[1].tok[0], 703); CHECK_EQ(v.st[1].ctx, 23);
|
||||
CHECK_EQ(v.st[3].acc, 4); CHECK_EQ(v.st[3].tok[0], 805); CHECK_EQ(v.st[3].ctx, 65);
|
||||
}
|
||||
|
||||
/* A row the card moves keeps the host's offset between its position and its rotary position on
|
||||
* all three planes (a text row after an image rotates at its index plus a shift); a row whose
|
||||
* position does not move keeps the host's three components, which differ for a media token. A
|
||||
@@ -684,4 +779,66 @@ TEST(a_block_drafter_step_on_the_card_continues_where_the_verify_left_off) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== a suffix step (--draft-suffix) */
|
||||
|
||||
/* A suffix step is a host-built verify of up to 8 proposals behind the bonus token while the head
|
||||
* drafts 3 rounds. The card's side of it: the acceptance walks all 8 drafts (a prefix of them, up to
|
||||
* the end-of-generation cut), the head's history pass covers all 9 positions with round 1 on the
|
||||
* last committed one and the rejected rows repeating it, and the 3 rounds publish the next verify's
|
||||
* 3 proposals into tok[1..3] without touching what lies past them. */
|
||||
TEST(a_host_built_nine_row_verify_is_accepted_caught_up_and_followed_by_three_rounds) {
|
||||
for (int acc_want = 0; acc_want <= 8; ++acc_want) {
|
||||
const int ctx = 200, n = 9;
|
||||
/* the verify: the bonus token and 8 proposals, a host row (no device row) */
|
||||
Slab a(ADV_ACCEPT);
|
||||
a.row(0, false, 0, n, ctx, /*card=*/3, /*rtok=*/0, /*rout=*/0, /*aux=*/8);
|
||||
for (int j = 0; j < n; ++j) a.w[Slab::TOK + j] = 500 + j;
|
||||
for (int j = 0; j <= 8; ++j) a.src[j] = j < acc_want ? 500 + j + 1 : 9000 + j;
|
||||
a.run();
|
||||
const StepSlot& S = a.st[3];
|
||||
CHECK_EQ(S.acc, acc_want);
|
||||
CHECK_EQ(S.tok[0], 9000 + acc_want);
|
||||
CHECK_EQ(S.head, ctx + acc_want);
|
||||
CHECK_EQ(S.ctx, ctx + acc_want + 1);
|
||||
CHECK_EQ(S.n_acc, acc_want + 1);
|
||||
CHECK_EQ(S.npath, 0);
|
||||
|
||||
/* the head's history pass over all nine rows: positions up to the last committed one, the
|
||||
* rest repeating it, so no rejected proposal's hidden state reaches the head's cache */
|
||||
Slab h(ADV_HIST);
|
||||
h.st[3] = S;
|
||||
h.row(0, true, 0, n, ctx, 3, 0, 0, /*aux=*/0);
|
||||
for (int j = 0; j < n; ++j) h.src[j] = a.src[j];
|
||||
h.run();
|
||||
for (int j = 0; j < n; ++j) {
|
||||
const int up = std::min(j, acc_want);
|
||||
CHECK_EQ(h.w[Slab::POS + j], ctx + up);
|
||||
CHECK_EQ(h.slot(0, j), ctx + up);
|
||||
CHECK_EQ(h.w[Slab::OUT + j], up);
|
||||
}
|
||||
CHECK_EQ(h.used(0, 0), ctx + acc_want + 1);
|
||||
|
||||
/* the head's own rounds: 3 of the 8 the verify window allows */
|
||||
for (int round = 2; round <= 3; ++round) {
|
||||
Slab r(ADV_ROUND);
|
||||
r.a.round = round;
|
||||
r.st[3] = h.st[3];
|
||||
r.row(0, true, 0, 1, 0, 3, 0, 0, 0);
|
||||
r.src[0] = 7100 + round;
|
||||
r.run();
|
||||
h.st[3] = r.st[3];
|
||||
}
|
||||
Slab t(ADV_TAKE);
|
||||
t.a.round = 3;
|
||||
t.st[3] = h.st[3];
|
||||
t.row(0, true, 0, 1, 0, 3, 0, 0, 0);
|
||||
t.src[0] = 7200;
|
||||
t.run();
|
||||
const StepSlot& N = t.st[3];
|
||||
CHECK_EQ(N.tok[0], 9000 + acc_want);
|
||||
CHECK_EQ(N.tok[3], 7200);
|
||||
for (int j = 4; j <= RAD_SCHED_MAX_SPEC; ++j) CHECK_EQ(N.tok[j], (int32_t)0x7f7f7f7f); /* untouched */
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -127,6 +127,8 @@ struct RadBuilder {
|
||||
int64_t drafter_short = 0; /* rad_drafter_short_block */
|
||||
/* A tree drafter's parents buffer (rad_drafter_tree), 0 for a chain. */
|
||||
rad_buf drafter_parents = 0;
|
||||
/* The routing counts' table (rad_route_table), 0 when the plugin declared none. */
|
||||
rad_buf route_table = 0;
|
||||
|
||||
/* The buffers named to rad_buf_concurrent: the ones a second lane touches. */
|
||||
std::vector<rad_buf> concurrent;
|
||||
@@ -531,6 +533,8 @@ extern "C" int rad_step_fail(RadCtx* c, const char* what) {
|
||||
}
|
||||
extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; }
|
||||
extern "C" int rad_rank(RadCtx* c) { return c->rank; }
|
||||
/* One engine: the slot is the rank (RadBuildCtx::slot_base zero). */
|
||||
extern "C" int rad_slot(RadCtx* c) { return c->rank; }
|
||||
extern "C" int rad_world_size(RadCtx* c) { return c->world; }
|
||||
extern "C" int rad_ctx_wgp_count(RadCtx*) { return 32; }
|
||||
/* The context itself, so a copy issued on the step's stream is recorded in it (rad_memcpy_async). */
|
||||
@@ -541,6 +545,11 @@ extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) {
|
||||
c->routed_layers.push_back(layer);
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_route_table(RadBuilder* b, rad_buf table) {
|
||||
if (!b || table == 0) return RAD_E_INVAL;
|
||||
b->route_table = table;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* No card-side histogram here, so a router writes and reports its own buffer. */
|
||||
extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) {
|
||||
(void)c; (void)layer; (void)n_expert;
|
||||
|
||||
+2284
-977
File diff suppressed because it is too large.
Load diff
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# artifact_sums.sh -- checks committed built artifacts against tests/ARTIFACTS.
|
||||
#
|
||||
# Some committed files are not sources but a build of sources: core/server/dashboard_page.h is a
|
||||
# Node build of dashboard/, committed because the engine's build has no Node. The digest recorded
|
||||
# INSIDE such an artifact proves only that the sources and the artifact's own claim agree --
|
||||
# tampering with the artifact together with its embedded digest reads as an honest build. This
|
||||
# manifest hashes the artifact itself from outside, the mechanical half that vendor/SHA256SUMS is
|
||||
# to vendor/UPSTREAM: the dashboard_page test keeps sources and header in step, this one checks
|
||||
# the served bytes. (A tamper that updates the artifact and this manifest in one breath remains,
|
||||
# exactly as with a vendor file -- the manifest is against drift and lone tampering, not against
|
||||
# a commit that rewrites the whole record.)
|
||||
#
|
||||
# tests/artifact_sums.sh <repo-root>
|
||||
#
|
||||
# When an artifact is rebuilt for real, re-record it in the same commit:
|
||||
# sha256sum $(awk '{print $2}' tests/ARTIFACTS) > tests/ARTIFACTS
|
||||
set -e
|
||||
root=${1:?usage: artifact_sums.sh <repo-root>}
|
||||
cd "$root"
|
||||
command -v sha256sum >/dev/null || { echo "artifact_sums: sha256sum is required" >&2; exit 1; }
|
||||
[ -f tests/ARTIFACTS ] || { echo "artifact_sums: tests/ARTIFACTS is missing" >&2; exit 1; }
|
||||
sha256sum -c --status tests/ARTIFACTS || {
|
||||
echo "artifact_sums: a committed artifact differs from its recorded hash;" \
|
||||
"run sha256sum -c tests/ARTIFACTS to see which" >&2
|
||||
exit 1; }
|
||||
echo "artifact_sums: $(wc -l < tests/ARTIFACTS) artifact(s), every hash matches"
|
||||
@@ -209,6 +209,66 @@ TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST(breeze_reference_rows_are_repeated_with_the_guidance_one_prompt) {
|
||||
for (float cfg : {1.0f, 2.0f}) {
|
||||
AudioFixture f;
|
||||
f.build();
|
||||
f.prog.audio_gen.ref_max = 1;
|
||||
f.prog.audio_gen.ref_rate = 50;
|
||||
f.prog.audio_gen.ref_hop = 4;
|
||||
f.prog.audio_gen.ref_max_samples = 8;
|
||||
CHECK_OK(f.start());
|
||||
auto r = f.req(cfg);
|
||||
r->ref_audio.assign(4, 0.25f);
|
||||
r->ref_cu = {0, 4};
|
||||
r->ref_frame = {-1, 0, -1, -1};
|
||||
std::string why;
|
||||
if (cfg != 1.0f) {
|
||||
CHECK_EQ(f.drv.submit(std::move(r), &why), RAD_E_INVAL);
|
||||
CHECK(has(why, "guidance_scale 1"));
|
||||
continue;
|
||||
}
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT);
|
||||
const auto* A = b->agen_b;
|
||||
REQUIRE(A->ref_frame_h != nullptr && A->ref_frame != nullptr);
|
||||
CHECK_EQ(A->ref_frame_h[1], 0);
|
||||
CHECK_EQ(A->ref_frame_h[4], -1);
|
||||
CHECK_EQ(A->ref_frame_h[5], cfg == 1.0f ? 0 : -1);
|
||||
for (int64_t i = 0; i < b->n_tok; ++i) CHECK_EQ(A->ref_frame[i], A->ref_frame_h[i]);
|
||||
CHECK_EQ(A->ref_samples, (int64_t)4);
|
||||
f.answer(b, 0, 0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(reference_direction_keeps_each_guidance_branchs_reference_map) {
|
||||
for (float cfg : {1.0f, 4.0f}) {
|
||||
AudioFixture f;
|
||||
f.build();
|
||||
f.prog.audio_gen.ref_max = 1;
|
||||
f.prog.audio_gen.ref_rate = 50;
|
||||
f.prog.audio_gen.ref_hop = 4;
|
||||
f.prog.audio_gen.ref_max_samples = 8;
|
||||
CHECK_OK(f.start());
|
||||
auto r = f.req(cfg);
|
||||
r->ref_audio.assign(4, 0.25f); r->ref_cu = {0, 4};
|
||||
r->ref_frame = {-1, 0, -1, -1}; r->neg_ref_frame = {-1, 0};
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b && b->agen_b && b->agen_b->prompt_cu_h);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(cfg == 1.0f ? 8 : 6));
|
||||
CHECK_EQ(b->agen_b->prompt_cu_h[1], 4);
|
||||
CHECK_EQ(b->agen_b->prompt_cu_h[2], b->n_tok);
|
||||
CHECK_EQ(b->agen_b->ref_frame_h[5], 0);
|
||||
for (int64_t i = 0; i < b->n_tok; ++i)
|
||||
CHECK_EQ(b->agen_b->ref_frame[i], b->agen_b->ref_frame_h[i]);
|
||||
f.answer(b, 0, 0); CHECK_OK(f.drv.done());
|
||||
}
|
||||
}
|
||||
|
||||
/* A hybrid language model (paged attention beside a linear-attention state and a convolution
|
||||
* group, as Qwen3.5's delta-net layers keep) of one branch: every pass stages one sequence a
|
||||
* request, the state groups' rows are the sequence's slots, and each entry carries its context
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
/* Ling-3.0's declaration and step (arch/bailing_hybrid), without a GPU or checkpoint: the IQ8R
|
||||
* container data/recipes/ling-3.0-tiny-iq8r.recipe makes, at one and two ranks, and the bf16 and
|
||||
* four-bit containers, tiny and flash (with its MTP layer). */
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "arch_fakes.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "../arch/bailing_hybrid/bailing_hybrid.cpp"
|
||||
|
||||
using namespace rad_fake;
|
||||
|
||||
namespace {
|
||||
|
||||
/* Ling-3.0-tiny's configuration as rad-convert records it. */
|
||||
MetaKV tiny_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "bailinghybrid";
|
||||
m.name = "test-ling-tiny";
|
||||
m.quant = "";
|
||||
m.n_layers = 24;
|
||||
m.n_embd = 1536;
|
||||
m.n_head = 16;
|
||||
m.n_head_kv = 16;
|
||||
m.head_dim = 128;
|
||||
m.n_ff = 4608;
|
||||
m.n_vocab = 157184;
|
||||
m.n_ctx_train = 131072;
|
||||
m.rms_eps = 1e-6f;
|
||||
m.rope_theta = 6e6f;
|
||||
m.n_expert = 128;
|
||||
m.n_expert_used = 8;
|
||||
MetaKV k(m);
|
||||
k.set("num_attention_heads", "16").set("head_dim", "128").set("qk_nope_head_dim", "128")
|
||||
.set("qk_rope_head_dim", "64").set("v_head_dim", "128").set("kv_lora_rank", "512")
|
||||
.set("num_experts", "128").set("num_experts_per_tok", "8").set("n_group", "8")
|
||||
.set("topk_group", "4").set("moe_intermediate_size", "512")
|
||||
.set("moe_shared_expert_intermediate_size", "512").set("num_shared_experts", "1")
|
||||
.set("intermediate_size", "4608").set("first_k_dense_replace", "1")
|
||||
.set("layer_group_size", "4").set("short_conv_kernel_size", "4").set("q_lora_rank", "256")
|
||||
.set("kda_lower_bound", "-5").set("routed_scaling_factor", "2.5").set("no_kda_lora", "1")
|
||||
.set("kda_safe_gate", "1").set("rope_interleave", "1")
|
||||
.set("gated_attention_proj_granularity_type", "head_wise").set("score_function", "sigmoid")
|
||||
.set("num_nextn_predict_layers", "0").set("norm_topk_prob", "1");
|
||||
return k;
|
||||
}
|
||||
|
||||
/* Ling-3.0-flash's: 42 layers of 2560, MLA every sixth with no query LoRA, two dense layers, 512
|
||||
* experts of 768, the SwiGLU clamped in the last layers, one MTP layer. */
|
||||
MetaKV flash_meta() {
|
||||
MetaKV k = tiny_meta();
|
||||
k.m.name = "test-ling-flash";
|
||||
k.m.n_layers = 42;
|
||||
k.m.n_embd = 2560;
|
||||
k.m.n_head = 32;
|
||||
k.m.n_head_kv = 32;
|
||||
k.m.n_ff = 6144;
|
||||
k.m.n_expert = 512;
|
||||
std::string routed, shared;
|
||||
for (int l = 0; l < 42; ++l) {
|
||||
routed += std::string(l ? "," : "") + (l >= 35 ? "4" : "0");
|
||||
shared += std::string(l ? "," : "") + (l >= 40 ? "7" : l >= 34 ? "5" : "0");
|
||||
}
|
||||
k.set("num_attention_heads", "32").set("num_experts", "512")
|
||||
.set("moe_intermediate_size", "768").set("moe_shared_expert_intermediate_size", "768")
|
||||
.set("intermediate_size", "6144").set("first_k_dense_replace", "2")
|
||||
.set("layer_group_size", "6").set("q_lora_rank", "0").set("num_nextn_predict_layers", "1")
|
||||
.set("expert_swiglu_limit_list", routed.c_str())
|
||||
.set("share_expert_swiglu_limit_list", shared.c_str());
|
||||
return k;
|
||||
}
|
||||
|
||||
/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under
|
||||
* a bf16 scale a row. */
|
||||
RadEncoding iq8r() {
|
||||
RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256);
|
||||
rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0);
|
||||
rad_enc_copy_str(e.transform, "fwht128");
|
||||
return e;
|
||||
}
|
||||
|
||||
/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */
|
||||
RadEncoding i8h() {
|
||||
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
|
||||
rad_enc_copy_str(e.transform, "fwht128");
|
||||
return e;
|
||||
}
|
||||
|
||||
const RadEncoding kI4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
|
||||
|
||||
/* data/recipes/ling-3.0-tiny-iq8r.recipe's encodings by declared name, every other weight plain
|
||||
* bf16. `attn_gate.weight` is the KDA output gate; the MLA's head gate is `attn_head_gate`. */
|
||||
void iq8r_encs(RadBuilder* b) {
|
||||
b->encs.clear();
|
||||
for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" })
|
||||
b->encs.push_back({ t, i8h() });
|
||||
for (const char* t : { "attn_qkv.weight", "attn_forget.weight", "attn_gate.weight",
|
||||
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight",
|
||||
"ffn_gate_up_shexp" })
|
||||
b->encs.push_back({ t, iq8r() });
|
||||
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
|
||||
}
|
||||
|
||||
/* data/recipes/ling3-w4a8-rtn.recipe's: four-bit routed experts, everything else bf16. */
|
||||
void w4_encs(RadBuilder* b) {
|
||||
b->encs.clear();
|
||||
b->encs.push_back({ "ffn_gate_up_exps", kI4 });
|
||||
b->encs.push_back({ "ffn_down_exps", kI4 });
|
||||
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
|
||||
}
|
||||
|
||||
/* The bf16 checkpoint. */
|
||||
void bf16_encs(RadBuilder* b) {
|
||||
b->encs.clear();
|
||||
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
|
||||
}
|
||||
|
||||
bool is_mla(int l) { return (l + 1) % 4 == 0; }
|
||||
|
||||
const std::string& wname(const RadBuilder& b, rad_weight w) { return b.weights[w - 1].name; }
|
||||
|
||||
/* The buffer a name declared, 0 if none. */
|
||||
rad_buf buf(const RadBuilder& b, const char* n) {
|
||||
for (size_t i = 0; i < b.bufs.size(); ++i)
|
||||
if (b.bufs[i].name == n) return (rad_buf)(i + 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* graph_hash with the name maps in declared-name order (stable, so maps that extend one name keep
|
||||
* theirs): where among the other declarations a map is made (the trunk probe maps layer 0's
|
||||
* q|k|v ahead of the buffers) is not part of what the core builds from it. */
|
||||
uint64_t graph_hash_maps_by_name(const RadBuilder& b0) {
|
||||
RadBuilder b = b0;
|
||||
std::stable_sort(b.maps.begin(), b.maps.end(),
|
||||
[](const RecMap& x, const RecMap& y) { return x.declared < y.declared; });
|
||||
return graph_hash(b);
|
||||
}
|
||||
|
||||
/* A decode step, a prefill of two prompts and a mixed step, each pass clean. */
|
||||
void steps_lint_clean(RadBuilder& b, int rank, int world) {
|
||||
const auto dc = kit(b, { 1, 1, 1 }, {});
|
||||
const auto pf = kit(b, {}, { 64, 100 }, 0);
|
||||
const auto mx = kit(b, { 1, 1 }, { 120 }, 300);
|
||||
for (const Kit* k : { dc.get(), pf.get(), mx.get() }) {
|
||||
auto v = run_passes(b, bailing_hybrid::step, { k }, rank, world);
|
||||
CHECK_PASSES(b, v);
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The IQ8R container at one rank and both ranks of two: every trunk linear the recipe quantises is
|
||||
* one gemm_nt_q at i8a8h, its N and K this rank's, reading the codes of the producer that feeds it
|
||||
* at that producer's group; the linears the recipe keeps bf16 are gemm_nt over the norm's bf16
|
||||
* output; the grouped GEMMs are the int8 rows. No E4M3 code and no unrotated int8 quantiser
|
||||
* exist, and no linear quantises its own input. */
|
||||
TEST(iq8r_container_declares_the_rotated_int8_trunk) {
|
||||
for (int world : { 1, 2 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const bailing_hybrid::Model& m = bailing_hybrid::g_model[rank];
|
||||
CHECK(m.trunk_rot);
|
||||
CHECK(m.norm_fed);
|
||||
CHECK_EQ(m.trunk_g8, 256);
|
||||
const int64_t H = 16 / world, W = 128 * H, FF = 4608 / world, SH = 512 / world,
|
||||
EX = 512 / world;
|
||||
const rad_buf normed = buf(b, "normed"), nq = buf(b, "normed.q8"),
|
||||
ns = buf(b, "normed.s8"), kq = buf(b, "kda_out.q8"),
|
||||
vq = buf(b, "mla_value.q8"), dq = buf(b, "dense_ff.q8"),
|
||||
sq = buf(b, "shared_ff.q8"), eq = buf(b, "expert_ff.q8"),
|
||||
qa = buf(b, "mla_q_a");
|
||||
REQUIRE(normed && nq && ns && kq && vq && dq && sq && eq && qa);
|
||||
CHECK_EQ(m.act.q8, (uint32_t)nq);
|
||||
|
||||
/* ---- each quantised linear: N, K, group, the codes it reads. */
|
||||
struct Want { int64_t N, K, group; rad_buf in; int n; };
|
||||
std::map<std::string, Want> want;
|
||||
for (int l = 0; l < 24; ++l) {
|
||||
char n[96];
|
||||
if (is_mla(l)) {
|
||||
std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l);
|
||||
want[n] = { 1536, H * 128, 256, vq, 0 };
|
||||
} else {
|
||||
std::snprintf(n, sizeof n, "blk.%d.attn_qkv.weight", l);
|
||||
want[n] = { 3 * W, 1536, 256, nq, 0 };
|
||||
std::snprintf(n, sizeof n, "blk.%d.attn_forget.weight", l);
|
||||
want[n] = { W, 1536, 256, nq, 0 };
|
||||
std::snprintf(n, sizeof n, "blk.%d.attn_gate.weight", l);
|
||||
want[n] = { W, 1536, 256, nq, 0 };
|
||||
std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l);
|
||||
want[n] = { 1536, W, 256, kq, 0 };
|
||||
}
|
||||
if (l == 0) {
|
||||
want["blk.0.ffn_gate_up.weight"] = { 2 * FF, 1536, 256, nq, 0 };
|
||||
want["blk.0.ffn_down.weight"] = { 1536, FF, 256, dq, 0 };
|
||||
} else {
|
||||
std::snprintf(n, sizeof n, "blk.%d.ffn_gate_up_shexp.weight", l);
|
||||
want[n] = { 2 * SH, 1536, 256, nq, 0 };
|
||||
std::snprintf(n, sizeof n, "blk.%d.ffn_down_shexp.weight", l);
|
||||
want[n] = { 1536, SH, 128, sq, 0 };
|
||||
}
|
||||
}
|
||||
int q = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "gemm_nt_q") continue;
|
||||
++q;
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
|
||||
REQUIRE(!o.w.empty());
|
||||
auto it = want.find(wname(b, o.w[0]));
|
||||
REQUIRE(it != want.end());
|
||||
Want& x = it->second;
|
||||
++x.n;
|
||||
CHECK_EQ(pint(&o, "N"), x.N);
|
||||
CHECK_EQ(pint(&o, "K"), x.K);
|
||||
CHECK_EQ(pint(&o, "group"), x.group);
|
||||
CHECK(in(o.reads, x.in));
|
||||
}
|
||||
CHECK_EQ(q, 18 * 4 + 6 + 2 + 23 * 2);
|
||||
for (const auto& [name, x] : want) CHECK_EQ(x.n, 1);
|
||||
|
||||
/* ---- the linears the recipe keeps bf16, over the norm's bf16 output (the query parts
|
||||
* over the LoRA's normed latent). */
|
||||
int keep = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "gemm_nt" || o.w.empty()) continue;
|
||||
const std::string& n = wname(b, o.w[0]);
|
||||
const bool lora = n.find("attn_q_rope") != std::string::npos ||
|
||||
n.find("attn_q_nope") != std::string::npos;
|
||||
if (n.find("attn_beta") == std::string::npos &&
|
||||
n.find("attn_q_a.") == std::string::npos &&
|
||||
n.find("attn_kv_a.") == std::string::npos &&
|
||||
n.find("attn_head_gate") == std::string::npos && !lora)
|
||||
continue;
|
||||
++keep;
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("bf16"));
|
||||
CHECK(in(o.reads, lora ? qa : normed));
|
||||
CHECK(!in(o.reads, nq));
|
||||
}
|
||||
CHECK_EQ(keep, 18 + 6 * 5);
|
||||
|
||||
/* ---- the producers and their groups. */
|
||||
int norms = 0, outq = 0, dense = 0, shared = 0, routed = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op == "rmsnorm_had_quant_i8g") {
|
||||
++norms;
|
||||
CHECK_EQ(pint(&o, "group"), 256);
|
||||
CHECK_EQ(pint(&o, "n"), 1536);
|
||||
CHECK(in(o.writes, nq) && in(o.writes, ns) && in(o.writes, normed));
|
||||
} else if (o.op == "had_quant_act_i8g") {
|
||||
++outq;
|
||||
CHECK_EQ(pint(&o, "group"), 256);
|
||||
const bool kda = in(o.writes, kq);
|
||||
CHECK(kda || in(o.writes, vq));
|
||||
CHECK_EQ(pint(&o, "n"), kda ? W : H * 128);
|
||||
} else if (o.op == "gated_had_quant_i8g") {
|
||||
if (in(o.writes, dq)) {
|
||||
++dense;
|
||||
CHECK_EQ(pint(&o, "group"), 256);
|
||||
CHECK_EQ(pint(&o, "n"), FF);
|
||||
} else if (in(o.writes, sq)) {
|
||||
++shared;
|
||||
CHECK_EQ(pint(&o, "group"), 128);
|
||||
CHECK_EQ(pint(&o, "n"), SH);
|
||||
} else {
|
||||
CHECK(in(o.writes, eq));
|
||||
++routed;
|
||||
CHECK_EQ(pint(&o, "group"), 128);
|
||||
CHECK_EQ(pint(&o, "n"), EX);
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_EQ(norms, 48);
|
||||
CHECK_EQ(outq, 18 + 6);
|
||||
CHECK_EQ(dense, 1);
|
||||
CHECK_EQ(shared, 23);
|
||||
CHECK_EQ(routed, 23);
|
||||
for (const char* op : { "rmsnorm_quant_fp8", "ar_rmsnorm_quant_fp8",
|
||||
"ar_rmsnorm_had_quant_i8g", "quant_act_fp8", "quant_act_i8g",
|
||||
"gated_quant_fp8", "had_quant_act_fp8", "gated_had_quant_fp8",
|
||||
"swiglu_step", "silu_mul" })
|
||||
CHECK_EQ(count_op(b, op), 0);
|
||||
for (const char* n : { "normed.q", "kda_out.q", "mla_value.q", "mla_q_a.q",
|
||||
"dense_ff.q", "shared_ff.q", "expert_ff.q", "normed_rot.q",
|
||||
"normed_rot.q8" })
|
||||
CHECK(find_b(b, n) == nullptr);
|
||||
|
||||
/* ---- the routed experts: rotated int8 rows, gate_up over the norm's codes at 256,
|
||||
* down over the gated product's at 128, each rank a slice of every expert. */
|
||||
int gu = 0, dn = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "moe_gemm_q") continue;
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
|
||||
const bool token = pstr(&o, "a_order") == "token";
|
||||
CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128);
|
||||
CHECK(in(o.reads, token ? nq : eq));
|
||||
CHECK_EQ(pint(&o, "N"), token ? 2 * EX : 1536);
|
||||
CHECK_EQ(pint(&o, "K"), token ? 1536 : EX);
|
||||
CHECK_EQ(pint(&o, "n_expert"), 128);
|
||||
(token ? gu : dn) += 1;
|
||||
}
|
||||
CHECK_EQ(gu, 23);
|
||||
CHECK_EQ(dn, 23);
|
||||
const RecWeight* e0 = find_w(b, "blk.1.ffn_gate_up_exps.127.weight");
|
||||
REQUIRE(e0 != nullptr);
|
||||
CHECK_EQ(e0->d.dtype, (uint32_t)RAD_I8);
|
||||
CHECK_EQ((int)e0->d.shard, (int)RAD_SHARD_ROW);
|
||||
steps_lint_clean(b, rank, world);
|
||||
}
|
||||
}
|
||||
|
||||
/* The IQ8R container shards as the bf16 one does: every weight both declare outside the routed
|
||||
* experts is split the same way, and the collectives are the same standalone all-reduces (the plugin's norms take no
|
||||
* collective, so no `ar_` norm is declared at two ranks). */
|
||||
TEST(iq8r_container_follows_the_plugins_sharding) {
|
||||
for (int world : { 1, 2 }) {
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder q, f;
|
||||
iq8r_encs(&q);
|
||||
bf16_encs(&f);
|
||||
RadBuildCtx cq = build_ctx(0, world), cf = build_ctx(0, world);
|
||||
cf.slot_base = 4;
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&q, mk.meta(), &cq), RAD_OK);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&f, mk.meta(), &cf), RAD_OK);
|
||||
int same = 0;
|
||||
for (const RecWeight& w : q.weights) {
|
||||
const RecWeight* o = find_w(f, w.name);
|
||||
if (!o || w.name.find("_exps.") != std::string::npos) continue;
|
||||
++same;
|
||||
CHECK_EQ(w.d.shard, o->d.shard);
|
||||
CHECK_EQ(w.d.n_row_parts, o->d.n_row_parts);
|
||||
}
|
||||
CHECK(same > 300);
|
||||
CHECK_EQ(count_op(q, "all_reduce"), count_op(f, "all_reduce"));
|
||||
CHECK_EQ(count_op(q, "all_reduce"), world == 2 ? 1 + 24 + 24 : 0);
|
||||
/* Rotated int8 experts are a slice of every expert on each rank, where bf16 ones are
|
||||
* whole on one. */
|
||||
CHECK(find_w(q, "blk.1.ffn_gate_up_exps.0.weight") != nullptr);
|
||||
CHECK(find_w(q, "blk.1.ffn_gate_up_exps.127.weight") != nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
/* Where no loaded library serves the rotating norm (a CPU-only engine), the norms write E4M3
|
||||
* codes no linear reads, every int8 trunk linear quantises the norm's bf16 output itself at the
|
||||
* trunk's group, and the routed gate_up reads a rotated int8 copy written once a layer at 128. */
|
||||
TEST(iq8r_container_without_the_rotating_norm_quantises_each_input) {
|
||||
for (int world : { 1, 2 }) {
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
b.undeclared.insert("rmsnorm_had_quant_i8g");
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(0, world);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
CHECK(bailing_hybrid::g_model[0].trunk_rot);
|
||||
CHECK(!bailing_hybrid::g_model[0].norm_fed);
|
||||
CHECK_EQ(count_op(b, "rmsnorm_quant_fp8"), 48);
|
||||
const rad_buf normed = buf(b, "normed"), hr = buf(b, "normed_rot.q8");
|
||||
REQUIRE(hr != 0);
|
||||
int own = 0, copy = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op == "had_quant_act_i8g" && in(o.reads, normed)) {
|
||||
const bool c = in(o.writes, hr);
|
||||
(c ? copy : own) += 1;
|
||||
CHECK_EQ(pint(&o, "group"), c ? 128 : 256);
|
||||
}
|
||||
if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") {
|
||||
CHECK_EQ(pint(&o, "a_group"), 128);
|
||||
CHECK(in(o.reads, hr));
|
||||
}
|
||||
}
|
||||
/* q|k|v, forget and gate on 18 layers, the dense gate_up, 23 shared gate_ups. */
|
||||
CHECK_EQ(own, 18 * 3 + 1 + 23);
|
||||
CHECK_EQ(copy, 23);
|
||||
steps_lint_clean(b, 0, world);
|
||||
}
|
||||
}
|
||||
|
||||
/* A shared expert whose down projection is stored IQ8R too takes its input codes at 256. */
|
||||
TEST(iq8r_shared_down_sets_its_inputs_group) {
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
b.encs.insert(b.encs.begin(), { "ffn_down_shexp", iq8r() });
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const rad_buf sq = buf(b, "shared_ff.q8");
|
||||
int n = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "gated_had_quant_i8g" && in(o.writes, sq)) {
|
||||
CHECK_EQ(pint(&o, "group"), 256);
|
||||
++n;
|
||||
}
|
||||
CHECK_EQ(n, 23);
|
||||
CHECK_EQ(find_b(b, "shared_ff.s8")->d.shape[1], 2);
|
||||
}
|
||||
|
||||
/* The bf16 and four-bit containers at one rank and both ranks of two, tiny and flash (with its
|
||||
* MTP layer under speculation), pinned by their graphs' fingerprints: no int8 op, E4M3 codes from
|
||||
* the norms, and the four-bit experts reading the norm's E4M3 pair at w4a8. */
|
||||
TEST(bf16_and_four_bit_containers_keep_their_graphs) {
|
||||
struct Case { bool flash, w4; int world, rank; uint64_t hash; };
|
||||
const Case cases[] = {
|
||||
{ false, false, 1, 0, 0x86ab7d6c2a6c7d9aull },
|
||||
{ false, false, 2, 0, 0x08a9d5eac89cbfdcull },
|
||||
{ false, false, 2, 1, 0x6bbc016892e93dacull },
|
||||
{ false, true, 1, 0, 0xcdcf0243f2a0c792ull },
|
||||
{ false, true, 2, 0, 0xda4c82105c0feb47ull },
|
||||
{ false, true, 2, 1, 0xd94daa2c5c90352bull },
|
||||
{ true, false, 1, 0, 0x21f7c41f985de35eull },
|
||||
{ true, false, 2, 0, 0x0420376396574defull },
|
||||
{ true, false, 2, 1, 0xb7df9b2e13bc4ae6ull },
|
||||
{ true, true, 1, 0, 0xf9dec754da195628ull },
|
||||
{ true, true, 2, 0, 0x7da4ef872c9304e9ull },
|
||||
{ true, true, 2, 1, 0xcc97ada7f98fca85ull },
|
||||
};
|
||||
for (const Case& c : cases) {
|
||||
MetaKV mk = c.flash ? flash_meta() : tiny_meta();
|
||||
RadBuilder b;
|
||||
if (c.w4) w4_encs(&b); else bf16_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(c.rank, c.world);
|
||||
if (c.flash) ctx.max_spec = 3;
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const bailing_hybrid::Model& m = bailing_hybrid::g_model[c.rank];
|
||||
CHECK(!m.trunk_rot);
|
||||
CHECK_EQ(m.have_mtp, c.flash);
|
||||
CHECK_EQ(graph_hash_maps_by_name(b), c.hash);
|
||||
CHECK(count_op(b, "rmsnorm_quant_fp8") > 0);
|
||||
for (const char* op : { "rmsnorm_had_quant_i8g", "had_quant_act_i8g",
|
||||
"gated_had_quant_i8g", "gemm_nt_q" })
|
||||
CHECK_EQ(count_op(b, op), 0);
|
||||
if (c.w4) {
|
||||
const rad_buf nq = buf(b, "normed.q");
|
||||
int moe = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "moe_gemm_q") {
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8"));
|
||||
if (pstr(&o, "a_order") == "token") CHECK(in(o.reads, nq));
|
||||
++moe;
|
||||
}
|
||||
CHECK_EQ(moe, 2 * (c.flash ? 41 : 23));
|
||||
}
|
||||
if (!c.flash) steps_lint_clean(b, c.rank, c.world);
|
||||
}
|
||||
}
|
||||
|
||||
/* What the plugin refuses by name: a rotated trunk over unrotated experts, rotated int8 experts
|
||||
* under an unrotated trunk, and the tiny IQ8R trunk at four ranks, whose 1152-column dense slice
|
||||
* cuts a 256-column scale group. */
|
||||
TEST(refuses_mismatched_forms) {
|
||||
{
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
for (auto& e : b.encs)
|
||||
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = kI4;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
w4_encs(&b);
|
||||
for (auto& e : b.encs)
|
||||
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(0, 4);
|
||||
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
|
||||
/* Flash's IQ8R trunk with the clamp lists cut declares, MTP layer included: the drafter's MLA and
|
||||
* routed feed-forward read the trunk's codes like any trunk layer. */
|
||||
TEST(flash_iq8r_without_clamps_declares_its_drafter_on_the_int8_trunk) {
|
||||
for (int world : { 1, 2 }) {
|
||||
MetaKV mk = flash_meta();
|
||||
mk.drop("expert_swiglu_limit_list").drop("share_expert_swiglu_limit_list");
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(0, world);
|
||||
ctx.max_spec = 3;
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const bailing_hybrid::Model& m = bailing_hybrid::g_model[0];
|
||||
CHECK(m.trunk_rot);
|
||||
CHECK(m.have_mtp);
|
||||
const RecWeight* d = find_w(b, "blk.42.attn_output.weight");
|
||||
REQUIRE(d != nullptr);
|
||||
CHECK_EQ(d->d.dtype, (uint32_t)RAD_I8);
|
||||
/* 40 routed layers and the drafter's; two norms a layer. */
|
||||
CHECK_EQ(count_op(b, "moe_gemm_q"), 2 * 41);
|
||||
CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 2 * 43);
|
||||
}
|
||||
}
|
||||
|
||||
/* Flash's IQ8R trunk with its clamp lists declares at one, two and four ranks. Each clamped gated
|
||||
* product (routed in layers 35-41, shared in 34-41) is two launches: the clamp into the bf16 plane
|
||||
* (swiglu_step) and the rotating int8 quantiser reading it (had_quant_act_i8g, at the 128-column
|
||||
* group of the int8 down projection that reads the codes). Against the same container without
|
||||
* the clamp lists, those 15 gated_had_quant_i8g become 15 such pairs and no other op changes; no
|
||||
* unrotated int8 and no E4M3 quantiser exists, and the steps run lint-clean. */
|
||||
TEST(flash_iq8r_clamps_its_gated_products_then_quantises_them_rotated) {
|
||||
for (int world : { 1, 2, 4 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV plain = flash_meta();
|
||||
plain.drop("expert_swiglu_limit_list").drop("share_expert_swiglu_limit_list");
|
||||
RadBuilder b0;
|
||||
iq8r_encs(&b0);
|
||||
RadBuildCtx c0 = build_ctx(rank, world);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b0, plain.meta(), &c0), RAD_OK);
|
||||
MetaKV mk = flash_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
CHECK(bailing_hybrid::g_model[0].trunk_rot);
|
||||
CHECK_EQ(count_op(b, "swiglu_step"), 15);
|
||||
CHECK_EQ(count_op(b, "had_quant_act_i8g") - count_op(b0, "had_quant_act_i8g"), 15);
|
||||
CHECK_EQ(count_op(b0, "gated_had_quant_i8g") - count_op(b, "gated_had_quant_i8g"), 15);
|
||||
CHECK_EQ(b.ops.size(), b0.ops.size() + 15);
|
||||
CHECK_EQ(count_op(b, "quant_act_i8g"), 0);
|
||||
CHECK_EQ(count_op(b, "quant_act_fp8"), 0);
|
||||
CHECK_EQ(count_op(b, "swiglu_clamped"), 0);
|
||||
for (size_t i = 0; i + 1 < b.ops.size(); ++i) {
|
||||
if (b.ops[i].op != "swiglu_step") continue;
|
||||
const RecOp& q = b.ops[i + 1];
|
||||
CHECK_EQ(q.op, std::string("had_quant_act_i8g"));
|
||||
REQUIRE_EQ(b.ops[i].writes.size(), (size_t)1);
|
||||
CHECK(std::find(q.reads.begin(), q.reads.end(), b.ops[i].writes[0]) !=
|
||||
q.reads.end());
|
||||
const RecParam* g = param(&q, "group");
|
||||
REQUIRE(g != nullptr);
|
||||
CHECK_EQ(g->ival, 128LL);
|
||||
}
|
||||
steps_lint_clean(b, rank, world);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Per-instance state lives in the declaring instance's slot, so a second engine in the process
|
||||
* leaves the first one's model alone. */
|
||||
TEST(declares_into_its_own_slot) {
|
||||
MetaKV mk = tiny_meta();
|
||||
RadBuilder b0, b1;
|
||||
iq8r_encs(&b0);
|
||||
w4_encs(&b1);
|
||||
RadBuildCtx c0 = build_ctx();
|
||||
RadBuildCtx c1 = build_ctx();
|
||||
c1.slot_base = 4;
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b0, mk.meta(), &c0), RAD_OK);
|
||||
REQUIRE_EQ(bailing_hybrid::declare(&b1, mk.meta(), &c1), RAD_OK);
|
||||
CHECK(bailing_hybrid::g_model[0].trunk_rot);
|
||||
CHECK(!bailing_hybrid::g_model[4].trunk_rot);
|
||||
CHECK_EQ(bailing_hybrid::g_model[4].s.n_layer, 24);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,150 @@
|
||||
/* Recording tests of Breeze's reference encoder and prompt assembly; no weights or GPU. */
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "arch_fakes.h"
|
||||
#include <dlfcn.h>
|
||||
#include "../arch/breeze/breeze.cpp"
|
||||
|
||||
extern "C" int rad_declare_audio_generator(RadBuilder*, const RadAudioGenDecl*) { return RAD_OK; }
|
||||
|
||||
namespace {
|
||||
struct Fixture {
|
||||
RadBuilder b;
|
||||
breeze::Model m;
|
||||
Fixture() {
|
||||
m.gl.max_tok = 1024;
|
||||
m.gl.n_embd = 2048;
|
||||
m.ge = m.gl;
|
||||
m.b_x = rad::arch::decl_b(&b, "lm.x", RAD_BF16, {1024, 2048});
|
||||
m.w_cb = rad::arch::decl_w(&b, "frame.codebooks.weight", RAD_BF16, {16 * 2051, 2048},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, rad::arch::grp_layer(0));
|
||||
const char* keys[] = {"text_encoder_config.layer_types", "text_encoder_config.num_hidden_layers",
|
||||
"audio_tokenizer.encoder_config.hidden_size", "audio_tokenizer.encoder_config.num_hidden_layers",
|
||||
"audio_tokenizer.encoder_config.num_filters"};
|
||||
const char* vals[] = {"full_attention", "1", "512", "8", "64"};
|
||||
RadModelMeta meta{};
|
||||
meta.n_kv = 5; meta.kv_key = keys; meta.kv_val = vals;
|
||||
CHECK_OK(breeze::declare_encoder(&b, &meta, m));
|
||||
CHECK_OK(breeze::declare_reference(&b, &meta, m));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
TEST(breeze_clone_encodes_text_segments_independently_and_audio_only_once) {
|
||||
Fixture f;
|
||||
/* Three text rows, two reference frames, one audio EOS, three new text rows, twice. */
|
||||
int32_t tokens[18]{}, positions[18]{}, cu[] = {0, 9, 18}, ref_cu[] = {0, 3840};
|
||||
int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1,
|
||||
-1, -1, -1, 0, 1, -1, -1, -1, -1};
|
||||
int32_t last[] = {0};
|
||||
float audio = 0;
|
||||
RadAudioGenBatch A{};
|
||||
A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840;
|
||||
A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio; A.ref_frame_h = map;
|
||||
A.prompt_cu_h = cu;
|
||||
RadBatch batch{};
|
||||
batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 18; batch.n_seq = 2;
|
||||
batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A;
|
||||
RadCtx c; c.b = &f.b; c.batch = &batch;
|
||||
breeze::step_prompt(&c, &batch, f.m);
|
||||
int text_segments = 0, reference_encodes = 0, quantisers = 0, embeddings = 0;
|
||||
std::vector<int64_t> output_offsets;
|
||||
for (const auto& issue : c.issues) {
|
||||
if (issue.op == f.m.op_eembed) {
|
||||
++text_segments;
|
||||
CHECK_EQ(issue.n, (int64_t)3);
|
||||
}
|
||||
if (issue.op == f.m.enc[0].op_qknr)
|
||||
CHECK_EQ(issue.opd[1].handle, f.m.ref.text_pos);
|
||||
if (issue.op == f.m.op_eproj) output_offsets.push_back(issue.opd.back().offset / 2048);
|
||||
if (issue.op == f.m.ref.first.op) ++reference_encodes;
|
||||
if (f.b.ops[issue.op - 1].op == "vq_euclidean") {
|
||||
++quantisers; CHECK_EQ(issue.n, (int64_t)2);
|
||||
}
|
||||
if (issue.op == f.m.ref.embed) {
|
||||
++embeddings;
|
||||
/* rvq_embed's second table starts at codebook 1, not at codebook 0.
|
||||
* The same slice is required for the reference frames and their audio EOS. */
|
||||
CHECK_EQ(issue.opd[1].handle, f.m.w_cb);
|
||||
CHECK_EQ(issue.opd[1].offset, (int64_t)0);
|
||||
CHECK_EQ(issue.opd[2].handle, f.m.w_cb);
|
||||
CHECK_EQ(issue.opd[2].offset, (int64_t)2051 * 2048);
|
||||
CHECK_EQ(issue.opd[2].rows, (int64_t)15 * 2051);
|
||||
}
|
||||
}
|
||||
CHECK_EQ(text_segments, 4);
|
||||
CHECK_EQ(reference_encodes, 1);
|
||||
CHECK_EQ(quantisers, 16);
|
||||
CHECK_EQ(embeddings, 4); /* a clip and its EOS in each branch */
|
||||
CHECK(output_offsets == std::vector<int64_t>({0, 6, 9, 15}));
|
||||
CHECK_LINT(f.b, &c);
|
||||
}
|
||||
|
||||
TEST(breeze_reference_transcripts_cannot_inject_audio_or_template_markers) {
|
||||
char out[128];
|
||||
CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, "the reference words", out, sizeof(out)), 19);
|
||||
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>", "<ins_bos>", "<ins_eos>"})
|
||||
CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, marker, out, sizeof(out)), (int64_t)RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(breeze_reference_direction_uses_actual_unequal_branch_boundaries) {
|
||||
Fixture f;
|
||||
int32_t tokens[22]{}, positions[22]{}, cu[] = {0, 13, 22}, ref_cu[] = {0, 3840};
|
||||
int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1,
|
||||
-1, -1, -1, 0, 1, -1, -1, -1, -1};
|
||||
int32_t last[] = {0}; float audio = 0;
|
||||
RadAudioGenBatch A{};
|
||||
A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840;
|
||||
A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio;
|
||||
A.ref_frame_h = map; A.prompt_cu_h = cu;
|
||||
RadBatch batch{};
|
||||
batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 22; batch.n_seq = 2;
|
||||
batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A;
|
||||
RadCtx c; c.b = &f.b; c.batch = &batch;
|
||||
breeze::step_prompt(&c, &batch, f.m);
|
||||
std::vector<int64_t> lengths, offsets;
|
||||
int encodes = 0;
|
||||
for (const auto& issue : c.issues) {
|
||||
if (issue.op == f.m.op_eembed) lengths.push_back(issue.n);
|
||||
if (issue.op == f.m.op_eproj) offsets.push_back(issue.opd.back().offset / 2048);
|
||||
if (issue.op == f.m.ref.first.op) ++encodes;
|
||||
}
|
||||
CHECK(lengths == std::vector<int64_t>({3, 7, 3, 3}));
|
||||
CHECK(offsets == std::vector<int64_t>({0, 6, 13, 19}));
|
||||
CHECK_EQ(encodes, 1);
|
||||
CHECK_LINT(f.b, &c);
|
||||
}
|
||||
|
||||
TEST(breeze_reference_declarations_use_the_real_kernel_vocabulary) {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
REQUIRE(home != nullptr);
|
||||
void* lib = dlopen((std::string(home) + "/kernels/libref.so").c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
REQUIRE(lib != nullptr);
|
||||
auto count = (int (*)())dlsym(lib, "rad_kernel_schema_count");
|
||||
auto at = (const RadOpSchema* (*)(int))dlsym(lib, "rad_kernel_schema_at");
|
||||
REQUIRE(count && at);
|
||||
std::map<std::string, const RadOpSchema*> schemas;
|
||||
for (int i = 0; i < count(); ++i) schemas[at(i)->op] = at(i);
|
||||
Fixture f;
|
||||
for (const auto& op : f.b.ops) {
|
||||
REQUIRE(schemas.count(op.op) != 0);
|
||||
const auto* s = schemas.at(op.op);
|
||||
for (const auto& p : op.p) {
|
||||
bool known = false;
|
||||
for (int i = 0; i < s->n_params; ++i) known |= p.key == s->params[i].key;
|
||||
CHECK(known);
|
||||
}
|
||||
for (int i = 0; i < s->n_params; ++i) {
|
||||
if (!s->params[i].required) continue;
|
||||
CHECK(std::any_of(op.p.begin(), op.p.end(), [&](const auto& p) { return p.key == s->params[i].key; }));
|
||||
}
|
||||
size_t min_w = 0, max_w = 0;
|
||||
for (int i = 0; i < s->n_operands; ++i) if (s->operands[i].role == RAD_OPD_WEIGHT) {
|
||||
++max_w; if (!s->operands[i].optional) ++min_w;
|
||||
}
|
||||
CHECK(op.w.size() >= min_w && op.w.size() <= max_w);
|
||||
for (auto w : op.w) CHECK(w != 0 && w <= f.b.weights.size());
|
||||
}
|
||||
dlclose(lib);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+23
-2
@@ -11,7 +11,7 @@
|
||||
#include "rad_test.h"
|
||||
#include "rad_planes.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include "build/rad_build.h"
|
||||
#include "build/startup.h"
|
||||
@@ -27,7 +27,7 @@
|
||||
#include <unistd.h>
|
||||
|
||||
using namespace rad;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -1170,6 +1170,27 @@ TEST(a_tree_drafter_takes_a_short_block) {
|
||||
CHECK_EQ(b7.program().drafter_short_block, 8);
|
||||
}
|
||||
|
||||
/* The routing table (rad_route_table) is an i32 persistent device buffer, named once: the core
|
||||
* reads its rows between passes, where a transient's bytes may be another buffer's. */
|
||||
TEST(a_routing_table_is_a_persistent_i32_buffer) {
|
||||
Registry reg;
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadBufDecl bd{};
|
||||
bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 4; bd.shape[1] = 8;
|
||||
const rad_buf transient = rad_decl_buffer(&b, "t", &bd);
|
||||
bd.kind = RAD_BUF_PERSIST;
|
||||
const rad_buf tab = rad_decl_buffer(&b, "tab", &bd);
|
||||
const rad_buf tab2 = rad_decl_buffer(&b, "tab2", &bd);
|
||||
bd.dtype = RAD_BF16;
|
||||
const rad_buf half = rad_decl_buffer(&b, "half", &bd);
|
||||
CHECK_EQ(rad_route_table(&b, 0), RAD_E_INVAL);
|
||||
CHECK_EQ(rad_route_table(&b, transient), RAD_E_INVAL);
|
||||
CHECK_EQ(rad_route_table(&b, half), RAD_E_DTYPE);
|
||||
CHECK_OK(rad_route_table(&b, tab));
|
||||
CHECK_EQ(b.program().route_table, tab);
|
||||
CHECK_EQ(rad_route_table(&b, tab2), RAD_E_STATE);
|
||||
}
|
||||
|
||||
/* A block drafter's proposal pitch is its row pitch, which the engine reads row s at: left at 0 it
|
||||
* defaults to depth, and under depth it is refused, since a row could not hold the proposals. */
|
||||
TEST(a_block_drafters_proposal_pitch_holds_its_proposals) {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""chain_scalar_audit.py BUILD_DIR OUT_DIR [--check]
|
||||
|
||||
A chained wait ends with an acquire: the agent-scope fence for the vector caches and, unless the kernel's wait is the
|
||||
variant that leaves it out, `s_dcache_inv` for the scalar data cache (libr4d/r4d_chain.h). A kernel may use that
|
||||
variant only when nothing it reads behind the wait goes through a scalar load. This audit compiles every HIP unit that
|
||||
holds a chained kernel to gfx1201 assembly with the build's own flags (compile_commands.json) and checks each chained
|
||||
(`r4dchain`) kernel: one that has no `s_dcache_inv` must have no scalar load, from a base other than the kernel
|
||||
argument segment (s[0:1]), behind its in-kernel acquire (`global_inv` at device or system scope).
|
||||
|
||||
--list also lists the kernels that keep it, with their scalar-load counts.
|
||||
--check exits 1 when a kernel breaks that rule. Without it the kernels that skip the instruction are listed."""
|
||||
import json, sys, os, re, shlex, subprocess, concurrent.futures as cf
|
||||
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
bd, out = os.path.abspath(args[0]), os.path.abspath(args[1])
|
||||
check = "--check" in sys.argv
|
||||
os.makedirs(out, exist_ok=True)
|
||||
cc = json.load(open(bd + "/compile_commands.json"))
|
||||
units = [e for e in cc if e["file"].endswith(".hip") and
|
||||
("/libr4d/" in e["file"] or "/core/device/" in e["file"] or "/core/sched/" in e["file"])]
|
||||
|
||||
|
||||
def sregs(t):
|
||||
"""The scalar registers an operand names, [] for anything else (v, exec, vcc, an immediate)."""
|
||||
m = re.fullmatch(r"s\[(\d+):(\d+)\]", t)
|
||||
if m:
|
||||
return list(range(int(m.group(1)), int(m.group(2)) + 1))
|
||||
m = re.fullmatch(r"s(\d+)", t)
|
||||
return [int(m.group(1))] if m else []
|
||||
|
||||
|
||||
def run(e):
|
||||
a = shlex.split(e["command"])
|
||||
o = []
|
||||
i = 0
|
||||
while i < len(a):
|
||||
if a[i] == "-o":
|
||||
i += 2; continue
|
||||
if a[i] == "-c":
|
||||
i += 1; continue
|
||||
if a[i].startswith("--offload-arch=") and a[i] != "--offload-arch=gfx1201":
|
||||
i += 1; continue
|
||||
if a[i] == "--no-offload-compress":
|
||||
i += 1; continue
|
||||
o.append(a[i]); i += 1
|
||||
s = out + "/" + os.path.basename(e["file"]) + ".s"
|
||||
o += shlex.split(os.environ.get("AUDIT_FLAGS", ""))
|
||||
if "--reuse" in sys.argv and os.path.exists(s):
|
||||
return s
|
||||
o = [x for x in o if x != e["file"]] + ["--offload-device-only", "-S", "-o", s, e["file"]]
|
||||
r = subprocess.run(o, cwd=e["directory"], capture_output=True, text=True)
|
||||
if r.returncode:
|
||||
print("FAIL", e["file"], r.stderr[-400:])
|
||||
return None
|
||||
return s
|
||||
|
||||
|
||||
with cf.ThreadPoolExecutor(int(os.environ.get("J", "24"))) as ex:
|
||||
sfs = [s for s in ex.map(run, units) if s]
|
||||
bad = nk = skip = keep = 0
|
||||
for fn in sorted(sfs):
|
||||
cur = None
|
||||
rows = []
|
||||
for line in open(fn, errors="replace"):
|
||||
m = re.match(r"^(_Z\S+):\s*; @", line)
|
||||
if m:
|
||||
cur = {"name": m.group(1), "inv": 0, "dc": 0, "after": 0, "ex": [], "k": {0, 1}}
|
||||
rows.append(cur)
|
||||
continue
|
||||
if cur is None:
|
||||
continue
|
||||
s = line.strip()
|
||||
if not s or s.startswith((".", ";")):
|
||||
continue
|
||||
if s.startswith("global_inv") and ("SCOPE_DEV" in s or "SCOPE_SYS" in s):
|
||||
cur["inv"] += 1
|
||||
if s.startswith("s_dcache_inv"):
|
||||
cur["dc"] += 1
|
||||
ops = [o.strip() for o in s.split(None, 1)[1].split(",")] if " " in s else []
|
||||
op = s.split()[0]
|
||||
if op.startswith(("s_load_", "s_buffer_load_")) and len(ops) >= 2:
|
||||
if op.startswith("s_buffer"):
|
||||
base = None
|
||||
else:
|
||||
base = sregs(ops[1])
|
||||
if cur["inv"] > 0 and not (base and all(r in cur["k"] for r in base)):
|
||||
cur["after"] += 1
|
||||
if len(cur["ex"]) < 2:
|
||||
cur["ex"].append(s)
|
||||
for r in sregs(ops[0]):
|
||||
cur["k"].discard(r)
|
||||
elif ops and sregs(ops[0]) and not op.startswith(("s_cmp", "s_bitcmp", "s_wait", "s_cbranch")):
|
||||
d = sregs(ops[0])
|
||||
srcs = [sregs(o) for o in ops[1:]]
|
||||
src0 = srcs[0] if srcs else []
|
||||
derived = False
|
||||
if op in ("s_mov_b64", "s_mov_b32") and src0:
|
||||
derived = all(r in cur["k"] for r in src0)
|
||||
elif op in ("s_add_nc_u64", "s_add_u32", "s_add_co_u32", "s_add_nc_u32", "s_add_co_ci_u32", "s_addc_u32") and src0:
|
||||
derived = all(r in cur["k"] for r in src0)
|
||||
elif op == "s_cselect_b32" and src0:
|
||||
derived = all(r in cur["k"] for r in src0)
|
||||
if derived:
|
||||
cur["k"].update(d)
|
||||
elif op not in ("s_cselect_b32",) or True:
|
||||
for r in d:
|
||||
cur["k"].discard(r)
|
||||
for r in rows:
|
||||
if "r4dchain" not in r["name"]:
|
||||
continue
|
||||
nk += 1
|
||||
if r["dc"]:
|
||||
keep += 1
|
||||
if "--list" in sys.argv:
|
||||
print("keeps s_dcache_inv: %-90s scalar loads behind the acquire: %d" % (r["name"][:90], r["after"]))
|
||||
continue
|
||||
skip += 1
|
||||
if r["after"]:
|
||||
bad += 1
|
||||
print("%s skips s_dcache_inv: %-90s scalar loads behind the acquire: %d %s" %
|
||||
("BAD" if r["after"] else "ok ", r["name"][:90], r["after"], r["ex"]))
|
||||
print("chained kernels %d: keep s_dcache_inv %d, skip it %d, of those with a scalar load behind the acquire %d" %
|
||||
(nk, keep, skip, bad))
|
||||
sys.exit(1 if (check and bad) else 0)
|
||||
+412
-2
@@ -22,7 +22,7 @@
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -31,7 +31,7 @@
|
||||
#include <string>
|
||||
|
||||
using namespace rad;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
/* ------------------------------------------------------------------ the template under test */
|
||||
|
||||
@@ -164,6 +164,130 @@ TEST(hyv3_template_renders_openai_tool_schemas_and_replayed_history) {
|
||||
CHECK(prompt.prompt.find("Summarize the results.") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A template whose assistant prefix is built from the messages gets each request's own prefix,
|
||||
* never an earlier request's. */
|
||||
TEST(a_message_dependent_generation_prompt_is_not_served_from_cache) {
|
||||
ChatTemplate t;
|
||||
REQUIRE(t.load(
|
||||
"{% for m in messages %}{{ m.role + ': ' + m.content + '\\n' }}{% endfor %}"
|
||||
"{% if add_generation_prompt %}assistant-to-{{ messages[-1].content }}:{% endif %}",
|
||||
"", "") >= 0);
|
||||
auto ask = [&](const char* word) -> ChatPrompt {
|
||||
ChatPrompt p;
|
||||
json msgs = json::array({ { { "role", "user" }, { "content", word } } });
|
||||
CHECK(t.apply(msgs, json(), ChatOptions(), &p) >= 0);
|
||||
return p;
|
||||
};
|
||||
const ChatPrompt a = ask("alpha");
|
||||
CHECK_EQ(a.generation_prompt, std::string("assistant-to-alpha:"));
|
||||
CHECK(a.prompt.ends_with(a.generation_prompt));
|
||||
const ChatPrompt b = ask("beta");
|
||||
CHECK_EQ(b.generation_prompt, std::string("assistant-to-beta:"));
|
||||
CHECK(b.prompt.ends_with(b.generation_prompt));
|
||||
const ChatPrompt a2 = ask("alpha");
|
||||
CHECK_EQ(a2.generation_prompt, std::string("assistant-to-alpha:"));
|
||||
CHECK_EQ(a2.prompt, a.prompt);
|
||||
}
|
||||
|
||||
/* A generation prompt that depends on how many messages there are, ahead of a fixed tail: each
|
||||
* request's is its own, whatever an earlier request with fewer messages rendered. */
|
||||
TEST(a_generation_prompt_counted_from_the_messages_follows_each_request) {
|
||||
ChatTemplate t;
|
||||
REQUIRE(t.load(
|
||||
"{% for m in messages %}{{ m.role + ': ' + m.content + '\\n' }}{% endfor %}"
|
||||
"{% if add_generation_prompt %}{% if messages|length > 4 %}[short]{% endif %}"
|
||||
"assistant:{% endif %}",
|
||||
"", "") >= 0);
|
||||
auto ask = [&](int n) -> ChatPrompt {
|
||||
ChatPrompt p;
|
||||
json msgs = json::array();
|
||||
for (int i = 0; i < n; ++i)
|
||||
msgs.push_back({ { "role", i % 2 ? "assistant" : "user" }, { "content", "m" } });
|
||||
CHECK(t.apply(msgs, json(), ChatOptions(), &p) >= 0);
|
||||
return p;
|
||||
};
|
||||
CHECK_EQ(ask(1).generation_prompt, std::string("assistant:"));
|
||||
CHECK_EQ(ask(5).generation_prompt, std::string("[short]assistant:"));
|
||||
CHECK_EQ(ask(1).generation_prompt, std::string("assistant:"));
|
||||
}
|
||||
|
||||
/* Strings built by concatenation compare, look up and test membership by their text, whatever
|
||||
* pieces they were built from (an empty piece included). */
|
||||
TEST(a_concatenated_string_equals_its_text) {
|
||||
ChatTemplate t;
|
||||
REQUIRE(t.load(
|
||||
"{% set k = 'x' ~ '' %}{% set e = '' ~ '' %}"
|
||||
"{{ 'eq' if k == 'x' else 'ne' }} {{ 'eq' if e == '' else 'ne' }} "
|
||||
"{{ {'x': 1}[k] }} {{ 'in' if k in {'x': 1} else 'out' }}"
|
||||
"{% for m in messages %}{% endfor %}",
|
||||
"", "") >= 0);
|
||||
ChatPrompt p;
|
||||
json msgs = json::array({ { { "role", "user" }, { "content", "hi" } } });
|
||||
CHECK(t.apply(msgs, json(), ChatOptions(), &p) >= 0);
|
||||
CHECK(p.prompt.find("eq eq 1 in") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Tool-call arguments sent as an object reach a template that only takes them as text as their
|
||||
* compact JSON, as when the request sent that text. */
|
||||
TEST(a_refused_request_cannot_grow_an_unbounded_dom_in_its_tool_call_arguments) {
|
||||
/* bad_arguments runs on the !served path -- template refused, merge refused -- and probes the
|
||||
* arguments strings as JSON to name the offender. Probing with the unbounded parser let a
|
||||
* client that had already failed the template hand the probe a few million flat values to
|
||||
* grow into a DOM nothing would read. The probe is bounded now; these bounds reject the
|
||||
* oversized and over-deep strings as the refusal they name, and a real call is unaffected. */
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(
|
||||
"{%- for m in messages %}"
|
||||
"{%- if m.role == 'system' and not loop.first %}"
|
||||
"{{- raise_exception('System message must be at the beginning.') }}{%- endif %}"
|
||||
"{%- if m.role == 'user' and m.content == 'boom' %}{{- raise_exception('no boom') }}{%- endif %}"
|
||||
"<{{ m.role }}>{{ m.content }}</{{ m.role }}>"
|
||||
"{%- endfor %}", "", ""));
|
||||
ChatOptions opt;
|
||||
opt.quiet = true;
|
||||
auto with_args = [](const std::string& args) {
|
||||
return json::parse(R"([{"role":"system","content":"s1"},{"role":"system","content":"s2"},)"
|
||||
R"({"role":"user","content":"boom"},)"
|
||||
R"({"role":"assistant","content":"","tool_calls":[{"id":"c","type":"function",)"
|
||||
R"("function":{"name":"f","arguments":)" + json(args).dump() + R"(}}]}])");
|
||||
};
|
||||
ChatPrompt huge_p;
|
||||
std::string many = "[";
|
||||
for (int v = 0; v < 1100000; ++v) many += v ? ",1" : "1";
|
||||
many += "]";
|
||||
const int huge_rc = t.apply(with_args(many), json(), opt, &huge_p);
|
||||
CHECK(huge_rc < 0);
|
||||
CHECK(huge_p.error.find("carries far more values") != std::string::npos);
|
||||
ChatPrompt deep_p;
|
||||
CHECK(t.apply(with_args(std::string(1200, '[') + std::string(1200, ']')), json(), opt, &deep_p) < 0);
|
||||
CHECK(deep_p.error.find("nests far deeper") != std::string::npos);
|
||||
/* An honest refusal of an honest call still comes back in the template's own words. */
|
||||
ChatPrompt ok_p;
|
||||
CHECK(t.apply(with_args("{\"z\":1}"), json(), opt, &ok_p) < 0);
|
||||
CHECK(ok_p.error.find("chat template refused") != std::string::npos);
|
||||
CHECK(ok_p.error.find("function.arguments") == std::string::npos);
|
||||
}
|
||||
|
||||
TEST(object_arguments_reach_a_string_only_template_as_compact_json) {
|
||||
ChatTemplate t;
|
||||
REQUIRE(t.load(
|
||||
"{% for m in messages %}{% if m.tool_calls %}"
|
||||
"{{ '[' + m.tool_calls[0].function.arguments + ']' }}"
|
||||
"{% else %}{{ m.role + ': ' + m.content }}{% endif %}{% endfor %}",
|
||||
"", "") >= 0);
|
||||
json call = { { "id", "c1" }, { "type", "function" },
|
||||
{ "function", { { "name", "f" },
|
||||
{ "arguments", { { "z", 1 }, { "a", 100000.0 } } } } } };
|
||||
json msgs = json::array({ { { "role", "user" }, { "content", "go" } },
|
||||
{ { "role", "assistant" }, { "content", "" },
|
||||
{ "tool_calls", json::array({ call }) } } });
|
||||
ChatPrompt p;
|
||||
ChatOptions opt;
|
||||
opt.add_generation_prompt = false;
|
||||
CHECK(t.apply(msgs, json(), opt, &p) >= 0);
|
||||
CHECK(p.prompt.find("[{\"z\":1,\"a\":100000.0}]") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Render one turn, passing `effort` as the template's reasoning_effort when set. */
|
||||
static int render_turn(ChatPrompt* p, bool with_tools, const char* effort) {
|
||||
json msgs = json::array();
|
||||
@@ -265,6 +389,65 @@ TEST(replayed_tool_call_arguments_render_as_parameter_xml) {
|
||||
/* The raw JSON string must not survive. The needle is the exact string sent, spaces
|
||||
* included, because the tool schema in the preamble legitimately contains `"path":`. */
|
||||
CHECK(p.prompt.find("{\"path\": \"/work/a.py\"") == std::string::npos);
|
||||
|
||||
/* The same call replayed flat -- no `function` wrapper, no `type` -- renders the same
|
||||
* prompt, as a call whose arguments were never sent renders with an empty object. */
|
||||
json flat = msgs;
|
||||
flat[1]["tool_calls"] = json::array({ json{
|
||||
{ "id", "c1" }, { "name", "read" },
|
||||
{ "arguments", "{\"path\": \"/work/a.py\", \"limit\": 40}" } } });
|
||||
ChatPrompt pf;
|
||||
CHECK_OK(qwen().t->apply(flat, tools_json(), opt, &pf));
|
||||
CHECK_EQ(pf.prompt, p.prompt);
|
||||
json bare = msgs;
|
||||
bare[1]["tool_calls"] = json::array({ json{ { "id", "c1" }, { "name", "read" } } });
|
||||
ChatPrompt pb;
|
||||
CHECK_OK(qwen().t->apply(bare, tools_json(), opt, &pb));
|
||||
CHECK(pb.prompt.find("<function=read>") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A tool-call round in the current turn, as a client replays it, with the call's arguments as
|
||||
* `args` (absent when null). */
|
||||
static json replayed_round(const json* args) {
|
||||
json fn = {{"name", "read"}};
|
||||
if (args) fn["arguments"] = *args;
|
||||
json msgs = json::array();
|
||||
msgs.push_back({{"role", "user"}, {"content", "Read /work/a.py."}});
|
||||
msgs.push_back({{"role", "assistant"}, {"content", ""},
|
||||
{"tool_calls", json::array({{{"id", "c1"}, {"type", "function"},
|
||||
{"function", fn}}})}});
|
||||
msgs.push_back({{"role", "tool"}, {"tool_call_id", "c1"}, {"content", "print(1)\n"}});
|
||||
return msgs;
|
||||
}
|
||||
|
||||
/* A call without arguments, replayed as "" (a stored stream) or with no `arguments`, is the
|
||||
* empty object. Refusing it refused every later turn of the conversation. */
|
||||
TEST(a_replayed_call_with_empty_or_absent_arguments_is_the_empty_object) {
|
||||
if (!qwen().need()) return;
|
||||
const json empty = "", spaces = " \n", obj = "{}";
|
||||
ChatPrompt want;
|
||||
ChatOptions opt;
|
||||
CHECK_OK(qwen().t->apply(replayed_round(&obj), tools_json(), opt, &want));
|
||||
CHECK(want.prompt.find("<function=read>\n</function>") != std::string::npos);
|
||||
for (const json* a : {&empty, &spaces, (const json*)nullptr}) {
|
||||
ChatPrompt p;
|
||||
CHECK_OK(qwen().t->apply(replayed_round(a), tools_json(), opt, &p));
|
||||
CHECK_EQ(p.prompt, want.prompt);
|
||||
}
|
||||
}
|
||||
|
||||
/* Arguments that are not JSON are still refused, but as the request's fault and naming the call,
|
||||
* not as a refusal by the template. */
|
||||
TEST(replayed_arguments_that_are_not_json_are_refused_naming_the_call) {
|
||||
if (!qwen().need()) return;
|
||||
const json bad = "{\"path\": \"/work/a.py\"";
|
||||
ChatPrompt p;
|
||||
ChatOptions opt;
|
||||
opt.quiet = true;
|
||||
CHECK_EQ(qwen().t->apply(replayed_round(&bad), tools_json(), opt, &p), (int)RAD_E_INVAL);
|
||||
CHECK(p.error.find("messages[1].tool_calls[0].function.arguments is not JSON") !=
|
||||
std::string::npos);
|
||||
CHECK(p.error.find("template") == std::string::npos);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ golden renders
|
||||
@@ -950,6 +1133,50 @@ TEST(mc_a_reply_with_no_call_is_just_content) {
|
||||
* report tool support for a template without it.
|
||||
*/
|
||||
|
||||
/* The template is container data and the engine parses and runs it. Both sides of that had no
|
||||
* budget: the parser recursed once per nesting paren/block -- tens of KB of brackets in a
|
||||
* container's tokenizer.chat_template was an uncatchable stack overflow of the probe or the
|
||||
* first render -- and range() materialised one value per step, so {{ range(4000000000) }} was
|
||||
* an OOM per render. The budgets refuse; the refusals cross this seam as the error values the
|
||||
* block above promises, and templates past any real nesting still render. */
|
||||
TEST(template_budgets_refuse_as_values_never_as_crashes) {
|
||||
json msgs = json::array();
|
||||
msgs.push_back({{"role", "user"}, {"content", "x"}});
|
||||
ChatOptions opt;
|
||||
opt.add_generation_prompt = true;
|
||||
ChatPrompt p;
|
||||
|
||||
ChatTemplate parens;
|
||||
const std::string deep = "{{ " + std::string(5000, '(') + "1" + std::string(5000, ')') + " }}";
|
||||
CHECK(parens.load(deep, "", "") < 0 || parens.apply(msgs, json(), opt, &p) < 0);
|
||||
|
||||
ChatTemplate ifs;
|
||||
std::string nested;
|
||||
for (int i = 0; i < 5000; ++i) nested += "{% if 1 %}";
|
||||
nested += "ok";
|
||||
for (int i = 0; i < 5000; ++i) nested += "{% endif %}";
|
||||
CHECK(ifs.load(nested, "", "") < 0 || ifs.apply(msgs, json(), opt, &p) < 0);
|
||||
|
||||
/* The engine constant-folds at load, so the huge range is refused at load already; the
|
||||
* seam's promise is that SOME step refuses with an error value -- same shape as above. */
|
||||
ChatTemplate big;
|
||||
CHECK(big.load("{{ range(4000000000)|length }}", "", "") < 0 ||
|
||||
big.apply(msgs, json(), opt, &p) < 0);
|
||||
|
||||
/* Repetition is range()'s sibling: "x" * 4e9 materialised a byte per step. The cap
|
||||
* refuses at load or at render -- the seam still answers with a value, never memory. */
|
||||
ChatTemplate rep;
|
||||
CHECK(rep.load("{{ 'x' * 4000000000 }}", "", "") < 0 ||
|
||||
rep.apply(msgs, json(), opt, &p) < 0);
|
||||
|
||||
/* The shape no real template reaches is refused; what real ones do still renders. */
|
||||
ChatTemplate sane;
|
||||
CHECK_OK(sane.load("A{{ (((1))) }}{% if 1 %}{% if 1 %}B{% endif %}{% endif %}{{ range(10)|length }}",
|
||||
"", ""));
|
||||
CHECK_OK(sane.apply(msgs, json(), opt, &p));
|
||||
CHECK(p.prompt.find("A1B10") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(an_empty_template_is_the_chatml_fallback_and_says_which_one_it_is) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load("", "", ""));
|
||||
@@ -1004,6 +1231,105 @@ TEST(chatml_renders_every_turn_in_order_and_marks_the_assistant_prefix) {
|
||||
p.generation_prompt.size(), p.generation_prompt), 0);
|
||||
}
|
||||
|
||||
/* `reasoning` is the field name vLLM and its router use for an assistant turn's reasoning;
|
||||
* `reasoning_content` is the llama.cpp spelling the templates read. A request replayed
|
||||
* through such a router arrives with only `reasoning`, and the reasoning must still reach
|
||||
* the template: without it the rendered history differs from the tokens that were
|
||||
* generated, so no prefix cache can match it and the model loses its own earlier reasoning. */
|
||||
TEST(a_replayed_reasoning_field_reaches_the_template_as_reasoning_content) {
|
||||
ChatTemplate t;
|
||||
REQUIRE(t.load(
|
||||
"{% for m in messages %}{{ m.role + '<' + "
|
||||
"(m.reasoning_content if m.reasoning_content is string else '') + '>' + m.content + ';' }}"
|
||||
"{% endfor %}",
|
||||
"", "") >= 0);
|
||||
auto ask = [&](const json& assistant) -> ChatPrompt {
|
||||
ChatPrompt p;
|
||||
json msgs = json::array({
|
||||
{ { "role", "user" }, { "content", "q" } },
|
||||
assistant,
|
||||
{ { "role", "user" }, { "content", "next" } },
|
||||
});
|
||||
CHECK(t.apply(msgs, json(), ChatOptions(), &p) >= 0);
|
||||
return p;
|
||||
};
|
||||
const ChatPrompt canonical = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" }, { "reasoning_content", "thought" } });
|
||||
CHECK_EQ(canonical.prompt, std::string("user<>q;assistant<thought>a;user<>next;"));
|
||||
|
||||
/* The alias renders exactly as the canonical spelling does. */
|
||||
const ChatPrompt aliased = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" }, { "reasoning", "thought" } });
|
||||
CHECK_EQ(aliased.prompt, canonical.prompt);
|
||||
|
||||
/* Both spellings present: the canonical one the template reads wins. */
|
||||
const ChatPrompt both = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning_content", "thought" }, { "reasoning", "other" } });
|
||||
CHECK_EQ(both.prompt, canonical.prompt);
|
||||
|
||||
/* A non-string `reasoning` (a flag or an effort object in other APIs) is not reasoning
|
||||
* text: it renders as none rather than refusing the request. */
|
||||
const ChatPrompt flag = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" }, { "reasoning", true } });
|
||||
CHECK_EQ(flag.prompt, std::string("user<>q;assistant<>a;user<>next;"));
|
||||
const ChatPrompt effort = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning", { { "effort", "low" } } } });
|
||||
CHECK_EQ(effort.prompt, flag.prompt);
|
||||
|
||||
/* Null or empty canonical fields are the serializers beside a router at work, not a
|
||||
* refusal: the alias fills them, and a lone null renders as no reasoning. */
|
||||
const ChatPrompt null_alias = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning_content", nullptr }, { "reasoning", "thought" } });
|
||||
CHECK_EQ(null_alias.prompt, canonical.prompt);
|
||||
const ChatPrompt null_only = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" }, { "reasoning_content", nullptr } });
|
||||
CHECK_EQ(null_only.prompt, flag.prompt);
|
||||
const ChatPrompt empty_alias = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning_content", "" }, { "reasoning", "thought" } });
|
||||
CHECK_EQ(empty_alias.prompt, canonical.prompt);
|
||||
|
||||
/* The other carriers: a `thinking` field, OpenRouter's details (their text, never the
|
||||
* text and its summary both), and a thinking content part. */
|
||||
const ChatPrompt thinking = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" }, { "thinking", "thought" } });
|
||||
CHECK_EQ(thinking.prompt, canonical.prompt);
|
||||
const ChatPrompt details = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning_details", json::array({
|
||||
{ { "type", "reasoning.summary" }, { "summary", "short" } },
|
||||
{ { "type", "reasoning.text" }, { "text", "thought" } },
|
||||
{ { "type", "reasoning.encrypted" }, { "data", "opaque" } } }) } });
|
||||
CHECK_EQ(details.prompt, canonical.prompt);
|
||||
const ChatPrompt summary_only = ask(json{
|
||||
{ "role", "assistant" }, { "content", "a" },
|
||||
{ "reasoning_details", json::array({
|
||||
{ { "type", "reasoning.summary" }, { "summary", "thought" } } }) } });
|
||||
CHECK_EQ(summary_only.prompt, canonical.prompt);
|
||||
const ChatPrompt part = ask(json{
|
||||
{ "role", "assistant" },
|
||||
{ "content", json::array({
|
||||
{ { "type", "thinking" }, { "thinking", "thought" } },
|
||||
{ { "type", "output_text" }, { "text", "a" } } }) } });
|
||||
CHECK_EQ(part.prompt, canonical.prompt);
|
||||
|
||||
/* Two replayed turns keep their own reasoning, in order. */
|
||||
ChatPrompt two;
|
||||
json msgs = json::array({
|
||||
{ { "role", "user" }, { "content", "q" } },
|
||||
{ { "role", "assistant" }, { "content", "a" }, { "reasoning", "first" } },
|
||||
{ { "role", "user" }, { "content", "next" } },
|
||||
{ { "role", "assistant" }, { "content", "b" }, { "reasoning_content", "second" } },
|
||||
{ { "role", "user" }, { "content", "last" } },
|
||||
});
|
||||
CHECK(t.apply(msgs, json(), ChatOptions(), &two) >= 0);
|
||||
CHECK_EQ(two.prompt,
|
||||
std::string("user<>q;assistant<first>a;user<>next;assistant<second>b;user<>last;"));
|
||||
}
|
||||
|
||||
TEST(without_a_generation_prompt_nothing_is_appended_for_the_assistant) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(ChatTemplate::chatml_source(), "", ""));
|
||||
@@ -1112,6 +1438,68 @@ TEST(a_dotted_integer_is_an_index_as_in_jinja2) {
|
||||
CHECK_EQ(p.prompt, std::string("hi|assistant"));
|
||||
}
|
||||
|
||||
/* jinja2's unique: first occurrences in order, strings folded unless case_sensitive, by attribute
|
||||
* where one is given. GLM-5.3-Flash's template checks its tool-call ids with it; while the filter
|
||||
* threw, the capability probe reported the model as having no tool support. */
|
||||
TEST(unique_keeps_first_occurrences_as_jinja2_does) {
|
||||
auto render = [](const char* expr) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(std::string("{{ ") + expr + " }}", "", ""));
|
||||
json msgs = json::array();
|
||||
msgs.push_back({{"role", "user"}, {"content", "hi"}});
|
||||
ChatPrompt p;
|
||||
ChatOptions opt;
|
||||
opt.add_generation_prompt = false;
|
||||
CHECK_OK(t.apply(msgs, json(), opt, &p));
|
||||
return p.prompt;
|
||||
};
|
||||
CHECK_EQ(render("['a','b','a','c','b'] | unique | list"), std::string("['a', 'b', 'c']"));
|
||||
CHECK_EQ(render("['a','A','b'] | unique | list"), std::string("['a', 'b']"));
|
||||
CHECK_EQ(render("['a','A','b'] | unique(case_sensitive=true) | list"),
|
||||
std::string("['a', 'A', 'b']"));
|
||||
CHECK_EQ(render("[3,1,3,2,1] | unique | list"), std::string("[3, 1, 2]"));
|
||||
CHECK_EQ(render("[] | unique | list"), std::string("[]"));
|
||||
CHECK_EQ(render("[{'n':'x','v':1},{'n':'X','v':2},{'n':'y','v':3}] | unique(attribute='n') "
|
||||
"| map(attribute='v') | list"),
|
||||
std::string("[1, 3]"));
|
||||
CHECK_EQ(render("[1,'1',1] | unique | list | length"), std::string("2"));
|
||||
|
||||
/* The duplicate-id check of GLM-5.3-Flash's template, in a template that declares tools. */
|
||||
ChatTemplate glm;
|
||||
CHECK_OK(glm.load(
|
||||
"{%- if tools %}<tools>{% for t in tools %}{{ t.function.name }};{% endfor %}</tools>{% endif %}"
|
||||
"{%- set ns = namespace(ids=[]) %}"
|
||||
"{%- for m in messages %}"
|
||||
"{%- if m.tool_calls %}{% for c in m.tool_calls %}{% set ns.ids = ns.ids + [c.id] %}"
|
||||
"<call>{{ c.function.name }}:{{ c.function.arguments | tojson }}</call>{% endfor %}{% endif %}"
|
||||
"<{{ m.role }}>{{ m.content }}</{{ m.role }}>"
|
||||
"{%- endfor %}"
|
||||
"{%- if ns.ids | unique(case_sensitive=true) | list | length != ns.ids | length %}"
|
||||
"{{- raise_exception('duplicate tool call id') }}{%- endif %}"
|
||||
"{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
|
||||
CHECK(glm.caps().tools);
|
||||
CHECK(glm.caps().tool_calls);
|
||||
CHECK(glm.caps().probe_error.empty());
|
||||
}
|
||||
|
||||
/* A tool-bearing probe that throws is reported: the template below declares tools and calls a
|
||||
* filter no Jinja has, which the probe alone would report as a model without tool support. */
|
||||
TEST(a_tool_probe_that_throws_says_what_it_threw) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(
|
||||
"{%- if tools %}<tools>{{ tools | no_such_filter }}</tools>{% endif %}"
|
||||
"{%- for m in messages %}<{{ m.role }}>{{ m.content }}</{{ m.role }}>{%- endfor %}"
|
||||
"{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
|
||||
CHECK(!t.caps().tools);
|
||||
CHECK(t.caps().probe_error.find("no_such_filter") != std::string::npos);
|
||||
|
||||
ChatTemplate plain;
|
||||
CHECK_OK(plain.load(
|
||||
"{%- for m in messages %}<{{ m.role }}>{{ m.content }}</{{ m.role }}>{%- endfor %}"
|
||||
"{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
|
||||
CHECK(plain.caps().probe_error.empty());
|
||||
}
|
||||
|
||||
/* A template that takes one system message, first, as many do, against conversations the Chat
|
||||
* Completions API allows: a system message after a user turn, and two at the head. They are
|
||||
* rendered with the system messages merged, in order, into one at the head. Any other
|
||||
@@ -1140,6 +1528,28 @@ TEST(system_messages_a_template_takes_only_first_are_merged_at_the_head) {
|
||||
&d) < 0);
|
||||
CHECK(d.error.find("no boom") != std::string::npos);
|
||||
CHECK(d.error.find("Unable to generate parser") == std::string::npos);
|
||||
|
||||
/* The merged retry renders the aliased messages: replayed reasoning under its other
|
||||
* name survives the merge exactly as the canonical spelling does. */
|
||||
ChatTemplate tr;
|
||||
CHECK_OK(tr.load(
|
||||
"{%- for m in messages %}"
|
||||
"{%- if m.role == 'system' and not loop.first %}"
|
||||
"{{- raise_exception('System message must be at the beginning.') }}{%- endif %}"
|
||||
"<{{ m.role }}>{{ m.reasoning_content if m.reasoning_content is string else '' }}"
|
||||
"{{ m.content }}</{{ m.role }}>"
|
||||
"{%- endfor %}", "", ""));
|
||||
ChatPrompt e, f;
|
||||
CHECK_OK(tr.apply(json::parse(
|
||||
R"([{"role":"user","content":"hi"},{"role":"system","content":"s"},)"
|
||||
R"({"role":"assistant","content":"a","reasoning":"thought"},)"
|
||||
R"({"role":"user","content":"next"}])"), json(), opt, &e));
|
||||
CHECK_OK(tr.apply(json::parse(
|
||||
R"([{"role":"user","content":"hi"},{"role":"system","content":"s"},)"
|
||||
R"({"role":"assistant","content":"a","reasoning_content":"thought"},)"
|
||||
R"({"role":"user","content":"next"}])"), json(), opt, &f));
|
||||
CHECK_EQ(e.prompt, f.prompt);
|
||||
CHECK(e.prompt.find("thought") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value;
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
@@ -43,7 +43,22 @@
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::chatdiff;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
/* v with every object's members in key order, so two values compare whatever order their keys
|
||||
* were written in. */
|
||||
static json keys_sorted(const json& v) {
|
||||
if (v.is_array()) {
|
||||
json out = json::array();
|
||||
for (const json& e : v) out.push_back(keys_sorted(e));
|
||||
return out;
|
||||
}
|
||||
if (!v.is_object()) return v;
|
||||
std::vector<std::pair<std::string, json>> m;
|
||||
for (auto it = v.begin(); it != v.end(); ++it) m.emplace_back(it.key(), keys_sorted(it.value()));
|
||||
std::sort(m.begin(), m.end(), [](const auto& a, const auto& b) { return a.first < b.first; });
|
||||
return json(json::object_t(std::move(m)));
|
||||
}
|
||||
|
||||
/* ================================================================== fixtures */
|
||||
|
||||
@@ -257,8 +272,8 @@ TEST(rendered_replies_read_back_as_the_template_wrote_them) {
|
||||
CHECK_EQ(m.calls[i].name, want["name"].get<std::string>());
|
||||
CHECK(m.calls[i].closed);
|
||||
/* Compared as values: the template writes keys in sorted order. */
|
||||
CHECK(nlohmann::json::parse(m.calls[i].arguments) ==
|
||||
nlohmann::json::parse(want["arguments"].get<std::string>()));
|
||||
CHECK(keys_sorted(Json::parse(m.calls[i].arguments)) ==
|
||||
keys_sorted(Json::parse(want["arguments"].get<std::string>())));
|
||||
}
|
||||
const std::string r = msg.contains("reasoning_content") ? msg["reasoning_content"].get<std::string>() : "";
|
||||
CHECK_EQ(m.reasoning, r.empty() ? r : r + "\n");
|
||||
@@ -842,7 +857,9 @@ TEST(the_chat_bridge_serves_gemma_from_its_declaration) {
|
||||
server::ChatRender r;
|
||||
std::string why;
|
||||
const json msgs = json::array({ { { "role", "user" }, { "content", "List /work." } } });
|
||||
REQUIRE_EQ(br.apply(msgs, agent_tools(), opt, &r, &why), RAD_OK);
|
||||
REQUIRE_EQ(br.apply(msgs, agent_tools(), opt, &r,
|
||||
&why),
|
||||
RAD_OK);
|
||||
CHECK_EQ(r.generation_prompt, kOff);
|
||||
CHECK(r.grammar_lazy);
|
||||
REQUIRE_EQ(r.grammar_triggers.size(), (size_t)1);
|
||||
|
||||
+243
-7
@@ -32,9 +32,11 @@
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
|
||||
#include <arch/rad_museglimmer_chat.h>
|
||||
#include <arch/rad_deepseek41_chat.h>
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -52,7 +54,7 @@
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::chatdiff;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
/* ================================================================== fixtures */
|
||||
|
||||
@@ -1326,7 +1328,7 @@ TEST(a_tool_name_holding_the_format_delimiter_is_refused_at_admission) {
|
||||
*
|
||||
* What a streaming client assembles from the SSE chunks (content, reasoning, each call's id, name
|
||||
* and arguments) equals the buffered answer, for every reply cut a byte at a time. Delta chunks
|
||||
* are written directly rather than through a JSON tree, and must match nlohmann's bytes. */
|
||||
* are written directly rather than through a JSON tree, and must match the DOM writer's bytes. */
|
||||
TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
|
||||
for (const Model& m : models()) {
|
||||
Bench* b = bench(m, ChatRequest{});
|
||||
@@ -1420,7 +1422,8 @@ static server::ChatRender bridge_render(const server::ChatTemplateBridge& br, co
|
||||
server::ChatRender out;
|
||||
std::string w;
|
||||
const json msgs = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } });
|
||||
if (br.apply(msgs, tools, opt, &out, why ? why : &w) < 0) out.prompt.clear();
|
||||
if (br.apply(msgs, tools, opt, &out, why ? why : &w) < 0)
|
||||
out.prompt.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1476,6 +1479,39 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) {
|
||||
}
|
||||
|
||||
/* The declared format preserves HYV3's outer section and all of its argument markers. */
|
||||
/* A container that names the tool-call close end-of-generation cannot serve a second call, or
|
||||
* a reply that quotes the tag: the turn ends the moment the call does. The bridge finds the ids
|
||||
* this format writes as its own delimiters and the engine drops them from the stop set, leaving
|
||||
* the real turn terminator alone. */
|
||||
TEST(a_call_delimiter_is_not_a_turn_terminator) {
|
||||
VocabBuild vb;
|
||||
vb.tokens = { "a", "<|im_end|>", "<tool_call>", "</tool_call>" };
|
||||
vb.types = { RAD_TT_NORMAL, RAD_TT_CONTROL, RAD_TT_CONTROL, RAD_TT_CONTROL };
|
||||
vb.eos = 1;
|
||||
vb.eos_ids = { 3 }; /* the close, declared terminal by the container */
|
||||
vb.chat_template = fixture("glm53");
|
||||
auto v = std::make_shared<Vocab>();
|
||||
REQUIRE(v->load(std::move(vb)) >= 0);
|
||||
REQUIRE(v->is_eog(3));
|
||||
|
||||
server::ChatTemplateBridge br;
|
||||
REQUIRE(br.init(*v) >= 0);
|
||||
CHECK(br.supports_tools());
|
||||
REQUIRE(br.eog_call_markers().size() == 1);
|
||||
CHECK_EQ(br.eog_call_markers()[0], 3);
|
||||
/* The terminator the template writes stays one; the engine demotes only what the bridge
|
||||
* reports (core/engine.cpp). */
|
||||
CHECK(v->is_eog(1));
|
||||
|
||||
/* A template with no tool calls has no call delimiters to report. */
|
||||
std::shared_ptr<Vocab> plain_v = vocab_with("");
|
||||
REQUIRE(plain_v != nullptr);
|
||||
server::ChatTemplateBridge plain;
|
||||
REQUIRE(plain.init(*plain_v) >= 0);
|
||||
CHECK(!plain.supports_tools());
|
||||
CHECK(plain.eog_call_markers().empty());
|
||||
}
|
||||
|
||||
TEST(hyv3_plugin_format_runs_through_the_chat_template_bridge) {
|
||||
std::shared_ptr<Vocab> v = vocab_with(fixture("hyv3"));
|
||||
REQUIRE(v != nullptr);
|
||||
@@ -1522,7 +1558,8 @@ TEST(hyv3_plugin_format_splits_requested_reasoning_before_native_tools) {
|
||||
opt.template_kwargs["reasoning_effort"] = json("high").dump();
|
||||
server::ChatRender out;
|
||||
std::string why;
|
||||
CHECK_OK(br.apply(msgs, agent_tools(), opt, &out, &why));
|
||||
CHECK_OK(br.apply(msgs, agent_tools(), opt, &out,
|
||||
&why));
|
||||
REQUIRE(out.parser != nullptr);
|
||||
CHECK(out.generation_prompt.ends_with("<think>"));
|
||||
auto rd = out.parser->open();
|
||||
@@ -2377,6 +2414,78 @@ TEST(glm53_derives_a_name_the_opener_opens) {
|
||||
CHECK(why.find("name_suffix") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Ling 3.0's template ends the function name with a newline and only then writes the argument
|
||||
* tags, so the analysis derives a name_suffix of whitespace alone. The reader treats that as the
|
||||
* suffixless ending -- the name stops at the first argument tag, whitespace trimmed -- while the
|
||||
* grammar keeps the newline the template writes. Before it was allowed, every request carrying
|
||||
* tools was refused: "name_suffix must end the function name with something besides
|
||||
* whitespace". */
|
||||
TEST(ling3_reads_a_name_that_ends_at_whitespace) {
|
||||
ChatFormat f;
|
||||
std::string why, refused;
|
||||
CHECK_OK(chat_format_from_template(fixture("ling3"), "", "<|role_end|>", &f, &refused, &why));
|
||||
CHECK(refused.empty());
|
||||
/* The spellings of this shape are pinned by glm53_derives_a_name_the_opener_opens; Ling's
|
||||
* difference is the newline between the name and the first argument tag. */
|
||||
CHECK(f.call_open.empty() && f.call_close.empty());
|
||||
CHECK(!f.name_prefix.empty() && f.name_prefix[0] == '<');
|
||||
CHECK(!f.name_suffix.empty() &&
|
||||
f.name_suffix.find_first_not_of(" \t\r\n") == std::string::npos);
|
||||
CHECK(!f.call_end.empty());
|
||||
CHECK(!f.arg_prefix.empty() && !f.arg_name_suffix.empty() && !f.arg_value_prefix.empty() &&
|
||||
!f.arg_value_suffix.empty());
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &agent_tools();
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
CHECK(g.lazy);
|
||||
CHECK(!g.trigger_words.empty());
|
||||
|
||||
/* A reply built the way the template writes it reads back as the calls it renders, newline
|
||||
* after the name and no whitespace between one argument's close and the next argument's
|
||||
* tag. */
|
||||
std::string reply = "Look.";
|
||||
auto arg = [&](const std::string& k, const std::string& v) {
|
||||
return f.arg_prefix + k + f.arg_name_suffix + f.arg_value_prefix + v + f.arg_value_suffix;
|
||||
};
|
||||
reply += f.name_prefix + "read" + f.name_suffix + arg("path", "/a") + arg("limit", "3") +
|
||||
f.call_end;
|
||||
reply += f.name_prefix + "ping" + f.name_suffix + f.call_end;
|
||||
|
||||
ReplyOptions ro;
|
||||
ro.tools = &agent_tools();
|
||||
ro.terminators = { "<|role_end|>" };
|
||||
const std::shared_ptr<const ReplyParser> p = parser_of(f, ro);
|
||||
REQUIRE(p != nullptr);
|
||||
bool strict = false;
|
||||
const ReplyMessage m = reply_parse(*p, reply, &strict);
|
||||
CHECK_EQ(m.content, std::string("Look."));
|
||||
REQUIRE(m.calls.size() == 2);
|
||||
CHECK_EQ(m.calls[0].name, std::string("read"));
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":3}"));
|
||||
CHECK(m.calls[0].closed);
|
||||
CHECK_EQ(m.calls[1].name, std::string("ping"));
|
||||
CHECK(m.calls[1].closed);
|
||||
CHECK(strict);
|
||||
const std::string stream_error = stream_all(*p, reply);
|
||||
if (!stream_error.empty()) ::radtest::fail(__FILE__, __LINE__, stream_error);
|
||||
}
|
||||
|
||||
/* The relaxation is for the tagged family only: an object family's name ends at its `{`, so a
|
||||
* whitespace suffix there still describes a format nothing reads. */
|
||||
TEST(a_whitespace_name_suffix_is_refused_for_object_arguments) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why));
|
||||
CHECK(f.object_args());
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
f.name_suffix = "\n";
|
||||
CHECK(chat_format_check(f, &why) < 0);
|
||||
CHECK(why.find("whitespace") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(glm53_replies_read_back_as_the_messages_they_render) {
|
||||
const Glm* g = glm();
|
||||
REQUIRE(g != nullptr);
|
||||
@@ -2579,8 +2688,11 @@ static double stream_bytes(const ReplyParser& p, const std::string& text, size_t
|
||||
return seconds_to([&] {
|
||||
std::unique_ptr<ReplyStream> s = p.open();
|
||||
std::vector<ReplyEvent> ev;
|
||||
/* The clock only when a call's time is asked for: on a host whose clocksource is HPET
|
||||
* (the TSC marked unstable) a read is a system call of about a microsecond, as much as
|
||||
* the feed it would time. */
|
||||
for (size_t at = 0; at < text.size(); at += piece) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const auto t0 = per_call ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
|
||||
s->feed(std::string_view(text).substr(at, std::min(piece, text.size() - at)), &ev);
|
||||
if (per_call)
|
||||
per_call->push_back(std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
|
||||
@@ -2663,5 +2775,129 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
/* ================================================================== Muse's channels
|
||||
*
|
||||
* The model opens its own channel after `<|start|>assistant`: ` to=self<|message|>` reasoning
|
||||
* first, or ` to=user<|message|>` straight into the answer when it does not reason
|
||||
* (arch/rad_museglimmer_chat.h). The header of an answer that follows reasoning is reasoning_close's;
|
||||
* the header of an answer that does not is content_open's. */
|
||||
|
||||
static std::shared_ptr<const ReplyParser> muse_parser(bool tools, bool extract = true) {
|
||||
static const json t = agent_tools();
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why));
|
||||
ReplyOptions ro;
|
||||
ro.extract_reasoning = extract;
|
||||
ro.terminators = { "<|eot|>" };
|
||||
if (tools) ro.tools = &t;
|
||||
return parser_of(f, ro);
|
||||
}
|
||||
|
||||
/* `reply` read whole, then streamed at every cut: the answer must come out as `content`, with
|
||||
* `reasoning` split off and no call. */
|
||||
static void muse_reads(const std::shared_ptr<const ReplyParser>& rp, const std::string& reply,
|
||||
const std::string& content, const std::string& reasoning = "") {
|
||||
REQUIRE(rp);
|
||||
const ReplyMessage m = reply_parse(*rp, reply);
|
||||
if (m.content != content || m.reasoning != reasoning || !m.calls.empty())
|
||||
::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + " read as content " +
|
||||
quote(m.content) + ", reasoning " + quote(m.reasoning) + ", " +
|
||||
std::to_string(m.calls.size()) + " calls");
|
||||
const std::string e = stream_all(*rp, reply);
|
||||
if (!e.empty()) ::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + ": " + e);
|
||||
++::radtest::checks();
|
||||
}
|
||||
|
||||
/* A reply with no reasoning opens on the user channel, and the header is not content. */
|
||||
TEST(a_muse_reply_that_opens_on_the_content_channel_drops_its_header) {
|
||||
for (bool tools : { false, true }) {
|
||||
const auto rp = muse_parser(tools);
|
||||
muse_reads(rp, " to=user<|message|>Here are five prime numbers: 2, 3, 5, 7, 11.<|eot|>",
|
||||
"Here are five prime numbers: 2, 3, 5, 7, 11.");
|
||||
muse_reads(rp, "to=user<|message|>Hi", "Hi");
|
||||
muse_reads(rp, "\n to=user<|message|>\nHi there\n", "\nHi there");
|
||||
muse_reads(rp, " to=user<|message|>", "");
|
||||
/* The header's words later in the answer are the answer's. */
|
||||
muse_reads(rp, " to=user<|message|>write to=user<|message|> next", "write to=user<|message|> next");
|
||||
}
|
||||
/* Reasoning kept inline (reasoning_format none): the answer's header is still dropped. */
|
||||
muse_reads(muse_parser(false, false), " to=user<|message|>Hi<|eot|>", "Hi");
|
||||
}
|
||||
|
||||
/* Text that starts like the header but is not it is the reply, unchanged, and nothing of it is
|
||||
* held back for good. */
|
||||
TEST(a_muse_reply_that_only_starts_like_the_content_header_is_unchanged) {
|
||||
for (bool tools : { false, true }) {
|
||||
const auto rp = muse_parser(tools);
|
||||
for (const char* r : { "to=users are asked to wait", "to=user", "to=user<|message", "to=",
|
||||
"to=user<|message|", "to=user <|message|>x", "to=use", "t",
|
||||
"to=user<|messages|>x", "to=self", "to=sel", "x to=user<|message|>y",
|
||||
"to=user to=user<|message|>y" })
|
||||
muse_reads(rp, r, r);
|
||||
muse_reads(rp, "to=users are asked to wait<|eot|>", "to=users are asked to wait");
|
||||
muse_reads(rp, "to=user\n<|message|>x", "to=user\n<|message|>x");
|
||||
}
|
||||
}
|
||||
|
||||
/* Reasoning first, then the user channel: the header after the block is reasoning_close's, and
|
||||
* a header-shaped string inside the answer stays. */
|
||||
TEST(a_muse_reply_that_reasons_first_reads_as_before) {
|
||||
for (bool tools : { false, true }) {
|
||||
const auto rp = muse_parser(tools);
|
||||
muse_reads(rp, " to=self<|message|>Five primes.<|eom|><|start|>assistant to=user<|message|>2, 3, 5, 7, 11.<|eot|>",
|
||||
"2, 3, 5, 7, 11.", "Five primes.");
|
||||
muse_reads(rp, " to=self<|message|>r<|eom|><|start|>assistant to=user<|message|>to=user<|message|>x",
|
||||
"to=user<|message|>x", "r");
|
||||
}
|
||||
}
|
||||
|
||||
/* A tool call after reasoning is handed off exactly as before: the channel header is framing, the
|
||||
* call is a call, and the content is empty. */
|
||||
TEST(a_muse_tool_call_after_reasoning_is_unchanged) {
|
||||
const auto rp = muse_parser(true);
|
||||
REQUIRE(rp);
|
||||
const std::string reply =
|
||||
" to=self<|message|>Look at it.<|eom|><|start|>assistant to=read<|message|>"
|
||||
"<atem:function_calls>\n<atem:invoke name=\"read\">\n"
|
||||
"<atem:parameter name=\"path\">a.txt</atem:parameter>\n</atem:invoke>\n"
|
||||
"</atem:function_calls>";
|
||||
const ReplyMessage m = reply_parse(*rp, reply);
|
||||
CHECK_EQ(m.content, std::string());
|
||||
CHECK_EQ(m.reasoning, std::string("Look at it."));
|
||||
REQUIRE_EQ(m.calls.size(), (size_t)1);
|
||||
CHECK_EQ(m.calls[0].name, std::string("read"));
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"a.txt\"}"));
|
||||
const std::string e = stream_all(*rp, reply);
|
||||
CHECK(e.empty());
|
||||
if (!e.empty()) std::fprintf(stderr, "%s\n", e.c_str());
|
||||
}
|
||||
|
||||
/* The header is a declared literal like any other: it travels in the ABI struct, reads as absent
|
||||
* from a struct that ends before it, and a format without one reads a reply as it always did. */
|
||||
TEST(the_content_header_is_declared_through_the_abi_struct) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why));
|
||||
CHECK_EQ(f.content_open, std::string("to=user<|message|>"));
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
const std::vector<std::string> mk = chat_format_markers(f);
|
||||
CHECK(std::find(mk.begin(), mk.end(), "to=user<|message|>") != mk.end());
|
||||
/* A plugin compiled before the field: struct_size stops short of it. */
|
||||
RadChatFormat old = *museglimmer::muse_chat_format();
|
||||
old.struct_size = (uint32_t)offsetof(RadChatFormat, content_open);
|
||||
ChatFormat g;
|
||||
CHECK_OK(chat_format_from_abi(&old, &g, &why));
|
||||
CHECK(g.content_open.empty());
|
||||
CHECK_EQ(g.reasoning_open, f.reasoning_open);
|
||||
CHECK(chat_format_describe(g).find("content") == std::string::npos);
|
||||
/* Without it the header is content, as before. */
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
CHECK_OK(ReplyFormat::compile(g, &rf, &why));
|
||||
ReplyOptions ro;
|
||||
std::shared_ptr<const ReplyParser> rp;
|
||||
CHECK_OK(ReplyParser::create(rf, ro, &rp, &why));
|
||||
CHECK_EQ(reply_parse(*rp, " to=user<|message|>Hi").content, std::string("to=user<|message|>Hi"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -136,6 +136,32 @@ TEST(the_metadata_names_the_architecture_and_the_quantisation) {
|
||||
CHECK_EQ(ck.dir(), dir);
|
||||
}
|
||||
|
||||
/* The index is checkpoint-supplied data like the tensors, and its weight_map values are paths:
|
||||
* a poisoned one must not lead the loader to open files outside the model dir as the serving
|
||||
* user. hfget screens the listing's names; nothing screened the index's until here. */
|
||||
TEST(a_poisoned_index_cannot_lead_the_shard_list_out_of_the_model_dir) {
|
||||
auto dir_with_index = [](const char* shard) -> std::string {
|
||||
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, kConfig);
|
||||
const std::string idx = std::string("{\"metadata\":{\"total_size\":8},\"weight_map\":"
|
||||
"{\"x\":\"") + shard + "\"}}";
|
||||
/* No REQUIRE in here: its failure spelling returns void, and this lambda returns a
|
||||
* directory. A null FILE* just fails to write, and every caller checks the open. */
|
||||
std::FILE* f = std::fopen((dir + "/model.safetensors.index.json").c_str(), "wb");
|
||||
if (f != nullptr) {
|
||||
std::fwrite(idx.data(), 1, idx.size(), f);
|
||||
std::fclose(f);
|
||||
}
|
||||
return dir;
|
||||
};
|
||||
/* The honest index still reads: the name is the real shard's own. */
|
||||
Checkpoint ok;
|
||||
CHECK_EQ(ok.open(dir_with_index("model.safetensors")), RAD_OK);
|
||||
for (const char* bad : { "../../../../etc/passwd", "/etc/passwd", "..", "a/..", "./x", "" }) {
|
||||
Checkpoint ck;
|
||||
CHECK(ck.open(dir_with_index(bad)) < 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) {
|
||||
const std::string dir = write_checkpoint({ bf16("x", {2, 2}, 0) },
|
||||
"{\"model_type\":\"glm5_next\",\"text_config\":{\"hidden_size\":4096,"
|
||||
@@ -150,6 +176,57 @@ TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) {
|
||||
CHECK_EQ(ck.meta().m.head_dim, (int64_t)0);
|
||||
}
|
||||
|
||||
/* Muse Glimmer: the underscore-stripped model_type is the architecture id, the trunk's config
|
||||
* lives under text_config (nested() reads it; the alias pass copies it to bare keys), and the
|
||||
* head_dim 128 is read, not derived (6656/32 would be 208). The free-form keys a plugin reads --
|
||||
* the layer schedule, the per-layer rotary bases, the family scalars -- flatten to strings under
|
||||
* their dotted config.json spellings, and vision_config stays unaliased under its full prefix. */
|
||||
TEST(muse_glimmer_metadata_maps_the_trunk_and_keeps_the_family_keys) {
|
||||
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) },
|
||||
"{\"model_type\":\"muse_glimmer\",\"architectures\":[\"MuseGlimmerForConditionalGeneration\"],"
|
||||
"\"image_token_id\":200092,\"video_token_id\":200091,"
|
||||
"\"text_config\":{\"hidden_size\":6656,\"num_hidden_layers\":52,"
|
||||
"\"num_attention_heads\":32,\"num_key_value_heads\":2,\"head_dim\":128,"
|
||||
"\"intermediate_size\":19968,\"vocab_size\":202048,\"rms_norm_eps\":1e-5,"
|
||||
"\"post_norm_eps\":1e-8,\"sliding_window\":2048,\"max_position_embeddings\":131072,"
|
||||
"\"qk_scale_factor\":3.87,\"output_multiplier\":0.19611613513818404,"
|
||||
"\"final_logit_softcapping\":20.0,"
|
||||
"\"rope_parameters\":{\"rope_theta\":500000.0,\"rope_type\":\"default\"},"
|
||||
"\"layer_types\":[\"sliding_attention\",\"sliding_attention\",\"sliding_attention\","
|
||||
"\"full_attention\"],\"layer_rope_theta\":[500000.0,500000.0,500000.0,0]},"
|
||||
"\"vision_config\":{\"model_type\":\"muse_glimmer_vision\",\"hidden_size\":1536,"
|
||||
"\"num_hidden_layers\":50,\"patch_size\":14}}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
const MetaOwn& mo = ck.meta();
|
||||
const RadModelMeta& m = mo.m;
|
||||
CHECK_EQ(mo.arch, std::string("museglimmer"));
|
||||
CHECK_EQ(mo.quant, std::string(""));
|
||||
CHECK_EQ(mo.has("text_config.layer_rope_theta"), true);
|
||||
CHECK_EQ(m.n_embd, (int64_t)6656);
|
||||
CHECK_EQ(m.n_layers, (int64_t)52);
|
||||
CHECK_EQ(m.n_head, (int64_t)32);
|
||||
CHECK_EQ(m.n_head_kv, (int64_t)2);
|
||||
CHECK_EQ(m.head_dim, (int64_t)128);
|
||||
CHECK_EQ(m.n_ff, (int64_t)19968);
|
||||
CHECK_EQ(m.n_vocab, (int64_t)202048);
|
||||
CHECK_EQ(m.rms_eps, 1e-5f);
|
||||
CHECK_EQ(m.n_ctx_train, (int64_t)131072);
|
||||
CHECK_EQ(m.rope_theta, 500000.0);
|
||||
/* The plugin's free-form reads: the aliased bare spellings and the dotted originals agree,
|
||||
* and the layer arrays arrive as one space-separated string each. */
|
||||
CHECK_EQ(rad_meta_gets(&m, "layer_types", ""), std::string("sliding_attention sliding_attention "
|
||||
"sliding_attention full_attention"));
|
||||
CHECK_EQ(rad_meta_gets(&m, "layer_rope_theta", ""), std::string("500000 500000 500000 0"));
|
||||
CHECK_EQ(rad_meta_geti(&m, "sliding_window", 0), (long long)2048);
|
||||
CHECK_EQ(rad_meta_getf(&m, "qk_scale_factor", 0.0), 3.87);
|
||||
CHECK_EQ(rad_meta_getf(&m, "post_norm_eps", 0.0), 1e-8);
|
||||
/* vision_config is never aliased: only the full prefix carries it. */
|
||||
CHECK_EQ(rad_meta_geti(&m, "vision_config.num_hidden_layers", -1), (long long)50);
|
||||
CHECK_EQ(rad_meta_geti(&m, "num_hidden_layers", -1), (long long)52);
|
||||
CHECK_EQ(rad_meta_gets(&m, "vision_config.model_type", ""), std::string("muse_glimmer_vision"));
|
||||
}
|
||||
|
||||
/* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's
|
||||
* --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin,
|
||||
* so the container never names one format and selects another's plugin. transformers' fp8 states
|
||||
@@ -1925,6 +2002,26 @@ TEST(config_json_fills_the_model_meta_as_each_family_spells_it) {
|
||||
"lfm2", 0, 1024, 16, 8, 64, 0, 0, 0, 0, 0, 0, 1e-5, 1e4,
|
||||
{ { "layer_types", "conv full_attention conv" }, { "hidden_size", "7" },
|
||||
{ "vision_config.hidden_size", "768" } } },
|
||||
{ "LFM3: the rotary per attention class with its partial factor, the window, booleans; the "
|
||||
"typed theta is the default, which the plugin does not read",
|
||||
R"({"model_type":"lfm3","hidden_size":2048,"num_attention_heads":16,
|
||||
"num_key_value_heads":4,"head_dim":128,"num_hidden_layers":4,
|
||||
"intermediate_size":7680,"norm_eps":1e-05,"vocab_size":128000,
|
||||
"max_position_embeddings":262144,"conv_L_cache":7,"conv_bias":false,
|
||||
"use_sandwich_norm":true,"tie_word_embeddings":true,"sliding_window":256,
|
||||
"layer_types":["conv","full_attention","sliding_attention","conv"],
|
||||
"rope_parameters":{"full_attention":{"partial_rotary_factor":0.5,
|
||||
"rope_theta":1000000.0,"rope_type":"default"},
|
||||
"sliding_attention":{"rope_theta":10000,"rope_type":"default"}}})",
|
||||
"lfm3", 4, 2048, 16, 4, 128, 7680, 128000, 262144, 0, 0, 0, 1e-5, 1e4,
|
||||
{ { "layer_types", "conv full_attention sliding_attention conv" },
|
||||
{ "rope_parameters.full_attention.rope_theta", "1000000" },
|
||||
{ "rope_parameters.full_attention.partial_rotary_factor", "0.5" },
|
||||
{ "rope_parameters.full_attention.rope_type", "default" },
|
||||
{ "rope_parameters.sliding_attention.rope_theta", "10000" },
|
||||
{ "rope_parameters.sliding_attention.partial_rotary_factor", nullptr },
|
||||
{ "sliding_window", "256" }, { "conv_L_cache", "7" }, { "conv_bias", "0" },
|
||||
{ "use_sandwich_norm", "1" }, { "tie_word_embeddings", "1" } } },
|
||||
{ "Gemma 4 12B: the unified wrapper maps to gemma4, its model_type stays, null experts",
|
||||
R"({"model_type":"gemma4_unified","eos_token_id":[1,106],
|
||||
"text_config":{"model_type":"gemma4_unified_text","hidden_size":3840,
|
||||
@@ -3504,4 +3601,53 @@ TEST(single_files_merge_by_name_and_read_their_metadata_elsewhere) {
|
||||
CHECK_EQ(ck.tok_dir(), meta);
|
||||
}
|
||||
|
||||
TEST(a_bailing_gguf_must_promise_a_walkable_layer_count) {
|
||||
/* bailingmoe3_layouts rebuilds the release layout by walking every layer the container
|
||||
* claims, on the open path and before any plugin runs. A GGUF naming 2^62 layers is
|
||||
* therefore not a slow load but a permanent hang -- and a negative dense prefix opens a
|
||||
* second loop of the same order. Both must refuse at open, quickly, RAD_E_FORMAT. */
|
||||
const std::string dir = fresh_dir();
|
||||
auto bailing_kvs = [](int64_t layers, int64_t dense, int64_t heads = 4, int64_t latent = 512) {
|
||||
return std::vector<GKv>{
|
||||
{ "general.architecture", 8, 0, { "bailingmoe3" } },
|
||||
{ "bailingmoe3.block_count", 10, (double)layers, {} },
|
||||
{ "bailingmoe3.embedding_length", 4, 64, {} },
|
||||
{ "bailingmoe3.attention.head_count", 10, (double)heads, {} },
|
||||
{ "bailingmoe3.feed_forward_length", 4, 128, {} },
|
||||
{ "bailingmoe3.context_length", 4, 4096, {} },
|
||||
{ "bailingmoe3.kda.head_dim", 4, 128, {} },
|
||||
{ "bailingmoe3.rope.dimension_count", 4, 64, {} },
|
||||
{ "bailingmoe3.attention.key_length_mla", 4, 192, {} },
|
||||
{ "bailingmoe3.attention.value_length_mla", 4, 128, {} },
|
||||
{ "bailingmoe3.attention.kv_lora_rank", 10, (double)latent, {} },
|
||||
{ "bailingmoe3.expert_feed_forward_length", 4, 256, {} },
|
||||
{ "bailingmoe3.leading_dense_block_count", 10, (double)dense, {} },
|
||||
};
|
||||
};
|
||||
const std::string huge = dir + "/huge.gguf";
|
||||
write_gguf(huge, bailing_kvs(4611686018427387904LL, 0), {});
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(huge), RAD_E_FORMAT);
|
||||
const std::string neg = dir + "/neg.gguf";
|
||||
write_gguf(neg, bailing_kvs(4, -4611686018427387904LL), {});
|
||||
Checkpoint ck2;
|
||||
REQUIRE_EQ(ck2.open(neg), RAD_E_FORMAT);
|
||||
/* The bound must not bite the honest: a small stack opens (no tensors, so the walk finds
|
||||
* nothing to rebuild, and open returns OK exactly as before). */
|
||||
const std::string sane = dir + "/sane.gguf";
|
||||
write_gguf(sane, bailing_kvs(4, 1), {});
|
||||
Checkpoint ck3;
|
||||
REQUIRE_EQ(ck3.open(sane), RAD_OK);
|
||||
/* The widths the layout products are built from are bounded too: past the caps they are
|
||||
* vector sizes and wrapped row products, not geometry. */
|
||||
const std::string wide = dir + "/wide.gguf";
|
||||
write_gguf(wide, bailing_kvs(4, 1, 4611686018427387904LL), {});
|
||||
Checkpoint ck4;
|
||||
REQUIRE_EQ(ck4.open(wide), RAD_E_FORMAT);
|
||||
const std::string deep_rank = dir + "/deep_rank.gguf";
|
||||
write_gguf(deep_rank, bailing_kvs(4, 1, 4, 4611686018427387904LL), {});
|
||||
Checkpoint ck5;
|
||||
REQUIRE_EQ(ck5.open(deep_rank), RAD_E_FORMAT);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -92,7 +92,7 @@ bool write_tiny_clef(const std::string& dir, uint64_t seed) {
|
||||
ts.push_back(tiny::noise("joint_logit_scale", {}, r, 0.0f, 0.5f));
|
||||
ts.push_back(tiny::noise("residual_gate", {}, r, 0.0f, -1.0f));
|
||||
if (!tiny::write_safetensors(dir + "/joint_head.safetensors", ts)) return false;
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["hidden_size"] = E;
|
||||
c["width"] = W;
|
||||
c["routing_layers"] = 1;
|
||||
@@ -206,10 +206,11 @@ TEST(a_clef_container_decides_every_question_on_the_card_and_matches_the_release
|
||||
img["images"] = json::array({ "data:image/png;base64,AAAA" });
|
||||
call(s.port, "POST", "/v1/systemone", img, &status);
|
||||
CHECK_EQ(status, 501);
|
||||
/* A model the process does not serve is not found, as OpenAI answers an unknown model. */
|
||||
json wrong = gold["request"];
|
||||
wrong["model"] = "other";
|
||||
call(s.port, "POST", "/v1/systemone", wrong, &status);
|
||||
CHECK_EQ(status, 400);
|
||||
CHECK_EQ(status, 404);
|
||||
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "rad_clef.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
+225
-35
@@ -203,6 +203,42 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
|
||||
CHECK_EQ(parse({ "--kld-record", "/r", "--kld-corpus", "/c", "--kld-top", "-1" }, &f), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The diagnose mode: one mode a run, and its corpus and baseline belong to its workload. A run
|
||||
* that took one of them without a DIR would measure nothing while looking configured. */
|
||||
TEST(the_diagnose_mode_takes_its_own_flags_and_nothing_else) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-tokens", "64", "--diagnose-runs", "1",
|
||||
"--diagnose-concurrency", "1,2", "--diagnose-prefill", "1024,4096",
|
||||
"--diagnose-corpus", "/c.jsonl", "--diagnose-baseline", "/b.json" }, &c), RAD_OK);
|
||||
CHECK(c.diagnose_mode());
|
||||
CHECK_EQ(c.diagnose, std::string("/d"));
|
||||
CHECK_EQ(c.diagnose_tokens, 64);
|
||||
CHECK_EQ(c.diagnose_runs, 1);
|
||||
CHECK_EQ(c.diagnose_concurrency.size(), (size_t)2);
|
||||
CHECK_EQ(c.diagnose_prefill.size(), (size_t)2);
|
||||
CHECK_EQ(c.diagnose_corpus, std::string("/c.jsonl"));
|
||||
CHECK_EQ(c.diagnose_baseline, std::string("/b.json"));
|
||||
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK(!d.diagnose_mode());
|
||||
CHECK_EQ(d.diagnose_tokens, 256); /* the defaults the report states */
|
||||
CHECK_EQ(d.diagnose_runs, 3);
|
||||
CHECK_EQ(d.diagnose_concurrency.size(), (size_t)4);
|
||||
CHECK_EQ(d.diagnose_prefill.size(), (size_t)4);
|
||||
|
||||
Config f;
|
||||
CHECK_EQ(parse({ "--diagnose-corpus", "/c.jsonl" }, &f), RAD_E_INVAL); /* no workload */
|
||||
CHECK_EQ(parse({ "--diagnose-baseline", "/b.json" }, &f), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--kld-ref", "/r" }, &f), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--debug-graph" }, &f), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--calib-corpus", "/c.jsonl", "--calib-dir", "/s" }, &f),
|
||||
RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-concurrency", "1,,2" }, &f), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-prefill", "8" }, &f), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-runs", "0" }, &f), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a
|
||||
* combination that would size slots no adapter uses, or name an adapter that is not served, is
|
||||
* refused by name. A text model's slot count against its adapters, and its targets, are checked
|
||||
@@ -312,7 +348,7 @@ TEST(the_sizes_and_counts_reach_the_fields_they_name) {
|
||||
CHECK_EQ(c.max_tok, 512ll);
|
||||
CHECK_EQ(c.max_seqs, 8ll);
|
||||
CHECK_EQ(c.max_ctx, 200000ll);
|
||||
CHECK_EQ(c.host_pool_mib, 12288ll);
|
||||
CHECK_EQ(c.host_pool_mib, 6144ll); /* a rank's share of the 12288 at --tp 2 */
|
||||
CHECK_EQ(c.prefix_cache_mib, 4096ll);
|
||||
CHECK_EQ(c.prefix_cache_ttl, 600ll);
|
||||
CHECK_EQ(c.checkpoint_interval, 2048ll);
|
||||
@@ -478,6 +514,17 @@ TEST(prefill_interleave_takes_a_step_count_up_to_64) {
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto:x" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(mixed_step_target_is_an_opt_in_soft_millisecond_target) {
|
||||
Config d;
|
||||
REQUIRE_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK_EQ(d.mixed_step_target_ms, 0);
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--mixed-step-target-ms", "150" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.mixed_step_target_ms, 150);
|
||||
CHECK_EQ(parse({ "--mixed-step-target-ms", "60001" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--mixed-step-target-ms", "-1" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* ================================================================== the table, the parser and the help agree
|
||||
*
|
||||
* One table (g_flags) drives the help text and the startup report, and a separate chain of ifs
|
||||
@@ -520,12 +567,13 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--tp-attn-split", { "rows" } }, { "--weight-prefetch", { "off" } },
|
||||
{ "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } },
|
||||
{ "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } },
|
||||
{ "--mixed-step-target-ms", { "150" } },
|
||||
{ "--preempt-wait-ms", { "5000" } },
|
||||
{ "--max-num-seqs", { "4" } },
|
||||
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
|
||||
{ "--gpu-memory-mib", { "16384" } }, { "--gpu-headroom-mib", { "128" } },
|
||||
{ "--kv-cache-dtype", { "fp8" } },
|
||||
{ "--state-cache-dtype", { "f16" } }, { "--attn-prefill-fp8", { "both" } },
|
||||
{ "--kv-cache-dtype", { "i8" } },
|
||||
{ "--state-cache-dtype", { "f16" } },
|
||||
{ "--kv-resident", { "65536" } },
|
||||
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
|
||||
{ "--embedding-placement", { "vram" } },
|
||||
@@ -539,13 +587,19 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--num-speculative-tokens", { "2" } }, { "--spec-ngram", { "4" } },
|
||||
{ "--spec-ngram-min", { "1" } }, { "--spec-ngram-max", { "6" } },
|
||||
{ "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } },
|
||||
{ "--draft-coupling", { "on" } },
|
||||
{ "--draft-coupling", { "on" } }, { "--draft-verify", { "block" } },
|
||||
{ "--draft-suffix", { "on" } }, { "--draft-suffix-min-match", { "5" } },
|
||||
{ "--draft-suffix-max", { "6" } }, { "--draft-suffix-min-score", { "0.4" } },
|
||||
{ "--draft-depth", { "adaptive" } }, { "--draft-depth-max", { "5" } },
|
||||
{ "--draft-depth-min", { "2" } }, { "--draft-depth-stop", { "0.7" } },
|
||||
{ "--draft-depth-lag", { "0" } }, { "--draft-depth-stat", { "path" } },
|
||||
{ "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } },
|
||||
{ "--api-key-env", { "RAD_KEY_ENV_INVENTORY" } },
|
||||
{ "--allow-host", { "box" } },
|
||||
{ "--trusted-proxy", { "127.0.0.0/8" } },
|
||||
{ "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } },
|
||||
{ "--control-vector", { "off" } },
|
||||
{ "--control-vector-variant", { "uncensored", "--control-vector", "off" } },
|
||||
{ "--generation-config", { "/g.json" } }, { "--override-chat-template", { "/t.jinja" } },
|
||||
{ "--temp", { "0.7" } }, { "--top-k", { "40" } }, { "--top-p", { "0.9" } },
|
||||
{ "--min-p", { "0.05" } }, { "--reasoning-effort", { "low" } },
|
||||
@@ -589,6 +643,13 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--kld-lora", { "a", "--lora", "a=/adapters/a", "--kld-ref", "/r" } },
|
||||
{ "--kld-lora-sources", { "doc/", "--kld-lora", "a", "--lora", "a=/adapters/a",
|
||||
"--kld-ref", "/r" } },
|
||||
{ "--diagnose", { "/d" } },
|
||||
{ "--diagnose-tokens", { "64", "--diagnose", "/d" } },
|
||||
{ "--diagnose-runs", { "1", "--diagnose", "/d" } },
|
||||
{ "--diagnose-concurrency", { "1,2", "--diagnose", "/d" } },
|
||||
{ "--diagnose-prefill", { "1024,4096", "--diagnose", "/d" } },
|
||||
{ "--diagnose-corpus", { "/c.jsonl", "--diagnose", "/d" } },
|
||||
{ "--diagnose-baseline", { "/b.json", "--diagnose", "/d" } },
|
||||
};
|
||||
return v;
|
||||
}
|
||||
@@ -746,6 +807,37 @@ TEST(the_control_vector_flag_is_off_on_or_disabled) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The variant is a name a request gives as `model`, so it keeps the rule names keep, and it needs a
|
||||
* loaded vector: with none it would answer as the stock model while the client asked for the
|
||||
* vector. A --lora adapter of the same name would make `base:name` mean two things. */
|
||||
TEST(the_control_vector_variant_needs_a_vector_and_a_plain_name_of_its_own) {
|
||||
{
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--control-vector", "off", "--control-vector-variant", "uncensored" }, &c),
|
||||
RAD_OK);
|
||||
CHECK_EQ(c.control_vector_variant, std::string("uncensored"));
|
||||
}
|
||||
{
|
||||
Config c;
|
||||
CHECK_EQ(parse({}, &c), RAD_OK);
|
||||
CHECK(c.control_vector_variant.empty());
|
||||
}
|
||||
auto refused = [](std::initializer_list<const char*> v) {
|
||||
Config c;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = parse(v, &c); });
|
||||
CHECK_EQ(st, (int)RAD_E_INVAL);
|
||||
CHECK(has(log, "--control-vector-variant"));
|
||||
};
|
||||
refused({ "--control-vector-variant", "uncensored" });
|
||||
refused({ "--control-vector", "disabled", "--control-vector-variant", "uncensored" });
|
||||
refused({ "--control-vector", "off", "--control-vector-variant", "base:uncensored" });
|
||||
refused({ "--control-vector", "off", "--control-vector-variant", "two words" });
|
||||
refused({ "--control-vector", "off", "--control-vector-variant", "" });
|
||||
refused({ "--control-vector", "off", "--lora", "uncensored=/ad/u",
|
||||
"--control-vector-variant", "uncensored" });
|
||||
}
|
||||
|
||||
TEST(the_wire_mode_is_one_of_two_names) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--tp-wire", "exact" }, &c), RAD_OK);
|
||||
@@ -786,25 +878,6 @@ TEST(weight_prefetch_is_on_or_off) {
|
||||
CHECK_EQ(parse({ "--weight-prefetch", "" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The prefill attention's e4m3 legs are lossy, so the default is off and anything but the four
|
||||
* names stops the server. */
|
||||
TEST(the_attention_fp8_mode_is_one_of_four_names) {
|
||||
Config c;
|
||||
CHECK_EQ(c.attn_prefill_fp8, 0);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "qk" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.attn_prefill_fp8, (int)RAD_ATTN_FP8_QK);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "pv" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.attn_prefill_fp8, (int)RAD_ATTN_FP8_PV);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "both" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.attn_prefill_fp8, (int)(RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV));
|
||||
CHECK_EQ(std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)), std::string("both"));
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "off" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.attn_prefill_fp8, 0);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "3" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--attn-prefill-fp8", "QK" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_p2p_mode_is_one_of_three_names) {
|
||||
Config c;
|
||||
CHECK_EQ(c.p2p, RAD_P2P_AUTO);
|
||||
@@ -835,21 +908,26 @@ TEST(the_state_cache_dtype_is_f32_or_f16) {
|
||||
CHECK_EQ(parse({ "--state-cache-dtype" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_kv_cache_dtype_is_one_of_four_names) {
|
||||
TEST(the_kv_cache_dtype_is_one_of_three_names) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("bf16"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp8" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("fp8"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp8_v4" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("fp8_v4"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "k6_v4" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("k6_v4"));
|
||||
/* Four values only: an "auto" resolving to bf16 would be a second name for the default, and
|
||||
* each value should be unambiguous in a log. */
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "i8" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("i8"));
|
||||
/* Three values only: an "auto" resolving to bf16 would be a second name for the default, and
|
||||
* each value should be unambiguous in a log. The packed caches are refused by name, with the
|
||||
* cache that serves in their place. */
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "auto" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp16" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "v4" }, &c), RAD_E_INVAL);
|
||||
for (const char* gone : { "fp8_v4", "k6_v4" }) {
|
||||
int rc = RAD_OK;
|
||||
const std::string err = stderr_of([&] { rc = parse({ "--kv-cache-dtype", gone }, &c); });
|
||||
CHECK_EQ(rc, RAD_E_INVAL);
|
||||
CHECK(err.find("i8 is the 8-bit cache") != std::string::npos);
|
||||
}
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("i8"));
|
||||
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
@@ -964,6 +1042,103 @@ TEST(the_draft_window_is_fixed_or_adaptive) {
|
||||
CHECK_EQ(std::string(draft_window_name(DraftWindow::Fixed)), std::string("fixed"));
|
||||
}
|
||||
|
||||
/* --draft-depth is fixed unless asked for. adaptive switches the coupled drafting on (its rule reads
|
||||
* the draft's laws), excludes the fixed block verify and --draft-window adaptive, and takes its knobs
|
||||
* in range. */
|
||||
TEST(draft_depth_adaptive_parses_and_needs_a_coupled_chain) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({}, &c), RAD_OK);
|
||||
CHECK(!c.draft_depth_adaptive);
|
||||
CHECK_EQ(c.draft_depth_max, 0);
|
||||
CHECK_EQ(c.draft_depth_min, 1);
|
||||
CHECK_EQ(c.draft_depth_lag, 1);
|
||||
CHECK_EQ(c.draft_depth_stat, 0);
|
||||
CHECK(c.draft_depth_stop == 0.85);
|
||||
CHECK(!c.draft_coupling);
|
||||
Config a;
|
||||
CHECK_EQ(parse({ "--draft-depth", "adaptive", "--draft-depth-max", "6", "--draft-depth-stop", "0.6",
|
||||
"--draft-depth-lag", "0", "--draft-depth-stat", "path", "--draft-depth-min", "2" }, &a),
|
||||
RAD_OK);
|
||||
CHECK(a.draft_depth_adaptive);
|
||||
CHECK(a.draft_coupling);
|
||||
CHECK_EQ(a.draft_depth_max, 6);
|
||||
CHECK_EQ(a.draft_depth_min, 2);
|
||||
CHECK_EQ(a.draft_depth_lag, 0);
|
||||
CHECK_EQ(a.draft_depth_stat, 1);
|
||||
CHECK(a.draft_depth_stop == 0.6);
|
||||
CHECK_EQ(parse({ "--draft-depth", "fixed" }, &a), RAD_OK);
|
||||
CHECK(!a.draft_depth_adaptive);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-verify", "traversal" }), RAD_OK);
|
||||
for (const char* bad : { "on", "auto", "" }) CHECK_EQ(parse_fresh({ "--draft-depth", bad }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth" }), RAD_E_INVAL);
|
||||
for (const char* bad : { "-0.1", "1.5", "x" }) CHECK_EQ(parse_fresh({ "--draft-depth-stop", bad }), RAD_E_INVAL);
|
||||
for (const char* bad : { "2", "-1" }) CHECK_EQ(parse_fresh({ "--draft-depth-lag", bad }), RAD_E_INVAL);
|
||||
for (const char* bad : { "17", "-1" }) CHECK_EQ(parse_fresh({ "--draft-depth-max", bad }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth-min", "0" }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth-stat", "mean" }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-coupling", "off" }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-window", "adaptive" }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-window", "fixed" }), RAD_OK);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-verify", "block" }), RAD_E_INVAL);
|
||||
CHECK_EQ(parse_fresh({ "--draft-depth", "adaptive", "--draft-depth-min", "4", "--draft-depth-max", "3" }),
|
||||
RAD_E_INVAL);
|
||||
}
|
||||
|
||||
|
||||
/* The SuffixDecoding selector: off by default (bit-identical engine), min match 1..12, rows 1..32,
|
||||
* a score in [0, 1]. */
|
||||
TEST(the_draft_suffix_flags_default_off_and_parse) {
|
||||
Config c;
|
||||
CHECK(!c.draft_suffix);
|
||||
CHECK_EQ(c.draft_suffix_min_match, 6);
|
||||
CHECK_EQ(c.draft_suffix_max, 7);
|
||||
CHECK_NEAR(c.draft_suffix_min_score, 0.3, 1e-6);
|
||||
CHECK_EQ(c.n_spec_head, 0);
|
||||
CHECK_EQ(parse({ "--draft-suffix", "on", "--draft-suffix-min-match", "5", "--draft-suffix-max", "6",
|
||||
"--draft-suffix-min-score", "0.45" }, &c), RAD_OK);
|
||||
CHECK(c.draft_suffix);
|
||||
CHECK_EQ(c.draft_suffix_min_match, 5);
|
||||
CHECK_EQ(c.draft_suffix_max, 6);
|
||||
CHECK_NEAR(c.draft_suffix_min_score, 0.45, 1e-6);
|
||||
CHECK_EQ(parse({ "--draft-suffix", "off" }, &c), RAD_OK);
|
||||
CHECK(!c.draft_suffix);
|
||||
for (const char* bad : { "yes", "1", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix", bad }), RAD_E_INVAL);
|
||||
for (const char* bad : { "0", "13", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-min-match", bad }), RAD_E_INVAL);
|
||||
for (const char* bad : { "0", "33", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-max", bad }), RAD_E_INVAL);
|
||||
for (const char* bad : { "-0.1", "1.5", "x", "" }) CHECK_EQ(parse_fresh({ "--draft-suffix-min-score", bad }), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
|
||||
/* --draft-verify is token (alias rowwise) unless asked for; block and traversal parse. block
|
||||
* implies the coupled drafting and refuses coupling off; traversal needs the coupling and says so. */
|
||||
TEST(the_draft_verify_is_token_block_or_traversal) {
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK(!d.draft_verify_block);
|
||||
CHECK(!d.draft_verify_traversal);
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--draft-verify", "block" }, &c), RAD_OK);
|
||||
CHECK(c.draft_verify_block);
|
||||
CHECK(!c.draft_verify_traversal);
|
||||
CHECK(c.draft_coupling);
|
||||
Config t;
|
||||
CHECK_EQ(parse({ "--draft-coupling", "on", "--draft-verify", "traversal" }, &t), RAD_OK);
|
||||
CHECK(t.draft_verify_traversal);
|
||||
CHECK(!t.draft_verify_block);
|
||||
CHECK_EQ(parse({ "--draft-verify", "rowwise" }, &t), RAD_OK);
|
||||
CHECK(!t.draft_verify_traversal);
|
||||
CHECK_EQ(parse({ "--draft-verify", "token" }, &t), RAD_OK);
|
||||
CHECK(!t.draft_verify_block);
|
||||
Config b;
|
||||
for (const char* bad : { "Block", "Traversal", "on", "" })
|
||||
CHECK_EQ(parse({ "--draft-verify", bad }, &b), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--draft-verify" }, &b), RAD_E_INVAL);
|
||||
Config off;
|
||||
CHECK_EQ(parse({ "--draft-verify", "block", "--draft-coupling", "off" }, &off), RAD_E_INVAL);
|
||||
Config nocouple;
|
||||
CHECK_EQ(parse({ "--draft-verify", "traversal" }, &nocouple), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* --draft-coupling is off unless asked for, and only off and on parse: a misspelt value must not
|
||||
* start a server on the other path. */
|
||||
TEST(the_draft_coupling_is_off_or_on) {
|
||||
@@ -1550,8 +1725,8 @@ TEST(a_repeated_flag_takes_the_last_one) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--port", "1", "--port", "8100" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.port, 8100);
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16", "--kv-cache-dtype", "fp8" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("fp8"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16", "--kv-cache-dtype", "i8" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("i8"));
|
||||
/* A bad value is refused even after a good one. */
|
||||
CHECK_EQ(parse({ "--tp-wire", "exact", "--tp-wire", "nope" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
@@ -1561,10 +1736,10 @@ TEST(usage_names_every_flag_it_documents) {
|
||||
* for, so a flag added without a help line is caught. */
|
||||
const std::string text = stderr_of([] { config_usage("radiance"); });
|
||||
for (const char* f : { "--model", "--host-pool-mib", "--kv-cache-dtype",
|
||||
"--num-speculative-tokens", "--draft-window", "--draft-coupling",
|
||||
"--num-speculative-tokens", "--draft-window", "--draft-coupling", "--draft-verify",
|
||||
"--checkpoint-policy",
|
||||
"--prefix-cache-mib", "--prefix-cache-ttl", "--tp-wire",
|
||||
"--attn-prefill-fp8", "--embedding-placement", "--ngram-placement",
|
||||
"--embedding-placement", "--ngram-placement",
|
||||
"--kld-record", "--kld-ref", "--default-max-tokens", "--max-tokens-cap",
|
||||
"--presence-penalty", "--dry-sequence-breakers",
|
||||
"--chat-template-kwargs", "--reasoning-format", "--max-n",
|
||||
@@ -1597,4 +1772,19 @@ TEST(rope_scaling_takes_yarn_with_a_factor_above_one_or_none) {
|
||||
CHECK(d.rope_scaling.empty());
|
||||
}
|
||||
|
||||
/* The suffix selector and the adaptive chain depth are served together, with traversal verification
|
||||
* (bring-up refuses what the model cannot do; the parse and the shown rows say what was asked). */
|
||||
TEST(the_suffix_selector_parses_beside_adaptive_depth_and_traversal) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--draft-suffix", "on", "--draft-depth", "adaptive", "--draft-coupling", "on",
|
||||
"--draft-verify", "traversal", "--num-speculative-tokens", "5" }, &c), RAD_OK);
|
||||
CHECK(c.draft_suffix);
|
||||
CHECK(c.draft_depth_adaptive);
|
||||
CHECK(c.draft_coupling);
|
||||
CHECK(c.draft_verify_traversal);
|
||||
CHECK(!c.draft_verify_block);
|
||||
CHECK_EQ(c.n_spec, 5);
|
||||
CHECK_EQ(c.draft_suffix_max, 7);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+83
-31
@@ -2,7 +2,7 @@
|
||||
*
|
||||
* The binary runs as a child on the host backend; the containers it writes are read back with
|
||||
* core's reader and decoder. The checkpoint is a two-layer LLaMA served by llama_dense_fp8, whose
|
||||
* recipe makes every linear block fp8 and keeps the norms, the embedding and the head as the
|
||||
* recipe makes every linear rotated int8 and keeps the norms, the embedding and the head as the
|
||||
* checkpoint holds them, so one conversion writes a quantised and a copied weight of every kind.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
@@ -64,10 +64,10 @@ struct World {
|
||||
World() {
|
||||
if (!dir.ok()) return;
|
||||
ckpt = dir / "llama";
|
||||
recipe = dir / "fp8.recipe";
|
||||
recipe = dir / "i8.recipe";
|
||||
base = dir / "base.rad";
|
||||
if (mkdir(ckpt.c_str(), 0755) != 0 || !tiny::write_llama(ckpt, {}) ||
|
||||
!tiny::write_text(recipe, tiny::kLlamaFp8Recipe))
|
||||
!tiny::write_text(recipe, tiny::kLlamaI8Recipe))
|
||||
return;
|
||||
for (tiny::Tensor& t : tiny::read_safetensors(ckpt + "/model.safetensors"))
|
||||
src[t.name] = std::move(t);
|
||||
@@ -120,11 +120,11 @@ std::vector<std::string> differing_weights(const RadFile& a, const RadFile& b) {
|
||||
|
||||
/* ================================================================== what a conversion writes */
|
||||
|
||||
/* A recipe weight is block fp8 over the rows its name map joins, in the map's order: attn_qkv is
|
||||
* q, then k, then v, and ffn_gate_up is gate then up. Each element decodes to its source within
|
||||
* E4M3's half step (2^-4 relative) plus one subnormal step of its block's scale (amax / 448 /
|
||||
* 2^9). A part out of order, or a block's scale applied to another block's rows, is off by the
|
||||
* source's own magnitude. */
|
||||
/* A recipe weight is rotated int8 over the rows its name map joins, in the map's order: attn_qkv
|
||||
* is q, then k, then v, and ffn_gate_up is gate then up. A row's 128 columns under one scale
|
||||
* decode to their source within a twentieth of the source's RMS there: the codes' step is the
|
||||
* rotated group's largest magnitude over 127, about a hundredth of its RMS in error. A part out of
|
||||
* order, or a group's scale applied to another group, is off by the source's own magnitude. */
|
||||
TEST(a_recipe_weight_decodes_to_its_source_rows_in_name_map_order) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
@@ -142,7 +142,7 @@ TEST(a_recipe_weight_decodes_to_its_source_rows_in_name_map_order) {
|
||||
for (const auto& j : kJoins) {
|
||||
const RadFileEntry* e = f.find(j.weight);
|
||||
REQUIRE(e != nullptr);
|
||||
CHECK_EQ(enc_name(f.encoding(*e)), std::string("fp8_e4m3*bf16[128x128]"));
|
||||
CHECK_EQ(enc_name(f.encoding(*e)), std::string("i8*bf16[1x128]/fwht128"));
|
||||
CHECK_EQ(std::string(f.str(e->quantizer)), std::string("rtn"));
|
||||
const std::vector<float> got = decode(f, *e);
|
||||
REQUIRE(!got.empty());
|
||||
@@ -159,21 +159,19 @@ TEST(a_recipe_weight_decodes_to_its_source_rows_in_name_map_order) {
|
||||
}
|
||||
REQUIRE_EQ((int64_t)want.size(), rows * cols);
|
||||
int64_t bad = 0;
|
||||
for (int64_t r0 = 0; r0 < rows; r0 += 128)
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c0 = 0; c0 < cols; c0 += 128) {
|
||||
float amax = 0;
|
||||
for (int64_t r = r0; r < std::min(rows, r0 + 128); ++r)
|
||||
for (int64_t c = c0; c < std::min(cols, c0 + 128); ++c)
|
||||
amax = std::max(amax, std::fabs(want[(size_t)(r * cols + c)]));
|
||||
for (int64_t r = r0; r < std::min(rows, r0 + 128); ++r)
|
||||
for (int64_t c = c0; c < std::min(cols, c0 + 128); ++c) {
|
||||
const size_t i = (size_t)(r * cols + c);
|
||||
const float tol = 0.0625f * std::fabs(want[i]) + amax / 448.0f / 512.0f;
|
||||
if (!(std::fabs(got[i] - want[i]) <= tol)) ++bad;
|
||||
}
|
||||
double sw = 0, se = 0;
|
||||
for (int64_t c = c0; c < std::min(cols, c0 + 128); ++c) {
|
||||
const size_t i = (size_t)(r * cols + c);
|
||||
sw += (double)want[i] * want[i];
|
||||
se += ((double)got[i] - want[i]) * ((double)got[i] - want[i]);
|
||||
}
|
||||
if (!(std::sqrt(se) <= 0.05 * std::sqrt(sw) + 1e-6)) ++bad;
|
||||
}
|
||||
if (bad)
|
||||
fprintf(stderr, " %s: %lld elements outside the bound\n", j.weight, (long long)bad);
|
||||
fprintf(stderr, " %s: %lld scale groups outside the bound\n", j.weight,
|
||||
(long long)bad);
|
||||
CHECK_EQ(bad, (int64_t)0);
|
||||
}
|
||||
}
|
||||
@@ -713,9 +711,9 @@ TEST(in_place_keeps_a_weight_the_plugin_has_regrouped) {
|
||||
CHECK_EQ(e->offset, off);
|
||||
}
|
||||
|
||||
/* In place, a weight cannot be replaced: a rule that would write one differently is refused and
|
||||
* the file is left as it was. Without --in-place, -o may not name the --reuse container, whose
|
||||
* weights the run reads while it truncates the output. */
|
||||
/* In place, a rule that would write a weight differently is refused unless --replace names the
|
||||
* weight, and the file is left as it was. Without --in-place, -o may not name the --reuse
|
||||
* container, whose weights the run reads while it truncates the output. */
|
||||
TEST(in_place_refuses_to_change_a_weight_and_reuse_never_truncates_its_source) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
@@ -723,17 +721,70 @@ TEST(in_place_refuses_to_change_a_weight_and_reuse_never_truncates_its_source) {
|
||||
const std::string ip = d / "ip.rad";
|
||||
REQUIRE(copy_file(w.base, ip));
|
||||
REQUIRE(tiny::write_text(d / "search.recipe",
|
||||
std::string("blk.0.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 "
|
||||
"scale=bf16 rule=search\n") + tiny::kLlamaFp8Recipe));
|
||||
std::string("blk.0.attn_qkv.weight rtn codes=i8 group=128 scale=bf16 "
|
||||
"transform=fwht128 clamp=sym rule=search\n") +
|
||||
tiny::kLlamaI8Recipe));
|
||||
std::string log;
|
||||
CHECK(convert(w.ckpt, { "--recipe", d / "search.recipe", "--reuse", ip, "--in-place" },
|
||||
&log) != 0);
|
||||
CHECK(has(log, "cannot be replaced in place"));
|
||||
CHECK(has(log, "Name it with --replace"));
|
||||
CHECK(tiny::read_text(ip) == tiny::read_text(w.base));
|
||||
CHECK_EQ(convert(w.ckpt, { "-o", ip, "--recipe", w.recipe, "--reuse", ip }, &log), 2);
|
||||
CHECK(tiny::read_text(ip) == tiny::read_text(w.base));
|
||||
}
|
||||
|
||||
/* --replace: the named weight is written again past the container's end under its new rule, equal
|
||||
* to a conversion to a new file; every other weight stays at its offset, and the old planes are
|
||||
* reported as unreachable. A glob no weight matches, or --replace without --in-place, is refused. */
|
||||
TEST(in_place_replace_writes_the_named_weight_again_past_the_end) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("convert_ipx");
|
||||
const std::string ip = d / "ip.rad", fresh = d / "fresh.rad";
|
||||
REQUIRE(copy_file(w.base, ip));
|
||||
const char* kName = "blk.0.attn_qkv.weight";
|
||||
REQUIRE(tiny::write_text(d / "search.recipe",
|
||||
std::string(kName) + " rtn codes=i8 group=128 scale=bf16 "
|
||||
"transform=fwht128 clamp=sym rule=search\n" +
|
||||
tiny::kLlamaI8Recipe));
|
||||
std::string log;
|
||||
CHECK(convert(w.ckpt, { "--recipe", w.recipe, "--reuse", ip, "--in-place",
|
||||
"--replace", "blk.9.nope" }, &log) != 0);
|
||||
CHECK(has(log, "matches no weight"));
|
||||
CHECK(tiny::read_text(ip) == tiny::read_text(w.base));
|
||||
CHECK_EQ(convert(w.ckpt, { "-o", fresh, "--recipe", d / "search.recipe", "--reuse", w.base,
|
||||
"--replace", kName }, &log), 2);
|
||||
|
||||
REQUIRE_EQ(convert(w.ckpt, { "--recipe", d / "search.recipe", "--reuse", ip, "--in-place",
|
||||
"--replace", kName }, &log), 0);
|
||||
CHECK(has(log, "1 of the added weight(s) replace"));
|
||||
REQUIRE_EQ(convert(w.ckpt, { "-o", fresh, "--recipe", d / "search.recipe" }, &log), 0);
|
||||
RadFile a, b, c;
|
||||
REQUIRE_EQ(a.open(w.base.c_str()), RAD_OK);
|
||||
REQUIRE_EQ(b.open(ip.c_str()), RAD_OK);
|
||||
REQUIRE_EQ(c.open(fresh.c_str()), RAD_OK);
|
||||
REQUIRE_EQ(a.entry_count(), b.entry_count());
|
||||
for (int64_t i = 0; i < a.entry_count(); ++i) {
|
||||
const std::string name = a.str(a.entry(i).name);
|
||||
const RadFileEntry* e = b.find(name.c_str());
|
||||
const RadFileEntry* f = c.find(name.c_str());
|
||||
REQUIRE(e != nullptr);
|
||||
REQUIRE(f != nullptr);
|
||||
if (name == kName) {
|
||||
CHECK(e->offset >= (uint64_t)a.size());
|
||||
CHECK(has(b.str(e->options), "rule=search"));
|
||||
} else {
|
||||
CHECK_EQ(e->offset, a.entry(i).offset);
|
||||
}
|
||||
REQUIRE_EQ(e->n_planes, f->n_planes);
|
||||
for (uint32_t k = 0; k < e->n_planes; ++k) {
|
||||
const RadFilePlane &pe = b.plane(*e, (int)k), &pf = c.plane(*f, (int)k);
|
||||
REQUIRE_EQ(pe.bytes, pf.bytes);
|
||||
CHECK(std::memcmp(b.data(pe), c.data(pf), (size_t)pe.bytes) == 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== refusals and options */
|
||||
|
||||
/* --plan-only declares and plans every weight, and writes nothing. */
|
||||
@@ -928,7 +979,7 @@ TEST(a_rule_that_matches_no_weight_is_warned_about) {
|
||||
tiny::TempDir d("convert_w");
|
||||
REQUIRE(tiny::write_text(d / "r", std::string("blk.*.attn_qvk.weight rtn codes=fp8_e4m3 "
|
||||
"block=128x128 scale=bf16\n") +
|
||||
tiny::kLlamaFp8Recipe));
|
||||
tiny::kLlamaI8Recipe));
|
||||
std::string log;
|
||||
CHECK_EQ(convert(w.ckpt, { "-o", d / "w.rad", "--recipe", d / "r" }, &log), 0);
|
||||
CHECK(has(log, "'blk.*.attn_qvk.weight rtn' matches no weight"));
|
||||
@@ -986,12 +1037,13 @@ TEST(generation_config_travels_as_generation_keys) {
|
||||
CHECK_NEAR(g.top_p, 0.95, 1e-6);
|
||||
}
|
||||
|
||||
/* Declare runs at the KV dtype the engine will use; fp8 resolves on the host kernels too. */
|
||||
TEST(an_fp8_kv_cache_declares) {
|
||||
/* Declare runs at the KV dtype the engine will use; the int8 cache resolves on the host kernels
|
||||
* too. */
|
||||
TEST(an_int8_kv_cache_declares) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("convert_k");
|
||||
CHECK_EQ(convert(w.ckpt, { "-o", d / "k.rad", "--recipe", w.recipe, "--kv-cache-dtype", "fp8" },
|
||||
CHECK_EQ(convert(w.ckpt, { "-o", d / "k.rad", "--recipe", w.recipe, "--kv-cache-dtype", "i8" },
|
||||
nullptr), 0);
|
||||
CHECK(exists(d / "k.rad"));
|
||||
}
|
||||
|
||||
+61
-104
@@ -1,15 +1,20 @@
|
||||
/* tests/dashboard_test.cpp -- what the dashboard and its JSON routes show.
|
||||
*
|
||||
* The page at `/` polls /stats and /sessions and reads dozens of their fields by name; a field
|
||||
* renamed on either side blanks a panel with no error anywhere. So the routes are checked for the
|
||||
* values a populated engine gives them, and the page's own script is read for every field it
|
||||
* takes from them, each of which a route must emit. The KV figures behind both come from
|
||||
* The page at `/` and the process's sampler read dozens of the fields of /stats and /sessions by
|
||||
* name; a field renamed on either side blanks a panel with no error anywhere. So the routes are
|
||||
* checked for the values a populated engine gives them, for every field the page reads of them
|
||||
* and for every figure the sampler derives from them. The KV figures behind both come from
|
||||
* SchedulerBridge's aggregation over the scheduler's groups, checked here on a hybrid model's
|
||||
* groups, where summing or picking the wrong group goes wrong silently.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
#include "rad_internal.h" /* rad_mono_ns: a synthetic bringup start */
|
||||
#include "server/dashboard_page.h"
|
||||
#include "server/history.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace {
|
||||
@@ -155,41 +160,6 @@ struct Dash {
|
||||
}
|
||||
};
|
||||
|
||||
/* The identifiers `var.<name>` that `text` reads, and the string arguments of `calls("<name>")`. */
|
||||
std::set<std::string> fields(const std::string& text, const std::string& var) {
|
||||
std::set<std::string> out;
|
||||
const std::string pat = var + ".";
|
||||
for (size_t at = text.find(pat); at != std::string::npos; at = text.find(pat, at + 1)) {
|
||||
if (at > 0) {
|
||||
const char b = text[at - 1];
|
||||
if (std::isalnum((unsigned char)b) || b == '_' || b == '.' || b == '$') continue;
|
||||
}
|
||||
size_t e = at + pat.size();
|
||||
while (e < text.size() && (std::isalnum((unsigned char)text[e]) || text[e] == '_')) ++e;
|
||||
if (e > at + pat.size()) out.insert(text.substr(at + pat.size(), e - at - pat.size()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::set<std::string> called(const std::string& text, const std::string& fn) {
|
||||
std::set<std::string> out;
|
||||
const std::string pat = fn + "(\"";
|
||||
for (size_t at = text.find(pat); at != std::string::npos; at = text.find(pat, at + 1)) {
|
||||
if (at > 0 && (std::isalnum((unsigned char)text[at - 1]) || text[at - 1] == '_')) continue;
|
||||
const size_t b = at + pat.size(), e = text.find('"', b);
|
||||
out.insert(text.substr(b, e - b));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* The page's script from `from` up to the line that closes the function starting there. */
|
||||
std::string function_body(const std::string& page, const std::string& from) {
|
||||
const size_t at = page.find(from);
|
||||
if (at == std::string::npos) return std::string();
|
||||
const size_t end = page.find("\n}\n", at);
|
||||
return page.substr(at, end == std::string::npos ? std::string::npos : end - at);
|
||||
}
|
||||
|
||||
void each_field_is_emitted(const std::set<std::string>& names, const json& o, const char* what) {
|
||||
for (const std::string& n : names) {
|
||||
const bool there = o.is_object() && o.contains(n);
|
||||
@@ -359,77 +329,64 @@ TEST(stats_reports_how_long_bringup_took_once_the_server_listens) {
|
||||
CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47);
|
||||
}
|
||||
|
||||
/* The pooled acceptance ring's element shape is a contract between two functions of the page,
|
||||
* and no browser runs here: accWindow returns {ratio, dr, da}, and acceptTriple reads the ring's
|
||||
* entries as `d` and `last`. A field name it reads that the ring does not carry is undefined in
|
||||
* JavaScript, and the pooled figures render as NaN. */
|
||||
TEST(the_pooled_acceptance_ring_reads_the_names_accWindow_writes) {
|
||||
Dash d(false);
|
||||
const std::string p = d.srv->router().call("GET", "/").body;
|
||||
const std::string aw = function_body(p, "function accWindow(");
|
||||
const std::string at = function_body(p, "function acceptTriple(");
|
||||
REQUIRE(!aw.empty() && !at.empty());
|
||||
/* what goes into the ring */
|
||||
CHECK(aw.find("dr: dr") != std::string::npos);
|
||||
CHECK(aw.find("da: da") != std::string::npos);
|
||||
/* what comes out of it: every `d.<field>` and `last.<field>` must be a ring name */
|
||||
const std::set<std::string> ring = {"dr", "da"};
|
||||
for (const std::string& n : fields(at, "d")) {
|
||||
CHECK(ring.count(n) == 1);
|
||||
if (!ring.count(n))
|
||||
fprintf(stderr, " acceptTriple reads d.%s, which the ring does not carry\n", n.c_str());
|
||||
}
|
||||
for (const std::string& n : fields(at, "last")) {
|
||||
CHECK(ring.count(n) == 1);
|
||||
if (!ring.count(n))
|
||||
fprintf(stderr, " acceptTriple reads last.%s, which the ring does not carry\n", n.c_str());
|
||||
}
|
||||
/* only polls that drafted enter the ring */
|
||||
CHECK(aw.find("dr <= 0") != std::string::npos);
|
||||
}
|
||||
|
||||
/* The page is built from typed sources: every field it reads of a route's object is a member of an
|
||||
* interface in dashboard/src/lib/api.ts, and the compiled-in header lists them (kPageReads). Each
|
||||
* must be one the route emits for a populated engine. */
|
||||
TEST(every_field_the_page_reads_is_one_the_routes_emit) {
|
||||
Dash d(false);
|
||||
HttpResponse page = d.srv->router().call("GET", "/");
|
||||
REQUIRE(page.status == 200 && has(page.body, "function update(s, dt)"));
|
||||
const std::string& p = page.body;
|
||||
REQUIRE(page.status == 200 && has(page.body, "<div id=\"root\">"));
|
||||
const json stats = d.get("/stats");
|
||||
const json sessions = d.get("/sessions");
|
||||
const std::map<std::string, const json*> objects = {
|
||||
{ "stats", &stats },
|
||||
{ "requests", &stats["requests"][0] },
|
||||
{ "draft_positions", &stats["draft_positions"][0] },
|
||||
{ "experts", &stats["experts"] },
|
||||
{ "tiers", &stats["experts"]["tiers"][0] },
|
||||
{ "sessions", &sessions },
|
||||
{ "session", &sessions["sessions"][0] },
|
||||
};
|
||||
std::map<std::string, std::set<std::string>> reads;
|
||||
for (const char* const* r = kPageReads; *r; ++r) {
|
||||
const std::string e = *r;
|
||||
const size_t dot = e.find('.');
|
||||
REQUIRE(dot != std::string::npos);
|
||||
reads[e.substr(0, dot)].insert(e.substr(dot + 1));
|
||||
}
|
||||
CHECK(reads["stats"].size() > 12);
|
||||
for (const auto& [object, names] : reads) {
|
||||
const auto it = objects.find(object);
|
||||
CHECK(it != objects.end());
|
||||
if (it != objects.end()) each_field_is_emitted(names, *it->second, object.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
const std::string update = function_body(p, "function update(s, dt)");
|
||||
const std::string batch = function_body(p, "function renderBatch(list, s)");
|
||||
REQUIRE(!update.empty() && !batch.empty());
|
||||
std::set<std::string> top = fields(update, "s");
|
||||
for (const std::string& n : fields(batch, "s")) top.insert(n);
|
||||
CHECK(top.size() > 15);
|
||||
each_field_is_emitted(top, stats, "stats");
|
||||
each_field_is_emitted(fields(update, "ex"), stats["experts"], "experts");
|
||||
each_field_is_emitted(fields(update, "t"), stats["experts"]["tiers"][0], "experts.tiers[]");
|
||||
std::set<std::string> link = fields(update, "lk");
|
||||
for (const char* fn : { "d", "pre", "dP" })
|
||||
for (const std::string& n : called(update, fn)) link.insert(n);
|
||||
each_field_is_emitted(link, stats["link"], "link");
|
||||
each_field_is_emitted(fields(update, "c"), stats["cards"][0], "cards[]");
|
||||
each_field_is_emitted(fields(update, "p"), stats["draft_positions"][0], "draft_positions[]");
|
||||
|
||||
/* The request table: renderBatch through renderRequests. */
|
||||
const size_t rb = p.find("function renderBatch("), up = p.find("function update(s, dt)");
|
||||
REQUIRE(rb != std::string::npos && up > rb);
|
||||
each_field_is_emitted(fields(p.substr(rb, up - rb), "r"), stats["requests"][0], "requests[]");
|
||||
|
||||
/* The sessions view: its loader, and the rows from reuseOf through sessRow. */
|
||||
const std::string load = function_body(p, "async function loadSessions()");
|
||||
REQUIRE(!load.empty());
|
||||
each_field_is_emitted(fields(load, "s"), sessions, "sessions");
|
||||
each_field_is_emitted(fields(load, "mv"), sessions["snapshot_store"], "snapshot_store");
|
||||
each_field_is_emitted(fields(load, "ln"), sessions["linear"], "linear");
|
||||
each_field_is_emitted(fields(load, "pool"), sessions["pool"], "pool");
|
||||
each_field_is_emitted(fields(load, "occ"), sessions["occupancy"], "occupancy");
|
||||
const size_t ro = p.find("const reuseOf"), lo = p.find("async function loadSessions()");
|
||||
REQUIRE(ro != std::string::npos && lo > ro);
|
||||
std::set<std::string> rows = fields(p.substr(ro, lo - ro), "r");
|
||||
for (const std::string& n : fields(load, "r")) rows.insert(n);
|
||||
each_field_is_emitted(rows, sessions["sessions"][0], "sessions[]");
|
||||
/* The charts draw what the process samples (History), which reads /stats by field name as the page
|
||||
* does. Fed a populated engine's /stats and an earlier one with every counter lower, the sampler
|
||||
* must yield each figure a chart draws; a field the route renamed would leave its column out. */
|
||||
TEST(the_sampler_yields_every_charted_figure_from_the_stats_route) {
|
||||
Dash d(false);
|
||||
const json now = d.get("/stats");
|
||||
std::function<json(const json&)> earlier = [&](const json& j) -> json {
|
||||
if (j.is_number()) return json(j.get<double>() - 7.0);
|
||||
if (j.is_object()) { json o = json::object(); for (auto it = j.begin(); it != j.end(); ++it) o[it.key()] = earlier(it.value()); return o; }
|
||||
if (j.is_array()) { json a = json::array(); for (const json& e : j) a.push_back(earlier(e)); return a; }
|
||||
return j;
|
||||
};
|
||||
json prev = earlier(now);
|
||||
prev["started_at"] = now["started_at"];
|
||||
const History::Row row = History::model_row(now, &prev, 1.0);
|
||||
std::set<std::string> have;
|
||||
for (const auto& [name, v] : row)
|
||||
if (std::isfinite(v)) have.insert(name);
|
||||
for (const char* k : { "decode", "prefill", "running", "waiting", "preempted", "flight", "hit", "kvUsed", "kvCap",
|
||||
"kvKept", "kvRead", "jobRun", "jobDone", "prefillRate", "reqRate", "stepAny", "step",
|
||||
"accept", "tokStep", "lkAr", "lkUp", "lkDn", "lkSsd", "lkStream", "expHit", "expIn",
|
||||
"expOut" }) {
|
||||
CHECK(have.count(k) == 1);
|
||||
if (!have.count(k)) fprintf(stderr, " the sampler yields no '%s' from /stats\n", k);
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the bridge's KV figures */
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
{#- Bailing V3 chat template -#}
|
||||
{#- Supports: thinking option, tool calling -#}
|
||||
|
||||
{#- ==================== thinking option normalization ==================== -#}
|
||||
{%- if enable_thinking is defined %}
|
||||
{%- if enable_thinking %}
|
||||
{%- set thinking_option = 'on' %}
|
||||
{%- else %}
|
||||
{%- set thinking_option = 'off' %}
|
||||
{%- endif %}
|
||||
{%- elif thinking_option is not defined %}
|
||||
{%- set thinking_option = 'on' %}
|
||||
{%- endif %}
|
||||
|
||||
{#- ==================== preserved thinking ==================== -#}
|
||||
{% set preserved_thinking = true %}
|
||||
|
||||
{#- ==================== system message ==================== -#}
|
||||
{{- '<role>SYSTEM</role>' }}
|
||||
{%- if tools %}
|
||||
{%- if messages[0].role == 'system' %}
|
||||
{{- messages[0].content + '\n' }}
|
||||
{%- endif %}
|
||||
{{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
||||
{%- for tool in tools %}
|
||||
{{- "\n" }}
|
||||
{{- tool | tojson }}
|
||||
{%- endfor %}
|
||||
{{- "\n</tools>\n\nIf none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out.\nIf you need to use a function, for each function call, output the function name and arguments within the following XML format:\n<tool_call>{function-name}\n<arg_key>{arg-key-1}</arg_key>\n<arg_value>{arg-value-1}</arg_value>\n<arg_key>{arg-key-2}</arg_key>\n<arg_value>{arg-value-2}</arg_value>\n...\n</tool_call>\n" }}
|
||||
{%- if messages[0].role == 'system' and messages[0].content is string and ('detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content) %}
|
||||
{{- '<|role_end|>' }}
|
||||
{%- else %}
|
||||
{{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
|
||||
{%- endif %}
|
||||
{%- else %}
|
||||
{%- if messages[0].role == 'system' %}
|
||||
{%- if 'detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content %}
|
||||
{{- messages[0].content + '<|role_end|>' }}
|
||||
{%- else %}
|
||||
{{- messages[0].content + '\n' }}
|
||||
{{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
|
||||
{%- endif %}
|
||||
{% else %}
|
||||
{{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
||||
{%- for message in messages[::-1] %}
|
||||
{%- set index = (messages|length - 1) - loop.index0 %}
|
||||
{%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
|
||||
{%- set ns.multi_step_tool = false %}
|
||||
{%- set ns.last_query_index = index %}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
{%- for message in messages %}
|
||||
{%- if message.content is string %}
|
||||
{%- set content = message.content %}
|
||||
{%- else %}
|
||||
{%- set content = '' %}
|
||||
{%- endif %}
|
||||
{%- if message.role == "user" %}
|
||||
{{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }}
|
||||
{%- elif message.role == "system" and not loop.first %}
|
||||
{{- '<role>SYSTEM</role>' + message.content + '<|role_end|>' }}
|
||||
{%- elif message.role == "assistant" %}
|
||||
{%- set reasoning_content = '' %}
|
||||
{%- if message.reasoning_content is string and message.reasoning_content != '' %}
|
||||
{%- set reasoning_content = message.reasoning_content %}
|
||||
{%- else %}
|
||||
{%- if '</think>' in content %}
|
||||
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
||||
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
{%- if preserved_thinking or loop.index0 > ns.last_query_index %}
|
||||
{%- if reasoning_content != '' %}
|
||||
{{- '<role>ASSISTANT</role>' + '\n<think>' + reasoning_content.strip('\n') + '</think>' + content.lstrip('\n') }}
|
||||
{%- else %}
|
||||
{{- '<role>ASSISTANT</role>\n<think></think>' + content }}
|
||||
{%- endif %}
|
||||
{%- else %}
|
||||
{{- '<role>ASSISTANT</role>\n<think></think>' + content }}
|
||||
{%- endif %}
|
||||
{%- if message.tool_calls %}
|
||||
{%- for tool_call in message.tool_calls %}
|
||||
{%- if (loop.first and content) or (not loop.first) %}
|
||||
{{- '\n' }}
|
||||
{%- endif %}
|
||||
{%- set tc = tool_call %}
|
||||
{%- if tool_call.function %}
|
||||
{%- set tc = tool_call.function %}
|
||||
{%- endif %}
|
||||
{{- '<tool_call>' + tc.name }}
|
||||
{% set _args = tc.arguments %}
|
||||
{%- for k, v in _args.items() %}
|
||||
{{- '<arg_key>' + k + '</arg_key>' }}
|
||||
{{- '\n<arg_value>' }}
|
||||
{%- if v is string %}
|
||||
{{- v }}
|
||||
{%- else %}
|
||||
{{- v | tojson(ensure_ascii=False) }}
|
||||
{%- endif %}
|
||||
{{- '</arg_value>' }}
|
||||
{%- endfor %}
|
||||
{{- '\n</tool_call>' }}
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
{{- '<|role_end|>' }}
|
||||
{%- elif message.role == "tool" %}
|
||||
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
||||
{{- '<role>OBSERVATION</role>' }}
|
||||
{%- endif %}
|
||||
{{- '\n<tool_response>\n' }}
|
||||
{{- content }}
|
||||
{{- '\n</tool_response>' }}
|
||||
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
||||
{{- '<|role_end|>' }}
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
|
||||
{#- ==================== generation prompt ==================== -#}
|
||||
{%- if add_generation_prompt %}
|
||||
{{- '<role>ASSISTANT</role>' }}
|
||||
{%- if thinking_option == 'on' %}
|
||||
{{- '\n<think>' }}
|
||||
{%- elif thinking_option == 'off' %}
|
||||
{{- '\n<think></think>' }}
|
||||
{%- endif %}
|
||||
{%- endif %}
|
||||
@@ -7,9 +7,10 @@
|
||||
#pragma once
|
||||
|
||||
#include "rad_test.h"
|
||||
#include "e2e_config.h"
|
||||
#include "tiny_model.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
@@ -24,7 +25,7 @@
|
||||
|
||||
namespace decision_e2e {
|
||||
|
||||
using json = nlohmann::ordered_json; /* the request order, which Laya reads */
|
||||
using json = rad::Json; /* the request order, which Laya reads */
|
||||
|
||||
inline std::vector<std::string> engine_env() {
|
||||
return { "ROCR_VISIBLE_DEVICES=99", "RADIANCE_HOST_VRAM_MIB=1024", "OMP_WAIT_POLICY=passive",
|
||||
@@ -36,7 +37,7 @@ inline std::vector<std::string> engine_argv(const std::string& model,
|
||||
std::vector<std::string> a = { RAD_E2E_SERVER, "--model", model, "--kernels", "libref",
|
||||
"--debug-accept-reference-kernels" };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
return a;
|
||||
return radtest::config_argv(a);
|
||||
}
|
||||
|
||||
inline std::string tail(const std::string& log, int n = 14) {
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
using rad::DirectFile;
|
||||
@@ -145,8 +148,190 @@ TEST(chained_launches_follow_the_plugins_ask_on_the_aql_backend_only) {
|
||||
CHECK_EQ(rad_dev_chain_enabled(), 0);
|
||||
rad_dev_chain_infer(1);
|
||||
CHECK_EQ(rad_dev_chain_enabled(), aql ? 1 : 0);
|
||||
/* Their packets go unfenced only where the engine says every chained form fences itself (2),
|
||||
* and only where launches chain at all. */
|
||||
CHECK_EQ(rad_dev_chain_unfenced(), 0);
|
||||
rad_dev_chain_infer(2);
|
||||
CHECK_EQ(rad_dev_chain_enabled(), aql ? 1 : 0);
|
||||
CHECK_EQ(rad_dev_chain_unfenced(), aql ? 1 : 0);
|
||||
rad_dev_chain_infer(0);
|
||||
CHECK_EQ(rad_dev_chain_enabled(), 0);
|
||||
CHECK_EQ(rad_dev_chain_unfenced(), 0);
|
||||
}
|
||||
|
||||
/* A chained kernel reads behind its wait what the launch in front of it wrote, a value all its
|
||||
* lanes share included. The compiler loads such a value through the scalar data cache, which no
|
||||
* fence it emits empties: only the packet processor's acquire did, when the kernel was launched,
|
||||
* before the launch in front had written. A chained launch whose packet goes unfenced
|
||||
* (rad_dev_chain_infer(2)) must therefore empty that cache behind its wait (chain_kernel.h), or
|
||||
* every reader here sees the value the reader before it loaded: 1797 launches in 1800 did on an
|
||||
* R9700 before the wait emptied it. Behind a gate, so the card has the readers launched ahead of
|
||||
* the stores they wait for, as a played pass has them. */
|
||||
TEST(a_chained_kernel_sees_a_shared_value_the_launch_in_front_wrote) {
|
||||
if (std::strcmp(rad::device_backend_name(), "aql") != 0) SKIP("launches chain on the AQL backend only");
|
||||
const unsigned pairs = 400, blocks = 256;
|
||||
Stream st;
|
||||
DevBuf<unsigned> x(64 * sizeof(unsigned), RAD_MEM_DEVICE);
|
||||
DevBuf<unsigned> seen((int64_t)pairs * blocks * sizeof(unsigned), RAD_MEM_DEVICE);
|
||||
REQUIRE(x && seen);
|
||||
std::vector<unsigned> got((size_t)pairs * blocks);
|
||||
for (int fenced = 0; fenced < 2; ++fenced) {
|
||||
/* 2: the packets go unfenced, as an engine whose libraries fence in the kernel issues
|
||||
* them. 1: they keep the packet processor's fences, and the readers must see the same. */
|
||||
rad_dev_chain_infer(fenced ? 1 : 2);
|
||||
CHECK_OK(rad_memset_async(x, 0, 64 * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_memset_async(seen, 0, (int64_t)pairs * blocks * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
void* gate = nullptr;
|
||||
REQUIRE_EQ(rad_stream_gate(st.s, &gate), RAD_OK);
|
||||
REQUIRE(rad_gate_room(st.s) >= (int64_t)2 * pairs);
|
||||
CHECK_OK(rad::aql::chain_probe(st.s, x, seen, pairs, blocks));
|
||||
CHECK_OK(rad_gate_open(gate));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
CHECK_OK(rad_memcpy_async(got.data(), seen, (int64_t)pairs * blocks * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
int64_t stale = 0;
|
||||
for (unsigned i = 0; i < pairs; ++i)
|
||||
for (unsigned b = 0; b < blocks; ++b) stale += got[(size_t)i * blocks + b] != i + 1u;
|
||||
CHECK_EQ(stale, 0);
|
||||
}
|
||||
rad_dev_chain_infer(0);
|
||||
}
|
||||
|
||||
/* A chained launch reads its own arguments and its chain record from a slot of the argument ring
|
||||
* that the host wrote and that another launch read a lap of the ring ago; the L2 still holds what
|
||||
* that launch read. Only a system-scope acquire of the packet processor's makes the card forget
|
||||
* it: the one the ring asks for every half lap, which a chained packet keeps while it goes
|
||||
* without every other. Three laps of launches that each store where their own arguments say,
|
||||
* with no host wait between them: without that acquire every launch past the first lap stores
|
||||
* where the launch a lap before did (as they do on a prefetch stream, which never takes one and
|
||||
* counts on the pass beside it to have turned the L2 over). */
|
||||
/* The prefetch stream (rad_xp_stream_create, agent-scope acquires) also reads its own arguments
|
||||
* from a host-written ring: across three laps every launch must see its own slot. */
|
||||
TEST(a_prefetch_stream_launch_reads_its_own_arguments_after_the_ring_has_lapped) {
|
||||
if (std::strcmp(rad::device_backend_name(), "aql") != 0) SKIP("the prefetch stream is an AQL stream");
|
||||
const unsigned n = 3 * 4096 + 517;
|
||||
RadStream xs = nullptr;
|
||||
if (rad_xp_stream_create(&xs) != RAD_OK || !xs) SKIP("no prefetch stream on this device");
|
||||
DevBuf<unsigned> seen((int64_t)n * sizeof(unsigned), RAD_MEM_DEVICE);
|
||||
REQUIRE(!!seen);
|
||||
std::vector<unsigned> got(n);
|
||||
{
|
||||
rad_dev_chain_infer(1);
|
||||
CHECK_OK(rad_memset_async(seen, 0, (int64_t)n * sizeof(unsigned), xs));
|
||||
CHECK_OK(rad_stream_sync(xs));
|
||||
CHECK_OK(rad::aql::chain_marks(xs, seen, n));
|
||||
CHECK_OK(rad_stream_sync(xs));
|
||||
CHECK_OK(rad_memcpy_async(got.data(), seen, (int64_t)n * sizeof(unsigned), xs));
|
||||
CHECK_OK(rad_stream_sync(xs));
|
||||
unsigned wrong = 0;
|
||||
for (unsigned i = 0; i < n; ++i) wrong += got[i] != i + 1u;
|
||||
CHECK_EQ(wrong, 0u);
|
||||
}
|
||||
rad_dev_chain_infer(0);
|
||||
rad_stream_destroy(xs);
|
||||
}
|
||||
|
||||
TEST(a_chained_launch_reads_its_own_arguments_after_the_ring_has_lapped) {
|
||||
if (std::strcmp(rad::device_backend_name(), "aql") != 0) SKIP("launches chain on the AQL backend only");
|
||||
const unsigned n = 3 * 4096 + 517;
|
||||
Stream st;
|
||||
DevBuf<unsigned> seen((int64_t)n * sizeof(unsigned), RAD_MEM_DEVICE);
|
||||
REQUIRE(!!seen);
|
||||
std::vector<unsigned> got(n);
|
||||
for (int fenced = 0; fenced < 2; ++fenced) {
|
||||
rad_dev_chain_infer(fenced ? 1 : 2);
|
||||
CHECK_OK(rad_memset_async(seen, 0, (int64_t)n * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
CHECK_OK(rad::aql::chain_marks(st.s, seen, n));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
CHECK_OK(rad_memcpy_async(got.data(), seen, (int64_t)n * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
unsigned wrong = 0;
|
||||
for (unsigned i = 0; i < n; ++i) wrong += got[i] != i + 1u;
|
||||
CHECK_EQ(wrong, 0u);
|
||||
}
|
||||
rad_dev_chain_infer(0);
|
||||
}
|
||||
|
||||
/* The host writes a launch's arguments and chain record into VRAM through the BAR, and the card's
|
||||
* host data path keeps such a write until it is flushed (aql.cpp, host_writes_out). A launch the
|
||||
* card starts within a microsecond or two of its doorbell otherwise reads the slot as it was. What
|
||||
* it reads first is its chain record, so that is what this asks every launch for, on every card:
|
||||
* a lap of card-side copies with chaining off leaves every slot with their arguments and a record
|
||||
* no kernel accepts; then the same copies chained and 50 us apart, the host quiet between them as
|
||||
* the mover is between the copies of a loan recall, each saying whether it found a record. One
|
||||
* that does not would count nothing and stall the queue; the probe counts for it. With the
|
||||
* packets unacquired and with the packet processor's acquire on them. */
|
||||
TEST(a_copy_issued_after_a_pause_finds_the_record_written_for_it) {
|
||||
if (std::strcmp(rad::device_backend_name(), "aql") != 0) SKIP("the AQL backend's argument ring");
|
||||
const unsigned lap = 4096 + 64, words = 8192;
|
||||
const int64_t bytes = 256 * 1024;
|
||||
for (int card = 0; card < rad_dev_count(); ++card) {
|
||||
REQUIRE_EQ(rad_dev_set(card), RAD_OK);
|
||||
DevBuf<unsigned> seen((int64_t)words * sizeof(unsigned), RAD_MEM_DEVICE);
|
||||
DevBuf<uint8_t> src(bytes, RAD_MEM_DEVICE), dst(bytes, RAD_MEM_DEVICE);
|
||||
REQUIRE(seen && src && dst);
|
||||
std::vector<unsigned> got(words);
|
||||
for (int fenced = 0; fenced < 2; ++fenced) {
|
||||
/* Without the flush four runs in five of this many found unacquired launches that
|
||||
* had read the old slot on an R9700, a few or tens of them at a time. */
|
||||
const unsigned n = fenced ? 1500 : 6000;
|
||||
Stream st;
|
||||
rad_dev_chain_infer(0);
|
||||
CHECK_OK(rad::aql::chain_asks(st.s, src, dst, (uint64_t)bytes, seen, lap));
|
||||
CHECK_OK(rad_memset_async(seen, 0, (int64_t)words * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
rad_dev_chain_infer(fenced ? 1 : 2);
|
||||
for (unsigned i = 0; i < n; ++i) {
|
||||
/* In runs of eight with a host wait between them, as a recall ends in one. */
|
||||
if (i % 8 == 0) CHECK_OK(rad_stream_sync(st.s));
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
while (std::chrono::steady_clock::now() - t0 < std::chrono::microseconds(50)) {}
|
||||
CHECK_OK(rad::aql::chain_asks(st.s, src, dst, (uint64_t)bytes, seen + i, 1));
|
||||
}
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
CHECK_OK(rad_memcpy_async(got.data(), seen, (int64_t)words * sizeof(unsigned), st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
/* A launch that read the slot as the lap left it stores where that launch did. */
|
||||
unsigned without = 0, missing = 0;
|
||||
for (unsigned i = 0; i < words; ++i) {
|
||||
without += (got[i] & 0x80000000u) != 0;
|
||||
missing += i < n && got[i] != 1u;
|
||||
}
|
||||
CHECK_EQ(without, 0u);
|
||||
CHECK_EQ(missing, 0u);
|
||||
}
|
||||
rad_dev_chain_infer(0);
|
||||
}
|
||||
rad_dev_set(0);
|
||||
}
|
||||
|
||||
/* An engine of more than one rank claims its cards (rad_dev_cards_claim). The claim that makes a
|
||||
* card shared returns only once everything issued on that card's queues before it has finished:
|
||||
* from then on no chained launch waits on the card behind a collective, and nothing issued under
|
||||
* the old rule is left. A backend that never launches ahead has nothing to wait for and accepts
|
||||
* any claim. */
|
||||
TEST(a_claim_that_shares_a_card_returns_with_the_cards_queues_drained) {
|
||||
const bool aql = std::strcmp(rad::device_backend_name(), "aql") == 0;
|
||||
const int card = 0;
|
||||
CHECK_EQ(rad_dev_cards_claim(nullptr, 1, 1), RAD_E_INVAL);
|
||||
CHECK_EQ(rad_dev_cards_claim(&card, 0, 1), RAD_E_INVAL);
|
||||
CHECK_OK(rad_dev_set(card));
|
||||
const int64_t big = 256 << 20;
|
||||
Stream st;
|
||||
Event done;
|
||||
DevBuf<uint8_t> fat(big, RAD_MEM_DEVICE);
|
||||
CHECK(!!fat);
|
||||
if (!fat) return;
|
||||
CHECK_OK(rad_dev_cards_claim(&card, 1, 1)); /* the first engine: the card is its own */
|
||||
for (int k = 0; k < 24; ++k) CHECK_OK(rad_memset_async(fat, k, big, st.s));
|
||||
CHECK_OK(rad_event_record(done.e, st.s));
|
||||
CHECK_OK(rad_dev_cards_claim(&card, 1, 1)); /* a second: shared from here */
|
||||
if (aql) CHECK_EQ(rad_event_query(done.e), 1);
|
||||
CHECK_OK(rad_dev_cards_claim(&card, 1, 0));
|
||||
CHECK_OK(rad_dev_cards_claim(&card, 1, 0));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
}
|
||||
|
||||
TEST(host_vram_budget_comes_from_the_environment) {
|
||||
@@ -212,6 +397,33 @@ TEST(alloc_free_roundtrip) {
|
||||
CHECK(rad_dev_host_ptr(nullptr) == nullptr);
|
||||
}
|
||||
|
||||
/* A kernel library's free hook (rad_plugin_freed) is registered by every registry that loads the
|
||||
* library and goes with the last of them: a library closed and opened again can sit at another
|
||||
* address, and a hook left behind called into memory nothing mapped. */
|
||||
namespace {
|
||||
std::atomic<int> g_hook_calls{0};
|
||||
void count_free(const void*, int64_t) { ++g_hook_calls; }
|
||||
} // namespace
|
||||
|
||||
TEST(a_free_hook_goes_with_its_last_registration) {
|
||||
auto one_free = [] {
|
||||
void* p = rad_dev_alloc(4096, RAD_MEM_DEVICE);
|
||||
REQUIRE(p != nullptr);
|
||||
rad_dev_free(p, RAD_MEM_DEVICE);
|
||||
};
|
||||
rad::rad_dev_on_free(count_free);
|
||||
rad::rad_dev_on_free(count_free);
|
||||
one_free();
|
||||
CHECK_EQ(g_hook_calls.load(), 1);
|
||||
rad::rad_dev_off_free(count_free);
|
||||
one_free();
|
||||
CHECK_EQ(g_hook_calls.load(), 2);
|
||||
rad::rad_dev_off_free(count_free);
|
||||
one_free();
|
||||
CHECK_EQ(g_hook_calls.load(), 2);
|
||||
rad::rad_dev_off_free(count_free); /* one too many: nothing to take back */
|
||||
}
|
||||
|
||||
/* A pinned range larger than one pin is locked in pieces (core/device/aql.cpp, pin_pieces),
|
||||
* invisibly above the device layer: one base, every byte at the same address on the card, and
|
||||
* copies and fills across a piece boundary land whole. A fill of pageable memory is refused, so the
|
||||
@@ -1626,4 +1838,652 @@ TEST(a_damaged_code_object_is_refused_not_misread) {
|
||||
CHECK(has(why, "amdhsa.kernels"));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ parking (paging.cpp)
|
||||
*
|
||||
* An engine's large device allocations are mapped in chunks a park can take off the card and put
|
||||
* back at the same address. Whatever route a chunk's bytes take while it is out (a host copy, the
|
||||
* disk tier, a copy kept from an earlier park, the container it was loaded from), they must come
|
||||
* back exact.
|
||||
*/
|
||||
namespace {
|
||||
|
||||
/* The paging chunk (paging.cpp's kChunk). */
|
||||
constexpr int64_t kParkChunk = (int64_t)64 << 20;
|
||||
|
||||
/* One pageable allocation under engine owner `owner`, and in `want` the pattern it should hold
|
||||
* (upload() writes it). The owner's scope stays current for the object's life, so further
|
||||
* allocations join the same owner. */
|
||||
struct Paged {
|
||||
rad::EngineScope es;
|
||||
int owner;
|
||||
int64_t n;
|
||||
void* d = nullptr;
|
||||
std::vector<uint8_t> want;
|
||||
RadStream s = nullptr;
|
||||
Paged(int o, int64_t bytes, uint32_t seed)
|
||||
: es(o, "paging-test"), owner(o), n(bytes), want((size_t)bytes) {
|
||||
rad_dev_set(0);
|
||||
fill(want.data(), n, seed);
|
||||
d = rad_dev_alloc(n, RAD_MEM_DEVICE);
|
||||
rad_stream_create(&s, 0);
|
||||
}
|
||||
~Paged() {
|
||||
if (d) rad_dev_free(d, RAD_MEM_DEVICE);
|
||||
if (s) rad_stream_destroy(s);
|
||||
}
|
||||
/* Through pinned memory: an async copy reads its host side when it runs. */
|
||||
int upload() {
|
||||
void* h = rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
if (!h) return RAD_E_NOMEM;
|
||||
std::memcpy(h, want.data(), (size_t)n);
|
||||
int rc = rad_memcpy_async(d, h, n, s);
|
||||
if (rc >= 0) rc = rad_stream_sync(s);
|
||||
rad_dev_free(h, RAD_MEM_HOST_PINNED);
|
||||
return rc;
|
||||
}
|
||||
/* Index of the first byte that differs from `want`, -1 when none does, -2 when the copy back
|
||||
* fails. */
|
||||
int64_t first_bad() {
|
||||
std::vector<uint8_t> got((size_t)n);
|
||||
void* h = rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
if (!h) return -2;
|
||||
const bool ok = rad_memcpy_async(h, d, n, s) >= 0 && rad_stream_sync(s) >= 0;
|
||||
if (ok) std::memcpy(got.data(), h, (size_t)n);
|
||||
rad_dev_free(h, RAD_MEM_HOST_PINNED);
|
||||
if (!ok) return -2;
|
||||
int64_t first = -1, count = 0;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
if (got[(size_t)i] != want[(size_t)i]) {
|
||||
if (first < 0) first = i;
|
||||
++count;
|
||||
}
|
||||
if (first >= 0) {
|
||||
std::fprintf(stderr, " %lld of %lld bytes differ, first at %lld (got %02x, want %02x); by chunk:",
|
||||
(long long)count, (long long)n, (long long)first, got[(size_t)first],
|
||||
want[(size_t)first]);
|
||||
for (int64_t c0 = 0; c0 < n; c0 += kParkChunk) {
|
||||
int64_t b = 0;
|
||||
for (int64_t i = c0; i < std::min(n, c0 + kParkChunk); ++i) b += got[(size_t)i] != want[(size_t)i];
|
||||
std::fprintf(stderr, " %lld", (long long)b);
|
||||
}
|
||||
std::fprintf(stderr, "\n");
|
||||
}
|
||||
return first;
|
||||
}
|
||||
};
|
||||
|
||||
/* A disk tier of the case's own, under the binary's temporary directory. */
|
||||
std::string park_dir() {
|
||||
static int n = 0;
|
||||
const std::string d = radtest::tmpdir() + "/park-" + std::to_string(++n);
|
||||
return ::mkdir(d.c_str(), 0700) == 0 ? d : "";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* Three and a bit chunks, so the last one is short. */
|
||||
constexpr int64_t kParkBytes = 3 * kParkChunk + (5 << 20);
|
||||
|
||||
/* Chunks mapped again at their old addresses and written at once: until the cards' translation
|
||||
* caches are flushed in full the writes land nowhere (Linux 7.1 with gfx1201), so the maps are
|
||||
* followed by dev_settle_maps's flush before anything writes them. This is the page-in's order:
|
||||
* every chunk released, then all mapped, then each written. */
|
||||
TEST(a_chunk_remapped_right_after_its_release_keeps_what_is_written) {
|
||||
if (!need_vmem()) return;
|
||||
const int64_t c = kParkChunk;
|
||||
const int K = 4;
|
||||
rad_dev_set(0);
|
||||
const auto* be = rad::active_backend();
|
||||
char* res = (char*)be->vmem_reserve(K * c, rad::VMem::granularity());
|
||||
CHECK(res != nullptr);
|
||||
RadStream s = nullptr;
|
||||
CHECK_OK(rad_stream_create(&s, 0));
|
||||
std::vector<uint8_t> want((size_t)(K * c));
|
||||
fill(want.data(), K * c, 99u);
|
||||
uint8_t* h = (uint8_t*)rad_dev_alloc(K * c, RAD_MEM_HOST_PINNED);
|
||||
CHECK(h != nullptr);
|
||||
for (int round = 0; round < 3; ++round) {
|
||||
for (int k = 0; k < K; ++k) CHECK_OK(be->vmem_commit(res + k * c, c));
|
||||
for (int k = K - 1; k >= 0; --k) CHECK_OK(be->vmem_decommit(res + k * c, c));
|
||||
std::memcpy(h, want.data(), (size_t)(K * c));
|
||||
for (int k = 0; k < K; ++k) CHECK_OK(be->vmem_commit(res + k * c, c));
|
||||
CHECK_OK(rad::dev_settle_maps());
|
||||
for (int k = 0; k < K; ++k) CHECK_OK(rad_memcpy_async(res + k * c, h + k * c, c, s));
|
||||
CHECK_OK(rad_stream_sync(s));
|
||||
std::memset(h, 0, (size_t)(K * c));
|
||||
CHECK_OK(rad_memcpy_async(h, res, K * c, s));
|
||||
CHECK_OK(rad_stream_sync(s));
|
||||
for (int k = 0; k < K; ++k)
|
||||
CHECK_EQ(std::memcmp(h + k * c, want.data() + k * c, (size_t)c), 0);
|
||||
for (int k = 0; k < K; ++k) CHECK_OK(be->vmem_decommit(res + k * c, c));
|
||||
}
|
||||
rad_dev_free(h, RAD_MEM_HOST_PINNED);
|
||||
be->vmem_release(res, K * c);
|
||||
rad_stream_destroy(s);
|
||||
}
|
||||
|
||||
TEST(a_parked_allocation_comes_back_exact_from_host_copies) {
|
||||
if (!need_vmem()) return;
|
||||
Paged a(9101, kParkBytes, 11u);
|
||||
CHECK(a.d != nullptr);
|
||||
CHECK_OK(a.upload());
|
||||
CHECK_EQ(a.first_bad(), -1); /* the round trip itself, before any park */
|
||||
rad::PageOut req;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.disk, 0);
|
||||
CHECK(res.host >= kParkBytes);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
TEST(a_parked_allocation_comes_back_exact_from_the_disk_tier) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
CHECK(!dir.empty());
|
||||
Paged a(9102, kParkBytes, 12u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.host, 0);
|
||||
CHECK(res.disk >= kParkBytes);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* Sealed, the disk copy stays good for the next park, which writes nothing. */
|
||||
rad::dev_page_seal(a.d);
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.disk, 0);
|
||||
CHECK(res.reused >= kParkBytes);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* More chunks than a page-out batch (16) and than the read-back's staging ring (16), so buffers
|
||||
* are reused on both sides. */
|
||||
TEST(a_large_parked_allocation_comes_back_exact_from_the_disk_tier) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
const int64_t n = 18 * kParkChunk + (3 << 20);
|
||||
Paged a(9105, n, 15u);
|
||||
CHECK(a.d != nullptr);
|
||||
CHECK_OK(a.upload());
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.disk >= n);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* An engine owns several pageable allocations, each with its own page file. */
|
||||
TEST(two_allocations_of_one_owner_come_back_exact_from_the_disk_tier) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
const int64_t n = 6 * kParkChunk + (3 << 20);
|
||||
Paged a(9106, n, 21u);
|
||||
void* d2 = rad_dev_alloc(n / 2, RAD_MEM_DEVICE); /* same owner: a's scope is current */
|
||||
CHECK(a.d != nullptr && d2 != nullptr);
|
||||
std::vector<uint8_t> want2((size_t)(n / 2));
|
||||
fill(want2.data(), n / 2, 22u); /* not 20: the filler sets the seed's low bit, so 20 is 21 */
|
||||
{
|
||||
void* h = rad_dev_alloc(n / 2, RAD_MEM_HOST_PINNED);
|
||||
std::memcpy(h, want2.data(), (size_t)(n / 2));
|
||||
CHECK_OK(rad_memcpy_async(d2, h, n / 2, a.s));
|
||||
CHECK_OK(rad_stream_sync(a.s));
|
||||
rad_dev_free(h, RAD_MEM_HOST_PINNED);
|
||||
}
|
||||
CHECK_OK(a.upload());
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.disk >= n + n / 2);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
{
|
||||
void* h = rad_dev_alloc(n / 2, RAD_MEM_HOST_PINNED);
|
||||
CHECK_OK(rad_memcpy_async(h, d2, n / 2, a.s));
|
||||
CHECK_OK(rad_stream_sync(a.s));
|
||||
CHECK_EQ(std::memcmp(h, want2.data(), (size_t)(n / 2)), 0);
|
||||
rad_dev_free(h, RAD_MEM_HOST_PINNED);
|
||||
}
|
||||
rad_dev_free(d2, RAD_MEM_DEVICE);
|
||||
}
|
||||
|
||||
TEST(a_partial_park_takes_only_what_is_asked_and_comes_back_exact) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
Paged a(9103, kParkBytes, 13u);
|
||||
CHECK_OK(a.upload());
|
||||
const int dev = 0; /* Paged allocates on card 0 */
|
||||
rad::PageOut req;
|
||||
req.want[dev] = (int64_t)100 << 20;
|
||||
req.host_budget = kParkChunk; /* what does not fit goes to disk */
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
/* Whole chunks, from the top: the short last one and two more, not all four. */
|
||||
CHECK(res.freed[dev] >= ((int64_t)100 << 20));
|
||||
CHECK(res.freed[dev] < kParkBytes);
|
||||
CHECK_EQ(res.host + res.disk, res.freed[dev]);
|
||||
CHECK(res.host <= kParkChunk);
|
||||
CHECK(res.disk > 0);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
TEST(a_chunk_loaded_from_a_container_parks_against_it) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
Paged a(9104, kParkBytes, 14u);
|
||||
/* The container holds the bytes at an offset that is not chunk-aligned, as weights are; the
|
||||
* last 5 MiB of the allocation never came from it and are zero. */
|
||||
const int64_t at = 3 * 4096 + 512, from = kParkBytes - (5 << 20);
|
||||
std::memset(a.want.data() + from, 0, (size_t)(kParkBytes - from));
|
||||
const std::string path = dir + "/container.bin";
|
||||
{
|
||||
FILE* f = std::fopen(path.c_str(), "wb");
|
||||
CHECK(f != nullptr);
|
||||
std::vector<uint8_t> pad((size_t)at, 0x7e);
|
||||
std::fwrite(pad.data(), 1, pad.size(), f);
|
||||
std::fwrite(a.want.data(), 1, (size_t)from, f);
|
||||
std::fclose(f);
|
||||
}
|
||||
CHECK_OK(a.upload());
|
||||
const int fid = rad::dev_page_file(path.c_str());
|
||||
/* As the load's sweep records it (engine_bringup.cpp): a run as a single piece, and one as
|
||||
* strided rows. */
|
||||
rad::dev_page_source(a.d, fid, at, (int64_t)100 << 20, 1, 0);
|
||||
const int64_t rows = (from - ((int64_t)100 << 20)) / 4096;
|
||||
rad::dev_page_source((char*)a.d + ((int64_t)100 << 20), fid, at + ((int64_t)100 << 20), 4096, rows, 4096);
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.file >= 3 * kParkChunk);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* A write since the load: that chunk no longer matches, and goes to disk instead. */
|
||||
a.want[70 << 20] ^= 0xff;
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_invalidate((char*)a.d + (70 << 20), 1);
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.disk >= kParkChunk);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* A write into a sealed chunk after a park leaves its copy exact but for the blocks written: the
|
||||
* next park moves only those, into the host copy or onto the disk copy. */
|
||||
TEST(a_write_after_a_park_moves_only_its_blocks_back_out) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
CHECK(!dir.empty());
|
||||
const int64_t blk = (int64_t)64 << 10;
|
||||
/* Two writes: one byte in chunk 1, and 20 bytes across a block boundary in chunk 2. */
|
||||
auto scribble = [&](Paged& a, uint8_t x) {
|
||||
a.want[(size_t)(70 << 20)] ^= x;
|
||||
for (int k = 0; k < 20; ++k) a.want[(size_t)((130 << 20) - 10 + k)] ^= x;
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_invalidate((char*)a.d + (70 << 20), 1);
|
||||
rad::dev_page_invalidate((char*)a.d + (130 << 20) - 10, 20);
|
||||
};
|
||||
for (int host = 0; host < 2; ++host) {
|
||||
Paged a(9107 + host, kParkBytes, 31u + 2 * host);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::PageOut req;
|
||||
req.host_budget = host ? ((int64_t)1 << 30) : 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
scribble(a, 0x5a);
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(host ? res.host : res.disk, 3 * blk);
|
||||
CHECK_EQ(host ? res.disk : res.host, 0);
|
||||
CHECK_EQ(res.reused, res.freed[0] - 3 * blk); /* the span: kParkBytes rounded up */
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
}
|
||||
|
||||
/* An allocation its owner refills (a weights pool and its container) leaves the card with nothing
|
||||
* copied, whatever host room or disk tier there is; the page-in maps it back and hands it to the
|
||||
* owner, which here writes it again; a page-in that would not hand it back refuses. */
|
||||
TEST(an_allocation_its_owner_refills_parks_with_no_copy_and_comes_back_to_be_filled) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
CHECK(!dir.empty());
|
||||
Paged a(9111, kParkBytes, 53u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::dev_page_refilled(a.d);
|
||||
CHECK_EQ(rad::dev_page_uncopied(a.owner), 0);
|
||||
for (int round = 0; round < 2; ++round) {
|
||||
rad::PageOut req;
|
||||
req.host_budget = (int64_t)1 << 30;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.host, 0);
|
||||
CHECK_EQ(res.disk, 0);
|
||||
CHECK_EQ(res.file, res.freed[0]);
|
||||
CHECK(res.freed[0] >= kParkBytes);
|
||||
CHECK_EQ(rad::dev_page_in(a.owner), RAD_E_STATE); /* nobody to fill it */
|
||||
std::vector<rad::PageSpan> spans;
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
REQUIRE_EQ(spans.size(), (size_t)1); /* adjacent chunks merged */
|
||||
CHECK(spans[0].p == (char*)a.d);
|
||||
CHECK(spans[0].bytes >= kParkBytes);
|
||||
CHECK_EQ(spans[0].device, 0);
|
||||
CHECK_OK(a.upload());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
/* A partial park takes chunks from the top (the short last one, then a whole one) and hands
|
||||
* back only those. */
|
||||
rad::PageOut part;
|
||||
part.want[0] = kParkChunk;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, part, &res));
|
||||
CHECK(res.file >= kParkChunk);
|
||||
CHECK(res.file < res.freed[0] + 1 && res.file < kParkBytes);
|
||||
std::vector<rad::PageSpan> spans;
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
REQUIRE_EQ(spans.size(), (size_t)1);
|
||||
CHECK_EQ(spans[0].bytes, res.file);
|
||||
CHECK(spans[0].p > (char*)a.d);
|
||||
CHECK_OK(a.upload());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* A host fill of an allocation its owner refills: host memory mapped at its parked chunks, filled by
|
||||
* the owner (here a copy from the card's side, as the refill's DMA writes it), comes back over the
|
||||
* link with nothing handed back; the copy stays exact, so the next park leaves by the swap; once
|
||||
* the host copies are dropped the chunks are the owner's to refill again. */
|
||||
TEST(a_refilled_allocation_fills_into_host_memory_and_keeps_that_copy) {
|
||||
if (!need_vmem()) return;
|
||||
Paged a(9113, kParkBytes, 59u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::dev_page_refilled(a.d);
|
||||
rad::PageOut req;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
const std::vector<rad::PageSpan> pend = rad::dev_page_refill_chunks(a.owner);
|
||||
CHECK_EQ(pend.size(), (size_t)4);
|
||||
CHECK(rad::dev_page_fillable(a.owner) >= kParkBytes);
|
||||
CHECK_OK(rad::dev_page_fill_begin(a.owner, pend));
|
||||
CHECK_OK(a.upload()); /* into the host memory now mapped at the chunks */
|
||||
rad::dev_page_fill_end(a.owner, pend, true);
|
||||
CHECK_EQ(rad::dev_page_fillable(a.owner), 0);
|
||||
CHECK(rad::dev_page_refill_chunks(a.owner).empty());
|
||||
std::vector<rad::PageSpan> spans;
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
CHECK(spans.empty());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* The kept copy is exact: the park swaps, copies nothing, and the restore copies it back. */
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.reused, res.freed[0]);
|
||||
CHECK_EQ(res.file, 0);
|
||||
CHECK_EQ(res.host, 0);
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
CHECK(spans.empty());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* Dropped while parked, the copies leave the chunks to the owner again. */
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(rad::dev_page_drop_host(a.owner) >= kParkBytes);
|
||||
CHECK_EQ(rad::dev_page_refill_chunks(a.owner).size(), (size_t)4);
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
REQUIRE_EQ(spans.size(), (size_t)1);
|
||||
CHECK_OK(a.upload());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* A fill that fails gives its host memory back and leaves the chunks to be refilled. */
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
const int64_t host0 = rad::dev_page_host_bytes();
|
||||
const std::vector<rad::PageSpan> again = rad::dev_page_refill_chunks(a.owner);
|
||||
CHECK_OK(rad::dev_page_fill_begin(a.owner, again));
|
||||
CHECK(rad::dev_page_host_bytes() >= host0 + kParkBytes);
|
||||
rad::dev_page_fill_end(a.owner, again, false);
|
||||
CHECK_EQ(rad::dev_page_host_bytes(), host0);
|
||||
CHECK_EQ(rad::dev_page_refill_chunks(a.owner).size(), (size_t)4);
|
||||
spans.clear();
|
||||
CHECK_OK(rad::dev_page_in(a.owner, &spans));
|
||||
CHECK_EQ(spans.size(), (size_t)1);
|
||||
CHECK_OK(a.upload());
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* Parked to host memory, the allocation stays mapped at its address: the card reads it and writes
|
||||
* it there, over the link, and a restore brings back what was written meanwhile. A second park
|
||||
* of the sealed allocation, its host copy kept, leaves by a swap of mappings and copies nothing. */
|
||||
TEST(a_parked_chunk_is_read_and_written_in_place_from_host_memory) {
|
||||
if (!need_vmem()) return;
|
||||
Paged a(9109, kParkBytes, 41u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::PageOut req;
|
||||
req.host_budget = (int64_t)1 << 30;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.host >= kParkBytes);
|
||||
CHECK(rad::dev_page_host_bytes() >= kParkBytes);
|
||||
CHECK_EQ(a.first_bad(), -1); /* read in place, out of host memory */
|
||||
a.want[(size_t)(100 << 20)] ^= 0x3c; /* written in place */
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_invalidate((char*)a.d + (100 << 20), 1);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.host, 0);
|
||||
CHECK_EQ(res.reused, res.freed[0]);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* The kept copies go; the host memory with them. */
|
||||
const int64_t before = rad::dev_page_host_bytes();
|
||||
CHECK(rad::dev_page_drop_copies(a.owner) >= kParkBytes);
|
||||
CHECK(rad::dev_page_host_bytes() <= before - kParkBytes);
|
||||
}
|
||||
|
||||
/* A live restore leaves a sealed allocation's chunks in host memory, read in place; promotion
|
||||
* moves them onto the card in a quiet window. A write that lands between the promotion's copy and
|
||||
* its swap (here, inside the quiet hook before the swap runs) is copied again, not lost. */
|
||||
TEST(a_live_restore_serves_from_host_memory_until_promoted) {
|
||||
if (!need_vmem()) return;
|
||||
Paged a(9110, kParkBytes, 51u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::PageOut req;
|
||||
req.host_budget = (int64_t)1 << 30;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
int64_t left = 0;
|
||||
CHECK_OK(rad::dev_page_in_live(a.owner, &left));
|
||||
CHECK_EQ(left, res.freed[0]);
|
||||
CHECK_EQ(rad::dev_page_live_bytes(a.owner), left);
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
bool wrote = false;
|
||||
auto quiet = [&](const std::function<int()>& fn) -> int {
|
||||
if (!wrote) {
|
||||
wrote = true;
|
||||
a.want[(size_t)(10 << 20)] ^= 0x77;
|
||||
if (a.upload() < 0) return RAD_E_DEVICE;
|
||||
rad::dev_page_invalidate((char*)a.d + (10 << 20), 1);
|
||||
}
|
||||
return fn();
|
||||
};
|
||||
/* One chunk at a time: the write lands in the first. */
|
||||
int64_t moved = 0;
|
||||
for (int k = 0; k < 8; ++k) {
|
||||
const int64_t n = rad::dev_page_promote(a.owner, kParkChunk, quiet);
|
||||
CHECK(n >= 0);
|
||||
if (n <= 0) break;
|
||||
moved += n;
|
||||
}
|
||||
CHECK_EQ(moved, left);
|
||||
CHECK_EQ(rad::dev_page_live_bytes(a.owner), 0);
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
/* Promoted with its host copy kept: the next park is a swap. */
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.host, 0);
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* Parked to the disk tier alone, then read into host memory while it waits: the chunks are
|
||||
* readable in place there, and the restore copies them over the link. */
|
||||
TEST(a_chunk_parked_on_the_drive_fills_into_host_memory_and_comes_back_exact) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
CHECK(!dir.empty());
|
||||
Paged a(9111, kParkBytes, 61u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK_EQ(res.host, 0);
|
||||
const int64_t out = res.freed[0];
|
||||
CHECK_EQ(rad::dev_page_fillable(a.owner), out);
|
||||
const int64_t held = rad::dev_page_host_bytes();
|
||||
/* One chunk, then the rest. */
|
||||
CHECK_EQ(rad::dev_page_fill_host(a.owner, 1), kParkChunk);
|
||||
CHECK_EQ(rad::dev_page_fillable(a.owner), out - kParkChunk);
|
||||
CHECK_EQ(rad::dev_page_fill_host(a.owner, INT64_MAX), out - kParkChunk);
|
||||
CHECK_EQ(rad::dev_page_fillable(a.owner), 0);
|
||||
CHECK_EQ(rad::dev_page_fill_host(a.owner, INT64_MAX), 0);
|
||||
CHECK_EQ(rad::dev_page_host_bytes() - held, out);
|
||||
CHECK_EQ(a.first_bad(), -1); /* read in place from host memory */
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
CHECK_EQ(rad::dev_page_host_bytes(), held);
|
||||
}
|
||||
|
||||
/* A chunk read in place from host memory and written there (a live restore after a fill from the
|
||||
* drive) has its host copy as its only exact one: the drive's copy is stale. Promoted onto the
|
||||
* card and its host copy then let go, the next park writes it again rather than unmapping it
|
||||
* against the drive, and it comes back with the write. */
|
||||
TEST(a_chunk_written_in_place_does_not_go_out_against_its_stale_drive_copy) {
|
||||
if (!need_vmem()) return;
|
||||
const std::string dir = park_dir();
|
||||
CHECK(!dir.empty());
|
||||
Paged a(9112, kParkBytes, 71u);
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_seal(a.d);
|
||||
rad::PageOut req;
|
||||
req.host_budget = 0;
|
||||
req.dir = dir;
|
||||
rad::PageResult res;
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
const int64_t out = res.freed[0];
|
||||
CHECK_EQ(rad::dev_page_fill_host(a.owner, INT64_MAX), out);
|
||||
int64_t left = 0;
|
||||
CHECK_OK(rad::dev_page_in_live(a.owner, &left));
|
||||
CHECK_EQ(left, out);
|
||||
a.want[(size_t)(10 << 20)] ^= 0x5a; /* written in place, in host memory */
|
||||
CHECK_OK(a.upload());
|
||||
rad::dev_page_invalidate((char*)a.d + (10 << 20), 1);
|
||||
int64_t moved = 0;
|
||||
for (int k = 0; k < 64; ++k) {
|
||||
const int64_t n = rad::dev_page_promote(a.owner, INT64_MAX,
|
||||
[](const std::function<int()>& fn) { return fn(); });
|
||||
CHECK(n >= 0);
|
||||
if (n <= 0) break;
|
||||
moved += n;
|
||||
}
|
||||
CHECK_EQ(moved, left);
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
(void)rad::dev_page_drop_copies(a.owner);
|
||||
CHECK_OK(rad::dev_page_out(a.owner, req, &res));
|
||||
CHECK(res.disk >= kParkChunk); /* the written chunk, at least, went to the drive again */
|
||||
CHECK_OK(rad::dev_page_in(a.owner));
|
||||
CHECK_EQ(a.first_bad(), -1);
|
||||
}
|
||||
|
||||
/* Granules mapped and unmapped at random, so the physical pages a freed granule held come back
|
||||
* under other addresses and addresses come back on other pages: each live granule must hold only
|
||||
* what was last written to it. On Linux 7.1 with gfx1201 an address mapped again kept its previous
|
||||
* page until the cards' translations were flushed in full (dev_settle_maps, which VMem::commit
|
||||
* runs): two live granules then shared a page and one's writes showed in the other. A process that
|
||||
* opens the render node meanwhile (rocm-smi) made the alias far more frequent, so this is also run
|
||||
* beside one. */
|
||||
TEST(granules_remapped_at_random_never_share_a_page) {
|
||||
if (!need_vmem()) return;
|
||||
const int64_t g = rad::VMem::granularity();
|
||||
constexpr int kGranules = 128, kCycles = 1000;
|
||||
/* Each granule's head and tail are written and read back: a page two granules share shows
|
||||
* at both ends. */
|
||||
constexpr int64_t kProbe = 4096;
|
||||
rad_dev_set(0);
|
||||
rad::VMem v;
|
||||
CHECK_OK(v.reserve(kGranules * g));
|
||||
RadStream s = nullptr;
|
||||
CHECK_OK(rad_stream_create(&s, 0));
|
||||
uint32_t* stage = static_cast<uint32_t*>(rad_dev_alloc(kProbe, RAD_MEM_HOST_PINNED));
|
||||
uint32_t* back = static_cast<uint32_t*>(rad_dev_alloc(kGranules * 2 * kProbe, RAD_MEM_HOST_PINNED));
|
||||
CHECK(stage && back);
|
||||
std::vector<uint32_t> tag(kGranules, 0); /* the word a live granule holds; 0: unmapped */
|
||||
uint32_t next = 1;
|
||||
std::mt19937 rng(20261106u);
|
||||
char* const base = static_cast<char*>(v.base());
|
||||
auto map = [&](int i) -> int {
|
||||
if (const int rc = v.commit(i * g, g); rc < 0) return rc;
|
||||
tag[i] = next++;
|
||||
std::fill(stage, stage + kProbe / 4, tag[i]);
|
||||
if (const int rc = rad_memcpy_async(base + i * g, stage, kProbe, s); rc < 0) return rc;
|
||||
if (const int rc = rad_memcpy_async(base + (i + 1) * g - kProbe, stage, kProbe, s); rc < 0) return rc;
|
||||
return rad_stream_sync(s);
|
||||
};
|
||||
for (int i = 0; i < kGranules; i += 2) CHECK_OK(map(i));
|
||||
int bad = 0, first_bad_cycle = -1, first_bad_granule = -1;
|
||||
for (int c = 0; c < kCycles && bad == 0; ++c) {
|
||||
std::vector<int> live, dead;
|
||||
for (int i = 0; i < kGranules; ++i) (tag[i] ? live : dead).push_back(i);
|
||||
if (!live.empty() && (dead.empty() || rng() % 2)) {
|
||||
const int i = live[rng() % live.size()];
|
||||
CHECK_OK(v.decommit(i * g, g));
|
||||
tag[i] = 0;
|
||||
continue;
|
||||
}
|
||||
CHECK_OK(map(dead[rng() % dead.size()]));
|
||||
/* Every live granule's head and tail, in one batch. */
|
||||
int k = 0;
|
||||
for (int i = 0; i < kGranules; ++i) {
|
||||
if (!tag[i]) continue;
|
||||
char* dst = reinterpret_cast<char*>(back) + (int64_t)k * 2 * kProbe;
|
||||
CHECK_OK(rad_memcpy_async(dst, base + i * g, kProbe, s));
|
||||
CHECK_OK(rad_memcpy_async(dst + kProbe, base + (i + 1) * g - kProbe, kProbe, s));
|
||||
++k;
|
||||
}
|
||||
CHECK_OK(rad_stream_sync(s));
|
||||
k = 0;
|
||||
for (int i = 0; i < kGranules; ++i) {
|
||||
if (!tag[i]) continue;
|
||||
const uint32_t* w = back + (int64_t)k * 2 * kProbe / 4;
|
||||
for (int64_t j = 0; j < 2 * kProbe / 4; ++j)
|
||||
if (w[j] != tag[i]) {
|
||||
if (bad++ == 0) { first_bad_cycle = c; first_bad_granule = i; }
|
||||
break;
|
||||
}
|
||||
++k;
|
||||
}
|
||||
}
|
||||
if (bad) fprintf(stderr, " %d granule(s) held another's bytes, first granule %d at cycle %d\n", bad,
|
||||
first_bad_granule, first_bad_cycle);
|
||||
CHECK_EQ(bad, 0);
|
||||
rad_dev_free(stage, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
rad_stream_destroy(s);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN_HOST_KARGS()
|
||||
+46
-5
@@ -17,7 +17,7 @@
|
||||
#include "diag/diag.h"
|
||||
#include "gen_config.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
@@ -500,8 +500,8 @@ TEST(a_run_started_anyway_says_so_at_the_top) {
|
||||
CHECK(text.find("--proceed-with-incompatible-configuration") != std::string::npos);
|
||||
CHECK(text.find("1 incompatible (started anyway)") != std::string::npos);
|
||||
CHECK(text.find("INCOMPATIBLE cwsr-off") != std::string::npos);
|
||||
const nlohmann::json j =
|
||||
nlohmann::json::parse(diag::to_json({}, {}, f, run, found), nullptr, false);
|
||||
const Json j =
|
||||
Json::parse(diag::to_json({}, {}, f, run, found), nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
if (j.is_discarded()) return;
|
||||
CHECK(j["unsupported_configuration"] == true);
|
||||
@@ -679,7 +679,7 @@ TEST(a_value_that_is_not_utf8_does_not_break_the_json) {
|
||||
std::string out;
|
||||
try { out = diag::to_json(rows, {}, f, diag::RunFacts{}, {}); } catch (...) { threw = true; }
|
||||
CHECK(!threw);
|
||||
const nlohmann::json j = nlohmann::json::parse(out, nullptr, false);
|
||||
const Json j = Json::parse(out, nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
if (j.is_discarded()) return;
|
||||
CHECK(j["configuration"][0]["value"].get<std::string>() == "/m/caf\xef\xbf\xbd.rad");
|
||||
@@ -736,7 +736,7 @@ TEST(the_json_carries_every_section) {
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad" });
|
||||
CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), 0);
|
||||
const nlohmann::json j = nlohmann::json::parse(
|
||||
const Json j = Json::parse(
|
||||
diag::to_json(diag::config_rows(c), {}, f, diag::RunFacts{}, found), nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
if (j.is_discarded()) return;
|
||||
@@ -750,4 +750,45 @@ TEST(the_json_carries_every_section) {
|
||||
CHECK(text.find("WARN link-below-max") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(a_card_sample_reads_temperatures_by_label_and_the_current_level) {
|
||||
Root r;
|
||||
const std::string d = "/sys/bus/pci/devices/0000:03:00.0";
|
||||
r.put(d + "/power_dpm_force_performance_level", "auto\n");
|
||||
r.put(d + "/pp_dpm_sclk", "0: 500Mhz\n1: 1800Mhz *\n2: 2350Mhz\n");
|
||||
r.put(d + "/pp_dpm_mclk", "0: 96Mhz\n1: 1258Mhz *\n");
|
||||
r.put(d + "/gpu_busy_percent", "0\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp1_input", "45000\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp1_label", "edge\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp2_input", "61000\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp2_label", "junction\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp3_input", "52000\n");
|
||||
r.put(d + "/hwmon/hwmon3/temp3_label", "mem\n");
|
||||
r.put(d + "/hwmon/hwmon3/power1_input", "31000000\n"); /* no power1_average: the instant reading */
|
||||
/* A card whose driver labels nothing: its temp1 is the edge sensor. */
|
||||
const std::string e = "/sys/bus/pci/devices/0000:07:00.0";
|
||||
r.put(e + "/hwmon/hwmon5/temp1_input", "38000\n");
|
||||
r.put(e + "/hwmon/hwmon5/power1_average", "12000000\n");
|
||||
r.put(e + "/hwmon/hwmon5/power1_input", "99000000\n");
|
||||
|
||||
const auto s = diag::sample_cards(r.dir, { "0000:03:00.0", "0000:07:00.0", "0000:0b:00.0" });
|
||||
REQUIRE(s.size() == 3);
|
||||
CHECK_EQ(s[0].perf_level, std::string("auto"));
|
||||
CHECK_EQ(s[0].sclk_cur, std::string("1800Mhz"));
|
||||
CHECK_EQ(s[0].mclk_cur, std::string("1258Mhz"));
|
||||
CHECK_EQ(s[0].busy_percent, 0);
|
||||
CHECK_EQ(s[0].edge_mc, (int64_t)45000);
|
||||
CHECK_EQ(s[0].junction_mc, (int64_t)61000);
|
||||
CHECK_EQ(s[0].mem_mc, (int64_t)52000);
|
||||
CHECK_EQ(s[0].power_uw, (int64_t)31000000);
|
||||
CHECK_EQ(s[1].edge_mc, (int64_t)38000);
|
||||
CHECK_EQ(s[1].junction_mc, (int64_t)-1);
|
||||
CHECK_EQ(s[1].power_uw, (int64_t)12000000); /* the average, when there is one */
|
||||
CHECK(s[1].perf_level.empty());
|
||||
/* A card with no files at all is all unknown, not an error. */
|
||||
CHECK_EQ(s[2].bdf, std::string("0000:0b:00.0"));
|
||||
CHECK_EQ(s[2].edge_mc, (int64_t)-1);
|
||||
CHECK_EQ(s[2].power_uw, (int64_t)-1);
|
||||
CHECK(s[2].sclk_cur.empty());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
||||
/* e2e_config.h -- the server command line an end-to-end test starts, as the YAML file the server
|
||||
* reads (core/fleet/config.h).
|
||||
*
|
||||
* The tests state their settings as flags, the spelling the option table and its messages use. The
|
||||
* server takes only `--config FILE`, so each start writes the flags as a file with the converter
|
||||
* the server's own refusal message prints, and runs the server on it.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_test.h"
|
||||
#include "fleet/config.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
namespace radtest {
|
||||
|
||||
/* {server, flags...} becomes {server, "--config", FILE}; FILE is a fresh name in the test's
|
||||
* temporary directory, left there for a failing case's record. */
|
||||
inline std::vector<std::string> config_argv(const std::vector<std::string>& argv) {
|
||||
static std::atomic<int> seq{ 0 };
|
||||
std::vector<char*> raw;
|
||||
std::vector<std::string> store(argv);
|
||||
for (std::string& a : store) raw.push_back(a.data());
|
||||
const std::string path = tmp_path("server." + std::to_string(::getpid()) + "." +
|
||||
std::to_string(seq++) + ".yaml");
|
||||
std::ofstream(path) << rad::fleet::yaml_from_args((int)raw.size(), raw.data());
|
||||
return { argv.front(), "--config", path };
|
||||
}
|
||||
|
||||
} // namespace radtest
|
||||
+391
-109
@@ -20,13 +20,15 @@
|
||||
* Every child gets ROCR_VISIBLE_DEVICES=99, so a machine with a card still runs the host backend.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "e2e_config.h"
|
||||
#include "tiny_golden.h"
|
||||
#include "lfm3_golden.h"
|
||||
#include "tiny_model.h"
|
||||
|
||||
#include "mm/media.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
@@ -36,13 +38,15 @@
|
||||
#include <cerrno>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using json = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -73,7 +77,7 @@ std::vector<std::string> engine_argv(const std::string& model,
|
||||
if (!kernels) { a.push_back("--kernels"); a.push_back("libref"); }
|
||||
if (ref) a.push_back("--debug-accept-reference-kernels");
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
return a;
|
||||
return radtest::config_argv(a);
|
||||
}
|
||||
|
||||
/* As a deployment runs: the arguments as given, so a reference library serves nothing. */
|
||||
@@ -81,7 +85,7 @@ std::vector<std::string> serving_argv(const std::string& model,
|
||||
const std::vector<std::string>& args) {
|
||||
std::vector<std::string> a = { RAD_E2E_SERVER, "--model", model };
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
return a;
|
||||
return radtest::config_argv(a);
|
||||
}
|
||||
|
||||
/* The shape the preemption cases run in: four sequences of at most 512 tokens, 256 a step. Their
|
||||
@@ -190,13 +194,12 @@ std::string words(tiny::Rng& r, size_t n) {
|
||||
struct World {
|
||||
/* RAD_E2E_KEEP keeps the checkpoints for tests/mktinygolden.py, which reads them. */
|
||||
tiny::TempDir dir{ "e2e", std::getenv("RAD_E2E_KEEP") != nullptr };
|
||||
std::string qwen35, lfm2, gemma4, llama, llama_rad;
|
||||
/* llama.rad with its lm head block fp8, and int8 per (row, 128 of K). */
|
||||
std::string llama_fp8head, llama_i8head;
|
||||
std::string qwen35, lfm2, lfm3, gemma4, llama, llama_rad;
|
||||
/* llama.rad with its lm head int8 per (row, 128 of K). */
|
||||
std::string llama_i8head;
|
||||
/* The llama as an int4 W4A16 release with zero points (tiny_model.h, write_llama_ct_int4),
|
||||
* and its container through the import rule. */
|
||||
std::string llama_int4, llama_int4_rad;
|
||||
std::string llama_mxfp4; /* llama's trunk as OCP-MXFP4 */
|
||||
/* qwen35 and gemma4 with 4 KiB of KV a token (wider KV heads), for the preemption cases: a MiB
|
||||
* of device is then about 256 tokens of pool, fine enough for small_device() to land between
|
||||
* one request and four. */
|
||||
@@ -229,14 +232,13 @@ struct World {
|
||||
fprintf(stderr, " checkpoints kept in %s\n", dir.path.c_str());
|
||||
qwen35 = dir / "qwen35";
|
||||
lfm2 = dir / "lfm2";
|
||||
lfm3 = dir / "lfm3";
|
||||
gemma4 = dir / "gemma4";
|
||||
llama = dir / "llama";
|
||||
llama_rad = dir / "llama.rad";
|
||||
llama_fp8head = dir / "llama_fp8head.rad";
|
||||
llama_i8head = dir / "llama_i8head.rad";
|
||||
llama_int4 = dir / "llama_int4";
|
||||
llama_int4_rad = dir / "llama_int4.rad";
|
||||
llama_mxfp4 = dir / "llama_mxfp4.rad";
|
||||
qwen35_kv = dir / "qwen35_kv";
|
||||
gemma4_kv = dir / "gemma4_kv";
|
||||
qwen35_spec = dir / "qwen35_spec";
|
||||
@@ -246,7 +248,7 @@ struct World {
|
||||
g31_df2 = dir / "g31_df2.rad";
|
||||
g31w = dir / "g31w";
|
||||
g31w_df2 = dir / "g31w_df2.rad";
|
||||
for (const std::string* d : { &qwen35, &lfm2, &gemma4, &llama, &qwen35_kv, &gemma4_kv,
|
||||
for (const std::string* d : { &qwen35, &lfm2, &lfm3, &gemma4, &llama, &qwen35_kv, &gemma4_kv,
|
||||
&qwen35_spec, &qwen3asr, &llama_int4, &g31, &g31_draft, &g31w })
|
||||
if (mkdir(d->c_str(), 0755) != 0) return;
|
||||
tiny::Qwen35 qkv;
|
||||
@@ -270,17 +272,15 @@ struct World {
|
||||
tiny::Gemma4 g31ws = g31s;
|
||||
g31ws.window = 1024;
|
||||
if (!tiny::write_qwen35(qwen35, {}) || !tiny::write_lfm2(lfm2, {}) ||
|
||||
!tiny::write_lfm3(lfm3, {}) ||
|
||||
!tiny::write_gemma4(gemma4, {}) || !tiny::write_llama(llama, {}) ||
|
||||
!tiny::write_qwen35(qwen35_kv, qkv) || !tiny::write_gemma4(gemma4_kv, gkv) ||
|
||||
!tiny::write_qwen35(qwen35_spec, qspec) || !tiny::write_qwen3asr(qwen3asr, {}) ||
|
||||
!tiny::write_text(dir / "llama.recipe", tiny::kLlamaFp8Recipe) ||
|
||||
!tiny::write_text(dir / "llama_fp8head.recipe",
|
||||
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaFp8HeadRule) ||
|
||||
!tiny::write_text(dir / "llama.recipe", tiny::kLlamaI8Recipe) ||
|
||||
!tiny::write_text(dir / "llama_i8head.recipe",
|
||||
std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaI8HeadRule) ||
|
||||
std::string(tiny::kLlamaI8Recipe) + tiny::kLlamaI8HeadRule) ||
|
||||
!tiny::write_llama_ct_int4(llama_int4, {}, true) ||
|
||||
!tiny::write_text(dir / "llama_int4.recipe", tiny::kInt4ImportRecipe) ||
|
||||
!tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe) ||
|
||||
!tiny::write_gemma4(g31, g31s) || !tiny::write_gemma4(g31w, g31ws) ||
|
||||
!tiny::write_dflash2(g31_draft, {}))
|
||||
return;
|
||||
@@ -302,10 +302,8 @@ struct World {
|
||||
|
||||
const struct { std::string out; const char* recipe; const std::string* ckpt; }
|
||||
kConverts[] = { { llama_rad, "llama.recipe", &llama },
|
||||
{ llama_fp8head, "llama_fp8head.recipe", &llama },
|
||||
{ llama_i8head, "llama_i8head.recipe", &llama },
|
||||
{ llama_int4_rad, "llama_int4.recipe", &llama_int4 },
|
||||
{ llama_mxfp4, "llama_mxfp4.recipe", &llama } };
|
||||
{ llama_int4_rad, "llama_int4.recipe", &llama_int4 } };
|
||||
for (const auto& [out, recipe, ckpt] : kConverts) {
|
||||
const int st = tiny::run({ RAD_E2E_CONVERT, *ckpt, "-o", out, "--recipe",
|
||||
dir / recipe },
|
||||
@@ -473,6 +471,20 @@ struct Server {
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
if (!child.start(serving ? serving_argv(model, a) : engine_argv(model, a), engine_env(env)))
|
||||
return false;
|
||||
return listening();
|
||||
}
|
||||
|
||||
/* A whole configuration file, for a process of several models. */
|
||||
bool start_yaml(const std::string& yaml, const std::vector<std::string>& env = {}) {
|
||||
static int seq = 0;
|
||||
const std::string path = radtest::tmp_path("fleet." + std::to_string(seq++) + ".yaml");
|
||||
std::ofstream(path) << yaml;
|
||||
if (!child.start({ RAD_E2E_SERVER, "--config", path }, engine_env(env))) return false;
|
||||
return listening();
|
||||
}
|
||||
|
||||
/* Drains the child's output and waits for the listen line; the port it names. */
|
||||
bool listening() {
|
||||
drain = std::thread([this] {
|
||||
char buf[4096];
|
||||
for (;;) {
|
||||
@@ -705,6 +717,128 @@ TEST(qwen35_preemption_by_recompute_changes_no_logit) {
|
||||
CHECK(n > 0);
|
||||
}
|
||||
|
||||
/* The diagnose mode end to end: the real binary starts as a serve would, runs its own workload
|
||||
* through the scheduler, and writes a report whose sections are the ones the report format
|
||||
* declares. Its arithmetic is tests/diagnose_test.cpp's; this is that the driver runs at all, that
|
||||
* every prompt was salted and the cache emptied (no request reports a cached token), and that a
|
||||
* second run on the same build reproduces every request's tokens, which is what --diagnose-baseline
|
||||
* compares. The numbers themselves are a card's measurement, not this test's.
|
||||
*
|
||||
* The model, the corpus and the baseline all live under a directory named after a marker: the
|
||||
* report is pasted into issues, so no path of the machine may reach it, and a variable whose name
|
||||
* is an allowed prefix plus a secret suffix must not be reported at all. */
|
||||
TEST(the_diagnose_mode_measures_itself_and_reproduces_its_tokens) {
|
||||
World& w = world();
|
||||
tiny::TempDir d("diagnose");
|
||||
REQUIRE(d.ok());
|
||||
const std::string private_dir = d / "MARKER-private-home";
|
||||
REQUIRE_EQ(mkdir(private_dir.c_str(), 0755), 0);
|
||||
const std::string model = private_dir + "/model.rad";
|
||||
REQUIRE_EQ(symlink(w.llama_rad.c_str(), model.c_str()), 0);
|
||||
const std::string corpus = private_dir + "/corpus.jsonl";
|
||||
std::string body;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
tiny::Rng r(40 + i);
|
||||
body += json{ { "category", "prose" }, { "prompt", words(r, 120) }, { "max_tokens", 8 } }
|
||||
.dump() + "\n";
|
||||
}
|
||||
REQUIRE(tiny::write_text(corpus, body));
|
||||
/* One point of each sweep, one measured run: the driver's whole shape, quickly. */
|
||||
const std::vector<std::string> shared = {
|
||||
"--diagnose-corpus", corpus, "--diagnose-tokens", "8", "--diagnose-runs", "1",
|
||||
"--diagnose-concurrency", "1", "--diagnose-prefill", "512",
|
||||
"--max-model-len", "1024", "--max-num-seqs", "2", "--max-num-batched-tokens", "256" };
|
||||
std::vector<std::string> a = { "--diagnose", d / "first" };
|
||||
a.insert(a.end(), shared.begin(), shared.end());
|
||||
const Ran r = radiance(model, a, { "RADIANCE_API_KEY_SYNTHETIC_SECRET_IN_NAME=x" }, 600);
|
||||
REQUIRE_RAN(r);
|
||||
|
||||
std::string text;
|
||||
{
|
||||
const std::string path = d.path + "/first/diagnose.json";
|
||||
FILE* f = std::fopen(path.c_str(), "rb");
|
||||
REQUIRE(f != nullptr);
|
||||
char buf[4096];
|
||||
for (size_t n; (n = std::fread(buf, 1, sizeof buf, f)) > 0;) text.append(buf, n);
|
||||
std::fclose(f);
|
||||
}
|
||||
const json rep = json::parse(text, nullptr, false);
|
||||
REQUIRE(rep.is_object());
|
||||
for (const char* k : { "engine", "workload", "categories", "concurrency", "prefill",
|
||||
"interference", "environment", "not_measured", "verdict", "problems",
|
||||
"warnings" })
|
||||
CHECK(rep.contains(k));
|
||||
CHECK_EQ(rep["verdict"].get<std::string>(), std::string("valid"));
|
||||
CHECK_EQ(rep["problems"].size(), (size_t)0);
|
||||
/* Every point of the workload ran: three prose prompts once each, one stream, one 512-token
|
||||
* prefill, and a prompt arriving into a running stream. A point the engine could not run is
|
||||
* named in the report, never left as a zero. */
|
||||
REQUIRE_EQ(rep["categories"].size(), (size_t)1);
|
||||
const json& cat = rep["categories"][0];
|
||||
CHECK_EQ(cat["prompts"].get<int64_t>(), (int64_t)3);
|
||||
CHECK_EQ(cat["runs"].size(), (size_t)3);
|
||||
CHECK_EQ(rep["concurrency"].size(), (size_t)1);
|
||||
CHECK_EQ(rep["concurrency"][0]["streams"].get<int64_t>(), (int64_t)1);
|
||||
REQUIRE_EQ(rep["prefill"].size(), (size_t)1);
|
||||
CHECK_EQ(rep["prefill"][0]["prompt_tokens"].get<int64_t>(), (int64_t)512);
|
||||
CHECK(rep["interference"]["runs"][0]["arrival_ttft_ms"].get<double>() > 0);
|
||||
CHECK(rep["interference"]["runs"][0]["interference"]["stall_ratio"].get<double>() > 0);
|
||||
|
||||
/* Salted and uncached, and the step ring lost nothing: the workload's own statement of its
|
||||
* validity, checked afterwards from what each run recorded. */
|
||||
int64_t cached = 0, lost = 0;
|
||||
for (const json& run : cat["runs"]) {
|
||||
cached += run["requests"]["cached_prompt_tokens"].get<int64_t>();
|
||||
lost += run["steps"]["lost"].get<int64_t>();
|
||||
CHECK(run["steps"]["recorded"].get<int64_t>() > 0);
|
||||
CHECK(run["requests"]["outputs"][0].size() > 0);
|
||||
}
|
||||
CHECK_EQ(cached, (int64_t)0);
|
||||
CHECK_EQ(lost, (int64_t)0);
|
||||
/* What the run was taken under, and whether its runs agree. The verdict itself is not held
|
||||
* here: these are a CI host's timings. */
|
||||
REQUIRE(rep.contains("conditions"));
|
||||
CHECK_EQ(rep["conditions"]["fingerprint"].get<std::string>().size(), (size_t)16);
|
||||
CHECK(rep["conditions"]["cards"].empty()); /* the host backend serves no card */
|
||||
CHECK(rep["stability"].contains("verdict"));
|
||||
CHECK_EQ(cat["prompts_summary"].size(), (size_t)3);
|
||||
CHECK(rep["thermal"]["cards"].empty());
|
||||
CHECK(rep["reproducibility"].is_array());
|
||||
/* Names, not values: the report is pasted into issues. */
|
||||
for (const json& n : rep["environment"]["variables"])
|
||||
CHECK(n.get<std::string>().find('=') == std::string::npos);
|
||||
/* No path and no secret-suffixed name in either artifact of either run. */
|
||||
for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) {
|
||||
CHECK(text.find(marker) == std::string::npos);
|
||||
CHECK(tiny::read_text(d.path + "/first/diagnose.md").find(marker) == std::string::npos);
|
||||
}
|
||||
|
||||
/* The same build, the same workload: identical tokens, which is what the baseline compares. */
|
||||
const std::string baseline = private_dir + "/baseline.json";
|
||||
REQUIRE(tiny::write_text(baseline, text));
|
||||
std::vector<std::string> b = { "--diagnose", d / "second", "--diagnose-baseline", baseline };
|
||||
b.insert(b.end(), shared.begin(), shared.end());
|
||||
const Ran r2 = radiance(model, b, {}, 600);
|
||||
REQUIRE_RAN(r2);
|
||||
const std::string json2 = tiny::read_text(d.path + "/second/diagnose.json");
|
||||
const std::string md = tiny::read_text(d.path + "/second/diagnose.md");
|
||||
CHECK(md.find("# Diagnosis") == 0);
|
||||
CHECK(md.find("**Verdict: valid**") != std::string::npos);
|
||||
CHECK(md.find("## Parity") != std::string::npos);
|
||||
CHECK(md.find("## Reproducibility") != std::string::npos);
|
||||
{
|
||||
/* Two runs on one machine, one after the other: the same conditions. */
|
||||
const json rep2 = json::parse(json2, nullptr, false);
|
||||
REQUIRE(rep2.is_object());
|
||||
CHECK(rep2["parity"]["conditions"].is_array());
|
||||
CHECK(rep2["parity"]["conditions"].empty());
|
||||
}
|
||||
for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) {
|
||||
CHECK(json2.find(marker) == std::string::npos);
|
||||
CHECK(md.find(marker) == std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
/* A document longer than the whole KV pool could never be admitted: admission takes only a chunk
|
||||
* the pool can hold, so it would wait at the head of the queue forever. The run is refused before
|
||||
* anything is scored, naming the document's length and the pool's. Bounded by a timeout, so the
|
||||
@@ -772,22 +906,6 @@ TEST(a_checkpoint_store_the_host_cannot_hold_is_refused_at_startup) {
|
||||
CHECK(named);
|
||||
}
|
||||
|
||||
/* --attn-prefill-fp8 is a permission an exact kernel also satisfies. The host libraries have no
|
||||
* e4m3 attention, so asked for it the start is refused by the flag's name instead of serving the
|
||||
* exact form under it. */
|
||||
TEST(an_attention_fp8_mode_no_kernel_takes_is_refused_at_startup) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
const Ran r = radiance(w.qwen35, { "--host", "127.0.0.1", "--port", "0",
|
||||
"--attn-prefill-fp8", "both" }, {}, 120);
|
||||
const bool named = has(r.log, "not starting: --attn-prefill-fp8 both, but no attention kernel");
|
||||
if (r.status == 0 || r.status == 124 || !named)
|
||||
fprintf(stderr, " exited %d:\n%s\n", r.status, tail(r.log, 20).c_str());
|
||||
CHECK(r.status != 0);
|
||||
CHECK(r.status != 124);
|
||||
CHECK(named);
|
||||
}
|
||||
|
||||
/* The row split of a prefill's attention is a graph only a plugin that declares it can build, so
|
||||
* a plugin that does not (qwen35 here) is refused by the flag's name instead of serving the head
|
||||
* split under it. */
|
||||
@@ -986,58 +1104,6 @@ TEST(runtime_lora_scores_as_the_merged_checkpoint_does) {
|
||||
CHECK(kl > 0.05);
|
||||
}
|
||||
|
||||
/* An MXFP4 trunk: its GEMM's `group` is the weight's 32-wide exponent block, while the
|
||||
* activation it reads is scaled per 128, and the adapter's shrink reads that activation at the
|
||||
* activation's grid. Against the merged checkpoint, the adapter takes the container from the
|
||||
* adapter's whole effect down to the MXFP4 rounding, on libref and on libavx. (The tiny llama's
|
||||
* MXFP4 container declares at one rank only.) */
|
||||
TEST(runtime_lora_reads_an_mxfp4_trunks_activation_at_its_own_grid) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("e2e_lora_mx");
|
||||
const std::string adapter = d / "adapter", merged = d / "merged", ref = d / "ref";
|
||||
const std::vector<std::string> targets = { "q_proj", "k_proj", "v_proj", "o_proj",
|
||||
"gate_proj", "up_proj", "down_proj" };
|
||||
REQUIRE(tiny::write_lora(adapter, w.llama, targets, 8, 16.0, 23, 0.25f, merged));
|
||||
const std::vector<std::string> one = { "--max-num-batched-tokens", "512", "--max-num-seqs", "1" };
|
||||
std::vector<std::string> rec = { "--kld-record", ref, "--kld-corpus", w.corpus_short };
|
||||
rec.insert(rec.end(), one.begin(), one.end());
|
||||
const Ran recorded = radiance(merged, rec);
|
||||
REQUIRE_RAN(recorded);
|
||||
auto score = [&](const std::vector<std::string>& args, const std::vector<std::string>& env) {
|
||||
tiny::TempDir o("e2e_lora_mx_kld");
|
||||
std::vector<std::string> a = { "--kld-ref", ref, "--kld-out", o / "kld.json" };
|
||||
a.insert(a.end(), one.begin(), one.end());
|
||||
a.insert(a.end(), args.begin(), args.end());
|
||||
const Ran r = radiance(w.llama_mxfp4, a, env);
|
||||
if (r.status != 0) {
|
||||
fprintf(stderr, " child exited %d:\n%s\n", r.status, tail(r.log).c_str());
|
||||
return -1.0;
|
||||
}
|
||||
const json j = json::parse(tiny::read_text(o / "kld.json"), nullptr, false);
|
||||
return j.is_object() && j.contains("all") ? j["all"]["kld"]["mean"].get<double>() : -1.0;
|
||||
};
|
||||
const double base = score({}, {});
|
||||
fprintf(stderr, " the MXFP4 base against the merged checkpoint: mean KL %.3g\n", base);
|
||||
REQUIRE(base > 0.05);
|
||||
const std::vector<std::string> ad = { "--lora", "ad=" + adapter, "--kld-lora", "ad" };
|
||||
struct Arm { const char* what; std::vector<std::string> args, env; };
|
||||
std::vector<Arm> arms = { { "libref", ad, {} } };
|
||||
#if defined(__x86_64__)
|
||||
if (::access(RAD_E2E_HOME "/kernels/libavx.so", R_OK) == 0) {
|
||||
std::vector<std::string> avx = { "--kernels", "libavx" };
|
||||
avx.insert(avx.end(), ad.begin(), ad.end());
|
||||
arms.push_back({ "libavx", avx, {} });
|
||||
}
|
||||
#endif
|
||||
for (const Arm& a : arms) {
|
||||
const double kl = score(a.args, a.env);
|
||||
fprintf(stderr, " the MXFP4 container with the adapter, %s: mean KL %.3g\n", a.what, kl);
|
||||
CHECK(kl >= 0);
|
||||
CHECK(kl < base / 4);
|
||||
}
|
||||
}
|
||||
|
||||
/* Off is off: without --lora or --max-loras the declared graph names no adapter op, buffer or
|
||||
* declined GEMM, and with an adapter it is the same graph plus the adapter ops and their buffers
|
||||
* over the same weights. */
|
||||
@@ -1136,12 +1202,76 @@ TEST(runtime_lora_refuses_targets_it_cannot_serve_at_startup) {
|
||||
CHECK(has(s.log, "has the served model's own name"));
|
||||
}
|
||||
|
||||
/* LFM3's IQ8R container (data/recipes/lfm3-1.7b-iq8r.recipe) beside the bf16 container of the same
|
||||
* checkpoint, a tiny LFM3 at widths the recipe's scale group divides: the recipe quantises the
|
||||
* eight trunk linears of every layer and nothing else, the engine serves it, and its record stays
|
||||
* near the bf16 one. On random weights of this size rounding to int8 moves an agreed top token's
|
||||
* log-probability by up to 0.2 and changes the top token at one position in sixteen; a rotation
|
||||
* applied on one side only, or a scale plane read at the wrong group, leaves no resemblance. */
|
||||
TEST(lfm3_iq8r_container_tracks_the_bf16_one) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("e2e_lfm3_iq8r");
|
||||
tiny::Lfm3 spec;
|
||||
spec.hidden = 256; spec.heads = 4; spec.kv_heads = 2; spec.ffn = 512;
|
||||
const std::string ckpt = d / "ckpt";
|
||||
REQUIRE_EQ(mkdir(ckpt.c_str(), 0755), 0);
|
||||
REQUIRE(tiny::write_lfm3(ckpt, spec));
|
||||
REQUIRE(World::write_corpus(d / "corpus.jsonl", { kTinyGoldPrompt }));
|
||||
auto convert = [&](const std::string& out, bool iq8r, std::string* log) {
|
||||
std::vector<std::string> argv = { RAD_E2E_CONVERT, d / "ckpt", "-o", out };
|
||||
if (iq8r) {
|
||||
argv.push_back("--recipe");
|
||||
argv.push_back(RAD_E2E_RECIPES "/lfm3-1.7b-iq8r.recipe");
|
||||
}
|
||||
const int st = tiny::run(argv, engine_env({}), log);
|
||||
if (st != 0) fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(*log).c_str());
|
||||
return st;
|
||||
};
|
||||
std::string blog, qlog;
|
||||
REQUIRE_EQ(convert(d / "bf16.rad", false, &blog), 0);
|
||||
REQUIRE_EQ(convert(d / "iq8r.rad", true, &qlog), 0);
|
||||
/* 2 conv layers x 4 linears and 2 attention layers x 6; the gate is not among them */
|
||||
CHECK(qlog.find("20 quantised by the recipe") != std::string::npos);
|
||||
|
||||
struct Top { int32_t id; float lp; };
|
||||
const size_t row = 16 * sizeof(Top);
|
||||
auto record = [&](const char* name) {
|
||||
const std::string out = d / (std::string(name) + ".rec");
|
||||
Ran r = radiance(d / (std::string(name) + ".rad"),
|
||||
{ "--kld-record", out, "--kld-corpus", d / "corpus.jsonl" });
|
||||
if (r.status != 0) fprintf(stderr, " %s:\n%s\n", name, tail(r.log).c_str());
|
||||
return r.status == 0 ? tiny::read_text(out + "/top.bin") : std::string();
|
||||
};
|
||||
const std::string a = record("bf16"), q = record("iq8r");
|
||||
REQUIRE(!a.empty());
|
||||
REQUIRE_EQ(q.size(), a.size());
|
||||
REQUIRE(a != q); /* the int8 trunk is what ran */
|
||||
const int n = (int)(a.size() / row);
|
||||
int same = 0;
|
||||
double worst = 0;
|
||||
for (int p = 0; p < n; ++p) {
|
||||
Top x, y;
|
||||
std::memcpy(&x, a.data() + (size_t)p * row, sizeof x);
|
||||
std::memcpy(&y, q.data() + (size_t)p * row, sizeof y);
|
||||
if (x.id != y.id) continue;
|
||||
++same;
|
||||
worst = std::max(worst, (double)std::fabs(x.lp - y.lp));
|
||||
}
|
||||
fprintf(stderr, " lfm3 iq8r against bf16: %d of %d top tokens equal, worst |dlogp| %.4f\n",
|
||||
same, n, worst);
|
||||
CHECK(same * 10 >= n * 9);
|
||||
CHECK(worst < 0.5);
|
||||
}
|
||||
|
||||
/* ================================================================== against transformers */
|
||||
|
||||
/* Each family's forward pass against transformers' own, run in float32 over the same weights
|
||||
* (tests/tiny_golden.h, from tests/mktinygolden.py): the gated delta net with its query scale and
|
||||
* (1 + w) norms, the gated and partial-rotary attention, LFM2's convolutions, Gemma 4's sliding and
|
||||
* K-equals-V global layers, soft cap and layer scalars. bf16 activations put this engine within
|
||||
* K-equals-V global layers, soft cap and layer scalars; LFM3 against LiquidAI's own modelling code
|
||||
* (tests/lfm3_golden.h, from tests/mklfm3golden.py), for its sandwich norms, head gates, partial
|
||||
* rotary and sliding window. bf16 activations put this engine within
|
||||
* about 0.08 of transformers' log-probabilities; a wrong rotary width, window or epsilon moves
|
||||
* them by 0.5 or more and changes the top token at a tenth of the positions. So at every position
|
||||
* the top token must agree, unless transformers' own top two are within the bound, and the
|
||||
@@ -1151,16 +1281,22 @@ TEST(each_family_computes_what_transformers_computes) {
|
||||
REQUIRE(w.ok);
|
||||
tiny::TempDir d("e2e_gold");
|
||||
REQUIRE(World::write_corpus(d / "corpus.jsonl", { kTinyGoldPrompt }));
|
||||
for (const TinyGold& g : kTinyGold) {
|
||||
std::vector<const TinyGold*> golds;
|
||||
for (const TinyGold& g : kTinyGold) golds.push_back(&g);
|
||||
golds.push_back(&kLfm3Gold);
|
||||
for (const TinyGold* gp : golds) {
|
||||
const TinyGold& g = *gp;
|
||||
const std::string family = g.family;
|
||||
const std::string model = family == "qwen35" ? w.qwen35
|
||||
: family == "lfm2" ? w.lfm2
|
||||
: family == "lfm3" ? w.lfm3
|
||||
: w.gemma4;
|
||||
const uint64_t h = fnv1a(tiny::read_text(model + "/model.safetensors"));
|
||||
if (h != g.weights_fnv)
|
||||
fprintf(stderr, " %s: the checkpoint is not the one the golden was made from; "
|
||||
"regenerate tests/tiny_golden.h with tests/mktinygolden.py\n",
|
||||
g.family);
|
||||
"regenerate tests/%s\n",
|
||||
g.family, family == "lfm3" ? "lfm3_golden.h with tests/mklfm3golden.py"
|
||||
: "tiny_golden.h with tests/mktinygolden.py");
|
||||
REQUIRE_EQ(h, g.weights_fnv);
|
||||
const std::string out = d / family;
|
||||
Ran r = radiance(model, { "--kld-record", out, "--kld-corpus", d / "corpus.jsonl" });
|
||||
@@ -1206,6 +1342,15 @@ TEST(lfm2_chunking_and_batching_change_no_logit) {
|
||||
{ "--max-num-batched-tokens", "512", "--max-num-seqs", "4" });
|
||||
}
|
||||
|
||||
/* LFM3 has both states at once: the convolution's rolling window, seven taps wide, and an 8-token
|
||||
* attention window on its sliding layers, which every document crosses. */
|
||||
TEST(lfm3_chunking_and_batching_change_no_logit) {
|
||||
check_recording_matches(world().lfm3, world().corpus_short,
|
||||
{ "--max-num-batched-tokens", "64", "--max-num-seqs", "1" });
|
||||
check_recording_matches(world().lfm3, world().corpus_short,
|
||||
{ "--max-num-batched-tokens", "512", "--max-num-seqs", "4" });
|
||||
}
|
||||
|
||||
/* Gemma 4's sliding layers attend over a 32-token window, which every document crosses, and its
|
||||
* global layers read V from K at a wider head. */
|
||||
TEST(gemma4_chunking_and_batching_change_no_logit) {
|
||||
@@ -1323,6 +1468,7 @@ TEST(libavx_alone_serves_every_family_within_rounding_of_libref) {
|
||||
const struct { const char* name; const std::string* model; const std::string* corpus; }
|
||||
kRuns[] = { { "qwen35 on libavx", &w.qwen35, &w.corpus },
|
||||
{ "lfm2 on libavx", &w.lfm2, &w.corpus_short },
|
||||
{ "lfm3 on libavx", &w.lfm3, &w.corpus_short },
|
||||
{ "gemma4 on libavx", &w.gemma4, &w.corpus_short },
|
||||
{ "llama_fp8 on libavx", &w.llama_rad, &w.corpus_tiny },
|
||||
{ "qwen3asr's decoder on libavx", &w.qwen3asr, &w.corpus_short } };
|
||||
@@ -1617,7 +1763,6 @@ TEST(libavx_alone_serves_a_quantised_head_within_rounding_of_libref) {
|
||||
REQUIRE(world().ok);
|
||||
World& w = world();
|
||||
const struct { const char* name; const std::string* model; } kRuns[] = {
|
||||
{ "llama, fp8 head, on libavx alone", &w.llama_fp8head },
|
||||
{ "llama, int8 head, on libavx alone", &w.llama_i8head } };
|
||||
for (const auto& run : kRuns)
|
||||
check_within_rounding(run.name, score_against_reference(
|
||||
@@ -1675,7 +1820,8 @@ struct Family {
|
||||
const char* name;
|
||||
std::string World::*model;
|
||||
};
|
||||
const Family kSpecFamilies[] = { { "lfm2", &World::lfm2 }, { "gemma4", &World::gemma4 },
|
||||
const Family kSpecFamilies[] = { { "lfm2", &World::lfm2 }, { "lfm3", &World::lfm3 },
|
||||
{ "gemma4", &World::gemma4 },
|
||||
{ "qwen35", &World::qwen35_spec } };
|
||||
|
||||
const std::vector<int32_t>& repetitive_prompt() {
|
||||
@@ -1773,7 +1919,7 @@ TEST(concurrent_requests_return_what_each_returns_alone) {
|
||||
for (uint64_t i = 0; i < 4; ++i) prompts.push_back(prompt_ids(100 + i, 60 + 37 * i));
|
||||
const struct { const char* name; std::string World::*model; const char* n_spec; } kRuns[] = {
|
||||
{ "qwen35", &World::qwen35, "4" }, { "lfm2", &World::lfm2, "4" },
|
||||
{ "gemma4", &World::gemma4, "4" } };
|
||||
{ "lfm3", &World::lfm3, "4" }, { "gemma4", &World::gemma4, "4" } };
|
||||
for (const auto& run : kRuns) {
|
||||
std::vector<std::vector<int32_t>> alone;
|
||||
{
|
||||
@@ -1983,6 +2129,70 @@ TEST(a_prompt_resumed_from_a_window_snapshot_returns_what_a_cold_run_does) {
|
||||
}
|
||||
}
|
||||
|
||||
/* LFM3 resumes three kinds of state at once: the full-attention layers from the cached blocks, the
|
||||
* sliding layers from a window snapshot, and the convolutions' last inputs from the same checkpoint
|
||||
* slot. The convolutions make it a linear-state model to the scheduler, so checkpoints follow the
|
||||
* interval and not the window's lower floor. Under `exact` a prompt sharing a 200-token head
|
||||
* resumes at a checkpoint (every 64 tokens) inside it; under `nearest` a prompt that extends a
|
||||
* 600-token one resumes from that prompt's tail checkpoint, 75 windows deep. Either way the reply,
|
||||
* and every probability in it, equals a cold run's, and so does a repeat, which resumes further
|
||||
* in. */
|
||||
TEST(lfm3_resumed_from_the_prefix_cache_returns_what_a_cold_run_does) {
|
||||
REQUIRE(world().ok);
|
||||
struct Case {
|
||||
const char* name;
|
||||
std::vector<int32_t> first, second;
|
||||
std::vector<std::string> args;
|
||||
int64_t lo, hi; /* where the shared hit must end */
|
||||
};
|
||||
std::vector<Case> cases;
|
||||
{
|
||||
const std::vector<int32_t> head = prompt_ids(7, 200);
|
||||
std::vector<int32_t> a = head, b = head;
|
||||
for (int32_t t : prompt_ids(8, 70)) a.push_back(t);
|
||||
for (int32_t t : prompt_ids(9, 90)) b.push_back(t);
|
||||
cases.push_back({ "exact", a, b,
|
||||
{ "--num-speculative-tokens", "0", "--checkpoint-interval", "64" }, 1,
|
||||
200 });
|
||||
const std::vector<int32_t> c = prompt_ids(51, 600);
|
||||
std::vector<int32_t> d = c;
|
||||
for (int32_t t : prompt_ids(52, 60)) d.push_back(t);
|
||||
cases.push_back({ "nearest", c, d,
|
||||
{ "--num-speculative-tokens", "0", "--checkpoint-interval", "64",
|
||||
"--prefix-resume", "nearest" },
|
||||
512, 599 });
|
||||
}
|
||||
for (const Case& k : cases) {
|
||||
json cold;
|
||||
{
|
||||
Server s;
|
||||
REQUIRE(s.start(world().lfm3, kPlain));
|
||||
cold = post(s.port, "/completion", completion(k.second, 24, 0.0, 0, 3));
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
Server s;
|
||||
REQUIRE(s.start(world().lfm3, k.args));
|
||||
(void)post(s.port, "/completion", completion(k.first, 24, 0.0, 0, 3));
|
||||
const json shared = post(s.port, "/completion", completion(k.second, 24, 0.0, 0, 3));
|
||||
const json again = post(s.port, "/completion", completion(k.second, 24, 0.0, 0, 3));
|
||||
const int64_t c1 = timing(shared, "cache_n"), c2 = timing(again, "cache_n");
|
||||
REQUIRE(cold.contains("completion_probabilities"));
|
||||
const bool same = tokens_of(shared) == tokens_of(cold) &&
|
||||
tokens_of(again) == tokens_of(cold) &&
|
||||
shared["completion_probabilities"] == cold["completion_probabilities"] &&
|
||||
again["completion_probabilities"] == cold["completion_probabilities"];
|
||||
if (!(c1 >= k.lo && c1 <= k.hi && c2 > c1 && same))
|
||||
fprintf(stderr, " %s: cached %lld then %lld, %s a cold run's\n", k.name,
|
||||
(long long)c1, (long long)c2, same ? "equal to" : "NOT equal to");
|
||||
CHECK(c1 >= k.lo);
|
||||
CHECK(c1 <= k.hi);
|
||||
CHECK(c2 > c1);
|
||||
CHECK_EQ(tokens_of(cold).size(), (size_t)24);
|
||||
CHECK(same);
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* The row a running server's /diagnostics reports for `option`, or null. */
|
||||
json config_row(int port, const std::string& option) {
|
||||
Call c;
|
||||
@@ -1995,6 +2205,72 @@ json config_row(int port, const std::string& option) {
|
||||
return json();
|
||||
}
|
||||
|
||||
/* Several models in one process (docs/MULTIMODEL.md): two architectures, and one architecture
|
||||
* twice, each answering under its own name exactly what it answers alone, behind one listener. */
|
||||
TEST(several_models_in_one_process_answer_as_they_do_alone) {
|
||||
REQUIRE(world().ok);
|
||||
const json req = completion({ 1, 2, 3, 4, 5 }, 6);
|
||||
auto alone = [&](const std::string& model) -> json {
|
||||
Server s;
|
||||
if (!s.start(model, { "--max-num-seqs", "4" })) return json::array();
|
||||
int st = 0;
|
||||
const json r = post(s.port, "/completion", req, &st);
|
||||
CHECK_EQ(st, 200);
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
return r.value("tokens", json::array());
|
||||
};
|
||||
const json q_alone = alone(world().qwen35), l_alone = alone(world().llama);
|
||||
CHECK(!q_alone.empty() && !l_alone.empty());
|
||||
|
||||
const std::string common =
|
||||
"server: {host: 127.0.0.1, port: 0, http-threads: 4, kernels: libref,\n"
|
||||
" debug-accept-reference-kernels: true}\n"
|
||||
"defaults: {max-num-seqs: 4, gpu-memory-mib: 200}\n";
|
||||
{
|
||||
Server s;
|
||||
REQUIRE(s.start_yaml(common + "models:\n q: {model: " + world().qwen35 + ", aliases: [default]}\n"
|
||||
" l: {model: " + world().llama + "}\n"));
|
||||
int st = 0;
|
||||
json named = req;
|
||||
named["model"] = "q";
|
||||
CHECK(post(s.port, "/completion", named, &st).value("tokens", json::array()) == q_alone);
|
||||
CHECK_EQ(st, 200);
|
||||
named["model"] = "l";
|
||||
CHECK(post(s.port, "/completion", named, &st).value("tokens", json::array()) == l_alone);
|
||||
CHECK_EQ(st, 200);
|
||||
/* No model: the one aliased default. An unknown one: not found. */
|
||||
CHECK(post(s.port, "/completion", req, &st).value("tokens", json::array()) == q_alone);
|
||||
named["model"] = "nope";
|
||||
post(s.port, "/completion", named, &st);
|
||||
CHECK_EQ(st, 404);
|
||||
|
||||
Call c;
|
||||
std::string body;
|
||||
CHECK(c.send(s.port, "GET", "/v1/models", "") && c.read(&body) == 200);
|
||||
std::set<std::string> ids;
|
||||
for (const json& m : json::parse(body, nullptr, false).value("data", json::array()))
|
||||
ids.insert(m.value("id", ""));
|
||||
CHECK(ids == std::set<std::string>({ "q", "l", "default" }));
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
{
|
||||
/* One plugin, two instances: each keeps its own state (RadBuildCtx::slot_base). */
|
||||
Server s;
|
||||
REQUIRE(s.start_yaml(common + "models:\n a: {model: " + world().qwen35 + "}\n"
|
||||
" b: {model: " + world().qwen35 + "}\n"));
|
||||
int st = 0;
|
||||
json named = req;
|
||||
for (const char* m : { "a", "b", "a" }) {
|
||||
named["model"] = m;
|
||||
CHECK(post(s.port, "/completion", named, &st).value("tokens", json::array()) == q_alone);
|
||||
CHECK_EQ(st, 200);
|
||||
}
|
||||
post(s.port, "/completion", req, &st);
|
||||
CHECK_EQ(st, 400); /* several models, none named */
|
||||
CHECK_EQ(s.stop(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* --checkpoint-slots auto, the default, sizes the snapshot store from --max-num-seqs and what the
|
||||
* retention policy keeps for a --max-model-len session (the tiny hybrid's 4096 tokens are two
|
||||
* 2048-token intervals: 2 snapshots, 3 a sequence), says so on its startup line and reports the
|
||||
@@ -2016,12 +2292,12 @@ TEST(the_snapshot_store_is_sized_by_auto_unless_a_count_is_given) {
|
||||
"geometric-backoff keeps 2 for a 4096-token session at a 2048-token interval",
|
||||
"checkpoint slots: auto: 12 linear-state snapshot(s) of " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--checkpoint-slots", "auto" }, "12",
|
||||
"command line", "3 a sequence", "checkpoint slots: auto: 12 " },
|
||||
"models.qwen35.checkpoint-slots", "3 a sequence", "checkpoint slots: auto: 12 " },
|
||||
{ &World::qwen35,
|
||||
{ "--max-num-seqs", "4", "--checkpoint-policy", "keep-all", "--checkpoint-interval", "256" },
|
||||
"68", "auto", "keep-all keeps 16 for a 4096-token session at a 256-token interval",
|
||||
"checkpoint slots: auto: 68 " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--checkpoint-slots", "5" }, "5", "command line",
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--checkpoint-slots", "5" }, "5", "models.qwen35.checkpoint-slots",
|
||||
"", "checkpoint slots: 5 linear-state snapshot(s) of " },
|
||||
{ &World::qwen35, { "--max-num-seqs", "4", "--no-prefix-cache" }, "0", "auto",
|
||||
"prefix caching is off", "" },
|
||||
@@ -2120,7 +2396,8 @@ TEST(a_requests_last_step_issues_no_step_ahead) {
|
||||
TEST(a_decoded_token_has_the_probabilities_prefilling_it_gives) {
|
||||
REQUIRE(world().ok);
|
||||
const struct { const char* name; std::string World::*model; double tol; } kRuns[] = {
|
||||
{ "lfm2", &World::lfm2, 0.0 }, { "gemma4", &World::gemma4, 0.0 },
|
||||
{ "lfm2", &World::lfm2, 0.0 }, { "lfm3", &World::lfm3, 0.0 },
|
||||
{ "gemma4", &World::gemma4, 0.0 },
|
||||
{ "llama_fp8", &World::llama_rad, 0.0 }, { "qwen35", &World::qwen35, 0.1 } };
|
||||
const std::vector<int32_t> p = prompt_ids(31, 120);
|
||||
for (const auto& run : kRuns) {
|
||||
@@ -2212,27 +2489,32 @@ TEST(preemption_by_recompute_continues_each_stream_exactly) {
|
||||
namespace {
|
||||
|
||||
/* The tiny Qwen-Image pipeline (tiny_model.h: QwenImage) as rad-convert makes it containers, the
|
||||
* bf16 one and the one whose DiT linears are block fp8, written once per process. Empty when a
|
||||
* bf16 one and the one whose DiT linears are rotated int8, written once per process. The text
|
||||
* encoder is 128 wide so that its activations take the int8 pair's scale group too. Empty when a
|
||||
* step fails. */
|
||||
struct QwenImageContainers {
|
||||
tiny::TempDir dir{ "e2e_qimg", std::getenv("RAD_E2E_KEEP") != nullptr };
|
||||
std::string pipeline, bf16, fp8; /* the diffusers folder, and its two containers */
|
||||
std::string pipeline, bf16, i8; /* the diffusers folder, and its two containers */
|
||||
QwenImageContainers() {
|
||||
const std::string p = dir / "qwen_image";
|
||||
if (!dir.ok() || mkdir(p.c_str(), 0755) != 0 || !tiny::write_qwen_image(p, {}) ||
|
||||
!tiny::write_text(dir / "fp8.recipe", tiny::kQwenImageFp8Recipe))
|
||||
tiny::QwenImage shape;
|
||||
shape.te_hidden = 128;
|
||||
shape.te_head_dim = 32;
|
||||
shape.te_ffn = 256;
|
||||
if (!dir.ok() || mkdir(p.c_str(), 0755) != 0 || !tiny::write_qwen_image(p, shape) ||
|
||||
!tiny::write_text(dir / "i8.recipe", tiny::kQwenImageI8Recipe))
|
||||
return;
|
||||
for (const bool q : { false, true }) {
|
||||
const std::string rad = dir / (q ? "qwen_image_fp8.rad" : "qwen_image.rad");
|
||||
const std::string rad = dir / (q ? "qwen_image_i8.rad" : "qwen_image.rad");
|
||||
std::vector<std::string> argv = { RAD_E2E_CONVERT, p, "-o", rad };
|
||||
if (q) { argv.push_back("--recipe"); argv.push_back(dir / "fp8.recipe"); }
|
||||
if (q) { argv.push_back("--recipe"); argv.push_back(dir / "i8.recipe"); }
|
||||
std::string log;
|
||||
const int st = tiny::run(argv, engine_env(), &log);
|
||||
if (st != 0) {
|
||||
fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(log).c_str());
|
||||
return;
|
||||
}
|
||||
(q ? fp8 : bf16) = rad;
|
||||
(q ? i8 : bf16) = rad;
|
||||
}
|
||||
pipeline = p;
|
||||
}
|
||||
@@ -2307,8 +2589,8 @@ double psnr(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b) {
|
||||
* generator declares has a libavx row, the picture comes back, a seed repeats it byte for byte, and
|
||||
* it agrees with libref's within rounding (the two libraries round the DiT's and the decoder's
|
||||
* products in different orders). Another seed gives another picture, so the agreement is not two
|
||||
* constant images. Guidance runs a second, negative conditioning beside the first; the fp8
|
||||
* container takes the fused fp8 norm, the fp8 GEMMs and the int8 attention scores. */
|
||||
* constant images. Guidance runs a second, negative conditioning beside the first; the int8
|
||||
* container takes the fused int8 norm, the int8 GEMMs and the int8 attention scores. */
|
||||
TEST(qwen_image_generates_on_libavx_alone_as_on_libref) {
|
||||
#if defined(__x86_64__)
|
||||
NEED_ARTIFACT(RAD_E2E_HOME "/kernels/libavx.so");
|
||||
@@ -2317,8 +2599,8 @@ TEST(qwen_image_generates_on_libavx_alone_as_on_libref) {
|
||||
#endif
|
||||
if (!rad::mm::decoder_available()) SKIP("this build has no image codec");
|
||||
const QwenImageContainers& q = qwen_image();
|
||||
REQUIRE(!q.bf16.empty() && !q.fp8.empty());
|
||||
for (const std::string* model : { &q.bf16, &q.fp8 })
|
||||
REQUIRE(!q.bf16.empty() && !q.i8.empty());
|
||||
for (const std::string* model : { &q.bf16, &q.i8 })
|
||||
for (const double cfg : { 0.0, 3.0 }) {
|
||||
const Picture a = generate(*model, { "libavx" }, false, 7, 3, cfg);
|
||||
const Picture b = generate(*model, { "libavx" }, false, 7, 3, cfg);
|
||||
@@ -2328,7 +2610,7 @@ TEST(qwen_image_generates_on_libavx_alone_as_on_libref) {
|
||||
CHECK(a.png == b.png);
|
||||
const double same = psnr(a.rgba, ref.rgba), other = psnr(a.rgba, c.rgba);
|
||||
fprintf(stderr, " %s, cfg %.0f: libavx against libref %.1f dB, against another "
|
||||
"seed %.1f dB\n", model == &q.fp8 ? "fp8" : "bf16", cfg, same, other);
|
||||
"seed %.1f dB\n", model == &q.i8 ? "int8" : "bf16", cfg, same, other);
|
||||
CHECK(same > 40.0);
|
||||
CHECK(other < 30.0);
|
||||
}
|
||||
|
||||
@@ -1088,6 +1088,11 @@ TEST(the_checked_in_fixtures_use_no_dtype_the_harness_cannot_draw_or_read) {
|
||||
}
|
||||
for (const auto& [what, w] : weights) {
|
||||
KfOperand t = *w.first;
|
||||
/* A scale of two planes (IQ8R's u8 scale per 256 of K under a bf16 scale a row) is one
|
||||
* operand at the weight's extents that the kernel's layout combines; it has no
|
||||
* logical decode of its own, and the codes operand beside it is the one drawn here. */
|
||||
if (t.sel.size() > 1 && std::find(t.sel.begin(), t.sel.end(), 0) == t.sel.end())
|
||||
continue;
|
||||
t.sel_rows.clear();
|
||||
t.sel_cols.clear();
|
||||
for (int i : t.sel) {
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
/* fleet_config_test.cpp -- the YAML configuration (core/fleet/config.h, docs/MULTIMODEL.md §4).
|
||||
*
|
||||
* Taken each level's keys reach the Config an engine is built from, with the YAML path as
|
||||
* their source in the startup report
|
||||
* Merged defaults sit under every model; a model's own key wins; anchors and merge keys work
|
||||
* Refused unknown, misplaced, duplicated and contradictory keys stop the load by name
|
||||
* Migrated a command line turns into a YAML file that loads to the same Config
|
||||
* Placed card choice, eviction order and the flex claim (core/fleet/policy.h), from plain
|
||||
* numbers
|
||||
*
|
||||
* No device, no model, no container: text in, a FleetConfig out.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_core.h"
|
||||
#include "fleet/config.h"
|
||||
#include "fleet/policy.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
int yload(const std::string& text, fleet::FleetConfig* out) { return fleet::parse(text, "fleet.yaml", out); }
|
||||
|
||||
bool refused(const std::string& text) {
|
||||
fleet::FleetConfig fc;
|
||||
return yload(text, &fc) != RAD_OK;
|
||||
}
|
||||
|
||||
/* The YAML file a command line becomes. */
|
||||
std::string yaml_of(std::vector<std::string> args) {
|
||||
std::vector<char*> argv;
|
||||
for (std::string& a : args) argv.push_back(a.data());
|
||||
return fleet::yaml_from_args((int)argv.size(), argv.data());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* ------------------------------------------------------------------ taken */
|
||||
|
||||
TEST(one_model_is_an_engine_config) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("models:\n qwen:\n model: /m/q.rad\n tp: 2\n max-num-seqs: 8\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models.size(), 1u);
|
||||
const fleet::ModelEntry& m = fc.models[0];
|
||||
CHECK_EQ(m.name, "qwen");
|
||||
CHECK_EQ(m.cfg.model, "/m/q.rad");
|
||||
CHECK_EQ(m.cfg.tp, 2);
|
||||
CHECK_EQ(m.cfg.max_seqs, 8);
|
||||
CHECK_EQ(m.cfg.served_model_name, "qwen");
|
||||
CHECK_EQ(m.cfg.given.at("--tp"), "models.qwen.tp");
|
||||
CHECK_EQ(m.cfg.given.at("--served-model-name"), "models.qwen");
|
||||
}
|
||||
|
||||
TEST(server_and_memory_keys_reach_every_model) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("server:\n host: \"::\"\n port: 8123\n log: debug\n allow-host: [a.example, b.example]\n"
|
||||
"memory:\n gpu-headroom-mib: 160\n host-mib: 4096\n disk-tier: /var/cache/r\n"
|
||||
"models:\n a:\n model: /m/a.rad\n b:\n model: /m/b.rad\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models.size(), 2u);
|
||||
for (const fleet::ModelEntry& m : fc.models) {
|
||||
CHECK_EQ(m.cfg.host, "::");
|
||||
CHECK_EQ(m.cfg.port, 8123);
|
||||
CHECK_EQ(m.cfg.allow_hosts.size(), 2u);
|
||||
CHECK_EQ(m.cfg.gpu_headroom_mib, 160);
|
||||
CHECK_EQ(m.cfg.given.at("--port"), "server.port");
|
||||
CHECK_EQ(m.cfg.given.at("--gpu-headroom-mib"), "memory.gpu-headroom-mib");
|
||||
}
|
||||
CHECK(fc.log == Log::Debug);
|
||||
CHECK_EQ(fc.host_mib, 4096);
|
||||
CHECK_EQ(fc.disk_tier, "/var/cache/r");
|
||||
}
|
||||
|
||||
TEST(structured_values_are_spelled_for_their_flag) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n"
|
||||
" weights-disk-tier: true\n"
|
||||
" deterministic: false\n"
|
||||
" chat-template-kwargs: {enable_thinking: false, style: \"terse\"}\n"
|
||||
" lora: {sql: /a/sql, chat: /a/chat}\n"
|
||||
" reasoning-effort-map: {minimal: low}\n"
|
||||
" temp: 0.7\n", &fc), RAD_OK);
|
||||
const Config& c = fc.models[0].cfg;
|
||||
CHECK(c.weights_disk_tier);
|
||||
CHECK(!c.deterministic);
|
||||
CHECK_EQ(c.chat_template_kwargs.at("enable_thinking"), "false");
|
||||
CHECK_EQ(c.chat_template_kwargs.at("style"), "\"terse\"");
|
||||
CHECK_EQ(c.lora.adapters.size(), 2u);
|
||||
CHECK_EQ(c.lora.adapters[0].first, "sql");
|
||||
CHECK_EQ(c.reasoning_effort_map.at("minimal"), "low");
|
||||
CHECK(c.sample_temp > 0.69f && c.sample_temp < 0.71f);
|
||||
}
|
||||
|
||||
/* The diagnose mode is a model key like the KL mode's: the entry's Config is what main() tests to
|
||||
* run it offline, and a sequence spells the sweeps' lists. */
|
||||
TEST(the_diagnose_keys_are_model_keys) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("models:\n qwen:\n model: /m/q.rad\n diagnose: /out\n diagnose-runs: 5\n"
|
||||
" diagnose-concurrency: [1, 2]\n diagnose-prefill: [1024, 4096]\n", &fc), RAD_OK);
|
||||
REQUIRE_EQ(fc.models.size(), 1u);
|
||||
const Config& c = fc.models[0].cfg;
|
||||
CHECK(c.diagnose_mode());
|
||||
CHECK_EQ(c.diagnose, "/out");
|
||||
CHECK_EQ(c.diagnose_runs, 5);
|
||||
CHECK_EQ(c.diagnose_concurrency.size(), 2u);
|
||||
CHECK_EQ(c.diagnose_prefill.size(), 2u);
|
||||
CHECK_EQ(c.given.at("--diagnose"), "models.qwen.diagnose");
|
||||
CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-runs: 5\n diagnose: /out\n"
|
||||
" kld-ref: /r\n"));
|
||||
CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-baseline: /b.json\n"));
|
||||
}
|
||||
|
||||
TEST(model_ids_may_hold_dots) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("models:\n qwen3.8-27b:\n model: /m/q.rad\n tp: 2\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].name, "qwen3.8-27b");
|
||||
CHECK_EQ(fc.models[0].cfg.tp, 2);
|
||||
CHECK_EQ(fc.models[0].cfg.given.at("--tp"), "models.qwen3.8-27b.tp");
|
||||
}
|
||||
|
||||
/* A model stating its part of the card replaces the memory level's card pair; the others keep it. */
|
||||
TEST(a_model_divides_its_card_with_gpu_memory_mib) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("memory: {gpu-headroom-mib: 160}\n"
|
||||
"models:\n a: {model: /m/a.rad, gpu-memory-mib: 12000}\n b: {model: /m/b.rad}\n", &fc),
|
||||
RAD_OK);
|
||||
CHECK_EQ(fc.models[0].cfg.gpu_memory_mib, 12000);
|
||||
CHECK(!fc.models[0].cfg.given.count("--gpu-headroom-mib"));
|
||||
CHECK_EQ(fc.models[0].cfg.given.at("--gpu-memory-mib"), "models.a.gpu-memory-mib");
|
||||
CHECK_EQ(fc.models[1].cfg.gpu_headroom_mib, 160);
|
||||
CHECK(!fc.models[1].cfg.given.count("--gpu-memory-mib"));
|
||||
}
|
||||
|
||||
/* Card choice and eviction (fleet/policy.h): a model goes where it displaces least, models leave
|
||||
* lowest priority first and idle before busy, and pinned, kept and higher-priority models stay. */
|
||||
TEST(a_model_loads_where_it_displaces_least) {
|
||||
using fleet::CardRoom;
|
||||
using fleet::Resident;
|
||||
const int64_t G = (int64_t)1 << 30;
|
||||
fleet::RoomPlan p;
|
||||
std::string why;
|
||||
/* Room on card 1 already: nothing leaves. */
|
||||
std::vector<CardRoom> cards = { { 0, 2 * G }, { 1, 20 * G } };
|
||||
std::vector<Resident> res = { { 0, { 0 }, 28 * G, 0, false, false, false, 10, 5 } };
|
||||
CHECK(fleet::plan_room(cards, res, 1, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.cards == std::vector<int>({ 1 }) && p.victims.empty());
|
||||
/* Two cards needed: the resident on card 0 leaves. */
|
||||
CHECK(fleet::plan_room(cards, res, 2, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.cards == std::vector<int>({ 0, 1 }) && p.victims == std::vector<size_t>({ 0 }));
|
||||
/* It may not leave for a lower-priority model, nor when pinned. */
|
||||
CHECK(!fleet::plan_room(cards, res, 2, 10 * G, -1, {}, {}, nullptr, &p, &why));
|
||||
res[0].pin = true;
|
||||
CHECK(!fleet::plan_room(cards, res, 2, 10 * G, 5, {}, {}, nullptr, &p, &why));
|
||||
res[0].pin = false;
|
||||
/* The idle one leaves before the busy one, then the cheaper one to bring back. */
|
||||
cards = { { 0, 0 } };
|
||||
res = { { 0, { 0 }, 10 * G, 0, false, false, true, 100, 5 },
|
||||
{ 1, { 0 }, 10 * G, 0, false, false, false, 10, 5 },
|
||||
{ 2, { 0 }, 10 * G, 0, false, false, false, 10, 1 } };
|
||||
CHECK(fleet::plan_room(cards, res, 1, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.victims == std::vector<size_t>({ 2 }));
|
||||
CHECK(fleet::plan_room(cards, res, 1, 25 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.victims == std::vector<size_t>({ 2, 1, 0 }));
|
||||
/* A parked model leaves last, after every resident one. */
|
||||
{
|
||||
std::vector<Resident> pr = { { 0, { 0 }, 1 * G, 0, false, false, false, 1000, 5 },
|
||||
{ 1, { 0 }, 10 * G, 0, false, false, true, 1, 5 } };
|
||||
pr[0].parked = true;
|
||||
CHECK(fleet::plan_room(cards, pr, 1, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.victims == std::vector<size_t>({ 1 }));
|
||||
}
|
||||
/* Lower priority leaves first whatever its idle time. */
|
||||
res[0].priority = -5;
|
||||
CHECK(fleet::plan_room(cards, res, 1, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.victims == std::vector<size_t>({ 0 }));
|
||||
/* A forced member (exclusive group) leaves even when there is room. */
|
||||
cards = { { 0, 30 * G } };
|
||||
CHECK(fleet::plan_room(cards, res, 1, 10 * G, 0, { 1 }, {}, nullptr, &p, &why));
|
||||
CHECK(p.victims == std::vector<size_t>({ 1 }));
|
||||
/* With room everywhere, the card no model is on. */
|
||||
cards = { { 0, 30 * G }, { 1, 30 * G } };
|
||||
res = { { 0, { 0 }, 2 * G, 0, false, false, false, 10, 5 } };
|
||||
CHECK(fleet::plan_room(cards, res, 1, 10 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.cards == std::vector<int>({ 1 }) && p.victims.empty());
|
||||
/* Among equal sets, the cards it was on before. */
|
||||
cards = { { 0, 30 * G }, { 1, 30 * G } };
|
||||
CHECK(fleet::plan_room(cards, {}, 1, 10 * G, 0, {}, { 1 }, nullptr, &p, &why));
|
||||
CHECK(p.cards == std::vector<int>({ 1 }));
|
||||
/* A unit (a together group) gives back each member's bytes on its own card, and its members
|
||||
* leave together. */
|
||||
cards = { { 0, 0 }, { 1, 0 } };
|
||||
res = { { 7, { 0, 1 }, 0, 0, false, false, false, 10, 5, false, { 6 * G, 2 * G }, { 7, 8 } } };
|
||||
CHECK(fleet::plan_room(cards, res, 1, 5 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
CHECK(p.cards == std::vector<int>({ 0 }) && p.victims == std::vector<size_t>({ 7, 8 }));
|
||||
CHECK(!fleet::plan_room(cards, res, 1, 7 * G, 0, {}, {}, nullptr, &p, &why));
|
||||
/* Too few cards. */
|
||||
CHECK(!fleet::plan_room(cards, {}, 3, G, 0, {}, {}, nullptr, &p, &why));
|
||||
/* A returning model of two ranks, all out on card 1 and mostly still on card 0: card 0 needs
|
||||
* only its own part, so the model on card 1 leaves and the one on card 0 stays. */
|
||||
{
|
||||
cards = { { 0, 4 * G }, { 1, 2 * G } };
|
||||
res = { { 0, { 0 }, 8 * G, 0, false, false, false, 10, 5 },
|
||||
{ 1, { 1 }, 20 * G, 0, false, false, false, 10, 5 } };
|
||||
const std::vector<int> both = { 0, 1 };
|
||||
const std::map<int, int64_t> need = { { 0, 3 * G }, { 1, 20 * G } };
|
||||
CHECK(!fleet::plan_room(cards, res, 2, 20 * G, 0, {}, {}, &both, &p, &why));
|
||||
CHECK(fleet::plan_room(cards, res, 2, 20 * G, 0, {}, {}, &both, &p, &why, &need));
|
||||
CHECK(p.victims == std::vector<size_t>({ 1 }));
|
||||
}
|
||||
}
|
||||
|
||||
/* The claim: need, raised by the flex floors, never above want. */
|
||||
TEST(a_claim_is_the_need_raised_by_the_flex_floor) {
|
||||
const int64_t M = (int64_t)1 << 20;
|
||||
/* kv: 100 MiB fixed state, 900 MiB for 9000 tokens; one context (1000 tokens) = 200 MiB. */
|
||||
CHECK_EQ(fleet::flex_claim(1000 * M, 5000 * M, 100 * M, 1000 * M, 200 * M, 9000, 0, 0, -1, -1),
|
||||
1000 * M);
|
||||
CHECK_EQ(fleet::flex_claim(1000 * M, 5000 * M, 100 * M, 1000 * M, 200 * M, 9000, 0, 0, 4500, -1),
|
||||
1000 * M + 350 * M);
|
||||
CHECK_EQ(fleet::flex_claim(1000 * M, 1100 * M, 100 * M, 1000 * M, 200 * M, 9000, 0, 0, 9000, -1),
|
||||
1100 * M);
|
||||
CHECK_EQ(fleet::flex_claim(1000 * M, 9000 * M, 0, 0, 0, 0, 4000 * M, 1000 * M, -1, 3000),
|
||||
3000 * M);
|
||||
}
|
||||
|
||||
TEST(fleet_keys_on_a_model) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n aliases: [default, chat]\n priority: 100\n"
|
||||
" pin: true\n ttl: 30m\n"
|
||||
" flex: {kv: {min-tokens: 200000, weight: 2}, experts: {max-mib: 4096}}\n"
|
||||
" park: {vram: statics, ram: required, restore: live}\n", &fc), RAD_OK);
|
||||
const fleet::ModelEntry& m = fc.models[0];
|
||||
CHECK_EQ(m.aliases.size(), 2u);
|
||||
CHECK_EQ(m.priority, 100);
|
||||
CHECK(m.pin);
|
||||
CHECK_EQ(m.ttl_ms, 30 * 60 * 1000);
|
||||
CHECK_EQ(m.flex.kv_min_tokens, 200000);
|
||||
CHECK(m.flex.kv_weight == 2.0);
|
||||
CHECK_EQ(m.flex.experts_max_mib, 4096);
|
||||
{
|
||||
/* 0 keeps a tiered model's experts at its claim: no growth into free VRAM. */
|
||||
fleet::FleetConfig z;
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n flex: {experts: {max-mib: 0}}\n", &z), RAD_OK);
|
||||
CHECK_EQ(z.models[0].flex.experts_max_mib, 0);
|
||||
}
|
||||
CHECK(m.park.vram == fleet::ParkSpec::Vram::Statics);
|
||||
CHECK(m.park.ram == fleet::ParkSpec::Ram::Required);
|
||||
CHECK(m.park.restore == fleet::ParkSpec::Restore::Live);
|
||||
CHECK(fc.find("chat") == &m);
|
||||
CHECK(fc.find("default") == &m);
|
||||
CHECK(fc.find("nope") == nullptr);
|
||||
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n park: {vram: 2048}\n", &fc), RAD_OK);
|
||||
CHECK(fc.models[0].park.vram == fleet::ParkSpec::Vram::Mib);
|
||||
CHECK_EQ(fc.models[0].park.vram_mib, 2048);
|
||||
CHECK(fc.models[0].park.restore == fleet::ParkSpec::Restore::Auto);
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n park: {restore: full}\n", &fc), RAD_OK);
|
||||
CHECK(fc.models[0].park.restore == fleet::ParkSpec::Restore::Full);
|
||||
CHECK(refused("models:\n q:\n model: /m/q.rad\n park: {restore: whole}\n"));
|
||||
}
|
||||
|
||||
TEST(scheduler_cards_and_groups) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("cards: [0, 1]\nscheduler: {load-timeout: 90s, drain-timeout: 500ms, keepalive: 5s}\n"
|
||||
"models:\n a: {model: /m/a.rad}\n b: {model: /m/b.rad}\n c: {model: /m/c.rad}\n"
|
||||
"groups:\n rag: {together: [a, b]}\n big: {exclusive: [a, c]}\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.cards.size(), 2u);
|
||||
CHECK_EQ(fc.load_timeout_ms, 90000);
|
||||
CHECK_EQ(fc.drain_timeout_ms, 500);
|
||||
CHECK_EQ(fc.keepalive_ms, 5000);
|
||||
CHECK_EQ(fc.stuck_exit_ms, 60000); /* a minute unless the file says otherwise */
|
||||
CHECK(fc.warm_up); /* on unless the file turns it off */
|
||||
CHECK_EQ(fc.groups.size(), 2u);
|
||||
CHECK(fc.groups[1].kind == fleet::Group::Kind::Exclusive);
|
||||
fleet::FleetConfig off;
|
||||
CHECK_EQ(yload("scheduler: {stuck-exit: 0}\nmodels:\n a: {model: /m/a.rad}\n", &off), RAD_OK);
|
||||
CHECK_EQ(off.stuck_exit_ms, 0);
|
||||
fleet::FleetConfig slow;
|
||||
CHECK_EQ(yload("scheduler: {stuck-exit: 5m}\nmodels:\n a: {model: /m/a.rad}\n", &slow), RAD_OK);
|
||||
CHECK_EQ(slow.stuck_exit_ms, 300000);
|
||||
CHECK_EQ(yload("cards: all\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK);
|
||||
CHECK(fc.cards.empty());
|
||||
CHECK_EQ(yload("scheduler: {warm-up: false}\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK);
|
||||
CHECK(!fc.warm_up);
|
||||
CHECK(refused("scheduler: {warm-up: soon}\nmodels:\n a: {model: /m/a.rad}\n"));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ merged */
|
||||
|
||||
TEST(defaults_sit_under_models) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("defaults:\n kv-cache-dtype: i8\n max-model-len: 65536\n priority: 5\n"
|
||||
"models:\n a:\n model: /m/a.rad\n b:\n model: /m/b.rad\n max-model-len: 4096\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].cfg.kv_cache_dtype, "i8");
|
||||
CHECK_EQ(fc.models[0].cfg.max_ctx, 65536);
|
||||
CHECK_EQ(fc.models[0].cfg.given.at("--max-model-len"), "defaults.max-model-len");
|
||||
CHECK_EQ(fc.models[1].cfg.max_ctx, 4096);
|
||||
CHECK_EQ(fc.models[1].cfg.given.at("--max-model-len"), "models.b.max-model-len");
|
||||
CHECK_EQ(fc.models[0].priority, 5);
|
||||
CHECK_EQ(fc.models[1].priority, 5);
|
||||
}
|
||||
|
||||
/* The variant's name is listed per model, as MODEL:NAME, so one name under defaults: gives every
|
||||
* model a variant of its own without a collision: the switch for a whole fleet at once. */
|
||||
TEST(a_control_vector_variant_under_defaults_reaches_every_model) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload("defaults:\n control-vector: off\n control-vector-variant: uncensored\n"
|
||||
"models:\n a:\n model: /m/a.rad\n b:\n model: /m/b.rad\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].cfg.control_vector_variant, "uncensored");
|
||||
CHECK_EQ(fc.models[1].cfg.control_vector_variant, "uncensored");
|
||||
CHECK_EQ(fc.models[1].cfg.given.at("--control-vector-variant"),
|
||||
"defaults.control-vector-variant");
|
||||
}
|
||||
|
||||
TEST(anchors_and_merge_keys) {
|
||||
fleet::FleetConfig fc;
|
||||
/* Top-level keys starting with x- are ignored, so they can hold anchors. */
|
||||
CHECK_EQ(yload("x-common: &common\n tp: 2\n max-num-seqs: 4\n"
|
||||
"models:\n a:\n <<: *common\n model: /m/a.rad\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].cfg.tp, 2);
|
||||
CHECK_EQ(yload("defaults: &d\n max-num-seqs: 4\n"
|
||||
"models:\n a:\n <<: *d\n model: /m/a.rad\n tp: 2\n", &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].cfg.max_seqs, 4);
|
||||
CHECK_EQ(fc.models[0].cfg.tp, 2);
|
||||
}
|
||||
|
||||
TEST(args_order_is_stable_for_reload) {
|
||||
fleet::FleetConfig a, b;
|
||||
CHECK_EQ(yload("models:\n q:\n model: /m/q.rad\n tp: 2\n max-num-seqs: 8\n", &a), RAD_OK);
|
||||
CHECK_EQ(yload("models:\n q:\n max-num-seqs: 8\n tp: 2\n model: /m/q.rad\n", &b), RAD_OK);
|
||||
CHECK(a.models[0].args == b.models[0].args);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ refused */
|
||||
|
||||
TEST(refusals) {
|
||||
CHECK(refused(""));
|
||||
CHECK(refused("server: {port: 8000}\n")); /* no models */
|
||||
CHECK(refused("models: {}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, max-num-seq: 8}\n")); /* unknown key */
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, port: 9000}\n")); /* server key on a model */
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, served-model-name: x}\n"));
|
||||
CHECK(refused("server: {tp: 2}\nmodels:\n a: {model: /m/a.rad}\n")); /* model key on server */
|
||||
CHECK(refused("tp: 2\nmodels:\n a: {model: /m/a.rad}\n")); /* model key at the top */
|
||||
CHECK(refused("models:\n a:\n model: /m/a.rad\n tp: 2\n tp: 4\n")); /* given twice */
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, tp: 0}\n")); /* config_parse refuses */
|
||||
CHECK(refused("models:\n a: {tp: 2}\n")); /* no model source */
|
||||
CHECK(refused("models:\n \"a:b\": {model: /m/a.rad}\n")); /* ':' is base:adapter */
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad}\n b: {model: /m/b.rad, aliases: [a]}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, weights-disk-tier: yes}\n")); /* true or false */
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, tp: [1, 2]}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, ttl: soon}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, park: {ram: maybe}}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, park: {restore: soon}}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad, flex: {kv: {min-tokens: 9, max-tokens: 3}}}\n"));
|
||||
CHECK(refused("defaults: {aliases: [x]}\nmodels:\n a: {model: /m/a.rad}\n"));
|
||||
CHECK(refused("server: {log: loud}\nmodels:\n a: {model: /m/a.rad}\n"));
|
||||
CHECK(refused("cards: [0, 0]\nmodels:\n a: {model: /m/a.rad}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad}\ngroups:\n g: {together: [a, nope]}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad}\n b: {model: /m/b.rad}\n"
|
||||
"groups:\n g: {together: [a, b]}\n h: {exclusive: [b, a]}\n"));
|
||||
CHECK(refused("models:\n a: {model: /m/a.rad}\ngroups:\n g: {together: [a]}\n"));
|
||||
CHECK(refused("models:\n a: [unclosed\n")); /* YAML syntax */
|
||||
CHECK(refused("---\nmodels: {a: {model: /m/a.rad}}\n---\nmodels: {b: {model: /m/b.rad}}\n"));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ migrated */
|
||||
|
||||
TEST(command_line_becomes_yaml) {
|
||||
std::vector<std::string> args{ "radiance", "--model", "/models/q38-27b.rad", "--host", "::", "--port", "8000",
|
||||
"--tp", "2", "--kv-cache-dtype", "i8", "--gpu-headroom-mib", "160",
|
||||
"--weights-disk-tier", "--allow-host", "a.example", "--allow-host", "b.example",
|
||||
"--chat-template-kwargs", "{\"enable_thinking\": false}", "-v" };
|
||||
const std::string y = yaml_of(args);
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload(y, &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models.size(), 1u);
|
||||
const fleet::ModelEntry& m = fc.models[0];
|
||||
CHECK_EQ(m.name, "q38-27b");
|
||||
CHECK_EQ(m.cfg.model, "/models/q38-27b.rad");
|
||||
CHECK_EQ(m.cfg.host, "::");
|
||||
CHECK_EQ(m.cfg.tp, 2);
|
||||
CHECK_EQ(m.cfg.kv_cache_dtype, "i8");
|
||||
CHECK_EQ(m.cfg.gpu_headroom_mib, 160);
|
||||
CHECK(m.cfg.weights_disk_tier);
|
||||
CHECK_EQ(m.cfg.allow_hosts.size(), 2u);
|
||||
CHECK_EQ(m.cfg.chat_template_kwargs.at("enable_thinking"), "false");
|
||||
CHECK(fc.log == Log::Debug);
|
||||
CHECK(fc.log_set);
|
||||
}
|
||||
|
||||
TEST(entry_name_keeps_a_checkpoint_name_whole) {
|
||||
fleet::FleetConfig fc;
|
||||
CHECK_EQ(yload(yaml_of({ "radiance", "--model", "/hf/Qwen3.8-27B-FP8", "--tp", "1" }), &fc), RAD_OK);
|
||||
CHECK_EQ(fc.models[0].name, "Qwen3.8-27B-FP8");
|
||||
CHECK(!fc.log_set);
|
||||
}
|
||||
|
||||
TEST(durations) {
|
||||
int64_t ms = 0;
|
||||
CHECK(fleet::parse_duration_ms("250ms", &ms) && ms == 250);
|
||||
CHECK(fleet::parse_duration_ms("30", &ms) && ms == 30000);
|
||||
CHECK(fleet::parse_duration_ms("2h", &ms) && ms == 7200000);
|
||||
CHECK(!fleet::parse_duration_ms("", &ms));
|
||||
CHECK(!fleet::parse_duration_ms("1.5s", &ms));
|
||||
CHECK(!fleet::parse_duration_ms("5d", &ms));
|
||||
}
|
||||
|
||||
/* Every key the loader places at the server and memory levels is an option in the table, so a
|
||||
* renamed flag cannot leave a level key that nothing accepts. */
|
||||
TEST(level_keys_are_options) {
|
||||
size_t n = 0;
|
||||
const ConfigFlag* f = config_flags(&n);
|
||||
for (const char* level : { "server", "memory" }) {
|
||||
CHECK(!fleet::level_keys(level).empty());
|
||||
for (const std::string& k : fleet::level_keys(level)) {
|
||||
bool found = false;
|
||||
for (size_t i = 0; i < n; ++i) found |= ("--" + k) == f[i].name;
|
||||
if (!found) radtest::fail(__FILE__, __LINE__, std::string(level) + "." + k + " is not an option");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,318 @@
|
||||
/* Flint's declaration and step (arch/flint), without a GPU or checkpoint: the containers its
|
||||
* recipes make, both KV caches, one and two ranks. */
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "arch_fakes.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "../arch/flint/flint.cpp"
|
||||
|
||||
using namespace rad_fake;
|
||||
|
||||
namespace {
|
||||
|
||||
/* Recursive Flint's configuration as rad-convert records it. */
|
||||
MetaKV flint_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "flint";
|
||||
m.name = "test-flint";
|
||||
m.quant = "";
|
||||
m.n_layers = 49;
|
||||
m.n_embd = 2048;
|
||||
m.n_head = 32;
|
||||
m.n_head_kv = 4;
|
||||
m.head_dim = 128;
|
||||
m.n_ff = 6144;
|
||||
m.n_vocab = 150144;
|
||||
m.n_ctx_train = 262144;
|
||||
m.rms_eps = 1e-6f;
|
||||
m.rope_theta = 10000.0f;
|
||||
m.n_expert = 256;
|
||||
m.n_expert_used = 6;
|
||||
MetaKV k(m);
|
||||
k.set("sliding_window", "513").set("num_experts", "256").set("num_experts_per_tok", "6")
|
||||
.set("moe_intermediate_size", "512").set("shared_expert_intermediate_size", "1024")
|
||||
.set("intermediate_size", "6144");
|
||||
return k;
|
||||
}
|
||||
|
||||
/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under
|
||||
* a bf16 scale a row. */
|
||||
RadEncoding iq8r() {
|
||||
RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256);
|
||||
rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0);
|
||||
rad_enc_copy_str(e.transform, "fwht128");
|
||||
return e;
|
||||
}
|
||||
|
||||
/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */
|
||||
RadEncoding i8h() {
|
||||
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
|
||||
rad_enc_copy_str(e.transform, "fwht128");
|
||||
return e;
|
||||
}
|
||||
|
||||
/* data/recipes/flint-iq8r.recipe's encodings by declared name. The head comes last because
|
||||
* `output.weight` is in `attn_output.weight`. */
|
||||
void iq8r_encs(RadBuilder* b) {
|
||||
b->encs.clear();
|
||||
for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" })
|
||||
b->encs.push_back({ t, i8h() });
|
||||
for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight",
|
||||
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight",
|
||||
"ffn_gate_up_shexp" })
|
||||
b->encs.push_back({ t, iq8r() });
|
||||
b->encs.push_back({ "output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128) });
|
||||
}
|
||||
|
||||
/* data/recipes/flint-bf16-q4.recipe's: u4 attention under an f16 scale and a u8 zero a 128,
|
||||
* plain int8 dense and shared linears and head, signed int4 experts. */
|
||||
void q4_encs(RadBuilder* b) {
|
||||
RadEncoding u4 = rad_enc_affine(RAD_U4, RAD_F16, 1, 128);
|
||||
rad_enc_add_plane(&u4, "zero", RAD_U8, 1, 128);
|
||||
const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
|
||||
const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
|
||||
b->encs.clear();
|
||||
b->encs.push_back({ "ffn_gate_up_exps", i4 });
|
||||
b->encs.push_back({ "ffn_down_exps", i4 });
|
||||
for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight",
|
||||
"attn_output.weight" })
|
||||
b->encs.push_back({ t, u4 });
|
||||
for (const char* t : { "ffn_gate_up_shexp", "ffn_down_shexp", "ffn_gate_up.weight",
|
||||
"ffn_down.weight", "output.weight" })
|
||||
b->encs.push_back({ t, w8 });
|
||||
}
|
||||
|
||||
bool is_full(int l) { return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0); }
|
||||
|
||||
/* Decode, a fused-prologue prefill and one past the fused band, each lint clean. */
|
||||
void steps_lint_clean(RadBuilder& b, int rank, int world) {
|
||||
RadBatch d = decode_batch();
|
||||
RadCtx c1{.b = &b, .batch = &d, .rank = rank, .world = world};
|
||||
flint::step(&c1, &d);
|
||||
CHECK_LINT(b, &c1);
|
||||
CHECK(c1.step_fail.empty());
|
||||
RadBatch p = prefill_batch();
|
||||
RadCtx c2{.b = &b, .batch = &p, .rank = rank, .world = world};
|
||||
flint::step(&c2, &p);
|
||||
CHECK_LINT(b, &c2);
|
||||
CHECK(c2.step_fail.empty());
|
||||
RadBatch w = prefill_batch();
|
||||
w.n_tok = 200;
|
||||
w.max_q_len = 100;
|
||||
RadCtx c3{.b = &b, .batch = &w, .rank = rank, .world = world};
|
||||
flint::step(&c3, &w);
|
||||
CHECK_LINT(b, &c3);
|
||||
CHECK(c3.step_fail.empty());
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The attention of every layer: the sink op, the 513 window on the sliding layers, and the fused
|
||||
* prologue with the rotary on the sliding layers and none (`rotary_dim` 0) on the full ones, on
|
||||
* the bf16 and the int8 cache; the two KV groups take the cache's dtype. */
|
||||
TEST(attention_takes_the_sink_window_and_nope_prologue_on_both_caches) {
|
||||
for (const bool i8 : { false, true }) {
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
if (i8) ctx.kv_dtype = RAD_I8;
|
||||
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const char* kvn = i8 ? "i8" : "bf16";
|
||||
REQUIRE_EQ(b.kv_groups.size(), (size_t)2);
|
||||
for (const auto& g : b.kv_groups) CHECK_EQ(g.d.dtype, (uint32_t)(i8 ? RAD_I8 : RAD_BF16));
|
||||
REQUIRE_EQ(count_op(b, "attn_paged_sink"), 49);
|
||||
REQUIRE_EQ(count_op(b, "qkv_norm_rope_kv_store"), 49);
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 0);
|
||||
CHECK_EQ(count_op(b, "rope"), 2 * 35);
|
||||
for (int l = 0; l < 49; ++l) {
|
||||
const RecOp* a = find_op(b, "attn_paged_sink", l);
|
||||
const RecOp* f = find_op(b, "qkv_norm_rope_kv_store", l);
|
||||
const RecOp* s = find_op(b, "kv_store", l);
|
||||
REQUIRE(a && f && s);
|
||||
CHECK_EQ(pint(a, "window"), is_full(l) ? 0 : 513);
|
||||
CHECK_EQ(pint(a, "gqa"), 8);
|
||||
CHECK_EQ(pint(a, "causal"), 1);
|
||||
CHECK_EQ(pstr(a, "kv_dtype"), std::string(kvn));
|
||||
CHECK_EQ(pint(f, "rotary_dim"), is_full(l) ? 0 : 128);
|
||||
CHECK_EQ(pstr(f, "kv_dtype"), std::string(kvn));
|
||||
CHECK_EQ(pstr(s, "kv_dtype"), std::string(kvn));
|
||||
CHECK(param(s, "k_scale") == nullptr);
|
||||
}
|
||||
steps_lint_clean(b, 0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* The IQ8R container: every trunk linear is an i8a8h GEMM, every grouped GEMM the int8 row, gate_up
|
||||
* reading the block input's own rotated codes at IQ8R's 256 and down the gated product's at a 128;
|
||||
* the norms, the gated products and the attention output write those codes, so no linear declares
|
||||
* a quantiser and no E4M3 code is written. One rank and both ranks of two. */
|
||||
TEST(iq8r_container_reads_the_trunks_rotated_codes_everywhere) {
|
||||
for (int world : { 1, 2 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const flint::Model& m = flint::g_model[rank];
|
||||
CHECK(m.trunk_rot);
|
||||
CHECK_EQ(m.trunk_g8, 256);
|
||||
const rad_buf hq = (rad_buf)m.h.q8, fq = (rad_buf)m.mw.eff.q8;
|
||||
REQUIRE(hq != 0);
|
||||
REQUIRE(fq != 0);
|
||||
int gu = 0, dn = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op == "gemm_nt_q") CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
|
||||
if (o.op != "moe_gemm_q") continue;
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
|
||||
const bool token = pstr(&o, "a_order") == "token";
|
||||
CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128);
|
||||
CHECK(in(o.reads, token ? hq : fq));
|
||||
(token ? gu : dn) += 1;
|
||||
}
|
||||
CHECK_EQ(gu, 47);
|
||||
CHECK_EQ(dn, 47);
|
||||
/* q|k|v, o, the dense pair twice, the shared pair 47 times. */
|
||||
CHECK_EQ(count_op(b, "gemm_nt_q"), 49 * 4 + 2 * 2 + 47 * 2);
|
||||
CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 2 + 47 + 47);
|
||||
CHECK_EQ(count_op(b, "had_quant_act_i8g"), 49);
|
||||
for (const char* op : { "gated_quant_fp8", "quant_act_fp8", "rmsnorm_quant_fp8",
|
||||
"ar_rmsnorm_quant_fp8", "quant_act_i8g" })
|
||||
CHECK_EQ(count_op(b, op), 0);
|
||||
CHECK_EQ(count_op(b, world == 2 ? "ar_rmsnorm_had_quant_i8g" : "rmsnorm_had_quant_i8g") > 0,
|
||||
true);
|
||||
for (const char* a : { "h.q", "moe_ffn.q", "moe_hr.q8", "shared_ffn.q", "attn_out.q" })
|
||||
CHECK(find_b(b, a) == nullptr);
|
||||
/* Expert parallel: each rank owns 128 whole experts. */
|
||||
CHECK(find_w(b, rank == 0 ? "blk.2.ffn_gate_up_exps.0.weight"
|
||||
: "blk.2.ffn_gate_up_exps.128.weight") != nullptr);
|
||||
steps_lint_clean(b, rank, world);
|
||||
}
|
||||
}
|
||||
|
||||
/* Where the rotating norm is not served (the CPU kernels), every linear quantises `h` itself and
|
||||
* the routed experts read a rotated int8 copy that had_quant_act_i8g writes once a layer. */
|
||||
TEST(iq8r_container_quantises_the_expert_input_without_the_rotating_norm) {
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
for (const char* op : { "rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g" })
|
||||
b.undeclared.insert(op);
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
const RecBuf* hr = find_b(b, "moe_hr.q8");
|
||||
REQUIRE(hr != nullptr);
|
||||
const rad_buf hrb = (rad_buf)flint::g_model[0].hr.q8;
|
||||
int reads = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") {
|
||||
CHECK_EQ(pint(&o, "a_group"), 128);
|
||||
reads += in(o.reads, hrb);
|
||||
}
|
||||
CHECK_EQ(reads, 47);
|
||||
steps_lint_clean(b, 0, 1);
|
||||
}
|
||||
|
||||
/* The four-bit container: u4 attention over the bf16 plane, four-bit experts over the block
|
||||
* input's E4M3 pair (w4a8), plain int8 dense and shared linears each quantising its own input,
|
||||
* an int8 head. */
|
||||
TEST(q4_container_serves_four_bit_experts_and_plain_int8_linears) {
|
||||
for (int world : { 1, 2 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
q4_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
|
||||
CHECK(!flint::g_model[rank].trunk_rot);
|
||||
int moe = 0, asym = 0, i8 = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op == "moe_gemm_q") {
|
||||
CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8"));
|
||||
++moe;
|
||||
}
|
||||
if (o.op == "gemm_nt_q") {
|
||||
const std::string dt = pstr(&o, "dtype");
|
||||
asym += dt == "w4a16_asym" || dt == "w4a8i8_asym";
|
||||
i8 += dt == "i8a8";
|
||||
}
|
||||
}
|
||||
CHECK_EQ(moe, 2 * 47);
|
||||
CHECK(asym >= 4 * 49);
|
||||
CHECK_EQ(i8, 2 * 2 + 2 * 47);
|
||||
CHECK(count_op(b, world == 2 ? "ar_rmsnorm_quant_fp8" : "rmsnorm_quant_fp8") > 0);
|
||||
/* No attention output quantiser: the u4 out projection reads the bf16 plane. */
|
||||
CHECK_EQ(count_op(b, "quant_act_fp8"), 0);
|
||||
const RecWeight* head = find_w(b, "output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK_EQ(head->d.dtype, (uint32_t)RAD_I8);
|
||||
steps_lint_clean(b, rank, world);
|
||||
}
|
||||
}
|
||||
|
||||
/* What the plugin refuses by name: a container whose experts are plain (unrotated) int8, a rotated
|
||||
* trunk over unrotated four-bit experts, rotated int8 experts under an unrotated trunk, and a
|
||||
* cache other than bf16 or int8. */
|
||||
TEST(refuses_mismatched_forms_and_other_caches) {
|
||||
{
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
|
||||
for (auto& e : b.encs) e.second = w8;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }) < 0);
|
||||
}
|
||||
{
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
|
||||
for (auto& e : b.encs)
|
||||
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i4;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
q4_encs(&b);
|
||||
for (auto& e : b.encs)
|
||||
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b;
|
||||
iq8r_encs(&b);
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.kv_dtype = RAD_F8E4M3;
|
||||
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
|
||||
/* Per-instance state lives in the declaring instance's slot, so a second engine in the process
|
||||
* leaves the first one's model alone. */
|
||||
TEST(declares_into_its_own_slot) {
|
||||
MetaKV mk = flint_meta();
|
||||
RadBuilder b0, b1;
|
||||
iq8r_encs(&b0);
|
||||
q4_encs(&b1);
|
||||
RadBuildCtx c0 = build_ctx();
|
||||
RadBuildCtx c1 = build_ctx();
|
||||
c1.slot_base = 4;
|
||||
REQUIRE_EQ(flint::declare(&b0, mk.meta(), &c0), RAD_OK);
|
||||
REQUIRE_EQ(flint::declare(&b1, mk.meta(), &c1), RAD_OK);
|
||||
RadArchProbe probe{};
|
||||
CHECK_OK(flint::probe(mk.meta(), &probe));
|
||||
CHECK_EQ(probe.draft_depth, 0);
|
||||
CHECK(flint::g_model[0].trunk_rot);
|
||||
CHECK(!flint::g_model[4].trunk_rot);
|
||||
CHECK_EQ(flint::g_model[4].g.n_layer, 49);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -1022,6 +1022,146 @@ TEST(a_container_extended_in_place_keeps_every_old_weight_where_it_was) {
|
||||
CHECK(slurp(b.path) == before);
|
||||
}
|
||||
|
||||
/* A layer the container holds no expert of takes its whole table past the end, at a fixed stride
|
||||
* like a layer written with the file; the layers it had keep theirs. */
|
||||
TEST(an_in_place_extension_takes_a_whole_new_layer_of_experts) {
|
||||
Built b = write_model("append_layer");
|
||||
RadFile old;
|
||||
REQUIRE((old.open(b.path.c_str())) >= 0);
|
||||
const int64_t n_old = old.entry_count(), size_old = old.size();
|
||||
RadWriter w;
|
||||
REQUIRE((w.begin_append(b.path.c_str(), old)) >= 0);
|
||||
carry_over(w, old);
|
||||
std::vector<RadWriter::Weight> made;
|
||||
for (int32_t e = 0; e < 5; ++e) {
|
||||
const std::string x = "." + std::to_string(e);
|
||||
RadWriter::Weight g = mkw(("blk.2.ffn_gate" + x).c_str(), int4_g32(), EXP_ROWS, EXP_COLS,
|
||||
2, e, 0);
|
||||
const Planes gp = planes_of(g, (uint8_t)(40 + e));
|
||||
CHECK(w.add_weight(g, gp.ptr.data()) >= 0);
|
||||
RadWriter::Weight d = mkw(("blk.2.ffn_down" + x).c_str(), plain_bf16(), 64, 32, 2, e, 1);
|
||||
const Planes dp = planes_of(d, (uint8_t)(60 + e));
|
||||
CHECK(w.add_weight(d, dp.ptr.data()) >= 0);
|
||||
made.push_back(g);
|
||||
made.push_back(d);
|
||||
}
|
||||
/* The new layer's table is closed like any other: an expert out of order is refused. */
|
||||
const RadWriter::Weight late = mkw("blk.2.ffn_gate.6", int4_g32(), EXP_ROWS, EXP_COLS, 2, 6, 0);
|
||||
CHECK(w.add_weight(late) < 0);
|
||||
REQUIRE((w.finish()) >= 0);
|
||||
old.close();
|
||||
|
||||
RadFile f;
|
||||
REQUIRE((f.open(b.path.c_str())) >= 0);
|
||||
CHECK_EQ(f.entry_count(), n_old + 10);
|
||||
CHECK_EQ(f.group_count(), (int64_t)3);
|
||||
for (int32_t layer = 0; layer < 2; ++layer) {
|
||||
const RadFile::ExpertGroup* g = f.group_for_layer(layer);
|
||||
REQUIRE(g != nullptr);
|
||||
CHECK_EQ((int)g->n_expert, 4);
|
||||
CHECK_EQ((int)g->n_slot, 3);
|
||||
}
|
||||
const RadFile::ExpertGroup* g = f.group_for_layer(2);
|
||||
REQUIRE(g != nullptr);
|
||||
CHECK_EQ((int)g->n_expert, 5);
|
||||
CHECK_EQ((int)g->n_slot, 2);
|
||||
CHECK((int64_t)g->base >= size_old);
|
||||
CHECK_EQ((int64_t)(g->stride % RAD_ALIGN_UNIT), (int64_t)0);
|
||||
for (int32_t e = 0; e < 5; ++e)
|
||||
for (int32_t sl = 0; sl < 2; ++sl) {
|
||||
const RadFileEntry& row = f.expert_entry(*g, e, sl);
|
||||
CHECK_EQ((int)row.expert, (int)e);
|
||||
CHECK_EQ((int64_t)(row.offset - g->base - (uint64_t)e * g->stride),
|
||||
(int64_t)g->slot_off[sl]);
|
||||
CHECK(planes_match(f, row, made[(size_t)(2 * e + sl)],
|
||||
(uint8_t)((sl ? 60 : 40) + e)));
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
|
||||
/* A layer whose old experts are not kept takes a whole new table past the end, of its own
|
||||
* geometry, and the old table is left behind; a layer is kept whole or written whole, in either
|
||||
* order of the two calls. */
|
||||
TEST(an_in_place_extension_writes_a_layers_experts_again_all_together) {
|
||||
Built b = write_model("append_replace");
|
||||
RadFile old;
|
||||
REQUIRE((old.open(b.path.c_str())) >= 0);
|
||||
const int64_t size_old = old.size();
|
||||
int64_t n_kept = 0;
|
||||
{
|
||||
RadWriter w;
|
||||
REQUIRE((w.begin_append(b.path.c_str(), old)) >= 0);
|
||||
const RadWriter::Weight g0 = mkw("blk.1.ffn_gate.0", int4_g32(), EXP_ROWS, EXP_COLS, 1, 0, 0);
|
||||
CHECK(w.add_weight(g0) >= 0);
|
||||
const RadFileEntry* kept = old.find("blk.1.ffn_gate.1");
|
||||
REQUIRE(kept != nullptr);
|
||||
CHECK(w.add_existing(weight_of(old, *kept), old, *kept) < 0);
|
||||
w.abort();
|
||||
}
|
||||
{
|
||||
RadWriter w;
|
||||
REQUIRE((w.begin_append(b.path.c_str(), old)) >= 0);
|
||||
const RadFileEntry* kept = old.find("blk.1.ffn_gate.1");
|
||||
REQUIRE(kept != nullptr);
|
||||
CHECK(w.add_existing(weight_of(old, *kept), old, *kept) >= 0);
|
||||
const RadWriter::Weight g0 = mkw("blk.1.ffn_gate.0", int4_g32(), EXP_ROWS, EXP_COLS, 1, 0, 0);
|
||||
CHECK(w.add_weight(g0) < 0);
|
||||
w.abort();
|
||||
}
|
||||
RadWriter w;
|
||||
REQUIRE((w.begin_append(b.path.c_str(), old)) >= 0);
|
||||
w.set_arch("radtest");
|
||||
w.set_model_name("format-test");
|
||||
w.set_quant("fp8_block");
|
||||
w.set_recipe(kRecipe);
|
||||
w.set_created_by("format_test, a layer written again");
|
||||
w.meta_i("n_layers", 2);
|
||||
for (int64_t i = 0; i < old.entry_count(); ++i) {
|
||||
const RadFileEntry& e = old.entry(i);
|
||||
if (e.expert >= 0 && e.layer == 1) continue;
|
||||
CHECK(w.add_existing(weight_of(old, e), old, e) >= 0);
|
||||
++n_kept;
|
||||
}
|
||||
std::vector<RadWriter::Weight> made;
|
||||
for (int32_t e = 0; e < 5; ++e) {
|
||||
const std::string x = "." + std::to_string(e);
|
||||
RadWriter::Weight g = mkw(("blk.1.ffn_gate" + x).c_str(), plain_bf16(), 64, 32, 1, e, 0);
|
||||
const Planes gp = planes_of(g, (uint8_t)(90 + e));
|
||||
CHECK(w.add_weight(g, gp.ptr.data()) >= 0);
|
||||
RadWriter::Weight d = mkw(("blk.1.ffn_down" + x).c_str(), int4_g32(), EXP_ROWS, EXP_COLS,
|
||||
1, e, 1);
|
||||
const Planes dp = planes_of(d, (uint8_t)(110 + e));
|
||||
CHECK(w.add_weight(d, dp.ptr.data()) >= 0);
|
||||
made.push_back(g);
|
||||
made.push_back(d);
|
||||
}
|
||||
REQUIRE((w.finish()) >= 0);
|
||||
old.close();
|
||||
|
||||
RadFile f;
|
||||
REQUIRE((f.open(b.path.c_str())) >= 0);
|
||||
CHECK_EQ(f.entry_count(), n_kept + 10);
|
||||
CHECK_EQ(f.group_count(), (int64_t)2);
|
||||
const RadFile::ExpertGroup* g0 = f.group_for_layer(0);
|
||||
REQUIRE(g0 != nullptr);
|
||||
CHECK_EQ((int)g0->n_expert, 4);
|
||||
CHECK((int64_t)g0->base < size_old);
|
||||
const RadFile::ExpertGroup* g = f.group_for_layer(1);
|
||||
REQUIRE(g != nullptr);
|
||||
CHECK_EQ((int)g->n_expert, 5);
|
||||
CHECK_EQ((int)g->n_slot, 2);
|
||||
CHECK((int64_t)g->base >= size_old);
|
||||
for (int32_t e = 0; e < 5; ++e)
|
||||
for (int32_t sl = 0; sl < 2; ++sl) {
|
||||
const RadFileEntry& row = f.expert_entry(*g, e, sl);
|
||||
CHECK_EQ((int)row.expert, (int)e);
|
||||
CHECK(planes_match(f, row, made[(size_t)(2 * e + sl)],
|
||||
(uint8_t)((sl ? 110 : 90) + e)));
|
||||
}
|
||||
CHECK(f.find("blk.1.ffn_up.0") == nullptr);
|
||||
f.close();
|
||||
}
|
||||
|
||||
TEST(an_in_place_extension_that_fails_leaves_the_container_as_it_was) {
|
||||
Built b = write_model("append_fail");
|
||||
const std::vector<uint8_t> before = slurp(b.path);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/* front_test.cpp -- the listener in front of every model (core/server/front.h).
|
||||
*
|
||||
* Read a request's model comes from the query, a form field, or the body's top-level
|
||||
* string, found without parsing the body
|
||||
* Merged several models' metrics are one exposition, each family declared once
|
||||
* Reads what the dashboard polls is told apart from requests for work
|
||||
* Jobs a finished job is answered by its id with no model, until it expires or is deleted
|
||||
*
|
||||
* No server and no socket: requests and texts in, answers out.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "server/front.h"
|
||||
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::server;
|
||||
|
||||
TEST(the_top_level_model_string_is_found_without_a_parse) {
|
||||
size_t b = 0, e = 0;
|
||||
const std::string body =
|
||||
R"({"messages":[{"role":"user","content":"say \"model\": no"}],"n":2,"x":{"model":"inner"},)"
|
||||
R"( "model" : "qwen:sql", "stream": true})";
|
||||
CHECK(json_top_string(body, "model", &b, &e));
|
||||
CHECK_EQ(body.substr(b, e - b), "qwen:sql");
|
||||
CHECK(!json_top_string(R"({"messages":[]})", "model", &b, &e));
|
||||
CHECK(!json_top_string(R"({"model": 3})", "model", &b, &e));
|
||||
CHECK(!json_top_string(R"([{"model":"x"}])", "model", &b, &e));
|
||||
CHECK(!json_top_string(R"({"model":"unterminated)", "model", &b, &e));
|
||||
}
|
||||
|
||||
TEST(a_request_names_its_model_by_query_form_or_body) {
|
||||
HttpRequest q;
|
||||
q.body = R"({"model":"a"})";
|
||||
CHECK_EQ(Front::requested_model(q), "a");
|
||||
q.query["model"] = "b";
|
||||
CHECK_EQ(Front::requested_model(q), "b");
|
||||
HttpRequest f;
|
||||
f.form.push_back(FormPart{ "model", "", "", "whisper" });
|
||||
CHECK_EQ(Front::requested_model(f), "whisper");
|
||||
HttpRequest esc;
|
||||
esc.body = R"({"model":"a\u002db"})";
|
||||
CHECK_EQ(Front::requested_model(esc), "a-b");
|
||||
CHECK_EQ(Front::requested_model(HttpRequest{}), "");
|
||||
}
|
||||
|
||||
TEST(the_dashboards_reads_do_not_count_as_wanting_a_model) {
|
||||
HttpRequest q;
|
||||
for (const char* path : { "/stats", "/sessions", "/graph", "/server_info", "/admin/control-vector" }) {
|
||||
q.path = path;
|
||||
q.method = "GET";
|
||||
CHECK(Front::dashboard_read(q));
|
||||
/* The router dispatches a doubled or trailing slash to the same route; so must the
|
||||
* read's exemption, or the read wakes a model for a slash. */
|
||||
q.path = std::string("/") + path;
|
||||
CHECK(Front::dashboard_read(q));
|
||||
q.path = std::string(path) + "/";
|
||||
CHECK(Front::dashboard_read(q));
|
||||
}
|
||||
q.path = "/admin/control-vector";
|
||||
q.method = "POST";
|
||||
CHECK(!Front::dashboard_read(q));
|
||||
q.path = "/v1/chat/completions";
|
||||
CHECK(!Front::dashboard_read(q));
|
||||
q.method = "GET";
|
||||
q.path = "/v1/videos/abc";
|
||||
CHECK(!Front::dashboard_read(q));
|
||||
}
|
||||
|
||||
/* The set that must not wake a model for a caller its handler will refuse: exactly the routes
|
||||
* Server::register_routes guards with local_operator keyless, and nothing beside them. */
|
||||
TEST(guarded_routes_are_the_local_operator_ones) {
|
||||
/* guarded_route now reads the front's own copied routes, so the decision is made by an
|
||||
* instance's matcher -- a Front with no models installed still carries the full route table
|
||||
* (its prototype does), which is exactly the set whose handlers guard. */
|
||||
Front f(TransportOptions{}, 0);
|
||||
HttpRequest q;
|
||||
q.method = "GET"; q.path = "/diagnostics"; CHECK(f.guarded_route(q));
|
||||
/* The router collapses "//x" and "x/" into "/x" (split_path, http.cpp) -- the guard sees
|
||||
* the same path the handler reaches, or a slash buys the wake the guard denies. */
|
||||
q.path = "//diagnostics"; CHECK(f.guarded_route(q));
|
||||
q.path = "/diagnostics/"; CHECK(f.guarded_route(q));
|
||||
q.method = "POST"; q.path = "/reset_prefix_cache"; CHECK(f.guarded_route(q));
|
||||
q.path = "/admin/control-vector"; CHECK(f.guarded_route(q));
|
||||
q.method = "GET"; q.path = "/admin/control-vector"; CHECK(f.guarded_route(q));
|
||||
q.method = "DELETE"; q.path = "/sessions"; CHECK(f.guarded_route(q));
|
||||
/* The :label form is registered and guarded next to it (server.cpp); the front must not
|
||||
* wake a model for a stranger's DELETE /sessions/whatever either. */
|
||||
q.path = "/sessions/abc"; CHECK(f.guarded_route(q));
|
||||
q.method = "POST"; q.path = "/v1/load_lora_adapter"; CHECK(f.guarded_route(q));
|
||||
q.path = "/v1/unload_lora_adapter"; CHECK(f.guarded_route(q));
|
||||
/* The rest is unguarded: the open dashboard reads stay as they are, and inference keeps
|
||||
* waking its model for whoever asks -- that is what a keyless box is for. */
|
||||
q.method = "GET"; q.path = "/sessions"; CHECK(!f.guarded_route(q));
|
||||
q.path = "/stats"; CHECK(!f.guarded_route(q));
|
||||
q.method = "POST"; q.path = "/v1/chat/completions"; CHECK(!f.guarded_route(q));
|
||||
q.method = "GET"; q.path = "/v1/models"; CHECK(!f.guarded_route(q));
|
||||
/* Shapes the :label pattern cannot match are no route at all, so they wake nothing -- but a
|
||||
* trailing slash is not such a shape: the router collapses it to the guarded bare route. */
|
||||
q.method = "DELETE"; q.path = "/sessions/"; CHECK(f.guarded_route(q));
|
||||
q.path = "/sessions/a/b"; CHECK(!f.guarded_route(q));
|
||||
}
|
||||
|
||||
TEST(a_finished_job_is_answered_by_its_id_with_no_model) {
|
||||
Front f(TransportOptions{}, 0);
|
||||
const int64_t later = (int64_t)std::time(nullptr) + 100;
|
||||
int asked = 0;
|
||||
const Handler answer = [&](const HttpRequest&) { ++asked; return HttpResponse::json_body(200, "{}"); };
|
||||
f.keep_job("video_a", later, 8, answer);
|
||||
f.keep_job("shape_b", later, 8, answer);
|
||||
HttpRequest q;
|
||||
q.method = "GET";
|
||||
q.path = "/v1/videos/video_a";
|
||||
CHECK(f.kept_job(q) != nullptr);
|
||||
q.path = "/v1/videos/video_a/content";
|
||||
CHECK(f.kept_job(q) != nullptr);
|
||||
q.path = "/status/shape_b";
|
||||
CHECK(f.kept_job(q) != nullptr);
|
||||
/* Another job, a prefix of the id, and a route that names no job. */
|
||||
q.path = "/v1/videos/video_b";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
q.path = "/v1/videos/video_";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
q.path = "/v1/chat/completions";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
/* A delete is answered once and forgets it. */
|
||||
q.method = "DELETE";
|
||||
q.path = "/v1/videos/video_a";
|
||||
const Handler del = f.kept_job(q);
|
||||
CHECK(del != nullptr);
|
||||
CHECK_EQ(del(q).status, 200);
|
||||
CHECK_EQ(asked, 1);
|
||||
q.method = "GET";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
}
|
||||
|
||||
TEST(kept_jobs_expire_and_the_oldest_go_past_the_count) {
|
||||
Front f(TransportOptions{}, 0);
|
||||
const int64_t now = (int64_t)std::time(nullptr);
|
||||
const Handler answer = [](const HttpRequest&) { return HttpResponse::json_body(200, "{}"); };
|
||||
HttpRequest q;
|
||||
q.method = "GET";
|
||||
f.keep_job("old", now - 1, 8, answer);
|
||||
q.path = "/v1/videos/old";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
f.keep_job("a", now + 100, 2, answer);
|
||||
f.keep_job("b", now + 100, 2, answer);
|
||||
f.keep_job("c", now + 100, 2, answer);
|
||||
q.path = "/v1/videos/a";
|
||||
CHECK(f.kept_job(q) == nullptr);
|
||||
q.path = "/v1/videos/b";
|
||||
CHECK(f.kept_job(q) != nullptr);
|
||||
q.path = "/v1/videos/c";
|
||||
CHECK(f.kept_job(q) != nullptr);
|
||||
}
|
||||
|
||||
TEST(metrics_from_several_models_declare_each_family_once) {
|
||||
const std::string a =
|
||||
"# HELP rad_requests_total Requests.\n# TYPE rad_requests_total counter\n"
|
||||
"rad_requests_total{model_name=\"a\"} 3\n"
|
||||
"# HELP rad_step_seconds Step time.\n# TYPE rad_step_seconds histogram\n"
|
||||
"rad_step_seconds_bucket{model_name=\"a\",le=\"0.1\"} 1\nrad_step_seconds_sum{model_name=\"a\"} 0.05\n";
|
||||
const std::string b =
|
||||
"# HELP rad_requests_total Requests.\n# TYPE rad_requests_total counter\n"
|
||||
"rad_requests_total{model_name=\"b\"} 5\n";
|
||||
const std::string m = merge_metrics({ a, b });
|
||||
CHECK_EQ(m,
|
||||
"# HELP rad_requests_total Requests.\n# TYPE rad_requests_total counter\n"
|
||||
"rad_requests_total{model_name=\"a\"} 3\nrad_requests_total{model_name=\"b\"} 5\n"
|
||||
"# HELP rad_step_seconds Step time.\n# TYPE rad_step_seconds histogram\n"
|
||||
"rad_step_seconds_bucket{model_name=\"a\",le=\"0.1\"} 1\n"
|
||||
"rad_step_seconds_sum{model_name=\"a\"} 0.05\n");
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+19
-3
@@ -40,7 +40,7 @@
|
||||
#include "text/chatfmt.h"
|
||||
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -54,7 +54,7 @@
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -1515,6 +1515,22 @@ TEST(gbnf_a_grammar_whose_masks_need_unbounded_context_is_refused) {
|
||||
std::fprintf(stderr, " refused: %s\n", err.c_str());
|
||||
}
|
||||
|
||||
/* `pattern` is client data, and the group scanner recurses once per nested '('. Unbounded, a
|
||||
* few tens of KB of '(' -- one JSON string, so the body's depth and value bounds never see it --
|
||||
* stack-overflows the request worker past any catch. Nesting past the cap is refused the way
|
||||
* every other unsupported syntax is, and a pattern no real schema exceeds stays legal. */
|
||||
TEST(gbnf_a_pattern_nesting_past_the_cap_is_refused_not_fatal) {
|
||||
const std::string deep = "^" + std::string(20000, '(') + "a" + std::string(20000, ')') + "$";
|
||||
const std::string schema = std::string(R"({"type":"string","pattern":")") + deep + R"("})";
|
||||
std::string gbnf, err;
|
||||
CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) != 0);
|
||||
CHECK(err.find("deep") != std::string::npos);
|
||||
const std::string sane = "^" + std::string(40, '(') + "a" + std::string(40, ')') + "$";
|
||||
const std::string schema_ok = std::string(R"({"type":"string","pattern":")") + sane + R"("})";
|
||||
std::string gbnf2, err2;
|
||||
CHECK_OK(grammar_from_json_schema(schema_ok, "root", &gbnf2, &err2));
|
||||
}
|
||||
|
||||
/* A rule that can never match is refused by name. `r ::= r` passes the left-recursion check (the
|
||||
* reference is in tail position) but only leads back into itself, and upstream reads the resulting
|
||||
* empty stack set as admitting every token. A grammar that merely never ends still compiles. */
|
||||
@@ -1875,7 +1891,7 @@ TEST(json_schema_walks_write_only_valid_instances) {
|
||||
++finished;
|
||||
bool ok = false;
|
||||
try {
|
||||
const nlohmann::json j = nlohmann::json::parse(text);
|
||||
const Json j = Json::parse(text);
|
||||
ok = j.is_object() && j.contains("n") && j.contains("s") && j["n"].is_number_integer() &&
|
||||
j["n"].get<int64_t>() >= -20 && j["n"].get<int64_t>() <= 300 && j["s"].is_string();
|
||||
if (ok) {
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -33,7 +33,7 @@
|
||||
|
||||
using namespace rad;
|
||||
namespace AR = rad::arch;
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -560,7 +560,7 @@ TEST(requests_name_adapters_in_a_field_or_in_prompt_tags) {
|
||||
std::vector<std::pair<std::string, double>> out;
|
||||
std::string field, why;
|
||||
std::string prompt = "a cat, <lora:pixel art:0.7>, sitting <lora:detail>";
|
||||
nlohmann::json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } };
|
||||
Json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } };
|
||||
REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK);
|
||||
REQUIRE_EQ(out.size(), (size_t)5);
|
||||
CHECK_EQ(out[0].first, std::string("style"));
|
||||
|
||||
+2
-1
@@ -11,7 +11,7 @@ namespace ggufw {
|
||||
|
||||
struct GKv {
|
||||
std::string key;
|
||||
uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings */
|
||||
uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings, 10 i64 */
|
||||
double num = 0;
|
||||
std::vector<std::string> strs;
|
||||
};
|
||||
@@ -42,6 +42,7 @@ inline bool write_gguf(const std::string& path, const std::vector<GKv>& kvs,
|
||||
put_str(&b, kv.key);
|
||||
put_bytes(&b, &kv.type, 4);
|
||||
if (kv.type == 4) { const uint32_t v = (uint32_t)kv.num; put_bytes(&b, &v, 4); }
|
||||
else if (kv.type == 10) { const int64_t v = (int64_t)kv.num; put_bytes(&b, &v, 8); }
|
||||
else if (kv.type == 6) { const float v = (float)kv.num; put_bytes(&b, &v, 4); }
|
||||
else if (kv.type == 8) put_str(&b, kv.strs.at(0));
|
||||
else {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers 5.23.0.dev0 (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, torch 2.15.0+cpu, torchvision 0.29.2+cpu); do not edit. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;
|
||||
static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;
|
||||
static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;
|
||||
static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;
|
||||
static const int32_t kGoldMuseVidSep = 200087;
|
||||
|
||||
/* A h x w picture's resize target, in pixels. */
|
||||
struct GoldMuseResize { int64_t h, w, oh, ow; };
|
||||
static const GoldMuseResize kGoldMuseResize[] = {
|
||||
{ 256, 320, 252, 308 },
|
||||
{ 100, 100, 112, 112 },
|
||||
{ 84, 84, 84, 84 },
|
||||
{ 10, 10, 28, 28 },
|
||||
{ 28, 28, 28, 28 },
|
||||
{ 27, 27, 28, 28 },
|
||||
{ 1, 1, 28, 28 },
|
||||
{ 8000, 8000, 1792, 1792 },
|
||||
{ 2000, 50, 2016, 56 },
|
||||
{ 50, 2000, 56, 2016 },
|
||||
{ 300, 500, 308, 504 },
|
||||
{ 640, 427, 616, 420 },
|
||||
{ 1920, 1080, 1932, 1092 },
|
||||
{ 3, 5000, 28, 5012 },
|
||||
{ 500, 3, 504, 28 },
|
||||
{ 1234, 5678, 812, 3836 },
|
||||
{ 7, 9, 28, 28 },
|
||||
{ 112, 224, 112, 224 },
|
||||
{ 224, 112, 224, 112 },
|
||||
};
|
||||
|
||||
/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row (temporal, channel, y, x) as the reference lays it out. */
|
||||
struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };
|
||||
static const GoldMuseImage kGoldMuseImage[] = {
|
||||
{ 100, 100, 8, 8, {0xbebf, 0xbf56, 0xbeaf, 0x3f50, 0x3db9, 0xbf10, 0x3ea7, 0x3f26, 0x3eef, 0xbeff, 0xbe75, 0xbf7e, 0x3f02, 0x3e2d, 0x3f08, 0xbe55}, 2422471396853671097ull },
|
||||
{ 256, 320, 18, 22, {0xbec7, 0xbf54, 0x3e4d, 0x3f22, 0xbf18, 0x3e7d, 0x3f28, 0x3e45, 0xbeef, 0xbf22, 0xbd71, 0x3ec7, 0xbf1e, 0x3ebb, 0x3f28, 0x3ca1}, 116533246137817081ull },
|
||||
};
|
||||
|
||||
/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid (groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's stamp. */
|
||||
static const int64_t kGoldMuseVideoTotal = 37;
|
||||
static const double kGoldMuseVideoFps = 6.0;
|
||||
static const int32_t kGoldMuseVideoN = 12;
|
||||
static const int64_t kGoldMuseVideoIndex[] = {
|
||||
0, 3, 6, 9, 13, 16, 19, 22, 26, 29, 32, 36};
|
||||
static const int32_t kGoldMuseVideoGrid[] = { 6, 4, 6 };
|
||||
static const uint16_t kGoldMuseVideoHead[16] = {
|
||||
0xbebf, 0xbf38, 0x3f08, 0x3d89, 0xbe93, 0x3f02, 0x3ee3, 0xbef3, 0xbf12, 0xbd11, 0x3e83, 0xbedf, 0x3e15, 0xbf08, 0x3f30, 0x3e9b};
|
||||
static const uint64_t kGoldMuseVideoFnv = 11707344584801435184ull;
|
||||
static const char* const kGoldMuseVideoStamps[] = {
|
||||
"Time: 0.0s",
|
||||
"Time: 1.0s",
|
||||
"Time: 2.2s",
|
||||
"Time: 3.2s",
|
||||
"Time: 4.3s",
|
||||
"Time: 5.3s",
|
||||
};
|
||||
/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */
|
||||
struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };
|
||||
static const GoldMuseSample kGoldMuseSample[] = {
|
||||
{ 37, 6.0, 12, 7586201493087669970ull },
|
||||
{ 6, 2.0, 6, 505324669386248260ull },
|
||||
{ 96, 24.0, 8, 5899556429423025984ull },
|
||||
{ 1, 2.0, 1, 12161962213042174405ull },
|
||||
{ 2, 2.0, 2, 7576559462502111812ull },
|
||||
{ 5, 12.0, 2, 879613241599343585ull },
|
||||
{ 600, 30.0, 40, 14808218070874272101ull },
|
||||
{ 1000, 24.0, 82, 13092565161413813425ull },
|
||||
{ 13, 7.0, 2, 291392423630507241ull },
|
||||
{ 4, 1.0, 4, 7267626464946418085ull },
|
||||
};
|
||||
@@ -337,6 +337,7 @@ TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) {
|
||||
* the gather sends whole runs into an output of world runs. Below the threshold, and at TP1, the
|
||||
* head form is unchanged, as it is unless the row form is opted into (the default). */
|
||||
TEST(glm_mla_splits_a_prefill_by_rows_over_ranks_from_the_row_threshold) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
using namespace rad::arch;
|
||||
for (int world : { 1, 2, 4, 8 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
@@ -514,6 +515,7 @@ TEST(glm_mla_splits_a_prefill_by_rows_over_ranks_from_the_row_threshold) {
|
||||
|
||||
TEST(
|
||||
glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
using namespace rad::arch;
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
@@ -766,6 +768,7 @@ TEST(
|
||||
* into planes that hold every run. The query side (projection, cast, quantiser, head gates) runs
|
||||
* on the run's rows that exist. Below the threshold the indexer stays replicated. */
|
||||
TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
using namespace rad::arch;
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
@@ -999,6 +1002,7 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
|
||||
* counts and buffer rows smaller. The TP splits declare its ops whatever the step size and their
|
||||
* gathers' message as a range, in the head and the row form of the MLA. */
|
||||
TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1079,6 +1083,7 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
|
||||
/* Each deployment or checkpoint the plugin cannot serve is refused with a line that names the
|
||||
* setting and the reason, not a bare status. */
|
||||
TEST(glm53_refusals_name_what_was_refused) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1142,6 +1147,7 @@ TEST(glm53_refusals_name_what_was_refused) {
|
||||
* name fp8_e4m3, and the index tail, DSA index and KDA groups keep their dtypes. Under bf16 the
|
||||
* attention states no kv_dtype, the op it always declared. */
|
||||
TEST(glm53_fp8_kv_cache_narrows_the_latent_group_only) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1206,6 +1212,7 @@ TEST(glm53_fp8_kv_cache_narrows_the_latent_group_only) {
|
||||
* launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's
|
||||
* row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */
|
||||
TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1488,6 +1495,7 @@ TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ri
|
||||
}
|
||||
|
||||
TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
using namespace rad::arch;
|
||||
RadBuilder b;
|
||||
Names nm("");
|
||||
@@ -1771,6 +1779,7 @@ TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets)
|
||||
* after history, a mixed step, a decode step, a verify and its draft passes, at eight in both
|
||||
* MLA forms. */
|
||||
TEST(glm53_is_the_pinned_graph_and_steps) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1836,6 +1845,7 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
|
||||
/* The width split is for all-MXFP4 experts alone: anything else keeps whole experts at four ranks
|
||||
* and up, because a plain bf16 expert, even one protected among MXFP4 ones, cannot be sliced. */
|
||||
TEST(glm53_lays_out_its_experts_by_their_format) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -1955,6 +1965,7 @@ RadBuildCtx glm53_vl_ctx(int rank, int world, int64_t patches, int max_spec = 3)
|
||||
* under tensor parallelism instead of once a rank. The linear groups travel in the checkpoint
|
||||
* store and carry no such flag. The flag is outside graph_hash(), so the pinned graphs stand. */
|
||||
TEST(glm53_declares_its_latent_and_index_caches_replicated) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
auto ends_with = [](const std::string& s, const char* t) {
|
||||
const size_t n = std::strlen(t);
|
||||
@@ -1984,6 +1995,7 @@ TEST(glm53_declares_its_latent_and_index_caches_replicated) {
|
||||
* frequencies an axis, gate and up joined gate first; one scatter over the trunk's embedding and
|
||||
* one over the draft head's. */
|
||||
TEST(glm53_declares_its_vision_tower_when_the_engine_asks_for_it) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
for (int world : { 1, 8 }) {
|
||||
const int rank = world - 1;
|
||||
@@ -2093,6 +2105,7 @@ TEST(glm53_declares_its_vision_tower_when_the_engine_asks_for_it) {
|
||||
|
||||
/* What the tower does not serve is refused by name at declare, not computed as another model. */
|
||||
TEST(glm53_refuses_a_vision_tower_it_does_not_serve) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const struct { const char* key; const char* val; int rc; } kCases[] = {
|
||||
{ "vision_config.hidden_act", "gelu", RAD_E_UNSUPPORTED },
|
||||
{ "vision_config.rope_parameters.rope_type", "default", RAD_E_UNSUPPORTED },
|
||||
@@ -2114,6 +2127,7 @@ TEST(glm53_refuses_a_vision_tower_it_does_not_serve) {
|
||||
* downsample's unfold and GEMM, and the merger, over two pictures of 8 x 8 patches. The rotary
|
||||
* reads the row and column planes, attention and the unfold the segment bounds. */
|
||||
TEST(a_glm53_encoder_pass_issues_the_tower_and_nothing_else) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
for (int world : { 1, 8 }) {
|
||||
const int rank = world - 1;
|
||||
@@ -2182,6 +2196,7 @@ TEST(a_glm53_encoder_pass_issues_the_tower_and_nothing_else) {
|
||||
* before the embedding's all-reduce, and so does the draft head's history pass over its own
|
||||
* lookup; a text-only step on the same program issues no scatter. */
|
||||
TEST(a_glm53_step_with_a_picture_scatters_its_rows_in_the_trunk_and_the_draft_head) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
for (int world : { 1, 4 }) {
|
||||
RadBuilder b;
|
||||
@@ -2227,6 +2242,7 @@ TEST(a_glm53_step_with_a_picture_scatters_its_rows_in_the_trunk_and_the_draft_he
|
||||
/* A sizing declare with the tower is the real graph at fewer rows: the same ops with the same
|
||||
* fixed parameters (the attention's longest segment included), and nothing declared to the core. */
|
||||
TEST(glm53_sizing_declares_with_the_vision_tower_match_the_real_graph) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
for (int64_t R : { 256 }) {
|
||||
RadBuildCtx c = glm53_vl_ctx(3, 8, 16384);
|
||||
@@ -2273,6 +2289,7 @@ TEST(glm53_sizing_declares_with_the_vision_tower_match_the_real_graph) {
|
||||
}
|
||||
|
||||
TEST(glm53_declaring_without_streamed_ops_ignores_the_flag) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -2310,6 +2327,7 @@ TEST(glm53_declaring_without_streamed_ops_ignores_the_flag) {
|
||||
}
|
||||
|
||||
TEST(glm53_streamed_decode_resolves_after_select_and_before_attention_with_the_entry_count) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
@@ -2567,6 +2585,7 @@ const LoadedSchemas& loaded_schemas() {
|
||||
* The engine refuses a step at the first mismatch, which the recording fakes do not check, so a
|
||||
* missing optional operand reaches no other host test. */
|
||||
TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const LoadedSchemas& lib = loaded_schemas();
|
||||
if (lib.ops.empty()) {
|
||||
fprintf(stderr, " no kernel library under $RADIANCE_HOME/kernels; nothing to count\n");
|
||||
@@ -2841,6 +2860,7 @@ std::string as_expert_zero(std::string n) {
|
||||
* from the table, as the container would answer. A full-width view declared as its own weight
|
||||
* at `fp8a8` passed every host test and left 88 bands with no kernel at the eight-card start. */
|
||||
TEST(glm53_declares_the_served_containers_names_and_their_encodings) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const Glm53Container& c = glm53_container();
|
||||
MetaKV mk = glm53_vl_meta();
|
||||
for (int world : { 8, 1 }) {
|
||||
|
||||
@@ -42,7 +42,7 @@ struct Case {
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static Fn pick(int hd, int gqa, bool fp8) {
|
||||
#define P(H, G) if (hd == H && gqa == G) return fp8 ? halo_rad_attn_window_h##H##_gqa##G##_fp8 : halo_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(128, 1) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
P(128, 1) P(128, 4) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
#undef P
|
||||
return nullptr;
|
||||
}
|
||||
@@ -182,6 +182,21 @@ int main(int argc, char** argv) {
|
||||
0, 0, 512, 1},
|
||||
{"wmma h128 gqa1 swa w1024 ragged", 128, 1, 1, false, true, true, false, 1024, {150, 70},
|
||||
{300, 70}, -1, 0, 0, 0, 1},
|
||||
/* LFM3: h128, 16 query heads over 4 KV heads; full layers and a 256-token sliding window.
|
||||
* Prefill and chunked prefill past the decode leg's band, ragged steps with decode rows, a
|
||||
* query whose window starts inside the context, fp8 cache */
|
||||
{"h128 gqa4 kvh4 full verify17 split", 128, 4, 4, false, true, false, false, 0, {17}, {300}, -1, 262144, s128},
|
||||
{"h128 gqa4 kvh4 swa w256 ragged", 128, 4, 4, false, true, true, false, 256, {1, 5, 40}, {600, 77, 300}},
|
||||
{"h128 gqa4 kvh2 swa w256 fp8+descale split", 128, 4, 2, true, true, false, true, 256, {20}, {700}, -1, 4096, s128},
|
||||
{"h128 gqa4 kvh4 noncausal missing-block", 128, 4, 4, false, false, true, false, 0, {4, 2}, {37, 20}, 1},
|
||||
{"wmma h128 gqa4 kvh4 full prefill 200 of 900", 128, 4, 4, false, true, false, false, 0, {200}, {900},
|
||||
-1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh4 swa w256 prefill 300 of 900", 128, 4, 4, false, true, false, false, 256, {300},
|
||||
{900}, -1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh4 swa w256 ragged + decode rows", 128, 4, 4, false, true, true, false, 256,
|
||||
{150, 1, 70}, {500, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh2 swa w256 fp8+descale", 128, 4, 2, true, true, true, true, 256, {100, 90},
|
||||
{400, 90}, -1, 0, 0, 0, 1},
|
||||
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
|
||||
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
@@ -113,8 +114,19 @@ static std::vector<int> glm_runs(std::vector<int> live) {
|
||||
return runs;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_decode(), cases = 1;
|
||||
int main(int argc, char** argv) {
|
||||
/* [--shard k/n]: every n-th case from the k-th (the table decode with shard 0), so ctest can
|
||||
* split the run. A case's seed is its place in the table, whichever shard runs it. */
|
||||
int shard = 0, shards = 1;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::string(argv[i]) == "--shard" && i + 1 < argc &&
|
||||
std::sscanf(argv[++i], "%d/%d", &shard, &shards) == 2 && shards >= 1 && shard >= 0 &&
|
||||
shard < shards)
|
||||
continue;
|
||||
std::fprintf(stderr, "usage: %s [--shard k/n], 0 <= k < n\n", argv[0]);
|
||||
return 2;
|
||||
}
|
||||
int fails = shard == 0 ? check_decode() : 0, cases = shard == 0 ? 1 : 0;
|
||||
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
|
||||
|
||||
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
|
||||
@@ -261,14 +273,16 @@ int main() {
|
||||
};
|
||||
|
||||
for (const Case& c : all) {
|
||||
const int idx = (int)(&c - all);
|
||||
if (idx % shards != shard) continue;
|
||||
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
|
||||
int routed = 0;
|
||||
for (int r : c.runs) routed += r;
|
||||
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
|
||||
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
|
||||
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
|
||||
yp = OUT + ((&c - all) % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1000 + cases);
|
||||
yp = OUT + (idx % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1001 + idx);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
|
||||
@@ -108,6 +108,30 @@ TEST(two_containers_are_refused_by_name) {
|
||||
CHECK(why.find("--model") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A repo fetched with hfget holds its source weights in the directory; a lone .rad among them
|
||||
* -- whoever put it there -- must not be served in their place without one word said. The
|
||||
* engine names the ambiguity instead of resolving it by rank. */
|
||||
TEST(a_container_beside_other_weights_is_not_served_silently) {
|
||||
TempDir t;
|
||||
t.touch("model-00001-of-00002.safetensors");
|
||||
t.touch("model-00002-of-00002.safetensors");
|
||||
t.touch("model.safetensors.index.json");
|
||||
t.touch("decoy.rad");
|
||||
std::string why;
|
||||
CHECK_EQ(hf_served_path(t.path, &why), std::string());
|
||||
CHECK(why.find("decoy.rad") != std::string::npos);
|
||||
CHECK(why.find("--model") != std::string::npos);
|
||||
/* gguf competes too, and without any competitor the lone container is still the answer. */
|
||||
TempDir g;
|
||||
g.touch("model.gguf");
|
||||
g.touch("converted.rad");
|
||||
CHECK_EQ(hf_served_path(g.path, &why), std::string());
|
||||
TempDir r;
|
||||
r.touch("qwen.rad");
|
||||
r.touch("config.json");
|
||||
CHECK_EQ(hf_served_path(r.path, &why), r.path + "/qwen.rad");
|
||||
}
|
||||
|
||||
TEST(the_download_dir_defaults_to_the_xdg_cache) {
|
||||
const char* x = std::getenv("XDG_CACHE_HOME");
|
||||
const std::string saved = x ? x : "";
|
||||
@@ -288,6 +312,49 @@ TEST(a_listing_naming_a_path_outside_the_destination_is_refused) {
|
||||
CHECK(has(err, "does not land inside the destination"));
|
||||
}
|
||||
|
||||
/* `#` and `?` end the URL's path: curl requests the stripped object instead. A listing that
|
||||
* spells out a truncated name with the truncated object's size and oid passes every check
|
||||
* afterwards -- the bytes arrive under a name nobody asked for, and the manifest certifies the
|
||||
* directory complete. Refused as an escaping name is. */
|
||||
const char* kFragmentListing =
|
||||
"#!/bin/sh\n"
|
||||
"for a in \"$@\"; do case \"$a\" in *api/models*)\n"
|
||||
" printf '[{\"type\":\"file\",\"path\":\"model.bin#x\",\"size\":1},"
|
||||
"{\"type\":\"file\",\"path\":\"kept.bin\",\"size\":1}]'; exit 0;; esac; done\n"
|
||||
"exit 22\n";
|
||||
|
||||
TEST(a_listing_name_that_curl_would_truncate_is_refused_whole) {
|
||||
NEED_ARTIFACT(hfget_beside_this_binary());
|
||||
if (!on_path("jq")) SKIP("no jq on PATH, which hfget.sh needs");
|
||||
TempDir root;
|
||||
REQUIRE(!root.path.empty());
|
||||
FakeCurl curl(kFragmentListing);
|
||||
const std::string cmd = "sh '" + hfget_beside_this_binary() +
|
||||
"' radiance-test-owner/radiance-test-model '" + root.path +
|
||||
"' >/dev/null 2>&1";
|
||||
CHECK(std::system(cmd.c_str()) != 0);
|
||||
CHECK(!fs::exists(root.path + "/model.bin#x"));
|
||||
CHECK(!fs::exists(root.path + "/model.bin")); /* curl would have fetched this one */
|
||||
CHECK(!fs::exists(root.path + "/kept.bin")); /* the whole listing is refused */
|
||||
CHECK(!fs::exists(root.path + "/.hfget-manifest"));
|
||||
}
|
||||
|
||||
/* The per-file child re-screens its name without waiting for the parent: a trailing `..` (the
|
||||
* parent's regex caught it, the child's old case did not) and curl's own path terminators must
|
||||
* fail there too, before any request or any write. */
|
||||
TEST(the_child_screen_refuses_trailing_dotdot_and_curl_terminator_names) {
|
||||
NEED_ARTIFACT(hfget_beside_this_binary());
|
||||
TempDir root;
|
||||
REQUIRE(!root.path.empty());
|
||||
for (const char* name : {"model.bin#x", "model.bin?y", "sub/.."}) {
|
||||
const std::string cmd =
|
||||
"HFGET_CHILD=1 HFGET_DEST='" + root.path + "' sh '" + hfget_beside_this_binary() +
|
||||
"' \"$(printf '5\\t\\t" + std::string(name) + "')\" >/dev/null 2>&1";
|
||||
CHECK(std::system(cmd.c_str()) != 0);
|
||||
}
|
||||
CHECK(fs::is_empty(root.path));
|
||||
}
|
||||
|
||||
/* An LFS file's oid is the hub's claim about its bytes; the download is kept only once those
|
||||
* bytes hash to it -- the size check alone would take a swapped file of the same length, and a
|
||||
* spliced resume at any length the hub likes. A mismatch deletes the file and fails the run;
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
/* history_test.cpp -- the dashboard's hour of history (core/server/history.h).
|
||||
*
|
||||
* Rows what two consecutive /stats objects yield: instantaneous figures from one, rates from
|
||||
* the difference, and nothing where a counter did not move
|
||||
* Fleet a card's telemetry, a model's state and its bytes on each card
|
||||
* Ring an hour is kept, a value a sample did not yield is null, and `since` cuts
|
||||
* Requests a request is recorded once when it finishes, seen done or gone between two samples
|
||||
* Starts a model's counters start over with it: no rate across a restart
|
||||
* Live a response body carries the latest sample's object, and none for a model not open
|
||||
*
|
||||
* No server: JSON objects in, JSON out.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "server/history.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::server;
|
||||
|
||||
namespace {
|
||||
|
||||
double of(const History::Row& r, const std::string& k) {
|
||||
for (const auto& [name, v] : r)
|
||||
if (name == k) return v;
|
||||
return std::nan("");
|
||||
}
|
||||
bool has(const History::Row& r, const std::string& k) { return std::isfinite(of(r, k)); }
|
||||
|
||||
json stats(int64_t started, double steps_decode, double step_ns_decode, double total_requests) {
|
||||
return json::parse(R"({"started_at": )" + std::to_string(started) + R"(, "decode_tps": 120.5, "prefill_tps": 900,
|
||||
"running": 2, "waiting": 1, "preempted": 0, "in_flight": 3, "prefix_hit_rate": 0.75,
|
||||
"kv_bytes_used": 4000, "kv_bytes_total": 16000, "kv_tokens_used": 1000, "kv_tokens_cached": 250,
|
||||
"step_ns_decode_best": 21000000, "jobs": {"running": 0, "done": 0, "last_ms": 0},
|
||||
"steps": )" + std::to_string(steps_decode) + R"(, "step_ns": )" + std::to_string(step_ns_decode) + R"(,
|
||||
"steps_decode": )" + std::to_string(steps_decode) + R"(, "step_ns_decode": )" + std::to_string(step_ns_decode) + R"(,
|
||||
"total_requests": )" + std::to_string(total_requests) + R"(,
|
||||
"draft_positions": [{"reached": )" + std::to_string(steps_decode) + R"(, "accepted": )" +
|
||||
std::to_string(steps_decode / 2) + R"(}], "requests": []})");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(one_stats_object_yields_the_instantaneous_figures_and_no_rate) {
|
||||
const History::Row r = History::model_row(stats(7, 100, 2.2e9, 10), nullptr, 0);
|
||||
CHECK_EQ(of(r, "decode"), 120.5);
|
||||
CHECK_EQ(of(r, "running"), 2.0);
|
||||
CHECK_EQ(of(r, "flight"), 3.0);
|
||||
CHECK_EQ(of(r, "hit"), 0.75);
|
||||
/* A quarter of the tokens are kept turns, so a quarter of the bytes. */
|
||||
CHECK_EQ(of(r, "kvKept"), 1000.0);
|
||||
CHECK_EQ(of(r, "kvRead"), 3000.0);
|
||||
CHECK_EQ(of(r, "stepBest"), 21.0);
|
||||
CHECK(!has(r, "step"));
|
||||
CHECK(!has(r, "reqRate"));
|
||||
CHECK(!has(r, "accept"));
|
||||
}
|
||||
|
||||
TEST(two_stats_objects_yield_rates_over_the_time_between_them) {
|
||||
const json a = stats(7, 100, 2.2e9, 10), b = stats(7, 150, 3.3e9, 14);
|
||||
const History::Row r = History::model_row(b, &a, 2.0);
|
||||
CHECK_EQ(of(r, "reqRate"), 2.0); /* four requests in two seconds */
|
||||
CHECK_EQ(of(r, "step"), 22.0); /* 1.1e9 ns over 50 steps */
|
||||
CHECK_EQ(of(r, "accept"), 0.5); /* 25 accepted of 50 reached */
|
||||
CHECK_EQ(of(r, "tokStep"), 1.5);
|
||||
/* No step ran: no step time, and the counters that did not move yield no acceptance. */
|
||||
const History::Row idle = History::model_row(a, &a, 1.0);
|
||||
CHECK(!has(idle, "step"));
|
||||
CHECK(!has(idle, "accept"));
|
||||
CHECK_EQ(of(idle, "reqRate"), 0.0);
|
||||
}
|
||||
|
||||
TEST(a_prompt_s_prefill_rate_is_its_fresh_tokens_over_its_own_prefill_time_once) {
|
||||
json a = stats(7, 100, 2.2e9, 10), b = stats(7, 100, 2.2e9, 10);
|
||||
b["requests"] = json::parse(R"([{"id": "r1", "state": "decode", "prompt": 5000, "cached": 1000, "prefill_s": 2.0}])");
|
||||
CHECK_EQ(of(History::model_row(b, &a, 1.0), "prefillRate"), 2000.0);
|
||||
/* The next sample sees the same request past its prefill: it is counted once. */
|
||||
CHECK(!has(History::model_row(b, &b, 1.0), "prefillRate"));
|
||||
}
|
||||
|
||||
TEST(the_fleet_row_holds_telemetry_states_and_bytes_per_card) {
|
||||
const json f = json::parse(R"({"models": [
|
||||
{"id": "a", "state": "resident", "cards": [0, 1], "vram_bytes_per_card": 1000},
|
||||
{"id": "b", "state": "parked", "cards": [1], "vram_bytes_per_card": 0},
|
||||
{"id": "c", "state": "cold"}],
|
||||
"cards": [{"card": 0, "busy": 0.5, "power_w": 200, "temp_c": 60, "free_bytes": 7},
|
||||
{"card": 1, "free_bytes": 9}]})");
|
||||
const History::Row r = History::fleet_row(f);
|
||||
CHECK_EQ(of(r, "s:a"), 3.0);
|
||||
CHECK_EQ(of(r, "s:b"), 1.0);
|
||||
CHECK_EQ(of(r, "s:c"), 0.0);
|
||||
CHECK_EQ(of(r, "busy0"), 0.5);
|
||||
CHECK_EQ(of(r, "power0"), 200.0);
|
||||
CHECK_EQ(of(r, "temp0"), 60.0);
|
||||
CHECK(!has(r, "busy1")); /* not sampled is a gap, not a zero */
|
||||
CHECK_EQ(of(r, "c0:a"), 1000.0);
|
||||
CHECK_EQ(of(r, "c1:a"), 1000.0);
|
||||
CHECK_EQ(of(r, "c0:b"), 0.0); /* a model with nothing on a card is an empty band */
|
||||
CHECK_EQ(of(r, "c1:c"), 0.0);
|
||||
}
|
||||
|
||||
TEST(the_ring_keeps_an_hour_and_since_cuts) {
|
||||
History h;
|
||||
for (int i = 0; i < History::kKeepS + 10; ++i) h.model_sample("m", stats(7, 100 + i, 2.2e9 + 2e7 * i, 10), 1000.0 + i);
|
||||
json all = h.model_since("m", 0);
|
||||
CHECK_EQ((int)all["t"].size(), History::kKeepS);
|
||||
CHECK_EQ(all["t"][0].get<double>(), 1010.0); /* the ten oldest are gone */
|
||||
CHECK_EQ((int)all["c"]["decode"].size(), History::kKeepS);
|
||||
CHECK_EQ(all["keep_s"].get<int>(), History::kKeepS);
|
||||
json tail = h.model_since("m", 1000.0 + History::kKeepS + 7);
|
||||
CHECK_EQ((int)tail["t"].size(), 2);
|
||||
CHECK_EQ((int)tail["c"]["step"].size(), 2);
|
||||
CHECK_EQ(tail["c"]["step"][0].get<double>(), 20.0);
|
||||
/* A model nobody sampled answers with nothing. */
|
||||
CHECK_EQ((int)h.model_since("other", 0)["t"].size(), 0);
|
||||
}
|
||||
|
||||
TEST(a_value_a_sample_did_not_yield_is_null_and_an_empty_column_is_left_out) {
|
||||
History h;
|
||||
h.model_sample("m", stats(7, 100, 2.2e9, 10), 10.0);
|
||||
h.model_sample("m", stats(7, 150, 3.3e9, 10), 11.0);
|
||||
json j = h.model_since("m", 0);
|
||||
CHECK(j["c"]["step"][0].is_null()); /* the first sample has no predecessor */
|
||||
CHECK_EQ(j["c"]["step"][1].get<double>(), 22.0);
|
||||
CHECK(!j["c"].contains("lkAr")); /* no link counters in these objects */
|
||||
}
|
||||
|
||||
TEST(a_request_is_recorded_once_when_it_finishes) {
|
||||
History h;
|
||||
json s = stats(7, 100, 2.2e9, 10);
|
||||
s["requests"] = json::parse(R"([{"id": "r1", "state": "decode", "prompt": 400, "cached": 0, "output": 10, "ctx": 410, "tps": 50},
|
||||
{"id": "r2", "state": "decode", "prompt": 100, "cached": 0, "output": 5, "ctx": 105, "tps": 40}])");
|
||||
h.model_sample("m", s, 10.0);
|
||||
CHECK_EQ((int)h.model_since("m", 0)["requests"].size(), 0);
|
||||
/* r1 is seen done and stays in the table for a while; r2 leaves between two samples. */
|
||||
s["requests"] = json::parse(R"([{"id": "r1", "state": "done", "prompt": 400, "cached": 100, "output": 90, "ctx": 490,
|
||||
"ttft_s": 0.25, "prefill_s": 0.5, "tps": 55}])");
|
||||
h.model_sample("m", s, 11.0);
|
||||
h.model_sample("m", s, 12.0);
|
||||
json r = h.model_since("m", 0)["requests"];
|
||||
REQUIRE_EQ((int)r.size(), 2);
|
||||
CHECK_EQ(r[0]["id"].get<std::string>(), "r1");
|
||||
CHECK_EQ(r[0]["out"].get<double>(), 90.0);
|
||||
CHECK_EQ(r[0]["pf"].get<double>(), 600.0); /* 300 fresh tokens in half a second */
|
||||
CHECK_EQ(r[0]["ttft"].get<double>(), 0.25);
|
||||
CHECK_EQ(r[1]["id"].get<std::string>(), "r2");
|
||||
CHECK(r[1]["ttft"].is_null());
|
||||
/* `since` cuts the requests as it cuts the samples. */
|
||||
CHECK_EQ((int)h.model_since("m", 11.5)["requests"].size(), 0);
|
||||
}
|
||||
|
||||
/* A page asks for what came after the last sample time it was given. Times are sent to the
|
||||
* millisecond, so a sample taken between two milliseconds must not be later than its own sent
|
||||
* time: asked with it, the history answers with nothing of that sample, and with no request that
|
||||
* finished in it. */
|
||||
TEST(asking_with_the_last_time_given_repeats_neither_a_sample_nor_a_request) {
|
||||
for (double frac : { 0.0, 0.0004, 0.0006, 0.84561, 0.9996 }) {
|
||||
History h;
|
||||
json s = stats(7, 100, 2.2e9, 10);
|
||||
s["requests"] = json::parse(R"([{"id": "r1", "state": "decode", "prompt": 40, "cached": 0, "output": 3, "ctx": 43, "tps": 50}])");
|
||||
h.model_sample("m", s, 1794590850.0 + frac);
|
||||
s["requests"] = json::array();
|
||||
h.model_sample("m", s, 1794590851.0 + frac); /* r1 is gone: it finished */
|
||||
const json all = h.model_since("m", 0);
|
||||
REQUIRE_EQ((int)all["t"].size(), 2);
|
||||
REQUIRE_EQ((int)all["requests"].size(), 1);
|
||||
const double last = all["t"][1].get<double>();
|
||||
/* The page sends the number back as text. */
|
||||
const double asked = std::strtod(json(last).dump().c_str(), nullptr);
|
||||
const json next = h.model_since("m", asked);
|
||||
CHECK_EQ((int)next["t"].size(), 0);
|
||||
CHECK_EQ((int)next["requests"].size(), 0);
|
||||
/* Asked with the sample before, it gets exactly the last one and its request. */
|
||||
const json one = h.model_since("m", all["t"][0].get<double>());
|
||||
CHECK_EQ((int)one["t"].size(), 1);
|
||||
CHECK_EQ((int)one["requests"].size(), 1);
|
||||
h.fleet_sample(json::parse(R"({"models": [], "cards": [{"card": 0, "free_bytes": 7}]})"), 1794590851.0 + frac);
|
||||
const json f = h.fleet_since(0);
|
||||
REQUIRE_EQ((int)f["t"].size(), 1);
|
||||
CHECK_EQ((int)h.fleet_since(f["t"][0].get<double>())["t"].size(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_restarted_model_yields_no_rate_across_the_restart) {
|
||||
History h;
|
||||
h.model_sample("m", stats(7, 5000, 9e10, 400), 10.0);
|
||||
h.model_sample("m", stats(8, 10, 2.2e8, 1), 11.0); /* started_at moved: counters began again */
|
||||
json j = h.model_since("m", 0);
|
||||
CHECK(!j["c"].contains("step"));
|
||||
h.model_sample("m", stats(8, 20, 4.4e8, 3), 12.0);
|
||||
j = h.model_since("m", 0);
|
||||
CHECK_EQ(j["c"]["step"][2].get<double>(), 22.0);
|
||||
CHECK_EQ(j["c"]["reqRate"][2].get<double>(), 2.0);
|
||||
h.forget("m");
|
||||
CHECK_EQ((int)h.model_since("m", 0)["t"].size(), 0);
|
||||
}
|
||||
|
||||
TEST(a_body_carries_the_latest_sample_s_object_as_live) {
|
||||
History h;
|
||||
CHECK_EQ(h.fleet_body(0), R"({"keep_s":3600,"t":[],"c":{},"live":null})");
|
||||
const json s = stats(7, 100, 2.2e9, 10);
|
||||
h.model_sample("m", s, 10.0, R"({"decode_tps":120.5})");
|
||||
json b = json::parse(h.model_body("m", 0));
|
||||
CHECK_EQ(b["live"]["decode_tps"].get<double>(), 120.5);
|
||||
CHECK_EQ((int)b["t"].size(), 1);
|
||||
/* A model that is not open keeps its history and has no live object. */
|
||||
h.model_closed("m");
|
||||
b = json::parse(h.model_body("m", 0));
|
||||
CHECK(b["live"].is_null());
|
||||
CHECK_EQ((int)b["t"].size(), 1);
|
||||
CHECK(json::parse(h.model_body("unknown", 0))["live"].is_null());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+18
-12
@@ -41,15 +41,15 @@ constexpr int64_t kEmbd = 256, kFF = 128, kExperts = 8, kTopK = 2, kHC = 4, kLow
|
||||
bool protected_expert(long long e) { return e == 3 || e == 5; }
|
||||
|
||||
RadEncoding codebook(const char* dtype) {
|
||||
const bool w5 = !std::strcmp(dtype, "w5nl64a8h"), bf = !std::strcmp(dtype, "w4nla8h");
|
||||
const int64_t group = !std::strcmp(dtype, "w4nl32a8h") ? 32 : bf ? 128 : 64;
|
||||
const bool w5 = !std::strcmp(dtype, "w5nl64a8h");
|
||||
const int64_t group = !std::strcmp(dtype, "w4nl32a8h") ? 32 : 64;
|
||||
RadEncoding e;
|
||||
rad_enc_clear(&e);
|
||||
rad_enc_copy_str(e.scheme, "affine");
|
||||
rad_enc_copy_str(e.transform, "fwht128");
|
||||
rad_enc_add_plane(&e, "codes", w5 ? RAD_U5 : RAD_U4, 1, 1);
|
||||
rad_enc_add_plane(&e, "scale", bf ? RAD_BF16 : RAD_F8E4M3, 1, group);
|
||||
if (!bf) rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0);
|
||||
rad_enc_add_plane(&e, "scale", RAD_F8E4M3, 1, group);
|
||||
rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0);
|
||||
rad_enc_add_table(&e, "table", RAD_F32, 1, w5 ? 32 : 16);
|
||||
return e;
|
||||
}
|
||||
@@ -131,9 +131,11 @@ int declare_layer(RadBuilder* b, MoeFP8* mlp, HyperConn* hc) {
|
||||
x.x = decl_b(b, nm.f("x"), RAD_BF16, { T, kEmbd });
|
||||
RAD_ARCH_TRY(x.declare_qs(b, nm, g, "x", kEmbd, 0, true));
|
||||
x.q8_fed = true;
|
||||
RAD_ARCH_TRY(hr.declare_qs(b, nm, g, "moe_hr", kEmbd));
|
||||
RAD_ARCH_TRY(hr.declare_qs(b, nm, g, "moe_hr", kEmbd, 0, true, false, RAD_FP8_BLOCK));
|
||||
hr.q8_fed = hr.q8_rot = true;
|
||||
eff.x = decl_b(b, nm.f("moe_eff"), RAD_BF16, { ER, kFF });
|
||||
RAD_ARCH_TRY(eff.declare_qs(b, nm, g, "moe_eff", kFF, ER));
|
||||
RAD_ARCH_TRY(eff.declare_qs(b, nm, g, "moe_eff", kFF, ER, true, false, RAD_FP8_BLOCK));
|
||||
eff.q8_fed = eff.q8_rot = true;
|
||||
sff.x = decl_b(b, nm.f("moe_sff"), RAD_BF16, { T, kFF });
|
||||
RAD_ARCH_TRY(sff.declare_qs(b, nm, g, "moe_sff", kFF, 0, true));
|
||||
sff.q8_fed = true;
|
||||
@@ -142,8 +144,8 @@ int declare_layer(RadBuilder* b, MoeFP8* mlp, HyperConn* hc) {
|
||||
hw.h = decl_b(b, nm.f("h_wide"), RAD_BF16, { T, kHC * kEmbd });
|
||||
hw.x = x;
|
||||
hw.inj = decl_b(b, nm.f("hc_inj"), RAD_BF16, { T, kHC });
|
||||
hw.rq = hr.q;
|
||||
hw.rs = hr.s;
|
||||
hw.rq = hr.cq();
|
||||
hw.rs = hr.cs();
|
||||
HyperConn::Config hcfg;
|
||||
hcfg.hc = kHC;
|
||||
hcfg.lowrank = kLowRank;
|
||||
@@ -190,7 +192,11 @@ TEST(flash_next_experts_declare_on_libavx_alone) {
|
||||
Registry reg;
|
||||
const int st = reg.load_dir(home() + "/kernels", { "libavx" });
|
||||
if (st == RAD_E_IO || !reg.plugin("libavx")) ARTIFACT_MISSING(home() + "/kernels/libavx.so");
|
||||
for (const char* dtype : { "w4nla8h", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) {
|
||||
/* The routed arm at int8 activations writes its gated product with gated_had_quant_i8g, which
|
||||
* libavx has no row for. */
|
||||
if (!reg.schema("gated_had_quant_i8g"))
|
||||
SKIP("libavx declares no gated_had_quant_i8g, the int8 routed arm's gated quantiser");
|
||||
for (const char* dtype : { "w4nl64a8h", "w4nl32a8h" }) {
|
||||
Builder b(reg, meta(), ctx());
|
||||
b.set_sources([dtype](const std::string& name, const Program&, WeightSource* out) {
|
||||
return sources(dtype, name, out);
|
||||
@@ -226,7 +232,7 @@ TEST(flash_next_experts_declare_on_libavx_alone) {
|
||||
}
|
||||
}
|
||||
for (const char* want : { "hc_read", "hc_write", "gemm_nt", "router_topk", "moe_scatter",
|
||||
"moe_gemm_q", "had_quant_act_fp8", "silu_mul", "moe_gemm",
|
||||
"moe_gemm_q", "silu_mul", "moe_gemm",
|
||||
"gemm_nt_q", "moe_gather" })
|
||||
if (!ops.count(want)) {
|
||||
fprintf(stderr, " %s: the layer declares no '%s'\n", dtype, want);
|
||||
@@ -247,8 +253,8 @@ TEST(flash_next_experts_declare_on_libavx_alone) {
|
||||
CHECK(w.layout_tag.empty());
|
||||
}
|
||||
}
|
||||
/* Six codebook experts, codes view and (but at w4nla8h) scale view, both projections. */
|
||||
CHECK_EQ(joined, (std::strcmp(dtype, "w4nla8h") ? 4 : 2) * 6);
|
||||
/* Six codebook experts, codes view and scale view, both projections. */
|
||||
CHECK_EQ(joined, 4 * 6);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,427 @@
|
||||
/* json_test.cpp -- rad::Json's observable contract.
|
||||
*
|
||||
* The DOM (util/json.h) is the tree's one JSON reader and writer: a yyjson read, ordered
|
||||
* objects, integer/float typing where non-negative integers are unsigned and an integer past
|
||||
* uint64 is a double, duplicate keys keeping the first position with the last value, and
|
||||
* shortest-round-trip float spellings. The curated expectations below are that contract
|
||||
* written down -- they were recorded against the DOM this one replaced, while the two still
|
||||
* stood side by side (type-exact fingerprints, dump bytes, boundary behaviour), and they now
|
||||
* hold the reader to it alone: change one only with the same deliberateness as changing a
|
||||
* wire format.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "util/json.h"
|
||||
|
||||
#include <charconv>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using rad::Json;
|
||||
|
||||
#define CHECK_THROWS(expr) \
|
||||
do { \
|
||||
bool threw_ = false; \
|
||||
try { \
|
||||
expr; \
|
||||
} catch (const std::exception&) { \
|
||||
threw_ = true; \
|
||||
} \
|
||||
CHECK(threw_); \
|
||||
} while (0)
|
||||
|
||||
namespace {
|
||||
|
||||
/* Type-exact fingerprint, bar one dump round trip's known loss: a non-negative integer
|
||||
* prints as its digits and re-reads unsigned, so signedness below 2^63 is not part of the
|
||||
* fingerprint (it is asserted directly where it matters). Float bit patterns are exact. */
|
||||
void fp(const Json& j, std::string& out) {
|
||||
if (j.is_null()) out += 'n';
|
||||
else if (j.is_boolean()) out += j.get<bool>() ? 'T' : 'F';
|
||||
else if (j.is_number_unsigned() && j.get<uint64_t>() > (uint64_t)INT64_MAX) {
|
||||
out += 'u';
|
||||
out += std::to_string(j.get<uint64_t>());
|
||||
}
|
||||
else if (j.is_number_integer()) { out += 'i'; out += std::to_string(j.get<int64_t>()); }
|
||||
else if (j.is_number_float()) {
|
||||
double d = j.get<double>();
|
||||
uint64_t bits;
|
||||
memcpy(&bits, &d, 8);
|
||||
char buf[32];
|
||||
snprintf(buf, sizeof buf, "f%016llx", (unsigned long long)bits);
|
||||
out += buf;
|
||||
}
|
||||
else if (j.is_string()) { out += 's'; out += j.get<std::string>(); out += '\x01'; }
|
||||
else if (j.is_array()) { out += '['; for (const auto& e : j) fp(e, out); out += ']'; }
|
||||
else {
|
||||
out += '{';
|
||||
for (auto it = j.begin(); it != j.end(); ++it) { out += it.key(); out += '='; fp(*it, out); }
|
||||
out += '}';
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(json_parse_accepts_and_refuses_the_recorded_texts) {
|
||||
/* input -> the canonical dump of what it reads as. */
|
||||
const std::pair<const char*, const char*> accepted[] = {
|
||||
{ "{\"a\":1e-999}", "{\"a\":0.0}" },
|
||||
{ "{\"a\":1e-400}", "{\"a\":0.0}" },
|
||||
{ "{\"a\":0e999}", "{\"a\":0.0}" },
|
||||
{ "{\"a\":1.7976931348623157e308}", "{\"a\":1.7976931348623157e+308}" },
|
||||
{ "{\"a\":2.2250738585072011e-308}", "{\"a\":2.225073858507201e-308}" },
|
||||
{ "{\"a\":5e-324}", "{\"a\":5e-324}" },
|
||||
{ "{\"a\":4e-324}", "{\"a\":5e-324}" },
|
||||
{ "{\"a\":0.1}", "{\"a\":0.1}" },
|
||||
{ "{\"a\":123456789012345678901234567890}", "{\"a\":1.2345678901234568e+29}" },
|
||||
{ "{\"a\":9223372036854775807}", "{\"a\":9223372036854775807}" },
|
||||
{ "{\"a\":9223372036854775808}", "{\"a\":9223372036854775808}" },
|
||||
{ "{\"a\":-9223372036854775808}", "{\"a\":-9223372036854775808}" },
|
||||
{ "{\"a\":-9223372036854775809}", "{\"a\":-9.223372036854776e+18}" },
|
||||
{ "{\"a\":18446744073709551615}", "{\"a\":18446744073709551615}" },
|
||||
{ "{\"a\":18446744073709551616}", "{\"a\":1.8446744073709552e+19}" },
|
||||
{ "{\"a\":-0}", "{\"a\":0}" },
|
||||
{ "{\"a\":-0.0}", "{\"a\":-0.0}" },
|
||||
{ "{\"a\":0.0}", "{\"a\":0.0}" },
|
||||
{ "{\"a\":1E7}", "{\"a\":10000000.0}" },
|
||||
{ "{\"a\":1e+7}", "{\"a\":10000000.0}" },
|
||||
{ "{\"a\":\"\\u0000\"}", "{\"a\":\"\\u0000\"}" },
|
||||
{ "{\"a\":\"\\/\"}", "{\"a\":\"/\"}" },
|
||||
{ "{\"a\":\"\"}", "{\"a\":\"\"}" },
|
||||
{ "{\"a\":1,\"b\":0,\"a\":2,\"b\":3}", "{\"a\":2,\"b\":3}" },
|
||||
{ "{\"\\u0061\":1}", "{\"a\":1}" },
|
||||
{ "[]", "[]" }, { "{}", "{}" }, { "null", "null" }, { "true", "true" },
|
||||
{ "42", "42" }, { "-17", "-17" }, { "3.25", "3.25" }, { "\"hi\"", "\"hi\"" },
|
||||
{ " {\"a\":1} ", "{\"a\":1}" },
|
||||
{ "{\"x\":[1,\"two\",3.0,null,true,{\"y\":[]},{}]}",
|
||||
"{\"x\":[1,\"two\",3.0,null,true,{\"y\":[]},{}]}" },
|
||||
{ "{\"a\":\"line\\nbreak\\t\\\"quote\\\" \\\\ slash\"}",
|
||||
"{\"a\":\"line\\nbreak\\t\\\"quote\\\" \\\\ slash\"}" },
|
||||
};
|
||||
for (const auto& c : accepted) {
|
||||
const Json j = Json::parse(c.first, nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
CHECK_EQ(j.dump(), std::string(c.second));
|
||||
/* Every spelling of a document reads back to the same tree. */
|
||||
for (const std::string& text : { j.dump(), j.dump(2), j.dump(-1, ' ', true) }) {
|
||||
std::string a, b;
|
||||
fp(j, a);
|
||||
fp(Json::parse(text), b);
|
||||
CHECK_EQ(b, a);
|
||||
}
|
||||
}
|
||||
/* Non-ASCII is carried as UTF-8 bytes, escapes in and raw out. */
|
||||
{
|
||||
const Json j = Json::parse("{\"a\":\"caf\\u00e9 \\ud83d\\ude00\"}");
|
||||
CHECK_EQ(j["a"].get<std::string>(), std::string("caf\xc3\xa9 \xf0\x9f\x98\x80"));
|
||||
CHECK_EQ(j.dump(), std::string("{\"a\":\"caf\xc3\xa9 \xf0\x9f\x98\x80\"}"));
|
||||
CHECK_EQ(j.dump(-1, ' ', true), std::string("{\"a\":\"caf\\u00e9 \\ud83d\\ude00\"}"));
|
||||
const Json bom = Json::parse(std::string("\xef\xbb\xbf") + "{\"a\":1}", nullptr, false);
|
||||
CHECK(!bom.is_discarded());
|
||||
CHECK_EQ(bom.dump(), std::string("{\"a\":1}"));
|
||||
CHECK(!Json::parse("{\"a\":\"\xc3\xa9\"}", nullptr, false).is_discarded());
|
||||
CHECK(!Json::parse("{\"a\":\"\xe2\x82\xac\"}", nullptr, false).is_discarded());
|
||||
}
|
||||
/* Typing: parsed non-negative integers are unsigned, -0 signed, past-uint64 double. */
|
||||
CHECK(Json::parse("3").is_number_unsigned());
|
||||
CHECK(Json::parse("-0").is_number_integer() && !Json::parse("-0").is_number_unsigned());
|
||||
CHECK(Json::parse("-9223372036854775809").is_number_float());
|
||||
/* Very long number texts read (or refuse) without incident. */
|
||||
CHECK(!Json::parse("{\"a\":0." + std::string(5000, '7') + "}", nullptr, false).is_discarded());
|
||||
CHECK(Json::parse("{\"a\":" + std::string(10000, '9') + "}", nullptr, false).is_discarded());
|
||||
|
||||
const char* refused[] = {
|
||||
"{\"a\":1e309}", "{\"a\":-1e309}", "{\"a\":1.7976931348623159e308}",
|
||||
"{\"a\":0x10}", "{\"a\":.5}", "{\"a\":1.}", "{\"a\":1e}", "{\"a\":01}", "{\"a\":+1}",
|
||||
"{\"a\":NaN}", "{\"a\":Infinity}",
|
||||
"{\"a\":\"\\ude00\"}", "{\"a\":\"\\ud800\"}", "{\"a\":\"\\x\"}", "{\"a\":\"\\u12g4\"}",
|
||||
"[1,2,]", "{,}", "{\"a\"}", "{\"a\":}", "[}", "nul", "{\"a\":\"unterminated}",
|
||||
"", " ", "{\"a\":1} x", "{\"a\":1} {\"b\":2}",
|
||||
"{\"a\":\"\xff\"}", "{\"a\":\"\xc3\x28\"}", "{\"a\":\"\xed\xa0\x80\"}",
|
||||
};
|
||||
for (const char* c : refused) CHECK(Json::parse(c, nullptr, false).is_discarded());
|
||||
}
|
||||
|
||||
TEST(json_dump_float_spellings_are_the_shortest_round_trip) {
|
||||
const std::pair<double, const char*> known[] = {
|
||||
{ 1.0, "1.0" }, { -0.0, "-0.0" }, { 0.1, "0.1" }, { 1e20, "1e+20" },
|
||||
{ 1e-7, "1e-07" }, { 1e16, "1e+16" }, { 1e15, "1e+15" },
|
||||
{ 123456789.25, "123456789.25" },
|
||||
{ 4.767695833215205e86, "4.767695833215205e+86" },
|
||||
{ 2.2250738585072014e-308, "2.2250738585072014e-308" },
|
||||
{ 5e-324, "5e-324" },
|
||||
{ 1.7976931348623157e308, "1.7976931348623157e+308" },
|
||||
{ 3.141592653589793, "3.141592653589793" },
|
||||
/* Fixed notation while the point is within (-4, 15] places of the first digit, as the
|
||||
* predecessor wrote them: these reach grammars through a schema's const and enum. */
|
||||
{ 100000.0, "100000.0" }, { 3e6, "3000000.0" }, { 0.0001, "0.0001" },
|
||||
{ 0.001234, "0.001234" }, { 1e-5, "1e-05" }, { 1.5e-5, "1.5e-05" },
|
||||
{ 123456789012345.0, "123456789012345.0" },
|
||||
{ 1234567890123456.0, "1.234567890123456e+15" },
|
||||
{ -9223372036854775809.0, "-9.223372036854776e+18" },
|
||||
{ 1.5e300, "1.5e+300" }, { -2.5, "-2.5" },
|
||||
};
|
||||
for (const auto& k : known) CHECK_EQ(Json(k.first).dump(), std::string(k.second));
|
||||
|
||||
std::mt19937_64 rng(4242);
|
||||
int checked = 0;
|
||||
for (int i = 0; i < 100000 && checked < 60000; ++i) {
|
||||
uint64_t bits = rng();
|
||||
double d;
|
||||
memcpy(&d, &bits, 8);
|
||||
if (!std::isfinite(d)) continue;
|
||||
const double back = Json::parse(Json(d).dump()).get<double>();
|
||||
uint64_t b2;
|
||||
memcpy(&b2, &back, 8);
|
||||
CHECK_EQ(b2, bits);
|
||||
++checked;
|
||||
}
|
||||
CHECK(checked > 50000);
|
||||
/* Non-finite values dump as null, integral floats keep their point. */
|
||||
CHECK_EQ(Json(HUGE_VAL).dump(), std::string("null"));
|
||||
CHECK_EQ(Json(NAN).dump(), std::string("null"));
|
||||
}
|
||||
|
||||
TEST(json_random_structures_round_trip_identically) {
|
||||
std::mt19937_64 rng(7);
|
||||
std::function<Json(int)> build = [&](int depth) -> Json {
|
||||
switch (rng() % (depth > 3 ? 6 : 9)) {
|
||||
case 0: return nullptr;
|
||||
case 1: return (bool)(rng() & 1);
|
||||
case 2: return (int64_t)rng();
|
||||
case 3: return rng();
|
||||
case 4: {
|
||||
double d;
|
||||
uint64_t bits = rng();
|
||||
memcpy(&d, &bits, 8);
|
||||
return std::isfinite(d) ? Json(d) : Json(0.5);
|
||||
}
|
||||
case 5: {
|
||||
static const char* words[] = { "plain", "with \"quotes\"", "uni\xc3\xa9", "\xe2\x82\xac",
|
||||
"ctrl\x01\x1f", "", "back\\slash", "nl\n" };
|
||||
return words[rng() % 8];
|
||||
}
|
||||
case 6: case 7: {
|
||||
Json a = Json::array();
|
||||
const int n = (int)(rng() % 5);
|
||||
for (int i = 0; i < n; ++i) a.push_back(build(depth + 1));
|
||||
return a;
|
||||
}
|
||||
default: {
|
||||
Json o = Json::object();
|
||||
const int n = (int)(rng() % 5);
|
||||
for (int i = 0; i < n; ++i) o["k" + std::to_string(rng() % 3)] = build(depth + 1);
|
||||
return o;
|
||||
}
|
||||
}
|
||||
};
|
||||
for (int i = 0; i < 2000; ++i) {
|
||||
const Json built = build(0);
|
||||
std::string want, got;
|
||||
fp(built, want);
|
||||
fp(Json::parse(built.dump()), got);
|
||||
CHECK_EQ(got, want);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(json_dom_api_carries_the_shapes_callers_use) {
|
||||
Json j = { { "name", "edit" }, { "count", 3 }, { "ratio", 0.5 }, { "on", true },
|
||||
{ "tags", Json::array({ "a", "b" }) }, { "none", nullptr } };
|
||||
CHECK(j.is_object());
|
||||
CHECK_EQ(j.size(), 6u);
|
||||
CHECK_EQ(j["name"].get<std::string>(), std::string("edit"));
|
||||
CHECK_EQ(j["count"].get<int>(), 3);
|
||||
CHECK(j["count"].is_number_integer() && !j["count"].is_number_unsigned());
|
||||
CHECK_NEAR(j["ratio"].get<double>(), 0.5, 1e-12);
|
||||
CHECK_EQ(j.value("missing", 42), 42);
|
||||
CHECK_EQ(j.value("name", std::string("?")), std::string("edit"));
|
||||
CHECK_EQ(j.value("missing", "fallback"), std::string("fallback"));
|
||||
CHECK(j.contains("tags"));
|
||||
CHECK(!j.contains("nope"));
|
||||
CHECK_EQ(j.at("tags").at(1).get<std::string>(), std::string("b"));
|
||||
CHECK_EQ(j.dump(),
|
||||
std::string("{\"name\":\"edit\",\"count\":3,\"ratio\":0.5,\"on\":true,"
|
||||
"\"tags\":[\"a\",\"b\"],\"none\":null}"));
|
||||
|
||||
/* Self-subtree assignment (schema $ref resolution writes n = n[sel]): the source must
|
||||
* survive the target's old value being destroyed. */
|
||||
{
|
||||
Json t = Json::parse("{\"a\":{\"b\":{\"c\":[1,2,3]}},\"d\":4}");
|
||||
t = t["a"];
|
||||
CHECK_EQ(t.dump(), std::string("{\"b\":{\"c\":[1,2,3]}}"));
|
||||
t = std::move(t["b"]);
|
||||
CHECK_EQ(t.dump(), std::string("{\"c\":[1,2,3]}"));
|
||||
Json arr = Json::parse("[[9,8],7]");
|
||||
arr = arr[0];
|
||||
CHECK_EQ(arr.dump(), std::string("[9,8]"));
|
||||
}
|
||||
|
||||
/* Insertion through operator[] on null, and duplicate keys. */
|
||||
Json k;
|
||||
k["a"] = 1;
|
||||
k["b"]["c"] = "deep";
|
||||
k["a"] = 2;
|
||||
CHECK_EQ(k.dump(), std::string("{\"a\":2,\"b\":{\"c\":\"deep\"}}"));
|
||||
|
||||
/* Array growth through operator[] fills gaps with null. */
|
||||
Json a;
|
||||
a[2] = "x";
|
||||
CHECK_EQ(a.dump(), std::string("[null,null,\"x\"]"));
|
||||
|
||||
/* Initializer-list disambiguation: pairs make an object, anything else an array. */
|
||||
Json arr = { 1, "two", 3.0 };
|
||||
CHECK(arr.is_array());
|
||||
Json empty_list = Json::array({});
|
||||
CHECK(empty_list.is_array() && empty_list.empty());
|
||||
|
||||
/* Iteration order and keys. */
|
||||
std::string keys;
|
||||
for (auto it = j.begin(); it != j.end(); ++it) keys += it.key() + ";";
|
||||
CHECK_EQ(keys, std::string("name;count;ratio;on;tags;none;"));
|
||||
std::string via_items;
|
||||
for (auto kv : j.items()) via_items += kv.key() + ";";
|
||||
CHECK_EQ(via_items, keys);
|
||||
std::string via_bindings;
|
||||
for (const auto& [key, val] : j.items()) { (void)val; via_bindings += key + ";"; }
|
||||
CHECK_EQ(via_bindings, keys);
|
||||
|
||||
/* erase, update, equality across number kinds. */
|
||||
CHECK_EQ(k.erase("a"), 1u);
|
||||
CHECK_EQ(k.erase("a"), 0u);
|
||||
Json u = { { "x", { { "p", 1 } } } };
|
||||
u.update(Json::parse("{\"x\":{\"q\":2},\"y\":3}"), true);
|
||||
CHECK_EQ(u.dump(), std::string("{\"x\":{\"p\":1,\"q\":2},\"y\":3}"));
|
||||
CHECK(Json(1) == Json(1.0));
|
||||
CHECK(Json(1) == Json::parse("1"));
|
||||
/* Objects compare member by member in order: key order is part of what is written. */
|
||||
CHECK(Json::parse("{\"a\":1,\"b\":2}") == Json::parse("{\"a\":1,\"b\":2}"));
|
||||
CHECK(Json::parse("{\"a\":1,\"b\":2}") != Json::parse("{\"b\":2,\"a\":1}"));
|
||||
CHECK(Json::parse("18446744073709551615") != Json::parse("18446744073709551616"));
|
||||
CHECK(Json("s") == "s");
|
||||
CHECK(Json(nullptr) == nullptr);
|
||||
|
||||
/* Booleans compare as booleans and read as 0/1 numbers. */
|
||||
CHECK(Json(true) == true);
|
||||
CHECK(Json(false) == false);
|
||||
CHECK(Json(true) != false);
|
||||
CHECK_EQ(Json(true).get<int>(), 1);
|
||||
CHECK_EQ(Json(false).get<int>(), 0);
|
||||
CHECK_NEAR(Json(true).get<double>(), 1.0, 1e-12);
|
||||
CHECK_THROWS(Json(1).get<bool>());
|
||||
|
||||
/* get<> across kinds throws; numbers convert. */
|
||||
CHECK_THROWS(j["name"].get<int>());
|
||||
CHECK_THROWS(j["count"].get<std::string>());
|
||||
CHECK_THROWS(j.at("absent"));
|
||||
CHECK_EQ(Json(3.75).get<int>(), 3);
|
||||
CHECK_NEAR(Json(2).get<double>(), 2.0, 1e-12);
|
||||
const std::vector<std::string> tags = j["tags"].get<std::vector<std::string>>();
|
||||
CHECK_EQ(tags.size(), 2u);
|
||||
std::set<std::string> tagset;
|
||||
j["tags"].get_to(tagset);
|
||||
CHECK_EQ(tagset.size(), 2u);
|
||||
|
||||
/* Implicit conversions. */
|
||||
std::string s = j["name"];
|
||||
int64_t n = j["count"];
|
||||
bool on = j["on"];
|
||||
std::vector<std::string> tv = j["tags"];
|
||||
CHECK_EQ(s, std::string("edit"));
|
||||
CHECK_EQ(n, (int64_t)3);
|
||||
CHECK(on);
|
||||
CHECK_EQ(tv.size(), 2u);
|
||||
|
||||
/* JSON Pointer reads. */
|
||||
CHECK_EQ(j.value(Json::json_pointer("/tags/1"), std::string("?")), std::string("b"));
|
||||
CHECK_EQ(j.value(Json::json_pointer("/nope"), 7), 7);
|
||||
CHECK(j.contains(Json::json_pointer("/tags/0")));
|
||||
CHECK(!j.contains(Json::json_pointer("/tags/9")));
|
||||
|
||||
/* Pretty printing: two-space nesting, "key": value, empty containers stay closed. */
|
||||
CHECK_EQ(Json::parse("{\"a\":[1,{}],\"b\":[]}").dump(2),
|
||||
std::string("{\n \"a\": [\n 1,\n {}\n ],\n \"b\": []\n}"));
|
||||
}
|
||||
|
||||
TEST(json_replace_handler_places_replacements_like_the_dfa) {
|
||||
const std::string rep = "\xef\xbf\xbd";
|
||||
auto dumped = [](const std::string& s, Json::error_handler_t eh) {
|
||||
return Json(s).dump(-1, ' ', false, eh);
|
||||
};
|
||||
/* One replacement per ill-formed maximal subpart: byte-at-a-time where every byte is
|
||||
* ill-formed on its own, one for a merely truncated tail. */
|
||||
const std::pair<std::string, std::string> cases[] = {
|
||||
{ "\xed\xa0\x80", rep + rep + rep }, { "\xc0\xaf", rep + rep },
|
||||
{ "\xe0\x80\xaf", rep + rep + rep }, { "\xf4\x90\x80\x80", rep + rep + rep + rep },
|
||||
{ "\xe2\x82", rep }, { "\xe2", rep }, { "\xc2", rep }, { "\xf0\x9f\x98", rep },
|
||||
{ "\x82", rep }, { "\x82\x82", rep + rep },
|
||||
{ "\xf0\x28\x8c\xbc", rep + "(" + rep + rep },
|
||||
{ "\xe2\x82\x28", rep + "(" }, { "\xc3\x28", rep + "(" },
|
||||
{ "\xff\xfe", rep + rep }, { "a\xed\xa0\x80" "b", "a" + rep + rep + rep + "b" },
|
||||
{ "a\xff\xfe b\xc3\x28 c\xe2\x82 d", "a" + rep + rep + " b" + rep + "( c" + rep + " d" },
|
||||
};
|
||||
for (const auto& c : cases) {
|
||||
CHECK_THROWS(dumped(c.first, Json::error_handler_t::strict));
|
||||
CHECK_EQ(dumped(c.first, Json::error_handler_t::replace), "\"" + c.second + "\"");
|
||||
}
|
||||
/* The valid sequence dumps under strict too; ignore drops ill-formed bytes silently. */
|
||||
CHECK_EQ(dumped("\xed\x9f\xbf", Json::error_handler_t::strict), std::string("\"\xed\x9f\xbf\""));
|
||||
CHECK_EQ(dumped("a\xff" "b", Json::error_handler_t::ignore), std::string("\"ab\""));
|
||||
}
|
||||
|
||||
TEST(json_parse_errors_and_bounds) {
|
||||
CHECK_THROWS(Json::parse("{oops"));
|
||||
CHECK(Json::parse("{oops", nullptr, false).is_discarded());
|
||||
CHECK(Json::accept("{\"a\":[1,2]}"));
|
||||
CHECK(!Json::accept("{\"a\":}"));
|
||||
CHECK(Json::accept("{/*c*/\"a\":1}", true));
|
||||
CHECK(!Json::accept("{/*c*/\"a\":1}"));
|
||||
|
||||
bool over = false, deep = false;
|
||||
const Json j = Json::parse_bounded("[1,2,3]", 3, 8, &over, &deep);
|
||||
CHECK(over && !deep); /* array + 3 scalars = 4 values */
|
||||
const Json k = Json::parse_bounded("[[[[1]]]]", 100, 3, &over, &deep);
|
||||
CHECK(!over && deep);
|
||||
const Json ok = Json::parse_bounded("[[[1]]]", 100, 3, &over, &deep);
|
||||
CHECK(!over && !deep && ok.is_array());
|
||||
CHECK(Json::parse_bounded("{bad", 100, 3, &over, &deep).is_discarded());
|
||||
/* A refused body must be refused WITHOUT first collecting it: this swarm carries no scalar
|
||||
* at all, and the bounded read used to trip its budget in a second pass that ran only after
|
||||
* every frame of the document sat in a scratch vector -- the refusal grew memory with the
|
||||
* body, which is exactly what the bound promises against. Containers are values too. */
|
||||
std::string swarm = "[";
|
||||
for (int i = 0; i < 200000; ++i) swarm += "[],";
|
||||
swarm.back() = ']';
|
||||
over = deep = false;
|
||||
CHECK(Json::parse_bounded(swarm, 1000, 64, &over, &deep).is_discarded());
|
||||
CHECK(over && !deep);
|
||||
}
|
||||
|
||||
TEST(json_parse_duplicate_keys_and_large_flat_objects) {
|
||||
/* A parsed duplicate keeps its first position and takes the last value (see the header). */
|
||||
const Json d = Json::parse("{\"a\":1,\"b\":2,\"a\":3,\"c\":4,\"b\":5}");
|
||||
CHECK_EQ(d.size(), 3u);
|
||||
CHECK_EQ(d.dump(), std::string("{\"a\":3,\"b\":5,\"c\":4}"));
|
||||
|
||||
/* A tokenizer.json-shaped flat object: tens of thousands of members must read back with
|
||||
* every value at its key, in file order, a trailing duplicate included. */
|
||||
std::string text = "{";
|
||||
for (int i = 0; i < 20000; ++i) {
|
||||
if (i) text += ',';
|
||||
text += "\"tok" + std::to_string(i) + "\":" + std::to_string(i * 7 % 100000);
|
||||
}
|
||||
text += ",\"tok0\":-1}";
|
||||
const Json big = Json::parse(text);
|
||||
CHECK_EQ(big.size(), 20000u);
|
||||
CHECK_EQ(big["tok0"].get<int64_t>(), -1LL);
|
||||
CHECK_EQ(big["tok12345"].get<int64_t>(), (long long)(12345 * 7 % 100000));
|
||||
CHECK_EQ(big["tok19999"].get<int64_t>(), (long long)(19999 * 7 % 100000));
|
||||
auto it = big.begin();
|
||||
CHECK_EQ(it.key(), std::string("tok0"));
|
||||
++it;
|
||||
CHECK_EQ(it.key(), std::string("tok1"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+5
-5
@@ -21,7 +21,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
using namespace rad;
|
||||
|
||||
@@ -322,10 +322,10 @@ TEST(the_reports_statistics_are_those_of_its_rows) {
|
||||
const std::vector<float> rows = read_rows(t.path + "/rep.json.rows");
|
||||
REQUIRE_EQ(rows.size(), (size_t)(55 * 4));
|
||||
std::ifstream in(t.path + "/rep.json");
|
||||
const nlohmann::json rep = nlohmann::json::parse(in, nullptr, false);
|
||||
const Json rep = Json::parse(in, nullptr, false);
|
||||
REQUIRE(!rep.is_discarded());
|
||||
|
||||
auto expect = [&](const nlohmann::json& j, size_t r0, size_t r1) {
|
||||
auto expect = [&](const Json& j, size_t r0, size_t r1) {
|
||||
std::vector<double> kl;
|
||||
double sum = 0, nq = 0, np = 0, t1 = 0;
|
||||
for (size_t r = r0; r < r1; ++r) {
|
||||
@@ -402,7 +402,7 @@ TEST(a_sparse_reference_scores_the_coarsened_kl) {
|
||||
CHECK_EQ((int64_t)std::filesystem::file_size(t.path + "/ref/rows.f32"), (int64_t)(55 * 3 * 4));
|
||||
{
|
||||
std::ifstream in(t.path + "/ref/kld.json");
|
||||
const nlohmann::json m = nlohmann::json::parse(in, nullptr, false);
|
||||
const Json m = Json::parse(in, nullptr, false);
|
||||
CHECK_EQ(m["format"].get<std::string>(), std::string("radiance-kld-top-1"));
|
||||
CHECK_EQ(m["top"].get<int>(), kTop);
|
||||
}
|
||||
@@ -445,7 +445,7 @@ TEST(a_sparse_reference_scores_the_coarsened_kl) {
|
||||
CHECK(flips > 0);
|
||||
CHECK(sum_c > 0.5 * sum_f); /* the head carries most of the divergence */
|
||||
std::ifstream in(t.path + "/rep.json");
|
||||
const nlohmann::json rep = nlohmann::json::parse(in, nullptr, false);
|
||||
const Json rep = Json::parse(in, nullptr, false);
|
||||
CHECK_EQ(rep["ref_form"].get<std::string>(), std::string("top-64 + tail"));
|
||||
}
|
||||
|
||||
|
||||
@@ -93,10 +93,10 @@ bool write_tiny_laya(const std::string& dir, uint64_t seed) {
|
||||
}
|
||||
if (!tiny::write_safetensors(dir + "/model.safetensors", ts)) return false;
|
||||
|
||||
nlohmann::ordered_json root;
|
||||
Json root;
|
||||
root["model_type"] = "laya";
|
||||
root["architectures"] = { "LayaTypedDecisions" };
|
||||
nlohmann::ordered_json enc;
|
||||
Json enc;
|
||||
enc["architectures"] = { "ModernBertForMaskedLM" };
|
||||
enc["model_type"] = "modernbert";
|
||||
enc["hidden_size"] = E;
|
||||
@@ -124,7 +124,7 @@ bool write_tiny_laya(const std::string& dir, uint64_t seed) {
|
||||
enc["bos_token_id"] = 259;
|
||||
enc["eos_token_id"] = 260;
|
||||
enc["tie_word_embeddings"] = true;
|
||||
nlohmann::ordered_json rl;
|
||||
Json rl;
|
||||
rl["encoder"] = "answerdotai/ModernBERT-large";
|
||||
rl["head_layers"] = HL;
|
||||
rl["max_len"] = 128;
|
||||
@@ -135,7 +135,7 @@ bool write_tiny_laya(const std::string& dir, uint64_t seed) {
|
||||
rl["model_name"] = "laya-tiny";
|
||||
rl["temperature"] = { 1.3, 0.9, 1.7 };
|
||||
rl["temperature_by_options"] = { { "choice:3-5", 1.6 }, { "noul:2", 2.2 }, { "choice:11+", 0.1 } };
|
||||
nlohmann::ordered_json tc;
|
||||
Json tc;
|
||||
tc["cls_token"] = "[CLS]";
|
||||
tc["mask_token"] = "[MASK]";
|
||||
tc["pad_token"] = "[PAD]";
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
#include "rad_laya.h"
|
||||
#include "server/systemone.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@ std::string Bench::render_reply_uncached(const ojson& assistant) const {
|
||||
}
|
||||
|
||||
static std::string q(const std::string& s) {
|
||||
return nlohmann::json(s).dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
|
||||
return Json(s).dump(-1, ' ', false, Json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
std::string show(const ReplyMessage& m) {
|
||||
@@ -206,7 +206,7 @@ Verdict compare(const Bench& b, const std::string& text) {
|
||||
* new one makes every complete value JSON (chatparse.cpp, ValueOut); the decided shapes and
|
||||
* streaming checks cover the new reader there. */
|
||||
auto args_agree = [](const std::string& old_a, const std::string& new_a) {
|
||||
if (old_a == new_a || !nlohmann::json::accept(old_a)) return true;
|
||||
if (old_a == new_a || !Json::accept(old_a)) return true;
|
||||
/* One allowed difference: a leading newline the old reader stripped from a value after
|
||||
* a tag that already ends with one (Qwen's `<parameter=NAME>\n`), which the template
|
||||
* writes when the value itself starts with a newline. Every other byte must agree. */
|
||||
@@ -333,7 +333,7 @@ std::string check_stream(const ReplyParser& p, const std::string& text,
|
||||
* wrote, for any valid UTF-8 reply (the decoder sanitises every reply). */
|
||||
if (sanitize(text) == text)
|
||||
for (const ReplyCall& c : expect.calls)
|
||||
if (c.closed && !nlohmann::json::accept(c.arguments))
|
||||
if (c.closed && !Json::accept(c.arguments))
|
||||
return "a closed call's arguments are no JSON: " + q(c.arguments);
|
||||
return std::string();
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
struct RadChatFormat;
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -25,7 +25,7 @@ struct RadChatFormat;
|
||||
namespace rad {
|
||||
namespace chatdiff {
|
||||
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
/* A model: where its template is and how its vocabulary spells the tokens a template reads. */
|
||||
struct Model {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
namespace rad {
|
||||
namespace legacy {
|
||||
@@ -108,7 +108,7 @@ std::string trimmed(const std::string& v) {
|
||||
}
|
||||
|
||||
size_t read_call(const std::string& s, size_t f, const XmlCallSyntax& x,
|
||||
std::string* name, nlohmann::ordered_json* args) {
|
||||
std::string* name, Json* args) {
|
||||
const std::string fn_open(x.fn_open), fn_name_end(x.fn_name_end), fn_close(x.fn_close);
|
||||
const std::string arg_open(x.arg_open), arg_name_end(x.arg_name_end), arg_close(x.arg_close);
|
||||
|
||||
@@ -119,7 +119,7 @@ size_t read_call(const std::string& s, size_t f, const XmlCallSyntax& x,
|
||||
*name = s.substr(ns, ne - ns);
|
||||
if (name->empty() || name->find('<') != std::string::npos) return std::string::npos;
|
||||
|
||||
*args = nlohmann::ordered_json::object();
|
||||
*args = Json::object();
|
||||
size_t p = ne + fn_name_end.size();
|
||||
while (true) {
|
||||
p = skip_ws(s, p);
|
||||
@@ -215,7 +215,7 @@ size_t toolparse_lift_xml_calls(std::string& s, std::vector<ToolCall>& out) {
|
||||
if (!x) { scan = at + 1; continue; }
|
||||
|
||||
std::string name;
|
||||
nlohmann::ordered_json args;
|
||||
Json args;
|
||||
size_t end = read_call(s, f, *x, &name, &args);
|
||||
if (end == std::string::npos) { scan = at + 1; continue; }
|
||||
if (wrap != std::string::npos) {
|
||||
@@ -301,18 +301,18 @@ bool extends(const std::string& sent, const std::string& cand) {
|
||||
return cand.size() >= sent.size() && cand.compare(0, sent.size(), sent) == 0;
|
||||
}
|
||||
|
||||
std::string chunk(const nlohmann::ordered_json& delta) {
|
||||
nlohmann::ordered_json ch;
|
||||
std::string chunk(const Json& delta) {
|
||||
Json ch;
|
||||
ch["index"] = 0;
|
||||
ch["delta"] = delta;
|
||||
ch["finish_reason"] = nullptr;
|
||||
nlohmann::ordered_json o;
|
||||
Json o;
|
||||
o["id"] = "chatcmpl-legacy";
|
||||
o["object"] = "chat.completion.chunk";
|
||||
o["created"] = 0;
|
||||
o["model"] = "legacy";
|
||||
o["choices"] = nlohmann::ordered_json::array({ ch });
|
||||
return "data: " + o.dump(-1, ' ', false, nlohmann::ordered_json::error_handler_t::replace) +
|
||||
o["choices"] = Json::array({ ch });
|
||||
return "data: " + o.dump(-1, ' ', false, Json::error_handler_t::replace) +
|
||||
"\n\n";
|
||||
}
|
||||
|
||||
@@ -328,12 +328,12 @@ std::string grow(std::string& sent, const std::string& cand, bool is_final) {
|
||||
}
|
||||
|
||||
/* A delta carrying call `i`'s function fields. */
|
||||
std::string call_chunk(size_t i, const nlohmann::ordered_json& function) {
|
||||
nlohmann::ordered_json e;
|
||||
std::string call_chunk(size_t i, const Json& function) {
|
||||
Json e;
|
||||
e["index"] = (int64_t)i;
|
||||
e["function"] = function;
|
||||
nlohmann::ordered_json d;
|
||||
d["tool_calls"] = nlohmann::ordered_json::array({ e });
|
||||
Json d;
|
||||
d["tool_calls"] = Json::array({ e });
|
||||
return chunk(d);
|
||||
}
|
||||
|
||||
@@ -344,13 +344,13 @@ size_t LegacyDeltaStream::push(const std::string& full_text, bool is_final) {
|
||||
size_t out = 0;
|
||||
const std::string r = grow(reasoning_, p.reasoning, is_final);
|
||||
if (!r.empty()) {
|
||||
nlohmann::ordered_json d;
|
||||
Json d;
|
||||
d["reasoning_content"] = r;
|
||||
out += chunk(d).size();
|
||||
}
|
||||
const std::string c = grow(content_, p.content, is_final);
|
||||
if (!c.empty()) {
|
||||
nlohmann::ordered_json d;
|
||||
Json d;
|
||||
d["content"] = c;
|
||||
out += chunk(d).size();
|
||||
}
|
||||
@@ -361,14 +361,14 @@ size_t LegacyDeltaStream::push(const std::string& full_text, bool is_final) {
|
||||
names_.resize(i + 1);
|
||||
args_.resize(i + 1);
|
||||
names_[i] = tc.name;
|
||||
nlohmann::ordered_json f;
|
||||
Json f;
|
||||
f["name"] = tc.name;
|
||||
f["arguments"] = "";
|
||||
out += call_chunk(i, f).size();
|
||||
}
|
||||
const std::string a = grow(args_[i], tc.arguments, is_final);
|
||||
if (a.empty()) continue;
|
||||
nlohmann::ordered_json f;
|
||||
Json f;
|
||||
f["arguments"] = a;
|
||||
out += call_chunk(i, f).size();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/* lfm3_golden.h -- GENERATED by mklfm3golden.py from LiquidAI's modeling_lfm3.py (sha256
|
||||
* e8cd5254ea99ce6bd731b57b10908c2e8b5010ce8315341f895a38484885eeab) under transformers 5.19.0;
|
||||
* do not edit. */
|
||||
#pragma once
|
||||
#include "tiny_golden.h"
|
||||
|
||||
static_assert(kTinyGoldPositions == 130 && kTinyGoldTop == 4, "lfm3_golden.h was made for another prompt");
|
||||
static const TinyGold kLfm3Gold = {
|
||||
"lfm3", 0x7113fe64531a84e0ull,
|
||||
{ { 145, 49, 91, 297 }, { 185, 81, 84, 105 }, { 258, 177, 235, 37 }, { 129, 98, 282, 214 }, { 318, 76, 310, 259 }, { 57, 90, 235, 128 }, { 21, 312, 46, 318 }, { 108, 223, 318, 54 }, { 2, 160, 4, 139 }, { 290, 147, 219, 191 }, { 253, 10, 236, 108 }, { 48, 191, 162, 20 }, { 261, 155, 76, 110 }, { 311, 21, 104, 129 }, { 75, 76, 188, 85 }, { 258, 177, 147, 76 }, { 31, 82, 76, 291 }, { 4, 311, 234, 159 }, { 191, 261, 273, 51 }, { 277, 177, 297, 235 }, { 13, 297, 206, 82 }, { 285, 154, 281, 123 }, { 9, 76, 202, 128 }, { 82, 68, 141, 201 }, { 304, 281, 285, 167 }, { 162, 124, 76, 282 }, { 263, 145, 289, 102 }, { 104, 142, 58, 82 }, { 9, 44, 290, 236 }, { 117, 9, 185, 108 }, { 162, 177, 96, 135 }, { 104, 24, 151, 308 }, { 217, 309, 310, 85 }, { 30, 193, 226, 24 }, { 108, 45, 178, 24 }, { 76, 139, 177, 30 }, { 311, 104, 217, 142 }, { 76, 311, 82, 42 }, { 137, 30, 90, 128 }, { 129, 76, 147, 234 }, { 318, 177, 235, 208 }, { 311, 104, 188, 217 }, { 108, 264, 190, 24 }, { 168, 188, 76, 235 }, { 76, 132, 42, 304 }, { 159, 47, 123, 160 }, { 76, 20, 178, 169 }, { 204, 84, 97, 12 }, { 254, 258, 222, 178 }, { 191, 129, 92, 20 }, { 92, 314, 109, 242 }, { 30, 76, 193, 305 }, { 230, 190, 275, 27 }, { 45, 54, 108, 268 }, { 147, 311, 104, 92 }, { 95, 167, 194, 193 }, { 92, 90, 48, 311 }, { 274, 135, 75, 277 }, { 168, 4, 142, 147 }, { 290, 219, 253, 18 }, { 318, 145, 9, 98 }, { 251, 139, 30, 168 }, { 24, 90, 267, 129 }, { 191, 23, 4, 229 }, { 82, 226, 139, 132 }, { 4, 176, 191, 123 }, { 76, 30, 102, 226 }, { 242, 12, 84, 97 }, { 258, 76, 9, 95 }, { 104, 92, 282, 253 }, { 92, 14, 194, 109 }, { 193, 311, 253, 19 }, { 230, 27, 190, 58 }, { 76, 100, 310, 139 }, { 254, 110, 258, 141 }, { 311, 104, 188, 82 }, { 287, 141, 54, 108 }, { 9, 317, 34, 154 }, { 104, 21, 282, 290 }, { 272, 236, 291, 183 }, { 216, 109, 293, 182 }, { 178, 76, 20, 258 }, { 282, 104, 24, 192 }, { 139, 290, 224, 9 }, { 24, 173, 257, 124 }, { 30, 291, 182, 289 }, { 139, 177, 76, 178 }, { 145, 9, 41, 95 }, { 4, 304, 191, 111 }, { 4, 147, 95, 234 }, { 291, 159, 252, 24 }, { 105, 186, 182, 32 }, { 37, 258, 178, 76 }, { 139, 4, 35, 76 }, { 217, 305, 92, 4 }, { 290, 236, 30, 76 }, { 318, 84, 108, 182 }, { 178, 258, 9, 37 }, { 129, 255, 311, 282 }, { 76, 137, 173, 236 }, { 45, 183, 24, 311 }, { 162, 283, 141, 28 }, { 84, 27, 186, 137 }, { 290, 183, 311, 120 }, { 129, 147, 234, 305 }, { 82, 290, 18, 54 }, { 315, 90, 37, 20 }, { 30, 130, 251, 232 }, { 51, 30, 311, 277 }, { 4, 129, 159, 234 }, { 132, 173, 89, 285 }, { 129, 112, 177, 272 }, { 290, 139, 145, 236 }, { 75, 217, 24, 133 }, { 4, 147, 234, 209 }, { 177, 309, 82, 30 }, { 86, 30, 118, 130 }, { 76, 281, 188, 30 }, { 217, 73, 123, 52 }, { 76, 178, 210, 291 }, { 84, 174, 40, 12 }, { 254, 258, 178, 20 }, { 191, 253, 20, 21 }, { 234, 305, 291, 264 }, { 258, 139, 76, 178 }, { 76, 30, 188, 9 }, { 21, 171, 129, 315 }, { 139, 145, 176, 289 }, { 177, 268, 234, 151 }, { 129, 214, 76, 24 } },
|
||||
{ { -2.98817f, -3.03352f, -3.62797f, -3.67657f }, { -2.75256f, -3.24892f, -3.40979f, -3.64145f }, { -2.54806f, -3.34782f, -3.36844f, -3.38181f }, { -3.38324f, -3.40307f, -3.70412f, -3.82979f }, { -2.86077f, -3.00919f, -3.12698f, -3.48121f }, { -2.69743f, -3.2496f, -3.48024f, -3.73044f }, { -3.01339f, -3.42614f, -3.69295f, -3.80717f }, { -2.68052f, -2.87851f, -3.04736f, -3.43097f }, { -3.34975f, -3.61946f, -3.67596f, -3.77074f }, { -3.47251f, -3.50023f, -3.69769f, -3.76665f }, { -2.68497f, -2.94795f, -2.95461f, -3.4484f }, { -2.59342f, -2.5996f, -3.21076f, -3.5642f }, { -3.25056f, -3.27442f, -3.36633f, -3.40139f }, { -3.38366f, -3.54624f, -3.55954f, -3.64867f }, { -3.0729f, -3.08015f, -3.22645f, -3.43199f }, { -2.57679f, -3.28433f, -3.29774f, -3.39713f }, { -3.05558f, -3.25115f, -3.32656f, -3.68142f }, { -3.39238f, -3.64295f, -3.71494f, -3.71865f }, { -3.03832f, -3.18086f, -3.47281f, -3.6483f }, { -2.96834f, -3.19179f, -3.50139f, -3.55101f }, { -3.21461f, -3.23587f, -3.68982f, -3.75831f }, { -2.93351f, -3.31798f, -3.62313f, -3.8811f }, { -2.85722f, -3.09732f, -3.46968f, -3.61992f }, { -2.86507f, -2.87945f, -2.93571f, -3.31197f }, { -3.1465f, -3.17213f, -3.24937f, -3.39482f }, { -2.93696f, -3.30345f, -3.53538f, -3.63915f }, { -3.68243f, -3.77965f, -3.80771f, -3.83978f }, { -2.4387f, -3.12498f, -3.54755f, -3.63841f }, { -2.42097f, -2.7566f, -2.77697f, -3.53281f }, { -2.07806f, -2.84058f, -3.11873f, -3.29671f }, { -3.2196f, -3.4465f, -3.61645f, -3.81003f }, { -2.33541f, -2.87655f, -3.10338f, -3.56947f }, { -3.08123f, -3.23259f, -3.44803f, -3.49418f }, { -2.97311f, -3.07175f, -3.19934f, -3.43903f }, { -2.81218f, -3.06361f, -3.28119f, -3.40067f }, { -2.65529f, -2.74721f, -3.08692f, -3.37798f }, { -2.80632f, -2.90143f, -3.58749f, -3.61202f }, { -3.09031f, -3.36565f, -3.37148f, -3.6407f }, { -2.4681f, -2.66549f, -3.27267f, -3.46856f }, { -2.83878f, -3.08415f, -3.35113f, -3.38258f }, { -3.16516f, -3.17588f, -3.33834f, -3.35932f }, { -2.79581f, -2.82343f, -3.09567f, -3.7576f }, { -3.11805f, -3.21293f, -3.44694f, -3.77395f }, { -3.06655f, -3.27577f, -3.45764f, -3.49091f }, { -3.29646f, -3.51747f, -3.6609f, -3.66376f }, { -2.55005f, -2.91533f, -3.14713f, -3.79063f }, { -2.8974f, -2.98985f, -3.08671f, -3.53977f }, { -3.20222f, -3.29478f, -3.5184f, -3.53399f }, { -3.25485f, -3.34718f, -3.3772f, -3.48506f }, { -3.14096f, -3.16827f, -3.23319f, -3.33683f }, { -2.2682f, -2.82129f, -3.3308f, -3.78214f }, { -2.95007f, -2.98886f, -3.01542f, -3.52623f }, { -3.08567f, -3.31516f, -3.35947f, -3.46903f }, { -2.08542f, -2.54016f, -2.88981f, -3.24298f }, { -3.38579f, -3.52315f, -3.56608f, -3.72473f }, { -3.07533f, -3.75051f, -3.81663f, -3.81872f }, { -2.91524f, -2.96535f, -3.4311f, -3.66922f }, { -1.79961f, -3.44798f, -3.55039f, -3.61708f }, { -3.52474f, -3.5282f, -3.61163f, -3.66879f }, { -2.64471f, -3.26007f, -3.4517f, -3.51779f }, { -3.36997f, -3.42892f, -3.51201f, -3.62165f }, { -2.61094f, -2.75435f, -2.77842f, -3.13219f }, { -2.90599f, -3.03646f, -3.26554f, -3.52561f }, { -2.44961f, -3.25237f, -3.29373f, -3.63732f }, { -2.59546f, -3.18057f, -3.26597f, -3.49452f }, { -2.67228f, -2.74601f, -3.51893f, -3.69199f }, { -1.8724f, -3.0418f, -3.47451f, -3.56163f }, { -2.89954f, -3.21322f, -3.24527f, -3.35185f }, { -2.86991f, -3.22503f, -3.4125f, -3.43115f }, { -3.21456f, -3.3355f, -3.37872f, -3.48221f }, { -2.87787f, -3.60785f, -3.61514f, -3.71297f }, { -2.92916f, -3.05712f, -3.70969f, -3.78754f }, { -2.92854f, -2.97641f, -3.29878f, -3.81979f }, { -2.15913f, -2.78871f, -3.29692f, -3.39128f }, { -2.23098f, -2.52687f, -2.90817f, -3.51316f }, { -1.76636f, -3.34171f, -3.5421f, -3.88353f }, { -2.14676f, -2.59534f, -2.7658f, -3.36535f }, { -2.56437f, -3.49714f, -4.111f, -4.14245f }, { -2.7581f, -3.33646f, -3.45454f, -3.78166f }, { -2.78005f, -2.87024f, -3.31907f, -3.57987f }, { -3.08461f, -3.27059f, -3.49966f, -3.61359f }, { -2.43154f, -2.97309f, -3.14252f, -3.86298f }, { -3.36001f, -3.42982f, -3.68671f, -3.69937f }, { -2.74569f, -2.75238f, -3.60143f, -3.72109f }, { -3.0447f, -3.16222f, -3.21272f, -3.52635f }, { -2.44938f, -2.52214f, -3.42678f, -3.67548f }, { -3.58031f, -3.62428f, -3.69892f, -3.70914f }, { -3.35625f, -3.40272f, -3.59072f, -3.67175f }, { -2.22529f, -3.21554f, -3.23958f, -3.40542f }, { -2.91392f, -3.26685f, -3.50198f, -3.50583f }, { -2.26024f, -2.56781f, -3.26943f, -3.4575f }, { -2.54826f, -3.39482f, -3.50184f, -3.54028f }, { -2.78551f, -2.93478f, -3.37596f, -3.3985f }, { -2.62991f, -2.82764f, -3.06437f, -3.21632f }, { -2.55374f, -3.04937f, -3.26839f, -3.30087f }, { -2.75576f, -2.81508f, -3.01244f, -3.49987f }, { -2.91304f, -3.04429f, -3.32989f, -3.56549f }, { -2.64294f, -3.18141f, -3.30781f, -3.31579f }, { -3.42033f, -3.46397f, -3.70477f, -3.75033f }, { -2.5952f, -2.77707f, -3.44736f, -3.62995f }, { -3.26617f, -3.48374f, -3.73873f, -3.76906f }, { -2.70772f, -3.05709f, -3.15899f, -3.37786f }, { -3.02327f, -3.23379f, -3.31161f, -3.43362f }, { -3.35371f, -3.40861f, -3.50216f, -3.63273f }, { -3.16782f, -3.60317f, -3.78695f, -3.Line truncated
|
||||
@@ -119,7 +119,7 @@ TEST(a_dropped_request_is_reaped_once_whether_buffered_or_streamed) {
|
||||
finish_and_check_reaped(f);
|
||||
}
|
||||
|
||||
/* A server stopping under a buffered request answers it 429 "shutting down" and still reaps
|
||||
/* A server stopping under a buffered request answers it 429 "stopping" and still reaps
|
||||
* what it had submitted. */
|
||||
TEST(a_request_waiting_when_the_server_stops_is_reaped_once) {
|
||||
Fixture f;
|
||||
@@ -133,7 +133,7 @@ TEST(a_request_waiting_when_the_server_stops_is_reaped_once) {
|
||||
f.srv->stop();
|
||||
client.join();
|
||||
CHECK_EQ(r.status, 429);
|
||||
CHECK(has(r.body, "shutting down"));
|
||||
CHECK(has(r.body, "stopping"));
|
||||
finish_and_check_reaped(f);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -26,7 +26,7 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
using namespace rad;
|
||||
namespace AR = rad::arch;
|
||||
using ojson = nlohmann::ordered_json;
|
||||
using ojson = Json;
|
||||
|
||||
namespace {
|
||||
|
||||
|
||||
+176
-42
@@ -152,7 +152,7 @@ static Program stream_program(const KVGroupInfo& g, int64_t sel_pitch, bool with
|
||||
oi.op = "kv_store_streamed";
|
||||
oi.bands.resize(1);
|
||||
if (store_resolved) oi.bands[0].dom[RAD_DOMAIN_DEVICE].row = &a_resolved_row();
|
||||
else oi.bands[0].miss[RAD_DOMAIN_DEVICE] = "kv_dtype in {fp8_e4m3}, have fp8_v4";
|
||||
else oi.bands[0].miss[RAD_DOMAIN_DEVICE] = "kv_dtype in {bf16}, have i8";
|
||||
oi.base.set_i("block_size", g.block_size);
|
||||
p.ops.push_back(std::move(oi));
|
||||
}
|
||||
@@ -654,6 +654,40 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) {
|
||||
CHECK(unclaimed < 114 * MiB);
|
||||
}
|
||||
|
||||
/* The runtime keeps queue scratch resident once a kernel with a private segment has run
|
||||
* (rad_dev_resident_scratch_bytes); it is part of the hardware queues' term, the largest rank's. */
|
||||
TEST(resident_queue_scratch_is_charged_with_the_hardware_queues) {
|
||||
Config c = small_config();
|
||||
c.vram_weights_mib = 0;
|
||||
c.vram_kv_mib = 0;
|
||||
c.gpu_headroom_mib = 96;
|
||||
VramFacts f{};
|
||||
f.capacity = 32LL << 30;
|
||||
f.free = f.capacity - (512LL << 20);
|
||||
f.arena = 144LL << 20;
|
||||
f.staging = 98LL << 20;
|
||||
f.statics = 2LL << 30;
|
||||
f.experts = 200LL << 30;
|
||||
f.kv_ceiling = 100LL << 30;
|
||||
f.n_queues = 2; f.queue_bytes = 33LL << 20;
|
||||
VramBudget b0, b1;
|
||||
Config c0 = c, c1 = c;
|
||||
CHECK_OK(vram_budget_resolve(c0, { f }, &b0));
|
||||
f.queue_scratch = 160LL << 20;
|
||||
CHECK_OK(vram_budget_resolve(c1, { f }, &b1));
|
||||
CHECK_EQ(b0.queues, 66LL << 20);
|
||||
CHECK_EQ(b1.queues, (66LL << 20) + (160LL << 20));
|
||||
CHECK_EQ(b1.claimable, b0.claimable - (160LL << 20));
|
||||
/* The minimum the fleet asks of the card moves by the same bytes. */
|
||||
int64_t need0 = 0, want0 = 0, need1 = 0, want1 = 0;
|
||||
f.queue_scratch = 0;
|
||||
vram_budget_need({ f }, &need0, &want0);
|
||||
f.queue_scratch = 160LL << 20;
|
||||
vram_budget_need({ f }, &need1, &want1);
|
||||
CHECK_EQ(need1 - need0, 160LL << 20);
|
||||
CHECK_EQ(want1 - want0, 160LL << 20);
|
||||
}
|
||||
|
||||
TEST(the_smallest_card_binds_and_a_short_one_refuses_by_name) {
|
||||
Config c = small_config();
|
||||
c.vram_weights_mib = 0;
|
||||
@@ -1425,7 +1459,7 @@ TEST(a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling) {
|
||||
f.cfg.n_spec = 0;
|
||||
f.cfg.vram_kv_mib = 64;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* the streamed store's one row */
|
||||
groups[G_FULL].decl.dtype = RAD_I8; /* a streamed store's row */
|
||||
groups[G_FULL].bytes_per_block = 2048; /* as declare sets it */
|
||||
const int64_t sel_pitch = 2048; /* a synthetic indexer's topk + 1 */
|
||||
const int64_t ctx_blocks = 2 * (65536 / 16); /* 8192 blocks of 16 tokens */
|
||||
@@ -1569,7 +1603,7 @@ TEST(a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path) {
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256; /* under the ring floor, so it is raised */
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3;
|
||||
groups[G_FULL].decl.dtype = RAD_I8;
|
||||
groups[G_FULL].bytes_per_block = 2048;
|
||||
/* The resolve resolves; the store is declared with no row (both domains null). */
|
||||
const Program unresolved = stream_program(groups[G_FULL], 8, true, true, /*store_resolved=*/false);
|
||||
@@ -1597,45 +1631,6 @@ TEST(a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path) {
|
||||
|
||||
}
|
||||
|
||||
TEST(a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed) {
|
||||
/* --kv-cache-dtype fp8_v4 / k6_v4: the architecture declares the resolve and no streamed store,
|
||||
* because libr4d's streamed rows are E4M3 and bf16 and a packed cache has base-store rows only
|
||||
* (arch/common/rad_block_attn_gated_fp8.h). The group is declared to the core as plain E4M3, so
|
||||
* no dtype gate downstream can see the layout: the operator has to be told the *layout* has no
|
||||
* writer, not that the architecture cannot stream -- and the group must run the base path.
|
||||
* Before this the op was declared against a table with no row for it, which is a weightless
|
||||
* device hole: startup refused with or without --kv-resident, naming a kernel band and never the
|
||||
* flag. */
|
||||
for (const char* dtype : { "fp8_v4", "k6_v4" }) {
|
||||
Fixture f;
|
||||
f.cfg.checkpoint_slots = 0;
|
||||
f.cfg.max_ctx = 65536; /* above the 32 768-token ring floor */
|
||||
f.cfg.max_seqs = 2;
|
||||
f.cfg.kv_resident = 256; /* under the ring floor, so it is raised */
|
||||
f.cfg.kv_cache_dtype = dtype;
|
||||
std::vector<KVGroupInfo> groups = hybrid_groups();
|
||||
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* what declare gives the core, packed or not */
|
||||
groups[G_FULL].bytes_per_block = 2048;
|
||||
/* What the gated plugin emits for a packed cache: the layout-blind resolve, no store. */
|
||||
const Program packed = stream_program(groups[G_FULL], 8, true, /*with_store=*/false);
|
||||
KVStreamSetup s;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] {
|
||||
st = kvstream_configure(f.cfg, 65536, groups, packed, &s);
|
||||
});
|
||||
CHECK_OK(st); /* started, not refused */
|
||||
CHECK_EQ(s.group, -1);
|
||||
CHECK_EQ(s.asked_tokens, (int64_t)0);
|
||||
CHECK_EQ(s.stage_blocks, (int64_t)0);
|
||||
CHECK(has(log, "ignored"));
|
||||
CHECK(has(log, std::string("group 'full' has a ") + dtype + " cache"));
|
||||
CHECK(has(log, "has no writer for that layout (E4M3 and bf16 only)"));
|
||||
CHECK(!has(log, "declares no")); /* not that sentence: the arch declared it */
|
||||
CHECK(!has(log, "raised to")); /* and not the ring's */
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_resolve_declared_for_another_group_does_not_enable_streaming) {
|
||||
/* The check is per group, not per program: the resolve states the layer-bytes pitch of the
|
||||
* group it was emitted for, so one declared for a narrower full group cannot make streaming
|
||||
@@ -2177,6 +2172,17 @@ TEST(chained_hash_identity) {
|
||||
/* The same span, same parent, different position is also a different block. */
|
||||
CHECK(chain_block_hash(a0, shared.data(), 16, nullptr, 0, 32) != a1);
|
||||
|
||||
/* Token order matters both inside a packed pair and across the hash's four lanes, and the
|
||||
* length is part of the identity even where one span is the other's prefix. */
|
||||
auto swapped = a;
|
||||
std::swap(swapped[0], swapped[1]);
|
||||
CHECK(chain_block_hash(root, swapped.data(), 16, nullptr, 0, 0) != a0);
|
||||
swapped = a;
|
||||
std::swap(swapped[0], swapped[8]);
|
||||
std::swap(swapped[1], swapped[9]);
|
||||
CHECK(chain_block_hash(root, swapped.data(), 16, nullptr, 0, 0) != a0);
|
||||
CHECK(chain_block_hash(root, a.data(), 15, nullptr, 0, 0) != a0);
|
||||
|
||||
/* Multimodal blocks hash by content: identical placeholder ids, different content keys. */
|
||||
MMContentKey m1{ 0, 16, 0x1111 };
|
||||
MMContentKey m2{ 0, 16, 0x2222 };
|
||||
@@ -4753,6 +4759,110 @@ TEST(dropping_a_clean_entry_gives_its_vram_back_and_keeps_it_restorable) {
|
||||
CHECK_EQ(x.f.pc.drop_clean(), 0); /* nothing left to drop */
|
||||
}
|
||||
|
||||
/* A conversation larger than the host tier keeps its end in VRAM only, with no host copy coming,
|
||||
* so it never becomes clean. Left high in the pool by sequences that have since gone, a few such
|
||||
* blocks stop the expert loan below them for as long as the server runs. drop_clean forgets them
|
||||
* where giving them up lends far more than it loses, inside the loan it is asked about and once
|
||||
* no sequence reads them. */
|
||||
struct Stragglers {
|
||||
Fixture f;
|
||||
IdleTiers t;
|
||||
int64_t all = 0;
|
||||
/* `slots` host entries; a sequence 9 over the bottom `under` blocks. */
|
||||
int build(int slots, int under) {
|
||||
int s = f.build(/*with_linear=*/false, 0);
|
||||
if (s < 0) return s;
|
||||
IdleTiers::Config c = tier_config(slots * 1024, 1024);
|
||||
c.block_tokens = 16;
|
||||
s = t.configure(c);
|
||||
if (s < 0) return s;
|
||||
f.pc.set_tiers(&t);
|
||||
all = f.kv.total_blocks(G_FULL);
|
||||
if (under <= 0) return RAD_OK;
|
||||
s = f.kv.add_sequence(9);
|
||||
return s < 0 ? s : f.kv.ensure(9, 16 * under);
|
||||
}
|
||||
/* A sequence that comes and goes: what makes drop_clean look again. */
|
||||
void pass() {
|
||||
CHECK_OK(f.kv.add_sequence(77));
|
||||
CHECK_OK(f.kv.ensure(77, 16));
|
||||
f.kv.free_sequence(77);
|
||||
}
|
||||
};
|
||||
|
||||
TEST(stragglers_with_no_host_copy_coming_leave_vram_for_the_loan) {
|
||||
Stragglers x;
|
||||
CHECK_OK(x.build(/*slots=*/16, /*under=*/300));
|
||||
REQUIRE(x.all >= 400);
|
||||
const auto prompt = tok_run(7700, 336);
|
||||
publish(x.f, 1, prompt, 320); /* twenty blocks, at 300 and up */
|
||||
CHECK_EQ(copy_now(x.t).size(), 16u);
|
||||
CHECK_EQ(x.t.stats().held_back, 4ll);
|
||||
const int64_t goal = (x.all - 100) * 16; /* a loan down to block 100 */
|
||||
|
||||
/* Still read by its sequence: nothing goes, whatever the loan. */
|
||||
CHECK_EQ(x.f.pc.drop_clean(goal), 0);
|
||||
x.f.kv.free_sequence(9);
|
||||
x.f.kv.free_sequence(1);
|
||||
|
||||
/* No loan asked for: the copied start leaves VRAM, the four blocks past the tier stay. */
|
||||
CHECK_EQ(x.f.pc.drop_clean(), 16);
|
||||
CHECK_EQ(x.f.pc.resident(), 4ll);
|
||||
CHECK_EQ(x.f.pc.stats().evictions, 0ll);
|
||||
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 0ll); /* four blocks keep 316 from the loan */
|
||||
const int64_t pinned = x.f.kv.spare_tokens();
|
||||
CHECK(pinned <= (x.all - 316) * 16);
|
||||
/* A loan that stops above them takes nothing. */
|
||||
x.pass();
|
||||
CHECK_EQ(x.f.pc.drop_clean((x.all - 330) * 16), 0);
|
||||
CHECK_EQ(x.f.pc.resident(), 4ll);
|
||||
|
||||
/* The loan the slab is short of reaches below them: they are forgotten, the start is not. */
|
||||
x.pass();
|
||||
CHECK_EQ(x.f.pc.drop_clean(goal), 4);
|
||||
CHECK_EQ(x.f.pc.resident(), 0ll);
|
||||
CHECK_EQ(x.f.pc.size(), 16ll);
|
||||
CHECK_EQ(x.f.pc.stats().evictions, 4ll);
|
||||
CHECK_EQ(x.f.kv.pool_bytes_used(G_FULL), 0ll);
|
||||
CHECK(x.f.kv.spare_tokens() > pinned);
|
||||
CHECK_OK(x.f.kv.set_loan(x.f.kv.spare_tokens()));
|
||||
CHECK_EQ(x.f.pc.restorable_from(prompt, {}).size(), 16u);
|
||||
}
|
||||
|
||||
/* Context that fills its part of the pool is not a straggler, with or without a host copy: the
|
||||
* loan stops at its edge and takes none of it, however large the loan asked about. The end of an
|
||||
* older conversation left far above it is, and goes alone. */
|
||||
TEST(cached_context_that_fills_its_part_of_the_pool_stays_and_the_blocks_far_above_it_go) {
|
||||
Stragglers x;
|
||||
CHECK_OK(x.build(/*slots=*/8, /*under=*/300));
|
||||
REQUIRE(x.all >= 400);
|
||||
const auto older = tok_run(7800, 16 * 12 + 16);
|
||||
publish(x.f, 1, older, 16 * 12); /* twelve blocks, at 300 and up */
|
||||
CHECK_EQ(copy_now(x.t).size(), 8u); /* its start fills the tier */
|
||||
x.f.kv.free_sequence(9);
|
||||
x.f.kv.free_sequence(1);
|
||||
const auto dense = tok_run(9100, 16 * 200 + 16);
|
||||
publish(x.f, 2, dense, 16 * 200); /* two hundred blocks from the bottom */
|
||||
CHECK_EQ(copy_now(x.t).size(), 0u); /* no room, and none is made here */
|
||||
x.f.kv.free_sequence(2);
|
||||
|
||||
CHECK_EQ(x.f.pc.drop_clean(), 8); /* the older start, to the host */
|
||||
CHECK_EQ(x.f.pc.resident(), 204ll);
|
||||
CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 312ll);
|
||||
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* the edge of the dense part */
|
||||
|
||||
x.pass();
|
||||
const int64_t goal = x.all * 16; /* every block the pool has */
|
||||
CHECK_EQ(x.f.pc.drop_clean(goal), 4);
|
||||
CHECK_EQ(x.f.pc.resident(), 200ll);
|
||||
CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 200ll);
|
||||
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* nothing above the dense part now */
|
||||
x.pass();
|
||||
CHECK_EQ(x.f.pc.drop_clean(goal), 0); /* which keeps every block */
|
||||
CHECK_EQ(x.f.pc.resident(), 200ll);
|
||||
CHECK_EQ(x.f.pc.lookup(dense, {}).n_attn_tokens, 16 * 200);
|
||||
}
|
||||
|
||||
TEST(a_recomputed_shared_prefix_keeps_its_original_host_copy_and_snapshot) {
|
||||
/* A short request shares less than one checkpoint with an off-device conversation, so it
|
||||
* recomputes instead of adopting that prefix. Its different prefill shape can round the KV
|
||||
@@ -6123,6 +6233,30 @@ TEST(a_window_shift_and_a_seeded_window_mark_the_whole_row) {
|
||||
* speculation a linear group's sequence owns two physical slots (copy k of s at s + k *
|
||||
* n_seq_states) and both are named; a conv group keeps one copy. The index row the kernels read
|
||||
* names copy 0 three times, then copy 1. */
|
||||
/* Giving idle slots back leaves a sequence that holds tokens its slot: ensure() grabs one only as
|
||||
* the sequence grows, so its next step would have no recurrent state. */
|
||||
TEST(giving_idle_state_slots_back_leaves_a_sequence_holding_tokens_its_slot) {
|
||||
Fixture f;
|
||||
REQUIRE_EQ(f.build_groups(hybrid_conv_groups()), RAD_OK);
|
||||
CHECK_OK(f.kv.add_sequence(1));
|
||||
CHECK_OK(f.kv.ensure(1, 16));
|
||||
CHECK_OK(f.kv.add_sequence(2));
|
||||
CHECK_OK(f.kv.ensure(2, 16));
|
||||
const int32_t s1 = f.kv.state_slot(1, G_GDN);
|
||||
REQUIRE(s1 >= 0);
|
||||
/* Preempted, then handed a slot it holds at zero tokens: that one goes back. */
|
||||
CHECK_OK(f.kv.preempt(2));
|
||||
CHECK_EQ(f.kv.state_slot(2, G_GDN), -1);
|
||||
const int64_t free_before = f.kv.free_states(G_GDN);
|
||||
CHECK_EQ(f.kv.release_idle_states(), 0);
|
||||
CHECK_EQ(f.kv.state_slot(1, G_GDN), s1);
|
||||
CHECK_EQ(f.kv.free_states(G_GDN), free_before);
|
||||
/* A slot held is not free, however many times the slots are counted. */
|
||||
for (int i = 0; i < 3; ++i) (void)f.kv.release_idle_states();
|
||||
CHECK_OK(f.kv.ensure(2, 16));
|
||||
CHECK(f.kv.state_slot(2, G_GDN) != s1);
|
||||
}
|
||||
|
||||
TEST(a_handed_out_state_slot_is_named_for_clearing_once_per_copy) {
|
||||
Fixture f;
|
||||
f.cfg.n_spec = 2;
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
#include "rad_test.h"
|
||||
#include "server/mica.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
"""mkglimmergolden.py OUT.h -- goldens for tests/mm_test.cpp's Muse Glimmer cases, every number
|
||||
from the reference itself: transformers' own MuseGlimmerImageProcessor and
|
||||
MuseGlimmerVideoProcessor (transformers 5.23.0.dev0, torch 2.15.0+cpu, torchvision 0.29.2+cpu),
|
||||
run on synthetic splitmix frames, plus their sample_frames and replace_video_token.
|
||||
|
||||
The resize filter is the real reference path, not a reimplementation: the processor is a
|
||||
TorchvisionBackend whose resize calls tvF.resize on the uint8 pixels with
|
||||
InterpolationMode.LANCZOS and antialias=True on CPU, which torch serves with its native uint8
|
||||
kernel (int16 fixed-point weights, horizontal pass first, an 8-bit rounded intermediate). The
|
||||
test's C++ side has to reproduce that byte for byte.
|
||||
|
||||
* the resize table: each picture's grid straight out of image_grid_thw;
|
||||
* two pictures' patch planes: the processor's f32 pixel_values cast to bfloat16, the patch rows
|
||||
in the reference's own raster order (patch row by row), each row (temporal, channel, y, x) as
|
||||
the reference lays it out, and the FNV-1a of the whole plane;
|
||||
* a twelve-frame clip: the grid, the plane's FNV-1a, the per-group stamps (each
|
||||
group's first frame's time, the reference's replace_video_token) and the sampled indices
|
||||
(the reference's sample_frames, torch.linspace(...).long());
|
||||
* a sampling table: the indices' count, first entry and FNV-1a.
|
||||
|
||||
The pixel at (frame f, row y, column x, channel c) is mm_test's pix(f, y, x, c) splitmix hash,
|
||||
and pix's frame argument is the SOURCE frame's index, so the test's decoded frames match the
|
||||
processor's sampled ones exactly.
|
||||
"""
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import transformers
|
||||
import torchvision
|
||||
from PIL import Image
|
||||
from transformers.models.muse_glimmer.image_processing_muse_glimmer import MuseGlimmerImageProcessor
|
||||
from transformers.models.muse_glimmer.video_processing_muse_glimmer import MuseGlimmerVideoProcessor
|
||||
from transformers.video_utils import VideoMetadata
|
||||
|
||||
PATCH, TEMPORAL, MERGE = 14, 2, 2
|
||||
MAX_IMAGE_TOKENS = 4096
|
||||
MAX_VIDEO_FRAME_TOKENS = 144
|
||||
|
||||
U = np.uint64
|
||||
|
||||
|
||||
def picture(f, h, w):
|
||||
"""[h, w, 3] uint8, mm_test's pix(f, y, x, c)."""
|
||||
y = np.arange(h, dtype=np.uint64)[:, None]
|
||||
x = np.arange(w, dtype=np.uint64)[None, :]
|
||||
c = np.arange(3, dtype=np.uint64)[None, None, :]
|
||||
z = (U(f) * U(0x9E3779B97F4A7C15) + y[:, :, None] * U(0xBF58476D1CE4E5B9) +
|
||||
x[:, :, None] * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345))
|
||||
z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9)
|
||||
z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB)
|
||||
return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8)
|
||||
|
||||
|
||||
def fnv16(bits):
|
||||
"""FNV-1a over each element's bytes, least significant first (mm_test's fnv)."""
|
||||
h = 0xcbf29ce484222325
|
||||
for v in np.asarray(bits, dtype=np.uint16).ravel(order="C"):
|
||||
for b in (0, 1):
|
||||
h = ((h ^ U((int(v) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1)
|
||||
return int(h)
|
||||
|
||||
|
||||
def bf16(a):
|
||||
t = torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32))
|
||||
return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16)
|
||||
|
||||
|
||||
def image_processor():
|
||||
return MuseGlimmerImageProcessor(
|
||||
patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE,
|
||||
max_image_tokens=MAX_IMAGE_TOKENS, image_mean=[0.5] * 3, image_std=[0.5] * 3)
|
||||
|
||||
|
||||
def video_processor():
|
||||
return MuseGlimmerVideoProcessor(
|
||||
patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE,
|
||||
max_video_frame_tokens=MAX_VIDEO_FRAME_TOKENS, num_frames=96, fps=2.0,
|
||||
image_mean=[0.5] * 3, image_std=[0.5] * 3)
|
||||
|
||||
|
||||
def process_image(h, w):
|
||||
pil = Image.fromarray(picture(0, h, w), mode="RGB")
|
||||
out = image_processor()(images=[pil], return_tensors="pt")
|
||||
rows = out["pixel_values"] # [gh*gw, dim] f32, raster order
|
||||
if rows.dim() == 3:
|
||||
rows = rows[0]
|
||||
gt, gh, gw = (int(v) for v in out["image_grid_thw"][0])
|
||||
assert gt == 1
|
||||
return bf16(rows.numpy()), gh, gw # raster order, as the reference emits it
|
||||
|
||||
|
||||
def main(out):
|
||||
print("transformers", transformers.__version__, "torch", torch.__version__,
|
||||
"torchvision", torchvision.__version__)
|
||||
|
||||
resize_cases = [
|
||||
(256, 320), (100, 100), (84, 84), (10, 10), (28, 28), (27, 27), (1, 1),
|
||||
(8000, 8000), (2000, 50), (50, 2000), (300, 500), (640, 427), (1920, 1080),
|
||||
(3, 5000), (500, 3), (1234, 5678), (7, 9), (112, 224), (224, 112),
|
||||
]
|
||||
L = [f"/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers "
|
||||
f"{transformers.__version__} (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, "
|
||||
f"torch {torch.__version__}, torchvision {torchvision.__version__}); do not edit. */",
|
||||
"#pragma once", "#include <cstdint>", "",
|
||||
"static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;",
|
||||
"static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;",
|
||||
"static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;",
|
||||
"static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;",
|
||||
"static const int32_t kGoldMuseVidSep = 200087;",
|
||||
"",
|
||||
"/* A h x w picture's resize target, in pixels. */",
|
||||
"struct GoldMuseResize { int64_t h, w, oh, ow; };",
|
||||
"static const GoldMuseResize kGoldMuseResize[] = {"]
|
||||
|
||||
print(" resize table + image patch planes")
|
||||
image_cases = []
|
||||
for h, w in resize_cases:
|
||||
pil = Image.fromarray(picture(0, h, w), mode="RGB")
|
||||
outi = image_processor()(images=[pil], return_tensors="pt")
|
||||
_, gh, gw = (int(v) for v in outi["image_grid_thw"][0])
|
||||
L.append(f" {{ {h}, {w}, {gh * PATCH}, {gw * PATCH} }},")
|
||||
L.append("};")
|
||||
L.append("")
|
||||
|
||||
for h, w in [(100, 100), (256, 320)]:
|
||||
px, gh, gw = process_image(h, w)
|
||||
image_cases.append((h, w, gh, gw, px))
|
||||
L += ["/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the "
|
||||
"FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row "
|
||||
"(temporal, channel, y, x) as the reference lays it out. */",
|
||||
"struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };",
|
||||
"static const GoldMuseImage kGoldMuseImage[] = {"]
|
||||
for h, w, gh, gw, px in image_cases:
|
||||
head = ", ".join("0x%04x" % int(v) for v in px[0][:16])
|
||||
L.append(f" {{ {h}, {w}, {gh}, {gw}, {{{head}}}, {fnv16(px)}ull }},")
|
||||
L.append("};")
|
||||
L.append("")
|
||||
|
||||
print(" video patch plane + stamps")
|
||||
# A 37-frame source at 6 fps: the reference's sample_frames takes 12 frames at 2 fps, the
|
||||
# indices linspace(0, 36, 12).long(); six temporal groups, one stamp per group, each the
|
||||
# group's first frame's time.
|
||||
total, native_fps, fps = 37, 6.0, 2.0
|
||||
n = min(int(total * fps / native_fps), 96, total)
|
||||
n = max(TEMPORAL, (n // TEMPORAL) * TEMPORAL)
|
||||
n = min(n, total)
|
||||
idx = torch.linspace(0, total - 1, n).long().tolist()
|
||||
print(" sampled", n, "frames:", idx)
|
||||
src = np.stack([picture(f, 64, 96) for f in idx]) # [T, H, W, 3]
|
||||
md = VideoMetadata(total_num_frames=total, fps=native_fps, width=96, height=64,
|
||||
duration=total / native_fps, video_backend="nil", frames_indices=idx)
|
||||
outv = video_processor()(videos=[torch.from_numpy(src)], return_tensors="pt",
|
||||
video_metadata=[md], do_sample_frames=False)
|
||||
pv = outv["pixel_values_videos"] # [gt*gh*gw, dim] f32
|
||||
gt, gh, gw = (int(v) for v in outv["video_grid_thw"][0])
|
||||
print(" grid", gt, gh, gw)
|
||||
plane = np.empty((gt, gh * gw, pv.shape[1]), dtype=np.uint16)
|
||||
for g in range(gt):
|
||||
plane[g] = bf16(pv[(g * gh * gw):(g + 1) * gh * gw].numpy())
|
||||
flat = plane.reshape(-1)
|
||||
|
||||
# The stamps: metadata.timestamps[::temporal][:grid_t], each formatted "Time: {t:.1f}s".
|
||||
timestamps = [i / native_fps for i in idx]
|
||||
stamps = [f"Time: {t:.1f}s" for t in timestamps[::TEMPORAL][:gt]]
|
||||
while len(stamps) < gt:
|
||||
stamps.append(stamps[-1] if stamps else "Time: 0.0s")
|
||||
print(" stamps:", stamps)
|
||||
|
||||
L += ["/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid "
|
||||
"(groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's "
|
||||
"stamp. */",
|
||||
f"static const int64_t kGoldMuseVideoTotal = {total};",
|
||||
f"static const double kGoldMuseVideoFps = {native_fps};",
|
||||
f"static const int32_t kGoldMuseVideoN = {n};",
|
||||
"static const int64_t kGoldMuseVideoIndex[] = {",
|
||||
" " + ", ".join(str(i) for i in idx) + "};",
|
||||
f"static const int32_t kGoldMuseVideoGrid[] = {{ {gt}, {gh}, {gw} }};",
|
||||
"static const uint16_t kGoldMuseVideoHead[16] = {",
|
||||
" " + ", ".join("0x%04x" % int(v) for v in flat[:16]) + "};",
|
||||
f"static const uint64_t kGoldMuseVideoFnv = {fnv16(flat)}ull;",
|
||||
"static const char* const kGoldMuseVideoStamps[] = {",
|
||||
"".join(f' "{s}",\n' for s in stamps) + "};",
|
||||
""]
|
||||
while L[-1] == "":
|
||||
L.pop()
|
||||
|
||||
print(" sampling table")
|
||||
sample_cases = [(37, 6.0), (6, 2.0), (96, 24.0), (1, 2.0), (2, 2.0), (5, 12.0),
|
||||
(600, 30.0), (1000, 24.0), (13, 7.0), (4, 1.0)]
|
||||
L += ["/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the "
|
||||
"FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */",
|
||||
"struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };",
|
||||
"static const GoldMuseSample kGoldMuseSample[] = {"]
|
||||
proc = video_processor()
|
||||
for total, fps in sample_cases:
|
||||
md = VideoMetadata(total_num_frames=total, fps=fps, width=96, height=64,
|
||||
duration=total / fps, video_backend="nil", frames_indices=None)
|
||||
got = proc.sample_frames(md, temporal_patch_size=TEMPORAL, num_frames=96, fps=2.0).tolist()
|
||||
h = 0xcbf29ce484222325
|
||||
for i in got:
|
||||
for b in range(8):
|
||||
h = ((h ^ U((int(i) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1)
|
||||
L.append(f" {{ {total}, {fps}, {len(got)}, {h}ull }},")
|
||||
print(f" {total} @ {fps}: {got[:6]}{'...' if len(got) > 6 else ''} ({len(got)})")
|
||||
L.append("};")
|
||||
with open(out, "w") as f:
|
||||
f.write("\n".join(L) + "\n")
|
||||
print("wrote", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1])
|
||||
@@ -0,0 +1,73 @@
|
||||
"""mklfm3golden.py CKPTDIR CODEDIR OUT.h -- the LFM3 golden for tests/engine_e2e_test.cpp.
|
||||
|
||||
transformers has no LFM3 model class; the reference is the modelling code LiquidAI ships with the
|
||||
checkpoint (configuration_lfm3.py, modeling_lfm3.py, lfm3_conv.py; Apache-2.0). CODEDIR is a
|
||||
directory holding those files, for example a download of LiquidAI/LFM3-1.7B: its classes are
|
||||
built over the tiny random checkpoint tests/tiny_model.h writes and run in float32, as
|
||||
mktinygolden.py does for the other families. Nothing of CODEDIR's weights is read.
|
||||
|
||||
CKPTDIR holds the tiny checkpoints: run `RAD_E2E_KEEP=1 build/tests/engine_e2e_test` and pass the
|
||||
directory it prints. The header records the FNV-1a hash of lfm3/model.safetensors (the test
|
||||
refuses a golden made from other weights), the sha256 of the modelling file, and at every
|
||||
position of mktinygolden.py's prompt the four most likely next tokens with their
|
||||
log-probabilities."""
|
||||
import hashlib, json, os, re, sys
|
||||
import torch
|
||||
from safetensors.torch import load_file
|
||||
import transformers
|
||||
from transformers.dynamic_module_utils import get_class_from_dynamic_module
|
||||
|
||||
ckpt_dir, code_dir, out = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
torch.manual_seed(0)
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
PROMPT = json.loads(re.search(r"kTinyGoldPrompt\[\] = (\".*\");",
|
||||
open(os.path.join(here, "tiny_golden.h")).read()).group(1))
|
||||
ids = list(PROMPT.encode())
|
||||
TOP = 4
|
||||
|
||||
|
||||
def fnv(path):
|
||||
h = 0xcbf29ce484222325
|
||||
for b in open(path, "rb").read():
|
||||
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
|
||||
return h
|
||||
|
||||
|
||||
d = os.path.join(ckpt_dir, "lfm3")
|
||||
cfg = json.load(open(os.path.join(d, "config.json")))
|
||||
for k in ("architectures", "model_type"):
|
||||
cfg.pop(k, None)
|
||||
# The release's pad and bos ids lie outside the tiny vocabulary.
|
||||
cfg["pad_token_id"] = None
|
||||
cfg["bos_token_id"] = None
|
||||
Config = get_class_from_dynamic_module("configuration_lfm3.Lfm3Config", code_dir)
|
||||
Model = get_class_from_dynamic_module("modeling_lfm3.Lfm3ForCausalLM", code_dir)
|
||||
model = Model(Config(**cfg))
|
||||
sd = {k: v.float() for k, v in load_file(os.path.join(d, "model.safetensors")).items()}
|
||||
missing, unexpected = model.load_state_dict(sd, strict=False)
|
||||
# A tied head is the embedding; anything else missing is a naming error.
|
||||
missing = [k for k in missing if k != "lm_head.weight"]
|
||||
if missing or unexpected:
|
||||
raise SystemExit(f"lfm3: missing {missing}, unexpected {unexpected}")
|
||||
model = model.float().eval()
|
||||
with torch.no_grad():
|
||||
lp = torch.log_softmax(model(torch.tensor([ids])).logits[0].float(), dim=-1)
|
||||
v, i = torch.topk(lp, TOP, dim=-1)
|
||||
code_sha = hashlib.sha256(open(os.path.join(code_dir, "modeling_lfm3.py"), "rb").read()).hexdigest()
|
||||
|
||||
|
||||
def rows(t, fmt):
|
||||
return ", ".join("{ " + ", ".join(fmt(x) for x in row) + " }" for row in t)
|
||||
|
||||
|
||||
L = ["/* lfm3_golden.h -- GENERATED by mklfm3golden.py from LiquidAI's modeling_lfm3.py (sha256",
|
||||
f" * {code_sha}) under transformers {transformers.__version__};",
|
||||
" * do not edit. */", "#pragma once", '#include "tiny_golden.h"', "",
|
||||
f"static_assert(kTinyGoldPositions == {len(ids)} && kTinyGoldTop == {TOP}, "
|
||||
'"lfm3_golden.h was made for another prompt");',
|
||||
"static const TinyGold kLfm3Gold = {",
|
||||
f" \"lfm3\", 0x{fnv(os.path.join(d, 'model.safetensors')):016x}ull,",
|
||||
" { " + rows(i, lambda x: str(int(x))) + " },",
|
||||
" { " + rows(v, lambda x: f"{float(x):.6g}f") + " } };"]
|
||||
open(out, "w").write("\n".join(L) + "\n")
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "mm/processor.h"
|
||||
#include "gemma4_golden.h"
|
||||
#include "gemma4u_golden.h"
|
||||
#include "glimmer_golden.h"
|
||||
#include "glm5_golden.h"
|
||||
#include "radio_golden.h"
|
||||
#include "imaging_golden.h"
|
||||
@@ -1126,6 +1127,222 @@ TEST(glm5_reads_its_processor_from_the_container) {
|
||||
CHECK(why.find("patch_expand_factor") != std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== Muse Glimmer's processor
|
||||
*
|
||||
* glimmer_golden.h: transformers' own MuseGlimmerImageProcessor and MuseGlimmerVideoProcessor
|
||||
* (mkglimmergolden.py ran them on synthetic splitmix frames), which the processor mirrors: the
|
||||
* token-capped aspect-nearest resize, torchvision's antialiased Lanczos on the uint8 pixels, the
|
||||
* (temporal, channel, y, x) patch rows in radiance's merge-block order, and the sampled frames'
|
||||
* per-group "Time: T s" stamps. */
|
||||
namespace {
|
||||
|
||||
VisionConfig muse_cfg() {
|
||||
VisionConfig c;
|
||||
c.family = Family::MuseGlimmer;
|
||||
c.patch = kGoldMusePatch;
|
||||
c.temporal = kGoldMuseTemporal;
|
||||
c.merge = kGoldMuseMerge;
|
||||
c.max_image_tokens = 4096;
|
||||
c.max_frame_rows = 144;
|
||||
c.fps = 2.0;
|
||||
c.min_frames = c.temporal;
|
||||
c.max_frames = 96;
|
||||
const int64_t f2 = (int64_t)c.factor() * c.factor();
|
||||
c.image_min_pixels = c.video_min_pixels = f2;
|
||||
c.image_max_pixels = (int64_t)c.max_image_tokens * f2;
|
||||
c.video_max_pixels = (int64_t)c.max_frame_rows * f2;
|
||||
c.tok_image = kGoldMuseTokImage;
|
||||
c.tok_video = kGoldMuseTokVideo;
|
||||
c.tok_start = kGoldMuseTokStart;
|
||||
c.tok_end = kGoldMuseTokEnd;
|
||||
c.tok_video_start = kGoldMuseVidStart;
|
||||
c.tok_video_end = kGoldMuseVidEnd;
|
||||
c.tok_video_sep = kGoldMuseVidSep;
|
||||
c.max_patches = 16384;
|
||||
return c;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(muse_sizes_are_the_references) {
|
||||
for (const GoldMuseResize& g : kGoldMuseResize) {
|
||||
int64_t oh = 0, ow = 0;
|
||||
std::string why;
|
||||
CHECK_OK(muse_size(g.h, g.w, kGoldMusePatch * kGoldMuseMerge, 4096, &oh, &ow, &why));
|
||||
if (oh != g.oh || ow != g.ow)
|
||||
std::fprintf(stderr, " %lld x %lld: %lld x %lld, reference %lld x %lld\n",
|
||||
(long long)g.h, (long long)g.w, (long long)oh, (long long)ow,
|
||||
(long long)g.oh, (long long)g.ow);
|
||||
CHECK_EQ(oh, g.oh);
|
||||
CHECK_EQ(ow, g.ow);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(muse_pictures_patchify_as_the_reference_does) {
|
||||
Processor p;
|
||||
int rc = p.init(muse_cfg(), [](const std::string&) { return std::vector<int32_t>{ 1 }; });
|
||||
REQUIRE(rc >= 0);
|
||||
for (const GoldMuseImage& g : kGoldMuseImage) {
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.image_from(frame(0, (int)g.h, (int)g.w), &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
if (it->grid_h != g.gh || it->grid_w != g.gw)
|
||||
std::fprintf(stderr, " %lld x %lld: grid %d x %d, reference %d x %d\n",
|
||||
(long long)g.h, (long long)g.w, it->grid_h, it->grid_w, g.gh, g.gw);
|
||||
CHECK_EQ(it->grid_t, 1);
|
||||
CHECK_EQ(it->grid_h, g.gh);
|
||||
CHECK_EQ(it->grid_w, g.gw);
|
||||
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]);
|
||||
CHECK_EQ(fnv(it->pixels), g.fnv);
|
||||
|
||||
/* <|image_start|>, one <|patch|> per merged row, <|image_end|>: the reference's
|
||||
* replace_image_token. */
|
||||
const int32_t rows = (g.gh / 2) * (g.gw / 2);
|
||||
REQUIRE_EQ(it->expand.size(), (size_t)rows + 2);
|
||||
CHECK_EQ(it->expand.front(), kGoldMuseTokStart);
|
||||
CHECK_EQ(it->expand.back(), kGoldMuseTokEnd);
|
||||
for (int32_t i = 1; i <= rows; ++i) CHECK_EQ(it->expand[(size_t)i], kGoldMuseTokImage);
|
||||
REQUIRE_EQ(it->seg_at.size(), (size_t)1);
|
||||
CHECK_EQ(it->seg_at[0], 1);
|
||||
CHECK_EQ(it->n_rows(), (int64_t)rows);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(muse_reads_its_processor_from_the_container) {
|
||||
const char* keys[] = { "vision_config.model_type", "vision_config.patch_size",
|
||||
"vision_config.patch_temporal", "vision_config.merge_size",
|
||||
"image_token_id", "video_token_id",
|
||||
"processor.image_processor.max_image_tokens",
|
||||
"processor.video_processor.max_video_frame_tokens",
|
||||
"processor.video_processor.num_frames",
|
||||
"processor.video_processor.fps",
|
||||
"processor.image_mean", "processor.image_std" };
|
||||
const char* vals[] = { "muse_glimmer_vision", "14", "2", "2", "200092", "200091",
|
||||
"4096", "144", "96", "2", "", "" };
|
||||
RadModelMeta m{};
|
||||
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
|
||||
m.kv_key = keys;
|
||||
m.kv_val = vals;
|
||||
VisionConfig c;
|
||||
std::string why;
|
||||
CHECK_OK(c.from_meta(m, &why));
|
||||
CHECK(c.family == Family::MuseGlimmer);
|
||||
CHECK_EQ(c.patch, 14);
|
||||
CHECK_EQ(c.temporal, 2);
|
||||
CHECK_EQ(c.merge, 2);
|
||||
CHECK_EQ(c.patch_dim(), (int64_t)1176);
|
||||
CHECK_EQ(c.factor(), 28);
|
||||
CHECK_EQ(c.max_image_tokens, 4096);
|
||||
CHECK_EQ(c.max_frame_rows, 144);
|
||||
CHECK_EQ(c.max_frames, 96);
|
||||
CHECK_EQ(c.fps, 2.0);
|
||||
CHECK_EQ(c.tok_image, 200092);
|
||||
CHECK_EQ(c.tok_video, 200091);
|
||||
/* The markers the container does not number stay unresolved for the vocabulary. */
|
||||
CHECK_EQ(c.tok_start, -1);
|
||||
CHECK_EQ(c.tok_video_sep, -1);
|
||||
/* The shipped mean and deviation, over the reference class's IMAGENET_STANDARD defaults. */
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
CHECK_EQ(c.mean[i], 0.5f);
|
||||
CHECK_EQ(c.stdv[i], 0.5f);
|
||||
}
|
||||
/* Numbered markers and stated mean/std win. */
|
||||
vals[4] = "200090";
|
||||
vals[10] = "0.48 0.46 0.41";
|
||||
vals[11] = "0.27 0.26 0.28";
|
||||
vals[11] = "0.27 0.26 0.28";
|
||||
VisionConfig d;
|
||||
CHECK_OK(d.from_meta(m, &why));
|
||||
CHECK_EQ(d.tok_image, 200090);
|
||||
CHECK_EQ(d.mean[0], 0.48f);
|
||||
CHECK_EQ(d.stdv[2], 0.28f);
|
||||
/* No tower geometry: refused, not defaulted. */
|
||||
vals[1] = "0";
|
||||
VisionConfig e;
|
||||
CHECK_EQ(e.from_meta(m, &why), RAD_E_NOTFOUND);
|
||||
/* A marker the container does not number that the vocabulary cannot spell: refused at init,
|
||||
* not on the first picture. */
|
||||
VisionConfig unnumbered = muse_cfg();
|
||||
unnumbered.tok_start = -1;
|
||||
Processor p;
|
||||
CHECK_EQ(p.init(unnumbered, [](const std::string&) { return std::vector<int32_t>{ 1 }; },
|
||||
[](const std::string&) { return -1; }),
|
||||
RAD_E_NOTFOUND);
|
||||
/* A frame budget above one pass: refused. */
|
||||
VisionConfig big = muse_cfg();
|
||||
big.max_patches = 100;
|
||||
Processor q;
|
||||
CHECK_EQ(q.init(big, [](const std::string&) { return std::vector<int32_t>{ 1 }; }),
|
||||
RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(muse_frames_are_sampled_as_the_reference_does) {
|
||||
for (const GoldMuseSample& g : kGoldMuseSample) {
|
||||
VideoInfo info{};
|
||||
info.n_frames = g.total;
|
||||
info.fps = g.fps;
|
||||
const std::vector<int64_t> idx = sample_frames_muse(info, 2.0, kGoldMuseTemporal, 96);
|
||||
if ((int32_t)idx.size() != g.n)
|
||||
std::fprintf(stderr, " %lld frames at %g fps: %zu indices, reference %d\n",
|
||||
(long long)g.total, g.fps, idx.size(), g.n);
|
||||
CHECK_EQ((int32_t)idx.size(), g.n);
|
||||
CHECK_EQ(fnv(idx), g.fnv);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_muse_clip_patchifies_and_is_stamped_as_the_reference_does) {
|
||||
std::vector<std::string> stamps;
|
||||
Processor p;
|
||||
REQUIRE(p.init(muse_cfg(), [&](const std::string& s) {
|
||||
stamps.push_back(s);
|
||||
return std::vector<int32_t>((size_t)s.size(), 7); /* a token per byte */
|
||||
}) >= 0);
|
||||
Video v;
|
||||
v.info.n_frames = kGoldMuseVideoTotal;
|
||||
v.info.fps = kGoldMuseVideoFps;
|
||||
v.info.w = 96;
|
||||
v.info.h = 64;
|
||||
v.index.assign(kGoldMuseVideoIndex,
|
||||
kGoldMuseVideoIndex + sizeof(kGoldMuseVideoIndex) / sizeof(kGoldMuseVideoIndex[0]));
|
||||
for (int64_t i : v.index) v.frames.push_back(frame((int)i, 64, 96));
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.video_from(v, &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
CHECK_EQ(it->grid_t, kGoldMuseVideoGrid[0]);
|
||||
CHECK_EQ(it->grid_h, kGoldMuseVideoGrid[1]);
|
||||
CHECK_EQ(it->grid_w, kGoldMuseVideoGrid[2]);
|
||||
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], kGoldMuseVideoHead[i]);
|
||||
CHECK_EQ(fnv(it->pixels), kGoldMuseVideoFnv);
|
||||
|
||||
/* One stamp per group, the group's first frame's time. */
|
||||
const size_t n_stamps = sizeof(kGoldMuseVideoStamps) / sizeof(kGoldMuseVideoStamps[0]);
|
||||
REQUIRE_EQ(stamps.size(), n_stamps);
|
||||
for (size_t i = 0; i < n_stamps; ++i) CHECK_EQ(stamps[i], std::string(kGoldMuseVideoStamps[i]));
|
||||
|
||||
/* <|vid_start|>, then per group: the stamp's tokens, one <|video|> per merged row, and a
|
||||
* <|vid_frame_separator|> between the groups and <|vid_end|> after the last. */
|
||||
const int32_t rows = (kGoldMuseVideoGrid[1] / 2) * (kGoldMuseVideoGrid[2] / 2);
|
||||
size_t at = 0;
|
||||
REQUIRE_EQ(it->seg_at.size(), (size_t)kGoldMuseVideoGrid[0]);
|
||||
CHECK_EQ(it->expand[at], kGoldMuseVidStart);
|
||||
++at;
|
||||
for (int32_t g = 0; g < kGoldMuseVideoGrid[0]; ++g) {
|
||||
at += stamps[(size_t)g].size();
|
||||
REQUIRE(at < it->expand.size());
|
||||
CHECK_EQ(it->seg_at[(size_t)g], (int32_t)at);
|
||||
for (int32_t r = 0; r < rows; ++r) CHECK_EQ(it->expand[at + (size_t)r], kGoldMuseTokVideo);
|
||||
at += (size_t)rows;
|
||||
CHECK_EQ(it->expand[at], g + 1 == kGoldMuseVideoGrid[0] ? kGoldMuseVidEnd
|
||||
: kGoldMuseVidSep);
|
||||
++at;
|
||||
}
|
||||
CHECK_EQ(at, it->expand.size());
|
||||
}
|
||||
|
||||
/* ================================================================== Pillow's arithmetic
|
||||
*
|
||||
* imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow,
|
||||
@@ -1163,6 +1380,30 @@ TEST(the_lanczos_resize_is_pillows_bit_for_bit) {
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_threaded_lanczos_resize_is_the_serial_one) {
|
||||
/* imaging.cpp splits a tall resize's rows across threads (its goldens above are 23 rows
|
||||
* tall and take the serial path, bar the 50-row upscale's vertical pass). At an unchanged
|
||||
* height each output row depends only on its own input row, so resizing row bands small
|
||||
* enough to stay serial and stacking them is an oracle for the threaded whole. */
|
||||
const FrameRGBA src = rgba_frame(3, 100, 61);
|
||||
FrameRGBA whole;
|
||||
resize_lanczos_rgba(src, 23, 100, &whole);
|
||||
REQUIRE_EQ(whole.rgba.size(), (size_t)23 * 100 * 4);
|
||||
std::vector<uint8_t> stacked;
|
||||
for (int y0 = 0; y0 < 100; y0 += 25) {
|
||||
FrameRGBA band;
|
||||
band.w = 61;
|
||||
band.h = 25;
|
||||
band.rgba.assign(src.rgba.begin() + (size_t)y0 * 61 * 4,
|
||||
src.rgba.begin() + (size_t)(y0 + 25) * 61 * 4);
|
||||
FrameRGBA out;
|
||||
resize_lanczos_rgba(band, 23, 25, &out);
|
||||
REQUIRE_EQ(out.rgba.size(), (size_t)23 * 25 * 4);
|
||||
stacked.insert(stacked.end(), out.rgba.begin(), out.rgba.end());
|
||||
}
|
||||
CHECK(stacked == whole.rgba);
|
||||
}
|
||||
|
||||
TEST(the_white_composite_is_pillows_paste) {
|
||||
const FrameRGBA src = rgba_frame(0, kGoldLanczosSrcH, kGoldLanczosSrcW);
|
||||
Frame out;
|
||||
@@ -1292,6 +1533,15 @@ TEST(a_picture_over_the_pixel_limit_is_refused_from_its_header) {
|
||||
why.clear();
|
||||
CHECK_EQ(decode_image_rgba(png.data(), png.size(), 64 * 48 - 1, &fa, &why), RAD_E_INVAL);
|
||||
CHECK(has(why, "3071-pixel limit"));
|
||||
/* A JPEG's size is read from its start of frame the same way. */
|
||||
std::vector<uint8_t> jpg;
|
||||
REQUIRE_EQ(encode_image(px.data(), 64, 48, 3, "jpeg", 90, &jpg, &why), RAD_OK);
|
||||
CHECK_EQ(decode_image(jpg.data(), jpg.size(), 64 * 48, &f, &why), RAD_OK);
|
||||
CHECK_EQ(f.w, 64);
|
||||
CHECK_EQ(f.h, 48);
|
||||
why.clear();
|
||||
CHECK_EQ(decode_image(jpg.data(), jpg.size(), 64 * 48 - 1, &f, &why), RAD_E_INVAL);
|
||||
CHECK(has(why, "64x48, over the server's 3071-pixel limit"));
|
||||
|
||||
/* 81 million pixels claimed in 66 bytes: refused on the header, so nothing is allocated for
|
||||
* them. A side past what FFmpeg can hold (60000) is refused by its own size check. */
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
/* tests/mtp_block_test.cpp -- Block Verification of a linear MTP draft chain (--draft-verify block,
|
||||
* abi/rad_mtp_block.h, arXiv 2403.10444), checked against its own law.
|
||||
*
|
||||
* The property: whatever the head's law Q and the chain's length g, the tokens a verify step commits
|
||||
* are a prefix of a sample of the TARGET's autoregressive law, and the step commits at least as many
|
||||
* tokens as the token-wise (maximal coupling) verify of the same drafts. Tests:
|
||||
*
|
||||
* exact enumeration every draft of a toy chain, the rule written out densely and independently
|
||||
* of the header, the law of the first three committed tokens summed in
|
||||
* closed form: equals the target's product law to 1e-12 (g = 1..4, three
|
||||
* head qualities); and the header's h_i equal the dense ones
|
||||
* chi-square the real shared code (the propose row, rad_mtp_couple_verify_row with the
|
||||
* block marking, the core's token-comparison walk) over 3e5 seeds: the joint
|
||||
* law of the first three tokens and the first token's marginal
|
||||
* negative control the same code with h_i nudged (a wrong acceptance rule) is NOT exact and
|
||||
* the same statistic sees it
|
||||
* dominance the mean committed tokens per step of block verification is at least the
|
||||
* token-wise verify's on the same drafts
|
||||
* inert rows a stale or non-consecutive state leaves the ordinary picks alone; rows
|
||||
* after the first of a block write nothing; a greedy row is untouched
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_mtp_block.h"
|
||||
#include "../plugin/spechub/spechub.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int V = 12; /* larger than the head's top 8: the target has mass off Q's support */
|
||||
|
||||
uint64_t H(uint64_t a) { return rad_mtp_rrs_mix(a); }
|
||||
|
||||
struct Law {
|
||||
int32_t pid[V]; float pval[V]; int pn = 0;
|
||||
double p[V];
|
||||
int32_t qid[8]; float qval[8];
|
||||
};
|
||||
|
||||
Law law_at(uint64_t prefix_hash, double head_noise) {
|
||||
Law L;
|
||||
float lt[V], lq[V];
|
||||
for (int i = 0; i < V; ++i) {
|
||||
lt[i] = (float)((H(prefix_hash * 131 + (uint64_t)i * 977 + 1) >> 40) % 3000) / 1000.0f - 1.5f;
|
||||
const float nz = (float)((H(prefix_hash * 257 + (uint64_t)i * 331 + 7) >> 40) % 3000) / 1000.0f - 1.5f;
|
||||
lq[i] = 0.75f * lt[i] + (float)head_noise * nz;
|
||||
}
|
||||
const uint64_t h = H(prefix_hash + 99);
|
||||
const int drop = h % 3 == 0 ? (int)((h >> 8) % V) : -1;
|
||||
double z = 0;
|
||||
for (int i = 0; i < V; ++i) { L.p[i] = 0; if (i != drop) { L.pid[L.pn] = i; L.pval[L.pn++] = lt[i]; } }
|
||||
for (int j = 0; j < L.pn; ++j) z += std::exp((double)L.pval[j]);
|
||||
for (int j = 0; j < L.pn; ++j) L.p[L.pid[j]] = std::exp((double)L.pval[j]) / z;
|
||||
int ord[V];
|
||||
for (int i = 0; i < V; ++i) ord[i] = i;
|
||||
std::stable_sort(ord, ord + V, [&](int a, int b) { return lq[a] > lq[b]; });
|
||||
for (int i = 0; i < 8; ++i) { L.qid[i] = ord[i]; L.qval[i] = lq[ord[i]]; }
|
||||
return L;
|
||||
}
|
||||
|
||||
uint64_t child_hash(uint64_t ph, int tok) { return H(ph * 1000003ull + (uint64_t)tok + 17); }
|
||||
|
||||
int sample_law(const Law& L, uint64_t seed, uint64_t pos, uint64_t key) {
|
||||
double u = rad_spechub_uniform(seed, pos, key);
|
||||
int last = 0;
|
||||
for (int i = 0; i < V; ++i) {
|
||||
if (L.p[i] <= 0) continue;
|
||||
last = i;
|
||||
u -= L.p[i];
|
||||
if (u < 0) return i;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
RadMtpCoupleDraw make_draw(uint64_t seed, uint64_t base) {
|
||||
RadMtpCoupleDraw d{};
|
||||
d.seed = seed; d.base = base; d.seq = 1; d.card = 0; d.mode = 1;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ a drafted chain */
|
||||
|
||||
struct Chain {
|
||||
int g = 0;
|
||||
int tok[8] = {}; /* X_1 .. X_g */
|
||||
uint64_t hash[9] = {}; /* the prefix hash after X^i, i = 0 .. g */
|
||||
RadMtpCoupleState st[8] = {}; /* row i's coupled state (round i + 1) */
|
||||
};
|
||||
|
||||
/* The chain drafted by the real propose row, round by round, over the head's law at the chain's own
|
||||
* prefix (x ~ Q at the draw's (seed, base, KEY_DRAFT + round)). */
|
||||
void draft_chain(Chain* t, uint64_t seed, uint64_t base, int g, double noise, uint64_t h0 = 1) {
|
||||
uint64_t h = h0;
|
||||
t->g = g;
|
||||
t->hash[0] = h;
|
||||
for (int r = 1; r <= g; ++r) {
|
||||
const Law law = law_at(h, noise);
|
||||
int32_t idx[8];
|
||||
float val[8];
|
||||
for (int i = 0; i < 8; ++i) { idx[i] = law.qid[i]; val[i] = law.qval[i]; }
|
||||
const RadMtpCoupleDraw draw = make_draw(seed, base);
|
||||
const int32_t card = 0;
|
||||
RadMtpCoupleProposeCall c{};
|
||||
c.idx = idx; c.val = val; c.card = &card;
|
||||
c.draw = reinterpret_cast<const uint32_t*>(&draw);
|
||||
RadMtpCoupleState rows[8] = {};
|
||||
c.state = reinterpret_cast<uint32_t*>(rows);
|
||||
c.M = 1; c.vocab = 1000;
|
||||
c.ld_idx = 8; c.ld_val = 8; c.ld_draw = RAD_MTP_COUPLE_DRAW_WORDS;
|
||||
c.st_round = RAD_MTP_COUPLE_STATE_WORDS; c.st_row = 0;
|
||||
c.round = r;
|
||||
rad_mtp_couple_propose_row(c, 0);
|
||||
t->st[r - 1] = rows[r - 1];
|
||||
t->tok[r - 1] = idx[0];
|
||||
h = child_hash(h, idx[0]);
|
||||
t->hash[r] = h;
|
||||
}
|
||||
}
|
||||
|
||||
enum Mode { TOKEN, BLOCK, CONTROL };
|
||||
|
||||
/* The control's wrong rule: every inner h_i raised by a quarter (clipped at 1). */
|
||||
void nudge(RadBlockPlan* pl) {
|
||||
for (int i = 1; i < pl->g; ++i) pl->h[i] = std::min(1.0, pl->h[i] * 1.25);
|
||||
}
|
||||
|
||||
/* The sampler's planes of one step: g + 1 rows, the last the bonus row with no state. */
|
||||
struct Planes {
|
||||
int32_t ids[9 * V];
|
||||
float val[9 * V];
|
||||
uint32_t params[9 * 24];
|
||||
RadMtpCoupleState st[9];
|
||||
int32_t tok[9];
|
||||
};
|
||||
|
||||
RadMtpCoupleVerifyCall call_of(Planes* pl, int g) {
|
||||
RadMtpCoupleVerifyCall c{};
|
||||
c.idx = pl->ids; c.val = pl->val; c.params = pl->params;
|
||||
c.state = reinterpret_cast<const uint32_t*>(pl->st);
|
||||
c.token = pl->tok;
|
||||
c.M = g + 1; c.n_cand = V; c.vocab = 1000;
|
||||
c.ld[0] = V; c.ld[1] = V; c.ld[2] = 24; c.ld[3] = RAD_MTP_COUPLE_STATE_WORDS; c.ld[4] = 1;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* One verify step over the chain, walked as the core does: the verify op's rows over the sampler's
|
||||
* planes, then the rule "a row's token that equals its draft accepts it". Writes the committed
|
||||
* tokens, extended to `want` by exact draws from the target. Returns the committed count before the
|
||||
* extension. */
|
||||
int step(const Chain& t, uint64_t seed, uint64_t n_out, double noise, Mode mode, int want, int* out) {
|
||||
const int g = t.g;
|
||||
Planes pl;
|
||||
std::memset(&pl, 0, sizeof pl);
|
||||
for (int i = 0; i <= g; ++i) {
|
||||
const Law L = law_at(t.hash[i], noise);
|
||||
for (int j = 0; j < V; ++j) {
|
||||
pl.ids[i * V + j] = j < L.pn ? L.pid[j] : -1;
|
||||
pl.val[i * V + j] = j < L.pn ? L.pval[j] : 0.0f;
|
||||
}
|
||||
RadSampleParams* p = reinterpret_cast<RadSampleParams*>(pl.params + i * 24);
|
||||
p->seed = seed;
|
||||
p->pos = n_out + (uint64_t)i;
|
||||
pl.tok[i] = sample_law(L, seed, n_out + (uint64_t)i, 0); /* the ordinary pick */
|
||||
if (i < g) {
|
||||
pl.st[i] = t.st[i];
|
||||
pl.st[i].pos = rad_mtp_couple_verify_pos(n_out, i + 1);
|
||||
pl.st[i].blk = mode == TOKEN ? 0 : g;
|
||||
}
|
||||
}
|
||||
const RadMtpCoupleVerifyCall c = call_of(&pl, g);
|
||||
if (mode == CONTROL) {
|
||||
RadBlockRow rows[8];
|
||||
RadBlockStat stat[8];
|
||||
for (int i = 0; i < g; ++i) {
|
||||
rows[i] = RadBlockRow{ pl.ids + i * V, pl.val + i * V, V, 0, 0.0f };
|
||||
rad_mtp_block_scan(&rows[i], 1000);
|
||||
CHECK(rad_mtp_block_stat(rows[i], pl.st[i], &stat[i]));
|
||||
}
|
||||
RadBlockPlan bp;
|
||||
rad_mtp_block_plan(pl.st, stat, g, &bp);
|
||||
nudge(&bp);
|
||||
const int tau = rad_mtp_block_tau(bp, seed, n_out);
|
||||
int32_t y = -1;
|
||||
if (tau < g)
|
||||
CHECK(rad_mtp_block_resid_draw(rows[tau], pl.st[tau], stat[tau], bp.p[tau],
|
||||
rad_spechub_uniform(seed, n_out + (uint64_t)tau,
|
||||
RAD_SAMPLE_KEY_RESID), &y));
|
||||
rad_mtp_block_write(c, 0, pl.st, tau, g, y);
|
||||
} else {
|
||||
for (int i = 0; i < g; ++i) rad_mtp_couple_verify_row(c, i);
|
||||
}
|
||||
int len = 0;
|
||||
for (int i = 0; i <= g; ++i) {
|
||||
out[len++] = pl.tok[i];
|
||||
if (i == g || pl.tok[i] != t.tok[i]) break;
|
||||
}
|
||||
const int committed = len;
|
||||
uint64_t ph = t.hash[0];
|
||||
for (int i = 0; i < len; ++i) ph = child_hash(ph, out[i]);
|
||||
while (len < want) {
|
||||
const Law L = law_at(ph, noise);
|
||||
const int y = sample_law(L, seed ^ 0xabcdef1234ull, n_out + (uint64_t)len, 1);
|
||||
out[len++] = y;
|
||||
ph = child_hash(ph, y);
|
||||
}
|
||||
return committed;
|
||||
}
|
||||
|
||||
double zscore(const std::vector<double>& counts, const std::vector<double>& expect, double n) {
|
||||
double chi = 0, pool_c = 0, pool_e = 0;
|
||||
int cells = 0;
|
||||
for (size_t i = 0; i < counts.size(); ++i) {
|
||||
const double e = expect[i] * n;
|
||||
if (e < 20) { pool_c += counts[i]; pool_e += e; continue; }
|
||||
chi += (counts[i] - e) * (counts[i] - e) / e;
|
||||
++cells;
|
||||
}
|
||||
if (pool_e >= 5) { chi += (pool_c - pool_e) * (pool_c - pool_e) / pool_e; ++cells; }
|
||||
const double df = cells - 1;
|
||||
return (chi - df) / std::sqrt(2.0 * df);
|
||||
}
|
||||
|
||||
struct Result { double z, first_z, mean_len, var_len; };
|
||||
|
||||
Result run(Mode mode, int g, int trials, double noise) {
|
||||
std::vector<double> cnt3((size_t)V * V * V, 0), cnt1((size_t)V, 0);
|
||||
double sum = 0, sq = 0;
|
||||
for (int s = 0; s < trials; ++s) {
|
||||
const uint64_t seed = 0x1234567ull + (uint64_t)s * 7919ull;
|
||||
Chain t;
|
||||
draft_chain(&t, seed, 0, g, noise);
|
||||
int out[16];
|
||||
const int len = step(t, seed, 0, noise, mode, 3, out);
|
||||
++cnt1[(size_t)out[0]];
|
||||
++cnt3[(size_t)((out[0] * V + out[1]) * V + out[2])];
|
||||
sum += len; sq += (double)len * len;
|
||||
}
|
||||
std::vector<double> e1((size_t)V, 0), e3((size_t)V * V * V, 0);
|
||||
const Law l0 = law_at(1, noise);
|
||||
for (int a = 0; a < V; ++a) {
|
||||
e1[(size_t)a] = l0.p[a];
|
||||
const Law l1 = law_at(child_hash(1, a), noise);
|
||||
for (int b = 0; b < V; ++b) {
|
||||
const Law l2 = law_at(child_hash(child_hash(1, a), b), noise);
|
||||
for (int c = 0; c < V; ++c) e3[(size_t)((a * V + b) * V + c)] = l0.p[a] * l1.p[b] * l2.p[c];
|
||||
}
|
||||
}
|
||||
const double mean = sum / trials;
|
||||
return { zscore(cnt3, e3, trials), zscore(cnt1, e1, trials), mean, sq / trials - mean * mean };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the exact law */
|
||||
|
||||
/* The rule written densely, independent of the header: P_i, Q_{i+1} as length-V vectors. */
|
||||
struct Dense { double P[V], Q[V]; };
|
||||
|
||||
void dense_h(const std::vector<Dense>& d, const int* x, int g, double* h, double* p) {
|
||||
p[0] = 1;
|
||||
for (int i = 1; i <= g; ++i)
|
||||
p[i] = std::min(1.0, p[i - 1] * d[(size_t)i - 1].P[x[i - 1]] / d[(size_t)i - 1].Q[x[i - 1]]);
|
||||
h[g] = p[g];
|
||||
for (int i = 0; i < g; ++i) {
|
||||
double S = 0;
|
||||
for (int v = 0; v < V; ++v) S += std::max(p[i] * d[(size_t)i].P[v] - d[(size_t)i].Q[v], 0.0);
|
||||
h[i] = S / (S + 1.0 - p[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/* The exact law of the first three committed tokens (the step, then the target's own draws), by
|
||||
* summing over every draft, tau and Y. Also compares the header's weights with the dense ones. */
|
||||
double exact_error(int gmax, double noise, double* h_err, int adaptive = 0) {
|
||||
std::map<std::vector<int>, double> emit; /* committed sequence -> probability */
|
||||
*h_err = 0;
|
||||
std::vector<int> x((size_t)gmax);
|
||||
std::vector<uint64_t> hash((size_t)gmax + 1);
|
||||
hash[0] = 1;
|
||||
std::function<void(int, double)> rec = [&](int i, double pr) {
|
||||
/* adaptive: the draft stage stops after X_i when a function of the drafted prefix says so
|
||||
* (what confidence pruning does); the block's length g is then draft-dependent. */
|
||||
const bool stop_here = adaptive && i >= 1 && i < gmax && (H(hash[(size_t)i] + 5) % 3) < (uint64_t)adaptive;
|
||||
const int g = i;
|
||||
if (i < gmax && !stop_here) {
|
||||
const Law L = law_at(hash[(size_t)i], noise);
|
||||
RadMtpCoupleState s{};
|
||||
CHECK(rad_mtp_couple_build_q(L.qid, L.qval, 1000, &s));
|
||||
for (int k = 0; k < s.count; ++k) {
|
||||
x[(size_t)i] = s.ids[k];
|
||||
hash[(size_t)i + 1] = child_hash(hash[(size_t)i], s.ids[k]);
|
||||
rec(i + 1, pr * s.q[k]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
std::vector<Dense> d((size_t)g);
|
||||
std::vector<Law> laws;
|
||||
std::vector<RadMtpCoupleState> st((size_t)g);
|
||||
std::vector<RadBlockRow> rows((size_t)g);
|
||||
for (int j = 0; j < g; ++j) laws.push_back(law_at(hash[(size_t)j], noise));
|
||||
for (int j = 0; j < g; ++j) {
|
||||
CHECK(rad_mtp_couple_build_q(laws[(size_t)j].qid, laws[(size_t)j].qval, 1000, &st[(size_t)j]));
|
||||
st[(size_t)j].x = x[(size_t)j];
|
||||
for (int v = 0; v < V; ++v) { d[(size_t)j].P[v] = laws[(size_t)j].p[v]; d[(size_t)j].Q[v] = 0; }
|
||||
for (int k = 0; k < st[(size_t)j].count; ++k)
|
||||
d[(size_t)j].Q[st[(size_t)j].ids[k]] = st[(size_t)j].q[k];
|
||||
rows[(size_t)j] = RadBlockRow{ laws[(size_t)j].pid, laws[(size_t)j].pval,
|
||||
laws[(size_t)j].pn, 0, 0.0f };
|
||||
rad_mtp_block_scan(&rows[(size_t)j], 1000);
|
||||
}
|
||||
double h[9], p[9];
|
||||
dense_h(d, x.data(), g, h, p);
|
||||
RadBlockStat stat[8];
|
||||
for (int j = 0; j < g; ++j) CHECK(rad_mtp_block_stat(rows[(size_t)j], st[(size_t)j], &stat[j]));
|
||||
RadBlockPlan bp;
|
||||
rad_mtp_block_plan(st.data(), stat, g, &bp);
|
||||
for (int j = 0; j <= g; ++j) *h_err = std::max(*h_err, std::fabs(bp.h[j] - h[j]));
|
||||
double stop = 1; /* probability that no larger i has accepted */
|
||||
for (int tau = g; tau >= 0; --tau) {
|
||||
const double pt = stop * h[tau];
|
||||
stop *= 1 - h[tau];
|
||||
if (pt <= 0) continue;
|
||||
std::vector<int> e(x.begin(), x.begin() + tau);
|
||||
if (tau == g) {
|
||||
const Law Lg = law_at(hash[(size_t)g], noise);
|
||||
for (int z = 0; z < V; ++z) {
|
||||
if (Lg.p[z] <= 0) continue;
|
||||
std::vector<int> e2 = e; e2.push_back(z);
|
||||
emit[e2] += pr * pt * Lg.p[z];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
double S = 0, r[V];
|
||||
for (int v = 0; v < V; ++v) {
|
||||
r[v] = std::max(p[tau] * d[(size_t)tau].P[v] - d[(size_t)tau].Q[v], 0.0);
|
||||
S += r[v];
|
||||
}
|
||||
if (!(S > 0)) { for (int v = 0; v < V; ++v) r[v] = d[(size_t)tau].P[v]; S = 1; }
|
||||
for (int v = 0; v < V; ++v) {
|
||||
if (r[v] <= 0) continue;
|
||||
std::vector<int> e2 = e; e2.push_back(v);
|
||||
emit[e2] += pr * pt * r[v] / S;
|
||||
}
|
||||
}
|
||||
};
|
||||
rec(0, 1.0);
|
||||
/* extend every committed sequence to three tokens with the target's conditionals */
|
||||
std::vector<double> got((size_t)V * V * V, 0);
|
||||
for (const auto& kv : emit) {
|
||||
const std::vector<int>& e = kv.first;
|
||||
std::function<void(std::vector<int>&, uint64_t, double)> ext =
|
||||
[&](std::vector<int>& w, uint64_t h, double pr) {
|
||||
if (w.size() == 3) { got[(size_t)((w[0] * V + w[1]) * V + w[2])] += pr; return; }
|
||||
const Law L = law_at(h, noise);
|
||||
for (int v = 0; v < V; ++v) {
|
||||
if (L.p[v] <= 0) continue;
|
||||
w.push_back(v);
|
||||
ext(w, child_hash(h, v), pr * L.p[v]);
|
||||
w.pop_back();
|
||||
}
|
||||
};
|
||||
std::vector<int> w(e.begin(), e.begin() + (long)std::min<size_t>(e.size(), 3));
|
||||
uint64_t h = 1;
|
||||
for (int t : w) h = child_hash(h, t);
|
||||
ext(w, h, kv.second);
|
||||
}
|
||||
const Law l0 = law_at(1, noise);
|
||||
double err = 0, tot = 0;
|
||||
for (int a = 0; a < V; ++a) {
|
||||
const Law l1 = law_at(child_hash(1, a), noise);
|
||||
for (int b = 0; b < V; ++b) {
|
||||
const Law l2 = law_at(child_hash(child_hash(1, a), b), noise);
|
||||
for (int c = 0; c < V; ++c) {
|
||||
const size_t i = (size_t)((a * V + b) * V + c);
|
||||
const double want = l0.p[a] * l1.p[b] * l2.p[c];
|
||||
err = std::max(err, std::fabs(got[i] - want));
|
||||
tot += got[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_NEAR(tot, 1.0, 1e-12);
|
||||
return err;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(block_verification_emits_exactly_the_target_law_by_enumeration) {
|
||||
for (double noise : { 0.3, 1.0, 3.0 })
|
||||
for (int g = 1; g <= 4; ++g) {
|
||||
double h_err = 0;
|
||||
const double err = exact_error(g, noise, &h_err);
|
||||
std::printf(" g=%d noise=%.1f max |law - target| = %.2e max |h - h_dense| = %.2e\n", g,
|
||||
noise, err, h_err);
|
||||
CHECK(err < 1e-12);
|
||||
CHECK(h_err < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
/* A draft stage that stops by a function of the drafted prefix (confidence pruning, dynamic rows)
|
||||
* makes the block length draft-dependent. Printed, and checked to be exact. */
|
||||
TEST(block_verification_with_a_draft_dependent_chain_length_is_exact) {
|
||||
for (double noise : { 0.3, 1.0, 3.0 })
|
||||
for (int adaptive : { 1, 2 }) {
|
||||
double h_err = 0;
|
||||
const double err = exact_error(4, noise, &h_err, adaptive);
|
||||
std::printf(" adaptive stop (%d/3 of prefixes) noise=%.1f: max |law - target| = %.2e\n",
|
||||
adaptive, noise, err);
|
||||
CHECK(err < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_chain_verify_with_block_marking_commits_the_target_law) {
|
||||
const Result a = run(BLOCK, 3, 300000, 1.0);
|
||||
std::printf(" g=3 noise 1.0: z=%.2f first=%.2f mean tokens %.4f\n", a.z, a.first_z, a.mean_len);
|
||||
CHECK(a.z < 4.5); CHECK(a.first_z < 4.5);
|
||||
const Result b = run(BLOCK, 3, 150000, 3.0);
|
||||
std::printf(" g=3 noise 3.0: z=%.2f first=%.2f mean tokens %.4f\n", b.z, b.first_z, b.mean_len);
|
||||
CHECK(b.z < 4.5); CHECK(b.first_z < 4.5);
|
||||
const Result c = run(BLOCK, 5, 150000, 0.3);
|
||||
std::printf(" g=5 noise 0.3: z=%.2f first=%.2f mean tokens %.4f\n", c.z, c.first_z, c.mean_len);
|
||||
CHECK(c.z < 4.5); CHECK(c.first_z < 4.5);
|
||||
}
|
||||
|
||||
/* The same statistic sees a wrong acceptance rule. */
|
||||
TEST(a_block_rule_with_nudged_weights_is_not_exact) {
|
||||
const Result r = run(CONTROL, 3, 300000, 1.0);
|
||||
std::printf(" nudged h (known wrong): z=%.1f first=%.1f\n", r.z, r.first_z);
|
||||
CHECK(r.z > 8.0);
|
||||
}
|
||||
|
||||
/* Block verification commits at least as many tokens as the token-wise verify of the same drafts,
|
||||
* and both are exact (the token-wise one is the existing coupling). */
|
||||
TEST(block_verification_commits_at_least_as_many_tokens_as_token_wise) {
|
||||
for (double noise : { 0.3, 1.0, 3.0 }) {
|
||||
const int trials = 200000;
|
||||
const Result tk = run(TOKEN, 3, trials, noise);
|
||||
const Result bl = run(BLOCK, 3, trials, noise);
|
||||
const double se = std::sqrt((tk.var_len + bl.var_len) / trials);
|
||||
std::printf(" noise %.1f: token-wise %.4f tokens/step (z=%.2f), block %.4f (z=%.2f), +%.4f\n",
|
||||
noise, tk.mean_len, tk.z, bl.mean_len, bl.z, bl.mean_len - tk.mean_len);
|
||||
CHECK(tk.z < 4.5);
|
||||
CHECK(bl.z < 4.5);
|
||||
CHECK(bl.mean_len > tk.mean_len - 4 * se);
|
||||
}
|
||||
}
|
||||
|
||||
/* A state that is not the one the sampler would have bound, or a block that is not consecutive,
|
||||
* leaves the ordinary picks alone; only the first row of a block writes. */
|
||||
TEST(block_rows_that_do_not_bind_keep_their_ordinary_picks) {
|
||||
const int g = 3;
|
||||
Chain t;
|
||||
draft_chain(&t, 77, 0, g, 1.0);
|
||||
auto build = [&](Planes* pl, uint64_t seed) {
|
||||
std::memset(pl, 0, sizeof *pl);
|
||||
for (int i = 0; i <= g; ++i) {
|
||||
const Law L = law_at(t.hash[i], 1.0);
|
||||
for (int j = 0; j < V; ++j) {
|
||||
pl->ids[i * V + j] = j < L.pn ? L.pid[j] : -1;
|
||||
pl->val[i * V + j] = j < L.pn ? L.pval[j] : 0.0f;
|
||||
}
|
||||
RadSampleParams* p = reinterpret_cast<RadSampleParams*>(pl->params + i * 24);
|
||||
p->seed = seed; p->pos = 10 + (uint64_t)i;
|
||||
pl->tok[i] = 1000 + i; /* a marker no verify could write */
|
||||
if (i < g) { pl->st[i] = t.st[i]; pl->st[i].pos = 10 + (uint64_t)i; pl->st[i].blk = g; }
|
||||
}
|
||||
};
|
||||
auto verify = [&](Planes* pl, int row0, int rows) {
|
||||
const RadMtpCoupleVerifyCall c = call_of(pl, g);
|
||||
for (int i = row0; i < row0 + rows; ++i) rad_mtp_couple_verify_row(c, i);
|
||||
};
|
||||
auto untouched = [&](const Planes& pl) {
|
||||
for (int i = 0; i <= g; ++i) if (pl.tok[i] != 1000 + i) return false;
|
||||
return true;
|
||||
};
|
||||
Planes pl;
|
||||
build(&pl, 77);
|
||||
verify(&pl, 0, g);
|
||||
CHECK(!untouched(pl)); /* the block binds and writes */
|
||||
build(&pl, 77);
|
||||
verify(&pl, 1, g - 1);
|
||||
CHECK(untouched(pl)); /* rows after the first write nothing */
|
||||
build(&pl, 77);
|
||||
pl.st[1].round = 3;
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* a row of the wrong round ends the block's coupling */
|
||||
build(&pl, 77);
|
||||
pl.st[2].draw.seq = 9;
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* another request's state */
|
||||
build(&pl, 77);
|
||||
pl.st[2].pos += 1;
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* a stale position */
|
||||
build(&pl, 77);
|
||||
reinterpret_cast<RadSampleParams*>(pl.params + 2 * 24)->flags = RAD_SP_GREEDY;
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* a greedy row */
|
||||
build(&pl, 78);
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* a seed the state was not drawn under */
|
||||
build(&pl, 77);
|
||||
pl.st[1].nkids = 2;
|
||||
verify(&pl, 0, g);
|
||||
CHECK(untouched(pl)); /* a tree node is not a chain row */
|
||||
}
|
||||
|
||||
|
||||
/* The residual draw over a plane WIDER than the workgroup's 128 lanes (several slots per lane, ids
|
||||
* on and off Q's support, holes): the lane-ordered walk of rad_mtp_block_resid_draw must still
|
||||
* sample max(p P - Q, 0) normalised. Chi-square over the plane's ids against the dense closed
|
||||
* form; the negative control draws from a residual with Q's mass halved (a wrong law) and the same
|
||||
* statistic must see it. Also the tree sum: stat over the wide plane equals a plain ascending sum
|
||||
* to rounding (the tree is a different order, not a different value). */
|
||||
TEST(the_lane_ordered_residual_draw_over_a_wide_plane_is_exact) {
|
||||
const int N = 700;
|
||||
std::vector<int32_t> ids((size_t)N);
|
||||
std::vector<float> val((size_t)N);
|
||||
for (int j = 0; j < N; ++j) {
|
||||
ids[(size_t)j] = j % 11 == 5 ? -1 : 2 * j + 3;
|
||||
val[(size_t)j] = j % 11 == 5 ? -INFINITY : (float)((H((uint64_t)j * 7919 + 5) >> 40) % 4000) / 1000.0f - 2.0f;
|
||||
}
|
||||
int32_t qid[8]; float qv[8];
|
||||
for (int k = 0; k < 8; ++k) { qid[k] = 2 * (k * 83 + 1) + 3; qv[k] = 1.5f - 0.3f * (float)k; }
|
||||
RadMtpCoupleState st{};
|
||||
CHECK(rad_mtp_couple_build_q(qid, qv, 100000, &st));
|
||||
st.x = st.ids[1];
|
||||
RadBlockRow r{ ids.data(), val.data(), N, 0, 0.0f };
|
||||
rad_mtp_block_scan(&r, 100000);
|
||||
RadBlockStat t;
|
||||
CHECK(rad_mtp_block_stat(r, st, &t));
|
||||
double ref = 0, top = r.top;
|
||||
for (int j = 0; j < N; ++j) if (ids[(size_t)j] >= 0) ref += std::exp((double)val[(size_t)j] - top);
|
||||
CHECK(std::fabs(t.sum - ref) <= 1e-12 * ref);
|
||||
const double p = 0.8;
|
||||
std::map<int32_t, double> want;
|
||||
double tot = 0;
|
||||
for (int j = 0; j < N; ++j) {
|
||||
if (ids[(size_t)j] < 0) continue;
|
||||
const double P = std::exp((double)val[(size_t)j] - top) / ref;
|
||||
double Q = 0;
|
||||
for (int k = 0; k < st.count; ++k) if (st.ids[k] == ids[(size_t)j]) Q = st.q[k];
|
||||
const double m = std::max(p * P - Q, 0.0);
|
||||
want[ids[(size_t)j]] = m; tot += m;
|
||||
}
|
||||
const int D = 400000;
|
||||
std::map<int32_t, double> got, bad;
|
||||
for (int d = 0; d < D; ++d) {
|
||||
const double u = (double)(H((uint64_t)d * 2654435761ull + 11) >> 11) / 9007199254740992.0;
|
||||
int32_t y = -1;
|
||||
CHECK(rad_mtp_block_resid_draw(r, st, t, p, u, &y));
|
||||
got[y] += 1;
|
||||
/* control: the walk with the uniform skewed (a wrong law) */
|
||||
int32_t yb = -1;
|
||||
CHECK(rad_mtp_block_resid_draw(r, st, t, p, u * u, &yb));
|
||||
bad[yb] += 1;
|
||||
}
|
||||
auto chi = [&](std::map<int32_t, double>& c) {
|
||||
double x = 0, pc = 0, pe = 0; int cells = 0;
|
||||
for (auto& kv : want) {
|
||||
const double e = D * kv.second / tot, o = c.count(kv.first) ? c[kv.first] : 0;
|
||||
if (e < 5) { pc += o; pe += e; continue; }
|
||||
x += (o - e) * (o - e) / e; ++cells;
|
||||
}
|
||||
if (pe >= 5) { x += (pc - pe) * (pc - pe) / pe; ++cells; }
|
||||
return (x - (cells - 1)) / std::sqrt(2.0 * (cells - 1)); /* z of chi-square */
|
||||
};
|
||||
for (auto& kv : got) CHECK(want.count(kv.first) && want[kv.first] > 0);
|
||||
const double z = chi(got), zb = chi(bad);
|
||||
fprintf(stderr, " wide plane residual draw: z=%.2f negative control z=%.1f\n", z, zb);
|
||||
CHECK(std::fabs(z) < 4.5);
|
||||
CHECK(zb > 20);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -9,12 +9,12 @@
|
||||
#include "server/nemotron35.h"
|
||||
#include "server/oai.h"
|
||||
#include "text/tokenizer.h"
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
#include <dlfcn.h>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using json = rad::Json;
|
||||
|
||||
namespace {
|
||||
std::vector<const char*> host_libraries() {
|
||||
@@ -1418,7 +1418,8 @@ TEST(nemotron35_reranker_parser_matches_the_native_pair_template_and_context_bou
|
||||
rad::server::OaiLimits lim;
|
||||
lim.max_ctx = 32768;
|
||||
lim.allow_image = true;
|
||||
for (const auto& c : golden("nemotron35_rerank.json")["http"]) {
|
||||
const json golden_http = golden("nemotron35_rerank.json")["http"];
|
||||
for (const auto& c : golden_http) {
|
||||
json doc = c["document"];
|
||||
if (!c["image"].is_null()) {
|
||||
json parts = json::array();
|
||||
|
||||
@@ -185,6 +185,7 @@ TEST(drafter_geom_replicates_kv_heads_only_when_the_block_asks) {
|
||||
* query heads over that head (gqa 8, a libr4d row of its own) where two ranks run 16 (gqa 16). At
|
||||
* two ranks nothing is spanned: the even shard is the head. */
|
||||
TEST(lilicorr_replicates_its_two_kv_heads_at_four_ranks) {
|
||||
SKIP("Nemotron-H's trunk is block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int world : { 2, 4 })
|
||||
@@ -244,6 +245,7 @@ TEST(lilicorr_replicates_its_two_kv_heads_at_four_ranks) {
|
||||
/* A speculative step at four ranks: the trunk's verify of two sequences, the drafter's context pass
|
||||
* over its rows and its query pass, each without a step failure and lint-clean. */
|
||||
TEST(nemotronh_tp4_steps_lint_clean_with_the_lilicorr_drafter) {
|
||||
SKIP("Nemotron-H's trunk is block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int rank : { 0, 3 }) {
|
||||
@@ -271,6 +273,7 @@ TEST(nemotronh_tp4_steps_lint_clean_with_the_lilicorr_drafter) {
|
||||
* counts and buffer rows smaller. The drafter's split fc gathers its message as a range; a fixed
|
||||
* numel there left every level unplanned, and sixteen sequences short of the lent arena. */
|
||||
TEST(nemotronh_sizing_declares_match_the_real_graph_at_every_arena_level) {
|
||||
SKIP("Nemotron-H's trunk is block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int world : { 2, 4 })
|
||||
|
||||
+64
-11
@@ -1,5 +1,6 @@
|
||||
#!/bin/sh
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER]]]
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER
|
||||
# [BUILD_TYPE]]]]
|
||||
#
|
||||
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
|
||||
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
|
||||
@@ -31,11 +32,15 @@
|
||||
# it needs an Intel card, which this test must not touch.
|
||||
set -eu
|
||||
B=$1; S=$2; W=$3
|
||||
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}
|
||||
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}; BT=${8:-}
|
||||
# The tree's own C++ compiler, so the out-of-tree build does not depend on the host's default
|
||||
# (`c++` may be a different GCC than the one the installed ABI headers require).
|
||||
CCXX=""
|
||||
[ -n "$CXXC" ] && CCXX="-DCMAKE_CXX_COMPILER=$CXXC"
|
||||
# The tree's build type too: a plugin configured without one takes RelWithDebInfo
|
||||
# (rad_plugin_defaults), and a tree configured as anything else would then be compared with device
|
||||
# code compiled at other flags.
|
||||
[ -n "$BT" ] && CCXX="$CCXX -DCMAKE_BUILD_TYPE=$BT"
|
||||
GEN=${CMAKE_GENERATOR:-Ninja}
|
||||
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
|
||||
|
||||
@@ -54,10 +59,14 @@ run() { # run LOG CMD... -- quiet unless it fails
|
||||
say "installing $B into $P"
|
||||
run "$W/logs/install.log" cmake --install "$B" --prefix "$P"
|
||||
|
||||
# The libraries have many sources and build one at a time at the build's full width. An
|
||||
# architecture or a bundled plugin is one or two large translation units, which no -j speeds up, and
|
||||
# there are dozens of them: those are built several at a time (`small`, below).
|
||||
dirs="libref libquant"
|
||||
[ -d "$S/libavx" ] && [ -f "$B/radiance_home/kernels/libavx.so" ] && dirs="$dirs libavx"
|
||||
small=""
|
||||
for d in "$S"/arch/*/ "$S"/plugin/*/; do
|
||||
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")"
|
||||
[ -f "$d/CMakeLists.txt" ] && small="$small $(basename "$(dirname "$d")")/$(basename "$d")"
|
||||
done
|
||||
# The device libraries: built out of tree only with the tree's HIP compiler, and left out of every
|
||||
# comparison below without it. Each declares the family it serves, so a tree built for one family
|
||||
@@ -67,21 +76,28 @@ devlibs=""
|
||||
for d in libr4d libr3d; do
|
||||
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d"
|
||||
done
|
||||
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
|
||||
devdirs=""
|
||||
[ -n "$HIPC" ] && devdirs="$devlibs"
|
||||
ICPX=${RAD_OOT_ICPX:-}
|
||||
sycllibs=""
|
||||
for d in libxe2; do
|
||||
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && sycllibs="$sycllibs $d"
|
||||
done
|
||||
[ -n "$ICPX" ] && dirs="$dirs $sycllibs"
|
||||
[ -n "$ICPX" ] && devdirs="$devdirs $sycllibs"
|
||||
is_dev() { case " $devlibs $sycllibs " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||
is_sycl() { case " $sycllibs " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||
|
||||
# Each plugin installs its plugin file under $H and anything else it ships (libr4d's r4d_selftest)
|
||||
# under the package's prefix, as a third party installing into that radiance would.
|
||||
for d in $dirs; do
|
||||
n=$(basename "$d")
|
||||
say "building $d against the installed package"
|
||||
#
|
||||
# The ROCm the environment names (the test sets ROCM_PATH to the one the tree links) goes on the
|
||||
# prefix path beside the package: CMake otherwise takes the HIP runtime from wherever the HIP
|
||||
# compiler sits, and a tree whose compiler comes from another ROCm build than its runtime would
|
||||
# get a libr4d linked against that build's runtime, which then fails to load.
|
||||
PP="$P"
|
||||
[ -n "${ROCM_PATH:-}" ] && PP="$P;$ROCM_PATH"
|
||||
build_one() { # build_one DIR JOBS -- configure and build one plugin directory
|
||||
d=$1; n=$(basename "$d")
|
||||
extra="$CCXX"
|
||||
if is_sycl "$n"; then
|
||||
extra="-DCMAKE_CXX_COMPILER=$ICPX"
|
||||
@@ -91,17 +107,54 @@ for d in $dirs; do
|
||||
fi
|
||||
# A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's
|
||||
# HIP compiler as a third party would pass theirs.
|
||||
case "$d" in plugin/*) [ -n "$HIPC" ] && extra="-DCMAKE_HIP_COMPILER=$HIPC" ;; esac
|
||||
case "$d" in plugin/*) [ -n "$HIPC" ] && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC" ;; esac
|
||||
# shellcheck disable=SC2086
|
||||
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
|
||||
-DCMAKE_PREFIX_PATH="$P" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
|
||||
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J"
|
||||
-DCMAKE_PREFIX_PATH="$PP" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
|
||||
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$2"
|
||||
}
|
||||
install_one() { # install_one DIR
|
||||
n=$(basename "$1")
|
||||
# --prefix for the same reason as the tree install above: a plugin's own CMakeLists may install
|
||||
# companions (libr4d ships r4d_selftest) to relative destinations under CMAKE_INSTALL_PREFIX, and
|
||||
# the test must not need root. The plugins themselves ignore the prefix -- rad_add_plugin installs
|
||||
# them under the absolute RAD_PLUGIN_INSTALL_HOME given at configure time -- so the checks below,
|
||||
# which look in $H, are unaffected.
|
||||
run "$W/logs/$n.install.log" cmake --install "$W/b/$n" --prefix "$W/i"
|
||||
}
|
||||
for d in $dirs; do
|
||||
say "building $d against the installed package"
|
||||
build_one "$d" "$J"
|
||||
install_one "$d"
|
||||
done
|
||||
|
||||
# OOT_JOBS of the small ones at a time (default half the build's width, at most 16: a plugin's
|
||||
# compile holds about half a GiB), two compile jobs each; installed one after another, in order.
|
||||
PJ=${OOT_JOBS:-$((J / 2))}
|
||||
[ "$PJ" -gt 16 ] && PJ=16
|
||||
[ "$PJ" -lt 1 ] && PJ=1
|
||||
# shellcheck disable=SC2086
|
||||
set -- $small
|
||||
say "building $# architectures and bundled plugins against the installed package, $PJ at a time"
|
||||
while [ $# -gt 0 ]; do
|
||||
batch=""; nb=0
|
||||
while [ $# -gt 0 ] && [ "$nb" -lt "$PJ" ]; do
|
||||
batch="$batch $1"; nb=$((nb + 1))
|
||||
( build_one "$1" 2 && : > "$W/logs/$(basename "$1").built" ) &
|
||||
shift
|
||||
done
|
||||
wait
|
||||
for d in $batch; do
|
||||
[ -f "$W/logs/$(basename "$d").built" ] ||
|
||||
fail "$d did not build out of tree (logs: $W/logs/$(basename "$d").*.log)"
|
||||
install_one "$d"
|
||||
done
|
||||
done
|
||||
|
||||
for d in $devdirs; do
|
||||
say "building $d against the installed package"
|
||||
build_one "$d" "$J"
|
||||
install_one "$d"
|
||||
done
|
||||
|
||||
# 1. The same plugins, file for file.
|
||||
|
||||
@@ -2108,6 +2108,9 @@ struct LoanRig {
|
||||
/* None by default: on a slab this small the production count would leave most of the loan
|
||||
* empty. Tests of turnover set their own. */
|
||||
int turnover = 0;
|
||||
/* MoverConfig::turnover_adaptive and its floor, for the test of it. */
|
||||
bool adaptive = false;
|
||||
int floor = 0;
|
||||
|
||||
explicit LoanRig(int n_expert = 8) : hf(n_expert) {}
|
||||
|
||||
@@ -2116,6 +2119,8 @@ struct LoanRig {
|
||||
RAD_TRY(h.init(hf.plan, hp));
|
||||
MoverConfig mc;
|
||||
mc.turnover_slots = turnover;
|
||||
mc.turnover_adaptive = adaptive;
|
||||
if (adaptive) mc.turnover_floor = floor;
|
||||
RAD_TRY(m.init(hf.f.prog, hf.plan, mc));
|
||||
RAD_TRY(rad_stream_create(&compute, 0));
|
||||
RAD_TRY(m.bind_compute_stream(compute));
|
||||
@@ -2212,6 +2217,69 @@ TEST(every_lent_slot_is_filled_in_one_dispatch) {
|
||||
CHECK(at[k] - at[k - 1] >= r.hf.plan.classes[0].stride);
|
||||
}
|
||||
|
||||
/* MoverConfig::turnover_adaptive: the slots kept free follow the swaps asked for. A quiet run keeps
|
||||
* only the floor free and fills the rest; steps that propose swaps get three steps' worth of
|
||||
* their mean back, up to the configured count, by drops (nothing crosses the link for them); and
|
||||
* a quiet run gives them up again, each a copy in. */
|
||||
TEST(an_adaptive_turnover_follows_the_swaps_asked_for) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 4;
|
||||
r.adaptive = true;
|
||||
r.floor = 1;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_EQ(r.m.turnover_slots(), (int64_t)4); /* the most it keeps */
|
||||
CHECK_EQ(r.m.turnover_now(), (int64_t)1); /* and what it starts from */
|
||||
const int64_t stride = r.hf.plan.classes[0].stride;
|
||||
const int64_t slots = r.m.flex_capacity() / stride;
|
||||
CHECK(r.pooled() > slots);
|
||||
REQUIRE(slots > 4);
|
||||
|
||||
auto settle = [&](int64_t proposed, int steps) {
|
||||
for (int k = 0; k < steps; ++k) {
|
||||
r.m.swap_demand(proposed);
|
||||
CHECK_OK(r.dispatch());
|
||||
}
|
||||
for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) CHECK_OK(r.dispatch());
|
||||
for (int k = 0; k < 4; ++k) CHECK_OK(r.dispatch());
|
||||
};
|
||||
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
|
||||
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) {
|
||||
r.m.swap_demand(0);
|
||||
CHECK_OK(r.dispatch());
|
||||
}
|
||||
CHECK_EQ(r.m.turnover_now(), (int64_t)1);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 1) * stride);
|
||||
|
||||
/* One swap a step, step after step: the mean reaches one, and three steps of it are three. */
|
||||
const uint64_t d2h = r.m.stats().d2h_bytes, h2d = r.m.stats().h2d_bytes;
|
||||
settle(1, 600);
|
||||
CHECK_EQ(r.m.turnover_now(), (int64_t)3);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 3) * stride);
|
||||
CHECK_EQ(r.m.stats().dropped, (uint64_t)2);
|
||||
/* Two a step would ask for six: the configured count bounds it. */
|
||||
settle(2, 600);
|
||||
CHECK_EQ(r.m.turnover_now(), (int64_t)4);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 4) * stride);
|
||||
CHECK_EQ(r.m.stats().dropped, (uint64_t)3);
|
||||
CHECK_EQ(r.m.stats().d2h_bytes, d2h); /* the drops crossed no link */
|
||||
CHECK_EQ(r.m.stats().h2d_bytes, h2d);
|
||||
|
||||
/* Quiet again: back to the floor, and the three slots are filled again. */
|
||||
settle(0, 800);
|
||||
CHECK_EQ(r.m.turnover_now(), (int64_t)1);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 1) * stride);
|
||||
CHECK(r.m.stats().h2d_bytes > h2d);
|
||||
|
||||
/* Off, the count is the configured one whatever is asked for. */
|
||||
LoanRig s(24);
|
||||
s.turnover = 4;
|
||||
CHECK_OK(s.build());
|
||||
s.m.swap_demand(0);
|
||||
CHECK_OK(s.dispatch());
|
||||
CHECK_EQ(s.m.turnover_now(), (int64_t)4);
|
||||
}
|
||||
|
||||
/* The turnover slots stay free, and a shrinking loan does not take them for good. The fill stops
|
||||
* that many slots short so the engine's swaps have somewhere to land. Free slots are at the loan's
|
||||
* top, which a reclaiming cache takes first; the mover then rebuilds them by dropping the coldest
|
||||
@@ -2609,6 +2677,56 @@ TEST(a_second_lender_is_recalled_without_touching_the_first) {
|
||||
CHECK(again > 0);
|
||||
}
|
||||
|
||||
/* The fleet lends free VRAM it backs into a range the engine reserved (Engine::xflex_tick).
|
||||
* lendable_bytes sizes that range so every pooled unit gets a slot; the loan is the backed top of
|
||||
* it, and a recall leaves nothing in it, so the range can be unbacked after. */
|
||||
TEST(the_fleets_loan_gives_every_pooled_unit_a_slot_and_comes_back_whole) {
|
||||
if (!VMem::supported()) SKIP("the backend has no elastic memory");
|
||||
LoanRig r;
|
||||
CHECK_OK(r.build());
|
||||
const int64_t b = r.m.lendable_bytes();
|
||||
CHECK(b > 0);
|
||||
const int64_t g = VMem::granularity();
|
||||
VMem vm;
|
||||
CHECK_OK(vm.reserve((b + g - 1) / g * g));
|
||||
const int64_t before = r.m.flex_capacity();
|
||||
LoanStrip st;
|
||||
st.top = (char*)vm.base() + vm.size();
|
||||
st.bytes = vm.size();
|
||||
st.unit_bytes = 1;
|
||||
st.unit_tokens = 1;
|
||||
CHECK_OK(r.m.lend_from(Mover::kLendFleet, { st }));
|
||||
const int64_t stride = r.hf.plan.classes[0].stride;
|
||||
CHECK_EQ((r.m.flex_capacity() - before) / stride, (int64_t)r.pooled());
|
||||
const int64_t ceil = r.m.loan_ceiling(Mover::kLendFleet);
|
||||
CHECK(ceil > 0 && ceil <= vm.size());
|
||||
|
||||
/* Backed from the top, then lent: the fill reaches only the fleet's slots. */
|
||||
const int64_t lend = (ceil + g - 1) / g * g;
|
||||
CHECK_OK(vm.commit(vm.size() - lend, lend));
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendFleet, lend));
|
||||
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
auto in_range = [&](const void* p) {
|
||||
return (const char*)p >= (const char*)vm.base() && (const char*)p < (const char*)vm.base() + vm.size();
|
||||
};
|
||||
int32_t in = 0;
|
||||
for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) {
|
||||
CHECK(!r.loan.inside(r.addr(u)));
|
||||
in += in_range(r.addr(u));
|
||||
}
|
||||
CHECK(in > 0);
|
||||
CHECK(r.m.loan_held(Mover::kLendFleet) > 0);
|
||||
|
||||
/* The recall empties the range before it returns; unbacking it after is safe. */
|
||||
CHECK_OK(r.m.reclaim(Mover::kLendFleet, 0, &r.h));
|
||||
CHECK_EQ(r.m.loan_held(Mover::kLendFleet), (int64_t)0);
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), r.planned);
|
||||
for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) CHECK(!in_range(r.addr(u)));
|
||||
CHECK_OK(vm.decommit(0, vm.size()));
|
||||
CHECK_EQ(vm.committed(), (int64_t)0);
|
||||
}
|
||||
|
||||
TEST(slot_pool_segments_have_their_own_targets) {
|
||||
SlotPool s;
|
||||
s.init(2, 1);
|
||||
@@ -4585,6 +4703,43 @@ TEST(expert_pin_top_keeps_the_hottest_resident) {
|
||||
CHECK(p.report(f.prog).find("pinned hot") != std::string::npos);
|
||||
}
|
||||
|
||||
/* Real profiles carry per-layer shares in [0, 1] (xs_profile_load divides by the layer's total), so
|
||||
* the cut must not assume integer gaps between shares: F = 0.25 pins the hottest quarter, not every
|
||||
* resident expert. */
|
||||
TEST(expert_pin_top_cuts_fractional_shares) {
|
||||
Fixture f;
|
||||
build_moe_layers(f, 2, 8, 1 * MiB, 0);
|
||||
|
||||
std::vector<RadFileProfile> prof;
|
||||
for (int l = 0; l < 2; ++l)
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
RadFileProfile r{};
|
||||
r.layer = l;
|
||||
r.expert = e;
|
||||
r.share = (float)(e + 1) / 36.0f;
|
||||
prof.push_back(r);
|
||||
}
|
||||
|
||||
Config c = base_config();
|
||||
c.placement = "expert_tiered";
|
||||
c.vram_weights_mib = 1024;
|
||||
c.host_pool_mib = 1024;
|
||||
c.expert_pin_top = 0.25f;
|
||||
|
||||
PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()};
|
||||
Plan p;
|
||||
CHECK_OK(Planner(in).plan(&p));
|
||||
|
||||
int pinned = 0, hot_pinned = 0;
|
||||
for (const MoveUnit& mu : p.units) {
|
||||
if (mu.expert < 0 || !mu.pinned) continue;
|
||||
++pinned;
|
||||
if (mu.expert >= 6) ++hot_pinned;
|
||||
}
|
||||
CHECK_EQ(pinned, 4);
|
||||
CHECK_EQ(hot_pinned, 4);
|
||||
}
|
||||
|
||||
TEST(expert_pin_top_zero_pins_nothing) {
|
||||
Fixture f;
|
||||
build_moe_layers(f, 1, 4, 1 * MiB, 0);
|
||||
|
||||
+38
-6
@@ -7,12 +7,14 @@
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "plugin/registry.h"
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -86,15 +88,17 @@ std::string band_names(const std::vector<Band>& b) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The shipped libr4d.so, or "" for the case to leave. A build without HIP makes none, which skips;
|
||||
* a HIP build always makes it, so there its absence is a missing in-tree artifact. */
|
||||
/* The shipped libr4d.so, or "" for the case to leave. A build without HIP makes none, and a
|
||||
* HIP build whose GPU targets name no RDNA4 card makes none either (libr4d serves gfx12
|
||||
* only); both skip. A build that did make the library (RAD_TEST_HAS_LIBR4D, from
|
||||
* tests/CMakeLists.txt) has it missing only by accident, which strict mode refuses. */
|
||||
std::string libr4d() {
|
||||
const std::string so = home() + "/kernels/libr4d.so";
|
||||
if (access(so.c_str(), R_OK) == 0) return so;
|
||||
#ifdef RAD_HAVE_HIP
|
||||
#ifdef RAD_TEST_HAS_LIBR4D
|
||||
radtest::artifact_missing(__FILE__, __LINE__, so);
|
||||
#else
|
||||
radtest::skip("no %s (a build without HIP)", so.c_str());
|
||||
radtest::skip("no %s (this build targets no RDNA4 card)", so.c_str());
|
||||
#endif
|
||||
return "";
|
||||
}
|
||||
@@ -289,7 +293,7 @@ TEST(an_architecture_plugin_may_declare_its_reply_format) {
|
||||
/* And the parser reads a reply in it. */
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
|
||||
const nlohmann::ordered_json tools = nlohmann::ordered_json::parse(
|
||||
const Json tools = Json::parse(
|
||||
R"([{"type":"function","function":{"name":"go","parameters":{"type":"object",)"
|
||||
R"("properties":{"n":{"type":"integer"},"s":{"type":"string"}}}}}])");
|
||||
ReplyOptions ro;
|
||||
@@ -434,6 +438,33 @@ TEST(selection_takes_the_highest_declared_priority) {
|
||||
CHECK(t.reason.empty());
|
||||
}
|
||||
|
||||
/* Engines in one process select from one loaded set (registry.h, Sharing): a share sees the same
|
||||
* rows, keeps its own selection table, cannot load into the set, and closing it leaves the set
|
||||
* loaded for the others. */
|
||||
TEST(a_shared_registry_selects_from_the_same_set_and_keeps_its_own_table) {
|
||||
Registry r;
|
||||
CHECK_OK(load(r));
|
||||
std::unique_ptr<Registry> a = r.share();
|
||||
std::unique_ptr<Registry> b = r.share();
|
||||
CHECK(r.shared());
|
||||
CHECK_EQ(a->plugins().size(), r.plugins().size());
|
||||
CHECK_EQ(picked(a->select("t_gemm", gemm_geom(16), RAD_DOMAIN_DEVICE)), "t_gemm_m16");
|
||||
CHECK_EQ(a->n_selections(), (size_t)1);
|
||||
CHECK_EQ(b->n_selections(), (size_t)0);
|
||||
CHECK_EQ(r.n_selections(), (size_t)0);
|
||||
|
||||
CHECK(b->load_dir(kernels_dir(), {}) < 0); /* the set is shared: loaded once */
|
||||
|
||||
a->close();
|
||||
CHECK(a->plugins().empty());
|
||||
CHECK(!r.plugins().empty());
|
||||
CHECK_EQ(picked(b->select("t_gemm", gemm_geom(65), RAD_DOMAIN_DEVICE)), "t_gemm_any");
|
||||
b.reset();
|
||||
a.reset();
|
||||
CHECK(!r.shared());
|
||||
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(17), RAD_DOMAIN_DEVICE)), "t_gemm_m64");
|
||||
}
|
||||
|
||||
/* Specificity is declared, not derived, and a tie goes to the row declared first. */
|
||||
TEST(selection_breaks_ties_on_declaration_order) {
|
||||
Registry r;
|
||||
@@ -1085,6 +1116,7 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) {
|
||||
* band of every op the row form adds resolves on the device, up to a 4096-token step's run of
|
||||
* 512 rows. A form libr4d does not serve would stop a TP8 start at "resolved to no kernel". */
|
||||
TEST(libr4d_resolves_every_band_of_glm_mla_split_by_rows) {
|
||||
SKIP("GLM-5.3's weights are MXFP4 and block fp8, which this build does not serve; the case returns with an int8 container");
|
||||
const std::string so = libr4d();
|
||||
if (so.empty()) return;
|
||||
Registry r;
|
||||
|
||||
@@ -282,6 +282,39 @@ TEST(gptq_with_a_hessian_lowers_the_output_error) {
|
||||
CHECK(gc.planes[1] == g.planes[1]);
|
||||
}
|
||||
|
||||
TEST(w6nl_gptq_and_coordinate_descent_accept_bf16_domain_hessians) {
|
||||
NEED_LIBQUANT();
|
||||
const int64_t R = 16, C = 128, T = 4096;
|
||||
std::vector<float> h((size_t)(C * C), (float)T * 0.25f);
|
||||
for (int64_t i = 0; i < C; ++i) h[(size_t)(i * C + i)] += (float)T;
|
||||
const TempDir td("rad_w6nl_gptq");
|
||||
REQUIRE(!td.path.empty());
|
||||
REQUIRE(write_gram(td.path + "/gram.r0.blk.3.ffn_down_exps.bin", C, T, h));
|
||||
Opts o;
|
||||
o.s("table", "w6nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
|
||||
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128")
|
||||
.s("rule", "search").i("cd", 3).s("calib", td.path.c_str());
|
||||
const std::vector<float> w = draw(R * C, 770, 1.0f);
|
||||
const Quantised q = quantise(quantizer("gptq"), o, "blk.3.ffn_down_exps.17.weight", R, C, w);
|
||||
REQUIRE_EQ(q.status, RAD_OK);
|
||||
CHECK_EQ(q.enc.plane[0].dtype, (uint32_t)RAD_U6);
|
||||
CHECK_EQ(q.planes[0].size(), (size_t)(R * C * 6 / 8));
|
||||
CHECK_EQ(q.enc.plane[3].extent[1], 64LL);
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
float value = 0.0f;
|
||||
std::memcpy(&value, q.planes[3].data() + i * sizeof(float), sizeof value);
|
||||
const uint8_t fp8 = rad_f32_to_fp8e4m3(value);
|
||||
CHECK_EQ(rad_load_f32(&fp8, RAD_F8E4M3, 0), value);
|
||||
if (i >= 32) {
|
||||
float positive = 0.0f;
|
||||
std::memcpy(&positive, q.planes[3].data() + (i - 32) * sizeof(float), sizeof positive);
|
||||
CHECK_EQ(value, -positive);
|
||||
}
|
||||
}
|
||||
const std::vector<float> decoded = decode(q, R, C);
|
||||
CHECK(rel_err(w, decoded) < 0.2);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ recipes, compiled
|
||||
*
|
||||
* A rule's options are typed by its quantiser's own table before declare runs, so a misspelt key or
|
||||
@@ -337,7 +370,10 @@ TEST(every_shipped_recipe_compiles_and_its_grids_are_accepted) {
|
||||
REQUIRE(!calib.path.empty());
|
||||
const char* old = std::getenv("CALIB");
|
||||
const std::string saved = old ? old : "";
|
||||
const char* old_mtp = std::getenv("MTP_CALIB");
|
||||
const std::string saved_mtp = old_mtp ? old_mtp : "";
|
||||
setenv("CALIB", calib.path.c_str(), 1);
|
||||
setenv("MTP_CALIB", calib.path.c_str(), 1);
|
||||
|
||||
int files = 0, rules = 0;
|
||||
std::error_code ec;
|
||||
@@ -391,6 +427,7 @@ TEST(every_shipped_recipe_compiles_and_its_grids_are_accepted) {
|
||||
CHECK(rules >= 250);
|
||||
std::filesystem::current_path(cwd, ec);
|
||||
if (old) setenv("CALIB", saved.c_str(), 1); else unsetenv("CALIB");
|
||||
if (old_mtp) setenv("MTP_CALIB", saved_mtp.c_str(), 1); else unsetenv("MTP_CALIB");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ GPTQ against the textbook
|
||||
@@ -660,6 +697,7 @@ TEST(round_to_nearest_stores_the_nearest_code_on_every_grid) {
|
||||
"table=iq4nl,group=32,scale=f16",
|
||||
"table=w4nl,group=128,scale=bf16,transform=fwht128",
|
||||
"table=w5nl,group=64,scale=fp8_e4m3,scale2=f32",
|
||||
"table=w6nl,group=64,scale=fp8_e4m3,scale2=f32,transform=fwht128,rule=search",
|
||||
"table=binary,group=32,scale=f16,rule=search",
|
||||
"table=ternary,group=32,scale=bf16",
|
||||
"table=-1.5;-0.25;0;0.5;2,group=32,scale=f32",
|
||||
@@ -877,6 +915,68 @@ TEST(a_codebook_indexes_its_table_and_the_scale_multiplies_it) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A vq= codebook file is attacker data, and its loader appended every line to memory before
|
||||
* checking any count, while its "# unit" line parsed `inf` through %lf -- and the fallback
|
||||
* guard `!(unit > 0.0)` let infinity through, where a NaN falls back to the entries' rms. The
|
||||
* count is now checked while appending (the widest code is u12: past 4096 codewords could not
|
||||
* be indexed even with the memory), and only a finite positive names the unit. */
|
||||
TEST(the_codebook_loader_caps_while_reading_and_refuses_an_infinite_unit) {
|
||||
NEED_LIBQUANT();
|
||||
TempDir dir("vqcap");
|
||||
auto write_cb = [&](const char* name, const char* head, int lines) -> std::string {
|
||||
const std::string p = dir.path + "/" + name;
|
||||
/* No REQUIRE in here: its failure spelling returns void, and this lambda returns a
|
||||
* path. An unopenable path yields an empty/short file, which the loaders refuse --
|
||||
* the surrounding CHECKs catch it either way. */
|
||||
std::FILE* f = std::fopen(p.c_str(), "wb");
|
||||
if (f != nullptr) {
|
||||
if (head) std::fprintf(f, "%s\n", head);
|
||||
for (int i = 0; i < lines; ++i) std::fprintf(f, "%d %d %d %d\n", i % 5 - 2, 3, -4, 5);
|
||||
std::fclose(f);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
const int64_t R = 8, C = 128;
|
||||
const std::vector<float> w = draw(R * C, 5, 0.0f);
|
||||
|
||||
/* vq= is gptq's path -- rtn refuses it ("vq= is quantised by gptq") -- so every case here
|
||||
* goes through gptq and every refusal below is the LOADER's, not a quantizer mismatch. */
|
||||
/* One past the cap: refused by name. 4097 entries used to build an encoding whose u12
|
||||
* codes could not index its own last codeword. */
|
||||
{
|
||||
Opts o;
|
||||
o.s("vq", write_cb("big.txt", "# unit 1.0", 4097).c_str()).i("group", 128).s("scale", "bf16");
|
||||
CHECK(quantise(quantizer("gptq"), o, "x", R, C, w).status != RAD_OK);
|
||||
}
|
||||
/* The cap itself is the largest honest codebook: it reads. */
|
||||
{
|
||||
Opts o;
|
||||
o.s("vq", write_cb("cap.txt", "# unit 1.0", 4096).c_str()).i("group", 128).s("scale", "bf16");
|
||||
CHECK_EQ(quantise(quantizer("gptq"), o, "x", R, C, w).status, RAD_OK);
|
||||
}
|
||||
/* "# unit inf" used to multiply every decoded value by infinity; ignored now, the entries'
|
||||
* own rms takes over and the decode stays finite. */
|
||||
{
|
||||
Opts o;
|
||||
o.s("vq", write_cb("inf.txt", "# unit inf", 256).c_str()).i("group", 128).s("scale", "bf16");
|
||||
Quantised q = quantise(quantizer("gptq"), o, "x", R, C, w);
|
||||
REQUIRE_EQ(q.status, RAD_OK);
|
||||
const std::vector<float> d = decode(q, R, C);
|
||||
REQUIRE(!d.empty());
|
||||
int bad = 0;
|
||||
for (float x : d) bad += !std::isfinite(x);
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
/* tcq's sibling flow: a zero tcq_gain used to divide the unit by zero and every code
|
||||
* became inf; the loader refuses it by name now. */
|
||||
{
|
||||
Opts o;
|
||||
o.s("codes", "u2").i("tcq", 10).i("tcq_rows", 256).i("group", 128).s("scale", "bf16")
|
||||
.f("tcq_gain", 0.0);
|
||||
CHECK(quantise(quantizer("gptq"), o, "x", R, C, w).status != RAD_OK);
|
||||
}
|
||||
}
|
||||
|
||||
/* A trellis grid (tcq=L): each column's codes are the bits a 2^L-state bitshift trellis shifts in,
|
||||
* row by row, and a value is its state's table entry times the block's scale. Its own scheme,
|
||||
* decoded by libquant's hook: the decode is the values the Viterbi search chose, and at the same
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
/* cfg_stub.cpp -- the two tuned-configuration readers the M2XFP4 GEMM units call
|
||||
* (r4d_cfg_mxfp4_decode, r4d_cfg_mxfp4_tiled), which libr4d defines on its declaration side
|
||||
* (r4d_rows.cpp) beside the row tables. That side is not in the emu build, and every r4d_emu_*
|
||||
* binary links every unit, so the readers are defined once here. Every axis default of
|
||||
* tGemmMxfp4Decode and tGemmMxfp4Tiled is 0, the kernels' own rule, so reading the key or 0 is
|
||||
* what r4d_rows.cpp's readers return for a caller with no tuned point. */
|
||||
#include "r4d_args.h"
|
||||
|
||||
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
|
||||
out->ks = (int)rad_args_geti_or(a, "ks", 0);
|
||||
out->bk = (int)rad_args_geti_or(a, "bk", 0);
|
||||
out->nt = (int)rad_args_geti_or(a, "nt", 0);
|
||||
}
|
||||
|
||||
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
|
||||
out->tn = (int)rad_args_geti_or(a, "tn", 0);
|
||||
}
|
||||
+119
-41
@@ -1,6 +1,8 @@
|
||||
#include "hip/hip_runtime.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <emmintrin.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
@@ -59,9 +61,29 @@ struct Sched {
|
||||
int slot[64][2][32] = {};
|
||||
int tag[64][2][32] = {}; /* which op, and its uniform operand, each lane posted */
|
||||
unsigned xparity[1024] = {};
|
||||
/* each wave's live lanes and returned-lane mask, kept as lanes return: a barrier arrival
|
||||
* reads them rather than walking the wave */
|
||||
int walive[64] = {};
|
||||
unsigned wdone[64] = {};
|
||||
/* the wave generation whose exchange slots have been checked and poisoned, by parity */
|
||||
unsigned xchecked[64][2] = {};
|
||||
/* bumped by every barrier arrival and every lane's return: a round that leaves it unchanged
|
||||
* made no progress */
|
||||
uint64_t progress = 0;
|
||||
} S;
|
||||
|
||||
void yield() { Fiber& me = S.f[S.cur]; emu_switch(&me.sp, S.main_sp); }
|
||||
/* Hands the core to the next live fiber of the round, in thread order, or back to the scheduler
|
||||
* after the last: the order fibers run in is the scheduler's own, at one switch a hand-off. */
|
||||
void yield() {
|
||||
Fiber& me = S.f[S.cur];
|
||||
for (int t = S.cur + 1; t < S.nthreads; ++t)
|
||||
if (!S.f[t].done) {
|
||||
S.cur = t;
|
||||
emu_switch(&me.sp, S.f[t].sp);
|
||||
return;
|
||||
}
|
||||
emu_switch(&me.sp, S.main_sp);
|
||||
}
|
||||
|
||||
/* Lanes of wave `w` that have not returned. A cross-lane op on the card runs over the active lanes:
|
||||
* a lane that has returned takes no part, and the op completes without it (a read of its value is
|
||||
@@ -73,21 +95,16 @@ int g_wmma_pending[64]; /* the wave exchange now forming is a WMMA's, which ev
|
||||
* arrive, so a lane reads this before it can be overwritten. */
|
||||
unsigned g_absent[64];
|
||||
unsigned wave_done_mask(int w);
|
||||
unsigned wave_done_mask(int w) {
|
||||
unsigned m = 0;
|
||||
for (int i = 0; i < 32 && w * 32 + i < S.nthreads; ++i) m |= (unsigned)S.f[w * 32 + i].done << i;
|
||||
return m;
|
||||
}
|
||||
int wave_alive(int w) {
|
||||
int n = 0;
|
||||
for (int i = w * 32; i < w * 32 + 32 && i < S.nthreads; ++i) n += !S.f[i].done;
|
||||
return n;
|
||||
}
|
||||
unsigned wave_done_mask(int w) { return S.wdone[w]; }
|
||||
int wave_alive(int w) { return S.walive[w]; }
|
||||
extern "C" void emu_trampoline() {
|
||||
S.body(S.ctx);
|
||||
S.f[S.cur].done = true;
|
||||
/* The lanes still running may be waiting at a wave exchange only this lane had yet to reach. */
|
||||
const int w = (int)S.f[S.cur].tid.x >> 5;
|
||||
--S.walive[w];
|
||||
S.wdone[w] |= 1u << ((int)S.f[S.cur].tid.x & 31);
|
||||
++S.progress;
|
||||
if (S.warrive[w] > 0 && S.warrive[w] == wave_alive(w)) {
|
||||
if (g_wmma_pending[w]) {
|
||||
std::fprintf(stderr, "emu: block (%u,%u,%u), wave %d: lane %d returned while the others wait at a "
|
||||
@@ -125,6 +142,7 @@ void __syncthreads() {
|
||||
/* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every
|
||||
* write to it (threads arrive at g + 1 only after g completes) and behind every read of the
|
||||
* slot it shares a residue with (g - 2's, read before arriving at g - 1). */
|
||||
++S.progress;
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; }
|
||||
me.waiting = 1;
|
||||
while (S.gen == g) yield();
|
||||
@@ -140,6 +158,7 @@ int __syncthreads_or(int p) {
|
||||
static void wave_barrier(int w) {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.wgen[w];
|
||||
++S.progress;
|
||||
if (++S.warrive[w] == wave_alive(w)) {
|
||||
g_absent[w] = wave_done_mask(w);
|
||||
S.warrive[w] = 0; ++S.wgen[w]; g_wmma_pending[w] = 0;
|
||||
@@ -163,6 +182,10 @@ static const int* exchange(int v, int* lane, int tag) {
|
||||
S.slot[w][par][*lane] = v;
|
||||
S.tag[w][par][*lane] = tag;
|
||||
wave_barrier(w);
|
||||
/* The exchange's slots are checked and poisoned once, by the first lane to read them: the
|
||||
* wave's generation names the exchange until every live lane has read it. */
|
||||
if (S.xchecked[w][par] == S.wgen[w]) return S.slot[w][par];
|
||||
S.xchecked[w][par] = S.wgen[w];
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
if ((g_absent[w] >> i) & 1u) { /* a lane that had returned: no value; a read of it shows */
|
||||
S.slot[w][par][i] = 0x7fbadbad;
|
||||
@@ -203,7 +226,12 @@ static void wmma_whole_wave(int w) {
|
||||
}
|
||||
}
|
||||
/* One 16x16x16 WMMA: each lane posts its A and B elements, then reads the whole tile back. `ga`
|
||||
* and `gb` are the exchange slots of one element type, [wave][parity][lane][element]. */
|
||||
* and `gb` are the exchange slots of one element type, [wave][parity][lane][element].
|
||||
*
|
||||
* A lane's eight outputs are rows M = 8h + e of column N. Its operands are converted once, A
|
||||
* transposed to [k][e], and the eight sums run in two SSE2 registers: each step multiplies and
|
||||
* then adds (the file builds with -ffp-contract=off), every output in k order from c, as the
|
||||
* hardware's own order is restated in the tests' host references. */
|
||||
template <class T, class V, class Cvt>
|
||||
static emu_v8f emu_wmma(T (&ga)[64][2][32][8], T (&gb)[64][2][32][8], V a, V b, emu_v8f c,
|
||||
Cvt cvt) {
|
||||
@@ -213,36 +241,71 @@ static emu_v8f emu_wmma(T (&ga)[64][2][32][8], T (&gb)[64][2][32][8], V a, V b,
|
||||
wmma_whole_wave(w);
|
||||
wave_barrier(w);
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 8 * h + e;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += cvt(ga[w][par][M + 16 * (k >> 3)][k & 7]) * cvt(gb[w][par][N + 16 * (k >> 3)][k & 7]);
|
||||
d[e] = acc;
|
||||
alignas(16) float at[16][8];
|
||||
float bt[16];
|
||||
for (int k = 0; k < 16; ++k) {
|
||||
const int slot = 16 * (k >> 3), el = k & 7;
|
||||
bt[k] = cvt(gb[w][par][N + slot][el]);
|
||||
for (int e = 0; e < 8; ++e) at[k][e] = cvt(ga[w][par][8 * h + e + slot][el]);
|
||||
}
|
||||
__m128 lo = _mm_setr_ps(c[0], c[1], c[2], c[3]), hi = _mm_setr_ps(c[4], c[5], c[6], c[7]);
|
||||
for (int k = 0; k < 16; ++k) {
|
||||
const __m128 bk = _mm_set1_ps(bt[k]);
|
||||
lo = _mm_add_ps(lo, _mm_mul_ps(_mm_load_ps(at[k]), bk));
|
||||
hi = _mm_add_ps(hi, _mm_mul_ps(_mm_load_ps(at[k] + 4), bk));
|
||||
}
|
||||
alignas(16) float out[8];
|
||||
_mm_store_ps(out, lo);
|
||||
_mm_store_ps(out + 4, hi);
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) d[e] = out[e];
|
||||
return d;
|
||||
}
|
||||
namespace {
|
||||
/* Every binary16 pattern's value: the baseline ISA has no F16C, so a conversion is a libgcc call. */
|
||||
struct HalfTable {
|
||||
std::unique_ptr<float[]> v{ new float[65536] };
|
||||
HalfTable() {
|
||||
for (uint32_t i = 0; i < 65536; ++i) {
|
||||
const uint16_t u = (uint16_t)i;
|
||||
_Float16 h;
|
||||
std::memcpy(&h, &u, 2);
|
||||
v[i] = (float)h;
|
||||
}
|
||||
}
|
||||
};
|
||||
const HalfTable g_half;
|
||||
}
|
||||
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
|
||||
return emu_wmma(g_wa, g_wb, a, b, c, [](short v) { return rad_bf16_to_f32((uint16_t)v); });
|
||||
}
|
||||
static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
|
||||
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; });
|
||||
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) {
|
||||
uint16_t u;
|
||||
std::memcpy(&u, &v, 2);
|
||||
return g_half.v[u];
|
||||
});
|
||||
}
|
||||
namespace {
|
||||
struct Bytes8 {
|
||||
uint8_t v[8];
|
||||
uint8_t operator[](int e) const { return v[e]; }
|
||||
};
|
||||
/* Every E4M3 code's value, from the ABI's own converter. */
|
||||
struct Fp8Table {
|
||||
float v[256];
|
||||
Fp8Table() { for (int i = 0; i < 256; ++i) v[i] = rad_fp8e4m3_to_f32((uint8_t)i); }
|
||||
};
|
||||
const Fp8Table g_fp8;
|
||||
}
|
||||
static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8];
|
||||
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) {
|
||||
Bytes8 pa, pb;
|
||||
std::memcpy(pa.v, &a, 8);
|
||||
std::memcpy(pb.v, &b, 8);
|
||||
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); });
|
||||
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return g_fp8.v[v]; });
|
||||
}
|
||||
emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) {
|
||||
std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n");
|
||||
@@ -330,7 +393,12 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
std::memset(g_lds, 0xA5, dyn_lds);
|
||||
S.arrive = 0; S.gen = 0;
|
||||
for (int& a : S.or_acc) a = 0;
|
||||
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; g_wmma_pending[w] = 0; g_absent[w] = 0; }
|
||||
for (int w = 0; w < 64; ++w) {
|
||||
S.warrive[w] = 0; S.wgen[w] = 0; g_wmma_pending[w] = 0; g_absent[w] = 0;
|
||||
S.walive[w] = std::max(0, std::min(32, n - 32 * w));
|
||||
S.wdone[w] = 0;
|
||||
S.xchecked[w][0] = S.xchecked[w][1] = ~0u;
|
||||
}
|
||||
for (int t = 0; t < n; ++t) {
|
||||
Fiber& f = S.f[t];
|
||||
f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0};
|
||||
@@ -344,18 +412,17 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
int live = n;
|
||||
while (live > 0) {
|
||||
const int live_before = live;
|
||||
const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w];
|
||||
int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w];
|
||||
const uint64_t p0 = S.progress;
|
||||
/* One round: the first live fiber runs, each hands on to the next (yield), and the
|
||||
* last hands back here. */
|
||||
int first = 0;
|
||||
while (S.f[first].done) ++first;
|
||||
S.cur = first;
|
||||
emu_switch(&S.main_sp, S.f[first].sp);
|
||||
S.cur = -1;
|
||||
live = 0;
|
||||
for (int t = 0; t < n; ++t) {
|
||||
if (S.f[t].done) continue;
|
||||
S.cur = t;
|
||||
emu_switch(&S.main_sp, S.f[t].sp);
|
||||
S.cur = -1;
|
||||
if (!S.f[t].done) ++live;
|
||||
}
|
||||
bool progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
|
||||
for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]);
|
||||
for (int t = 0; t < n; ++t) live += !S.f[t].done;
|
||||
const bool progressed = S.progress != p0 || live != live_before;
|
||||
if (live > 0 && !progressed) {
|
||||
int done = 0, wb = 0, bb = 0;
|
||||
for (auto& f : S.f) { done += f.done; wb += f.waiting == 2; bb += f.waiting == 1; }
|
||||
@@ -374,6 +441,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
* that replicates its operands across the halves (the documented form) sees no difference; one that
|
||||
* leaves the lanes the part never reads holding something else is emulated as the part runs it. */
|
||||
static uint16_t g11_a[64][2][32][16], g11_b[64][2][32][16];
|
||||
/* As emu_wmma: the lane's operands converted once (A transposed to [k][e]), then the eight sums
|
||||
* in two SSE2 registers, each in k order from c, multiply then add. */
|
||||
template <class Cvt>
|
||||
static emu_v8f emu_wmma11(const uint16_t (&a)[16], const uint16_t (&b)[16], emu_v8f c, Cvt cvt) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
@@ -382,14 +451,23 @@ static emu_v8f emu_wmma11(const uint16_t (&a)[16], const uint16_t (&b)[16], emu_
|
||||
wmma_whole_wave(w);
|
||||
wave_barrier(w);
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 2 * e + h;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += cvt(g11_a[w][par][M + 16 * h][k]) * cvt(g11_b[w][par][N + 16 * h][k]);
|
||||
d[e] = acc;
|
||||
alignas(16) float at[16][8];
|
||||
float bt[16];
|
||||
for (int k = 0; k < 16; ++k) {
|
||||
bt[k] = cvt(g11_b[w][par][N + 16 * h][k]);
|
||||
for (int e = 0; e < 8; ++e) at[k][e] = cvt(g11_a[w][par][2 * e + h + 16 * h][k]);
|
||||
}
|
||||
__m128 lo = _mm_setr_ps(c[0], c[1], c[2], c[3]), hi = _mm_setr_ps(c[4], c[5], c[6], c[7]);
|
||||
for (int k = 0; k < 16; ++k) {
|
||||
const __m128 bk = _mm_set1_ps(bt[k]);
|
||||
lo = _mm_add_ps(lo, _mm_mul_ps(_mm_load_ps(at[k]), bk));
|
||||
hi = _mm_add_ps(hi, _mm_mul_ps(_mm_load_ps(at[k] + 4), bk));
|
||||
}
|
||||
alignas(16) float out[8];
|
||||
_mm_store_ps(out, lo);
|
||||
_mm_store_ps(out + 4, hi);
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) d[e] = out[e];
|
||||
return d;
|
||||
}
|
||||
emu_v8f emu_wmma11_bf16(emu_v16bf a, emu_v16bf b, emu_v8f c) {
|
||||
@@ -402,7 +480,7 @@ emu_v8f emu_wmma11_f16(emu_v16h a, emu_v16h b, emu_v8f c) {
|
||||
uint16_t ua[16], ub[16];
|
||||
std::memcpy(ua, &a, 32);
|
||||
std::memcpy(ub, &b, 32);
|
||||
return emu_wmma11(ua, ub, c, [](uint16_t v) { _Float16 h; std::memcpy(&h, &v, 2); return (float)h; });
|
||||
return emu_wmma11(ua, ub, c, [](uint16_t v) { return g_half.v[v]; });
|
||||
}
|
||||
emu_v2hf emu_cvt_pkrtz(float a, float b) {
|
||||
auto rtz = [](float f) {
|
||||
|
||||
@@ -33,6 +33,7 @@ inline hipError_t hipGetLastError() { return 0; }
|
||||
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
|
||||
struct hipDeviceProp_t { size_t sharedMemPerBlock; int multiProcessorCount; };
|
||||
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
|
||||
inline hipError_t hipSetDevice(int) { return hipSuccess; }
|
||||
/* no graphs: a stream never captures */
|
||||
enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 };
|
||||
inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) {
|
||||
|
||||
@@ -67,7 +67,19 @@ static bool hgain(const RadTensor* w, int64_t n) {
|
||||
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
|
||||
}
|
||||
|
||||
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */
|
||||
/* The unnormalised Hadamard of 128 values in place, strides ascending: had_quant_act_i8g's. */
|
||||
static void hfwht128(float* v) {
|
||||
for (int h = 1; h < 128; h <<= 1)
|
||||
for (int i = 0; i < 128; ++i)
|
||||
if ((i & h) == 0) {
|
||||
const float x = v[i], y = v[i + h];
|
||||
v[i] = x + y;
|
||||
v[i + h] = x - y;
|
||||
}
|
||||
}
|
||||
|
||||
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs; an int8 `q` takes
|
||||
* norm_add_norm_route_i8g's rotated int8 codes */
|
||||
static int nan_host(const RadArgs* a, bool route) {
|
||||
if (!a || a->n_t < (route ? 10 : 5)) return RAD_E_INVAL;
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
@@ -84,7 +96,8 @@ static int nan_host(const RadArgs* a, bool route) {
|
||||
return RAD_E_DTYPE;
|
||||
int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0;
|
||||
if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
|
||||
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
|
||||
const bool i8 = route && Q->dtype == RAD_I8;
|
||||
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, i8 ? RAD_I8 : RAD_F8E4M3, n, &rq, &lq) ||
|
||||
!hrows_as(S, RAD_F32, n / 128, &rs, &ls)))
|
||||
return RAD_E_SHAPE;
|
||||
if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE;
|
||||
@@ -113,7 +126,19 @@ static int nan_host(const RadArgs* a, bool route) {
|
||||
rrow[i] = f2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
|
||||
v[(size_t)i] = rb((xv[(size_t)i] * sx) * we[i]);
|
||||
}
|
||||
for (int64_t g = 0; g < n / 128; ++g) {
|
||||
for (int64_t g = 0; i8 && g < n / 128; ++g) {
|
||||
hfwht128(v.data() + g * 128);
|
||||
float am = 0.0f;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
|
||||
am = std::fmax(am, std::fabs(v[(size_t)i]));
|
||||
const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
srow[g] = sc;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
|
||||
qrow[i] = (uint8_t)(int8_t)std::rint(
|
||||
std::fmin(std::fmax(v[(size_t)i] * inv, -127.0f), 127.0f));
|
||||
}
|
||||
for (int64_t g = 0; !i8 && g < n / 128; ++g) {
|
||||
float am = 0.0f;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
|
||||
am = std::fmax(am, std::fabs(v[(size_t)i]));
|
||||
|
||||
+117
-37
@@ -30,7 +30,7 @@ static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
struct Case {
|
||||
std::string name;
|
||||
int hd, gqa, kvh;
|
||||
bool fp8, causal, ragged, descale;
|
||||
bool i8, causal, ragged, descale; /* i8: the int8 cache, codes and two f16 scales a slot */
|
||||
int window;
|
||||
std::vector<int> qlen, ctx; /* per sequence */
|
||||
int missing_block = -1; /* sequence 0's block index to mark -1, or -1 */
|
||||
@@ -43,24 +43,24 @@ struct Case {
|
||||
};
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static Fn pick(int hd, int gqa, bool fp8, bool ahead) {
|
||||
static Fn pick(int hd, int gqa, bool i8, bool ahead) {
|
||||
if (ahead) {
|
||||
#define A(G) if (hd == 256 && gqa == G) return fp8 ? r4d_rad_attn_window_ahead_h256_gqa##G##_fp8 : r4d_rad_attn_window_ahead_h256_gqa##G##_bf16;
|
||||
#define A(G) if (hd == 256 && gqa == G) return i8 ? r4d_rad_attn_window_ahead_h256_gqa##G##_i8 : r4d_rad_attn_window_ahead_h256_gqa##G##_bf16;
|
||||
A(1) A(2) A(4) A(8)
|
||||
#undef A
|
||||
return nullptr;
|
||||
}
|
||||
#define P(H, G) if (hd == H && gqa == G) return fp8 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(128, 1) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
#define P(H, G) if (hd == H && gqa == G) return i8 ? r4d_rad_attn_window_h##H##_gqa##G##_i8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(128, 1) P(128, 4) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
P(512, 16)
|
||||
#undef P
|
||||
return nullptr;
|
||||
}
|
||||
static Fn pick_sink(int hd, int gqa, bool fp8) {
|
||||
static Fn pick_sink(int hd, int gqa, bool i8) {
|
||||
if (hd == 128 && gqa == 8)
|
||||
return fp8 ? r4d_rad_attn_window_sink_h128_gqa8_fp8 : r4d_rad_attn_window_sink_h128_gqa8_bf16;
|
||||
return i8 ? r4d_rad_attn_window_sink_h128_gqa8_i8 : r4d_rad_attn_window_sink_h128_gqa8_bf16;
|
||||
if (hd == 128 && gqa == 16)
|
||||
return fp8 ? r4d_rad_attn_window_sink_h128_gqa16_fp8 : r4d_rad_attn_window_sink_h128_gqa16_bf16;
|
||||
return i8 ? r4d_rad_attn_window_sink_h128_gqa16_i8 : r4d_rad_attn_window_sink_h128_gqa16_bf16;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -81,17 +81,45 @@ static int run(const Case& c) {
|
||||
* kernel that reads a masked key's V without guarding is caught */
|
||||
const int64_t slot = 2 * HD, nel = (int64_t)nblocks * kvh * 16 * slot;
|
||||
std::vector<float> kvf(nel);
|
||||
std::vector<uint16_t> kvb(nel); std::vector<uint8_t> kv8(nel);
|
||||
for (int64_t i = 0; i < nel; ++i) {
|
||||
float v = nrm();
|
||||
if (c.fp8) { kv8[i] = rad_f32_to_fp8e4m3(v * 4.f); kvf[i] = rad_fp8e4m3_to_f32(kv8[i]); }
|
||||
else { kvb[i] = rad_f32_to_bf16(v); kvf[i] = rad_bf16_to_f32(kvb[i]); }
|
||||
}
|
||||
std::vector<uint16_t> kvb(nel);
|
||||
for (int64_t i = 0; i < nel; ++i) { kvb[i] = rad_f32_to_bf16(nrm()); kvf[i] = rad_bf16_to_f32(kvb[i]); }
|
||||
/* The int8 cache's bytes, as kv_store_i8 lays a slot out: K codes, V codes, K's f16 scale, V's.
|
||||
* Each slot's two rows get their own magnitude, so a kernel that used one scale for another
|
||||
* key's codes is caught; kvf holds code times scale, what the reference reads. */
|
||||
const int64_t slot8 = 2 * HD + 4;
|
||||
std::vector<uint8_t> kvi(c.i8 ? (size_t)((int64_t)nblocks * kvh * 16 * slot8) : 0);
|
||||
if (c.i8)
|
||||
for (int64_t r = 0; r < (int64_t)nblocks * kvh * 16; ++r)
|
||||
for (int half = 0; half < 2; ++half) {
|
||||
const float mag = 0.25f + (float)(rng() % 64) / 8.0f;
|
||||
std::vector<float> v((size_t)HD);
|
||||
float am = 0.0f;
|
||||
for (int d = 0; d < HD; ++d) { v[(size_t)d] = nrm() * mag; am = std::max(am, std::fabs(v[(size_t)d])); }
|
||||
const _Float16 s16 = (_Float16)(am / 127.0f);
|
||||
const float sc = (float)s16;
|
||||
for (int d = 0; d < HD; ++d) {
|
||||
const float q = sc > 0.0f ? std::rint(v[(size_t)d] / sc) : 0.0f;
|
||||
const int8_t code = (int8_t)std::fmin(std::fmax(q, -127.0f), 127.0f);
|
||||
kvi[(size_t)(r * slot8 + half * HD + d)] = (uint8_t)code;
|
||||
kvf[(size_t)(r * slot + half * HD + d)] = (float)code * sc;
|
||||
}
|
||||
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD + 2 * half)], &s16, 2);
|
||||
}
|
||||
/* poison: every slot at or past a sequence's context in its last block, and every block no
|
||||
* table names */
|
||||
std::vector<char> named(nblocks, 0);
|
||||
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < maxb; ++b) if (bt[s * maxb + b] >= 0) named[bt[s * maxb + b]] = 1;
|
||||
auto poison = [&](int64_t i) { if (c.fp8) { kv8[i] = 0x7f; } else { kvb[i] = 0x7fc0; } kvf[i] = NAN; };
|
||||
/* An int8 slot is poisoned through its scales (an f16 NaN each), which every element of it is
|
||||
* multiplied by. */
|
||||
auto poison = [&](int64_t i) {
|
||||
if (c.i8) {
|
||||
const int64_t r = i / slot;
|
||||
const uint16_t nan16 = 0x7e00;
|
||||
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD)], &nan16, 2);
|
||||
std::memcpy(&kvi[(size_t)(r * slot8 + 2 * HD + 2)], &nan16, 2);
|
||||
} else { kvb[i] = 0x7fc0; }
|
||||
kvf[i] = NAN;
|
||||
};
|
||||
for (int blk = 0; blk < nblocks; ++blk) if (!named[blk]) for (int64_t i = 0; i < kvh * 16 * slot; ++i) poison((int64_t)blk * kvh * 16 * slot + i);
|
||||
for (int s = 0; s < n_seq; ++s) {
|
||||
const int last = (c.ctx[s] - 1) / 16, blk = bt[s * maxb + last];
|
||||
@@ -116,7 +144,8 @@ static int run(const Case& c) {
|
||||
for (int h = 0; h < qh; ++h) sinks[h] = h % 5 == 3 ? 6.f + nrm() : h % 7 == 6 ? -40.f : 1.5f * nrm();
|
||||
RadTensor t[9];
|
||||
t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols;
|
||||
t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot});
|
||||
t[1] = c.i8 ? tens(kvi.data(), RAD_I8, {nblocks, kvh, 16, slot8})
|
||||
: tens(kvb.data(), RAD_BF16, {nblocks, kvh, 16, slot});
|
||||
t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb});
|
||||
t[3] = tens(su.data(), RAD_I32, {n_seq});
|
||||
t[4] = c.descale ? tens(kd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
@@ -131,13 +160,13 @@ static int run(const Case& c) {
|
||||
auto pf = [&](const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); };
|
||||
pi("q_len", qmax + 3); /* the band bound, above the step's max */
|
||||
pi("head_dim", HD); pi("gqa", c.gqa); pi("block_size", 16); pi("causal", c.causal && !c.ahead); pi("window", c.window);
|
||||
ps("q_dtype", "bf16"); ps("kv_dtype", c.fp8 ? "fp8_e4m3" : "bf16");
|
||||
ps("q_dtype", "bf16"); ps("kv_dtype", c.i8 ? "i8" : "bf16");
|
||||
const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */
|
||||
pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq);
|
||||
if (c.max_ctx) pi("max_ctx", c.max_ctx);
|
||||
RadArgs a{}; a.t = t; a.n_t = c.sink ? 9 : 8; a.p = p.data(); a.n_p = (int)p.size();
|
||||
a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch;
|
||||
Fn fn = c.sink ? pick_sink(HD, c.gqa, c.fp8) : pick(HD, c.gqa, c.fp8, c.ahead);
|
||||
Fn fn = c.sink ? pick_sink(HD, c.gqa, c.i8) : pick(HD, c.gqa, c.i8, c.ahead);
|
||||
if (!fn) { std::printf("%-44s no entry point for this geometry\n", c.name.c_str()); return 1; }
|
||||
const int g0 = emu_grids;
|
||||
const int rc = fn(&a, nullptr);
|
||||
@@ -208,16 +237,31 @@ int main(int argc, char** argv) {
|
||||
0, 0, 512, 1},
|
||||
{"wmma h128 gqa1 swa w1024 ragged", 128, 1, 1, false, true, true, false, 1024, {150, 70},
|
||||
{300, 70}, -1, 0, 0, 0, 1},
|
||||
/* LFM3: h128, 16 query heads over 4 KV heads; full layers and a 256-token sliding window.
|
||||
* Prefill and chunked prefill past the decode leg's band, ragged steps with decode rows, a
|
||||
* query whose window starts inside the context, int8 cache */
|
||||
{"h128 gqa4 kvh4 full verify17 split", 128, 4, 4, false, true, false, false, 0, {17}, {300}, -1, 262144, s128},
|
||||
{"h128 gqa4 kvh4 swa w256 ragged", 128, 4, 4, false, true, true, false, 256, {1, 5, 40}, {600, 77, 300}},
|
||||
{"h128 gqa4 kvh2 swa w256 i8+descale split", 128, 4, 2, true, true, false, true, 256, {20}, {700}, -1, 4096, s128},
|
||||
{"h128 gqa4 kvh4 noncausal missing-block", 128, 4, 4, false, false, true, false, 0, {4, 2}, {37, 20}, 1},
|
||||
{"wmma h128 gqa4 kvh4 full prefill 200 of 900", 128, 4, 4, false, true, false, false, 0, {200}, {900},
|
||||
-1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh4 swa w256 prefill 300 of 900", 128, 4, 4, false, true, false, false, 256, {300},
|
||||
{900}, -1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh4 swa w256 ragged + decode rows", 128, 4, 4, false, true, true, false, 256,
|
||||
{150, 1, 70}, {500, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa4 kvh2 swa w256 i8+descale", 128, 4, 2, true, true, true, true, 256, {100, 90},
|
||||
{400, 90}, -1, 0, 0, 0, 1},
|
||||
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
|
||||
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
{"h256 gqa2 swa w64 ragged i8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
/* the real window, a context past it, a verify-sized query */
|
||||
{"h256 gqa2 swa w1024 verify16", 256, 2, 1, false, true, false, false, 1024, {16}, {1100}},
|
||||
/* split-KV decode: one row a sequence, long context, scratch present */
|
||||
{"h256 gqa2 swa w1024 decode split", 256, 2, 2, false, true, true, false, 1024, {1, 1}, {1300, 40}, -1, 0, s256},
|
||||
/* Gemma 4 full: h512, causal, no window, at the three TP ratios */
|
||||
{"h512 gqa8 full ragged bf16", 512, 8, 1, false, true, true, false, 0, {2, 7}, {90, 33}},
|
||||
{"h512 gqa8 full decode split fp8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa8 full decode split i8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa4 full verify16 split", 512, 4, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
|
||||
/* the serving case: max_ctx 262144 gives a decode step 64 splits, most of them empty */
|
||||
{"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512},
|
||||
@@ -226,7 +270,7 @@ int main(int argc, char** argv) {
|
||||
/* Gemma 4 12B full at TP1: 16 q heads over its one kv head, one position a tile; the
|
||||
* assistant's full layer is the same geometry at one row a sequence */
|
||||
{"h512 gqa16 full ragged bf16", 512, 16, 1, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}},
|
||||
{"h512 gqa16 full decode split fp8", 512, 16, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa16 full decode split i8", 512, 16, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa16 full verify16 split", 512, 16, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
|
||||
{"h512 gqa16 full decode, 3 seqs, 64 splits", 512, 16, 1, false, true, true, false, 0, {1, 1, 1}, {40, 90, 300}, -1, 262144, s512},
|
||||
{"h512 gqa16 kvh2 noncausal missing-block", 512, 16, 2, false, false, true, false, 0, {4, 2}, {37, 20}, 1},
|
||||
@@ -238,41 +282,55 @@ int main(int argc, char** argv) {
|
||||
{"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}},
|
||||
/* Prefill-shaped: the WMMA kernel (a 64-row query, or longer) */
|
||||
{"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
|
||||
{"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa8 prefill i8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa1 noncausal", 512, 1, 1, false, false, false, false, 0, {64}, {100}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa16 prefill 200 of 900", 512, 16, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
|
||||
{"wmma h512 gqa16 ragged + decode rows fp8+descale", 512, 16, 1, true, true, true, true, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa16 ragged + decode rows i8+descale", 512, 16, 1, true, true, true, true, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w1024 prefill 300 of 1500", 256, 2, 2, false, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w64 ragged i8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {80, 70}, {200, 70}, 3, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {64}, {64}, -1, 0, 0, 512, 1},
|
||||
{"wmma h256 gqa1 causal w5 fp8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa1 causal w5 i8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
|
||||
/* Gemma 4's picture runs, read again non-causally up to the run's end: 280 rows after a short
|
||||
* prefix, after one the window cuts, q at the fused plane's pitch, a run's tail after a prefix hit */
|
||||
{"wmma h256 gqa2 picture 280 of 300", 256, 2, 2, false, false, false, false, 1024, {280}, {300}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 picture 280 of 1500 fp8", 256, 2, 2, true, false, false, true, 1024, {280}, {1500}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 picture 280 of 1500 i8", 256, 2, 2, true, false, false, true, 1024, {280}, {1500}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 picture q-pitch slice", 256, 2, 2, false, false, false, false, 1024, {96}, {120}, -1, 0, 0, 512, 1},
|
||||
{"h256 gqa2 picture tail split", 256, 2, 2, false, false, false, false, 1024, {10}, {1300}, -1, 0, s256, 0, 0},
|
||||
/* a picture longer than the window, whose rows read every later key (attn_paged_ahead): the
|
||||
* window is 20 here, the rows 70 to 100, and the scalar, split and WMMA kernels all take it */
|
||||
{"h256 gqa2 ahead w20 verify-like", 256, 2, 2, false, false, false, false, 20, {6}, {70}, -1, 0, 0, 0, 0, true},
|
||||
{"h256 gqa2 ahead w20 ragged fp8", 256, 2, 2, true, false, true, true, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
|
||||
{"h256 gqa2 ahead w20 ragged i8", 256, 2, 2, true, false, true, true, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
|
||||
{"h256 gqa1 ahead w5 missing-block", 256, 1, 1, false, false, true, false, 5, {4, 2}, {37, 20}, 1, 0, 0, 0, 0, true},
|
||||
{"h256 gqa4 ahead w20 split", 256, 4, 1, false, false, false, false, 20, {5}, {300}, -1, 4096, s256, 0, 0, true},
|
||||
{"wmma h256 gqa2 ahead w20 picture 100 of 100", 256, 2, 2, false, false, false, false, 20, {100}, {100}, -1, 0, 0, 0, 1, true},
|
||||
{"wmma h256 gqa2 ahead w20 picture 90 of 300 fp8", 256, 2, 2, true, false, false, true, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
|
||||
{"wmma h256 gqa2 ahead w20 picture 90 of 300 i8", 256, 2, 2, true, false, false, true, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
|
||||
/* the int8 cache (kv_store_i8's slots) at Gemma 4 26B-A4B's two geometries: decode with the
|
||||
* split, a ragged verify, prefill on the WMMA kernel with a missing block, the sliding
|
||||
* window, a picture's non-causal rows and the open-ended window */
|
||||
{"h512 gqa8 i8 decode split", 512, 8, 1, true, true, false, false, 0, {1}, {700}, -1, 4096, s512, 0, -1, false},
|
||||
{"h512 gqa8 i8 verify ragged", 512, 8, 1, true, true, true, false, 0, {16, 3}, {300, 70}, -1, 0, 0, 0, 0, false},
|
||||
{"wmma h512 gqa8 i8 prefill 130", 512, 8, 1, true, true, false, false, 0, {130}, {130}, -1, 0, 0, 0, 1, false},
|
||||
{"wmma h512 gqa8 i8 ragged missing-block", 512, 8, 1, true, true, true, false, 0, {200, 70}, {900, 70}, 3, 0, 0, 0, 1, false},
|
||||
{"h256 gqa2 i8 swa w64 ragged", 256, 2, 2, true, true, true, false, 64, {1, 5, 40}, {200, 77, 140}, -1, 0, 0, 0, -1, false},
|
||||
{"h256 gqa2 i8 decode split", 256, 2, 2, true, true, false, false, 1024, {1}, {1300}, -1, 4096, s256, 0, -1, false},
|
||||
{"wmma h256 gqa2 i8 swa w1024 prefill 300 of 1500", 256, 2, 2, true, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1, false},
|
||||
{"wmma h256 gqa2 i8 picture 280 of 1500", 256, 2, 2, true, false, false, false, 1024, {280}, {1500}, -1, 0, 0, 0, 1, false},
|
||||
{"h256 gqa2 i8 ahead w20 ragged", 256, 2, 2, true, false, true, false, 20, {3, 1, 9}, {50, 64, 40}, -1, 0, 0, 0, 0, true},
|
||||
{"wmma h256 gqa2 i8 ahead w20 picture 90 of 300", 256, 2, 2, true, false, false, false, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
|
||||
/* LiLiCorr's drafter (attn_paged_sink): 32 query heads over 2 KV heads at h128 (16 over 1 at
|
||||
* TP 2), a block of 8 non-causal rows past the context, a 1024-token window; one sequence
|
||||
* and a batch, unsplit and split, a bf16 and an fp8 cache */
|
||||
* and a batch, unsplit and split, a bf16 and an int8 cache, and a prefill-shaped launch
|
||||
* that takes the WMMA kernel (with and without int8 descales) */
|
||||
{"sink h128 gqa16 kvh2 block8 w1024", 128, 16, 2, false, false, false, false, 1024, {8}, {1500},
|
||||
-1, 0, 0, 0, -1, false, true},
|
||||
{"sink h128 gqa16 kvh1 block8 x3 split", 128, 16, 1, false, false, true, false, 1024, {8, 8, 8},
|
||||
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa16 kvh2 fp8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300},
|
||||
{"sink h128 gqa16 kvh2 i8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300},
|
||||
-1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96},
|
||||
{400}, -1, 0, 0, 0, 0, false, true},
|
||||
{"sink h128 gqa16 prefill-shaped takes WMMA", 128, 16, 1, false, false, false, false, 1024, {96},
|
||||
{400}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa16 missing-block", 128, 16, 1, false, false, false, false, 1024, {8}, {70}, 1,
|
||||
0, 0, 0, -1, false, true},
|
||||
/* and at TP 4, 8 query heads over the rank's replicated KV head */
|
||||
@@ -280,10 +338,32 @@ int main(int argc, char** argv) {
|
||||
-1, 0, 0, 0, -1, false, true},
|
||||
{"sink h128 gqa8 kvh1 block8 x3 split", 128, 8, 1, false, false, true, false, 1024, {8, 8, 8},
|
||||
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa8 kvh1 fp8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300},
|
||||
{"sink h128 gqa8 kvh1 i8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300},
|
||||
-1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa8 prefill-shaped stays scalar", 128, 8, 1, false, false, false, false, 1024, {96},
|
||||
{400}, -1, 0, 0, 0, 0, false, true},
|
||||
{"sink h128 gqa8 prefill-shaped takes WMMA", 128, 8, 1, false, false, false, false, 1024, {96},
|
||||
{400}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 prefill-shaped WMMA i8+descale", 128, 8, 1, true, false, false, true, 1024,
|
||||
{96}, {400}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa16 prefill-shaped WMMA i8+descale", 128, 16, 1, true, false, false, true, 1024,
|
||||
{96}, {400}, -1, 0, 0, 0, 1, false, true},
|
||||
/* Recursive Flint (arch/flint): 32 query heads over 4 KV heads at h128 (gqa 8 at TP 1 and
|
||||
* 2), causal, a sink on every layer; the sliding layers' 513-token window and the full
|
||||
* layers' none. Prefill on the WMMA kernel, ragged with decode rows beside it and with a
|
||||
* missing block, and decode on the scalar kernel's split, at both caches. */
|
||||
{"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200", 128, 8, 4, false, true, false, false,
|
||||
513, {300}, {1200}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200 i8", 128, 8, 4, true, true, false, false,
|
||||
513, {300}, {1200}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 kvh2 causal full prefill 200 of 900 i8", 128, 8, 2, true, true, false, false,
|
||||
0, {200}, {900}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 kvh2 causal full ragged + decode rows", 128, 8, 2, false, true, true, false,
|
||||
0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 kvh2 causal w513 ragged missing-block i8", 128, 8, 2, true, true, true, false,
|
||||
513, {130, 70}, {700, 70}, 3, 0, 0, 0, 1, false, true},
|
||||
{"sink h128 gqa8 kvh4 causal w513 decode split i8", 128, 8, 4, true, true, true, false, 513,
|
||||
{1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa8 kvh4 causal full decode split", 128, 8, 4, false, true, true, false, 0,
|
||||
{1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true},
|
||||
/* and what must stay scalar: a verify batch, many sequences, a few rows each */
|
||||
{"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16},
|
||||
{40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0},
|
||||
@@ -295,7 +375,7 @@ int main(int argc, char** argv) {
|
||||
for (int it = 0; it < n; ++it) {
|
||||
Case c;
|
||||
c.hd = hds[rng() % 2]; c.gqa = gqas[rng() % 4]; c.kvh = 1 + rng() % 3;
|
||||
c.fp8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
|
||||
c.i8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
|
||||
c.window = rng() % 3 == 0 ? 0 : 1 + rng() % 200;
|
||||
const int ns = 1 + rng() % 4;
|
||||
const bool pre = rng() % 3 == 0; /* prefill-shaped: the WMMA kernel */
|
||||
@@ -311,7 +391,7 @@ int main(int argc, char** argv) {
|
||||
if (rng() % 2) c.max_ctx = 512;
|
||||
if (rng() % 5 == 0) c.missing_block = (int)(rng() % ((c.ctx[0] + 15) / 16));
|
||||
c.name = "sweep " + std::to_string(it) + " h" + std::to_string(c.hd) + " g" + std::to_string(c.gqa) +
|
||||
" kvh" + std::to_string(c.kvh) + (c.fp8 ? " fp8" : " bf16") + (c.causal ? " c" : " nc") +
|
||||
" kvh" + std::to_string(c.kvh) + (c.i8 ? " i8" : " bf16") + (c.causal ? " c" : " nc") +
|
||||
" w" + std::to_string(c.window) + (c.ragged ? " rag" : "");
|
||||
const int g0 = emu_grids;
|
||||
fails += run(c);
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT
|
||||
* emulator. The form the rule picks at each shape (the decode form at one and two column tiles a
|
||||
* wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile,
|
||||
* which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma
|
||||
* chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that
|
||||
* leaves the decode form's last wave group partly idle are covered; the output's pitch padding
|
||||
* stays untouched. The grouped row at GLM's MTP slices is held to a host restatement
|
||||
* (grouped_cases). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
/* The grouped row at GLM's MTP slices (288 experts, top 8) below 384 routed rows -- the small-M
|
||||
* form at gate_up, the expert-major form at down -- against a host restatement of the
|
||||
* per-element sequence: per 128 of K in order, the
|
||||
* 128-product sum of the emulated WMMA chain from zero, folded as raw * (activation scale *
|
||||
* weight scale) and added. Dropped slots inside runs and past the routed rows, runs longer than an
|
||||
* A tile, token and sorted rows, pointer tables over three slices a class. */
|
||||
static int grouped_cases(int& cases) {
|
||||
struct G {
|
||||
const char* name;
|
||||
int N, K;
|
||||
bool sorted_a;
|
||||
std::vector<int> live;
|
||||
int tail;
|
||||
const char* kernel;
|
||||
};
|
||||
const G all[] = {
|
||||
{ "MTP gate_up, one token", 512, 4096, false, { 1, 1, 1, 1, 1, 1, 1, 1 }, 0,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP gate_up, runs past one tile", 512, 4096, false, { 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }, 2,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP down, six tokens", 4096, 256, true, { 3, 1, 10, 2, 1, 5, 1, 1, 17, 4 },
|
||||
3, "(fp8_f32scale_experts<128, 4>)" },
|
||||
};
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
int fails = 0;
|
||||
std::mt19937 rng(77);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (const G& g : all) {
|
||||
const int E = 288, top = 8, N = g.N, K = g.K, kb = K / 128;
|
||||
std::vector<int> runs(E, 0);
|
||||
for (size_t i = 0; i < g.live.size(); ++i) runs[at[i]] = g.live[i];
|
||||
int routed = 0;
|
||||
for (int r : runs) routed += r;
|
||||
const int T = (routed + g.tail + top - 1) / top * top;
|
||||
const int Arows = g.sorted_a ? T : T / top, ap = K + 16, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
std::vector<float> as((size_t)Arows * kb);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
std::vector<uint8_t> w[2];
|
||||
std::vector<float> s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
w[q].resize((size_t)3 * N * K);
|
||||
s[q].resize((size_t)3 * (N / 128) * kb);
|
||||
for (auto& v : w[q]) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
for (auto& v : s[q]) v = std::exp2(oct(rng)) * 0.01f;
|
||||
for (int x = 0; x < E / 2; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % 3) * N * K);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % 3) * (N / 128) * kb);
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777), got((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int n = 0; n < N; ++n) {
|
||||
uint16_t& out = ref[(size_t)r * yp + n];
|
||||
out = 0;
|
||||
if (owner[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1;
|
||||
const bool rv = sorted[r] >= 0;
|
||||
const int ar = !rv ? -1 : g.sorted_a ? r : sorted[r] / top;
|
||||
const uint8_t* wr = (const uint8_t*)wt[q][(size_t)(e / 2)] + (size_t)n * K;
|
||||
const float* sr = (const float*)st[q][(size_t)(e / 2)] + (size_t)(n / 128) * kb;
|
||||
float acc = 0.f;
|
||||
for (int b = 0; b < kb; ++b) {
|
||||
float raw = 0.f;
|
||||
if (rv)
|
||||
for (int k = b * 128; k < b * 128 + 128; ++k)
|
||||
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + k]) *
|
||||
rad_fp8e4m3_to_f32(wr[k]);
|
||||
const float scale = rv ? as[(size_t)ar * kb + b] * sr[b] : 0.f;
|
||||
const float t = raw * scale;
|
||||
acc = acc + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &acc, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
auto ten3 = [](const void* const* tab, uint32_t dt, int64_t n0, int64_t n1, int64_t n2) {
|
||||
RadTensor t{};
|
||||
t.data = (void*)tab;
|
||||
t.dtype = dt;
|
||||
t.rank = 3;
|
||||
t.shape[0] = n0;
|
||||
t.shape[1] = n1;
|
||||
t.shape[2] = n2;
|
||||
t.stride[0] = 0;
|
||||
t.stride[1] = n2;
|
||||
t.stride[2] = 1;
|
||||
return t;
|
||||
};
|
||||
RadTensor t[9] = { mat(a.data(), RAD_F8E4M3, Arows, K, ap),
|
||||
mat(as.data(), RAD_F32, Arows, kb, kb),
|
||||
ten3(wt[0].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[0].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
ten3(wt[1].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[1].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
mat(got.data(), RAD_BF16, T, N, yp) };
|
||||
t[4].data = sorted.data();
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].data = offsets.data();
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = E + 1;
|
||||
t[5].stride[0] = 1;
|
||||
RadParam p[10]{};
|
||||
p[0] = { "M", RAD_P_INT, T / top };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "N_odd", RAD_P_INT, N };
|
||||
p[4] = { "K_odd", RAD_P_INT, K };
|
||||
p[5] = { "n_expert", RAD_P_INT, E };
|
||||
p[6] = { "top_k", RAD_P_INT, top };
|
||||
p[7] = { "group", RAD_P_INT, 128 };
|
||||
p[8].key = "a_order";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = g.sorted_a ? "sorted" : "token";
|
||||
p[9].key = "dtype";
|
||||
p[9].kind = RAD_P_STR;
|
||||
p[9].sval = "fp8a8f32";
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 10;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = r4d_rad_moe_fp8_f32scale(&ar, nullptr);
|
||||
size_t i = 0;
|
||||
while (i < got.size() && got[i] == ref[i]) ++i;
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, g.kernel) || i != got.size() ||
|
||||
live < routed * N / 2) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu of %zu, %d live\n",
|
||||
g.name, T, emu_last_kernel, g.kernel, rc, i, got.size(), live);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(31);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
const char* kernel;
|
||||
};
|
||||
const char* const dec1 = "(fp8_f32scale_decode<1, 1>)";
|
||||
const char* const dec2 = "(fp8_f32scale_decode<1, 2>)";
|
||||
const char* const rows = "fp8_f32scale_rows<R>";
|
||||
// Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column
|
||||
// tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096.
|
||||
const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 },
|
||||
{ 17, 256, 512, dec1 }, { 48, 128, 512, dec1 },
|
||||
{ 2, 128, 256, dec1 }, { 5, 256, 128, dec1 },
|
||||
{ 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 },
|
||||
{ 20, 640, 256, dec2 }, { 70, 128, 384, rows },
|
||||
{ 130, 128, 256, rows }, { 33, 4096, 512, rows },
|
||||
{ 70, 4096, 128, rows } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K);
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
|
||||
// summation order shows through the bf16 output.
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap),
|
||||
mat(as.data(), RAD_F32, M, kb, kb),
|
||||
mat(w.data(), RAD_F8E4M3, N, K, K),
|
||||
mat(ws.data(), RAD_F32, N / 128, kb, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
// The pitch off 16 bytes takes the legacy tile.
|
||||
auto run = [&](bool legacy, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * yp, 0x7777);
|
||||
t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp)
|
||||
: mat(a.data(), RAD_F8E4M3, M, K, ap);
|
||||
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return r4d_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> legacy, got;
|
||||
++cases;
|
||||
if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) {
|
||||
std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int nonzero = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0;
|
||||
if (nonzero < M * N / 2) {
|
||||
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
|
||||
++fails;
|
||||
}
|
||||
++cases;
|
||||
const int rc = run(false, got);
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) {
|
||||
size_t i = 0;
|
||||
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
|
||||
std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n",
|
||||
emu_last_kernel, sh.kernel, M, N, K, rc, i);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
fails += grouped_cases(cases);
|
||||
{
|
||||
/* A run of rows and a slice of columns give the bytes the whole product has there: GLM's
|
||||
* MLA split by rows computes q_b and o over a rank's rows at full width, the head form
|
||||
* over every row at a slice of the columns (or of K, as eight rank partials). */
|
||||
const int M = 130, N = 1024, K = 512, kb = K / 128, r0 = 37, mr = 33, c0 = 256, nc = 256;
|
||||
std::vector<uint8_t> a((size_t)M * K), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
auto gemm = [&](int rows, int cols, int row0, int col0, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)rows * cols, 0x7777);
|
||||
RadTensor t[7] = { mat(a.data() + (size_t)row0 * K, RAD_F8E4M3, rows, K, K),
|
||||
mat(as.data() + (size_t)row0 * kb, RAD_F32, rows, kb, kb),
|
||||
mat(w.data() + (size_t)col0 * K, RAD_F8E4M3, cols, K, K),
|
||||
mat(ws.data() + (size_t)(col0 / 128) * kb, RAD_F32, cols / 128, kb,
|
||||
kb),
|
||||
mat(y.data(), RAD_BF16, rows, cols, cols), RadTensor{}, RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, rows };
|
||||
p[1] = { "N", RAD_P_INT, cols };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return r4d_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> whole, part;
|
||||
++cases;
|
||||
bool same = gemm(M, N, 0, 0, whole) == RAD_OK && gemm(mr, nc, r0, c0, part) == RAD_OK;
|
||||
for (int r = 0; same && r < mr; ++r)
|
||||
for (int c = 0; c < nc; ++c)
|
||||
same = same && part[(size_t)r * nc + c] == whole[(size_t)(r0 + r) * N + c0 + c];
|
||||
std::printf("%s rows %d..%d x columns %d..%d alone against the %dx%d product\n",
|
||||
same ? "ok " : "FAIL", r0, r0 + mr, c0, c0 + nc, M, N);
|
||||
fails += !same;
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -1,405 +0,0 @@
|
||||
/* tests/r4d_emu: the M2XFP4 x fp8 GEMMs (r4d_gemm_m2xfp4a8_decode.hip, r4d_gemm_m2xfp4a8_tiled.hip)
|
||||
* on the host SIMT emulator. The container's m2xfp4 encoding (the paper's weight-side Sg-EM,
|
||||
* arXiv 2601.19213 §4.4.2) is synthesised from random f32 weights by an in-test scalar quantiser
|
||||
* implementing the spec: per group of 32 columns an E8M0 exponent with the adaptive bias (-1, 0, 1,
|
||||
* drawn at random) folded into the stored byte, and a meta byte of four two-bit subgroup
|
||||
* multipliers with k = 3 in heavy rotation; the codes are the e2m1 roundings of the exact
|
||||
* dequantiser's inverse.
|
||||
* The stored bytes are then built the way r4d_rad_relayout_m2xfp4 builds them (fragment-order
|
||||
* codes, the meta plane appended in the exponents' [K/32][N] order), and both kernels run against
|
||||
* an f64 CPU reference of the exact decode, at the FP8 WMMA's tolerance plus the table's accepted
|
||||
* k = 3 rounding (rel_l2 < 4e-2, see run_cases). Cases cover both activation scale grids (per row,
|
||||
* per (row, 128) with a zero block), M across the decode band's band edges (1, 8, 16, 40, 128) and
|
||||
* the tiled row's, the one-fragment prefetch form (M <= 16), both K slabs (64 and 128), and a
|
||||
* split-K launch on the decode kernel.
|
||||
*
|
||||
* The table itself is held to arithmetic first: every kM2xfp4Mag[d][k] cell must be the
|
||||
* round-to-nearest-even e4m3 of e2m1mag * (1 + k/4) * 2^-d; the k = 0..2 rows must be exact while
|
||||
* the product is a normal e4m3 value, and the k = 3 odd-mantissa entries must be the tie's even
|
||||
* side (2.5, 5, 10 scaled by 2^-d). The unpack is held to the same arithmetic over every code at
|
||||
* every (d, k).
|
||||
*
|
||||
* The declaration side (r4d_rows.cpp) is not in the emu build, so the two cfg readers it defines,
|
||||
* which the units' plugin entries call, are stubbed in cfg_stub.cpp at their axis defaults (0 = the
|
||||
* kernels' own rules), which is what an untuned call gets. This test calls the raw entries, so it
|
||||
* runs no stub; everything it runs is the library's own code.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d.h"
|
||||
#include "r4d_m2xfp4.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
/* ------------------------------------------------------------------ arithmetic e4m3 / e2m1 */
|
||||
|
||||
/* Round-to-nearest-even e4m3 (OCP FP8, 1-4-3, bias 7, subnormals at 2^-9, 0x7F/0xFF NaN), the
|
||||
* conversion the device tables and the WMMA's own converts use. */
|
||||
static uint8_t rne_e4m3(double v) {
|
||||
if (v == 0) return std::signbit(v) ? 0x80 : 0; /* the kernels keep a sign on zero */
|
||||
const uint8_t sign = v < 0 ? 0x80 : 0;
|
||||
double a = std::fabs(v);
|
||||
if (a > 480) return (uint8_t)(sign | 0x7E);
|
||||
int e = 0;
|
||||
while (a >= 2.0) { a *= 0.5; ++e; }
|
||||
while (a < 1.0) { a *= 2.0; --e; }
|
||||
int m;
|
||||
if (e < -6) { /* subnormal: 2^-9 steps of the value itself */
|
||||
double q = std::fabs(v) * 512.0;
|
||||
double fl = std::floor(q);
|
||||
const double frac = q - fl;
|
||||
int qi = (int)fl;
|
||||
if (frac > 0.5 || (frac == 0.5 && (qi & 1))) ++qi;
|
||||
if (qi >= 8) return (uint8_t)(sign | 0x08); /* up to min normal 2^-6 */
|
||||
return (uint8_t)(sign | qi);
|
||||
}
|
||||
double q = (a - 1.0) * 8.0;
|
||||
m = (int)q;
|
||||
const double frac = q - m;
|
||||
if (frac > 0.5 || (frac == 0.5 && (m & 1))) ++m;
|
||||
if (m == 8) { m = 0; ++e; }
|
||||
return (uint8_t)(sign | ((e + 7) << 3) | m);
|
||||
}
|
||||
|
||||
static double e4m3_f64(uint8_t b) {
|
||||
const double s = b & 0x80 ? -1.0 : 1.0;
|
||||
const int e = (b >> 3) & 15, m = b & 7;
|
||||
if (e == 0) return s * m * 0.001953125; /* 2^-9 steps */
|
||||
return s * std::ldexp(1.0 + m / 8.0, e - 7);
|
||||
}
|
||||
|
||||
/* The e2m1 magnitudes, and the quantiser's RNE code for a magnitude against them (ties to the even
|
||||
* code, as the hardware's convert and the CPU reference agree). */
|
||||
static const double kE2m1Mag[8] = { 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 };
|
||||
static uint8_t rne_e2m1(double v) {
|
||||
double a = std::fabs(v);
|
||||
int best = 0;
|
||||
double bd = 1e300;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const double d = std::fabs(a - kE2m1Mag[i]);
|
||||
if (d < bd || (d == bd && !(best & 1))) { bd = d; best = i; }
|
||||
}
|
||||
return (uint8_t)(best | (v < 0 ? 8 : 0));
|
||||
}
|
||||
static double e2m1_f64(uint8_t code) {
|
||||
return (code & 8 ? -1.0 : 1.0) * kE2m1Mag[code & 7];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the table checks */
|
||||
|
||||
static int check_lut() {
|
||||
int fails = 0;
|
||||
for (int d = 0; d < 16; ++d)
|
||||
for (int k = 0; k < 4; ++k)
|
||||
for (int m = 0; m < 8; ++m) {
|
||||
const uint8_t got = (uint8_t)((kM2xfp4Mag[d][k][m >> 2] >> (8 * (m & 3))) & 0xFF);
|
||||
const double exact = kE2m1Mag[m] * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
|
||||
const uint8_t want = rne_e4m3(exact);
|
||||
if (got != want) {
|
||||
std::printf("FAIL lut d=%d k=%d mag=%d: %02x, want %02x (%.6g)\n", d, k, m,
|
||||
got, want, exact);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
/* k = 0..2 exact wherever the product is a normal e4m3 value; k = 3 only the
|
||||
* odd-mantissa magnitudes round, and to the tie's even side. */
|
||||
if (e4m3_f64(got) != exact) {
|
||||
const bool k3tie = k == 3 && (m == 3 || m == 5 || m == 7);
|
||||
const double rounded = k3tie ? std::ldexp(m == 3 ? 2.5 : m == 5 ? 5.0 : 10.0, -d)
|
||||
: exact;
|
||||
if (k3tie && e4m3_f64(got) == rounded) continue;
|
||||
/* the subnormal floor: like r4d_mxfp4.h's table one binade earlier, the 2^-9
|
||||
* step rounds once the product falls in it; exactness is only claimed while
|
||||
* the product is normal (>= 2^-6), and every k = 0..2 normal product is */
|
||||
if (k <= 2 && exact >= 0.015625 && std::fabs(exact) > 0) {
|
||||
std::printf("FAIL lut k=%d d=%d mag=%d: %02x decodes %.6g, want %.6g\n", k,
|
||||
d, m, got, e4m3_f64(got), exact);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* and the k = 0 rows are r4d_mxfp4.h's, byte for byte (a memcmp would walk the [k] axis) */
|
||||
static const unsigned kM0[16][2] = {
|
||||
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u}, {0x2c282000u, 0x3c383430u},
|
||||
{0x24201800u, 0x34302c28u}, {0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
|
||||
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u}, {0x03020100u, 0x0c080604u},
|
||||
{0x02010000u, 0x06040302u}, {0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
|
||||
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u},
|
||||
};
|
||||
for (int d = 0; d < 16; ++d)
|
||||
if (kM2xfp4Mag[d][0][0] != kM0[d][0] || kM2xfp4Mag[d][0][1] != kM0[d][1]) {
|
||||
std::printf("FAIL lut: the k=0 row d=%d is not kMxfp4Mag\n", d);
|
||||
++fails;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The unpack against arithmetic, over every 16-bit pattern at both halves of a word and random
|
||||
* words, at every (d, k). */
|
||||
static int check_unpack() {
|
||||
int fails = 0;
|
||||
auto one = [&](uint32_t word, int d, int k) {
|
||||
uint32_t lo = 0, hi = 0;
|
||||
r4d_m2xfp4_unpack8(word, d, k, &lo, &hi);
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const uint8_t code = (uint8_t)((word >> (4 * j)) & 0xF);
|
||||
const uint8_t got = (uint8_t)((j < 4 ? (lo >> (8 * j)) : (hi >> (8 * (j - 4)))) & 0xFF);
|
||||
const double exact = e2m1_f64(code) * (1.0 + k / 4.0) * std::ldexp(1.0, -d);
|
||||
const uint8_t want = rne_e4m3(exact);
|
||||
if (got != want) {
|
||||
if (fails < 12)
|
||||
std::printf("FAIL unpack w=%08x d=%d k=%d j=%d: %02x, want %02x\n", word, d, k,
|
||||
j, got, want);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
};
|
||||
for (int d = 0; d < 16; ++d)
|
||||
for (int k = 0; k < 4; ++k) {
|
||||
for (uint32_t v = 0; v < 65536; ++v) {
|
||||
one(v, d, k);
|
||||
if (v < 256) { one(v << 24, d, k); one(v << 16, d, k); }
|
||||
}
|
||||
}
|
||||
std::mt19937 rng(11);
|
||||
for (int i = 0; i < 20000; ++i) one(rng(), (int)(rng() % 16), (int)(rng() % 4));
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the GEMM cases */
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
const char* kernel; // the decode row's two forms, or the tiled row
|
||||
int M, N, K;
|
||||
bool ablk; // the activation scale per (row, 128 of K), with a zero block
|
||||
int ks; // the decode launch's split (0 = the kernel's rule)
|
||||
};
|
||||
|
||||
/* The in-test quantiser's planes for one weight [N][K]: codes (packed e2m1, element 2j in bits
|
||||
* 0-3 of byte j), the per-(row, 32) exponents with the bias folded in, the meta bytes, and the
|
||||
* f64 exact dequant the reference multiplies. */
|
||||
struct M2Weight {
|
||||
std::vector<uint8_t> codes; // [N][K/2]
|
||||
std::vector<uint8_t> scale; // [N][K/32]
|
||||
std::vector<uint8_t> meta; // [N][K/32]
|
||||
std::vector<double> exact; // [N][K], the spec's decode
|
||||
};
|
||||
|
||||
static M2Weight m2_quantise(const std::vector<float>& w, int N, int K, std::mt19937& rng) {
|
||||
const int nblk = K / 32;
|
||||
M2Weight m;
|
||||
m.codes.assign((size_t)N * K / 2, 0);
|
||||
m.scale.assign((size_t)N * nblk, 0);
|
||||
m.meta.assign((size_t)N * nblk, 0);
|
||||
m.exact.assign((size_t)N * K, 0.0);
|
||||
std::uniform_int_distribution<int> bias(-1, 1);
|
||||
for (int n = 0; n < N; ++n)
|
||||
for (int b = 0; b < nblk; ++b) {
|
||||
double absmax = 0.0;
|
||||
for (int j = 0; j < 32; ++j) absmax = std::max(absmax, (double)std::fabs(w[(size_t)n * K + b * 32 + j]));
|
||||
/* the exponent the six-magnitude grid needs, plus the adaptive bias, folded into the
|
||||
* stored byte; a zero group keeps a small exponent, its codes all zero */
|
||||
int e8 = absmax > 0 ? (int)std::ceil(std::log2(absmax / 6.0)) : -30;
|
||||
e8 += bias(rng);
|
||||
if (e8 < -30) e8 = -30;
|
||||
if (e8 > 30) e8 = 30;
|
||||
const uint8_t sbyte = (uint8_t)(e8 + 127);
|
||||
uint8_t mbyte = 0;
|
||||
for (int s = 0; s < 4; ++s) {
|
||||
/* k = 3 in heavy rotation, the multiplier the rounding lives on */
|
||||
const int k = (n + b + s * 3 + (int)(rng() % 2)) & 3;
|
||||
mbyte |= k << (2 * s);
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int col = b * 32 + s * 8 + j;
|
||||
const double scale = std::ldexp(1.0 + k / 4.0, e8);
|
||||
const uint8_t code = rne_e2m1(w[(size_t)n * K + col] / scale);
|
||||
m.codes[(size_t)n * K / 2 + col / 2] |=
|
||||
(uint8_t)(code << (4 * (col & 1)));
|
||||
m.exact[(size_t)n * K + col] =
|
||||
e2m1_f64(code) * std::ldexp(1.0, e8) * (1.0 + k / 4.0);
|
||||
}
|
||||
}
|
||||
m.scale[(size_t)n * nblk + b] = sbyte;
|
||||
m.meta[(size_t)n * nblk + b] = mbyte;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/* The stored weight, as r4d_rad_relayout_m2xfp4 writes it: codes in WMMA fragment order, then the
|
||||
* meta plane in the exponents' [K/32][N] order, and the exponent plane and per-row reference
|
||||
* beside them. */
|
||||
static void m2_store(const M2Weight& m, int N, int K, std::vector<uint8_t>* wq,
|
||||
std::vector<uint8_t>* ws, std::vector<uint8_t>* wm,
|
||||
std::vector<uint8_t>* wref) {
|
||||
const int nblk = K / 32;
|
||||
wq->assign((size_t)N * K / 2 + (size_t)nblk * N, 0);
|
||||
ws->assign((size_t)nblk * N, 0);
|
||||
wm->assign((size_t)nblk * N, 0);
|
||||
wref->assign(N, 0);
|
||||
/* fragment order: slot = ((t * ks + ksi) * 32 + lh * 16 + r) * 4 + bin, element 2j in the low
|
||||
* nibble of byte j (r4d_layout.cpp, mx_slot) */
|
||||
const int ks16 = K / 16;
|
||||
for (int n = 0; n < N; ++n) {
|
||||
const int t = n / 16, r = n % 16;
|
||||
uint8_t ref = 0;
|
||||
for (int b = 0; b < nblk; ++b) {
|
||||
const uint8_t s = m.scale[(size_t)n * nblk + b];
|
||||
(*ws)[(size_t)b * N + n] = s;
|
||||
(*wm)[(size_t)b * N + n] = m.meta[(size_t)n * nblk + b];
|
||||
if (s > ref) ref = s;
|
||||
}
|
||||
(*wref)[n] = ref;
|
||||
for (int k = 0; k < K; ++k) {
|
||||
const uint8_t code = (uint8_t)((m.codes[(size_t)n * K / 2 + k / 2] >> (4 * (k & 1))) & 0xF);
|
||||
const int ksi = k / 16, kin = k % 16;
|
||||
const int lh = kin / 8, bin = (kin % 8) / 2;
|
||||
const size_t idx = (size_t)((t * ks16 + ksi) * 32 + lh * 16 + r) * 4 + bin;
|
||||
(*wq)[idx] |= (uint8_t)(code << (4 * (k & 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static double bf16_f64(uint16_t h) {
|
||||
const double s = h & 0x8000 ? -1.0 : 1.0;
|
||||
const int e = (h >> 7) & 0xFF, m = h & 0x7F;
|
||||
if (e == 0) return s * m * std::ldexp(1.0, -133); /* zero / bf16 subnormal */
|
||||
return s * std::ldexp(1.0 + m / 128.0, e - 127);
|
||||
}
|
||||
|
||||
static int run_cases() {
|
||||
static const Case all[] = {
|
||||
{ "decode1, K 128, rule split 16, per-row scales",
|
||||
"(r4d_gemm_m2xfp4a8_decode1_kernel<128, 16, false, false>)", 1, 48, 128, false, 0 },
|
||||
{ "decode1, K 64, split 4", "(r4d_gemm_m2xfp4a8_decode1_kernel<64, 4, false, false>)",
|
||||
8, 16, 64, false, 4 },
|
||||
{ "decode1, M 16, block scales", "(r4d_gemm_m2xfp4a8_decode1_kernel<128, 2, false, true>)",
|
||||
16, 128, 256, true, 2 },
|
||||
{ "decode, M 40 three fragments, odd K slab 192",
|
||||
"(r4d_gemm_m2xfp4a8_decode_kernel<64, 1, 3, false, false>)", 40, 272, 192, false, 1 },
|
||||
{ "decode, M 128 all fragments, block scales with a zero block",
|
||||
"(r4d_gemm_m2xfp4a8_decode_kernel<128, 1, 8, false, true>)", 128, 128, 128, true, 1 },
|
||||
{ "tiled, TN 2 just past the decode band, wide slab",
|
||||
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, false>)", 129, 64, 128, false, 0 },
|
||||
{ "tiled, TN 2, K 192 takes the 64 slab",
|
||||
"(r4d_gemm_m2xfp4a8_tiled_kernel<2, 64, false>)", 300, 64, 192, false, 0 },
|
||||
{ "tiled, TN 2, block scales", "(r4d_gemm_m2xfp4a8_tiled_kernel<2, 128, true>)",
|
||||
256, 128, 128, true, 0 },
|
||||
};
|
||||
int fails = 0, cases = 0;
|
||||
for (const Case& c : all) {
|
||||
std::mt19937 rng(2000 + cases);
|
||||
std::normal_distribution<double> nd(0.0, 1.0);
|
||||
const int nkb = (c.K + 127) / 128;
|
||||
/* random f32 weights -> the m2xfp4 planes */
|
||||
std::vector<float> wf((size_t)c.N * c.K);
|
||||
for (auto& v : wf) v = (float)(3.5 * nd(rng));
|
||||
const M2Weight m = m2_quantise(wf, c.N, c.K, rng);
|
||||
std::vector<uint8_t> wq, ws, wm, wref;
|
||||
m2_store(m, c.N, c.K, &wq, &ws, &wm, &wref);
|
||||
/* fp8 activations and their grid. The bytes are the quantised values; the grid's scale is
|
||||
* applied once, where the kernel applies it: per row in the epilogue, per (row, 128) at
|
||||
* each boundary -- the reference multiplies the same way. */
|
||||
const int PA = c.ablk ? nkb : 1;
|
||||
std::vector<uint8_t> a((size_t)c.M * c.K);
|
||||
std::vector<float> as((size_t)c.M * PA);
|
||||
for (int i = 0; i < c.M; ++i)
|
||||
for (int q = 0; q < PA; ++q) {
|
||||
/* block 1 of every fourth row is zero: the carried-scale path */
|
||||
const float s = c.ablk && i % 4 == 1 && q == 1
|
||||
? 0.0f
|
||||
: std::ldexp(1.0f, (int)((rng() % 7) - 3)) * (1.0f + (rng() % 97) / 97.0f);
|
||||
as[(size_t)i * PA + q] = s;
|
||||
}
|
||||
for (int i = 0; i < c.M; ++i)
|
||||
for (int k = 0; k < c.K; ++k) {
|
||||
const float block_scale = as[(size_t)i * PA + (c.ablk ? k / 128 : 0)];
|
||||
const float v = (float)(nd(rng) * 2.0);
|
||||
/* a zero-scale block's activation bytes are zero (the block-scaled quantisers
|
||||
* produce nothing there), and the kernels carry the previous scale through */
|
||||
a[(size_t)i * c.K + k] =
|
||||
block_scale == 0.0f ? 0 : rne_e4m3(v / block_scale);
|
||||
}
|
||||
/* the f64 reference: the activation's bytes (times the block grid, when there is one) and
|
||||
* the exact weight decode, which already carries its 2^(scale - 127) */
|
||||
std::vector<double> reff((size_t)c.M * c.N);
|
||||
for (int i = 0; i < c.M; ++i)
|
||||
for (int n = 0; n < c.N; ++n) {
|
||||
double acc = 0.0;
|
||||
for (int k = 0; k < c.K; ++k)
|
||||
acc += e4m3_f64(a[(size_t)i * c.K + k]) *
|
||||
(c.ablk ? (double)as[(size_t)i * PA + k / 128] : 1.0) *
|
||||
m.exact[(size_t)n * c.K + k];
|
||||
if (!c.ablk) acc *= (double)as[(size_t)i];
|
||||
reff[(size_t)i * c.N + n] = acc;
|
||||
}
|
||||
/* launch. The scratch is sized for the widest split the band's rule can pick (16), which
|
||||
* the ABI's scratch hook bounds the same way; the arrival counters are the unit's own,
|
||||
* one block per output buffer. */
|
||||
std::vector<uint16_t> got((size_t)c.M * c.N, 0x7777);
|
||||
const long wq_ptr = (long)(uintptr_t)wq.data();
|
||||
const long scratch_bytes = 16l * c.M * c.N * (long)sizeof(float);
|
||||
std::vector<float> scratch((size_t)(scratch_bytes / sizeof(float)), 0.0f);
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
if (std::strstr(c.kernel, "tiled")) {
|
||||
std::vector<uint8_t> at((size_t)r4d_m2xfp4a8_tile_a_bytes(c.M, c.K));
|
||||
r4d_m2xfp4a8_tile_a((long)(uintptr_t)a.data(), (long)(uintptr_t)at.data(), c.M, c.K,
|
||||
0, 0);
|
||||
r4d_gemm_m2xfp4a8_tiled((long)(uintptr_t)at.data(), (long)(uintptr_t)as.data(),
|
||||
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
|
||||
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
|
||||
c.M, c.K, c.N, 0, c.ablk ? 128 : 0, PA,
|
||||
0, c.N, c.N);
|
||||
} else {
|
||||
r4d_gemm_m2xfp4a8_decode((long)(uintptr_t)a.data(), (long)(uintptr_t)as.data(),
|
||||
wq_ptr, (long)(uintptr_t)ws.data(), (long)(uintptr_t)wm.data(),
|
||||
(long)(uintptr_t)wref.data(), (long)(uintptr_t)got.data(),
|
||||
c.M, c.K, c.N, c.ks, 0, 0, c.ablk ? 128 : 0, PA,
|
||||
(long)(uintptr_t)scratch.data(), scratch_bytes, 0, 0, c.N,
|
||||
c.N);
|
||||
}
|
||||
/* every launch lands on one form; a moved bound shows by name */
|
||||
if (!std::strstr(emu_last_kernel, c.kernel)) {
|
||||
std::printf("FAIL %s: ran %s, want %s\n", c.name,
|
||||
emu_last_kernel ? emu_last_kernel : "(nothing)", c.kernel);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
double num = 0, den = 0, worst = 0;
|
||||
for (size_t i = 0; i < reff.size(); ++i) {
|
||||
const double d = bf16_f64(got[i]) - reff[i];
|
||||
num += d * d;
|
||||
den += reff[i] * reff[i];
|
||||
worst = std::max(worst, std::fabs(d) / (std::fabs(reff[i]) + 1e-3));
|
||||
}
|
||||
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
|
||||
/* The FP8 WMMA's tolerance, plus the table's accepted k = 3 rounding: the mxfp4 row's
|
||||
* 1e-2 with the ~1.2% whole-dot contribution a full rotation of k = 3 subgroups adds
|
||||
* (a quarter of the weights at up to 2^-4.4 each). Cancellation can make a single
|
||||
* element's relative error unbounded, so the aggregate is what is held. */
|
||||
if (rel >= 4e-2) {
|
||||
std::printf("FAIL %s: rel_l2 %.3e, worst %.3e\n", c.name, rel, worst);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d gemm case(s), %d failure(s)\n", cases, fails);
|
||||
return fails;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_lut();
|
||||
fails += check_unpack();
|
||||
fails += run_cases();
|
||||
if (fails) std::printf("FAIL m2xfp4 (%d)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -8,11 +8,6 @@
|
||||
* wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past
|
||||
* every output and the gate's untouched rows show an overrun.
|
||||
*
|
||||
* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes,
|
||||
* scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the
|
||||
* clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the
|
||||
* sigmoid underflows, and NaN and infinite inputs.
|
||||
*
|
||||
* moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself
|
||||
* without, and the inverse against the table the gather builds from `sorted`; then moe_gather's
|
||||
* kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at
|
||||
@@ -370,152 +365,6 @@ void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
}
|
||||
}
|
||||
|
||||
struct QuantShape {
|
||||
int M, n;
|
||||
float limit;
|
||||
int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */
|
||||
bool y; /* the fused op also writes the bf16 product */
|
||||
};
|
||||
|
||||
void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const QuantShape shapes[] = {
|
||||
{ 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false },
|
||||
{ 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true },
|
||||
{ 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true },
|
||||
{ 2, 260, 0.5f, 2, false },
|
||||
};
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> ud(0, 15);
|
||||
for (const QuantShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, nkb = (n + 127) / 128;
|
||||
const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3;
|
||||
std::vector<uint16_t> gu((size_t)M * gp, f2b(-3.f));
|
||||
const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < 2 * n; ++c) {
|
||||
float v = nd(rng) * 6.f;
|
||||
uint16_t h = f2b(v);
|
||||
if (sh.mode == 1) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = lim;
|
||||
else if (pick == 1)
|
||||
h = past;
|
||||
else if (pick == 2)
|
||||
h = (uint16_t)(lim | 0x8000u);
|
||||
else if (pick == 3)
|
||||
h = (uint16_t)(past | 0x8000u);
|
||||
else if (pick == 4)
|
||||
h = f2b(-200.f);
|
||||
/* rows divisible by 3 hold an all-zero first group */
|
||||
if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0;
|
||||
} else if (sh.mode == 2) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = 0x7fc0; /* NaN */
|
||||
else if (pick == 1)
|
||||
h = 0x7f80; /* +inf */
|
||||
else if (pick == 2)
|
||||
h = 0xff80; /* -inf */
|
||||
}
|
||||
gu[(size_t)r * gp + c] = h;
|
||||
}
|
||||
RadTensor t[4]{};
|
||||
t[0].data = gu.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = 2 * n;
|
||||
t[0].stride[0] = gp;
|
||||
t[0].stride[1] = 1;
|
||||
auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) {
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = pitch;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
RadParam pc[4]{};
|
||||
pc[0] = { "M", RAD_P_INT, M };
|
||||
pc[1] = { "n", RAD_P_INT, n };
|
||||
pc[2].key = "limit";
|
||||
pc[2].kind = RAD_P_F64;
|
||||
pc[2].dval = sh.limit;
|
||||
pc[3].key = "dtype";
|
||||
pc[3].kind = RAD_P_STR;
|
||||
pc[3].sval = "bf16";
|
||||
RadParam pq[4]{};
|
||||
pq[0] = { "M", RAD_P_INT, M };
|
||||
pq[1] = { "n", RAD_P_INT, n };
|
||||
pq[2] = { "group", RAD_P_INT, 128 };
|
||||
pq[3].key = "dtype";
|
||||
pq[3].kind = RAD_P_STR;
|
||||
pq[3].sval = "bf16";
|
||||
RadParam pf[5]{};
|
||||
pf[0] = pc[0];
|
||||
pf[1] = pc[1];
|
||||
pf[2] = pc[2];
|
||||
pf[3] = pq[2];
|
||||
pf[4] = pc[3];
|
||||
|
||||
std::vector<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
|
||||
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
|
||||
std::vector<float> s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f);
|
||||
RadTensor tc[2] = { t[0], {} };
|
||||
mat(tc[1], RAD_BF16, M, n, yp);
|
||||
tc[1].data = y_ref.data();
|
||||
RadArgs ac{};
|
||||
ac.t = tc;
|
||||
ac.n_t = 2;
|
||||
ac.p = pc;
|
||||
ac.n_p = 4;
|
||||
RadTensor tq[3] = { tc[1], {}, {} };
|
||||
mat(tq[1], RAD_F8E4M3, M, n, qp);
|
||||
tq[1].data = q_ref.data();
|
||||
mat(tq[2], RAD_F32, M, nkb, sp);
|
||||
tq[2].data = s_ref.data();
|
||||
RadArgs aq{};
|
||||
aq.t = tq;
|
||||
aq.n_t = 3;
|
||||
aq.p = pq;
|
||||
aq.n_p = 4;
|
||||
++cases;
|
||||
if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK ||
|
||||
r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
RadTensor tf[4] = { t[0], {}, {}, {} };
|
||||
mat(tf[1], RAD_F8E4M3, M, n, qp);
|
||||
tf[1].data = q.data();
|
||||
mat(tf[2], RAD_F32, M, nkb, sp);
|
||||
tf[2].data = s.data();
|
||||
mat(tf[3], RAD_BF16, M, n, yp);
|
||||
tf[3].data = sh.y ? y.data() : nullptr;
|
||||
RadArgs af{};
|
||||
af.t = tf;
|
||||
af.n_t = 4;
|
||||
af.p = pf;
|
||||
af.n_p = 5;
|
||||
const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr);
|
||||
int bad = 0;
|
||||
bad += q != q_ref;
|
||||
bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0;
|
||||
if (sh.y)
|
||||
bad += y != y_ref;
|
||||
else
|
||||
for (uint16_t v : y) bad += v != 0x7e57;
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d "
|
||||
"mismatching outputs)\n",
|
||||
M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GatherShape {
|
||||
int M, n, nl, base;
|
||||
bool f32w; /* GLM's f32 routing weights, else bf16 */
|
||||
@@ -607,7 +456,6 @@ int main() {
|
||||
std::mt19937 rng(23);
|
||||
int fails = 0, cases = 0;
|
||||
router_scatter_cases(rng, cases, fails);
|
||||
swiglu_quant_cases(rng, cases, fails);
|
||||
gather_inverse_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
|
||||
@@ -1,422 +0,0 @@
|
||||
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the
|
||||
* rule picks at each case (named per case, so a moved bound shows) must match a host restatement
|
||||
* of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh
|
||||
* 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0
|
||||
* scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a
|
||||
* longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up
|
||||
* slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped
|
||||
* slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for
|
||||
* odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer
|
||||
* tables. At GLM's TP8 slices below P64 the small-M form, with runs longer than one tile. The
|
||||
* table decode is also held to the arithmetic one over every code. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes
|
||||
* from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high
|
||||
* nibbles' bytes interleave in k order. */
|
||||
static uint32_t fp4x4_ref(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4);
|
||||
}
|
||||
static int check_decode() {
|
||||
int fails = 0;
|
||||
auto one = [&](uint32_t w) {
|
||||
const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu);
|
||||
const uint32_t lo_ref = __byte_perm(low, high, 0x5140),
|
||||
hi_ref = __byte_perm(low, high, 0x7362);
|
||||
uint32_t lo, hi, tlo, thi;
|
||||
r4d_mxfp4_unpack8_exact(w, &lo, &hi);
|
||||
r4d_mxfp4_unpack8(w, 0, &tlo, &thi);
|
||||
if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) {
|
||||
if (fails < 4)
|
||||
std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi,
|
||||
lo, hi_ref, lo_ref);
|
||||
++fails;
|
||||
}
|
||||
/* each byte against the e2m1 value it encodes */
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const uint32_t c = (w >> (4 * e)) & 15u;
|
||||
static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f };
|
||||
const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u];
|
||||
const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu);
|
||||
if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) {
|
||||
if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
};
|
||||
/* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves
|
||||
* of the word, and random words over all four */
|
||||
for (uint32_t v = 0; v < 65536; ++v) {
|
||||
one(v);
|
||||
one(v << 16);
|
||||
one(v << 8);
|
||||
}
|
||||
std::mt19937 rng(7);
|
||||
for (int i = 0; i < 200000; ++i) one((uint32_t)rng());
|
||||
return fails;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
int N, K, N_odd, K_odd, parts, top;
|
||||
bool sorted_a, tables, exceptional;
|
||||
std::vector<int> runs;
|
||||
int tail; // dropped slots past the routed rows
|
||||
const char* kernel; // the form the rule picks
|
||||
};
|
||||
|
||||
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
|
||||
* default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap;
|
||||
* the card generates the positive quiet NaN, so a NaN's sign carries no information here. */
|
||||
static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); }
|
||||
static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
for (size_t i = 0; i < a.size() && i < b.size(); ++i)
|
||||
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
|
||||
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
|
||||
}
|
||||
|
||||
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
|
||||
std::vector<int64_t> stride) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
for (size_t i = 0; i < shape.size(); ++i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = stride[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */
|
||||
static std::vector<int> glm_runs(std::vector<int> live) {
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
std::vector<int> runs(288, 0);
|
||||
for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i];
|
||||
return runs;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_decode(), cases = 1;
|
||||
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
|
||||
|
||||
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
|
||||
const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)";
|
||||
const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)";
|
||||
const char* const groups = "moe_mxfp4_fp8_kernel";
|
||||
const Case all[] = {
|
||||
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6,
|
||||
groups },
|
||||
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
|
||||
2, groups },
|
||||
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups },
|
||||
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups },
|
||||
{ "expert-major, K 384",
|
||||
64,
|
||||
384,
|
||||
64,
|
||||
384,
|
||||
2,
|
||||
2,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
{ 0, 1, 15, 16, 17, 30 },
|
||||
3,
|
||||
expert },
|
||||
{ "expert-major, K 256, exceptional codes",
|
||||
64,
|
||||
256,
|
||||
32,
|
||||
256,
|
||||
1,
|
||||
2,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
{ 1, 0, 3, 15, 1 },
|
||||
2,
|
||||
staged },
|
||||
{ "expert-major, K 512:384, runs past 64 rows, N under a block",
|
||||
96,
|
||||
512,
|
||||
96,
|
||||
384,
|
||||
1,
|
||||
2,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
{ 32, 33, 31, 96, 128, 129, 0, 2 },
|
||||
9,
|
||||
expert },
|
||||
{ "expert-major, K 256:128, column tiles cut",
|
||||
192,
|
||||
256,
|
||||
128,
|
||||
128,
|
||||
2,
|
||||
4,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
{ 64, 63, 65, 1, 0, 127, 17 },
|
||||
5,
|
||||
staged },
|
||||
{ "GLM TP4 down, the GLM prefill form",
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }),
|
||||
13,
|
||||
"moe_mxfp4_prefill_kernel" },
|
||||
{ "GLM TP8 gate_up, P64 BM32 BN64 K256",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 200, 33, 300, 31, 200 }),
|
||||
20,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, four tokens",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 1, 2, 1, 3, 1, 6, 1, 2, 9, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, runs past one tile",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }),
|
||||
2,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 down, small-M form, a run past one tile",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 3, 1, 17, 2, 1, 1, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<256, 4>)" },
|
||||
{ "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }),
|
||||
40,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" },
|
||||
};
|
||||
|
||||
for (const Case& c : all) {
|
||||
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
|
||||
int routed = 0;
|
||||
for (int r : c.runs) routed += r;
|
||||
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
|
||||
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
|
||||
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
|
||||
yp = OUT + ((&c - all) % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1000 + cases);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
|
||||
std::vector<float> as((size_t)Arows * asp);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
// A dropped slot about every eleventh row, the first rows of some runs included.
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
/* Stacked planes hold every expert; a pointer table names one of at most three slices a
|
||||
* class, so GLM's 288 experts stay small. */
|
||||
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
|
||||
nexp[2] = { (E + 1) / 2, E / 2 };
|
||||
std::vector<uint8_t> w[2], s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
std::vector<std::vector<float>> wf[2];
|
||||
int slices[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q];
|
||||
w[q].resize((size_t)slices[q] * n[q] * k[q] / 2);
|
||||
s[q].resize((size_t)slices[q] * n[q] * k[q] / 32);
|
||||
for (auto& v : w[q]) v = (uint8_t)rng();
|
||||
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
|
||||
for (size_t i = 0; i < s[q].size(); ++i)
|
||||
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
|
||||
: (uint8_t)(118 + rng() % 16);
|
||||
for (int x = 0; x < nexp[q]; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32);
|
||||
}
|
||||
/* each slice's codes as the E4M3 values the table decode gives */
|
||||
for (int x = 0; x < slices[q]; ++x) {
|
||||
std::vector<float> f((size_t)n[q] * k[q]);
|
||||
const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2;
|
||||
for (size_t i = 0; i < f.size(); ++i) {
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi);
|
||||
f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
|
||||
}
|
||||
wf[q].push_back(std::move(f));
|
||||
}
|
||||
}
|
||||
auto plane = [&](int q, bool scale) {
|
||||
const int64_t cols = scale ? k[q] / 32 : k[q];
|
||||
void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data())
|
||||
: (void*)(scale ? s[q].data() : w[q].data());
|
||||
RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols },
|
||||
{ c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 });
|
||||
return t;
|
||||
};
|
||||
|
||||
/* the per-element sequence, on the host */
|
||||
std::vector<float> af(a.size());
|
||||
for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]);
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int col = 0; col < OUT; ++col) {
|
||||
uint16_t& out = ref[(size_t)r * yp + col];
|
||||
out = 0;
|
||||
if (owner[r] < 0 || sorted[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top;
|
||||
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
|
||||
const bool valid = within < cw;
|
||||
const int wn = (col / pw) * cw + within;
|
||||
const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q];
|
||||
const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32;
|
||||
const float* arow = af.data() + (size_t)ar * ap;
|
||||
float total = 0.f;
|
||||
for (int kb = 0; kb < k[q]; kb += 128)
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
float raw = 0.f;
|
||||
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk)
|
||||
raw += arow[kk] * (valid ? wr[kk] : 0.f);
|
||||
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
|
||||
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
|
||||
float scale;
|
||||
std::memcpy(&scale, &bits, 4);
|
||||
float t = raw * as[(size_t)ar * asp + kb / 128];
|
||||
t = t * scale;
|
||||
total = total + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &total, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
|
||||
16); // f32_to_bf16, r4d_common.h
|
||||
}
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (live < T * OUT / 3) {
|
||||
std::printf("FAIL %s: output mostly zero\n", c.name);
|
||||
++fails;
|
||||
}
|
||||
|
||||
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
|
||||
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
|
||||
plane(0, false),
|
||||
plane(0, true),
|
||||
ten(sorted.data(), RAD_I32, { T }, { 1 }),
|
||||
ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }),
|
||||
plane(1, false),
|
||||
plane(1, true),
|
||||
RadTensor{} };
|
||||
RadParam p[11]{};
|
||||
auto pi = [](const char* key, long long v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
return x;
|
||||
};
|
||||
auto ps = [](const char* key, const char* v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_STR;
|
||||
x.sval = v;
|
||||
return x;
|
||||
};
|
||||
p[0] = pi("M", T / c.top);
|
||||
p[1] = pi("N", c.N);
|
||||
p[2] = pi("K", c.K);
|
||||
p[3] = pi("N_odd", c.N_odd);
|
||||
p[4] = pi("K_odd", c.K_odd);
|
||||
p[5] = pi("n_expert", E);
|
||||
p[6] = pi("top_k", c.top);
|
||||
p[7] = pi("parts", c.parts);
|
||||
p[8] = pi("group", 128);
|
||||
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
|
||||
p[10] = ps("dtype", "mxfp4a8");
|
||||
std::vector<uint16_t> got((size_t)T * yp, 0x7777);
|
||||
t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 });
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 11;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = r4d_rad_moe_mxfp4(&ar, nullptr);
|
||||
const size_t i = first_diff(got, ref);
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: "
|
||||
"%04x, want %04x)\n",
|
||||
c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp,
|
||||
i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -131,8 +131,9 @@ static int case_nan(int M, int n, int pad, int extra_rows) {
|
||||
|
||||
/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts'
|
||||
* E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns,
|
||||
* so that group's amax is 0 and its scale the quantiser's 1. */
|
||||
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) {
|
||||
* so that group's amax is 0 and its scale the quantiser's 1. `i8` is norm_add_norm_route_i8g: q is
|
||||
* the int8 codes of each group rotated by the 128-wide Hadamard (rmsnorm_had_quant_i8g's). */
|
||||
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false, bool i8 = false) {
|
||||
const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3;
|
||||
const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n);
|
||||
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
|
||||
@@ -150,12 +151,12 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
|
||||
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
|
||||
rows(yd.data(), RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
|
||||
rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n),
|
||||
rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
|
||||
rows(qd.data(), i8 ? RAD_I8 : RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
|
||||
RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128};
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6;
|
||||
if (r4d_rad_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
|
||||
if ((i8 ? r4d_rad_norm_add_norm_route_i8g_bf16(&ar, nullptr) : r4d_rad_norm_add_norm_route_bf16(&ar, nullptr)) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
|
||||
t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data();
|
||||
if (host_norm_add_norm_route(&ar) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; }
|
||||
Tally tx, ty, tr;
|
||||
@@ -186,12 +187,26 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
|
||||
cmp(&rd[o], cr.data(), &rh[o], n, tr);
|
||||
for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */
|
||||
float h[128], am = 0.0f;
|
||||
for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); }
|
||||
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc;
|
||||
for (int j = 0; j < 128; ++j) h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]);
|
||||
if (i8) /* had_quant_act_i8g's rotation */
|
||||
for (int st = 1; st < 128; st <<= 1)
|
||||
for (int j = 0; j < 128; ++j)
|
||||
if ((j & st) == 0) { const float u = h[j], w = h[j + st]; h[j] = u + w; h[j + st] = u - w; }
|
||||
for (int j = 0; j < 128; ++j) am = std::fmax(am, std::fabs(h[j]));
|
||||
const float top = i8 ? 127.0f : 448.0f;
|
||||
const float sc = am > 0.0f ? am * (1.0f / top) : 1.0f, inv = 1.0f / sc;
|
||||
s_chain += sd[os + g] != sc;
|
||||
if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain;
|
||||
for (int j = 0; j < 128; ++j) {
|
||||
const int i = g * 128 + j;
|
||||
if (i8) {
|
||||
/* vs the host arm: a norm factor an ulp apart moves a few bf16 inputs by one, which
|
||||
* moves a rotated value and the group's amax each by less than a code step */
|
||||
q_chain += (int8_t)qd[oq + i] != (int8_t)std::rint(std::fmin(std::fmax(h[j] * inv, -127.0f), 127.0f));
|
||||
const double dv = std::fabs((double)(int8_t)qd[oq + i] * sd[os + g] - (double)(int8_t)qh[oq + i] * sh[os + g]);
|
||||
if (dv > 2.0 * (double)sc + 1e-30) ++q_host_bad;
|
||||
continue;
|
||||
}
|
||||
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
|
||||
/* vs the host arm: one code step is at most an eighth of its value, so at most an
|
||||
* eighth of the group's amax; a scale an ulp off moves less */
|
||||
@@ -203,8 +218,8 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 &&
|
||||
tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0;
|
||||
std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
|
||||
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld,
|
||||
std::printf("norm_add_norm_route%s M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
|
||||
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", i8 ? "_i8g" : "", M, n, ld,
|
||||
zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain,
|
||||
tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
@@ -280,6 +295,10 @@ int main() {
|
||||
for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2);
|
||||
fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1);
|
||||
fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true);
|
||||
/* the rotated int8 form at the same widths */
|
||||
for (int M : { 1, 5 }) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2, false, true);
|
||||
fails += case_route(2, 3200, 16, 1, false, true) + case_route(3, 128, 8, 1, false, true);
|
||||
fails += case_route(2, 6144, 0, 0, false, true) + case_route(4, 2816, 0, 1, true, true);
|
||||
std::printf("norm joins: %d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -267,8 +267,10 @@ int run(Fix& f, Form form) {
|
||||
: "qsa_select_kernel";
|
||||
const char* fn = kFormName[form];
|
||||
if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; }
|
||||
/* The launch site names the template, `kernel<Signed>`: the name is what precedes it. */
|
||||
const std::string ran(emu_last_kernel, std::strcspn(emu_last_kernel, "<"));
|
||||
/* The launch site names the template in parentheses, `(kernel<Signed, form>)`: the name is
|
||||
* what stands between the parenthesis and the arguments. */
|
||||
const char* const kname = emu_last_kernel + (emu_last_kernel[0] == '(' ? 1 : 0);
|
||||
const std::string ran(kname, std::strcspn(kname, "<"));
|
||||
if (ran != expect || grids != (split ? 2 : 1)) {
|
||||
std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn,
|
||||
emu_last_kernel, grids, expect, split ? 2 : 1);
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
/* tests/r4d_emu: Muse Glimmer's vision-tower coordinate ops (r4d_vit_muse.hip) on the host SIMT
|
||||
* emulator.
|
||||
*
|
||||
* grid_embed_pad: held to hand-computed constants -- a side-4 table resampled to an 8 x 8 grid,
|
||||
* whose last row and column reach taps off the table (zero-weight, grid_sample's zeros padding),
|
||||
* and an in-range 4 x 4 grid that reads the table whole. window_order: held to an independent host
|
||||
* reference that sorts the patches by (segment, window row, window column, raster), which shares
|
||||
* no arithmetic with the kernel's base-plus-rank slot formula; the inverse permutation, the rope
|
||||
* positions and every cuw boundary follow from that order.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor rows(void* p, uint32_t dt, int64_t r0, int64_t r1, int64_t ld) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = r0; t.shape[1] = r1;
|
||||
t.stride[0] = ld; t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, uint32_t dt, int64_t n) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadParam pi_(const char* k, long long v) { RadParam p{}; p.key = k; p.kind = RAD_P_INT; p.ival = v; return p; }
|
||||
static RadParam ps_(const char* k, const char* v) { RadParam p{}; p.key = k; p.kind = RAD_P_STR; p.sval = v; return p; }
|
||||
|
||||
// ------------------------------------------------------------------ grid_embed_pad
|
||||
|
||||
static int test_pad() {
|
||||
const int64_t n = 3, side = 4;
|
||||
/* table[h * 4 + w] = (h * 4 + w + 1) / 4, three channels offset by 0.1 */
|
||||
std::vector<float> tabf((size_t)(side * side * n));
|
||||
for (int h = 0; h < side; ++h)
|
||||
for (int w = 0; w < side; ++w)
|
||||
for (int c = 0; c < n; ++c) tabf[(size_t)((h * side + w) * n + c)] = (h * side + w + 1) * 0.25f + 0.1f * c;
|
||||
std::vector<uint16_t> tab((size_t)(side * side * n));
|
||||
for (size_t i = 0; i < tab.size(); ++i) tab[i] = f2b(tabf[i]);
|
||||
|
||||
/* An 8 x 8 grid: src(i) = i / 2 - 0.25 on each axis; per axis the taps are floor(src) and
|
||||
* floor(src) + 1 with hat weights, the off-table tap's weight zero. Row 0: taps -1 (masked)
|
||||
* and 0 at 3/4; row 7: tap 3 at 3/4 and 4 (masked); interior rows blend two adjacent taps. */
|
||||
const int64_t M = 6;
|
||||
/* Rows (0,0), (7,7), (1,3), (4,2), (7,0), (3,7) of the 8 x 8 grid. */
|
||||
const int rr[6] = { 0, 7, 1, 4, 7, 3 }, cc[6] = { 0, 7, 3, 2, 0, 7 };
|
||||
std::vector<int32_t> crd(4 * M);
|
||||
for (int m = 0; m < 6; ++m) {
|
||||
crd[m] = rr[m]; crd[M + m] = cc[m]; crd[2 * M + m] = 8; crd[3 * M + m] = 8;
|
||||
}
|
||||
std::vector<uint16_t> x((size_t)(M * n));
|
||||
for (size_t i = 0; i < x.size(); ++i) x[i] = f2b(7.0f);
|
||||
|
||||
RadTensor t[3] = { rows(x.data(), RAD_BF16, M, n, n), rows(tab.data(), RAD_BF16, side * side, n, n),
|
||||
rows(crd.data(), RAD_I32, 4, M, M) };
|
||||
RadParam p[4] = { pi_("M", M), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") };
|
||||
RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 4;
|
||||
if (r4d_rad_grid_embed_pad(&a, nullptr) != RAD_OK) { std::puts("grid_embed_pad: launch failed"); return 1; }
|
||||
|
||||
/* Hand-computed: each axis's in-range weight (the off-table tap contributes nothing), the
|
||||
* joint weight the product h*w, the taps summed in libref's order (top-left, top-right,
|
||||
* bottom-left, bottom-right). Channel 0; the others sit 0.1 apart, and x starts at 7. */
|
||||
/* (0,0): both axes tap 0 only, at 3/4 each -> 9/16 * 0.25 = 0.140625. */
|
||||
/* (7,7): both axes tap 3 only at 3/4 -> 9/16 * 4 = 2.25. */
|
||||
/* (1,3): rows 0,1 at 3/4, 1/4; cols 1,2 at 3/4, 1/4 -> 0.8125. */
|
||||
/* (4,2): rows 1,2 at 1/4, 3/4; cols 1,2 at 3/4, 1/4 -> 2.3125. */
|
||||
/* (7,0): row tap 3 at 3/4 (tap 4 masked), col tap 0 at 3/4 (tap -1 masked) -> 1.828125. */
|
||||
/* (3,7): rows 1,2 at 3/4, 1/4; col tap 3 at 3/4 (tap 4 masked) -> 1.6875. */
|
||||
/* Hand-derived per row: the literal taps and weights (channel 0 verified against the printed
|
||||
* fractions, every channel against this table). Taps summed in libref's order: top-left,
|
||||
* top-right, bottom-left, bottom-right, each joint weight the product h*w. */
|
||||
struct Taps { int th0, th1, tw0, tw1; float wh0, wh1, ww0, ww1; };
|
||||
const Taps taps[6] = {
|
||||
{ 0, 0, 0, 0, 0.0f, 0.75f, 0.0f, 0.75f }, /* (0,0): taps -1/4 masked, 0 at 3/4 */
|
||||
{ 3, 3, 3, 3, 0.75f, 0.0f, 0.75f, 0.0f }, /* (7,7): taps 3 at 3/4, 4 masked */
|
||||
{ 0, 1, 1, 2, 0.75f, 0.25f, 0.75f, 0.25f }, /* (1,3) */
|
||||
{ 1, 2, 0, 1, 0.25f, 0.75f, 0.25f, 0.75f }, /* (4,2) */
|
||||
{ 3, 3, 0, 0, 0.75f, 0.0f, 0.0f, 0.75f }, /* (7,0): row 4 and col -1 masked */
|
||||
{ 1, 2, 3, 3, 0.75f, 0.25f, 0.75f, 0.0f }, /* (3,7): col 4 masked */
|
||||
};
|
||||
int bad = 0;
|
||||
for (int m = 0; m < 6; ++m) {
|
||||
const Taps& t6 = taps[m];
|
||||
for (int c = 0; c < n; ++c) {
|
||||
const float acc =
|
||||
b2f(tab[(size_t)((t6.th0 * side + t6.tw0) * n + c)]) * (t6.wh0 * t6.ww0) +
|
||||
b2f(tab[(size_t)((t6.th0 * side + t6.tw1) * n + c)]) * (t6.wh0 * t6.ww1) +
|
||||
b2f(tab[(size_t)((t6.th1 * side + t6.tw0) * n + c)]) * (t6.wh1 * t6.ww0) +
|
||||
b2f(tab[(size_t)((t6.th1 * side + t6.tw1) * n + c)]) * (t6.wh1 * t6.ww1);
|
||||
const float w = rb(7.0f + rb(acc));
|
||||
const float got = b2f(x[(size_t)(m * n + c)]);
|
||||
if (got != w) {
|
||||
++bad;
|
||||
std::printf("grid_embed_pad: row %d ch %d: got %g want %g\n", m, c, got, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* In range: a 4 x 4 grid on the side-4 table reads each row whole (src = i exactly). */
|
||||
const int64_t M2 = 2;
|
||||
std::vector<int32_t> crd2(4 * M2);
|
||||
crd2[0] = 2; crd2[1] = 3; crd2[4] = 4; crd2[5] = 4; crd2[6] = 4; crd2[7] = 4;
|
||||
crd2[2] = 1; crd2[3] = 2;
|
||||
std::vector<uint16_t> x2((size_t)(M2 * n));
|
||||
for (size_t i = 0; i < x2.size(); ++i) x2[i] = f2b(0.0f);
|
||||
RadTensor t2[3] = { rows(x2.data(), RAD_BF16, M2, n, n),
|
||||
rows(tab.data(), RAD_BF16, side * side, n, n),
|
||||
rows(crd2.data(), RAD_I32, 4, M2, M2) };
|
||||
RadParam p2[4] = { pi_("M", M2), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") };
|
||||
RadArgs a2{}; a2.t = t2; a2.n_t = 3; a2.p = p2; a2.n_p = 4;
|
||||
if (r4d_rad_grid_embed_pad(&a2, nullptr) != RAD_OK) { std::puts("grid_embed_pad in-range: launch failed"); return 1; }
|
||||
for (int m = 0; m < 2; ++m)
|
||||
for (int c = 0; c < n; ++c) {
|
||||
const int h = m == 0 ? 2 : 3, w = m == 0 ? 1 : 2;
|
||||
const float want = rb(rb(tabf[(size_t)((h * side + w) * n + c)]) + 0.0f);
|
||||
if (b2f(x2[(size_t)(m * n + c)]) != want) {
|
||||
++bad;
|
||||
std::printf("grid_embed_pad in-range: row %d ch %d: got %g want %g\n", m, c,
|
||||
b2f(x2[(size_t)(m * n + c)]), want);
|
||||
}
|
||||
}
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ window_order
|
||||
|
||||
/* The independent reference: sort patches by (segment, window row, window column, row, col). */
|
||||
struct Ord { int seg, wr, wc, r, c, p; };
|
||||
static int test_window(int window, const std::vector<std::pair<int, int>>& grids) {
|
||||
/* Pack the grids back to back: segment s covers base .. base + gh*gw. */
|
||||
int P = 0;
|
||||
std::vector<int> cu{ 0 };
|
||||
std::vector<int> gh_(grids.size()), gw_(grids.size());
|
||||
for (size_t s = 0; s < grids.size(); ++s) {
|
||||
gh_[s] = grids[s].first; gw_[s] = grids[s].second;
|
||||
P += gh_[s] * gw_[s];
|
||||
cu.push_back(P);
|
||||
}
|
||||
std::vector<int32_t> crd(4 * (size_t)P, 0);
|
||||
std::vector<Ord> ord;
|
||||
for (size_t s = 0; s < grids.size(); ++s) {
|
||||
const int base = cu[s];
|
||||
for (int r = 0; r < gh_[s]; ++r)
|
||||
for (int c = 0; c < gw_[s]; ++c) {
|
||||
const int p = base + r * gw_[s] + c;
|
||||
crd[p] = r; crd[(size_t)P + p] = c;
|
||||
crd[2 * (size_t)P + p] = gh_[s]; crd[3 * (size_t)P + p] = gw_[s];
|
||||
ord.push_back({ (int)s, window > 0 ? r / window : 0, window > 0 ? c / window : 0,
|
||||
r, c, p });
|
||||
}
|
||||
}
|
||||
std::stable_sort(ord.begin(), ord.end(), [](const Ord& l, const Ord& r) {
|
||||
if (l.seg != r.seg) return l.seg < r.seg;
|
||||
if (l.wr != r.wr) return l.wr < r.wr;
|
||||
if (l.wc != r.wc) return l.wc < r.wc;
|
||||
if (l.r != r.r) return l.r < r.r;
|
||||
return l.c < r.c;
|
||||
});
|
||||
std::vector<int32_t> widx((size_t)P), winv((size_t)P), wpos(2 * (size_t)P), wcuw((size_t)P + 1, P);
|
||||
for (int slot = 0; slot < P; ++slot) {
|
||||
widx[(size_t)slot] = ord[(size_t)slot].p;
|
||||
winv[(size_t)ord[(size_t)slot].p] = slot;
|
||||
wpos[(size_t)slot] = ord[(size_t)slot].c + 1; /* pos[0][slot] = col + 1 */
|
||||
wpos[(size_t)P + (size_t)slot] = ord[(size_t)slot].r + 1;
|
||||
}
|
||||
if (window <= 0) {
|
||||
for (int i = 0; i <= (int)grids.size() && i <= P; ++i) wcuw[(size_t)i] = cu[(size_t)i];
|
||||
} else {
|
||||
/* cuw[k] is the base slot of window k: the patches before it in the permuted order. */
|
||||
int k = 0, base = 0;
|
||||
for (size_t s = 0; s < grids.size(); ++s) {
|
||||
const int nh = (gh_[s] + window - 1) / window, nw = (gw_[s] + window - 1) / window;
|
||||
for (int wr = 0; wr < nh; ++wr)
|
||||
for (int wc = 0; wc < nw; ++wc) {
|
||||
wcuw[(size_t)k] = base;
|
||||
int cnt = 0;
|
||||
for (const Ord& o : ord)
|
||||
if (o.seg == (int)s && o.wr == wr && o.wc == wc) ++cnt;
|
||||
base += cnt;
|
||||
++k;
|
||||
}
|
||||
}
|
||||
wcuw[(size_t)k] = P;
|
||||
}
|
||||
|
||||
std::vector<int32_t> idx((size_t)P, -1), inv((size_t)P, -1), pos(2 * (size_t)P, -1),
|
||||
cuw((size_t)P + 1, -1);
|
||||
RadTensor t[6] = { rows(crd.data(), RAD_I32, 4, P, P), rows(cu.data(), RAD_I32, 1, (int64_t)cu.size(), (int64_t)cu.size()),
|
||||
rows(idx.data(), RAD_I32, 1, P, P), rows(inv.data(), RAD_I32, 1, P, P),
|
||||
rows(pos.data(), RAD_I32, 2, P, P), rows(cuw.data(), RAD_I32, 1, P + 1, P + 1) };
|
||||
RadParam p[2] = { pi_("M", P), pi_("window", window) };
|
||||
RadArgs a{}; a.t = t; a.n_t = 6; a.p = p; a.n_p = 2;
|
||||
if (r4d_rad_window_order(&a, nullptr) != RAD_OK) {
|
||||
std::printf("window_order w=%d: launch failed\n", window);
|
||||
return 1;
|
||||
}
|
||||
int bad = 0;
|
||||
for (int i = 0; i < P; ++i) {
|
||||
if (idx[(size_t)i] != widx[(size_t)i]) { ++bad; std::printf("window_order w=%d: idx[%d] %d want %d\n", window, i, idx[(size_t)i], widx[(size_t)i]); }
|
||||
if (inv[(size_t)i] != winv[(size_t)i]) { ++bad; std::printf("window_order w=%d: inv[%d] %d want %d\n", window, i, inv[(size_t)i], winv[(size_t)i]); }
|
||||
if (pos[(size_t)i] != wpos[(size_t)i]) { ++bad; std::printf("window_order w=%d: pos c[%d] %d want %d\n", window, i, pos[(size_t)i], wpos[(size_t)i]); }
|
||||
if (pos[(size_t)P + (size_t)i] != wpos[(size_t)P + (size_t)i]) { ++bad; std::printf("window_order w=%d: pos r[%d] %d want %d\n", window, i, pos[(size_t)P + (size_t)i], wpos[(size_t)P + (size_t)i]); }
|
||||
if (idx[(size_t)inv[(size_t)i]] != i) ++bad; /* the inverse property */
|
||||
}
|
||||
for (size_t i = 0; i <= (size_t)P; ++i)
|
||||
if (cuw[i] != wcuw[i]) { ++bad; std::printf("window_order w=%d: cuw[%zu] %d want %d\n", window, i, cuw[i], wcuw[i]); }
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int rc = 0;
|
||||
rc |= test_pad();
|
||||
/* One 48 x 40 segment, window 32: ragged right and bottom, windows 32x32, 32x8, 16x32, 16x8. */
|
||||
rc |= test_window(32, { { 48, 40 } });
|
||||
/* Video-style: two segments back to back, window 16. */
|
||||
rc |= test_window(16, { { 20, 24 }, { 10, 12 } });
|
||||
/* Window-divisible. */
|
||||
rc |= test_window(8, { { 16, 24 } });
|
||||
/* A window larger than the grid: one window holding the whole segment. */
|
||||
rc |= test_window(64, { { 12, 10 } });
|
||||
/* window <= 0: the identity, cuw = cu. */
|
||||
rc |= test_window(0, { { 9, 7 }, { 5, 5 } });
|
||||
if (!rc) std::puts("r4d_emu_vit: ok");
|
||||
return rc;
|
||||
}
|
||||
@@ -204,9 +204,9 @@ if "minicpm5-2b-bf16-dspark" in by:
|
||||
check("recipe: minicpm5 dspark names its drafter", bool(r["draft"]), r)
|
||||
pick, _ = rx.pick_recipe(types.SimpleNamespace(recipe="auto"), {}, recipes, ["openbmb/MiniCPM5-2B", "MiniCPM5-2B"])
|
||||
check("auto: MiniCPM5-2B -> minicpm5-2b-bf16-dspark", pick["name"] == "minicpm5-2b-bf16-dspark", pick["name"])
|
||||
if "q38-27b-fp8block-df2" in by:
|
||||
if "gemma4-31b-dense-bf16-w4a8" in by:
|
||||
check("recipe: a usage line's --set keys are read",
|
||||
"quantization_config.weight_block_size=128 128" in by["q38-27b-fp8block-df2"]["set"])
|
||||
"quantization_config.quant_method=compressed-tensors" in by["gemma4-31b-dense-bf16-w4a8"]["set"])
|
||||
check("auto: an unknown model asks for --recipe",
|
||||
refused(lambda: rx.pick_recipe(types.SimpleNamespace(recipe="auto"), {}, recipes, ["org/NoSuchModel-9B", "NoSuchModel-9B"])))
|
||||
pin, _ = rx.pick_recipe(types.SimpleNamespace(recipe="auto"), {"recipes": {"NoSuchModel": recipes[0]["name"]}}, recipes, ["org/NoSuchModel-9B"])
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/* radfile_keep_test.cpp -- what the load's page-cache drop keeps, and what it must not.
|
||||
*
|
||||
* The bug this guards: a container larger than RAM has its blob dropped from the page cache after
|
||||
* the load, so the cache is not left full of weight pages nothing reads again. The mapped tier is
|
||||
* the exception -- an n-gram table is read through its mapping for the engine's whole life -- and
|
||||
* dropping it means every gather after a restart faults the rows back from disk (measured: 1 519
|
||||
* vs 1 998 tok/s prefill on a 24k prompt, 103 GiB table). Two things have to be right for the
|
||||
* exception to work, and neither is visible from the outside:
|
||||
*
|
||||
* 1. the drop frees the blob MINUS the kept ranges, page-aligned so a page holding kept bytes is
|
||||
* never dropped (rad_keep_complement);
|
||||
* 2. only addresses inside the container become kept ranges: a copy in RAM
|
||||
* (--ngram-placement ram) or a table read from its own file (disk=DIR) is not the blob, and
|
||||
* recording one would keep pages that belong to something else (rad_blob_range).
|
||||
*
|
||||
* The second is the easier one to get wrong silently: an offset computed from a pointer that is
|
||||
* not in the mapping is plausible arithmetic.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "format/radfile.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kPage = 4096;
|
||||
constexpr int64_t kTables = 64 * 1024; /* where the blob starts */
|
||||
constexpr int64_t kBlob = 1 << 20; /* one MiB of blob */
|
||||
constexpr int64_t kSize = kTables + kBlob; /* the container's size */
|
||||
|
||||
using Ranges = std::vector<std::pair<int64_t, int64_t>>; /* (offset, length) */
|
||||
|
||||
Ranges complement(Ranges keep) {
|
||||
return rad_keep_complement(kTables, kSize, std::move(keep));
|
||||
}
|
||||
|
||||
/* Total bytes a set of ranges covers, which is what "freed" or "kept" means to a page cache. */
|
||||
int64_t covered(const Ranges& r) {
|
||||
int64_t n = 0;
|
||||
for (const auto& x : r) n += x.second;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* ---- the drop's geometry ---------------------------------------------------------------- */
|
||||
|
||||
TEST(without_a_keep_list_the_whole_blob_is_dropped) {
|
||||
const Ranges freed = complement({});
|
||||
CHECK_EQ(freed.size(), size_t(1));
|
||||
CHECK_EQ(freed.at(0).first, kTables);
|
||||
CHECK_EQ(freed.at(0).second, kBlob);
|
||||
}
|
||||
|
||||
TEST(a_kept_range_splits_the_drop_around_it) {
|
||||
const Ranges freed = complement({{kTables + 256 * 1024, 256 * 1024}});
|
||||
CHECK_EQ(freed.size(), size_t(2));
|
||||
CHECK_EQ(freed.at(0).first, kTables);
|
||||
CHECK_EQ(freed.at(0).second, 256 * 1024);
|
||||
CHECK_EQ(freed.at(1).first, kTables + 512 * 1024);
|
||||
CHECK_EQ(freed.at(1).second, kBlob - 512 * 1024);
|
||||
CHECK_EQ(covered(freed), kBlob - 256 * 1024);
|
||||
}
|
||||
|
||||
TEST(a_kept_range_at_the_start_leaves_one_range_behind_it) {
|
||||
const Ranges freed = complement({{kTables, 128 * 1024}});
|
||||
CHECK_EQ(freed.size(), size_t(1));
|
||||
CHECK_EQ(freed.at(0).first, kTables + 128 * 1024);
|
||||
CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024);
|
||||
}
|
||||
|
||||
TEST(a_kept_range_at_the_end_leaves_one_range_before_it) {
|
||||
const Ranges freed = complement({{kSize - 128 * 1024, 128 * 1024}});
|
||||
CHECK_EQ(freed.size(), size_t(1));
|
||||
CHECK_EQ(freed.at(0).first, kTables);
|
||||
CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024);
|
||||
}
|
||||
|
||||
TEST(a_keep_list_covering_the_blob_drops_nothing) {
|
||||
CHECK(complement({{kTables, kBlob}}).empty());
|
||||
CHECK(complement({{kTables - kPage, kBlob + 2 * kPage}}).empty());
|
||||
}
|
||||
|
||||
TEST(unsorted_and_overlapping_keep_ranges_are_merged) {
|
||||
/* 250..310 KiB and 300..400 KiB merge to one 150 KiB keep; both are page-aligned at the ends
|
||||
* after rounding, and the duplicate is the same range a second rank would send. */
|
||||
const Ranges freed = complement({
|
||||
{kTables + 300 * 1024, 100 * 1024}, /* second */
|
||||
{kTables + 250 * 1024, 60 * 1024}, /* overlaps and precedes it */
|
||||
{kTables + 250 * 1024, 60 * 1024}, /* the same range again, one per rank */
|
||||
});
|
||||
CHECK_EQ(freed.size(), size_t(2));
|
||||
CHECK_EQ(freed.at(0).first, kTables);
|
||||
/* The gap ends at the page boundary below the keep's start: 250 KiB is 62.5 pages, so 62
|
||||
* pages (253 952 bytes) are freed and the half page holding kept bytes stays. */
|
||||
CHECK_EQ(freed.at(0).second, 253952);
|
||||
CHECK_EQ(freed.at(1).first, kTables + 400 * 1024); /* merged end: 250 + 150 KiB */
|
||||
CHECK_EQ(freed.at(1).second, kBlob - 400 * 1024 + 0);
|
||||
/* Freed plus kept is the blob, less the 2 KiB page the rounding gave back to the keep. */
|
||||
CHECK_EQ(covered(freed), kBlob - 150 * 1024 - 2048);
|
||||
}
|
||||
|
||||
TEST(keep_ranges_outside_the_blob_are_clamped_not_trusted) {
|
||||
CHECK_EQ(covered(complement({{0, kTables}})), kBlob); /* entirely in the tables */
|
||||
CHECK_EQ(covered(complement({{kSize, 4096}})), kBlob); /* past the end */
|
||||
CHECK_EQ(covered(complement({{-4096, 4096}})), kBlob); /* before the mapping */
|
||||
CHECK_EQ(covered(complement({{0, 0}})), kBlob); /* empty */
|
||||
/* Half in, half out: only the part inside the blob is kept. */
|
||||
CHECK_EQ(covered(complement({{kSize - 8192, 16384}})), kBlob - 8192);
|
||||
}
|
||||
|
||||
TEST(a_gap_never_takes_a_page_that_holds_kept_bytes) {
|
||||
/* The kept range starts four bytes into a page; the drop before it must stop at that page's
|
||||
* boundary, not one byte before the kept range, or the kept bytes share a dropped page. */
|
||||
const Ranges freed = complement({{kTables + 100 * 1024 + 4, 4096}});
|
||||
CHECK_EQ(freed.size(), size_t(2));
|
||||
CHECK_EQ(freed.at(0).second % kPage, 0);
|
||||
CHECK(freed.at(0).first + freed.at(0).second <= kTables + 100 * 1024 + 4);
|
||||
CHECK_EQ(freed.at(1).first % kPage, 0);
|
||||
CHECK(freed.at(1).first >= kTables + 100 * 1024 + 4 + 4096);
|
||||
}
|
||||
|
||||
TEST(a_container_with_no_blob_has_nothing_to_drop_or_keep) {
|
||||
const auto none = rad_keep_complement(8192, 8192, {{8192, 4096}});
|
||||
CHECK(none.empty());
|
||||
}
|
||||
|
||||
/* ---- which addresses are the blob -------------------------------------------------------- */
|
||||
|
||||
TEST(the_container_covers_its_own_bytes_and_nothing_else) {
|
||||
const std::vector<uint8_t> container(4 * kPage);
|
||||
const uint8_t* base = container.data();
|
||||
const int64_t size = (int64_t)container.size();
|
||||
int64_t off = -1, len = -1;
|
||||
|
||||
CHECK(rad_blob_range(base, size, base, 16, &off, &len));
|
||||
CHECK_EQ(off, int64_t(0));
|
||||
CHECK_EQ(len, int64_t(16));
|
||||
|
||||
CHECK(rad_blob_range(base, size, base + 2 * kPage + 7, 100, &off, &len));
|
||||
CHECK_EQ(off, 2 * kPage + 7);
|
||||
CHECK_EQ(len, int64_t(100));
|
||||
|
||||
/* Up to and including the last byte. */
|
||||
CHECK(rad_blob_range(base, size, base + size - 1, 1, &off, &len));
|
||||
CHECK_EQ(off, size - 1);
|
||||
|
||||
/* One byte past the end, or a range that overruns it. */
|
||||
CHECK(!rad_blob_range(base, size, base + size, 1, &off, &len));
|
||||
CHECK(!rad_blob_range(base, size, base + size - 1, 2, &off, &len));
|
||||
|
||||
/* A copy in RAM (the --ngram-placement ram case) is not the blob. */
|
||||
const std::vector<uint8_t> copy(4 * kPage);
|
||||
CHECK(!rad_blob_range(base, size, copy.data(), 16, &off, &len));
|
||||
|
||||
/* Degenerate input refuses rather than computing a range from nothing. */
|
||||
CHECK(!rad_blob_range(nullptr, size, base, 16, &off, &len));
|
||||
CHECK(!rad_blob_range(base, 0, base, 16, &off, &len));
|
||||
CHECK(!rad_blob_range(base, size, nullptr, 16, &off, &len));
|
||||
CHECK(!rad_blob_range(base, size, base, 0, &off, &len));
|
||||
CHECK(!rad_blob_range(base, size, base, -8, &off, &len));
|
||||
}
|
||||
|
||||
TEST(the_recorded_range_is_what_the_drop_is_asked_to_keep) {
|
||||
/* End to end on the two helpers alone: map a "table" inside a container, keep it, and check
|
||||
* that the freed ranges are its complement. */
|
||||
const std::vector<uint8_t> container(kSize);
|
||||
const uint8_t* base = container.data();
|
||||
const void* table = base + kTables + 4096;
|
||||
const int64_t n = 64 * 1024;
|
||||
|
||||
int64_t off = 0, len = 0;
|
||||
CHECK(rad_blob_range(base, kSize, table, n, &off, &len));
|
||||
const Ranges freed = rad_keep_complement(kTables, kSize, {{off, len}});
|
||||
CHECK_EQ(covered(freed), kBlob - n);
|
||||
for (const auto& r : freed) {
|
||||
CHECK(!(r.first < off + len && off < r.first + r.second)); /* no overlap with the keep */
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+362
-48
@@ -127,54 +127,6 @@ bool has_opt(const RecipeRule* r, const char* k, const char* v) {
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* The NVFP4 recipe as it ships: it parses, and its patterns decide the 27B architecture's
|
||||
* declared names. The linears (fused MLPs, attention, the delta net's in- and out-projections)
|
||||
* go to MXFP4, the head to block fp8, and the norms, the convolution, the a/b projection and the
|
||||
* embedding keep the checkpoint's form. */
|
||||
TEST(the_nvfp4_recipe_decides_the_model_it_was_written_for) {
|
||||
std::string dir = __FILE__;
|
||||
dir = dir.substr(0, dir.find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/q38-27b-nvfp4-df2.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "q38-27b-nvfp4-df2.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)17);
|
||||
|
||||
/* every linear, across the layer range, by the fused names the builder declares */
|
||||
const char* linears[] = { "blk.47.ffn_gate_up.weight", "blk.47.ffn_down.weight",
|
||||
"blk.3.ffn_gate_up.weight", "blk.3.attn_qg.weight",
|
||||
"blk.3.attn_k.weight", "blk.3.attn_v.weight",
|
||||
"blk.3.attn_output.weight", "blk.47.ssm_inz.weight",
|
||||
"blk.47.ssm_out.weight" };
|
||||
for (const char* n : linears) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "fp4_e2m1"));
|
||||
CHECK(has_opt(m, "group", "32"));
|
||||
CHECK(has_opt(m, "scale", "e8m0"));
|
||||
}
|
||||
/* the head to block fp8 */
|
||||
const RecipeRule* head = r.match("output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK(has_opt(head, "codes", "fp8_e4m3"));
|
||||
CHECK(has_opt(head, "block", "128x128"));
|
||||
/* kept as the checkpoint ships them (the a/b projection is bf16 there) */
|
||||
const char* kept[] = { "blk.0.ffn_norm.weight", "blk.0.attn_norm.weight", "blk.47.ssm_conv1d.weight",
|
||||
"blk.47.ssm_a_log", "blk.47.ssm_ab.weight", "token_embd.weight", "output_norm.weight" };
|
||||
for (const char* n : kept)
|
||||
CHECK(r.match(n) == nullptr);
|
||||
/* the drafter's own linears */
|
||||
const RecipeRule* fc = r.match("dflash.fc.weight");
|
||||
REQUIRE(fc != nullptr);
|
||||
CHECK(has_opt(fc, "codes", "fp4_e2m1"));
|
||||
const RecipeRule* dh = r.match("dflash.draft_head.weight");
|
||||
REQUIRE(dh != nullptr);
|
||||
CHECK(has_opt(dh, "codes", "u2"));
|
||||
}
|
||||
|
||||
/* The Sage-A1.5 recipe as it ships: every trunk linear -- attention, the delta net's in- and
|
||||
* out-projections, the routed and shared experts of all 40 blocks and the MTP layer at its own
|
||||
* index 40 -- goes to block fp8, the head likewise, and the routers, the shared-expert gates,
|
||||
@@ -295,4 +247,366 @@ TEST(the_sage_dflash2_recipes_decide_the_trunk_and_the_drafter) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The Muse Glimmer recipes as they ship. The bf16 one is documentation only -- no rule, so every
|
||||
* weight keeps the checkpoint's form. The w4a8 one routes every trunk linear to int4 on the
|
||||
# 128-column grid (the value projection to int8), and nothing else: the layer norms, the
|
||||
* embedding and the head match no rule. The patterns are the plugin's declared names:
|
||||
* separate q and gate projections (this family's q_proj/gate_proj are two tensors), the gate|up
|
||||
* concat, and the sliding/full two-group trunk. */
|
||||
TEST(the_museglimmer_recipes_decide_the_model_they_were_written_for) {
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
{
|
||||
std::ifstream in(dir + "/museglimmer-30b-bf16.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-bf16.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)0);
|
||||
CHECK(r.match("blk.3.attn_q.weight") == nullptr);
|
||||
}
|
||||
{
|
||||
std::ifstream in(dir + "/museglimmer-30b-w4a8.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-w4a8.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)7);
|
||||
const char* i4[] = { "blk.0.attn_q.weight", "blk.51.attn_k.weight", "blk.7.attn_gate.weight",
|
||||
"blk.3.attn_output.weight", "blk.3.ffn_gate_up.weight",
|
||||
"blk.3.ffn_down.weight" };
|
||||
for (const char* n : i4) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i4"));
|
||||
CHECK(has_opt(m, "group", "128"));
|
||||
CHECK(has_opt(m, "scale", "f16"));
|
||||
CHECK(has_opt(m, "rule", "search"));
|
||||
}
|
||||
const RecipeRule* v = r.match("blk.3.attn_v.weight");
|
||||
REQUIRE(v != nullptr);
|
||||
CHECK(has_opt(v, "codes", "i8"));
|
||||
const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight",
|
||||
"blk.3.ffn_norm.weight", "blk.3.ffn_post.weight",
|
||||
"token_embd.weight", "output_norm.weight", "output.weight",
|
||||
"model.vision_tower.layers.3.attn.q_proj.weight" };
|
||||
for (const char* n : kept)
|
||||
CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
/* museglimmer-30b-iq8r as it ships: all seven trunk linears of every layer IQ8R, the head plain
|
||||
* int8 (no rotation), and nothing else: the norms, the embedding, the vision tower and a merged
|
||||
* drafter's `dspark.*` matrices match no rule. */
|
||||
TEST(the_museglimmer_iq8r_recipe_decides_the_model_it_was_written_for) {
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/museglimmer-30b-iq8r.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-iq8r.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)8);
|
||||
const char* iq8r[] = { "blk.0.attn_q.weight", "blk.7.attn_gate.weight", "blk.51.attn_k.weight",
|
||||
"blk.3.attn_v.weight", "blk.3.attn_output.weight",
|
||||
"blk.0.ffn_gate_up.weight", "blk.51.ffn_down.weight" };
|
||||
for (const char* n : iq8r) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "256"));
|
||||
CHECK(has_opt(m, "scale", "u8"));
|
||||
CHECK(has_opt(m, "scale2", "bf16"));
|
||||
CHECK(has_opt(m, "block2", "1x*"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
CHECK(has_opt(m, "clamp", "sym"));
|
||||
CHECK(has_opt(m, "rule", "search"));
|
||||
}
|
||||
const RecipeRule* head = r.match("output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK(has_opt(head, "codes", "i8"));
|
||||
CHECK(has_opt(head, "group", "128"));
|
||||
CHECK(has_opt(head, "scale", "bf16"));
|
||||
CHECK(!has_opt(head, "transform", "fwht128"));
|
||||
const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight",
|
||||
"blk.3.ffn_norm.weight", "blk.3.ffn_post.weight", "token_embd.weight",
|
||||
"output_norm.weight", "v.blk.0.attn.q_proj.weight", "v.proj.weight",
|
||||
"dspark.fc.weight", "dspark.blk.0.attn_q.weight",
|
||||
"dspark.blk.4.ffn_down.weight",
|
||||
"model.vision_tower.layers.3.attn.q_proj.weight" };
|
||||
for (const char* n : kept)
|
||||
CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
|
||||
/* Muse Glimmer IQ4R-V4 uses computed-MAD trellises across the trunk and a compact U3/U4
|
||||
* DFlash2. The target head, embedding, norms, vision, selector and convolutions remain BF16. */
|
||||
TEST(the_museglimmer_iq4r_v4_recipe_selects_the_trellis_trunk) {
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/museglimmer-30b-iq4r-v4.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
const char* old_calib = std::getenv("CALIB");
|
||||
const std::string saved_calib = old_calib ? old_calib : "";
|
||||
setenv("CALIB", "/tmp/muse-glimmer-calib", 1);
|
||||
const int parse_rc = r.add_text(text, "museglimmer-30b-iq4r-v4.recipe", &why);
|
||||
if (old_calib) setenv("CALIB", saved_calib.c_str(), 1);
|
||||
else unsetenv("CALIB");
|
||||
REQUIRE_EQ(parse_rc, RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)14);
|
||||
for (const char* n : { "blk.0.attn_q.weight", "blk.51.attn_gate.weight",
|
||||
"blk.12.attn_k.weight", "blk.12.attn_v.weight",
|
||||
"blk.0.ffn_gate_up.weight", "blk.51.ffn_down.weight" }) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("gptq"));
|
||||
CHECK(has_opt(m, "tcq", "16"));
|
||||
CHECK(has_opt(m, "tcq_code", "mad"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
if (std::string(n).find("ffn_") != std::string::npos)
|
||||
CHECK(has_opt(m, "calib", "/tmp/muse-glimmer-calib"));
|
||||
else
|
||||
CHECK(!has_opt(m, "calib", "$CALIB"));
|
||||
CHECK(has_opt(m, "tcq_order", "1"));
|
||||
}
|
||||
const RecipeRule* kv = r.match("blk.1.attn_k.weight");
|
||||
REQUIRE(kv != nullptr);
|
||||
CHECK(has_opt(kv, "tcq_rows", "128"));
|
||||
for (const char* n : { "dflash.fc.weight", "dflash.blk.0.attn_q.weight",
|
||||
"dflash.blk.4.attn_output.weight", "dflash.blk.0.ffn_gate_up.weight",
|
||||
"dflash.blk.4.ffn_down.weight" }) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("gptq"));
|
||||
CHECK(has_opt(m, "tcq", "16"));
|
||||
CHECK(has_opt(m, "tcq_code", "mad"));
|
||||
CHECK(has_opt(m, "tcq_rows", "256"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
CHECK(!has_opt(m, "calib", "$CALIB"));
|
||||
}
|
||||
CHECK(has_opt(r.match("dflash.blk.0.ffn_down.weight"), "codes", "u3"));
|
||||
CHECK(has_opt(r.match("dflash.blk.0.attn_q.weight"), "codes", "u4"));
|
||||
const RecipeRule* o = r.match("blk.3.attn_output.weight");
|
||||
REQUIRE(o != nullptr);
|
||||
CHECK(has_opt(o, "codes", "u5"));
|
||||
CHECK(has_opt(o, "scale", "bf16"));
|
||||
CHECK(!has_opt(o, "tcq_order", "1"));
|
||||
for (const char* n : { "output.weight", "token_embd.weight", "blk.3.attn_norm.weight",
|
||||
"dflash.blk.0.attn_norm.weight", "dflash.sel_pred", "v.proj.weight",
|
||||
"dspark.fc.weight" })
|
||||
CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
|
||||
/* The Flint recipes as they ship, over arch/flint's declared names. flint-iq8r: every trunk linear
|
||||
* (attention, the two dense layers, the shared expert's gate/up) IQ8R, the routed experts and the
|
||||
* shared expert's down projection rotated int8 at a bf16 scale a (row, 128 of K), the head plain
|
||||
* int8. flint-bf16-q4: u4 attention, signed int4 experts, plain int8 dense, shared and head. In
|
||||
* both the norms, the sinks, the router and its zero correction, and the embedding match no rule. */
|
||||
TEST(the_flint_recipes_decide_the_model_they_were_written_for) {
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
const char* kept[] = { "blk.0.attn_norm.weight", "blk.0.attn_q_norm.weight",
|
||||
"blk.7.attn_k_norm.weight", "blk.0.attn_sinks", "blk.3.ffn_norm.weight",
|
||||
"blk.3.glm_router.weight", "blk.3.glm_router.correction",
|
||||
"token_embd.weight", "output_norm.weight" };
|
||||
{
|
||||
std::ifstream in(dir + "/flint-iq8r.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "flint-iq8r.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)13);
|
||||
const char* iq8r[] = { "blk.0.attn_q.weight", "blk.48.attn_k.weight", "blk.3.attn_v.weight",
|
||||
"blk.5.attn_output.weight", "blk.0.ffn_gate_up.weight",
|
||||
"blk.1.ffn_down.weight", "blk.2.ffn_gate_up_shexp.weight" };
|
||||
for (const char* n : iq8r) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "256"));
|
||||
CHECK(has_opt(m, "scale", "u8"));
|
||||
CHECK(has_opt(m, "scale2", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const char* i8h[] = { "blk.2.ffn_gate_up_exps.0.weight", "blk.48.ffn_down_exps.255.weight",
|
||||
"blk.17.ffn_down_shexp.weight" };
|
||||
for (const char* n : i8h) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "128"));
|
||||
CHECK(has_opt(m, "scale", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const RecipeRule* head = r.match("output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK(has_opt(head, "codes", "i8"));
|
||||
CHECK(!has_opt(head, "transform", "fwht128"));
|
||||
for (const char* n : kept) CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
{
|
||||
std::ifstream in(dir + "/flint-bf16-q4.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "flint-bf16-q4.recipe", &why), RAD_OK);
|
||||
const RecipeRule* a = r.match("blk.9.attn_output.weight");
|
||||
REQUIRE(a != nullptr);
|
||||
CHECK(has_opt(a, "codes", "u4"));
|
||||
CHECK(has_opt(a, "zero", "u8"));
|
||||
const RecipeRule* e = r.match("blk.30.ffn_down_exps.7.weight");
|
||||
REQUIRE(e != nullptr);
|
||||
CHECK(has_opt(e, "codes", "i4"));
|
||||
for (const char* n : { "blk.1.ffn_gate_up.weight", "blk.40.ffn_down_shexp.weight",
|
||||
"output.weight" }) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
}
|
||||
for (const char* n : kept) CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
/* The Ling-3.0-tiny IQ8R recipe as it ships, over arch/bailing_hybrid's declared names: the KDA
|
||||
* projections (fused q|k|v, forget, output gate, out), the MLA out projection, the dense layer's
|
||||
* pair and the shared expert's gate/up IQ8R; the routed experts and the shared expert's down
|
||||
* projection rotated int8 at a bf16 scale a (row, 128 of K). The KDA beta, the MLA's low-rank q
|
||||
* and kv projections, its query parts and its head gate, the convolution taps, the router, the
|
||||
* embedding and the head match no rule and keep the checkpoint's bf16; the norms, the KDA
|
||||
* parameters and the router are cast to the f32 the plugin declares. */
|
||||
TEST(the_ling_tiny_iq8r_recipe_decides_the_model_it_was_written_for) {
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/ling-3.0-tiny-iq8r.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "ling-3.0-tiny-iq8r.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)20);
|
||||
const char* iq8r[] = { "blk.0.attn_qkv.weight", "blk.22.attn_forget.weight",
|
||||
"blk.1.attn_gate.weight", "blk.2.attn_output.weight",
|
||||
"blk.3.attn_output.weight", "blk.0.ffn_gate_up.weight",
|
||||
"blk.0.ffn_down.weight", "blk.1.ffn_gate_up_shexp.weight",
|
||||
"blk.23.ffn_gate_up_shexp.weight" };
|
||||
for (const char* n : iq8r) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "256"));
|
||||
CHECK(has_opt(m, "scale", "u8"));
|
||||
CHECK(has_opt(m, "scale2", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const char* i8h[] = { "blk.1.ffn_gate_up_exps.0.weight", "blk.23.ffn_down_exps.127.weight",
|
||||
"blk.7.ffn_down_shexp.weight" };
|
||||
for (const char* n : i8h) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "128"));
|
||||
CHECK(has_opt(m, "scale", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const char* f32[] = { "blk.0.attn_norm.weight", "blk.3.attn_q_a_norm.weight",
|
||||
"blk.3.attn_kv_a_norm.weight", "blk.1.ffn_norm.weight",
|
||||
"blk.0.ssm_norm.weight", "blk.0.ssm_a", "blk.0.ssm_dt_bias",
|
||||
"blk.1.glm_router.weight", "blk.1.glm_router.correction",
|
||||
"output_norm.weight" };
|
||||
for (const char* n : f32) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("cast"));
|
||||
CHECK(has_opt(m, "dtype", "f32"));
|
||||
}
|
||||
const char* kept[] = { "blk.0.attn_beta.weight", "blk.3.attn_q_a.weight",
|
||||
"blk.3.attn_q_rope.weight", "blk.3.attn_q_nope.weight",
|
||||
"blk.3.attn_kv_a.weight", "blk.3.attn_kv_b.weight",
|
||||
"blk.3.attn_head_gate.weight", "blk.0.ssm_conv.weight",
|
||||
"token_embd.weight", "output.weight" };
|
||||
for (const char* n : kept) CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
|
||||
/* The Ling-3.0-flash recipe as it ships, over arch/bailing_hybrid's declared names: the trunk as the
|
||||
* tiny IQ8R recipe (KDA projections, MLA out, the two dense layers' pair, the shared expert's
|
||||
* gate/up IQ8R; the shared expert's down projection rotated int8 at a bf16 scale a (row, 128 of
|
||||
* K)), the 512 routed experts of a layer rotated four-bit codes into the w4nl codebook at an E4M3
|
||||
* scale a (row, 64 of K). Flash's MLA has no query LoRA, so no q_a norm is cast. The KDA beta, the
|
||||
* MLA's q parts, kv projections and head gate, the convolution taps, the embedding and the head
|
||||
* match no rule and keep the checkpoint's bf16. The experts name their statistics through $CALIB, so the test
|
||||
* sets it. */
|
||||
TEST(the_ling_flash_iq8r_w4nl64_recipe_decides_the_model_it_was_written_for) {
|
||||
::setenv("CALIB", "/data/calib", 1);
|
||||
const std::string dir = std::string(__FILE__).substr(
|
||||
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/ling-3.0-flash-iq8r-w4nl64.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "ling-3.0-flash-iq8r-w4nl64.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)18);
|
||||
const char* iq8r[] = { "blk.0.attn_qkv.weight", "blk.40.attn_forget.weight",
|
||||
"blk.1.attn_gate.weight", "blk.2.attn_output.weight",
|
||||
"blk.5.attn_output.weight", "blk.0.ffn_gate_up.weight",
|
||||
"blk.1.ffn_down.weight", "blk.2.ffn_gate_up_shexp.weight",
|
||||
"blk.41.ffn_gate_up_shexp.weight" };
|
||||
for (const char* n : iq8r) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "256"));
|
||||
CHECK(has_opt(m, "scale", "u8"));
|
||||
CHECK(has_opt(m, "scale2", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const char* w4nl[] = { "blk.2.ffn_gate_up_exps.0.weight", "blk.41.ffn_down_exps.511.weight" };
|
||||
for (const char* n : w4nl) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("gptq"));
|
||||
CHECK(has_opt(m, "table", "w4nl"));
|
||||
CHECK(has_opt(m, "group", "64"));
|
||||
CHECK(has_opt(m, "scale", "fp8_e4m3"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
CHECK(has_opt(m, "calib", "/data/calib"));
|
||||
}
|
||||
{
|
||||
const RecipeRule* m = r.match("blk.7.ffn_down_shexp.weight");
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "i8"));
|
||||
CHECK(has_opt(m, "group", "128"));
|
||||
CHECK(has_opt(m, "scale", "bf16"));
|
||||
CHECK(has_opt(m, "transform", "fwht128"));
|
||||
}
|
||||
const char* f32[] = { "blk.0.attn_norm.weight", "blk.5.attn_kv_a_norm.weight",
|
||||
"blk.2.ffn_norm.weight", "blk.0.ssm_norm.weight", "blk.0.ssm_a",
|
||||
"blk.0.ssm_dt_bias", "blk.2.glm_router.weight",
|
||||
"blk.2.glm_router.correction", "output_norm.weight" };
|
||||
for (const char* n : f32) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("cast"));
|
||||
CHECK(has_opt(m, "dtype", "f32"));
|
||||
}
|
||||
const char* kept[] = { "blk.0.attn_beta.weight", "blk.5.attn_q_rope.weight",
|
||||
"blk.5.attn_q_nope.weight", "blk.5.attn_kv_a.weight",
|
||||
"blk.5.attn_kv_b.weight", "blk.5.attn_head_gate.weight",
|
||||
"blk.0.ssm_conv.weight", "token_embd.weight", "output.weight" };
|
||||
for (const char* n : kept) CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -12,24 +12,25 @@
|
||||
#include "rad_test.h"
|
||||
#include "rad_ref2va_pack.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using Json = rad::Json;
|
||||
using namespace minimaxh3;
|
||||
|
||||
namespace {
|
||||
|
||||
nlohmann::json& golden() {
|
||||
static nlohmann::json g = [] {
|
||||
Json& golden() {
|
||||
static Json g = [] {
|
||||
std::ifstream f(std::string(RAD_REF2VA_GOLDEN) + "/golden.json");
|
||||
if (!f.is_open()) {
|
||||
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
|
||||
"tests/data/ref2va/gen_golden.py\n");
|
||||
std::exit(1);
|
||||
}
|
||||
return nlohmann::json::parse(f);
|
||||
return Json::parse(f);
|
||||
}();
|
||||
return g;
|
||||
}
|
||||
@@ -50,7 +51,7 @@ int ref_kind(const std::string& s) {
|
||||
}
|
||||
|
||||
/* The pack `name`'s case asks for, built. */
|
||||
Ref2VAPack build_case(const nlohmann::json& c) {
|
||||
Ref2VAPack build_case(const Json& c) {
|
||||
Ref2VAGeom g{ c["latent_t"], c["latent_h"], c["latent_w"], c["audio_t"] };
|
||||
std::vector<Ref2VAKeyframe> kfs;
|
||||
for (const auto& k : c["keyframes"])
|
||||
@@ -65,7 +66,7 @@ Ref2VAPack build_case(const nlohmann::json& c) {
|
||||
}
|
||||
|
||||
void check_case(const std::string& name) {
|
||||
const nlohmann::json& c = golden()[name];
|
||||
const Json& c = golden()[name];
|
||||
const Ref2VAPack p = build_case(c);
|
||||
|
||||
CHECK_EQ(p.rows, c["seq_len"].get<int64_t>());
|
||||
|
||||
+437
-348
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,466 @@
|
||||
/* relayout_iqr_test.cpp -- the IQR weights' stored form (libr4d/r4d_iqr.h) from the relayout hook,
|
||||
* against a reference written from the header's description, on every form the kernels are built
|
||||
* for; and back through the inverse.
|
||||
*
|
||||
* The relayout reads each lane's codes of a row as one field and writes a segment as a stream of
|
||||
* dwords; the reference here places every code alone, at the bit r4d_iqr.h names for it, so the
|
||||
* two share no code. The inverse (r4d_rad_unrelayout_iqr) is a third walk of the same order. A
|
||||
* code the form cannot read must refuse the weight.
|
||||
*
|
||||
* libr4d's layouts are host C++, compiled into this test (tests/CMakeLists.txt).
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_encoding.h"
|
||||
#include "r4d_iqr.h"
|
||||
#include "r4d_hsimd.h"
|
||||
#include "r4d_fp8_frag.h"
|
||||
|
||||
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
extern "C" int r4d_rad_layout_iqr(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
extern "C" int r4d_rad_relayout_iqr(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
extern "C" int r4d_rad_unrelayout_iqr(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const void*, int64_t, const RadTensor*, int);
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace r4d_iqr;
|
||||
|
||||
RadParam pint(const char* k, long long v) {
|
||||
RadParam p;
|
||||
std::memset(&p, 0, sizeof p);
|
||||
p.key = k;
|
||||
p.kind = RAD_P_INT;
|
||||
p.ival = v;
|
||||
return p;
|
||||
}
|
||||
RadParam pstr(const char* k, const char* v) {
|
||||
RadParam p;
|
||||
std::memset(&p, 0, sizeof p);
|
||||
p.key = k;
|
||||
p.kind = RAD_P_STR;
|
||||
p.sval = v;
|
||||
return p;
|
||||
}
|
||||
|
||||
uint64_t g_z = 0x9E3779B97F4A7C15ull;
|
||||
uint64_t rnd() {
|
||||
g_z += 0x9E3779B97F4A7C15ull;
|
||||
uint64_t x = g_z;
|
||||
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
|
||||
return x ^ (x >> 31);
|
||||
}
|
||||
|
||||
const uint32_t kU[] = { 0, RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6, RAD_U7,
|
||||
RAD_U8, RAD_U9, RAD_U10, RAD_U11, RAD_U12 };
|
||||
|
||||
/* One weight's planes, as the loader hands them over. */
|
||||
struct W {
|
||||
RadEncoding enc{};
|
||||
std::vector<std::vector<uint8_t>> data;
|
||||
std::vector<int64_t> rows, cols;
|
||||
int find(const char* r) const { return rad_enc_find(&enc, r); }
|
||||
RadTensor t(int i) {
|
||||
RadTensor x;
|
||||
std::memset(&x, 0, sizeof x);
|
||||
x.data = data[(size_t)i].data();
|
||||
x.dtype = enc.plane[i].dtype;
|
||||
x.rank = 2;
|
||||
x.shape[0] = rows[(size_t)i];
|
||||
x.shape[1] = cols[(size_t)i];
|
||||
rad_tensor_pack(&x);
|
||||
return x;
|
||||
}
|
||||
int64_t row_bytes(int i) const { return rad_enc_row_bytes(enc.plane[i].dtype, cols[(size_t)i]); }
|
||||
void size(int64_t n, int64_t k) {
|
||||
data.assign((size_t)enc.n_planes, {});
|
||||
rows.assign((size_t)enc.n_planes, 0);
|
||||
cols.assign((size_t)enc.n_planes, 0);
|
||||
for (int i = 0; i < enc.n_planes; ++i) {
|
||||
rad_enc_plane_dims(&enc.plane[i], n, k, &rows[(size_t)i], &cols[(size_t)i]);
|
||||
data[(size_t)i].assign((size_t)(rows[(size_t)i] * row_bytes(i)), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* kind as r4d_iqr.h's Kind; V the grid's vector; L the trellis' state bits. */
|
||||
struct Case { uint32_t kind; int B, V, L; bool rot; };
|
||||
|
||||
/* The planes of a weight of form `c`, codes at random and the auxiliary plane valid. */
|
||||
W make(const Case& c, int64_t N, int64_t K) {
|
||||
W w;
|
||||
const bool tr = is_trellis(c.kind);
|
||||
if (tr) {
|
||||
rad_enc_clear(&w.enc);
|
||||
rad_enc_copy_str(w.enc.scheme, "trellis");
|
||||
rad_enc_add_plane(&w.enc, "codes", kU[c.B], 1, 1);
|
||||
rad_enc_add_plane(&w.enc, "scale", RAD_F8E4M3, 1, 128);
|
||||
rad_enc_add_plane(&w.enc, "scale.1", RAD_F32, 0, 0);
|
||||
const int t = rad_enc_add_table(&w.enc, "trellis", RAD_I8, (int64_t)1 << c.L, 1);
|
||||
w.enc.plane[t].block[0] = 256;
|
||||
w.enc.plane[t].block[1] = c.L == 12 ? 0 : 32;
|
||||
if (c.kind == kTrellisMad) rad_enc_add_table(&w.enc, "trellis.mad", RAD_U32, 2, 1);
|
||||
} else {
|
||||
w.enc = rad_enc_affine(kU[c.B], RAD_BF16, 1, 128);
|
||||
if (c.kind == kGrid) {
|
||||
w.enc.plane[0].block[1] = c.V;
|
||||
rad_enc_add_table(&w.enc, "grid", RAD_I8, (int64_t)1 << c.B, c.V);
|
||||
} else if (c.kind == kTable) {
|
||||
rad_enc_add_table(&w.enc, "table", RAD_I8, 1, (int64_t)1 << c.B);
|
||||
} else if (c.kind == kZero) {
|
||||
rad_enc_add_plane(&w.enc, "zero", RAD_U6, 1, 128);
|
||||
}
|
||||
}
|
||||
if (c.rot) rad_enc_copy_str(w.enc.transform, "fwht128");
|
||||
w.size(N, K);
|
||||
const int ic = w.find("codes");
|
||||
for (auto& b : w.data[(size_t)ic]) b = (uint8_t)rnd();
|
||||
const int ia = tr ? w.find("trellis") : c.kind == kGrid ? w.find("grid")
|
||||
: c.kind == kTable ? w.find("table") : c.kind == kZero ? w.find("zero") : -1;
|
||||
if (c.kind == kZero) {
|
||||
/* six-bit zeros, a row's unused high bits clear as the inverse leaves them */
|
||||
for (int64_t r = 0; r < N; ++r)
|
||||
for (int64_t kb = 0; kb < K / 128; ++kb)
|
||||
rad_store_bits(w.data[(size_t)ia].data() + r * w.row_bytes(ia), 6, kb,
|
||||
(uint32_t)(rnd() & 63u));
|
||||
} else if (c.kind == kTrellisMad) {
|
||||
const uint32_t A = (uint32_t)(rnd() & 0xFFFFFFu) | 1u, Bc = (uint32_t)rnd();
|
||||
uint32_t* ab = (uint32_t*)w.data[(size_t)w.find("trellis.mad")].data();
|
||||
ab[0] = A;
|
||||
ab[1] = Bc;
|
||||
for (uint32_t st = 0; st < (1u << c.L); ++st) {
|
||||
const uint32_t h = ((st & 0xFFFFFFu) * A + Bc) & 0x3F3F3F3Fu;
|
||||
w.data[(size_t)ia][st] = (uint8_t)(int8_t)((int)((h & 0xFFu) + ((h >> 8) & 0xFFu) +
|
||||
((h >> 16) & 0xFFu) + (h >> 24)) - 126);
|
||||
}
|
||||
} else if (ia >= 0) {
|
||||
for (auto& b : w.data[(size_t)ia]) b = (uint8_t)(int8_t)((int)(rnd() % 255) - 127);
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
const char* aux_role(const Case& c) {
|
||||
return is_trellis(c.kind) ? "trellis" : c.kind == kGrid ? "grid" : c.kind == kTable ? "table"
|
||||
: c.kind == kZero ? "zero" : nullptr;
|
||||
}
|
||||
|
||||
/* The selected planes: codes, the auxiliary plane, A and B for a computed trellis. */
|
||||
struct Sel {
|
||||
std::vector<int> sel;
|
||||
std::vector<RadTensor> t;
|
||||
};
|
||||
Sel select(W& w, const Case& c) {
|
||||
Sel s;
|
||||
std::vector<const char*> roles = { "codes" };
|
||||
if (const char* a = aux_role(c)) roles.push_back(a);
|
||||
if (c.kind == kTrellisMad) roles.push_back("trellis.mad");
|
||||
for (const char* r : roles) {
|
||||
s.sel.push_back(w.find(r));
|
||||
s.t.push_back(w.t(s.sel.back()));
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* r4d_iqr.h's stored weight, every code placed alone. */
|
||||
std::vector<uint8_t> reference(W& w, const Case& c, int64_t N, int64_t K, int64_t bytes) {
|
||||
std::vector<uint8_t> d((size_t)bytes, 0);
|
||||
Form f{};
|
||||
f.kind = c.kind;
|
||||
f.bits = (uint32_t)c.B;
|
||||
f.lv = c.kind == kGrid ? (c.V == 4 ? 2u : 1u) : 0u;
|
||||
const int ic = w.find("codes");
|
||||
const int64_t nkb = K / 128, rbc = w.row_bytes(ic);
|
||||
const int64_t ub = unit_bytes(f) * 8, lb = lane_bits(f);
|
||||
const int per = c.kind == kGrid ? 4 / c.V : 4;
|
||||
for (int64_t rt = 0; rt < N / 16; ++rt)
|
||||
for (int64_t kb = 0; kb < nkb; ++kb)
|
||||
for (int lane = 0; lane < 32; ++lane)
|
||||
for (int r = 0; r < 16; ++r)
|
||||
for (int e = 0; e < per; ++e) {
|
||||
const int64_t col = c.kind == kGrid ? (kb * 128 + 4 * lane) / c.V + e
|
||||
: kb * 128 + 4 * lane + e;
|
||||
const uint32_t code = rad_load_bits(w.data[(size_t)ic].data() +
|
||||
(rt * 16 + r) * rbc, c.B, col);
|
||||
const int64_t idx = is_trellis(c.kind) ? 16 * e + 15 - r : per * r + e;
|
||||
const int64_t bit = (rt * nkb + kb) * ub + lane * lb + idx * c.B;
|
||||
for (int b = 0; b < c.B; ++b)
|
||||
if (code >> b & 1u) d[(size_t)((bit + b) >> 3)] |= (uint8_t)(1u << ((bit + b) & 7));
|
||||
}
|
||||
uint8_t* aux = d.data() + aux_off(f, N, K);
|
||||
const int ia = w.find(aux_role(c) ? aux_role(c) : "codes");
|
||||
if (c.kind == kZero) {
|
||||
for (int64_t r = 0; r < N; ++r)
|
||||
for (int64_t kb = 0; kb < nkb; ++kb)
|
||||
aux[tile_major(r, kb, nkb)] =
|
||||
(uint8_t)rad_load_bits(w.data[(size_t)ia].data() + r * w.row_bytes(ia), 6, kb);
|
||||
} else if (aux_role(c)) {
|
||||
const std::vector<uint8_t>& t = w.data[(size_t)ia];
|
||||
/* A computed trellis keeps A and B alone; every other form its table. */
|
||||
if (c.kind == kTrellisMad) std::memcpy(aux, w.data[(size_t)w.find("trellis.mad")].data(), 8);
|
||||
else std::memcpy(aux, t.data(), t.size());
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
std::vector<RadParam> params(int64_t N, int64_t K, bool rot) {
|
||||
return { pint("N", N), pint("K", K), pint("group", 128), pstr("dtype", rot ? "i8a8h" : "i8a8") };
|
||||
}
|
||||
|
||||
/* Relayout, reference and inverse of one form at one size. */
|
||||
void check_form(const Case& c, int64_t N, int64_t K) {
|
||||
W w = make(c, N, K);
|
||||
Sel s = select(w, c);
|
||||
const std::vector<RadParam> lp = params(N, K, c.rot);
|
||||
RadLayout L;
|
||||
std::memset(&L, 0, sizeof L);
|
||||
REQUIRE_EQ(r4d_rad_layout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), &L), RAD_OK);
|
||||
std::vector<uint8_t> got((size_t)L.bytes, 0xA5);
|
||||
REQUIRE_EQ(r4d_rad_relayout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), got.data(), L.bytes), RAD_OK);
|
||||
const std::vector<uint8_t> want = reference(w, c, N, K, L.bytes);
|
||||
size_t first = got.size();
|
||||
for (size_t i = 0; i < got.size(); ++i)
|
||||
if (got[i] != want[i]) { first = i; break; }
|
||||
if (first != got.size())
|
||||
std::fprintf(stderr, "kind %u B=%d V=%d L=%d N=%lld K=%lld: first differing byte %zu of %zu\n",
|
||||
c.kind, c.B, c.V, c.L, (long long)N, (long long)K, first, got.size());
|
||||
CHECK_EQ(first, got.size());
|
||||
|
||||
/* back: fresh planes of the same shape, filled by the inverse */
|
||||
W back = w;
|
||||
for (auto& p : back.data) std::fill(p.begin(), p.end(), (uint8_t)0x5A);
|
||||
Sel sb = select(back, c);
|
||||
REQUIRE_EQ(r4d_rad_unrelayout_iqr(lp.data(), (int)lp.size(), 2, &back.enc, sb.sel.data(),
|
||||
got.data(), L.bytes, sb.t.data(), (int)sb.t.size()), RAD_OK);
|
||||
for (size_t i = 0; i < s.sel.size(); ++i) {
|
||||
const bool same = back.data[(size_t)s.sel[i]] == w.data[(size_t)s.sel[i]];
|
||||
if (!same)
|
||||
std::fprintf(stderr, "kind %u B=%d: plane %s does not come back\n", c.kind, c.B,
|
||||
w.enc.plane[s.sel[i]].role);
|
||||
CHECK(same);
|
||||
}
|
||||
}
|
||||
|
||||
const Case kForms[] = {
|
||||
{ kTable, 2, 1, 0, false }, { kTable, 3, 1, 0, false }, { kTable, 4, 1, 0, true },
|
||||
{ kTable, 5, 1, 0, false },
|
||||
{ kGrid, 8, 4, 0, false }, { kGrid, 9, 4, 0, false }, { kGrid, 10, 4, 0, true },
|
||||
{ kGrid, 12, 4, 0, false },
|
||||
{ kZero, 6, 1, 0, false },
|
||||
{ kTrellis, 2, 1, 12, true }, { kTrellis, 3, 1, 12, true }, { kTrellis, 5, 1, 12, false },
|
||||
{ kTrellis, 7, 1, 12, true }, { kTrellis, 4, 1, 14, true }, { kTrellis, 6, 1, 14, false },
|
||||
{ kTrellisMad, 2, 1, 16, true }, { kTrellisMad, 3, 1, 16, true }, { kTrellisMad, 4, 1, 16, true },
|
||||
{ kTrellisMad, 5, 1, 16, true }, { kTrellisMad, 6, 1, 16, true }, { kTrellisMad, 7, 1, 16, true },
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(iqr_relayout_every_form_matches_the_header_and_inverts) {
|
||||
for (const Case& c : kForms) check_form(c, 512, 384);
|
||||
}
|
||||
|
||||
/* The trellis tile at every CPU level this host has: each level's vector unpack, transpose and
|
||||
* pack against the same reference. */
|
||||
TEST(iqr_relayout_trellis_matches_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
REQUIRE_EQ(r4d_hsimd::force_level(lvl), lvl);
|
||||
for (const Case& c : kForms)
|
||||
if (is_trellis(c.kind)) check_form(c, 512, 384);
|
||||
check_form({ kTrellisMad, 7, 1, 16, true }, 256, 1024);
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
|
||||
/* The MoE w4 nibble shuffle at every level against the scalar level, both ways, odd tails
|
||||
* included, and its inverse. */
|
||||
TEST(moew4_permute_matches_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
std::vector<uint8_t> src(4100), want(4100), got(4100), back(4100);
|
||||
for (auto& b : src) b = (uint8_t)rnd();
|
||||
for (int64_t n : { (int64_t)4, (int64_t)12, (int64_t)60, (int64_t)68, (int64_t)132, (int64_t)4100 })
|
||||
for (int fwd = 0; fwd < 2; ++fwd) {
|
||||
r4d_hsimd::force_level(0);
|
||||
r4d_hsimd::moew4_permute(src.data(), want.data(), n, fwd);
|
||||
for (int lvl = 1; lvl <= top; ++lvl) {
|
||||
r4d_hsimd::force_level(lvl);
|
||||
std::fill(got.begin(), got.end(), 0);
|
||||
r4d_hsimd::moew4_permute(src.data(), got.data(), n, fwd);
|
||||
CHECK(std::memcmp(got.data(), want.data(), (size_t)n) == 0);
|
||||
r4d_hsimd::moew4_permute(got.data(), back.data(), n, !fwd);
|
||||
CHECK(std::memcmp(back.data(), src.data(), (size_t)n) == 0);
|
||||
}
|
||||
}
|
||||
/* Forward is the canonical-to-kernel order: byte b of a dword holds element b low and b + 4
|
||||
* high. */
|
||||
const uint8_t dw[4] = { 0x10, 0x32, 0x54, 0x76 }; /* elements 0..7 in order */
|
||||
uint8_t out[4];
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
r4d_hsimd::force_level(lvl);
|
||||
r4d_hsimd::moew4_permute(dw, out, 4, true);
|
||||
CHECK_EQ(out[0], 0x40);
|
||||
CHECK_EQ(out[1], 0x51);
|
||||
CHECK_EQ(out[2], 0x62);
|
||||
CHECK_EQ(out[3], 0x73);
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
|
||||
/* Large enough that the relayout splits the weight over threads. */
|
||||
TEST(iqr_relayout_threaded_weight_matches_the_header) {
|
||||
check_form({ kTrellisMad, 4, 1, 16, true }, 4096, 16384);
|
||||
check_form({ kTrellisMad, 3, 1, 16, true }, 4096, 16384);
|
||||
}
|
||||
|
||||
/* A code no entry answers, or one standing for -128, refuses the weight. */
|
||||
TEST(iqr_relayout_refuses_unreadable_codes) {
|
||||
const int64_t N = 32, K = 256;
|
||||
{
|
||||
const Case c{ kTable, 3, 1, 0, false };
|
||||
W w = make(c, N, K);
|
||||
const int ia = w.find("table");
|
||||
w.data[(size_t)ia][5] = (uint8_t)(int8_t)-128;
|
||||
rad_store_bits(w.data[(size_t)w.find("codes")].data() + 7 * w.row_bytes(w.find("codes")), 3, 200, 5);
|
||||
Sel s = select(w, c);
|
||||
const std::vector<RadParam> lp = params(N, K, false);
|
||||
RadLayout L;
|
||||
REQUIRE_EQ(r4d_rad_layout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), &L), RAD_OK);
|
||||
std::vector<uint8_t> d((size_t)L.bytes);
|
||||
CHECK_EQ(r4d_rad_relayout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), d.data(), L.bytes), RAD_E_FORMAT);
|
||||
}
|
||||
{
|
||||
/* a table of 6 entries for 3-bit codes: code 7 has none */
|
||||
const Case c{ kTable, 3, 1, 0, false };
|
||||
W w = make(c, N, K);
|
||||
const int ia = w.find("table");
|
||||
w.enc.plane[ia].extent[1] = 6;
|
||||
w.cols[(size_t)ia] = 6;
|
||||
w.data[(size_t)ia].resize(6);
|
||||
uint8_t* codes = w.data[(size_t)w.find("codes")].data();
|
||||
for (int64_t i = 0; i < N * K; ++i) rad_store_bits(codes, 3, i, (uint32_t)(i % 6));
|
||||
rad_store_bits(codes, 3, 31 * K + 255, 7);
|
||||
Sel s = select(w, c);
|
||||
const std::vector<RadParam> lp = params(N, K, false);
|
||||
RadLayout L;
|
||||
REQUIRE_EQ(r4d_rad_layout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), &L), RAD_OK);
|
||||
std::vector<uint8_t> d((size_t)L.bytes);
|
||||
CHECK_EQ(r4d_rad_relayout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), d.data(), L.bytes), RAD_E_FORMAT);
|
||||
rad_store_bits(codes, 3, 31 * K + 255, 2);
|
||||
CHECK_EQ(r4d_rad_relayout_iqr(lp.data(), (int)lp.size(), 2, &w.enc, s.sel.data(), s.t.data(),
|
||||
(int)s.t.size(), d.data(), L.bytes), RAD_OK);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
|
||||
/* w2a8's stored order, a code at a time, as r4d_layout.cpp's w2_slot. */
|
||||
static void w2a8_reference(const uint8_t* codes, int64_t N, int64_t K, uint32_t* wq) {
|
||||
const int64_t kpb = K / 128;
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const int64_t t = n / 16, r = n % 16, kb = k / 128, kin = k % 128;
|
||||
const int64_t step = kin / 16, d = step / 2, h = step % 2;
|
||||
const int64_t kk = kin % 16, lh = (kk % 8) / 4, e = (kk / 8) * 4 + (kk % 4);
|
||||
const int f = (int)(4 * (e % 4) + (e / 4) + 2 * h);
|
||||
const int64_t w = ((t * kpb + kb) * 32 + lh * 16 + r) * 4 + d;
|
||||
wq[w] |= (uint32_t)((codes[n * (K / 4) + (k >> 2)] >> (2 * (k & 3))) & 3) << (2 * f);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(w2a8_tiles_match_the_slot_order_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
/* An odd unit count, so the widest level's two-unit step leaves one. */
|
||||
for (const int64_t K : { (int64_t)128, (int64_t)384, (int64_t)1024 }) {
|
||||
const int64_t N = 48, rb = K / 4;
|
||||
std::vector<uint8_t> codes((size_t)(N * rb));
|
||||
uint32_t x = 2463534242u;
|
||||
for (uint8_t& c : codes) { x ^= x << 13; x ^= x >> 17; x ^= x << 5; c = (uint8_t)x; }
|
||||
std::vector<uint32_t> want((size_t)(N * K / 16), 0);
|
||||
w2a8_reference(codes.data(), N, K, want.data());
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
REQUIRE_EQ(r4d_hsimd::force_level(lvl), lvl);
|
||||
std::vector<uint32_t> got(want.size(), 0xDEADBEEFu);
|
||||
for (int64_t t = 0; t < N / 16; ++t)
|
||||
r4d_hsimd::w2a8_tile(codes.data() + t * 16 * rb, rb, K / 128,
|
||||
(uint8_t*)got.data() + t * 16 * rb);
|
||||
CHECK_EQ(std::memcmp(got.data(), want.data(), want.size() * 4), 0);
|
||||
}
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
|
||||
TEST(dword_transpose16_matches_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
/* Column counts that leave a tail at every vector width. */
|
||||
for (const int64_t cols : { (int64_t)1, (int64_t)7, (int64_t)12, (int64_t)36, (int64_t)640 }) {
|
||||
const int64_t stride = cols + 3;
|
||||
std::vector<uint32_t> in((size_t)(16 * stride));
|
||||
for (size_t i = 0; i < in.size(); ++i) in[i] = (uint32_t)(i * 2654435761u);
|
||||
std::vector<uint32_t> want((size_t)(16 * cols));
|
||||
for (int64_t c = 0; c < cols; ++c)
|
||||
for (int r = 0; r < 16; ++r) want[(size_t)(16 * c + r)] = in[(size_t)(r * stride + c)];
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
REQUIRE_EQ(r4d_hsimd::force_level(lvl), lvl);
|
||||
std::vector<uint32_t> got(want.size(), 0xDEADBEEFu);
|
||||
r4d_hsimd::dword_transpose16(in.data(), stride, cols, got.data());
|
||||
CHECK(got == want);
|
||||
}
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
|
||||
TEST(fp8_frag_tiles_match_the_fragment_order_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
for (const int64_t K : { (int64_t)64, (int64_t)192, (int64_t)5120 }) {
|
||||
const int64_t ksuper = K / r4d_fp8::kSuperK;
|
||||
std::vector<uint8_t> in((size_t)(16 * K));
|
||||
for (size_t i = 0; i < in.size(); ++i) in[i] = (uint8_t)(i * 2654435761u >> 13);
|
||||
std::vector<uint8_t> want(in.size());
|
||||
int64_t at = 0;
|
||||
for (int64_t ks = 0; ks < ksuper; ++ks)
|
||||
for (int lane = 0; lane < 32; ++lane)
|
||||
for (int t = 0; t < 4; ++t)
|
||||
for (int j = 0; j < 8; ++j, ++at) {
|
||||
int64_t row, k;
|
||||
r4d_fp8::frag_src(0, ks, lane, t, j, &row, &k);
|
||||
want[(size_t)at] = in[(size_t)(row * K + k)];
|
||||
}
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
REQUIRE_EQ(r4d_hsimd::force_level(lvl), lvl);
|
||||
std::vector<uint8_t> got(in.size(), 0xA5);
|
||||
r4d_hsimd::fp8_frag_tile(in.data(), K, ksuper, got.data());
|
||||
CHECK(got == want);
|
||||
}
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
|
||||
TEST(byte_transpose_matches_at_every_cpu_level) {
|
||||
const int top = r4d_hsimd::detect_level();
|
||||
for (const auto& [rows, cols] : std::vector<std::pair<int64_t, int64_t>>{
|
||||
{ 1, 1 }, { 5, 40 }, { 16, 16 }, { 48, 160 }, { 37, 70 }, { 272, 33 } }) {
|
||||
std::vector<uint8_t> in((size_t)(rows * cols));
|
||||
for (size_t i = 0; i < in.size(); ++i) in[i] = (uint8_t)(i * 167 + 13);
|
||||
std::vector<uint8_t> want(in.size());
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < cols; ++c) want[(size_t)(c * rows + r)] = in[(size_t)(r * cols + c)];
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
REQUIRE_EQ(r4d_hsimd::force_level(lvl), lvl);
|
||||
std::vector<uint8_t> got(in.size(), 0xA5);
|
||||
r4d_hsimd::byte_transpose(in.data(), rows, cols, got.data());
|
||||
CHECK(got == want);
|
||||
}
|
||||
}
|
||||
r4d_hsimd::force_level(top);
|
||||
}
|
||||
+90
-114
@@ -17,6 +17,7 @@
|
||||
#include "r4d_plugin.h"
|
||||
#include "opshapes.h"
|
||||
|
||||
#include <array>
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -171,11 +172,6 @@ std::vector<float> weight(int64_t R, int64_t C, uint64_t seed, int64_t br, int64
|
||||
return w;
|
||||
}
|
||||
|
||||
const Hooks nFp8Frag { r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block,
|
||||
r4d_rad_unrelayout_fp8_block };
|
||||
const Hooks nFp8Rows { r4d_rad_layout_fp8_rowmajor, nullptr, nullptr };
|
||||
const Hooks nFp8Lm { r4d_rad_layout_fp8_logits, r4d_rad_relayout_fp8_logits,
|
||||
r4d_rad_unrelayout_fp8_logits };
|
||||
const Hooks nHc { r4d_rad_layout_hc_e4m3, r4d_rad_relayout_hc_e4m3,
|
||||
r4d_rad_unrelayout_hc_e4m3 };
|
||||
const Hooks nMtp { r4d_rad_layout_mtp_e4m3, r4d_rad_relayout_mtp_e4m3,
|
||||
@@ -202,39 +198,40 @@ Opts fp8_grid() {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(block_fp8_in_fragment_order_and_row_major) {
|
||||
NEED_LIBQUANT();
|
||||
{
|
||||
const int64_t N = 272, K = 384; /* a short last row block */
|
||||
const std::vector<float> w = weight(N, K, 11, 128, 128);
|
||||
TEST(a_convolution_weight_is_stored_tap_major_and_reads_back) {
|
||||
for (const auto& [co, ci, k] : std::vector<std::array<long long, 3>>{ { 3, 5, 3 }, { 16, 64, 3 },
|
||||
{ 8, 40, 1 }, { 4, 7, 2 } }) {
|
||||
Opts kp;
|
||||
kp.i("N", N).i("K", K);
|
||||
golden("fp8 frag", stored("fp8 frag", nFp8Frag, kp, "rtn", fp8_grid(),
|
||||
"blk.0.attn_q.weight", N, K, w,
|
||||
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
|
||||
0xd60d2b6299d47a63ull);
|
||||
kp.i("cout", co).i("cin", ci).i("k", k);
|
||||
const long long kk = k * k;
|
||||
std::vector<uint16_t> w((size_t)(co * ci * kk));
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = (uint16_t)(i * 40503u + 7);
|
||||
RadTensor t{};
|
||||
t.data = w.data();
|
||||
t.dtype = RAD_BF16;
|
||||
t.rank = 2;
|
||||
t.shape[0] = co;
|
||||
t.shape[1] = ci * kk;
|
||||
t.stride[0] = ci * kk;
|
||||
t.stride[1] = 1;
|
||||
const RadEncoding enc = rad_enc_plain(RAD_BF16);
|
||||
const int sel = 0;
|
||||
RadLayout L{};
|
||||
REQUIRE_EQ(r4d_rad_layout_conv_tap(kp.data(), kp.n(), 1, &enc, &sel, &t, 1, &L), RAD_OK);
|
||||
std::vector<uint16_t> got((size_t)(L.bytes / 2), 0xA5A5);
|
||||
REQUIRE_EQ(r4d_rad_relayout_conv_tap(kp.data(), kp.n(), 1, &enc, &sel, &t, 1, got.data(), L.bytes), RAD_OK);
|
||||
int64_t bad = 0;
|
||||
for (long long o = 0; o < co; ++o)
|
||||
for (long long c = 0; c < ci; ++c)
|
||||
for (long long tp = 0; tp < kk; ++tp)
|
||||
bad += got[(size_t)((o * kk + tp) * ci + c)] != w[(size_t)((o * ci + c) * kk + tp)];
|
||||
CHECK_EQ(bad, (int64_t)0);
|
||||
std::vector<uint16_t> back(w.size(), 0);
|
||||
RadTensor tb = t;
|
||||
tb.data = back.data();
|
||||
REQUIRE_EQ(r4d_rad_unrelayout_conv_tap(kp.data(), kp.n(), 1, &enc, &sel, got.data(), L.bytes, &tb, 1), RAD_OK);
|
||||
CHECK(back == w);
|
||||
}
|
||||
{
|
||||
const int64_t N = 400, K = 320; /* short blocks on both axes */
|
||||
const std::vector<float> w = weight(N, K, 12, 128, 128);
|
||||
Opts kp;
|
||||
kp.i("N", N).i("K", K);
|
||||
golden("fp8 rows", stored("fp8 rows", nFp8Rows, kp, "rtn", fp8_grid(),
|
||||
"blk.0.attn_o.weight", N, K, w,
|
||||
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
|
||||
0xe90f8e25169cc5e5ull);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_fp8_lm_head_carries_its_block_scales_in_each_row) {
|
||||
NEED_LIBQUANT();
|
||||
const int64_t V = 300, E = 384;
|
||||
const std::vector<float> w = weight(V, E, 13, 128, 128);
|
||||
Opts kp;
|
||||
kp.i("n_vocab", V).i("n_embd", E);
|
||||
golden("fp8 lm", stored("fp8 lm", nFp8Lm, kp, "rtn", fp8_grid(), "output.weight", V, E,
|
||||
w, { { LM_W, { "codes", "scale" } } }),
|
||||
0x4a710b4ca7fa4db0ull);
|
||||
}
|
||||
|
||||
TEST(the_fp8_hyper_connection_and_mtp_rows) {
|
||||
@@ -690,11 +687,68 @@ std::vector<MoeFmt> moe_formats() {
|
||||
{ "w4nl64a8h", nl("w4nl", 64), { "codes", "table" }, { "scale", "scale.1" } },
|
||||
{ "w4nl32a8h", nl("w4nl", 32), { "codes", "table" }, { "scale", "scale.1" } },
|
||||
{ "w5nl64a8h", nl("w5nl", 64), { "codes", "table" }, { "scale", "scale.1" } },
|
||||
{ "w6nl64a8h", nl("w6nl", 64), { "codes", "table" }, { "scale", "scale.1" } },
|
||||
};
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(w6nl_all_codes_have_independent_bit_planes_and_round_trip) {
|
||||
NEED_LIBQUANT();
|
||||
constexpr int64_t N = 64, K = 256;
|
||||
Opts qopt;
|
||||
qopt.s("table", "w6nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
|
||||
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128");
|
||||
Quantised q = quantise(quantizer("rtn"), qopt, "blk.0.ffn_down_exps.0.weight", N, K,
|
||||
draw(N * K, 187, 1.0f));
|
||||
REQUIRE_EQ(q.status, RAD_OK);
|
||||
REQUIRE_EQ(q.enc.plane[0].dtype, (uint32_t)RAD_U6);
|
||||
const int64_t row = rad_enc_row_bytes(RAD_U6, K);
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
rad_store_code(q.planes[0].data() + n * row, RAD_U6, k, (int)((k + n * 17) % 64));
|
||||
Opts kp;
|
||||
kp.i("N", N).i("K", K).i("group", 128).s("dtype", "w6nl64a8h");
|
||||
Selection s = select(q, N, K, { "codes", "table" });
|
||||
RadLayout L{};
|
||||
REQUIRE_EQ(nMoeW4.layout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2, &L), RAD_OK);
|
||||
REQUIRE_EQ(L.bytes, N * K * 6 / 8);
|
||||
std::vector<uint8_t> packed((size_t)L.bytes);
|
||||
REQUIRE_EQ(nMoeW4.relayout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2,
|
||||
packed.data(), L.bytes), RAD_OK);
|
||||
for (int64_t n = 0; n < N; ++n) for (int64_t k = 0; k < K; ++k) {
|
||||
const uint8_t* r = packed.data() + n * K * 6 / 8;
|
||||
const int want = (int)((k + n * 17) % 64);
|
||||
const int lo = (r[(k / 8) * 4 + k % 4] >> ((k % 8 / 4) * 4)) & 15;
|
||||
uint32_t h = 0, sign = 0;
|
||||
std::memcpy(&h, r + K / 2 + (k / 32) * 4, 4);
|
||||
std::memcpy(&sign, r + K / 2 + K / 8 + (k / 32) * 4, 4);
|
||||
const uint32_t bit = 8u * (uint32_t)(k % 4) + 7u - (uint32_t)((k % 32) / 4);
|
||||
CHECK_EQ(lo | (int)(((h >> bit) & 1u) << 4) | (int)(((sign >> bit) & 1u) << 5), want);
|
||||
}
|
||||
std::vector<std::vector<uint8_t>> backbuf;
|
||||
Selection back = select(q, N, K, { "codes", "table" }, &backbuf);
|
||||
REQUIRE_EQ(nMoeW4.unrelayout(kp.data(), kp.n(), B, &q.enc, back.sel.data(), packed.data(),
|
||||
L.bytes, back.t.data(), 2), RAD_OK);
|
||||
CHECK(backbuf[0] == q.planes[0]);
|
||||
CHECK(backbuf[1] == q.planes[(size_t)s.sel[1]]);
|
||||
/* A table with the right shape but different values must never reach the hard-coded GPU LUT. */
|
||||
float bad = 0.0f;
|
||||
std::memcpy(q.planes[(size_t)s.sel[1]].data(), &bad, sizeof bad);
|
||||
s = select(q, N, K, { "codes", "table" });
|
||||
CHECK_EQ(nMoeW4.relayout(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), 2,
|
||||
packed.data(), L.bytes), RAD_E_DTYPE);
|
||||
Selection scale = select(q, N, K, { "scale", "scale.1" });
|
||||
RadLayout LS{};
|
||||
REQUIRE_EQ(nMoeW4.layout(kp.data(), kp.n(), BSCALE, &q.enc, scale.sel.data(), scale.t.data(), 2,
|
||||
&LS), RAD_OK);
|
||||
std::vector<uint8_t> scales((size_t)LS.bytes);
|
||||
const float wrong_scale = 0x1p-12f;
|
||||
std::memcpy(q.planes[(size_t)scale.sel[1]].data(), &wrong_scale, sizeof wrong_scale);
|
||||
CHECK_EQ(nMoeW4.relayout(kp.data(), kp.n(), BSCALE, &q.enc, scale.sel.data(), scale.t.data(), 2,
|
||||
scales.data(), LS.bytes), RAD_E_DTYPE);
|
||||
}
|
||||
|
||||
/* The four-class hooks are the two-class hooks extended. moe_gemm_q_mod4's class q is operands 2/3
|
||||
* at N/K for q = 0 and 2q+4/2q+5 at N_q/K_q after it, and each is stored and read back exactly as
|
||||
* moe_gemm_q's hooks store an expert of that geometry: codes and scales, in every four-bit format,
|
||||
@@ -846,8 +900,6 @@ TEST(a_kernel_refuses_an_encoding_it_does_not_read) {
|
||||
rot.i("N", N).i("K", K).s("dtype", "w4a8h");
|
||||
sym.i("N", N).i("K", K).s("dtype", "w4a8");
|
||||
asym.i("N", N).i("K", K).s("dtype", "w4a8_asym");
|
||||
/* an fp8 GEMM handed int4 */
|
||||
CHECK_EQ(lay(r4d_rad_layout_fp8_block, dense, B, q_i4, { "codes" }), RAD_E_DTYPE);
|
||||
/* a rotated weight to the experts that do not rotate their activation, and the reverse */
|
||||
CHECK_EQ(lay(r4d_rad_layout_moe_w4, plain, B, q_i4r, { "codes" }), RAD_E_DTYPE);
|
||||
CHECK_EQ(lay(r4d_rad_layout_moe_w4, rot, B, q_i4, { "codes" }), RAD_E_DTYPE);
|
||||
@@ -858,8 +910,6 @@ TEST(a_kernel_refuses_an_encoding_it_does_not_read) {
|
||||
CHECK_EQ(lay(r4d_rad_layout_w4, sym, B, q_i4, { "codes" }), RAD_E_DTYPE);
|
||||
/* a block-fp8 weight to the int8 kernel */
|
||||
CHECK_EQ(lay(r4d_rad_layout_w8a8, dense, B, q_f8, { "codes" }), RAD_E_DTYPE);
|
||||
/* the right encoding with the wrong planes selected is a shape error, not a pass */
|
||||
CHECK_EQ(lay(r4d_rad_layout_fp8_block, dense, B, q_f8, { "scale" }), RAD_E_SHAPE);
|
||||
/* a codebook to the two's complement experts, and -8..7 to the codebook's; the codebook's codes
|
||||
* without their table */
|
||||
Opts nlk;
|
||||
@@ -929,78 +979,4 @@ TEST(a_dense_int_kernel_refuses_a_group_it_does_not_compute) {
|
||||
CHECK_EQ(lay(r4d_rad_layout_w2a8, "w2a8", 128, u2_128), RAD_OK);
|
||||
}
|
||||
|
||||
/* ParoQuant's rotation pairs are stored as they are, and refused at load when a stage is not a
|
||||
* pairing within its own group's 128 columns, which the rotate kernels would index out of bounds. */
|
||||
TEST(givens_pairs_are_stored_as_they_are_and_checked) {
|
||||
const int64_t K = 256, R = 2; /* two groups, two stages */
|
||||
RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
rad_enc_add_table(&e, "t.pairs", RAD_I32, R, K);
|
||||
const int sel[1] = { rad_enc_find(&e, "t.pairs") };
|
||||
std::vector<int32_t> pairs((size_t)(R * K));
|
||||
for (int64_t r = 0; r < R; ++r)
|
||||
for (int64_t c = 0; c < K; ++c) /* stage 0 reverses each group, stage 1 not */
|
||||
pairs[(size_t)(r * K + c)] = (int32_t)((c / 128) * 128 + (r ? c % 128 : 127 - c % 128));
|
||||
RadTensor t{};
|
||||
t.data = pairs.data();
|
||||
t.dtype = RAD_I32;
|
||||
t.rank = 2;
|
||||
t.shape[0] = R;
|
||||
t.shape[1] = K;
|
||||
t.stride[0] = K;
|
||||
t.stride[1] = 1;
|
||||
Opts kp;
|
||||
kp.i("n", K).i("stages", 1).i("parts", 2);
|
||||
RadLayout L{};
|
||||
CHECK_EQ(r4d_rad_layout_givens_pairs(kp.data(), kp.n(), 2, &e, sel, &t, 1, &L), RAD_E_UNSUPPORTED);
|
||||
REQUIRE_EQ(r4d_rad_layout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, &L), RAD_OK);
|
||||
REQUIRE_EQ(L.bytes, (int64_t)(R * K * 4));
|
||||
std::vector<uint8_t> dst((size_t)L.bytes);
|
||||
REQUIRE_EQ(r4d_rad_relayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, dst.data(), L.bytes),
|
||||
RAD_OK);
|
||||
CHECK_EQ(std::memcmp(dst.data(), pairs.data(), dst.size()), 0);
|
||||
std::vector<int32_t> back((size_t)(R * K), -1);
|
||||
RadTensor tb = t;
|
||||
tb.data = back.data();
|
||||
REQUIRE_EQ(r4d_rad_unrelayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, dst.data(), L.bytes, &tb, 1),
|
||||
RAD_OK);
|
||||
CHECK(back == pairs);
|
||||
/* a pair leaving its group, and a column paired twice in a stage */
|
||||
std::vector<int32_t> out = pairs, dup = pairs;
|
||||
out[(size_t)(K + 5)] = 130;
|
||||
dup[3] = dup[4];
|
||||
for (std::vector<int32_t>* bad : { &out, &dup }) {
|
||||
t.data = bad->data();
|
||||
CHECK_EQ(r4d_rad_relayout_givens_pairs(kp.data(), kp.n(), 1, &e, sel, &t, 1, dst.data(), L.bytes),
|
||||
RAD_E_FORMAT);
|
||||
}
|
||||
}
|
||||
|
||||
/* ParoQuant's dense rotation matrices are the "t.dense" table rad-convert composed (checkpoint_test
|
||||
* pins the composition by hash). The layout takes the table as stored, byte for byte, and refuses
|
||||
* a view of anything else, including the pairs and angles it would have to compose. */
|
||||
TEST(givens_dense_layout_is_the_stored_table) {
|
||||
const int64_t K = 256, P = 2, G = 128;
|
||||
RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
rad_enc_add_table(&e, "t.pairs", RAD_I32, P * 3, K);
|
||||
rad_enc_add_table(&e, "t.angle", RAD_F32, P * 3, K / 2);
|
||||
rad_enc_add_table(&e, "t.dense", RAD_F16, P * K / G, G * G);
|
||||
std::vector<uint16_t> dense((size_t)(P * K / G * G * G));
|
||||
for (size_t i = 0; i < dense.size(); ++i) dense[i] = (uint16_t)(i * 2654435761u >> 7);
|
||||
RadTensor t{};
|
||||
t.data = dense.data(); t.dtype = RAD_F16; t.rank = 2;
|
||||
t.shape[0] = P * K / G; t.shape[1] = G * G; t.stride[0] = G * G; t.stride[1] = 1;
|
||||
Opts kp;
|
||||
kp.i("n", K).i("parts", P);
|
||||
const int sel[1] = { rad_enc_find(&e, "t.dense") };
|
||||
RadLayout L{};
|
||||
REQUIRE_EQ(r4d_rad_layout_gdense(kp.data(), kp.n(), 1, &e, sel, &t, 1, &L), RAD_OK);
|
||||
REQUIRE_EQ(L.bytes, (int64_t)(P * K * G * 2));
|
||||
std::vector<uint8_t> dst((size_t)L.bytes);
|
||||
REQUIRE_EQ(r4d_rad_relayout_gdense(kp.data(), kp.n(), 1, &e, sel, &t, 1, dst.data(), L.bytes), RAD_OK);
|
||||
CHECK_EQ(std::memcmp(dst.data(), dense.data(), dst.size()), 0);
|
||||
const int sel2[2] = { rad_enc_find(&e, "t.pairs"), rad_enc_find(&e, "t.angle") };
|
||||
RadTensor two[2] = { t, t };
|
||||
CHECK(r4d_rad_layout_gdense(kp.data(), kp.n(), 1, &e, sel2, two, 2, &L) != RAD_OK);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -824,6 +824,47 @@ TEST(a_bank_is_credited_once_for_every_pass_of_its_step) {
|
||||
CHECK_EQ(f.ctx.route_dropped(), (uint64_t)1);
|
||||
}
|
||||
|
||||
/* A plugin's routing table (rad_route_table) is the card-side rows: a layer's row is the table's,
|
||||
* a report naming it is read from there at the end of the pass, and a report naming another
|
||||
* buffer is copied into it. A table short of a row per reporting layer is refused at bind. */
|
||||
TEST(a_routing_table_holds_the_card_side_rows) {
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
const rad_buf tab = f.add_buffer("ecnt", RAD_I32, 2, 4, 1024);
|
||||
f.P.route_table = tab;
|
||||
CHECK_OK(f.start());
|
||||
int32_t* const rows = (int32_t*)f.ctx.buf_ptr(tab);
|
||||
REQUIRE(rows != nullptr);
|
||||
CHECK(f.ctx.route_counts(0, 4) == rows);
|
||||
CHECK(f.ctx.route_counts(1, 4) == rows + 4);
|
||||
|
||||
const int32_t in_place[4] = { 5, 0, 2, 1 };
|
||||
std::memcpy(rows + 4, in_place, sizeof in_place);
|
||||
RadRouting r{};
|
||||
r.n_expert = 4;
|
||||
r.top_k = 2;
|
||||
r.expert_count = rows + 4;
|
||||
CHECK_OK(f.step(1, 0, [&](Ctx& c) { CHECK_OK(c.route_report(1, &r)); }));
|
||||
int b = -1;
|
||||
while ((b = f.ctx.next_histogram(1, -1, 1)) < 0) std::this_thread::yield();
|
||||
const int32_t* h = f.ctx.last_histogram(1, b);
|
||||
CHECK(h != nullptr);
|
||||
if (h) { CHECK_EQ(h[0], 5); CHECK_EQ(h[2], 2); CHECK_EQ(h[3], 1); }
|
||||
|
||||
static const int32_t elsewhere[4] = { 9, 8, 7, 6 };
|
||||
r.expert_count = elsewhere;
|
||||
CHECK_OK(f.step(1, 1, [&](Ctx& c) { CHECK_OK(c.route_report(0, &r)); }));
|
||||
CHECK_OK(rad_stream_sync(f.ctx.stream()));
|
||||
CHECK_EQ(rows[0], 9);
|
||||
CHECK_EQ(rows[3], 6);
|
||||
CHECK_EQ(rows[4], 5); /* the other layer's row is untouched */
|
||||
|
||||
Fixture g;
|
||||
g.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
g.P.route_table = g.add_buffer("ecnt", RAD_I32, 1, 4, 1024);
|
||||
CHECK_EQ(g.start(), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* Every event the context creates at bind is one Ctx::shutdown destroys: the routing ring holds
|
||||
* one per bank, not two. */
|
||||
TEST(shutdown_destroys_every_event_the_context_created) {
|
||||
@@ -2296,6 +2337,36 @@ TEST(a_host_op_reads_what_an_earlier_device_op_wrote_to_the_host_arena) {
|
||||
CHECK_EQ(f.ctx.host_syncs(), (int64_t)3);
|
||||
}
|
||||
|
||||
/* The same in a recorded pass, at every play: the host op waits for the device op the play just
|
||||
* submitted, whatever the pass was entered with. This pass leaves no host-arena touch pending
|
||||
* (its host op joined the only one), so every pass after the first is entered with none; a play
|
||||
* that went by the mark at entry ran the host op at once, on the poison. The host backend records
|
||||
* no tape and runs every round live. */
|
||||
TEST(a_played_pass_joins_its_host_op_to_the_device_op_it_replays) {
|
||||
ord_setup();
|
||||
Fixture f;
|
||||
rad_buf hb = f.add_buffer("ids", RAD_I32, 4, 1, 0);
|
||||
f.P.buffers[hb].decl.domain = RAD_DOMAIN_HOST;
|
||||
rad_op dev = f.add_op("rope", "M", { 8192 }, { k_late_write }, { "late_write" }, nullptr, {});
|
||||
rad_op hst = host_op(f, k_host_read, "host_read");
|
||||
CHECK_OK(f.start(nullptr, false, /*record=*/true));
|
||||
REQUIRE(f.ctx.set_op_domain(hst, RAD_DOMAIN_HOST) == RAD_OK);
|
||||
f.batch.phase = RAD_PHASE_DECODE;
|
||||
for (int round = 0; round < 8; ++round) {
|
||||
*g_ord_value = 2000 + round;
|
||||
*(int32_t*)f.ctx.buf_ptr(hb) = -7; /* the poison */
|
||||
g_ord_seen = -1;
|
||||
CHECK_OK(f.step(1, round, [&](Ctx& c) {
|
||||
const RadOperand o[1] = { RAD_B(hb) };
|
||||
CHECK_OK(c.issue(dev, o, 1, RAD_N_BATCH));
|
||||
CHECK_OK(c.issue(hst, o, 1, RAD_N_BATCH));
|
||||
}));
|
||||
CHECK_EQ(g_ord_seen, 2000 + round);
|
||||
CHECK_OK(rad_stream_sync(f.ctx.stream()));
|
||||
}
|
||||
if (f.ctx.records_passes()) CHECK(f.ctx.pass_counts().played > 0);
|
||||
}
|
||||
|
||||
/* A host op naming memory the arena does not track (a raw pointer) cannot know which device op
|
||||
* wrote it, so it drains the stream first and still reads the written value. */
|
||||
TEST(a_host_op_on_untracked_memory_drains_the_stream_first) {
|
||||
@@ -2475,6 +2546,49 @@ TEST(issue_passes_only_proven_kv_host_summaries) {
|
||||
CHECK_EQ(issue(used_device, 2, 2, RAD_PHASE_PREFILL, 0), 1152); // prefill keeps the exact one
|
||||
}
|
||||
|
||||
/* Under an architecture's pass-key callback as without one, a decode, verify or draft launch reads
|
||||
* the step's keyed context bound, so those passes record; a prefill launch keeps the exact
|
||||
* maximum that the callback keys. */
|
||||
TEST(an_arch_keyed_program_issues_decode_passes_at_the_keyed_bound) {
|
||||
Fixture f;
|
||||
rad_op op = f.add_op("rope", "M", { 8192 }, { k_pre }, { "prefill" }, nullptr, {});
|
||||
CHECK_OK(f.start(nullptr, false, false, test_prefill_geometry_key));
|
||||
|
||||
int32_t used_device[2] = { 896, 1152 }, used_host[2] = { 896, 1152 };
|
||||
RadKVGroupBatch kv{};
|
||||
kv.group = 1;
|
||||
kv.seqused = used_device;
|
||||
kv.seqused_h = used_host;
|
||||
int32_t used_max[1] = { 1152 };
|
||||
f.batch.n_kv_groups = 1;
|
||||
f.batch.kv = &kv;
|
||||
f.batch.kv_used_max_h = used_max;
|
||||
f.batch.max_ctx_len = 2048;
|
||||
f.batch.max_q_len = 2;
|
||||
|
||||
auto issue = [&](int phase, int n_spec, int draft_pass) -> int32_t {
|
||||
f.batch.phase = phase;
|
||||
f.batch.n_tok = 4;
|
||||
f.batch.n_seq = 2;
|
||||
f.batch.n_spec = n_spec;
|
||||
f.batch.draft_pass = draft_pass;
|
||||
g_rec.clear();
|
||||
g_body = [&](Ctx& c) {
|
||||
const RadOperand arg[1] = { RAD_P_T2(used_device, RAD_I32, 2, 1) };
|
||||
(void)c.issue(op, arg, 1, RAD_N_BATCH);
|
||||
};
|
||||
const int status = f.ctx.run_step(&f.batch);
|
||||
g_body = nullptr;
|
||||
if (status < 0 || g_rec.size() != 1) return -999;
|
||||
return g_rec[0].kv_used_max_h;
|
||||
};
|
||||
CHECK_EQ(issue(RAD_PHASE_DECODE, 0, 0), 2050);
|
||||
CHECK_EQ(issue(RAD_PHASE_DECODE, 1, 0), 2050);
|
||||
CHECK_EQ(issue(RAD_PHASE_DECODE, 0, 1), 2050);
|
||||
CHECK_EQ(issue(RAD_PHASE_PREFILL, 0, 0), 1152);
|
||||
CHECK_EQ(issue(RAD_PHASE_MIXED, 0, 0), 1152);
|
||||
}
|
||||
|
||||
TEST(the_prefill_geometry_key_reuses_equal_grids_and_separates_changed_grids) {
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
|
||||
+135
-1
@@ -995,6 +995,28 @@ TEST(json_schema_refuses_a_schema_nested_past_its_limit) {
|
||||
CHECK_OK(grammar_from_json_schema(nested(100), "root", &gbnf, &err));
|
||||
}
|
||||
|
||||
TEST(json_schema_conversion_is_cached_by_schema_text) {
|
||||
/* The same schema text converts to the same grammar every time, and a schema that
|
||||
* differs anywhere converts to its own; admission on /v1/completions sees the same
|
||||
* schema resent per request and must not re-derive it (nor confuse two schemas). */
|
||||
const char* schema =
|
||||
R"({"type":"object","properties":{"city":{"type":"string"},"days":{"type":"integer"}},"required":["city"]})";
|
||||
std::string a, b, c, err;
|
||||
CHECK_OK(grammar_from_json_schema(schema, "root", &a, &err));
|
||||
CHECK_OK(grammar_from_json_schema(schema, "root", &b, &err));
|
||||
CHECK_EQ(a, b);
|
||||
CHECK(!a.empty());
|
||||
CHECK_OK(grammar_from_json_schema(
|
||||
R"({"type":"object","properties":{"city":{"type":"string"},"days":{"type":"string"}},"required":["city"]})",
|
||||
"root", &c, &err));
|
||||
CHECK(c != a);
|
||||
/* A refusal is not cached as a grammar, and does not poison the cached one. */
|
||||
CHECK(grammar_from_json_schema("{\"not\":{\"type\":\"string\"}}", "root", &c, &err) < 0);
|
||||
std::string d;
|
||||
CHECK_OK(grammar_from_json_schema(schema, "root", &d, &err));
|
||||
CHECK_EQ(d, a);
|
||||
}
|
||||
|
||||
/* The bounded machinery against upstream's walk, over the shapes the bounds were built for: a star
|
||||
* over something nullable, a wide converging rule (past the 64 stacks a firing pattern is
|
||||
* memoised for and the 16 past which a set is indexed), an ambiguous rule whose stack set grows,
|
||||
@@ -1506,7 +1528,7 @@ struct HostChain {
|
||||
|
||||
HostChain(int64_t n_vocab, int64_t max_seqs, int max_spec, const VocabView* vocab = nullptr,
|
||||
int64_t max_candidates = 8, const char* second_plugin = nullptr,
|
||||
bool draft_coupling = false)
|
||||
bool draft_coupling = false, bool verify_block = false, bool verify_traversal = false)
|
||||
: nv(n_vocab) {
|
||||
/* libref alone: it is the implementation under test, and a directory scan would also
|
||||
* pick up whatever else was built beside it. */
|
||||
@@ -1549,6 +1571,8 @@ struct HostChain {
|
||||
cfg.max_hist = 64;
|
||||
cfg.max_candidates = max_candidates;
|
||||
cfg.draft_coupling = draft_coupling;
|
||||
cfg.draft_verify_block = verify_block;
|
||||
cfg.draft_verify_traversal = verify_traversal;
|
||||
if (s.declare(&b, cfg) < 0) return;
|
||||
if (b.finish() < 0) return;
|
||||
prog = std::move(b.program());
|
||||
@@ -3198,6 +3222,21 @@ TEST(each_rank_stages_its_window_of_the_grammar_mask) {
|
||||
CHECK(r0.staged(0, off) == want0);
|
||||
CHECK(r1.staged(off, sp2[1]) == want1);
|
||||
|
||||
/* t60..t69 lie on rank 1 across its first word's top bits (from the source word after
|
||||
* the one the window starts in) and its second word. */
|
||||
SamplingParams hi = greedy_params();
|
||||
hi.grammar = "root ::= \"t6\" [0-9]";
|
||||
Request h = make_req(9, { 70 }, hi);
|
||||
for (SplitRank* r : { &r0, &r1 }) {
|
||||
std::string err;
|
||||
REQUIRE(r->s.begin_request(9, hi, &err) >= 0);
|
||||
REQUIRE(r->s.build_step({ &h }) >= 0);
|
||||
}
|
||||
std::vector<int32_t> want_hi;
|
||||
for (int32_t id = 60; id <= 69; ++id) want_hi.push_back(id);
|
||||
CHECK(r0.staged(0, off).empty());
|
||||
CHECK(r1.staged(off, sp2[1]) == want_hi);
|
||||
|
||||
/* A spent thinking budget, the close on rank 1 and admitted by the grammar: only its
|
||||
* bit, on rank 1. */
|
||||
SamplingParams th = greedy_params();
|
||||
@@ -3560,6 +3599,101 @@ TEST(the_coupled_evidence_survives_the_drafters_greedy_build) {
|
||||
CHECK_EQ(ev.rows, (int64_t)6);
|
||||
}
|
||||
|
||||
/* --draft-verify block: the chain rows bound from round 1 on, consecutively, carry the block's
|
||||
* length in `blk` (what the verify's round-1 row decides from); the bonus row and a row after a
|
||||
* gap do not, and without the flag nothing is marked. */
|
||||
TEST(block_verification_marks_the_consecutive_bound_rows_of_a_chain) {
|
||||
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true, true);
|
||||
if (!ch.ok) {
|
||||
fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n",
|
||||
::radtest::current(), home().c_str());
|
||||
return;
|
||||
}
|
||||
SamplingParams sp;
|
||||
sp.temp = 1.0f;
|
||||
const int32_t draft[3] = { 21, 22, 23 };
|
||||
Request r = make_req(7, { 1, 2, 3 }, sp);
|
||||
r.draft = draft;
|
||||
r.n_draft = 3;
|
||||
std::string err;
|
||||
CHECK_OK(ch.s.begin_request(r.id, r.sp, &err));
|
||||
const uint64_t n_out = r.output.size();
|
||||
RadMtpCoupleState bound[3];
|
||||
couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound);
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
|
||||
std::vector<Request*> reqs = { &r };
|
||||
CHECK_OK(ch.s.build_step(reqs));
|
||||
for (int k = 0; k < 3; ++k) CHECK_EQ(ch.s.staged_couple(k).blk, 3);
|
||||
CHECK_EQ(ch.s.staged_couple(3).blk, 0);
|
||||
|
||||
/* row 1 stale: the block is row 0 alone; row 2 is bound but past the gap, so token-wise */
|
||||
bound[1].pos += 1;
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
|
||||
CHECK_OK(ch.s.build_step(reqs));
|
||||
CHECK_EQ(ch.s.staged_couple(0).blk, 1);
|
||||
CHECK_EQ(ch.s.staged_couple(1).round, 0);
|
||||
CHECK_EQ(ch.s.staged_couple(2).round, 3);
|
||||
CHECK_EQ(ch.s.staged_couple(2).blk, 0);
|
||||
|
||||
/* the same chain without the flag is not marked */
|
||||
HostChain plain(64, 2, 3, nullptr, 8, "spechub.so", true, false);
|
||||
CHECK(plain.ok);
|
||||
CHECK_OK(plain.s.begin_request(r.id, r.sp, &err));
|
||||
couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound);
|
||||
CHECK_OK(plain.s.set_mtp_couple(r.id, bound, 3));
|
||||
CHECK_OK(plain.s.build_step(reqs));
|
||||
for (int k = 0; k < 3; ++k) CHECK_EQ(plain.s.staged_couple(k).blk, 0);
|
||||
}
|
||||
|
||||
/* TRAVERSAL VERIFICATION THROUGH THE SAMPLER (--draft-verify traversal, abi/rad_mtp_traversal.h).
|
||||
*
|
||||
* The chain 21, 22, 23 with a point-mass draft law at every round. The sampler stages the per-row
|
||||
* topology plane (parent row, draft token) and issues `mtp_trav_verify` instead of the row-wise
|
||||
* verify. With the target peaked on 31 at every row the walk rejects the chain (the first draft's
|
||||
* ratio is ~e^-20) and the root row's token comes from the residual law, 31; with the target
|
||||
* peaked on each draft the walk accepts the whole chain and the final token is the bonus row's
|
||||
* own pick. */
|
||||
TEST(traversal_verification_walks_the_staged_chain_through_the_sampler) {
|
||||
HostChain ch(64, 2, 3, nullptr, 8, "spechub.so", true, false, true);
|
||||
if (!ch.ok) {
|
||||
fprintf(stderr, " SKIP %s: libref/spechub did not load from %s/kernels\n",
|
||||
::radtest::current(), home().c_str());
|
||||
return;
|
||||
}
|
||||
CHECK(ch.s.staged_couple_op() != RAD_NULL_HANDLE);
|
||||
SamplingParams sp;
|
||||
sp.temp = 1.0f;
|
||||
const int32_t draft[3] = { 21, 22, 23 };
|
||||
Request r = make_req(7, { 1, 2, 3 }, sp);
|
||||
r.draft = draft;
|
||||
r.n_draft = 3;
|
||||
std::string err;
|
||||
CHECK_OK(ch.s.begin_request(r.id, r.sp, &err));
|
||||
const uint64_t n_out = r.output.size();
|
||||
RadMtpCoupleState bound[3];
|
||||
couple_states(r.id, r.sp.seed, draft, 3, rad_mtp_couple_verify_pos(n_out, 1), bound);
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
|
||||
|
||||
std::vector<float> lg(4 * 64, 0.0f);
|
||||
for (int row = 0; row < 4; ++row) lg[(size_t)row * 64 + 31] = 20.0f;
|
||||
std::vector<int32_t> tok;
|
||||
CHECK_OK(ch.step({ &r }, lg, &tok));
|
||||
REQUIRE_EQ(tok.size(), (size_t)4);
|
||||
CHECK_EQ(tok[0], 31); /* the chain is rejected at its first draft: the residual's token */
|
||||
|
||||
CHECK_OK(ch.s.set_mtp_couple(r.id, bound, 3));
|
||||
std::vector<float> lg2(4 * 64, 0.0f);
|
||||
lg2[0 * 64 + 21] = 20.0f;
|
||||
lg2[1 * 64 + 22] = 20.0f;
|
||||
lg2[2 * 64 + 23] = 20.0f;
|
||||
lg2[3 * 64 + 9] = 20.0f;
|
||||
CHECK_OK(ch.step({ &r }, lg2, &tok));
|
||||
CHECK_EQ(tok[0], 21);
|
||||
CHECK_EQ(tok[1], 22);
|
||||
CHECK_EQ(tok[2], 23);
|
||||
CHECK_EQ(tok[3], 9);
|
||||
}
|
||||
|
||||
/* The planes are sized for the rows a step can sample: one per token the step carries, so never
|
||||
* more than max_tok, and never fewer than max_seqs (a drafter's greedy pass). */
|
||||
TEST(the_sampler_rows_are_bounded_by_the_steps_tokens) {
|
||||
|
||||
+1001
-50
File diff suppressed because it is too large.
Load diff
@@ -27,7 +27,7 @@
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
@@ -44,7 +44,6 @@
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::server;
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
/* ================================================================== text */
|
||||
|
||||
|
||||
+342
-10
@@ -720,6 +720,9 @@ TEST(the_ways_of_turning_thinking_off_all_reach_the_template) {
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"chat_template_kwargs":{"enable_thinking":false}})",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"enable_thinking":false})",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"reasoning":{"enabled":false}})",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"reasoning":{"effort":"none"}})",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"thinking":{"type":"disabled"}})",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"none"})" }) {
|
||||
Fixture f;
|
||||
CHECK_EQ(f.post("/v1/chat/completions", body).status, 200);
|
||||
@@ -732,6 +735,41 @@ TEST(the_ways_of_turning_thinking_off_all_reach_the_template) {
|
||||
CHECK(f.tmpl.last_opt.enable_thinking);
|
||||
}
|
||||
|
||||
/* The grouped spellings, and the switches that are refused by name instead of dropped.
|
||||
* OpenRouter's `reasoning` object carries the flat fields; asking to keep the reasoning
|
||||
* out of the reply, or to merge it into it, is never served silently as the opposite. */
|
||||
TEST(the_grouped_reasoning_spellings_reach_the_template_or_are_refused) {
|
||||
Fixture f;
|
||||
CHECK_EQ(f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"reasoning":{"effort":"high"}})").status, 200);
|
||||
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"),
|
||||
std::string("\"high\""));
|
||||
/* A flat spelling named with the grouped one wins, as with the other spellings. */
|
||||
CHECK_EQ(f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"reasoning":{"effort":"high"},"reasoning_effort":"low"})").status, 200);
|
||||
CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"),
|
||||
std::string("\"low\""));
|
||||
struct Case { const char* extra; const char* param; };
|
||||
for (const Case& c : { Case{ R"("reasoning":{"exclude":true})", "reasoning.exclude" },
|
||||
Case{ R"("include_reasoning":false)", "include_reasoning" },
|
||||
Case{ R"("separate_reasoning":false)", "separate_reasoning" },
|
||||
Case{ R"("reasoning":true)", "reasoning" },
|
||||
Case{ R"("thinking":{"type":"sideways"})", "thinking.type" } }) {
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
std::string(R"({"messages":[{"role":"user","content":"hi"}],)") +
|
||||
c.extra + "}");
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK_EQ(json::parse(r.body)["error"]["param"].get<std::string>(), std::string(c.param));
|
||||
}
|
||||
/* At the values this server's replies already have, both switches are accepted. */
|
||||
CHECK_EQ(f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"include_reasoning":true,"separate_reasoning":true})").status, 200);
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
/* ================================================================== deployment defaults
|
||||
*
|
||||
* Every default the command line can move, seen from a request: it reaches a request that leaves
|
||||
@@ -1602,6 +1640,8 @@ TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) {
|
||||
const json c = json::parse(r.body)["choices"][0];
|
||||
CHECK_EQ(c["finish_reason"].get<std::string>(), std::string("stop"));
|
||||
CHECK_EQ(c["message"]["reasoning_content"].get<std::string>(), std::string("Look first.\n"));
|
||||
/* The same text under vLLM's name for it, so either reader keeps it. */
|
||||
CHECK_EQ(c["message"]["reasoning"].get<std::string>(), std::string("Look first.\n"));
|
||||
CHECK_EQ(c["message"]["content"].get<std::string>(), "Checking.\n" + open);
|
||||
REQUIRE(c["message"].contains("tool_calls") && c["message"]["tool_calls"].size() == 1);
|
||||
CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get<std::string>(),
|
||||
@@ -1611,7 +1651,7 @@ TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) {
|
||||
HttpResponse s = f.post("/v1/chat/completions", body + R"(,"stream":true})");
|
||||
CHECK_EQ(s.status, 200);
|
||||
int bad = 0;
|
||||
std::string reasoning, finish;
|
||||
std::string reasoning, reasoning_alias, finish;
|
||||
std::vector<std::string> args;
|
||||
for (const std::string& p : sse_payloads(drain(s), &bad)) {
|
||||
if (p == "[DONE]") continue;
|
||||
@@ -1621,6 +1661,7 @@ TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) {
|
||||
if (!ch["finish_reason"].is_null()) finish = ch["finish_reason"].get<std::string>();
|
||||
const json& d = ch["delta"];
|
||||
if (d.contains("reasoning_content")) reasoning += d["reasoning_content"].get<std::string>();
|
||||
if (d.contains("reasoning")) reasoning_alias += d["reasoning"].get<std::string>();
|
||||
if (!d.contains("tool_calls")) continue;
|
||||
const size_t k = d["tool_calls"][0]["index"].get<size_t>();
|
||||
if (k >= args.size()) args.resize(k + 1);
|
||||
@@ -1630,6 +1671,7 @@ TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) {
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK_EQ(finish, std::string("stop"));
|
||||
CHECK_EQ(reasoning, std::string("Look first.\n"));
|
||||
CHECK_EQ(reasoning_alias, reasoning);
|
||||
REQUIRE(!args.empty());
|
||||
CHECK_EQ(args[0], std::string("{\"command\":\"ls\"}"));
|
||||
}
|
||||
@@ -1878,10 +1920,24 @@ TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
|
||||
CHECK(f.sched.last_sp.reasoning.starts_open);
|
||||
}
|
||||
|
||||
/* The grouped spellings carry the same budget. */
|
||||
for (const char* extra : { R"("reasoning":{"max_tokens":7})",
|
||||
R"("thinking":{"type":"enabled","budget_tokens":7})" }) {
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
std::string(R"({"messages":[{"role":"user","content":"hi"}],)") +
|
||||
extra + "}");
|
||||
CHECK_EQ(r.status, 200);
|
||||
f.sched.join_all();
|
||||
std::lock_guard<std::mutex> lk(f.sched.mu);
|
||||
CHECK_EQ(f.sched.last_sp.thinking_budget, 7);
|
||||
}
|
||||
|
||||
struct Case { const char* extra; const char* param; };
|
||||
for (const Case& c : { Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
|
||||
"thinking_budget" },
|
||||
Case{ R"("thinking_budget":"3")", "thinking_budget" } }) {
|
||||
Case{ R"("thinking_budget":"3")", "thinking_budget" },
|
||||
Case{ R"("thinking_token_budget":3,"reasoning":{"max_tokens":4})",
|
||||
"reasoning.max_tokens" } }) {
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
std::string(R"({"messages":[{"role":"user","content":"hi"}],)") +
|
||||
c.extra + "}");
|
||||
@@ -2198,6 +2254,41 @@ TEST(a_dropped_stream_cancels_at_the_scheduler) {
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
/* A model leaving its cards ends its streams even when the engine has stopped answering: the
|
||||
* response's lease is what keeps the server alive, so a stream that waits for the engine keeps a
|
||||
* park or an unload waiting, and a server freed under it faults at the client's hang-up. */
|
||||
TEST(ending_streams_ends_a_stream_the_engine_no_longer_feeds) {
|
||||
Fixture f;
|
||||
f.sched.reply = "abcdefgh";
|
||||
f.sched.hang = true; /* never finishes on its own */
|
||||
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = "/v1/chat/completions";
|
||||
q.body = R"({"messages":[{"role":"user","content":"hi"}],"stream":true})";
|
||||
q.closed = [] { return false; };
|
||||
|
||||
HttpResponse r = f.srv->router().dispatch(q);
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(r.streaming());
|
||||
for (int i = 0; i < 4; ++i) { std::string c; r.next(c); }
|
||||
CHECK_EQ(f.srv->in_flight(), 1LL);
|
||||
|
||||
f.srv->end_streams(true);
|
||||
std::string last;
|
||||
const bool more = r.next(last);
|
||||
CHECK(!more);
|
||||
/* Not a silent end: the client sees why, and the stream still closes the OpenAI way. */
|
||||
CHECK(last.find("leaving its cards") != std::string::npos);
|
||||
CHECK(last.find("[DONE]") != std::string::npos);
|
||||
r.on_close(true);
|
||||
|
||||
CHECK(f.sched.saw_cancel());
|
||||
CHECK_EQ(f.srv->in_flight(), 0LL);
|
||||
f.srv->end_streams(false);
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
TEST(a_dropped_non_streaming_request_cancels_too) {
|
||||
Fixture f;
|
||||
f.sched.reply = "abcdefgh";
|
||||
@@ -2524,6 +2615,24 @@ TEST(the_steps_a_prefill_interleave_held_are_counted) {
|
||||
CHECK(it != d.samples.end() && it->second == 6.0);
|
||||
}
|
||||
|
||||
TEST(the_mixed_step_target_controller_is_observable) {
|
||||
Metrics m("m", 1024);
|
||||
server::SchedMetrics s;
|
||||
s.mixed_step_target_steps = 9;
|
||||
s.mixed_step_target_misses = 2;
|
||||
s.mixed_step_target_prefill_cap = 384;
|
||||
m.sample(s);
|
||||
PromDoc d = parse_prom(m.render());
|
||||
CHECK_EQ((int)d.errors.size(), 0);
|
||||
CHECK_EQ(d.type["radiance:mixed_step_target_steps_total"], std::string("counter"));
|
||||
CHECK_EQ(d.type["radiance:mixed_step_target_misses_total"], std::string("counter"));
|
||||
CHECK_EQ(d.type["radiance:mixed_step_target_prefill_cap"], std::string("gauge"));
|
||||
const auto cap = d.samples.find(
|
||||
"radiance:mixed_step_target_prefill_cap{model_name=\"m\",engine=\"0\"}");
|
||||
CHECK(cap != d.samples.end());
|
||||
if (cap != d.samples.end()) CHECK_NEAR(cap->second, 384.0, 1e-9);
|
||||
}
|
||||
|
||||
/* Each draft position's acceptances are a counter next to its reach. At a fixed depth position
|
||||
* j+1's reach is j's acceptances, but an adaptive window can end at j with j taken, so a ratio
|
||||
* over a window needs both. Here two verifies end at position 1 with it accepted. */
|
||||
@@ -2585,6 +2694,20 @@ TEST(the_adaptive_draft_window_is_exposed_only_while_it_is_on) {
|
||||
CHECK_NEAR(value("radiance:draft_verify_depth_total" + L + ",depth=\"6\"}"), -1.0, 1e-9);
|
||||
}
|
||||
|
||||
/* The front matches /v1/models/ID itself and hands the request on with the path rewritten: an
|
||||
* alias becomes the model's name, `base:adapter` the adapter's. The model's router reads the id its
|
||||
* own route captured, not the front's, so the request still carries the front's capture here. */
|
||||
TEST(a_request_handed_on_reads_the_capture_of_the_route_that_matched_it) {
|
||||
Fixture f;
|
||||
HttpRequest q;
|
||||
q.method = "GET";
|
||||
q.path = "/v1/models/test-model";
|
||||
q.params["id"] = "an-alias";
|
||||
const HttpResponse r = f.srv->router().dispatch(q);
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK_EQ(json::parse(r.body).value("id", std::string()), std::string("test-model"));
|
||||
}
|
||||
|
||||
TEST(models_and_health_answer) {
|
||||
Fixture f;
|
||||
HttpResponse r = f.get("/v1/models");
|
||||
@@ -2787,6 +2910,36 @@ TEST(the_models_root_path_follows_the_key) {
|
||||
std::string("/models/m.rad"));
|
||||
}
|
||||
|
||||
/* The predicate every keyless "loopback only" guard reads -- hoisted so the fleet's front applies
|
||||
* the very rule the engine's routes do (fleet.cpp: the admin/fleet guard). The three legs:
|
||||
* loopback socket, no foreign Origin, a Host that names this box. */
|
||||
TEST(local_operator_reads_all_three_legs) {
|
||||
const std::vector<std::string> pinned = {"box.example"};
|
||||
auto ask = [&](const char* peer, const char* host, const char* origin,
|
||||
const char* bind) {
|
||||
HttpRequest q;
|
||||
q.peer = q.raw_peer = peer;
|
||||
if (host) q.headers["Host"] = host;
|
||||
if (origin) q.headers["Origin"] = origin;
|
||||
return local_operator(q, bind, pinned);
|
||||
};
|
||||
/* The machine dialling itself: loopback socket, loopback Host. */
|
||||
CHECK(ask("127.0.0.1:50122", "localhost:8000", nullptr, "0.0.0.0"));
|
||||
/* A pinned --allow-host name and a concrete --host bind answer for the box. */
|
||||
CHECK(ask("127.0.0.1:50122", "box.example:8000", nullptr, "0.0.0.0"));
|
||||
CHECK(ask("127.0.0.1:50122", "10.3.1.5", nullptr, "10.3.1.5"));
|
||||
/* The rebinding page: same-origin with itself, so no Origin leg fires -- the Host leg is
|
||||
* what refuses it. */
|
||||
CHECK(!ask("127.0.0.1:50122", "evil.test:8000", "http://evil.test:8000", "0.0.0.0"));
|
||||
/* The localhost proxy: every remote client arrives on a loopback socket carrying the
|
||||
* public Host, and no leg names that name. */
|
||||
CHECK(!ask("127.0.0.1:50122", "public.example:8000", nullptr, "0.0.0.0"));
|
||||
/* A foreign Origin never rides a loopback socket into a guard, whatever the Host says. */
|
||||
CHECK(!ask("127.0.0.1:50122", "localhost:8000", "http://evil.test", "0.0.0.0"));
|
||||
/* A remote socket is no operator, however it names itself. */
|
||||
CHECK(!ask("192.168.1.20:50122", "localhost:8000", nullptr, "0.0.0.0"));
|
||||
}
|
||||
|
||||
TEST(the_model_entry_and_server_info_report_the_same_capabilities) {
|
||||
Fixture f;
|
||||
const json info = json::parse(f.get("/server_info").body)["capabilities"];
|
||||
@@ -2838,10 +2991,10 @@ TEST(a_stable_prefix_never_cuts_a_code_point_or_an_escape) {
|
||||
CHECK_EQ((long long)json_stable_prefix("x\\u0041"), 7LL);
|
||||
}
|
||||
|
||||
/* A string literal is written exactly as nlohmann writes it and refused exactly where nlohmann
|
||||
/* A string literal is written exactly as Json::dump writes it and refused exactly where it
|
||||
* refuses: every byte value alone and after each lead byte, and random strings drawn from the
|
||||
* deciding bytes (controls, quote and backslash, DEL, continuation and lead bytes). */
|
||||
TEST(a_quoted_string_is_what_nlohmann_writes) {
|
||||
TEST(a_quoted_string_is_what_the_dom_writes) {
|
||||
auto agree = [](const std::string& s) {
|
||||
std::string got = "x";
|
||||
const bool ok = json_quote_append(got, s);
|
||||
@@ -2849,7 +3002,7 @@ TEST(a_quoted_string_is_what_nlohmann_writes) {
|
||||
bool refused = false;
|
||||
try {
|
||||
want = "x" + json(s).dump();
|
||||
} catch (const nlohmann::json::type_error&) {
|
||||
} catch (const Json::exception&) {
|
||||
refused = true;
|
||||
}
|
||||
CHECK_EQ(ok, !refused);
|
||||
@@ -3390,6 +3543,46 @@ TEST(llama_server_spellings_reach_the_engine) {
|
||||
CHECK_EQ(post(R"(,"max_tokens":-1)").status, 200);
|
||||
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK(f.sched.last_max_tokens != 32); }
|
||||
CHECK_EQ(post(R"(,"max_tokens":0)").status, 400);
|
||||
|
||||
/* The other spellings that echo back from /props and cross-API clients. */
|
||||
CHECK_EQ(post(R"(,"typ_p":0.8,"max_completion_tokens":6)").status, 200);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(f.sched.mu);
|
||||
CHECK_NEAR(f.sched.last_sp.typical_p, 0.8, 1e-6);
|
||||
CHECK_EQ(f.sched.last_max_tokens, 6);
|
||||
}
|
||||
CHECK_EQ(post(R"(,"typical_p":0.8,"typ_p":0.9)").status, 400);
|
||||
CHECK_EQ(post(R"(,"max_tokens":5,"max_completion_tokens":5)").status, 200);
|
||||
CHECK_EQ(post(R"(,"max_tokens":4,"max_completion_tokens":5)").status, 400);
|
||||
CHECK_EQ(post(R"(,"max_output_tokens":7)").status, 200);
|
||||
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK_EQ(f.sched.last_max_tokens, 7); }
|
||||
CHECK_EQ(post(R"(,"max_new_tokens":8)").status, 200);
|
||||
{ std::lock_guard<std::mutex> lk(f.sched.mu); CHECK_EQ(f.sched.last_max_tokens, 8); }
|
||||
CHECK_EQ(post(R"(,"no_repeat_ngram_size":35,"no_repeat_ngram_window_size":128)").status, 200);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(f.sched.mu);
|
||||
CHECK_EQ(f.sched.last_sp.ngram_ban_n, 35);
|
||||
CHECK_EQ(f.sched.last_sp.ngram_window, 128);
|
||||
}
|
||||
CHECK_EQ(post(R"(,"ngram_ban_n":35,"no_repeat_ngram_size":36)").status, 400);
|
||||
}
|
||||
|
||||
/* OpenRouter asks for the usage chunk at the top level; continuous stats, which would put
|
||||
* usage on every chunk, are refused by name rather than answered with only the last. */
|
||||
TEST(openrouters_usage_ask_gets_the_final_usage_chunk) {
|
||||
Fixture f;
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"stream":true,
|
||||
"usage":{"include":true}})");
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(has(drain(r), "\"usage\""));
|
||||
HttpResponse bad = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"stream":true,
|
||||
"stream_options":{"continuous_usage_stats":true}})");
|
||||
CHECK_EQ(bad.status, 400);
|
||||
CHECK_EQ(json::parse(bad.body)["error"]["param"].get<std::string>(),
|
||||
std::string("stream_options.continuous_usage_stats"));
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
/* `samplers`: a stage left out is off, temperature after the cuts sets temp_last, and an order the
|
||||
@@ -3481,6 +3674,17 @@ TEST(older_and_llama_server_chat_spellings_reach_the_template) {
|
||||
R"({"messages":[{"role":"user","content":"hi"}],"json_schema":{"type":"object"}})")
|
||||
.status, 200);
|
||||
CHECK_EQ(f.tmpl.last_opt.json_schema, std::string(R"({"type":"object"})"));
|
||||
|
||||
/* A Responses-flat tool and choice, and text parts under their Responses names, are
|
||||
* folded into the Chat spellings rather than refused. */
|
||||
CHECK_EQ(f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}],
|
||||
"tools":[{"type":"function","name":"f","parameters":{"type":"object"}}],
|
||||
"tool_choice":{"type":"function","name":"f"}})").status, 200);
|
||||
CHECK_EQ(f.tmpl.last_n_tools, 1);
|
||||
CHECK_EQ(f.tmpl.last_opt.tool_choice, std::string("required"));
|
||||
CHECK_EQ(f.tmpl.last_opt.tool_name, std::string("f"));
|
||||
CHECK(has(f.tmpl.last_prompt, "hi"));
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
@@ -3566,7 +3770,8 @@ TEST(an_anthropic_request_becomes_the_chat_request_it_means) {
|
||||
"tool_choice":{"type":"any","disable_parallel_tool_use":true},
|
||||
"messages":[
|
||||
{"role":"user","content":"weather?"},
|
||||
{"role":"assistant","content":[{"type":"text","text":"Looking."},
|
||||
{"role":"assistant","content":[{"type":"thinking","thinking":"Check Paris."},
|
||||
{"type":"text","text":"Looking."},
|
||||
{"type":"tool_use","id":"t1","name":"get","input":{"c":"P"}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"sun"},
|
||||
{"type":"text","text":"thanks"}]}]})",
|
||||
@@ -3575,6 +3780,7 @@ TEST(an_anthropic_request_becomes_the_chat_request_it_means) {
|
||||
CHECK_EQ(c["messages"][0].value("role", ""), std::string("system"));
|
||||
CHECK(has(c["messages"][0].value("content", ""), "cch=fffff;"));
|
||||
CHECK(has(c["messages"][0].value("content", ""), "Be terse."));
|
||||
CHECK_EQ(c["messages"][2].value("reasoning_content", ""), std::string("Check Paris."));
|
||||
CHECK_EQ(c["messages"][2]["tool_calls"][0]["function"].value("arguments", ""),
|
||||
std::string(R"({"c":"P"})"));
|
||||
CHECK_EQ(c["messages"][3].value("role", ""), std::string("tool")); /* result first */
|
||||
@@ -3947,7 +4153,7 @@ TEST(a_mid_conversation_system_message_keeps_the_roles_alternating) {
|
||||
ApiError e;
|
||||
if (anthropic_to_chat(body, lim, &chat, &label, &e) < 0) return -1000;
|
||||
ChatPrompt p;
|
||||
const int st = t.apply(json::parse(chat)["messages"], json::array(), ChatOptions(), &p);
|
||||
const int st = t.apply(json::parse(chat)["messages"], Json::array(), ChatOptions(), &p);
|
||||
if (st < 0) fprintf(stderr, " %s\n", p.error.c_str());
|
||||
*prompt = p.prompt;
|
||||
return st;
|
||||
@@ -4339,6 +4545,15 @@ TEST(a_responses_request_becomes_the_chat_request_it_means) {
|
||||
CHECK(!c.contains("input") && !c.contains("text") && !c.contains("instructions"));
|
||||
CHECK_EQ(json::parse(echo).value("instructions", ""), std::string("Be terse."));
|
||||
|
||||
/* A Responses field and its Chat spelling passed through in one body: the endpoint's
|
||||
* own spelling is the one the request was made in, and it wins. */
|
||||
CHECK_OK(responses_to_chat(
|
||||
R"({"input":"x","max_tokens":5,"max_output_tokens":7,
|
||||
"reasoning_effort":"high","reasoning":{"effort":"low"}})",
|
||||
lim, &chat, &echo, &e));
|
||||
CHECK_EQ(json::parse(chat).value("max_tokens", 0), 7);
|
||||
CHECK_EQ(json::parse(chat).value("reasoning_effort", ""), std::string("low"));
|
||||
|
||||
CHECK(responses_to_chat(R"({"input":"x","previous_response_id":"resp_1"})", lim, &chat,
|
||||
&echo, &e) < 0);
|
||||
}
|
||||
@@ -4842,6 +5057,106 @@ int status_with(Fixture& f, const std::string& ep, const std::string& key, const
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* --control-vector-variant: the variant's name runs the vector whatever the default, the model's
|
||||
* own name keeps the default, an explicit false beside the variant's name is refused as the
|
||||
* contradiction it is, and the name is listed as a child of the model the way an adapter is. */
|
||||
TEST(the_control_vector_variant_runs_with_the_vector_and_is_listed) {
|
||||
Fixture f(Fixture::Tweak{ [](ServerOptions& o, Deps& d) {
|
||||
o.control_vector_variant = "uncensored";
|
||||
d.control_vector.available = [] { return true; };
|
||||
d.control_vector.get_default = [] { return false; };
|
||||
} });
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
R"({"model":"uncensored","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4})");
|
||||
if (r.streaming()) drain(r);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* The model's own name runs the default, off here. */
|
||||
HttpResponse r2 = f.post("/v1/chat/completions",
|
||||
R"({"model":"test-model","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4})");
|
||||
if (r2.streaming()) drain(r2);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r2.status, 200);
|
||||
CHECK(!f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* The variant's name with an explicit true is the same request; with false it asks for both. */
|
||||
HttpResponse r3 = f.post("/v1/chat/completions",
|
||||
R"({"model":"uncensored","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4,"control_vector":true})");
|
||||
if (r3.streaming()) drain(r3);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r3.status, 200);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
HttpResponse r4 = f.post("/v1/chat/completions",
|
||||
R"({"model":"uncensored","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4,"control_vector":false})");
|
||||
if (r4.streaming()) drain(r4);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r4.status, 400);
|
||||
CHECK(r4.body.find("control_vector") != std::string::npos);
|
||||
CHECK(r4.body.find("uncensored") != std::string::npos);
|
||||
|
||||
/* Listed as a child of the model, and readable on its own. */
|
||||
const json all = json::parse(f.get("/v1/models").body);
|
||||
bool listed = false;
|
||||
for (const json& m : all["data"])
|
||||
if (m.value("id", std::string()) == "uncensored") {
|
||||
listed = true;
|
||||
CHECK_EQ(m.value("parent", std::string()), std::string("test-model"));
|
||||
}
|
||||
CHECK(listed);
|
||||
const HttpResponse one = f.get("/v1/models/uncensored");
|
||||
CHECK_EQ(one.status, 200);
|
||||
CHECK_EQ(json::parse(one.body).value("id", std::string()), std::string("uncensored"));
|
||||
}
|
||||
|
||||
/* With adapters enabled, every name but the model's own must be a loaded adapter. The variant is a
|
||||
* name of the model, so it reaches the base without an adapter lookup, and no adapter may be
|
||||
* loaded under it: `base:name` would then mean two things. */
|
||||
TEST(the_control_vector_variant_is_not_an_adapter) {
|
||||
int lookups = 0;
|
||||
Fixture f(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
|
||||
o.control_vector_variant = "uncensored";
|
||||
o.lora_acquire = [&](const std::string&, int32_t*, uint64_t*, std::shared_ptr<void>*) {
|
||||
++lookups;
|
||||
return (int)RAD_E_NOTFOUND;
|
||||
};
|
||||
o.lora_names = [] { return std::vector<std::string>{}; };
|
||||
o.lora_load = [](const std::string&, const std::string&, std::string*) {
|
||||
return (int)RAD_OK;
|
||||
};
|
||||
o.lora_unload = [](const std::string&, std::string*, int*) { return (int)RAD_OK; };
|
||||
d.control_vector.available = [] { return true; };
|
||||
d.control_vector.get_default = [] { return false; };
|
||||
} });
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
R"({"model":"uncensored","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4})");
|
||||
if (r.streaming()) drain(r);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK_EQ(lookups, 0);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* Any other name still goes to the adapters, which do not know it. */
|
||||
HttpResponse r2 = f.post("/v1/chat/completions",
|
||||
R"({"model":"other","messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4})");
|
||||
if (r2.streaming()) drain(r2);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r2.status, 404);
|
||||
CHECK_EQ(lookups, 1);
|
||||
|
||||
const HttpResponse l = f.post("/v1/load_lora_adapter",
|
||||
R"({"lora_name":"uncensored","lora_path":"/adapters/u"})");
|
||||
CHECK_EQ(l.status, 400);
|
||||
CHECK(l.body.find("control-vector variant") != std::string::npos);
|
||||
}
|
||||
|
||||
/* The control vector: absent, the deployment's default applies; an explicit `true` on a
|
||||
* deployment with no vector is refused by name (serving the stock model while the client believes
|
||||
* otherwise would be a silent lie), and on one with a vector it reaches the engine's request. */
|
||||
@@ -5023,6 +5338,8 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
{ "grammar_lazy", { false, true } },
|
||||
{ "grammar_triggers", { json::array(), json::parse(R"([{"type":1,"value":"x"}])") } },
|
||||
{ "preserved_tokens", { json::array(), json::parse(R"(["<x>"])") } },
|
||||
{ "include_reasoning", { true, false } },
|
||||
{ "separate_reasoning", { true, false } },
|
||||
};
|
||||
/* Where a guarded key is the endpoint's own field and served. */
|
||||
auto served_on = [](const std::string& key, const std::string& ep) {
|
||||
@@ -5065,10 +5382,14 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
const std::map<std::string, Valid> valid = {
|
||||
{ "model", { "m", none } }, { "stream", { true, none } },
|
||||
{ "stream_options", { json::parse(R"({"include_usage":true})"), json::parse(R"({"stream":true})") } },
|
||||
{ "usage", { json::parse(R"({"include":true})"), json::parse(R"({"stream":true})") } },
|
||||
{ "n", { 2, none } }, { "seed", { 1, none } }, { "stop", { json::parse(R"(["zz"])"), none } },
|
||||
{ "max_tokens", { 4, none } }, { "n_predict", { 4, none } }, { "temperature", { 0.5, none } },
|
||||
{ "max_tokens", { 4, none } }, { "max_output_tokens", { 4, none } },
|
||||
{ "max_new_tokens", { 4, none } }, { "n_predict", { 4, none } },
|
||||
{ "temperature", { 0.5, none } },
|
||||
{ "top_p", { 0.9, none } }, { "top_k", { 5, none } }, { "min_p", { 0.1, none } },
|
||||
{ "typical_p", { 0.9, none } }, { "presence_penalty", { 0.1, none } },
|
||||
{ "typical_p", { 0.9, none } }, { "typ_p", { 0.9, none } },
|
||||
{ "presence_penalty", { 0.1, none } },
|
||||
{ "frequency_penalty", { 0.1, none } }, { "repetition_penalty", { 1.1, none } },
|
||||
{ "repeat_penalty", { 1.1, none } }, { "repeat_last_n", { 32, none } },
|
||||
{ "xtc_probability", { 0.1, none } }, { "xtc_threshold", { 0.2, none } },
|
||||
@@ -5085,6 +5406,8 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
{ "ngram_ban_n", { 35, none } }, { "ngram_window", { 128, none } },
|
||||
{ "ngram_whitelist", { json::parse(R"([4,5])"), none } },
|
||||
{ "no_repeat_ngram_whitelist", { json::parse(R"([4,5])"), none } },
|
||||
{ "no_repeat_ngram_size", { 35, none } },
|
||||
{ "no_repeat_ngram_window_size", { 128, none } },
|
||||
{ "images_config", { "gundam", none } },
|
||||
{ "messages", { json::parse(R"([{"role":"user","content":"yo"}])"), none } },
|
||||
{ "tools", { json::parse(R"([{"type":"function","function":{"name":"f"}}])"), none } },
|
||||
@@ -5094,7 +5417,10 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
{ "parallel_tool_calls", { false, none } }, { "add_generation_prompt", { true, none } },
|
||||
{ "max_completion_tokens", { 4, none } },
|
||||
{ "chat_template_kwargs", { json::parse(R"({"x":"y"})"), none } },
|
||||
{ "reasoning_effort", { "low", none } }, { "enable_thinking", { false, none } },
|
||||
{ "reasoning_effort", { "low", none } },
|
||||
{ "reasoning", { json::parse(R"({"effort":"low"})"), none } },
|
||||
{ "thinking", { json::parse(R"({"type":"adaptive"})"), none } },
|
||||
{ "enable_thinking", { false, none } },
|
||||
{ "preserve_thinking", { true, none } }, { "thinking_token_budget", { -1, none } },
|
||||
{ "thinking_budget", { -1, none } }, { "thinking_budget_tokens", { -1, none } },
|
||||
{ "reasoning_budget_tokens", { -1, none } }, { "reasoning_format", { "none", none } },
|
||||
@@ -5498,6 +5824,12 @@ TEST(an_embedding_inputs_bos_moves_its_media_by_one) {
|
||||
{"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}]})", d, lim, &r, &e));
|
||||
REQUIRE(r.prompts.size() == 1 && r.prompts[0].media);
|
||||
CHECK(r.prompts[0].tokens == std::vector<int32_t>({ 1, 'a', 'b', 9001, 9002 }));
|
||||
/* A text part under its Responses name embeds as the same text. */
|
||||
OaiRequest r2;
|
||||
CHECK_OK(parse_embeddings_request(R"({"input":[{"type":"input_text","text":"ab"}]})", d, lim,
|
||||
&r2, &e));
|
||||
REQUIRE(r2.prompts.size() == 1);
|
||||
CHECK(r2.prompts[0].tokens == std::vector<int32_t>({ 1, 'a', 'b' }));
|
||||
REQUIRE(r.prompts[0].media->items.size() == 1);
|
||||
CHECK_EQ(r.prompts[0].media->items[0].tok, 3);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ using namespace sched_fake;
|
||||
#include "gen/shape_driver.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <random>
|
||||
#include "util/simd.h"
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
@@ -461,4 +463,290 @@ TEST(a_field_without_a_surface_ends_after_its_first_level) {
|
||||
CHECK(m.f.empty());
|
||||
}
|
||||
|
||||
/* ================================================================== bitmap kernels vs per point */
|
||||
/* The per-point forms shape_refine and shape_mesh had before they classified rows with
|
||||
* simd::level_bits_f32, with the case table they were built on, kept as the reference the
|
||||
* bitmap forms must match exactly. */
|
||||
namespace {
|
||||
|
||||
/* A 3 x 3 x 3 dilation of an n^3 mask (zero outside), as separable maxima along each axis. */
|
||||
void ref_dilate(std::vector<uint8_t>& m, int64_t n) {
|
||||
std::vector<uint8_t> t(m.size());
|
||||
/* One axis: each voxel ORs its two neighbours along it, where they exist. Along the
|
||||
* contiguous axis a line of n voxels at a time; along the others whole rows of `stride`
|
||||
* voxels, each with the rows either side of it. */
|
||||
auto pass = [&](const std::vector<uint8_t>& src, std::vector<uint8_t>& dst, int64_t stride) {
|
||||
const uint8_t* s = src.data();
|
||||
uint8_t* d = dst.data();
|
||||
const int64_t total = (int64_t)src.size(), plane = n * stride;
|
||||
for (int64_t base = 0; base < total; base += plane) {
|
||||
if (stride == 1) {
|
||||
simd::or_adjacent_u8(d + base, s + base, (size_t)n);
|
||||
continue;
|
||||
}
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const uint8_t* a = s + base + c * stride;
|
||||
simd::or3_u8(d + base + c * stride, a, c > 0 ? a - stride : nullptr,
|
||||
c + 1 < n ? a + stride : nullptr, (size_t)stride);
|
||||
}
|
||||
}
|
||||
};
|
||||
pass(m, t, 1);
|
||||
pass(t, m, n);
|
||||
pass(m, t, n * n);
|
||||
m.swap(t);
|
||||
}
|
||||
|
||||
|
||||
std::vector<uint32_t> ref_refine(const std::vector<float>& prev, int32_t rp, int32_t r,
|
||||
double level, bool last) {
|
||||
const int64_t np = (int64_t)rp + 1, n = (int64_t)r + 1;
|
||||
std::vector<uint8_t> near((size_t)(np * np * np), 0);
|
||||
auto sgn = [](float v) { return (v > 0.0f) - (v < 0.0f); };
|
||||
const float lv = (float)level;
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k) {
|
||||
const int64_t p = (i * np + j) * np + k;
|
||||
const float raw = prev[(size_t)p];
|
||||
if (std::isnan(raw)) continue;
|
||||
const float v = raw - lv;
|
||||
const int s = sgn(v);
|
||||
bool cross = std::fabs(v) < 0.95f;
|
||||
const int64_t nb[6][3] = { { i - 1, j, k }, { i + 1, j, k }, { i, j - 1, k },
|
||||
{ i, j + 1, k }, { i, j, k - 1 }, { i, j, k + 1 } };
|
||||
for (int q = 0; q < 6 && !cross; ++q) {
|
||||
const int64_t a = nb[q][0], b = nb[q][1], c = nb[q][2];
|
||||
/* Outside the grid the reference replicates the border, and a neighbour not
|
||||
* sampled stands in as the point itself: neither crosses. */
|
||||
if (a < 0 || a >= np || b < 0 || b >= np || c < 0 || c >= np) continue;
|
||||
const float u = prev[(size_t)((a * np + b) * np + c)];
|
||||
if (std::isnan(u)) continue;
|
||||
cross = sgn(u - lv) != s;
|
||||
}
|
||||
near[(size_t)p] = cross;
|
||||
}
|
||||
if (!last) ref_dilate(near, np);
|
||||
std::vector<uint8_t> mark((size_t)(n * n * n), 0);
|
||||
auto up = [&](int64_t c) { return (c * r + rp / 2) / rp; };
|
||||
for (int64_t i = 0; i < np; ++i)
|
||||
for (int64_t j = 0; j < np; ++j)
|
||||
for (int64_t k = 0; k < np; ++k)
|
||||
if (near[(size_t)((i * np + j) * np + k)])
|
||||
mark[(size_t)((up(i) * n + up(j)) * n + up(k))] = 1;
|
||||
ref_dilate(mark, n);
|
||||
if (last) ref_dilate(mark, n);
|
||||
std::vector<uint32_t> pts;
|
||||
for (int64_t p = 0; p < (int64_t)mark.size(); ++p)
|
||||
if (mark[(size_t)p]) pts.push_back((uint32_t)p);
|
||||
return pts;
|
||||
}
|
||||
|
||||
|
||||
/* Corner c of a cube is at (c & 1, c >> 1 & 1, c >> 2 & 1) along the grid's (i, j, k). Edge e is
|
||||
* along axis e / 4 from corner kEdge[e][0] to kEdge[e][1]. */
|
||||
struct McRef {
|
||||
int32_t edge[12][2];
|
||||
/* Each case's triangles as edge triples, -1 ended. */
|
||||
int8_t tri[256][31];
|
||||
};
|
||||
|
||||
McRef build_ref_tables() {
|
||||
McRef T{};
|
||||
int ne = 0;
|
||||
for (int a = 0; a < 3; ++a)
|
||||
for (int c = 0; c < 8; ++c)
|
||||
if (!(c >> a & 1)) { T.edge[ne][0] = c; T.edge[ne][1] = c | (1 << a); ++ne; }
|
||||
auto edge_of = [&](int c0, int c1) {
|
||||
for (int e = 0; e < 12; ++e)
|
||||
if ((T.edge[e][0] == c0 && T.edge[e][1] == c1) ||
|
||||
(T.edge[e][0] == c1 && T.edge[e][1] == c0))
|
||||
return e;
|
||||
return -1;
|
||||
};
|
||||
auto pos = [](int c, double* p) { p[0] = c & 1; p[1] = c >> 1 & 1; p[2] = c >> 2 & 1; };
|
||||
for (int m = 0; m < 256; ++m) {
|
||||
for (int i = 0; i < 31; ++i) T.tri[m][i] = -1;
|
||||
if (m == 0 || m == 255) continue;
|
||||
auto in = [&](int c) { return (m >> c & 1) != 0; };
|
||||
/* Each face's segments between its crossing edges. A face with all four edges crossing
|
||||
* (its inside corners diagonal) separates the inside corners, the rule both cubes that
|
||||
* share the face apply, so the surface has no cracks. */
|
||||
std::vector<std::array<int, 2>> seg;
|
||||
for (int a = 0; a < 3; ++a)
|
||||
for (int s = 0; s < 2; ++s) {
|
||||
const int u = (a + 1) % 3, v = (a + 2) % 3;
|
||||
const int base = s << a;
|
||||
const int cyc[4] = { base, base | (1 << u), base | (1 << u) | (1 << v),
|
||||
base | (1 << v) };
|
||||
int fe[4];
|
||||
bool cr[4];
|
||||
int ncr = 0;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
fe[q] = edge_of(cyc[q], cyc[(q + 1) % 4]);
|
||||
cr[q] = in(cyc[q]) != in(cyc[(q + 1) % 4]);
|
||||
ncr += cr[q];
|
||||
}
|
||||
if (ncr == 2) {
|
||||
int a0 = -1, a1 = -1;
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
if (!cr[q]) continue;
|
||||
if (a0 < 0) a0 = fe[q]; else a1 = fe[q];
|
||||
}
|
||||
seg.push_back({ a0, a1 });
|
||||
} else if (ncr == 4) {
|
||||
for (int q = 0; q < 4; ++q)
|
||||
if (in(cyc[q])) seg.push_back({ fe[(q + 3) % 4], fe[q] });
|
||||
}
|
||||
}
|
||||
/* The segments close into loops; each crossing edge is in exactly two. */
|
||||
std::vector<bool> used(seg.size(), false);
|
||||
int nt = 0;
|
||||
for (size_t s0 = 0; s0 < seg.size(); ++s0) {
|
||||
if (used[s0]) continue;
|
||||
std::vector<int> loop = { seg[s0][0], seg[s0][1] };
|
||||
used[s0] = true;
|
||||
for (bool grew = true; grew;) {
|
||||
grew = false;
|
||||
for (size_t q = 0; q < seg.size(); ++q) {
|
||||
if (used[q]) continue;
|
||||
const int tail = loop.back();
|
||||
int nx = -1;
|
||||
if (seg[q][0] == tail) nx = seg[q][1];
|
||||
else if (seg[q][1] == tail) nx = seg[q][0];
|
||||
if (nx < 0) continue;
|
||||
used[q] = true;
|
||||
grew = true;
|
||||
if (nx != loop.front()) loop.push_back(nx);
|
||||
}
|
||||
}
|
||||
/* Orientation: the loop's normal (Newell's, over the edges' midpoints) points from the
|
||||
* inside corners to the outside ones. */
|
||||
double nrm[3] = { 0, 0, 0 }, out[3] = { 0, 0, 0 };
|
||||
std::vector<std::array<double, 3>> mid;
|
||||
for (int e : loop) {
|
||||
double p0[3], p1[3];
|
||||
pos(T.edge[e][0], p0);
|
||||
pos(T.edge[e][1], p1);
|
||||
mid.push_back({ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2, (p0[2] + p1[2]) / 2 });
|
||||
const double sg = in(T.edge[e][0]) ? 1.0 : -1.0;
|
||||
for (int d = 0; d < 3; ++d) out[d] += sg * (p1[d] - p0[d]);
|
||||
}
|
||||
for (size_t q = 0; q < mid.size(); ++q) {
|
||||
const auto& c = mid[q];
|
||||
const auto& d = mid[(q + 1) % mid.size()];
|
||||
nrm[0] += (c[1] - d[1]) * (c[2] + d[2]);
|
||||
nrm[1] += (c[2] - d[2]) * (c[0] + d[0]);
|
||||
nrm[2] += (c[0] - d[0]) * (c[1] + d[1]);
|
||||
}
|
||||
if (nrm[0] * out[0] + nrm[1] * out[1] + nrm[2] * out[2] < 0)
|
||||
std::reverse(loop.begin(), loop.end());
|
||||
for (size_t q = 1; q + 1 < loop.size() && nt < 10; ++q) {
|
||||
T.tri[m][3 * nt] = (int8_t)loop[0];
|
||||
T.tri[m][3 * nt + 1] = (int8_t)loop[q];
|
||||
T.tri[m][3 * nt + 2] = (int8_t)loop[q + 1];
|
||||
++nt;
|
||||
}
|
||||
}
|
||||
}
|
||||
return T;
|
||||
}
|
||||
|
||||
const McRef& mc_ref() {
|
||||
static const McRef t = build_ref_tables();
|
||||
return t;
|
||||
}
|
||||
|
||||
void ref_mesh(const std::vector<float>& field, int32_t r, double bounds, double level,
|
||||
gen::ShapeMesh* out) {
|
||||
out->v.clear();
|
||||
out->f.clear();
|
||||
const McRef& T = mc_ref();
|
||||
const int64_t n = (int64_t)r + 1, nn = n * n;
|
||||
const float lv = (float)level;
|
||||
const double sc = 2.0 * bounds / (double)n;
|
||||
/* An edge's vertex by its first grid point: the x edges between planes i and i + 1, and the
|
||||
* y and z edges of planes i and i + 1. */
|
||||
std::vector<int32_t> ex((size_t)nn), ey[2], ez[2];
|
||||
for (int p = 0; p < 2; ++p) { ey[p].assign((size_t)nn, -1); ez[p].assign((size_t)nn, -1); }
|
||||
auto value = [&](int64_t i, int64_t j, int64_t k) {
|
||||
return field[(size_t)((i * n + j) * n + k)];
|
||||
};
|
||||
for (int64_t i = 0; i + 1 < n; ++i) {
|
||||
std::fill(ex.begin(), ex.end(), -1);
|
||||
if (i > 0) {
|
||||
std::swap(ey[0], ey[1]);
|
||||
std::swap(ez[0], ez[1]);
|
||||
std::fill(ey[1].begin(), ey[1].end(), -1);
|
||||
std::fill(ez[1].begin(), ez[1].end(), -1);
|
||||
}
|
||||
for (int64_t j = 0; j + 1 < n; ++j)
|
||||
for (int64_t k = 0; k + 1 < n; ++k) {
|
||||
float v[8];
|
||||
bool skip = false;
|
||||
int m = 0;
|
||||
for (int c = 0; c < 8 && !skip; ++c) {
|
||||
v[c] = value(i + (c & 1), j + (c >> 1 & 1), k + (c >> 2 & 1));
|
||||
if (std::isnan(v[c])) skip = true;
|
||||
else if (v[c] > lv) m |= 1 << c;
|
||||
}
|
||||
if (skip || m == 0 || m == 255) continue;
|
||||
for (int t = 0; t < 30 && T.tri[m][t] >= 0; ++t) {
|
||||
const int e = T.tri[m][t];
|
||||
const int c0 = T.edge[e][0], c1 = T.edge[e][1], a = e / 4;
|
||||
const int64_t bi = c0 & 1, bj = c0 >> 1 & 1, bk = c0 >> 2 & 1;
|
||||
int32_t* slot = a == 0 ? &ex[(size_t)((j + bj) * n + k + bk)]
|
||||
: a == 1 ? &ey[bi][(size_t)(j * n + k + bk)]
|
||||
: &ez[bi][(size_t)((j + bj) * n + k)];
|
||||
if (*slot < 0) {
|
||||
const float t0 = v[c0], t1 = v[c1];
|
||||
const float f = t1 != t0 ? (lv - t0) / (t1 - t0) : 0.5f;
|
||||
float g[3] = { (float)(i + bi), (float)(j + bj), (float)(k + bk) };
|
||||
g[a] += f;
|
||||
*slot = (int32_t)(out->v.size() / 3);
|
||||
for (int d = 0; d < 3; ++d) out->v.push_back((float)(g[d] * sc - bounds));
|
||||
}
|
||||
out->f.push_back((uint32_t)*slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* A field with NaNs, values exactly at the level, and a surface crossing everywhere. */
|
||||
std::vector<float> rough_field(int64_t n, std::mt19937& rng) {
|
||||
std::uniform_real_distribution<float> u(-1.0f, 1.0f);
|
||||
std::vector<float> f((size_t)(n * n * n));
|
||||
for (auto& x : f) {
|
||||
const float y = u(rng);
|
||||
x = y > 0.97f ? std::nanf("") : y > 0.9f ? 0.0f : y * 1.5f;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(shape_mesh_and_refine_match_the_per_point_forms_at_every_simd_level) {
|
||||
std::mt19937 rng(20261107);
|
||||
const int top = simd::detect_level();
|
||||
for (int lvl = 0; lvl <= top; ++lvl) {
|
||||
simd::force_level(lvl);
|
||||
for (int32_t r : { 1, 2, 5, 31, 62, 63, 64, 65, 66, 90 }) {
|
||||
const int64_t n = (int64_t)r + 1;
|
||||
const std::vector<float> f = rough_field(n, rng);
|
||||
gen::ShapeMesh got, want;
|
||||
gen::shape_mesh(f, r, 1.0, 0.0, &got);
|
||||
ref_mesh(f, r, 1.0, 0.0, &want);
|
||||
CHECK(got.f == want.f);
|
||||
CHECK(got.v == want.v);
|
||||
for (bool last : { false, true }) {
|
||||
const int32_t rf = r * 2;
|
||||
CHECK(gen::shape_refine(f, r, rf, 0.0, last) == ref_refine(f, r, rf, 0.0, last));
|
||||
CHECK(gen::shape_refine(f, r, rf, 0.3, last) == ref_refine(f, r, rf, 0.3, last));
|
||||
}
|
||||
}
|
||||
}
|
||||
simd::force_level(top);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -91,14 +91,20 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
}
|
||||
const std::set<std::pair<std::string, std::string>> want = {
|
||||
{ "anima", "" }, { "bailinghybrid", "" }, { "breeze", "" }, { "clef", "" },
|
||||
{ "bailinghybrid", "gguf_ftype_7" }, { "bailinghybrid", "gguf_ftype_15" },
|
||||
{ "bailinghybrid", "gguf_ftype_17" }, { "bailinghybrid", "gguf_ftype_18" },
|
||||
{ "bailinghybrid", "gguf_ftype_25" },
|
||||
{ "clef", "fp8_e4m3" }, { "embeddinggemma2", "" },
|
||||
{ "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" },
|
||||
{ "fishomni", "bsgemm-moe" }, { "flint", "" }, { "flux3", "" }, { "flux3distilled", "" },
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
|
||||
{ "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
|
||||
{ "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" },
|
||||
{ "laya", "" }, { "lfm2", "" }, { "lfm3", "" }, { "llama", "" }, { "mistral3", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "museglimmer", "" },
|
||||
{ "museglimmer", "compressed-tensors" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen35moe", "w8a8_fwht128" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },
|
||||
{ "spark25", "" }, { "spark25", "w8a8_fwht128" }, { "sdxl", "" },
|
||||
@@ -278,3 +284,26 @@ TEST(fishomni_tags_a_reference_transcript_as_the_prompt_builder_does) {
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
|
||||
/* libr4d's rows that chain answer 2 to rad_kernel_chain: every chained form of theirs ends its wait
|
||||
* in r4d_chain_acquire, which empties the scalar data cache behind the fence, and that is what
|
||||
* lets an engine issue their packets without the packet processor's acquire
|
||||
* (core/device/aql.cpp, "the acquire of a chained launch"). One row answering 1 keeps the acquire
|
||||
* on every chained packet of an engine that loads it, so a row added with a wait of its own shows
|
||||
* up here rather than as a slower step. */
|
||||
TEST(libr4ds_rows_that_chain_acquire_for_themselves) {
|
||||
Registry r;
|
||||
const int st = r.load_dir(dir_of("kernels"), { "libr4d", "libref" });
|
||||
if (!r.plugin("libr4d")) {
|
||||
(void)st;
|
||||
ARTIFACT_MISSING("libr4d under " + dir_of("kernels"));
|
||||
}
|
||||
int chained = 0;
|
||||
for (const KernelRow& k : r.rows()) {
|
||||
if (!k.chain) continue;
|
||||
++chained;
|
||||
CHECK(k.chain_fenced);
|
||||
if (!k.chain_fenced) fprintf(stderr, " %s chains and answers 1\n", k.info->name);
|
||||
}
|
||||
CHECK(chained > 0);
|
||||
}
|
||||
@@ -380,6 +380,14 @@ TEST(spark_prefill_keys_match_live_r4d_split_grid) {
|
||||
r.used = 2048;
|
||||
CHECK_EQ(rad_prefill_splits_for_live(96, 48, 256, 256, 1, 4, 65536, 2048, 32), 5);
|
||||
CHECK(spark25_prefill_key::pass_key(r) != k4);
|
||||
/* Decode, verify and draft passes issue at the keyed context bound, so they record; a
|
||||
* drafter's rows in a prefill pass read the live maximum and do not. */
|
||||
r.draft_pass = -1;
|
||||
CHECK_EQ(spark25_prefill_key::pass_key(r), (uint64_t)0);
|
||||
r.phase = RAD_PHASE_DECODE;
|
||||
CHECK(spark25_prefill_key::pass_key(r) != 0);
|
||||
r.draft_pass = 0; r.n_spec = 3;
|
||||
CHECK(spark25_prefill_key::pass_key(r) != 0);
|
||||
r = {}; r.phase = RAD_PHASE_PREFILL; r.n_tok = r.max_q_len = 256; r.n_seq = 2;
|
||||
r.max_ctx = 65536; r.head_dim = 256; r.gqa = 4; r.kv_heads = 4;
|
||||
r.kv_group_found = 1; r.used = 1536; r.wgps = 32;
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
#include "text/chatparse.h"
|
||||
#include "../arch/spark25_bf16/chat.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
using namespace rad;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
static const json& tools() {
|
||||
static const json t = json::parse(R"([
|
||||
|
||||
@@ -13,7 +13,7 @@ TEST(bf16_conversion_preserves_qkv_rows_gate_up_and_tied_head) {
|
||||
const std::string ckpt = d / "model";
|
||||
REQUIRE(std::filesystem::create_directory(ckpt));
|
||||
constexpr int H = 32, Q = 32, K = 16, F = 64, V = 320;
|
||||
nlohmann::ordered_json config = {
|
||||
Json config = {
|
||||
{"model_type", "spark2_5"}, {"architectures", {"Spark2_5ForCausalLM"}},
|
||||
{"hidden_size", H}, {"num_hidden_layers", 2}, {"num_attention_heads", 4},
|
||||
{"num_key_value_heads", 2}, {"head_dim", 8}, {"intermediate_size", F},
|
||||
|
||||
@@ -74,7 +74,9 @@ PROMPTS = ("a", "hello", "longer prompt", "the quick brown fox jumps over the la
|
||||
def serve(build, rad, port, env, log, tp=1):
|
||||
"""Start Radiance on the host kernels over `rad` and wait for /health. The caller stops it."""
|
||||
proc = subprocess.Popen(
|
||||
[str(build / "bin/radiance"), "--model", str(rad), "--host", "127.0.0.1", "--port",
|
||||
# The server reads a YAML file; scripts/radiance-flags writes these flags as one.
|
||||
[str(Path(__file__).resolve().parent.parent / "scripts/radiance-flags"),
|
||||
str(build / "bin/radiance"), "--model", str(rad), "--host", "127.0.0.1", "--port",
|
||||
str(port), "--kernels", "libref", "--debug-accept-reference-kernels", "--max-model-len",
|
||||
"64", "--max-num-batched-tokens", "32", "--max-num-seqs", "1", "--tp", str(tp)],
|
||||
env=env, stdout=log, stderr=subprocess.STDOUT)
|
||||
|
||||
@@ -276,9 +276,9 @@ TEST(the_coupling_uniform_is_the_specified_53_bit_draw) {
|
||||
* shift every later operand of a plane the host writes and the device reads. */
|
||||
TEST(the_coupling_wire_rows_keep_their_layout) {
|
||||
CHECK_EQ(sizeof(RadMtpCoupleDraw), (size_t)32);
|
||||
CHECK_EQ(sizeof(RadMtpCoupleState), (size_t)152);
|
||||
CHECK_EQ(sizeof(RadMtpCoupleState), (size_t)168);
|
||||
CHECK_EQ(RAD_MTP_COUPLE_DRAW_WORDS, (size_t)8);
|
||||
CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)38);
|
||||
CHECK_EQ(RAD_MTP_COUPLE_STATE_WORDS, (size_t)42);
|
||||
CHECK_EQ(offsetof(RadMtpCoupleState, q) % 8, (size_t)0);
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 850 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user