Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
+57
-22
@@ -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
|
||||
@@ -127,6 +135,7 @@ set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99")
|
||||
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)
|
||||
|
||||
# Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a
|
||||
@@ -170,6 +179,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
|
||||
@@ -181,7 +191,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)
|
||||
@@ -209,7 +221,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)
|
||||
@@ -219,14 +232,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
|
||||
@@ -312,6 +330,14 @@ if(RAD_HIP_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.
|
||||
@@ -536,21 +562,18 @@ 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)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc kda mla moefuse kvres
|
||||
dsa lili)
|
||||
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)
|
||||
@@ -582,11 +605,10 @@ 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)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -623,7 +645,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)
|
||||
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,
|
||||
@@ -634,7 +656,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
|
||||
@@ -768,9 +790,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()
|
||||
@@ -813,6 +838,16 @@ 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()
|
||||
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})
|
||||
|
||||
+21
-21
@@ -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 39 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 },
|
||||
@@ -109,7 +109,7 @@
|
||||
{ "RadBufDecl", "domain", 60, 4 },
|
||||
{ "RadBufDecl", "derive", 64, 8 },
|
||||
{ "RadBufDecl", "kv", 72, 4 },
|
||||
{ "RadBuildCtx", "", 0, 208 },
|
||||
{ "RadBuildCtx", "", 0, 200 },
|
||||
{ "RadBuildCtx", "rank", 0, 4 },
|
||||
{ "RadBuildCtx", "world_size", 4, 4 },
|
||||
{ "RadBuildCtx", "max_tok", 8, 8 },
|
||||
@@ -126,23 +126,22 @@
|
||||
{ "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 },
|
||||
{ "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 },
|
||||
{ "RadAudioGenBatch", "", 0, 344 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
@@ -311,7 +310,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 +319,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 },
|
||||
|
||||
@@ -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.
|
||||
@@ -58,8 +58,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 39 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 39, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
+1015
-989
File diff suppressed because it is too large.
Load diff
+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) {
|
||||
|
||||
+285
-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,91 @@ 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(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 +350,21 @@ 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);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ golden renders
|
||||
@@ -1004,6 +1104,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 +1311,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 +1401,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);
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
#include <arch/rad_deepseek41_chat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::chatdiff;
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = Json;
|
||||
|
||||
/* ================================================================== fixtures */
|
||||
|
||||
@@ -1326,7 +1326,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 +1420,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;
|
||||
}
|
||||
|
||||
@@ -1522,7 +1523,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();
|
||||
@@ -2579,8 +2581,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());
|
||||
|
||||
@@ -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>
|
||||
|
||||
+19
-33
@@ -312,7 +312,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);
|
||||
@@ -524,8 +524,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--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" } },
|
||||
@@ -786,25 +786,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 +816,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);
|
||||
@@ -1550,8 +1536,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);
|
||||
}
|
||||
@@ -1564,7 +1550,7 @@ TEST(usage_names_every_flag_it_documents) {
|
||||
"--num-speculative-tokens", "--draft-window", "--draft-coupling",
|
||||
"--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",
|
||||
|
||||
+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 */
|
||||
|
||||
@@ -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;
|
||||
@@ -134,6 +137,33 @@ TEST(chained_launches_follow_the_plugins_ask_on_the_aql_backend_only) {
|
||||
CHECK_EQ(rad_dev_chain_enabled(), 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) {
|
||||
/* A real card reports its own VRAM. */
|
||||
if (!need_host_backend()) return;
|
||||
@@ -197,6 +227,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
|
||||
@@ -1611,4 +1668,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()
|
||||
+5
-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;
|
||||
|
||||
@@ -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
|
||||
+111
-100
@@ -20,13 +20,14 @@
|
||||
* 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 "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 +37,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 +76,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 +84,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
|
||||
@@ -191,12 +194,11 @@ 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;
|
||||
/* 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. */
|
||||
@@ -232,11 +234,9 @@ struct World {
|
||||
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";
|
||||
@@ -273,14 +273,11 @@ struct World {
|
||||
!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 +299,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 +468,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 (;;) {
|
||||
@@ -772,22 +781,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 +979,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. */
|
||||
@@ -1617,7 +1558,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(
|
||||
@@ -1995,6 +1935,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 +2022,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", "" },
|
||||
@@ -2212,27 +2218,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 +2318,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 +2328,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 +2339,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,390 @@
|
||||
/* 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);
|
||||
}
|
||||
|
||||
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(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);
|
||||
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);
|
||||
}
|
||||
|
||||
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()
|
||||
@@ -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,137 @@
|
||||
/* 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));
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
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()
|
||||
+3
-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 {
|
||||
|
||||
@@ -1875,7 +1875,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"));
|
||||
|
||||
@@ -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 }) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,417 @@
|
||||
/* 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());
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
|
||||
+38
-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));
|
||||
}
|
||||
@@ -1425,7 +1425,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 +1569,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 +1597,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 +2138,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 };
|
||||
@@ -6123,6 +6095,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>
|
||||
|
||||
@@ -1163,6 +1163,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 +1316,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. */
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -2609,6 +2609,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);
|
||||
|
||||
+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;
|
||||
|
||||
@@ -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]));
|
||||
|
||||
+74
-32
@@ -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;
|
||||
#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(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);
|
||||
@@ -210,14 +239,14 @@ int main(int argc, char** argv) {
|
||||
{300, 70}, -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 +255,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,38 +267,51 @@ 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 */
|
||||
{"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},
|
||||
@@ -280,7 +322,7 @@ 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},
|
||||
@@ -295,7 +337,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 +353,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);
|
||||
|
||||
@@ -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"])
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>());
|
||||
|
||||
+77
-344
@@ -1238,7 +1238,7 @@ TEST(op_vocabulary) {
|
||||
"embed_lookup_q", "cast",
|
||||
"scale_rows",
|
||||
"softmax",
|
||||
"quant_act_i8", "quant_act_i8g", "quant_act_fp8", "quant_cols_fp8", "had_quant_act_fp8", "givens_dense_quant", "givens_rotate", "had_quant_act_i8",
|
||||
"quant_act_i8", "quant_act_i8g", "quant_act_fp8", "quant_cols_fp8", "had_quant_act_i8",
|
||||
"had_quant_act_i8g",
|
||||
"gram_accum",
|
||||
/* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run
|
||||
@@ -1258,7 +1258,7 @@ TEST(op_vocabulary) {
|
||||
"attn_paged_sink",
|
||||
"qk_norm_rope", "qsa_block_key",
|
||||
/* libr4d's row-form names, served by the base op's row. */
|
||||
"rmsnorm_rows", "rope_rows", "gemm_nt_q_short", "gemm_nt_q_gated_wide",
|
||||
"rmsnorm_rows", "rope_rows",
|
||||
/* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that
|
||||
* issues them has no other host path. */
|
||||
"qsa_score", "qsa_select", "qsa_tail_store", "qsa_work", "kv_resolve", "dflash_conv",
|
||||
@@ -1278,7 +1278,6 @@ TEST(op_vocabulary) {
|
||||
"ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store",
|
||||
"randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "im2col_nhwc", "l2norm_chan",
|
||||
"d2s_add", "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self",
|
||||
"ln_mod_quant_fp8",
|
||||
/* SDXL's (arch/sdxl): CLIP-L's activation and the k-diffusion sampler over a
|
||||
* discrete-time denoiser. */
|
||||
"gelu_quick", "kd_input", "kd_step",
|
||||
@@ -1294,7 +1293,7 @@ TEST(op_vocabulary) {
|
||||
/* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its
|
||||
* decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free
|
||||
* activation. */
|
||||
"rms_mod", "rms_mod_quant_fp8", "flow_x0_step", "flow_res_multistep", "patch_unfold",
|
||||
"rms_mod", "flow_x0_step", "flow_res_multistep", "patch_unfold",
|
||||
"vtile_gather",
|
||||
"vtile_stitch", "grid_pos3", "snake_aa",
|
||||
/* Its step-distilled form's video sparse attention: the tile selection and the
|
||||
@@ -3100,133 +3099,6 @@ TEST(op_gemm_nt_q_parts_read_their_own_activation_copy) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ParoQuant's activation quantiser, the rotation as dense per-group matrices. T[j][i] of a (part,
|
||||
* group) is the group's composed network applied to unit vector e_i, built here in double from the
|
||||
* same pairs and angles the device layout hook reads. The dequantised row is then the rotated row
|
||||
* to within the quantiser's grid (plus the f16 rounding of T), and the rotation preserves the
|
||||
* row's norm; both are checked per part against a double-precision rotation. With T the identity
|
||||
* and unit channel scales it is exactly quant_act_fp8. Run for both quantisers `out` names. */
|
||||
TEST(op_givens_dense_quant) {
|
||||
const int64_t M = 3, n = 256, S = 3, P = 2, G = 128;
|
||||
uint32_t rng = 99;
|
||||
auto nxt = [&]() { rng = rng * 1664525u + 1013904223u; return rng >> 8; };
|
||||
auto frand = [&](float lo, float hi) { return lo + (hi - lo) * (float)(nxt() % 10000) / 10000.0f; };
|
||||
T x(RAD_BF16, {M, n});
|
||||
std::vector<float> xv((size_t)(M * n));
|
||||
for (auto& v : xv) v = frand(-3.0f, 3.0f);
|
||||
for (int64_t m = 0; m < M; ++m) xv[(size_t)(m * n + 7)] = 0; // a zero in the mix
|
||||
x.f(xv);
|
||||
// a pairing of each group of 128 per stage per part
|
||||
std::vector<int32_t> pairs((size_t)(P * S * n));
|
||||
for (int64_t ps = 0; ps < P * S; ++ps)
|
||||
for (int64_t g = 0; g < n / G; ++g) {
|
||||
std::vector<int32_t> perm((size_t)G);
|
||||
for (int i = 0; i < G; ++i) perm[(size_t)i] = (int32_t)(g * G + i);
|
||||
for (int i = (int)G - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[nxt() % (i + 1)]);
|
||||
for (int i = 0; i < G; ++i) pairs[(size_t)(ps * n + g * G + i)] = perm[(size_t)i];
|
||||
}
|
||||
std::vector<float> av((size_t)(P * S * n / 2)), sv((size_t)(P * n));
|
||||
for (auto& v : av) v = frand(-3.0f, 3.0f);
|
||||
for (auto& v : sv) v = frand(0.5f, 2.0f);
|
||||
T rs(RAD_F32, {P, n});
|
||||
rs.f(sv);
|
||||
|
||||
// the composed matrices, [P * n/G groups][G (j)][G (i)], as f16
|
||||
auto compose = [&](const std::vector<float>& angles, std::vector<float>* tm) {
|
||||
tm->assign((size_t)(P * (n / G) * G * G), 0.0f);
|
||||
for (int64_t p = 0; p < P; ++p)
|
||||
for (int64_t g = 0; g < n / G; ++g)
|
||||
for (int64_t i = 0; i < G; ++i) {
|
||||
std::vector<double> v((size_t)G, 0.0);
|
||||
v[(size_t)i] = 1.0;
|
||||
for (int64_t st = 0; st < S; ++st)
|
||||
for (int64_t j = 0; j < G / 2; ++j) {
|
||||
const int64_t ia = pairs[(size_t)((p * S + st) * n + g * G + 2 * j)] - g * G;
|
||||
const int64_t ib = pairs[(size_t)((p * S + st) * n + g * G + 2 * j + 1)] - g * G;
|
||||
const double t = angles[(size_t)((p * S + st) * (n / 2) + g * (G / 2) + j)];
|
||||
const double c = std::cos(t), sn = std::sin(t);
|
||||
const double va = v[(size_t)ia], vb = v[(size_t)ib];
|
||||
v[(size_t)ia] = va * c + vb * sn;
|
||||
v[(size_t)ib] = vb * c - va * sn;
|
||||
}
|
||||
for (int64_t j = 0; j < G; ++j)
|
||||
(*tm)[(size_t)(((p * (n / G) + g) * G + j) * G + i)] = (float)v[(size_t)j];
|
||||
}
|
||||
};
|
||||
std::vector<float> tmv;
|
||||
compose(av, &tmv);
|
||||
T tm(RAD_F16, {P * n, G});
|
||||
tm.f(tmv);
|
||||
|
||||
for (int i8 = 0; i8 < 2; ++i8) {
|
||||
const double qmax = i8 ? 127.0 : 448.0;
|
||||
const uint32_t qdt = i8 ? RAD_I8 : RAD_F8E4M3;
|
||||
T q(qdt, {M, P * n}), s(RAD_F32, {M, P * n / G});
|
||||
A a; a.t(x).t(tm).t(rs).t(q).t(s)
|
||||
.i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", i8 ? "i8" : "fp8");
|
||||
CHECK_OK(run("givens_dense_quant", a));
|
||||
double worst = 0;
|
||||
int bad_norm = 0;
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t p = 0; p < P; ++p) {
|
||||
std::vector<double> b((size_t)n);
|
||||
double n0 = 0;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
b[(size_t)k] = (double)x.at(m * n + k) / (double)sv[(size_t)(p * n + k)];
|
||||
n0 += b[(size_t)k] * b[(size_t)k];
|
||||
}
|
||||
for (int64_t st = 0; st < S; ++st)
|
||||
for (int64_t j = 0; j < n / 2; ++j) {
|
||||
const int64_t ia = pairs[(size_t)((p * S + st) * n + 2 * j)];
|
||||
const int64_t ib = pairs[(size_t)((p * S + st) * n + 2 * j + 1)];
|
||||
const double t = av[(size_t)((p * S + st) * (n / 2) + j)], c = std::cos(t), sn = std::sin(t);
|
||||
const double va = b[(size_t)ia], vb = b[(size_t)ib];
|
||||
b[(size_t)ia] = va * c + vb * sn;
|
||||
b[(size_t)ib] = vb * c - va * sn;
|
||||
}
|
||||
double n1 = 0;
|
||||
for (int64_t k = 0; k < n; ++k) n1 += b[(size_t)k] * b[(size_t)k];
|
||||
if (std::fabs(n1 - n0) > 1e-9 * n0) ++bad_norm;
|
||||
for (int64_t g = 0; g < n / G; ++g) {
|
||||
double amax = 0;
|
||||
for (int64_t i = 0; i < G; ++i) amax = std::max(amax, std::fabs(b[(size_t)(g * G + i)]));
|
||||
const double sc = s.at(m * (P * n / G) + p * (n / G) + g);
|
||||
CHECK(std::fabs(sc - amax / qmax) < 2e-3 * amax / qmax + 1e-12); // T is f16
|
||||
for (int64_t i = 0; i < G; ++i) {
|
||||
const double deq = (double)q.at(m * P * n + p * n + g * G + i) * sc;
|
||||
worst = std::max(worst, std::fabs(deq - b[(size_t)(g * G + i)]) / amax);
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_EQ(bad_norm, 0);
|
||||
CHECK(worst < (i8 ? 0.006 : 0.04)); // half a step of the grid (int8: 1/254 of the maximum), and T's f16
|
||||
}
|
||||
|
||||
// T the identity, unit scales: exactly quant_act_fp8
|
||||
std::vector<float> eye((size_t)(P * (n / G) * G * G), 0.0f), ones((size_t)(P * n), 1.0f);
|
||||
for (int64_t pg = 0; pg < P * (n / G); ++pg)
|
||||
for (int64_t i = 0; i < G; ++i) eye[(size_t)((pg * G + i) * G + i)] = 1.0f;
|
||||
T tid(RAD_F16, {P * n, G}), rs1(RAD_F32, {P, n});
|
||||
tid.f(eye);
|
||||
rs1.f(ones);
|
||||
T q1(RAD_F8E4M3, {M, P * n}), s1(RAD_F32, {M, P * n / G});
|
||||
A b; b.t(x).t(tid).t(rs1).t(q1).t(s1)
|
||||
.i("M", M).i("n", n).i("group", G).s("dtype", "bf16").i("parts", P).s("out", "fp8");
|
||||
CHECK_OK(run("givens_dense_quant", b));
|
||||
T q2(RAD_F8E4M3, {M, n}), s2(RAD_F32, {M, n / G});
|
||||
A c; c.t(x).t(q2).t(s2).i("M", M).i("n", n).i("group", G).s("dtype", "bf16");
|
||||
CHECK_OK(run("quant_act_fp8", c));
|
||||
int diff = 0;
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t p = 0; p < P; ++p) {
|
||||
for (int64_t k = 0; k < n; ++k)
|
||||
if (q1.mem[(size_t)(m * P * n + p * n + k)] != q2.mem[(size_t)(m * n + k)]) ++diff;
|
||||
for (int64_t g = 0; g < n / G; ++g)
|
||||
if (s1.at(m * (P * n / G) + p * (n / G) + g) != s2.at(m * (n / G) + g)) ++diff;
|
||||
}
|
||||
CHECK_EQ(diff, 0);
|
||||
}
|
||||
|
||||
/* A block grid whose last block is partial, on both axes. K = 300 at 128 is scales over 128, 128
|
||||
* and 44 columns; N = 129 is two row blocks (the second of one row), N = 300 three. With every
|
||||
* code 1, output n is the sum over column groups of width times scale[n / 128][g]. The block is
|
||||
@@ -4052,6 +3924,34 @@ TEST(op_kv_store) {
|
||||
CHECK_EQ(kv.at(0), 0.0f); CHECK_EQ(kv.at(3), 0.0f);
|
||||
}
|
||||
|
||||
/* The int8 cache: each head's K and V as codes against its own f16 scale, the head's absmax / 127,
|
||||
* after the codes; and attention reads a key back as code times scale. */
|
||||
TEST(op_kv_store_int8_and_the_attention_that_reads_it) {
|
||||
T k(RAD_BF16, {1, 1, 2}); k.f({ 254, -64 });
|
||||
T v(RAD_BF16, {1, 1, 2}); v.f({ 31.75f, 8 });
|
||||
T sm(RAD_I32, {1}); sm.n({ 1 });
|
||||
T kv(RAD_I8, {1, 1, 2, 8});
|
||||
A a; a.t(k).t(v).t(sm).t(kv)
|
||||
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2).s("kv_dtype", "i8");
|
||||
CHECK_OK(run("kv_store", a));
|
||||
/* Position 1: K scale 2.0 (f16 0x4000), V scale 0.25 (0x3400). */
|
||||
const int want[8] = { 127, -32, 127, 32, 0x00, 0x40, 0x00, 0x34 };
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ((int)kv.at(8 + i), want[i]);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(kv.at(i), 0.0f);
|
||||
|
||||
/* One query over that one key: the output is the key's V, 127 * 0.25 and 32 * 0.25. */
|
||||
T q(RAD_BF16, {1, 1, 2}); q.f({ 1, 1 });
|
||||
T bt(RAD_I32, {1, 1}); bt.n({ 0 });
|
||||
T su(RAD_I32, {1}); su.n({ 2 });
|
||||
T out(RAD_BF16, {1, 1, 2});
|
||||
/* a window of one: the query at position 1 sees the key at position 1 alone */
|
||||
A b; b.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(out)
|
||||
.i("q_len", 1).i("head_dim", 2).i("gqa", 1).i("block_size", 2).i("causal", 1)
|
||||
.i("window", 1).s("q_dtype", "bf16").s("kv_dtype", "i8").d("scale", 1.0);
|
||||
CHECK_OK(run("attn_paged", b));
|
||||
CHECK_NEAR(out.at(0), 31.75f, 1e-3); CHECK_NEAR(out.at(1), 8.0f, 1e-3);
|
||||
}
|
||||
|
||||
/* The engine hands k and v a column slice, not a dense plane. Without de-interleaving, the KV
|
||||
* halves are declared over the fused qkv buffer, [tokens, kv_heads * head_dim] with the whole
|
||||
* projection's row stride. Deriving the stride from the shape puts every token after the first
|
||||
@@ -4083,14 +3983,6 @@ TEST(op_kv_store_reads_the_row_stride_and_not_the_shape) {
|
||||
CHECK_EQ(kv.at(12), 0.0f); CHECK_EQ(kv.at(15), 0.0f);
|
||||
}
|
||||
|
||||
/* The E4M3 byte a value stores as. The mirror is a byte plane, so `T::at` on it reads the byte and
|
||||
* not the value; comparing a mirror byte to a ring element needs the byte both sides are. */
|
||||
static int e4m3_byte(float x) {
|
||||
T t(RAD_F8E4M3, {1});
|
||||
t.f({ x });
|
||||
return (int)(uint8_t)t.mem[0];
|
||||
}
|
||||
|
||||
/* kv_store_streamed: the group's host mirror is written for every token with a slot, and the ring
|
||||
* slot only when the residency map says the block is resident. The two planes are the same paged
|
||||
* layout, so a token's bytes land at the same offset in either.
|
||||
@@ -4100,38 +3992,37 @@ static int e4m3_byte(float x) {
|
||||
* fall behind, and the resolve does not re-copy a resident block); block 0's must reach the mirror
|
||||
* only, leaving the ring untouched until a resolve copies the whole block in. */
|
||||
TEST(op_kv_store_streamed_writes_the_mirror_always_and_the_ring_when_resident) {
|
||||
/* head_dim 2, one kv head, block_size 2: a block row is [kv_heads, block_size, 2 * head_dim]
|
||||
* = 8 bytes, K then V inside a position. */
|
||||
T k(RAD_BF16, {2, 1, 2}); k.f({ 1, 2, 5, 6 });
|
||||
T v(RAD_BF16, {2, 1, 2}); v.f({ 3, 4, 7, 8 });
|
||||
/* The int8 cache at head_dim 2, one kv head, block_size 2: a position is [K codes 2][V codes 2]
|
||||
* [K scale f16][V scale f16] = 8 bytes, a block row 16. Each head's larger element is 127 times
|
||||
* a power of two, so its scale is that power exactly and its codes the elements over it. */
|
||||
T k(RAD_BF16, {2, 1, 2}); k.f({ 127, 64, 254, -2 });
|
||||
T v(RAD_BF16, {2, 1, 2}); v.f({ -127, 2, 4, 508 });
|
||||
T sm(RAD_I32, {2}); sm.n({ 0, 3 }); /* block 0 offset 0, block 1 offset 1 */
|
||||
T res(RAD_I32, {2}); res.n({ -1, 0 }); /* block 0 absent, block 1 in ring slot 0 */
|
||||
T host(RAD_U8, {2, 8});
|
||||
T kv(RAD_F8E4M3, {1, 1, 2, 4}); /* one ring slot, one block deep */
|
||||
T host(RAD_U8, {2, 16});
|
||||
T kv(RAD_I8, {1, 1, 2, 8}); /* one ring slot, one block deep */
|
||||
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
|
||||
.i("M", 2).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
|
||||
.s("kv_dtype", "fp8_e4m3");
|
||||
.s("kv_dtype", "i8");
|
||||
CHECK_OK(run("kv_store_streamed", a));
|
||||
/* Token 0, block 0, position 0: K then V, mirror only. */
|
||||
CHECK_EQ((int)host.at(0), e4m3_byte(1.0f)); CHECK_EQ((int)host.at(1), e4m3_byte(2.0f));
|
||||
CHECK_EQ((int)host.at(2), e4m3_byte(3.0f)); CHECK_EQ((int)host.at(3), e4m3_byte(4.0f));
|
||||
/* Token 1, block 1, position 1: both planes, at the same in-block offset, so the same bytes. */
|
||||
CHECK_EQ((int)host.at(12), e4m3_byte(5.0f)); CHECK_EQ((int)host.at(13), e4m3_byte(6.0f));
|
||||
CHECK_EQ((int)host.at(14), e4m3_byte(7.0f)); CHECK_EQ((int)host.at(15), e4m3_byte(8.0f));
|
||||
CHECK_EQ((int)host.at(12), e4m3_byte(kv.at(4)));
|
||||
CHECK_EQ((int)host.at(13), e4m3_byte(kv.at(5)));
|
||||
CHECK_EQ((int)host.at(14), e4m3_byte(kv.at(6)));
|
||||
CHECK_EQ((int)host.at(15), e4m3_byte(kv.at(7)));
|
||||
/* Token 0, block 0, position 0, mirror only: scales 1.0 and 1.0 (f16 0x3C00). */
|
||||
const int t0[8] = { 127, 64, 129 /* -127 */, 2, 0x00, 0x3C, 0x00, 0x3C };
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ((int)host.at(i), t0[i]);
|
||||
/* Token 1, block 1, position 1: scales 2.0 (0x4000) and 4.0 (0x4400); both planes, at the same
|
||||
* in-block offset, so the same bytes. */
|
||||
const int t1[8] = { 127, 255 /* -1 */, 1, 127, 0x00, 0x40, 0x00, 0x44 };
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
CHECK_EQ((int)host.at(24 + i), t1[i]);
|
||||
CHECK_EQ((int)(uint8_t)(int8_t)kv.at(8 + i), t1[i]);
|
||||
}
|
||||
/* Nothing else: block 0 has no slot, so its ring stays as it was, and block 1's position 0 is
|
||||
* another token's. */
|
||||
for (int i = 0; i < 4; ++i) CHECK_EQ(kv.at(i), 0.0f);
|
||||
for (int i = 4; i < 12; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(kv.at(i), 0.0f);
|
||||
for (int i = 8; i < 24; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
}
|
||||
|
||||
/* The bf16 streamed store: both planes hold the values themselves, two bytes an element, exactly
|
||||
* as kv_store_bf16 writes them. The descales are fp8-only, so a bf16 call with a non-1 k_scale
|
||||
* still stores the value (this is the difference from the E4M3 row, and the reason the fused bf16
|
||||
* fold passes the prologue's bf16 bytes straight through). */
|
||||
* as kv_store_bf16 writes them. */
|
||||
TEST(op_kv_store_streamed_bf16_writes_the_values_into_both_planes) {
|
||||
T k(RAD_BF16, {2, 1, 2}); k.f({ 1, 2, 5, 6 });
|
||||
T v(RAD_BF16, {2, 1, 2}); v.f({ 3, 4, 7, 8 });
|
||||
@@ -4163,20 +4054,19 @@ TEST(op_kv_store_streamed_bf16_writes_the_values_into_both_planes) {
|
||||
/* A block absent from the ring is written to the mirror alone, whatever the map holds: this is the
|
||||
* state every token of a block's first step is in, and the resolve copies the whole block in. */
|
||||
TEST(op_kv_store_streamed_a_block_with_no_slot_reaches_only_the_mirror) {
|
||||
T k(RAD_BF16, {1, 1, 2}); k.f({ 2, 4 });
|
||||
T v(RAD_BF16, {1, 1, 2}); v.f({ 6, 8 });
|
||||
T k(RAD_BF16, {1, 1, 2}); k.f({ 127, 1 });
|
||||
T v(RAD_BF16, {1, 1, 2}); v.f({ 2, -254 });
|
||||
T sm(RAD_I32, {1}); sm.n({ 3 }); /* block 1, position 1 */
|
||||
T res(RAD_I32, {2}); res.n({ -1, -1 });
|
||||
T host(RAD_U8, {2, 8});
|
||||
T kv(RAD_F8E4M3, {1, 1, 2, 4});
|
||||
T host(RAD_U8, {2, 16});
|
||||
T kv(RAD_I8, {1, 1, 2, 8});
|
||||
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
|
||||
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
|
||||
.s("kv_dtype", "fp8_e4m3").
|
||||
d("k_scale", 0.5).d("v_scale", 2.0); /* the store divides by the reader's descal */
|
||||
.s("kv_dtype", "i8");
|
||||
CHECK_OK(run("kv_store_streamed", a));
|
||||
CHECK_EQ((int)host.at(12), e4m3_byte(4.0f)); CHECK_EQ((int)host.at(13), e4m3_byte(8.0f));
|
||||
CHECK_EQ((int)host.at(14), e4m3_byte(3.0f)); CHECK_EQ((int)host.at(15), e4m3_byte(4.0f));
|
||||
for (int i = 0; i < 4; ++i) CHECK_EQ(kv.at(i), 0.0f); /* the ring is untouched */
|
||||
const int want[8] = { 127, 1, 1, 129 /* -127 */, 0x00, 0x3C, 0x00, 0x40 };
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ((int)host.at(24 + i), want[i]);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(kv.at(i), 0.0f); /* the ring is untouched */
|
||||
}
|
||||
|
||||
/* The refusals libref makes before its first write: a slot naming a block past the mirror, a
|
||||
@@ -4190,37 +4080,37 @@ TEST(op_kv_store_streamed_refuses_a_state_fault_before_writing) {
|
||||
{
|
||||
T sm(RAD_I32, {1}); sm.n({ 0 });
|
||||
T res(RAD_I32, {2}); res.n({ 1, -1 }); /* slot 1 of a one-slot ring */
|
||||
T host(RAD_U8, {2, 8});
|
||||
T kv(RAD_F8E4M3, {1, 1, 2, 4});
|
||||
T host(RAD_U8, {2, 16});
|
||||
T kv(RAD_I8, {1, 1, 2, 8});
|
||||
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
|
||||
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
|
||||
.s("kv_dtype", "fp8_e4m3");
|
||||
.s("kv_dtype", "i8");
|
||||
CHECK_EQ(run("kv_store_streamed", a), RAD_E_INVAL);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
}
|
||||
/* A slot naming a block past the mirror's extent. */
|
||||
{
|
||||
T sm(RAD_I32, {1}); sm.n({ 4 }); /* block 2 of a two-block mirror */
|
||||
T res(RAD_I32, {2}); res.n({ -1, -1 });
|
||||
T host(RAD_U8, {2, 8});
|
||||
T kv(RAD_F8E4M3, {1, 1, 2, 4});
|
||||
T host(RAD_U8, {2, 16});
|
||||
T kv(RAD_I8, {1, 1, 2, 8});
|
||||
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
|
||||
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
|
||||
.s("kv_dtype", "fp8_e4m3");
|
||||
.s("kv_dtype", "i8");
|
||||
CHECK_EQ(run("kv_store_streamed", a), RAD_E_SHAPE);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
for (int i = 0; i < 16; ++i) CHECK_EQ(host.at(i), 0.0f);
|
||||
}
|
||||
/* A mirror row that is not the block's byte pitch: a copy into it would spill over the next
|
||||
* block. */
|
||||
{
|
||||
T sm(RAD_I32, {1}); sm.n({ 0 });
|
||||
T res(RAD_I32, {2}); res.n({ -1, -1 });
|
||||
T host(RAD_U8, {2, 8});
|
||||
host.t.stride[0] = 12; /* a padded row */
|
||||
T kv(RAD_F8E4M3, {1, 1, 2, 4});
|
||||
T host(RAD_U8, {2, 16});
|
||||
host.t.stride[0] = 20; /* a padded row */
|
||||
T kv(RAD_I8, {1, 1, 2, 8});
|
||||
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
|
||||
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
|
||||
.s("kv_dtype", "fp8_e4m3");
|
||||
.s("kv_dtype", "i8");
|
||||
CHECK_EQ(run("kv_store_streamed", a), RAD_E_STRIDE);
|
||||
}
|
||||
}
|
||||
@@ -6462,9 +6352,9 @@ TEST(hc_project_removes_the_direction_per_stream_and_skips_off_rows) {
|
||||
CHECK_EQ(h.at(7), 5.0f);
|
||||
}
|
||||
|
||||
/* With `group`, hc_read also emits x as block-scaled fp8 taken over the stored (narrowed) x, and
|
||||
* with `rotate` the Hadamard-rotated twin: byte for byte what quant_act_fp8 and had_quant_act_fp8
|
||||
* produce from the stored x. */
|
||||
/* With `group`, hc_read also emits x as block-scaled fp8 taken over the stored (narrowed) x: byte
|
||||
* for byte what quant_act_fp8 produces from the stored x. `rotate` adds the Hadamard-rotated twin
|
||||
* beside it and leaves the plain pair as it is. */
|
||||
TEST(hc_read_fp8_forms_are_the_quantisers_of_the_stored_x) {
|
||||
const HcCase c;
|
||||
const int64_t hn = c.hc * c.n, g = 2;
|
||||
@@ -6483,13 +6373,8 @@ TEST(hc_read_fp8_forms_are_the_quantisers_of_the_stored_x) {
|
||||
T q2(RAD_F8E4M3, {c.rows, c.n}), s2(RAD_F32, {c.rows, c.n / g});
|
||||
A b; b.t(x).t(q2).t(s2).i("M", c.rows).i("n", c.n).i("group", g).s("dtype", "bf16");
|
||||
CHECK_OK(run("quant_act_fp8", b));
|
||||
T rq2(RAD_F8E4M3, {c.rows, c.n}), rs2(RAD_F32, {c.rows, c.n / g});
|
||||
A d; d.t(x).t(rq2).t(rs2).i("M", c.rows).i("n", c.n).i("group", g).s("dtype", "bf16");
|
||||
CHECK_OK(run("had_quant_act_fp8", d));
|
||||
CHECK(std::memcmp(q.t.data, q2.t.data, (size_t)(c.rows * c.n)) == 0);
|
||||
CHECK(std::memcmp(s.t.data, s2.t.data, (size_t)(c.rows * c.n / g * 4)) == 0);
|
||||
CHECK(std::memcmp(rq.t.data, rq2.t.data, (size_t)(c.rows * c.n)) == 0);
|
||||
CHECK(std::memcmp(rs.t.data, rs2.t.data, (size_t)(c.rows * c.n / g * 4)) == 0);
|
||||
}
|
||||
|
||||
/* mtp_enter with `ngroup` hc (one rsqrt per sub-stream) and 1 (one over the wide row), on streams
|
||||
@@ -6588,39 +6473,6 @@ TEST(gate_add_act_none_adds_through_the_gate_itself) {
|
||||
CHECK_EQ(run("gate_add", c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* ln_mod_quant_fp8 with `gated` is gate_add, ln_mod and quant_act_fp8 in one pass: the same bytes
|
||||
* in x, z, the codes and the scales as the three ops. */
|
||||
TEST(ln_mod_quant_fp8_is_the_three_ops_byte_for_byte) {
|
||||
const std::vector<float> yv = { 5, 6, 7, 8, 0.3f, -0.7f, 0.1f, 1.9f };
|
||||
const std::vector<float> gv = { 0, 0, 20, -20, 0.5f, 1, -1, 2 };
|
||||
const std::vector<float> xv = { 1, 2, 3, 4, -0.25f, 0.5f, 3, -2 };
|
||||
const std::vector<float> sv = { 0.5f, -0.5f, 1, 0, 0.25f, 0.125f, -0.75f, 2 };
|
||||
const int64_t n = 4;
|
||||
T cu(RAD_I32, {3}); cu.n({0, 1, 2});
|
||||
T y(RAD_BF16, {2, n}); y.f(yv);
|
||||
T g(RAD_BF16, {2, n}); g.f(gv);
|
||||
T s(RAD_BF16, {2, n}); s.f(sv);
|
||||
T x1(RAD_BF16, {2, n}); x1.f(xv);
|
||||
T q1(RAD_F8E4M3, {2, n}), sc1(RAD_F32, {2, 2}), z1(RAD_BF16, {2, n});
|
||||
A a; a.t(y).t(g).t(s).t(cu).t(x1).t(q1).t(sc1).t(z1)
|
||||
.i("M", 2).i("n", n).d("eps", 1e-6).i("group", 2).i("gated", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("ln_mod_quant_fp8", a));
|
||||
|
||||
T x2(RAD_BF16, {2, n}); x2.f(xv);
|
||||
A b; b.t(y).t(g).t(cu).t(x2).i("M", 2).i("n", n).s("dtype", "bf16");
|
||||
CHECK_OK(run("gate_add", b));
|
||||
T z2(RAD_BF16, {2, n});
|
||||
A c; c.t(x2).t(s).t(cu).t(z2).i("M", 2).i("n", n).d("eps", 1e-6).s("dtype", "bf16");
|
||||
CHECK_OK(run("ln_mod", c));
|
||||
T q2(RAD_F8E4M3, {2, n}), sc2(RAD_F32, {2, 2});
|
||||
A d; d.t(z2).t(q2).t(sc2).i("M", 2).i("n", n).i("group", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("quant_act_fp8", d));
|
||||
CHECK(x1.mem == x2.mem);
|
||||
CHECK(z1.mem == z2.mem);
|
||||
CHECK(q1.mem == q2.mem);
|
||||
CHECK(sc1.mem == sc2.mem);
|
||||
}
|
||||
|
||||
/* timestep_embed: [cos | sin] of t' f_i, f_i = exp(-ln(max_period) i / (n/2)); with `round`, t' is
|
||||
* scale * bf16(bf16(t * scale) / scale), the value diffusers hands its transformer. */
|
||||
TEST(timestep_embed_is_cos_then_sin_of_the_scaled_time) {
|
||||
@@ -7331,77 +7183,6 @@ TEST(rms_mod_column_map_redirects_sequences_to_table_columns) {
|
||||
CHECK_EQ(run("rms_mod", g), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* rms_mod_quant_fp8 is rms_mod with its chain in bf16 and quant_act_fp8 over that row: the same
|
||||
* bytes in x, z, the codes and the scales as the pair. */
|
||||
TEST(rms_mod_quant_fp8_is_rms_mod_then_quant_act_fp8) {
|
||||
const std::vector<float> yv = { 5, 6, 7, 8, 0.3f, -0.7f, 0.1f, 1.9f };
|
||||
const std::vector<float> gv = { 0, 0.5f, 2, -1, 0.5f, 1, -1, 2 };
|
||||
const std::vector<float> xv = { 1, 2, 3, 4, -0.25f, 0.5f, 3, -2 };
|
||||
const std::vector<float> sv = { 0.5f, -0.5f, 1, 0, 0.25f, 0.125f, -0.75f, 2,
|
||||
0, 1, -1, 0.5f, 0.125f, 0.25f, 0.5f, 1 };
|
||||
const int64_t n = 4;
|
||||
T cu(RAD_I32, {3}); cu.n({0, 1, 2});
|
||||
T y(RAD_BF16, {2, n}); y.f(yv);
|
||||
T g(RAD_BF16, {2, n}); g.f(gv);
|
||||
T s(RAD_BF16, {2, 2 * n}); s.f(sv);
|
||||
T w(RAD_BF16, {n}); w.f({1, 0.5f, 2, 0.75f});
|
||||
T x1(RAD_BF16, {2, n}); x1.f(xv);
|
||||
T q1(RAD_F8E4M3, {2, n}), sc1(RAD_F32, {2, 2}), z1(RAD_BF16, {2, n});
|
||||
A a; a.t(y).t(g).t(s).t(w).t(cu).t(x1).t(q1).t(sc1).t(z1)
|
||||
.i("M", 2).i("n", n).d("eps", 1e-5).i("group", 2).i("gated", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("rms_mod_quant_fp8", a));
|
||||
|
||||
T x2(RAD_BF16, {2, n}); x2.f(xv);
|
||||
T z2(RAD_BF16, {2, n});
|
||||
A b; b.t(y).t(g).t(s).t(w).t(cu).t(x2).t(z2).i("M", 2).i("n", n).d("eps", 1e-5)
|
||||
.i("gated", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("rms_mod", b));
|
||||
T q2(RAD_F8E4M3, {2, n}), sc2(RAD_F32, {2, 2});
|
||||
A d; d.t(z2).t(q2).t(sc2).i("M", 2).i("n", n).i("group", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("quant_act_fp8", d));
|
||||
CHECK(x1.mem == x2.mem);
|
||||
CHECK(z1.mem == z2.mem);
|
||||
CHECK(q1.mem == q2.mem);
|
||||
CHECK(sc1.mem == sc2.mem);
|
||||
}
|
||||
|
||||
/* The quant form takes the column map at its own trailing slot (9): the same run, both per-column
|
||||
* operands' rows swapped, the sequences redirected to each other's column, matches byte for byte. */
|
||||
TEST(rms_mod_quant_fp8_takes_the_column_map_too) {
|
||||
const std::vector<float> yv = { 5, 6, 7, 8, 0.3f, -0.7f, 0.1f, 1.9f };
|
||||
const std::vector<float> gv = { 0, 0.5f, 2, -1, 0.5f, 1, -1, 2 };
|
||||
const std::vector<float> xv = { 1, 2, 3, 4, -0.25f, 0.5f, 3, -2 };
|
||||
const std::vector<float> sv = { 0.5f, -0.5f, 1, 0, 0.25f, 0.125f, -0.75f, 2,
|
||||
0, 1, -1, 0.5f, 0.125f, 0.25f, 0.5f, 1 };
|
||||
const int64_t n = 4;
|
||||
T cu(RAD_I32, {3}); cu.n({0, 1, 2});
|
||||
T y(RAD_BF16, {2, n}); y.f(yv);
|
||||
T g(RAD_BF16, {2, n}); g.f(gv);
|
||||
T s(RAD_BF16, {2, 2 * n}); s.f(sv);
|
||||
T w(RAD_BF16, {n}); w.f({1, 0.5f, 2, 0.75f});
|
||||
T x1(RAD_BF16, {2, n}); x1.f(xv);
|
||||
T q1(RAD_F8E4M3, {2, n}), sc1(RAD_F32, {2, 2}), z1(RAD_BF16, {2, n});
|
||||
A a; a.t(y).t(g).t(s).t(w).t(cu).t(x1).t(q1).t(sc1).t(z1)
|
||||
.i("M", 2).i("n", n).d("eps", 1e-5).i("group", 2).i("gated", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("rms_mod_quant_fp8", a));
|
||||
|
||||
T gs(RAD_BF16, {2, n});
|
||||
gs.f({ gv[4], gv[5], gv[6], gv[7], gv[0], gv[1], gv[2], gv[3] });
|
||||
T ss(RAD_BF16, {2, 2 * n});
|
||||
ss.f({ sv[8], sv[9], sv[10], sv[11], sv[12], sv[13], sv[14], sv[15],
|
||||
sv[0], sv[1], sv[2], sv[3], sv[4], sv[5], sv[6], sv[7] });
|
||||
T cm(RAD_I32, {2}); cm.n({1, 0});
|
||||
T x2(RAD_BF16, {2, n}); x2.f(xv);
|
||||
T q2(RAD_F8E4M3, {2, n}), sc2(RAD_F32, {2, 2}), z2(RAD_BF16, {2, n});
|
||||
A b; b.t(y).t(gs).t(ss).t(w).t(cu).t(x2).t(q2).t(sc2).t(z2).t(cm)
|
||||
.i("M", 2).i("n", n).d("eps", 1e-5).i("group", 2).i("gated", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("rms_mod_quant_fp8", b));
|
||||
CHECK(x1.mem == x2.mem);
|
||||
CHECK(z1.mem == z2.mem);
|
||||
CHECK(q1.mem == q2.mem);
|
||||
CHECK(sc1.mem == sc2.mem);
|
||||
}
|
||||
|
||||
/* flow_x0_step in f32 steps: st = 1 - 0.3f, r = 0.4f / 0.7f, d = x + st v, x' = r x + (1 - r) d.
|
||||
* From x 1, v 3 that is 1.8999999f (0x3ff33333), where the algebraically equal x + (1 - r) st v
|
||||
* gives 1.9f; from x -2.5, v 0.75 it is -2.275f. */
|
||||
@@ -9643,18 +9424,6 @@ TEST(fill_writes_its_value_at_the_row_pitch_only) {
|
||||
CHECK_EQ(buf.at(0), 0.0f); CHECK_EQ(buf.at(3), 9.0f);
|
||||
}
|
||||
|
||||
/* had_quant_act_fp8 rotates each group by an unnormalised Hadamard before the absmax: [1, 1]
|
||||
* becomes [2, 0] and [1, -1] becomes [0, 2]; the scale is amax / 448 with no 1/sqrt(group). */
|
||||
TEST(had_quant_act_fp8_rotates_before_the_absmax) {
|
||||
T x(RAD_F32, {1, 4}); x.f({1, 1, 1, -1});
|
||||
T q(RAD_F8E4M3, {1, 4}), s(RAD_F32, {1, 2});
|
||||
A a; a.t(x).t(q).t(s).i("M", 1).i("n", 4).i("group", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("had_quant_act_fp8", a));
|
||||
CHECK_EQ(s.at(0), 2.0f / 448.0f); CHECK_EQ(s.at(1), 2.0f / 448.0f);
|
||||
CHECK_EQ(q.at(0), 448.0f); CHECK_EQ(q.at(1), 0.0f);
|
||||
CHECK_EQ(q.at(2), 0.0f); CHECK_EQ(q.at(3), 448.0f);
|
||||
}
|
||||
|
||||
/* had_quant_act_i8g is the same at int8 codes: amax / 127, nothing folded either. */
|
||||
TEST(had_quant_act_i8g_rotates_before_the_absmax) {
|
||||
T x(RAD_F32, {1, 4}); x.f({1, 1, 1, -1});
|
||||
@@ -9982,29 +9751,6 @@ TEST(gemm_nt_q_bias_adds_a_bias_per_column) {
|
||||
CHECK_EQ(y.at(1), 21.0f);
|
||||
}
|
||||
|
||||
/* givens_rotate divides by the channel scale, then turns each pair (a, b) into
|
||||
* (a cos t + b sin t, b cos t - a sin t), per part; a pair index outside the row is refused. */
|
||||
TEST(givens_rotate_scales_then_rotates_each_part) {
|
||||
T x(RAD_F32, {1, 2}); x.f({1, 4});
|
||||
T pr(RAD_I32, {2, 2}); pr.n({0, 1, 1, 0}); /* part 1 pairs (1, 0) */
|
||||
T an(RAD_F32, {2, 1}); an.f({0.5f, 0.25f});
|
||||
T sc(RAD_F32, {2, 2}); sc.f({1, 2, 2, 1});
|
||||
T y(RAD_F32, {1, 4});
|
||||
A a; a.t(x).t(pr).t(an).t(sc).t(y).i("M", 1).i("n", 2).i("group", 2).s("dtype", "f32")
|
||||
.i("stages", 1).i("parts", 2);
|
||||
CHECK_OK(run("givens_rotate", a));
|
||||
const double c0 = std::cos(0.5f), s0 = std::sin(0.5f), c1 = std::cos(0.25f), s1 = std::sin(0.25f);
|
||||
CHECK_NEAR(y.at(0), 1 * c0 + 2 * s0, 1e-6); /* part 0: x / [1, 2] = [1, 2] */
|
||||
CHECK_NEAR(y.at(1), 2 * c0 - 1 * s0, 1e-6);
|
||||
/* Part 1: x / [2, 1] = [0.5, 4], pair (a, b) = (lane 1, lane 0). */
|
||||
CHECK_NEAR(y.at(3), 4 * c1 + 0.5 * s1, 1e-6);
|
||||
CHECK_NEAR(y.at(2), 0.5 * c1 - 4 * s1, 1e-6);
|
||||
T bad(RAD_I32, {2, 2}); bad.n({0, 2, 1, 0});
|
||||
A b; b.t(x).t(bad).t(an).t(sc).t(y).i("M", 1).i("n", 2).i("group", 2).s("dtype", "f32")
|
||||
.i("stages", 1).i("parts", 2);
|
||||
CHECK_EQ(run("givens_rotate", b), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* gram_accum adds x^T x into h (twice is twice once); with a scale, x is dequantised per group. */
|
||||
TEST(gram_accum_accumulates_the_dequantised_gram) {
|
||||
T a_(RAD_BF16, {2, 2}); a_.f({1, 2, 3, 4});
|
||||
@@ -10372,17 +10118,12 @@ std::vector<Geo> geometries() {
|
||||
G("quant_act_i8g", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("quant_act_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("quant_cols_fp8", "M", 3, a.i("M", R).i("n", 32).s("dtype", "f32")),
|
||||
G("had_quant_act_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("had_quant_act_i8g", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("had_quant_act_i8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("rmsnorm_had_quant_i8", "M", 3, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16)
|
||||
.s("dtype", "f32")),
|
||||
G("gated_had_quant_i8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("gram_accum", "M", 3, a.i("M", R).i("n", 16).i("group", 8).s("dtype", "fp8a8")),
|
||||
G("givens_dense_quant", "M", 3, a.i("M", R).i("n", 128).i("group", 128).s("dtype", "f32")
|
||||
.i("parts", 1).s("out", "fp8")),
|
||||
G("givens_rotate", "M", 3, a.i("M", R).i("n", 8).i("group", 8).s("dtype", "f32")
|
||||
.i("stages", 2).i("parts", 1)),
|
||||
G("dequant", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")),
|
||||
G("dequant_w4", "N", 16, a.i("N", R).i("K", 64).i("group", 64).i("twos", 1)
|
||||
.s("dtype", "w4a8")),
|
||||
@@ -10394,8 +10135,6 @@ std::vector<Geo> geometries() {
|
||||
.s("act", "silu")),
|
||||
G("gemm_nt_q_gated", "M", 3, a.i("M", R).i("N", 32).i("K", 128).i("group", 128)
|
||||
.s("dtype", "fp8a8").s("act", "silu")),
|
||||
G("gemm_nt_q_gated_wide", "M", 3, a.i("M", R).i("N", 32).i("K", 128).i("group", 128)
|
||||
.s("dtype", "fp8a8").s("act", "silu")),
|
||||
G("dflash_select", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
|
||||
.i("n_vocab", 30).s("dtype", "bf16")),
|
||||
G("dflash_markov_greedy", "M", 2, a.i("M", R).i("steps", 3).i("rank", 32)
|
||||
@@ -10409,7 +10148,6 @@ std::vector<Geo> geometries() {
|
||||
G("gemm_nt", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
|
||||
G("gemm_nt_bias", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
|
||||
G("gemm_nt_q", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128).s("dtype", "fp8a8")),
|
||||
G("gemm_nt_q_short", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128).s("dtype", "fp8a8")),
|
||||
G("gemm_nt_q_bias", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128)
|
||||
.s("dtype", "fp8a8")),
|
||||
G("lora_shrink", "M", 3, a.i("M", R).i("K", 40).i("R", 8).i("S", 2).s("dtype", "f32")),
|
||||
@@ -10440,7 +10178,7 @@ std::vector<Geo> geometries() {
|
||||
.s("kv_dtype", "f32")),
|
||||
G("kv_store_streamed", "M", 3,
|
||||
a.i("M", R).i("head_dim", 8).i("n_head_kv", 2).i("block_size", 8)
|
||||
.s("kv_dtype", "fp8_e4m3")),
|
||||
.s("kv_dtype", "i8")),
|
||||
G("rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1)
|
||||
.d("theta", 1e4).d("scale", 1.0).s("mode", "neox")),
|
||||
G("rope_rows", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1)
|
||||
@@ -10531,8 +10269,6 @@ std::vector<Geo> geometries() {
|
||||
G("sample_argmax", "M", 2, a.i("M", R).i("n_vocab", 64)),
|
||||
G("sample_logprobs", "M", 2, a.i("M", R).i("n_vocab", 64).i("k", 4)),
|
||||
G("ln_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "bf16")),
|
||||
G("ln_mod_quant_fp8", "M", 4, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16)
|
||||
.i("gated", 1).s("dtype", "bf16")),
|
||||
G("gate_add", "M", 4, a.i("M", R).i("n", 8).s("dtype", "bf16")),
|
||||
G("timestep_embed", "M", 3, a.i("M", R).i("n", 8).d("scale", 1000.0)
|
||||
.d("max_period", 10000.0).d("clamp_min", 0.3).s("dtype", "f32")),
|
||||
@@ -10626,8 +10362,6 @@ std::vector<Geo> geometries() {
|
||||
G("frame_store", "M", 2, a.i("M", R).i("n_codes", 4).i("stride", 6).i("rep", 2)
|
||||
.i("skip", 0)),
|
||||
G("rms_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).i("gated", 1).s("dtype", "bf16")),
|
||||
G("rms_mod_quant_fp8", "M", 4, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16)
|
||||
.i("gated", 1).s("dtype", "bf16")),
|
||||
G("flow_x0_step", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("flow_res_multistep", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("patch_unfold", "M", 32, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2)
|
||||
@@ -10707,8 +10441,7 @@ std::vector<Geo> geometries() {
|
||||
* them. */
|
||||
bool undrawable(const char* op) {
|
||||
// Complete raster grids need the hand-built cases in nemotron35_test, not random indices.
|
||||
return !std::strcmp(op, "givens_dense_quant") || !std::strcmp(op, "givens_rotate") ||
|
||||
!std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") ||
|
||||
return !std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") ||
|
||||
!std::strcmp(op, "pixtral_merge") ||
|
||||
/* sample_logprobs rows (sorted pairs, positive sums): avx_check_hand.cpp builds them */
|
||||
!std::strcmp(op, "lili_cand");
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+33
-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) {
|
||||
@@ -846,8 +843,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 +853,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 +922,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);
|
||||
|
||||
@@ -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,
|
||||
@@ -3198,6 +3220,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();
|
||||
|
||||
+114
-49
@@ -1841,6 +1841,39 @@ TEST(an_idle_overdue_prefill_reclaims_a_leaked_state_slot) {
|
||||
f.commit_plain();
|
||||
}
|
||||
|
||||
/* Two overdue preempted requests on an idle engine, admitted in one pass, with no room for the
|
||||
* second's whole recompute beside the first. A request the pass has just admitted is not in
|
||||
* running_ yet, so the engine still looked idle to the second, whose reclaim took the first's state
|
||||
* slots: its chunk ran with no recurrent state and the next from zeros, and the model no longer knew
|
||||
* the start of its conversation. */
|
||||
TEST(an_overdue_prefill_leaves_the_state_of_one_admitted_beside_it) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/30, /*states=*/4); /* 30 x 16 = 480 tokens */
|
||||
f.cfg.preempt_wait_ms = 0;
|
||||
f.cfg.max_seqs = 3;
|
||||
f.cfg.max_tok = 128;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
const uint64_t b = f.submit(200, 8, /*priority=*/0);
|
||||
const uint64_t c = f.submit(440, 8, /*priority=*/0);
|
||||
for (int i = 0; i < 8 && f.sch.find(c)->state != ReqState::Running; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
}
|
||||
REQUIRE_EQ((int)f.sch.find(c)->state, (int)ReqState::Running);
|
||||
CHECK_EQ(f.sch.preempt_until([] { return false; }), 2);
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
|
||||
CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Preempted);
|
||||
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Running);
|
||||
for (size_t g = 0; g < f.kv.gs.size(); ++g)
|
||||
if (!f.kv.geom.g[g].paged) CHECK(f.kv.state_slot(b, (int32_t)g) >= 0);
|
||||
/* The second waits for the room it asked for. */
|
||||
CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Preempted);
|
||||
f.commit_plain();
|
||||
}
|
||||
|
||||
/* can_grow on an id the manager has forgotten is false. That must not park an idle engine:
|
||||
* admit adds the sequence. */
|
||||
TEST(an_idle_overdue_prefill_is_admitted_when_its_kv_sequence_is_gone) {
|
||||
@@ -3091,6 +3124,40 @@ TEST(off_a_long_prefill_keeps_a_new_request_out_of_every_step) {
|
||||
CHECK_EQ(f.sch.metrics().prefill_chunks_capped, 0);
|
||||
}
|
||||
|
||||
/* A prefill chunk held back for others and then refused KV is preempted with no entry in the plan.
|
||||
* The growth pass at the end of the step must not take the next entry, or the slot past the last,
|
||||
* for it: the slot past the last holds a stale entry from an earlier step, and growing it left the
|
||||
* plan's token count above its entries, so the whole step was thrown away. */
|
||||
TEST(a_held_back_chunk_refused_kv_leaves_no_mark_on_the_plan) {
|
||||
/* Decode rows ahead of long prefills on a pool too small for them all, across pool sizes and
|
||||
* arrival orders, so a chunk is held back for the rows and then refused its blocks. */
|
||||
for (int64_t blocks = 8; blocks <= 160; ++blocks)
|
||||
for (int shape = 0; shape < 4; ++shape) {
|
||||
Fixture f;
|
||||
f.build(blocks, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/4096);
|
||||
f.cfg.busy_prefill_chunk = -1;
|
||||
CHECK_OK(f.start());
|
||||
std::vector<uint64_t> ids;
|
||||
for (int r = 0; r < 2 + shape; ++r) ids.push_back(f.submit(32 + 16 * r, 2000, 0, true));
|
||||
for (int k = 0; k < 400; ++k) {
|
||||
if (k % 6 == 5 && ids.size() < 12) ids.push_back(f.submit(400 + 96 * ((k + shape) % 7), 64));
|
||||
const RadBatch* b = f.sch.step();
|
||||
if (!b) {
|
||||
/* An empty step only ever means nothing could run. */
|
||||
bool running = false;
|
||||
for (uint64_t id : ids)
|
||||
if (const Request* q = f.sch.find(id)) running = running || q->state == ReqState::Running;
|
||||
CHECK(!running);
|
||||
break;
|
||||
}
|
||||
int64_t sum = 0;
|
||||
for (const StepEntry& e : f.sch.plan().e) sum += e.n_tokens;
|
||||
CHECK_EQ(b->n_tok, sum);
|
||||
f.commit_plain();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* auto: the same arrival is admitted in the next step, and its prompt finishes in two. */
|
||||
TEST(auto_a_request_arriving_during_a_long_prefill_is_admitted_at_once) {
|
||||
Fixture f;
|
||||
@@ -3654,65 +3721,62 @@ TEST(the_adaptive_window_moves_only_past_its_hold_and_never_below_one_draft) {
|
||||
CHECK_EQ(w.depth, 0);
|
||||
off.observe(5, 2);
|
||||
CHECK_EQ(off.verified_at(5), (int64_t)0);
|
||||
off.step_time(3, 1, 12.0); /* and no step is timed */
|
||||
CHECK_EQ(off.cost_samples(3, 1), (int64_t)0);
|
||||
off.step_time(4, 12.0); /* and no step is timed */
|
||||
CHECK_EQ(off.cost_samples(4), (int64_t)0);
|
||||
|
||||
/* Adaptive with no speculation is no policy at all. */
|
||||
DraftController zero = adaptive_controller(0);
|
||||
CHECK(!zero.adaptive());
|
||||
}
|
||||
|
||||
/* The step cost is measured. A key (the step's deepest window, its class of running sequences)
|
||||
* with samples is its own mean; one without borrows the nearest measured key's, scaled by the
|
||||
* prior's shape; with nothing measured it is the prior. Same times, same choice. */
|
||||
/* The step cost is measured by query rows (StepCost). A timed row count is its own mean; one
|
||||
* between two timed counts lies on their line; one outside them is the nearest scaled by the
|
||||
* prior's shape; with nothing timed it is the prior. Same times, same choice. */
|
||||
TEST(the_adaptive_window_prices_a_step_from_measured_step_times) {
|
||||
DraftController c = adaptive_controller(6);
|
||||
CHECK_NEAR(c.step_cost(1, 1), 1.06, 1e-12); /* the prior */
|
||||
CHECK_NEAR(c.step_cost(6, 1), 1.36, 1e-12);
|
||||
const double k = DraftController::kRowCost;
|
||||
CHECK_NEAR(c.step_cost(1), 1.0, 1e-12); /* the prior */
|
||||
CHECK_NEAR(c.step_cost(7), 1.0 + 6 * k, 1e-12);
|
||||
|
||||
for (int i = 0; i < 10; ++i) c.step_time(3, 1, 12.0);
|
||||
CHECK_EQ(c.cost_samples(3, 1), (int64_t)10);
|
||||
CHECK_NEAR(c.step_cost(3, 1), 12.0, 1e-9);
|
||||
CHECK_NEAR(c.step_cost(5, 1), 12.0 * 1.30 / 1.18, 1e-9); /* borrowed, the prior's shape */
|
||||
CHECK_NEAR(c.step_cost(3, 9), 12.0, 1e-9); /* the nearest class */
|
||||
CHECK_EQ(c.cost_samples(3, 9), (int64_t)0);
|
||||
/* The classes: 1, 2-3, 4-7, 8-15, 16 and up. */
|
||||
c.step_time(3, 2, 20.0);
|
||||
CHECK_NEAR(c.step_cost(3, 3), 20.0, 1e-9);
|
||||
CHECK_NEAR(c.step_cost(3, 4), 20.0, 1e-9); /* 4-7 borrows from 2-3 */
|
||||
c.step_time(3, 16, 40.0);
|
||||
CHECK_NEAR(c.step_cost(3, 1000), 40.0, 1e-9);
|
||||
CHECK_NEAR(c.step_cost(3, 9), 40.0, 1e-9); /* 8-15: the nearest, 16 and up */
|
||||
for (int i = 0; i < 10; ++i) c.step_time(4, 12.0);
|
||||
CHECK_EQ(c.cost_samples(4), (int64_t)10);
|
||||
CHECK_NEAR(c.step_cost(4), 12.0, 1e-9);
|
||||
CHECK_NEAR(c.step_cost(6), 12.0 * (1 + 5 * k) / (1 + 3 * k), 1e-9); /* outside: the shape */
|
||||
CHECK_EQ(c.cost_samples(6), (int64_t)0);
|
||||
for (int i = 0; i < 10; ++i) c.step_time(8, 16.0);
|
||||
CHECK_NEAR(c.step_cost(6), 14.0, 1e-9); /* between: the line */
|
||||
CHECK_NEAR(c.step_cost(3), 12.0 * (1 + 2 * k) / (1 + 3 * k), 1e-9);
|
||||
CHECK_NEAR(c.step_cost(10), 16.0 * (1 + 9 * k) / (1 + 7 * k), 1e-9);
|
||||
|
||||
/* A step that waited on something else counts for at most four times the mean. */
|
||||
const double before = c.step_cost(3, 1);
|
||||
c.step_time(3, 1, 1.0e6);
|
||||
CHECK(c.step_cost(3, 1) <= before * 4.0);
|
||||
CHECK(c.step_cost(3, 1) > before);
|
||||
const double before = c.step_cost(4);
|
||||
c.step_time(4, 1.0e6);
|
||||
CHECK(c.step_cost(4) <= before * 4.0);
|
||||
CHECK(c.step_cost(4) > before);
|
||||
|
||||
/* Nonsense is not a sample. */
|
||||
c.step_time(0, 1, 5.0);
|
||||
c.step_time(7, 1, 5.0);
|
||||
c.step_time(2, 1, -1.0);
|
||||
c.step_time(2, 0, 5.0);
|
||||
CHECK_EQ(c.cost_samples(2, 1), (int64_t)0);
|
||||
c.step_time(0, 5.0);
|
||||
c.step_time(2, -1.0);
|
||||
CHECK_EQ(c.cost_samples(2), (int64_t)0);
|
||||
CHECK_EQ(c.cost_samples(0), (int64_t)0);
|
||||
|
||||
/* One sequence that accepts nearly everything: on the prior the whole window pays... */
|
||||
DraftController p = adaptive_controller(6);
|
||||
DraftAdapt s = estimate(p, 0.9, 0.9);
|
||||
DraftAdapt* one[1] = { &s };
|
||||
CHECK_EQ(p.plan_step(one, 1, 1), 6);
|
||||
/* ...and where the steps past three were measured dear, three is what pays. */
|
||||
/* ...and where the steps past three drafts (four rows) were measured dear, three is what
|
||||
* pays. */
|
||||
DraftController m = adaptive_controller(6);
|
||||
const double t[7] = { 0, 10.0, 11.0, 12.0, 30.0, 30.0, 30.0 };
|
||||
for (int d = 1; d <= 6; ++d) m.step_time(d, 1, t[d]);
|
||||
for (int d = 1; d <= 6; ++d) m.step_time(1 + d, t[d]);
|
||||
DraftAdapt u = estimate(m, 0.9, 0.9);
|
||||
DraftAdapt* mu[1] = { &u };
|
||||
CHECK_EQ(m.plan_step(mu, 1, 1), 3);
|
||||
CHECK_EQ(m.window_for(u), 3);
|
||||
/* Deterministic: the same times and the same estimate give the same depth. */
|
||||
DraftController m2 = adaptive_controller(6);
|
||||
for (int d = 1; d <= 6; ++d) m2.step_time(d, 1, t[d]);
|
||||
for (int d = 1; d <= 6; ++d) m2.step_time(1 + d, t[d]);
|
||||
DraftAdapt u2 = estimate(m2, 0.9, 0.9);
|
||||
DraftAdapt* mu2[1] = { &u2 };
|
||||
CHECK_EQ(m2.plan_step(mu2, 1, 1), 3);
|
||||
@@ -3735,36 +3799,37 @@ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) {
|
||||
CHECK_EQ(c.window_for(deep), 6);
|
||||
CHECK_EQ(c.window_for(shallow), 1);
|
||||
|
||||
/* The same deep sequence among seven shallow ones, at a class whose steps were measured to
|
||||
* grow by three units per round: eight rows pay for the rounds, and the one that gains does not
|
||||
* repay it. Every window comes down to one. */
|
||||
/* The same deep sequence among seven shallow ones, where steps were measured to grow by
|
||||
* three units per row past the fifteen the eight carry at one draft each: the one that gains
|
||||
* does not repay its rows and rounds. Every window comes down to one. */
|
||||
DraftController b = adaptive_controller(6);
|
||||
for (int d = 1; d <= 6; ++d) b.step_time(d, 8, 10.0 + 3.0 * d);
|
||||
for (int d = 1; d <= 6; ++d) b.step_time(15 + d, 10.0 + 3.0 * d);
|
||||
DraftAdapt bd = estimate(b, 0.95, 0.95);
|
||||
DraftAdapt bs[7];
|
||||
DraftAdapt* eight[8] = { &bd };
|
||||
for (int i = 0; i < 7; ++i) { bs[i] = estimate(b, 0.5, 0.15); eight[i + 1] = &bs[i]; }
|
||||
CHECK_EQ(b.plan_step(eight, 8, 8), 1);
|
||||
CHECK_EQ(b.window_for(bd), 1);
|
||||
/* Alone at its own class, unmeasured, the same sequence takes the whole window. */
|
||||
/* Alone, at row counts far under any timed one (priced on the prior's shape), the same
|
||||
* sequence drafts deeper. */
|
||||
DraftController a = adaptive_controller(6);
|
||||
for (int d = 1; d <= 6; ++d) a.step_time(d, 8, 10.0 + 3.0 * d);
|
||||
for (int d = 1; d <= 6; ++d) a.step_time(15 + d, 10.0 + 3.0 * d);
|
||||
DraftAdapt ad = estimate(a, 0.95, 0.95);
|
||||
DraftAdapt* lone[1] = { &ad };
|
||||
CHECK(a.plan_step(lone, 1, 1) > 1);
|
||||
|
||||
/* Rows that do not draft are part of the step: they emit a token whatever D is and pay for
|
||||
* every round. Here three plain rows beside one drafting row at the same measured class. */
|
||||
* every round. Here three plain rows beside one drafting row, at the same measured times. */
|
||||
DraftController r = adaptive_controller(6);
|
||||
for (int d = 1; d <= 6; ++d) r.step_time(d, 4, 10.0 + 3.0 * d);
|
||||
for (int d = 1; d <= 6; ++d) r.step_time(4 + d, 10.0 + 3.0 * d);
|
||||
DraftAdapt rd = estimate(r, 0.95, 0.95);
|
||||
DraftAdapt* rone[1] = { &rd };
|
||||
const int with_plain = r.plan_step(rone, 1, 4);
|
||||
DraftController r2 = adaptive_controller(6);
|
||||
for (int d = 1; d <= 6; ++d) r2.step_time(d, 4, 10.0 + 3.0 * d);
|
||||
for (int d = 1; d <= 6; ++d) r2.step_time(4 + d, 10.0 + 3.0 * d);
|
||||
DraftAdapt rd2 = estimate(r2, 0.95, 0.95);
|
||||
DraftAdapt* rone2[1] = { &rd2 };
|
||||
const int alone = r2.plan_step(rone2, 1, 1); /* class 1 unmeasured: borrows class 4-7 */
|
||||
const int alone = r2.plan_step(rone2, 1, 1); /* two to seven rows: partly timed */
|
||||
CHECK(with_plain <= alone);
|
||||
|
||||
/* D moves past a hold and a hysteresis. The first step that drafts takes the best outright;
|
||||
@@ -3773,7 +3838,7 @@ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) {
|
||||
DraftAdapt hs = estimate(h, 0.95, 0.95);
|
||||
DraftAdapt* hone[1] = { &hs };
|
||||
CHECK_EQ(h.plan_step(hone, 1, 1), 6);
|
||||
for (int d = 1; d <= 6; ++d) h.step_time(d, 1, d <= 2 ? 10.0 : 40.0);
|
||||
for (int d = 1; d <= 6; ++d) h.step_time(1 + d, d <= 2 ? 10.0 : 40.0);
|
||||
for (int t = 0; t < DraftController::kHold - 1; ++t) CHECK_EQ(h.plan_step(hone, 1, 1), 6);
|
||||
CHECK_EQ(h.plan_step(hone, 1, 1), 2);
|
||||
/* No drafting sequence: D stays where it is. */
|
||||
@@ -4472,9 +4537,9 @@ TEST(prompt_lookup_does_not_scan_the_context) {
|
||||
CHECK_EQ(ix.indexed(), (int64_t)seq.size() - 1);
|
||||
}
|
||||
|
||||
/* The scheduler's half of the cost: a decode step that verified drafts is timed at its deepest
|
||||
* window and row count, and the next cycle's head depth reads it. Measured dear past one round at
|
||||
* two rows, both windows (and the rounds) come down to one. */
|
||||
/* The scheduler's half of the cost: a decode step that verified drafts is timed at its query
|
||||
* rows, and the next cycle's head depth reads it. Measured dear past one draft a sequence, both
|
||||
* windows (and the rounds) come down to one. */
|
||||
TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) {
|
||||
Fixture f;
|
||||
adaptive_fixture(f, 4);
|
||||
@@ -4490,7 +4555,7 @@ TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) {
|
||||
REQUIRE(f.sch.step() != nullptr); /* both prompts */
|
||||
commit_all();
|
||||
f.sch.step_finished(); /* a prefill step: not a sample */
|
||||
for (int d = 1; d <= 4; ++d) CHECK_EQ(f.sch.draft().cost_samples(d, 2), (int64_t)0);
|
||||
for (int d = 1; d <= 4; ++d) CHECK_EQ(f.sch.draft().cost_samples(2 + 2 * d), (int64_t)0);
|
||||
|
||||
int32_t draft[4] = { 21, 22, 23, 24 };
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 4));
|
||||
@@ -4499,11 +4564,11 @@ TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) {
|
||||
CHECK_EQ(f.sch.plan().n_spec, 4);
|
||||
commit_all();
|
||||
f.sch.step_finished();
|
||||
CHECK_EQ(f.sch.draft().cost_samples(4, 2), (int64_t)1);
|
||||
CHECK_EQ(f.sch.draft().cost_samples(10), (int64_t)1); /* two sequences, five rows each */
|
||||
|
||||
/* The hold, then a cycle that reads steps past one round as four times dearer. */
|
||||
for (int d = 1; d <= 4; ++d)
|
||||
for (int i = 0; i < 64; ++i) f.sch.draft().step_time(d, 2, d == 1 ? 10.0 : 40.0);
|
||||
for (int i = 0; i < 64; ++i) f.sch.draft().step_time(2 + 2 * d, d == 1 ? 10.0 : 40.0);
|
||||
for (int t = 0; t < DraftController::kHold + 1; ++t) {
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 4));
|
||||
CHECK_OK(f.sch.set_draft(b, draft, 4));
|
||||
|
||||
@@ -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 */
|
||||
|
||||
|
||||
+180
-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";
|
||||
@@ -2838,10 +2929,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 +2940,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 +3481,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 +3612,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 +3708,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 +3718,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 +4091,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 +4483,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);
|
||||
}
|
||||
@@ -5023,6 +5176,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 +5220,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 +5244,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 +5255,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 +5662,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()
|
||||
@@ -99,6 +99,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
{ "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen35moe", "w8a8_fwht128" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },
|
||||
{ "spark25", "" }, { "spark25", "w8a8_fwht128" }, { "sdxl", "" },
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -85,6 +85,7 @@ struct ChatReply {
|
||||
|
||||
ChatReply chat_stream(const std::string& body) {
|
||||
ChatReply a;
|
||||
std::string reasoning_alias;
|
||||
int bad = 0;
|
||||
for (const std::string& p : sse_payloads(body, &bad)) {
|
||||
if (p == "[DONE]") continue;
|
||||
@@ -96,6 +97,7 @@ ChatReply chat_stream(const std::string& body) {
|
||||
if (d.contains("content") && d["content"].is_string())
|
||||
a.content += d["content"].get<std::string>();
|
||||
if (d.contains("reasoning_content")) a.reasoning += d["reasoning_content"].get<std::string>();
|
||||
if (d.contains("reasoning")) reasoning_alias += d["reasoning"].get<std::string>();
|
||||
if (!d.contains("tool_calls")) continue;
|
||||
for (const json& tc : d["tool_calls"]) {
|
||||
const size_t k = tc["index"].get<size_t>();
|
||||
@@ -106,6 +108,7 @@ ChatReply chat_stream(const std::string& body) {
|
||||
}
|
||||
}
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK_EQ(reasoning_alias, a.reasoning);
|
||||
return a;
|
||||
}
|
||||
|
||||
@@ -116,6 +119,7 @@ ChatReply chat_buffered(const std::string& body) {
|
||||
const json& m = c["message"];
|
||||
if (m["content"].is_string()) a.content = m["content"].get<std::string>();
|
||||
if (m.contains("reasoning_content")) a.reasoning = m["reasoning_content"].get<std::string>();
|
||||
CHECK_EQ(m.value("reasoning", std::string()), a.reasoning);
|
||||
if (m.contains("tool_calls"))
|
||||
for (const json& tc : m["tool_calls"])
|
||||
a.calls.emplace_back(tc["function"]["name"].get<std::string>(),
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
#include "server/sink.h"
|
||||
#include "server/systemone.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
+52
-59
@@ -24,7 +24,9 @@
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_test.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
using Json = rad::Json;
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
@@ -136,7 +138,7 @@ inline Tensor linear(const std::string& name, int64_t n_out, int64_t n_in, Rng&
|
||||
|
||||
/* One safetensors file holding `ts` in order, with the header padded to 8 bytes. */
|
||||
inline bool write_safetensors(const std::string& path, const std::vector<Tensor>& ts) {
|
||||
nlohmann::ordered_json h = nlohmann::ordered_json::object();
|
||||
Json h = Json::object();
|
||||
uint64_t off = 0;
|
||||
for (const Tensor& t : ts) {
|
||||
h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape },
|
||||
@@ -163,7 +165,7 @@ inline std::vector<Tensor> read_safetensors(const std::string& path) {
|
||||
uint64_t n = 0;
|
||||
std::memcpy(&n, raw.data(), 8);
|
||||
if (8 + n > raw.size()) return ts;
|
||||
const auto h = nlohmann::ordered_json::parse(raw.substr(8, n), nullptr, false);
|
||||
const auto h = Json::parse(raw.substr(8, n), nullptr, false);
|
||||
if (!h.is_object()) return ts;
|
||||
for (auto it = h.begin(); it != h.end(); ++it) {
|
||||
if (it.key() == "__metadata__") continue;
|
||||
@@ -205,18 +207,18 @@ enum : int32_t { kEndOfText = 256, kImStart = 257, kImEnd = 258, kTokenizerSize
|
||||
/* tokenizer.json: byte-level BPE, ids 0..255 the bytes, no merges, then the specials, then
|
||||
* `extra` special tokens from kTokenizerSize on. */
|
||||
inline std::string tokenizer_json(const std::vector<std::string>& extra = {}) {
|
||||
nlohmann::ordered_json vocab = nlohmann::ordered_json::object();
|
||||
Json vocab = Json::object();
|
||||
for (int b = 0; b < 256; ++b) vocab[byte_symbol(b)] = b;
|
||||
std::vector<std::string> specials = { "<|endoftext|>", "<|im_start|>", "<|im_end|>" };
|
||||
specials.insert(specials.end(), extra.begin(), extra.end());
|
||||
nlohmann::ordered_json added = nlohmann::ordered_json::array();
|
||||
Json added = Json::array();
|
||||
for (int i = 0; i < (int)specials.size(); ++i) {
|
||||
vocab[specials[(size_t)i]] = 256 + i;
|
||||
added.push_back({ { "id", 256 + i }, { "content", specials[(size_t)i] },
|
||||
{ "single_word", false }, { "lstrip", false }, { "rstrip", false },
|
||||
{ "normalized", false }, { "special", true } });
|
||||
}
|
||||
nlohmann::ordered_json j;
|
||||
Json j;
|
||||
j["version"] = "1.0";
|
||||
j["added_tokens"] = added;
|
||||
j["normalizer"] = nullptr;
|
||||
@@ -227,7 +229,7 @@ inline std::string tokenizer_json(const std::vector<std::string>& extra = {}) {
|
||||
{ "trim_offsets", false }, { "use_regex", true } };
|
||||
j["model"] = { { "type", "BPE" }, { "dropout", nullptr }, { "unk_token", nullptr },
|
||||
{ "byte_fallback", false }, { "vocab", vocab },
|
||||
{ "merges", nlohmann::ordered_json::array() } };
|
||||
{ "merges", Json::array() } };
|
||||
return j.dump();
|
||||
}
|
||||
|
||||
@@ -239,7 +241,7 @@ inline std::vector<int32_t> byte_ids(const std::string& text) {
|
||||
}
|
||||
|
||||
/* config.json, model.safetensors and tokenizer.json in `dir`. */
|
||||
inline bool write_checkpoint(const std::string& dir, const nlohmann::ordered_json& config,
|
||||
inline bool write_checkpoint(const std::string& dir, const Json& config,
|
||||
const std::vector<Tensor>& ts,
|
||||
const std::vector<std::string>& extra_specials = {}) {
|
||||
return write_text(dir + "/config.json", config.dump(2)) &&
|
||||
@@ -262,10 +264,10 @@ struct Qwen35 {
|
||||
|
||||
inline bool write_qwen35(const std::string& dir, const Qwen35& s) {
|
||||
Rng r(s.seed);
|
||||
nlohmann::ordered_json types = nlohmann::ordered_json::array();
|
||||
Json types = Json::array();
|
||||
for (int64_t l = 0; l < s.layers; ++l)
|
||||
types.push_back((l + 1) % s.interval == 0 ? "full_attention" : "linear_attention");
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "Qwen3_5ForConditionalGeneration" };
|
||||
c["model_type"] = "qwen3_5";
|
||||
c["vocab_size"] = s.vocab;
|
||||
@@ -344,9 +346,9 @@ struct Lfm2 {
|
||||
inline bool write_lfm2(const std::string& dir, const Lfm2& s) {
|
||||
Rng r(s.seed);
|
||||
const int64_t H = s.hidden, hd = s.hidden / s.heads, kv = s.kv_heads * hd;
|
||||
nlohmann::ordered_json types = nlohmann::ordered_json::array();
|
||||
Json types = Json::array();
|
||||
for (int64_t l = 0; l < s.layers; ++l) types.push_back(l % 2 ? "full_attention" : "conv");
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "Lfm2ForCausalLM" };
|
||||
c["model_type"] = "lfm2";
|
||||
c["vocab_size"] = s.vocab;
|
||||
@@ -414,10 +416,10 @@ struct Gemma4 {
|
||||
inline bool write_gemma4(const std::string& dir, const Gemma4& s) {
|
||||
Rng r(s.seed);
|
||||
const int64_t H = s.hidden;
|
||||
nlohmann::ordered_json types = nlohmann::ordered_json::array();
|
||||
Json types = Json::array();
|
||||
for (int64_t l = 0; l < s.layers; ++l)
|
||||
types.push_back((l + 1) % s.interval == 0 ? "full_attention" : "sliding_attention");
|
||||
nlohmann::ordered_json t;
|
||||
Json t;
|
||||
t["model_type"] = "gemma4_text";
|
||||
t["vocab_size"] = s.vocab;
|
||||
t["hidden_size"] = H;
|
||||
@@ -442,7 +444,7 @@ inline bool write_gemma4(const std::string& dir, const Gemma4& s) {
|
||||
{ "sliding_attention", { { "rope_type", "default" }, { "rope_theta", 10000.0 } } },
|
||||
{ "full_attention", { { "rope_type", "proportional" }, { "rope_theta", 1000000.0 },
|
||||
{ "partial_rotary_factor", 0.25 } } } };
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "Gemma4ForConditionalGeneration" };
|
||||
c["model_type"] = "gemma4";
|
||||
c["text_config"] = t;
|
||||
@@ -505,9 +507,9 @@ struct DFlash2 {
|
||||
inline bool write_dflash2(const std::string& dir, const DFlash2& s) {
|
||||
Rng r(s.seed);
|
||||
const int64_t H = s.hidden, q = s.heads * s.head_dim, kv = s.kv_heads * s.head_dim;
|
||||
nlohmann::ordered_json types = nlohmann::ordered_json::array();
|
||||
Json types = Json::array();
|
||||
for (int64_t l = 0; l < s.layers; ++l) types.push_back("sliding_attention");
|
||||
nlohmann::ordered_json t;
|
||||
Json t;
|
||||
t["attention_bias"] = false;
|
||||
t["head_dim"] = s.head_dim;
|
||||
t["hidden_act"] = "silu";
|
||||
@@ -524,18 +526,18 @@ inline bool write_dflash2(const std::string& dir, const DFlash2& s) {
|
||||
t["sliding_window"] = s.window;
|
||||
t["use_sliding_window"] = true;
|
||||
t["vocab_size"] = s.vocab;
|
||||
nlohmann::ordered_json greedy;
|
||||
Json greedy;
|
||||
greedy["proposal_type"] = "greedy";
|
||||
greedy["speculative_tokens"] = s.block - 1;
|
||||
nlohmann::ordered_json verifier;
|
||||
Json verifier;
|
||||
verifier["architectures"] = { "Gemma4ForConditionalGeneration" };
|
||||
verifier["name_or_path"] = "tiny";
|
||||
nlohmann::ordered_json spec;
|
||||
Json spec;
|
||||
spec["algorithm"] = "dflash2";
|
||||
spec["default_proposal_method"] = "greedy";
|
||||
spec["proposal_methods"] = nlohmann::ordered_json::array({ greedy });
|
||||
spec["proposal_methods"] = Json::array({ greedy });
|
||||
spec["verifier"] = verifier;
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "DFlash2DraftModel" };
|
||||
c["aux_hidden_state_layer_ids"] = s.taps;
|
||||
c["block_size"] = s.block;
|
||||
@@ -599,7 +601,7 @@ struct Llama {
|
||||
inline bool write_llama(const std::string& dir, const Llama& s) {
|
||||
Rng r(s.seed);
|
||||
const int64_t H = s.hidden, q = s.heads * s.head_dim, kv = s.kv_heads * s.head_dim;
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "LlamaForCausalLM" };
|
||||
c["model_type"] = "llama";
|
||||
c["vocab_size"] = s.vocab;
|
||||
@@ -692,7 +694,7 @@ inline bool write_llama_ct_int4(const std::string& dir, const Llama& s, bool asy
|
||||
out.push_back(std::move(sc));
|
||||
if (asym) out.push_back(std::move(zp));
|
||||
}
|
||||
nlohmann::ordered_json c = nlohmann::ordered_json::parse(read_text(dir + "/config.json"));
|
||||
Json c = Json::parse(read_text(dir + "/config.json"));
|
||||
c["quantization_config"] = {
|
||||
{ "quant_method", "compressed-tensors" }, { "format", "pack-quantized" },
|
||||
{ "config_groups",
|
||||
@@ -702,7 +704,7 @@ inline bool write_llama_ct_int4(const std::string& dir, const Llama& s, bool asy
|
||||
{ "weights",
|
||||
{ { "num_bits", 4 }, { "type", "int" }, { "symmetric", !asym },
|
||||
{ "strategy", "group" }, { "group_size", G }, { "dynamic", false },
|
||||
{ "actorder", asym ? nullptr : nlohmann::ordered_json("static") } } } } } } },
|
||||
{ "actorder", asym ? nullptr : Json("static") } } } } } } },
|
||||
{ "ignore", { "lm_head" } } };
|
||||
return write_text(dir + "/config.json", c.dump(2)) &&
|
||||
write_safetensors(dir + "/model.safetensors", out);
|
||||
@@ -734,7 +736,7 @@ inline bool write_qwen3asr(const std::string& dir, const Qwen3Asr& s) {
|
||||
const int64_t H = s.hidden, q = s.heads * s.head_dim, kv = s.kv_heads * s.head_dim;
|
||||
const int64_t A = s.a_dim, C = s.a_channels;
|
||||
const int64_t f3 = ((((s.mels + 1) / 2) + 1) / 2 + 1) / 2;
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["architectures"] = { "Qwen3ASRForConditionalGeneration" };
|
||||
c["model_type"] = "qwen3_asr";
|
||||
c["audio_token_id"] = (int)kAsrAudioPad;
|
||||
@@ -806,7 +808,7 @@ inline bool write_qwen3asr(const std::string& dir, const Qwen3Asr& s) {
|
||||
}
|
||||
ts.push_back(noise(m + "norm.weight", { H }, r, 0.1f, 1.0f));
|
||||
|
||||
nlohmann::ordered_json fe;
|
||||
Json fe;
|
||||
fe["feature_extractor"] = { { "feature_extractor_type", "Qwen3ASRFeatureExtractor" },
|
||||
{ "feature_size", s.mels }, { "hop_length", 160 },
|
||||
{ "n_fft", 400 }, { "sampling_rate", 16000 }, { "dither", 0.0 },
|
||||
@@ -832,7 +834,7 @@ inline bool write_lora(const std::string& dir, const std::string& base,
|
||||
if (ws.empty()) return false;
|
||||
const float scale = (float)(alpha / (double)r);
|
||||
std::vector<Tensor> ad;
|
||||
nlohmann::ordered_json leaves = nlohmann::ordered_json::array();
|
||||
Json leaves = Json::array();
|
||||
for (Tensor& w : ws) {
|
||||
const std::string sfx = ".weight";
|
||||
if (w.shape.size() != 2 || w.dtype != "BF16" || w.name.size() <= sfx.size() ||
|
||||
@@ -863,7 +865,7 @@ inline bool write_lora(const std::string& dir, const std::string& base,
|
||||
ad.push_back(std::move(B));
|
||||
}
|
||||
for (const std::string& t : targets) leaves.push_back(t);
|
||||
nlohmann::ordered_json c;
|
||||
Json c;
|
||||
c["peft_type"] = "LORA";
|
||||
c["base_model_name_or_path"] = base;
|
||||
c["r"] = r;
|
||||
@@ -884,21 +886,14 @@ inline bool write_lora(const std::string& dir, const std::string& base,
|
||||
write_safetensors(merged + "/model.safetensors", ws);
|
||||
}
|
||||
|
||||
/* The rad-convert recipe that makes llama_dense_fp8's linears block fp8, as
|
||||
* data/recipes/minicpm5-2b-dspark.recipe does for the trunk. */
|
||||
inline const char* kLlamaFp8Recipe =
|
||||
"blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n";
|
||||
|
||||
/* The same trunk as OCP-MXFP4: e2m1 codes with an E8M0 exponent per 32 of K, read by gemm_nt_q at
|
||||
* mxfp4a8 against the E4M3 activation pair scaled per 128. */
|
||||
inline const char* kLlamaMxfp4Recipe =
|
||||
"blk.*.attn_qkv.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n"
|
||||
"blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0\n";
|
||||
/* The rad-convert recipe that makes llama_dense_fp8's linears rotated int8 with a bf16 scale per
|
||||
* row and 128 of K (the 128-wide Hadamard domain), read by gemm_nt_q at i8a8h against int8
|
||||
* activations rotated the same way. */
|
||||
inline const char* kLlamaI8Recipe =
|
||||
"blk.*.attn_qkv.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"blk.*.ffn_down.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n";
|
||||
|
||||
/* ------------------------------------------------------------------ Qwen-Image 2.1 */
|
||||
|
||||
@@ -918,7 +913,7 @@ struct QwenImage {
|
||||
|
||||
inline bool write_qwen_image(const std::string& dir, const QwenImage& s) {
|
||||
Rng r(s.seed);
|
||||
using oj = nlohmann::ordered_json;
|
||||
using oj = Json;
|
||||
for (const char* sub : { "text_encoder", "transformer", "vae", "scheduler", "tokenizer" })
|
||||
if (mkdir((dir + "/" + sub).c_str(), 0755) != 0 && errno != EEXIST) return false;
|
||||
oj index;
|
||||
@@ -1091,21 +1086,19 @@ inline bool write_qwen_image(const std::string& dir, const QwenImage& s) {
|
||||
write_text(dir + "/tokenizer/tokenizer.json", tokenizer_json());
|
||||
}
|
||||
|
||||
/* The rad-convert recipe that makes the DiT's linears block fp8, as a shipped fp8 container holds
|
||||
* them; the plugin then takes the fp8 forms of its norms and attention scores. The text encoder's
|
||||
* 64-wide linears are no whole 128 x 128 block and stay bf16. */
|
||||
inline const char* kQwenImageFp8Recipe =
|
||||
"dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n"
|
||||
"dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n";
|
||||
/* The rad-convert recipe that makes the DiT's linears rotated int8 with a bf16 scale per row and
|
||||
* 128 of K, as a shipped int8 container holds them; the plugin then takes the int8 forms of its
|
||||
* norms and attention scores. The text encoder's 64-wide linears are no whole 128 of K and stay
|
||||
* bf16. */
|
||||
inline const char* kQwenImageI8Recipe =
|
||||
"dit.blk.*.attn_qkv.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"dit.blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"dit.blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n"
|
||||
"dit.blk.*.ffn_down.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym\n";
|
||||
|
||||
/* The lm head quantised as the shipped containers hold it, one rule each, after the trunk's:
|
||||
* block fp8 (the 27B family, data/recipes/q38-27b-fp8-df2.recipe) and int8 with a bf16 scale per
|
||||
* row and 128 of K (Flash-Next's, Gemma 4 31B's). Declared over all its planes, the head is joined
|
||||
* on the host (abi/rad_planes.h). */
|
||||
inline const char* kLlamaFp8HeadRule =
|
||||
"output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16\n";
|
||||
/* The lm head quantised as the shipped containers hold it, after the trunk's rules: int8 with a
|
||||
* bf16 scale per row and 128 of K (Flash-Next's, Gemma 4 31B's). Declared over all its planes, the
|
||||
* head is joined on the host (abi/rad_planes.h). */
|
||||
inline const char* kLlamaI8HeadRule =
|
||||
"output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym\n";
|
||||
|
||||
|
||||
+74
-2
@@ -1,5 +1,7 @@
|
||||
/* util_test.cpp -- core/util/rad_util.cpp, which every other translation unit links against, and
|
||||
* core/util/stallwatch.cpp, which reports where a phase that has gone quiet is waiting.
|
||||
/* util_test.cpp -- core/util/rad_util.cpp, which every other translation unit links against,
|
||||
* core/util/stallwatch.cpp, which reports where a phase that has gone quiet is waiting, and
|
||||
* core/util/rowpool.cpp, which spreads a loop's independent rows over threads kept for the
|
||||
* process.
|
||||
*
|
||||
* `Geometry` and `constraint_holds` decide which kernel runs. A geometry that hands a kernel
|
||||
* dangling parameter pointers, or a constraint that holds when it should not, does not fail: it
|
||||
@@ -11,8 +13,10 @@
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "util/rowpool.h"
|
||||
#include "util/stallwatch.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <barrier>
|
||||
#include <chrono>
|
||||
@@ -533,4 +537,72 @@ TEST(a_phase_that_marks_progress_is_never_reported) {
|
||||
CHECK(out.find("nothing has been logged") == std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== the row pool */
|
||||
|
||||
/* Each row runs exactly once, whatever the width, and the call returns only after all of them. */
|
||||
TEST(the_row_pool_runs_every_row_once) {
|
||||
for (int width : {1, 2, 8, 64}) {
|
||||
for (int64_t rows : {0, 1, 2, 7, 1000}) {
|
||||
std::vector<std::atomic<int>> hits((size_t)rows);
|
||||
row_pool_run(rows, width, [&](int64_t i) { hits[(size_t)i].fetch_add(1); });
|
||||
int bad = 0;
|
||||
for (auto& h : hits) bad += h.load() != 1;
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Under min_rows, or at width 1, the loop runs on the calling thread in order. */
|
||||
TEST(a_short_or_narrow_loop_runs_inline_in_order) {
|
||||
const std::thread::id self = std::this_thread::get_id();
|
||||
std::vector<int64_t> order;
|
||||
bool elsewhere = false;
|
||||
row_pool_run(31, 8, [&](int64_t i) {
|
||||
order.push_back(i);
|
||||
elsewhere = elsewhere || std::this_thread::get_id() != self;
|
||||
}, 32);
|
||||
CHECK(!elsewhere);
|
||||
CHECK_EQ((int64_t)order.size(), (int64_t)31);
|
||||
bool sorted = true;
|
||||
for (size_t i = 0; i < order.size(); ++i) sorted = sorted && order[i] == (int64_t)i;
|
||||
CHECK(sorted);
|
||||
order.clear();
|
||||
row_pool_run(100, 1, [&](int64_t i) { order.push_back(i); });
|
||||
CHECK_EQ((int64_t)order.size(), (int64_t)100);
|
||||
}
|
||||
|
||||
/* Callers on several threads at once each get all their rows, with workers shared between them,
|
||||
* and a slow row in one loop does not hold up another caller's. */
|
||||
TEST(concurrent_callers_share_the_row_pool) {
|
||||
if (row_pool_workers() == 0) return;
|
||||
constexpr int kCallers = 6;
|
||||
constexpr int64_t kRows = 4000;
|
||||
std::vector<std::vector<std::atomic<int>>> hits(kCallers);
|
||||
for (auto& h : hits) h = std::vector<std::atomic<int>>((size_t)kRows);
|
||||
std::vector<std::thread> ts;
|
||||
for (int c = 0; c < kCallers; ++c)
|
||||
ts.emplace_back([&, c] {
|
||||
for (int rep = 0; rep < 20; ++rep)
|
||||
row_pool_run(kRows / 20, 8, [&](int64_t i) {
|
||||
hits[(size_t)c][(size_t)(rep * (kRows / 20) + i)].fetch_add(1);
|
||||
});
|
||||
});
|
||||
for (auto& t : ts) t.join();
|
||||
int bad = 0;
|
||||
for (auto& h : hits)
|
||||
for (auto& x : h) bad += x.load() != 1;
|
||||
CHECK_EQ(bad, 0);
|
||||
|
||||
/* Rows spread over more than one thread when workers exist. */
|
||||
std::mutex mu;
|
||||
std::vector<std::thread::id> seen;
|
||||
row_pool_run(256, 8, [&](int64_t) {
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(200));
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
if (std::find(seen.begin(), seen.end(), std::this_thread::get_id()) == seen.end())
|
||||
seen.push_back(std::this_thread::get_id());
|
||||
});
|
||||
CHECK(seen.size() > 1);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -11,7 +11,9 @@
|
||||
#include "rad_test.h"
|
||||
#include "rad_vae_geom.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
using Json = rad::Json;
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
@@ -24,15 +26,15 @@ using namespace minimaxh3;
|
||||
|
||||
namespace {
|
||||
|
||||
nlohmann::json& golden() {
|
||||
static nlohmann::json g = [] {
|
||||
Json& golden() {
|
||||
static Json g = [] {
|
||||
std::ifstream f(std::string(RAD_VAE_GOLDEN) + "/golden.json");
|
||||
if (!f.is_open()) {
|
||||
fprintf(stderr, " FAIL golden.json missing -- regenerate with "
|
||||
"tests/data/vae_geom/gen_golden.py\n");
|
||||
std::exit(1);
|
||||
}
|
||||
return nlohmann::json::parse(f);
|
||||
return Json::parse(f);
|
||||
}();
|
||||
return g;
|
||||
}
|
||||
|
||||
+167
-3
@@ -13,7 +13,7 @@
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include "server/http.h"
|
||||
#include "server/json_partial.h"
|
||||
@@ -413,7 +413,7 @@ TEST(a_histogram_scraped_during_observations_stays_cumulative) {
|
||||
obs.emplace_back([&m, &stop, t] {
|
||||
const double v = 0.0001 * (t + 1); /* below every bucket's bound */
|
||||
while (!stop.load(std::memory_order_relaxed))
|
||||
m.observe_request(1, 2, v, v, v, v, 1, 8, SuccessReason::Stop);
|
||||
m.observe_request(1, 2, v, v, v, v, v, 1, 8, SuccessReason::Stop);
|
||||
});
|
||||
int bad = 0;
|
||||
for (int i = 0; i < 500 && bad == 0; ++i) bad += histogram_violations(m.render());
|
||||
@@ -423,6 +423,34 @@ TEST(a_histogram_scraped_during_observations_stays_cumulative) {
|
||||
CHECK_EQ(histogram_violations(m.render()), 0);
|
||||
}
|
||||
|
||||
/* The queue time, the prefix cache as counters and the cache settings, under vLLM's names. A
|
||||
* request that was never admitted leaves the queue histogram alone, and the hits are the tokens
|
||||
* requests did not compute again. */
|
||||
TEST(queue_time_and_prefix_cache_counters_render_under_vllm_names) {
|
||||
Metrics m("m", 1024);
|
||||
m.set_cache_config("fp8", 16, true, 4096);
|
||||
m.observe_request(10, 2, 0.5, 0.01, 1.0, 0.5, 0.25, 1, 8, SuccessReason::Stop);
|
||||
m.observe_request(10, 0, -1.0, -1.0, 0.1, -1.0, -1.0, 1, 8, SuccessReason::Abort);
|
||||
SchedMetrics sm;
|
||||
sm.prefix_queries = 100;
|
||||
sm.linear_cached_tokens = 60;
|
||||
m.sample(sm);
|
||||
const std::string out = m.render();
|
||||
const std::string L = "{model_name=\"m\",engine=\"0\"} ";
|
||||
CHECK(out.find("vllm:prefix_cache_queries_total" + L + "100\n") != std::string::npos);
|
||||
CHECK(out.find("vllm:prefix_cache_hits_total" + L + "60\n") != std::string::npos);
|
||||
CHECK(out.find("vllm:request_queue_time_seconds_count" + L + "1\n") != std::string::npos);
|
||||
CHECK(out.find("vllm:request_queue_time_seconds_sum" + L + "0.25\n") != std::string::npos);
|
||||
CHECK(out.find("vllm:cache_config_info{model_name=\"m\",engine=\"0\",cache_dtype=\"fp8\","
|
||||
"block_size=\"16\",enable_prefix_caching=\"True\",prefix_cache_mib=\"4096\"} 1\n")
|
||||
!= std::string::npos);
|
||||
CHECK_EQ(histogram_violations(out), 0);
|
||||
|
||||
/* Not set: no info line. */
|
||||
Metrics bare("m", 1024);
|
||||
CHECK(bare.render().find("vllm:cache_config_info") == std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== the response bodies
|
||||
*
|
||||
* The routes cover content end to end; these cases check shape. Client libraries deserialise into
|
||||
@@ -559,14 +587,17 @@ TEST(a_chat_body_with_a_tool_call_sends_a_null_content) {
|
||||
const json p = parsed(chat_completion_body(a_request("chatcmpl-3", "m"), { both }, UsageOut{}));
|
||||
CHECK_EQ(p["choices"][0]["message"].value("content", std::string()), std::string("checking"));
|
||||
|
||||
/* Reasoning goes under vLLM's key, and only when non-empty. */
|
||||
/* Reasoning goes under both spellings, and under neither when empty. */
|
||||
CHECK(!p["choices"][0]["message"].contains("reasoning_content"));
|
||||
CHECK(!p["choices"][0]["message"].contains("reasoning"));
|
||||
ChoiceOut think;
|
||||
think.msg.reasoning = "the user wants weather";
|
||||
think.msg.content = "it is cold";
|
||||
const json q = parsed(chat_completion_body(a_request("chatcmpl-4", "m"), { think }, UsageOut{}));
|
||||
CHECK_EQ(q["choices"][0]["message"].value("reasoning_content", std::string()),
|
||||
std::string("the user wants weather"));
|
||||
CHECK_EQ(q["choices"][0]["message"].value("reasoning", std::string()),
|
||||
std::string("the user wants weather"));
|
||||
}
|
||||
|
||||
TEST(a_text_completion_body_is_the_other_shape_entirely) {
|
||||
@@ -641,6 +672,20 @@ TEST(the_completion_usage_chunk_is_an_event_with_an_empty_choices_array) {
|
||||
CHECK_EQ(o.value("id", std::string()), std::string("cmpl-9"));
|
||||
}
|
||||
|
||||
/* An embedding value is spelled with the shortest digits that read back as the float: the
|
||||
* engine's float32, not the extra digits widening it to a double would add. */
|
||||
TEST(an_embeddings_value_is_spelled_as_its_float) {
|
||||
const std::vector<std::vector<float>> vecs = { { 0.1f, 1.0f, -2.5e-7f, 3.4028235e38f, -0.0f,
|
||||
0.0123f } };
|
||||
UsageOut u;
|
||||
const std::string body = embeddings_body(a_request("emb-3", "m"), vecs, u);
|
||||
CHECK(body.find("\"embedding\":[0.1,1.0,-2.5e-07,3.4028235e+38,-0.0,0.0123]") !=
|
||||
std::string::npos);
|
||||
const json o = parsed(body);
|
||||
for (size_t j = 0; j < vecs[0].size(); ++j)
|
||||
CHECK_EQ(o["data"][0]["embedding"][j].get<float>(), vecs[0][j]);
|
||||
}
|
||||
|
||||
/* Base64 encoding is per request and is the raw float buffer, which every client that asks for it
|
||||
* unpacks. Sending the JSON array under that flag, or base64 of a formatted array, would
|
||||
* deserialise to nonsense instead of failing. */
|
||||
@@ -680,4 +725,123 @@ TEST(an_embeddings_body_honours_the_encoding_the_request_asked_for) {
|
||||
CHECK_EQ(z["data"].size(), 0u);
|
||||
}
|
||||
|
||||
/* ================================================================== the body reader
|
||||
*
|
||||
* parse_json_bounded is the DOM's bounded read (util/json.cpp). Its verdicts and typing are
|
||||
* the recorded contract the request parser has always been written against: a non-negative
|
||||
* integer reads as unsigned, an integer past uint64 as a double, and the value-budget and
|
||||
* depth boundaries refuse the same bodies. These cases are what a yyjson refresh is re-run
|
||||
* against (vendor/UPSTREAM). */
|
||||
|
||||
TEST(the_bounded_body_reader_agrees_with_the_reference_reader) {
|
||||
const char* cases[] = {
|
||||
"{\"a\":1e-999}", "{\"a\":1e-400}", "{\"a\":0e999}", "{\"a\":1e309}", "{\"a\":-1e309}",
|
||||
"{\"a\":1.7976931348623157e308}", "{\"a\":1.7976931348623159e308}",
|
||||
"{\"a\":2.2250738585072011e-308}", "{\"a\":5e-324}", "{\"a\":4e-324}",
|
||||
"{\"a\":0.1}", "{\"a\":123456789012345678901234567890}",
|
||||
"{\"a\":9223372036854775807}", "{\"a\":9223372036854775808}",
|
||||
"{\"a\":-9223372036854775808}", "{\"a\":-9223372036854775809}",
|
||||
"{\"a\":18446744073709551615}", "{\"a\":18446744073709551616}",
|
||||
"{\"a\":-0}", "{\"a\":-0.0}", "{\"a\":0.0}", "{\"a\":1E7}", "{\"a\":1e+7}",
|
||||
"{\"a\":0x10}", "{\"a\":.5}", "{\"a\":1.}", "{\"a\":1e}", "{\"a\":01}", "{\"a\":+1}",
|
||||
"{\"a\":NaN}", "{\"a\":Infinity}",
|
||||
"{\"a\":\"\\u0000\"}", "{\"a\":\"\\ud83d\\ude00\"}", "{\"a\":\"\\ude00\"}",
|
||||
"{\"a\":\"\\ud800\"}", "{\"a\":\"\\/\"}", "{\"a\":\"\\x\"}", "{\"a\":\"\\u12g4\"}",
|
||||
"{\"a\":\"caf\\u00e9\"}", "{\"a\":\"\x7f\"}", "{\"a\":\"\"}",
|
||||
"{\"a\":1,\"b\":0,\"a\":2,\"b\":3}", "{\"\\u0061\":1}",
|
||||
"[]", "{}", "null", "true", "42", "-17", "\"hi\"", " {\"a\":1} ",
|
||||
"[1,2,]", "{,}", "{\"a\"}", "{\"a\":}", "[}", "nul", "{\"a\":\"unterminated}",
|
||||
"", " ", "{\"a\":1} x", "{\"a\":1} {\"b\":2}",
|
||||
};
|
||||
for (const char* c : cases) {
|
||||
const std::string s = c;
|
||||
bool over = false, deep = false;
|
||||
const json got = parse_json_bounded(s, 1 << 20, &over, &deep);
|
||||
const json want = json::parse(s, nullptr, false);
|
||||
CHECK_EQ(got.is_discarded(), want.is_discarded());
|
||||
CHECK(!over && !deep);
|
||||
if (!want.is_discarded()) {
|
||||
CHECK_EQ(got.dump(), want.dump());
|
||||
CHECK_EQ(got.type(), want.type());
|
||||
}
|
||||
}
|
||||
/* A BOM is skipped, as the reference reader skips it; invalid UTF-8 and a CESU-8
|
||||
* surrogate are refused. */
|
||||
{
|
||||
bool over = false, deep = false;
|
||||
const json j = parse_json_bounded(std::string("\xef\xbb\xbf") + "{\"a\":1}", 0, &over, &deep);
|
||||
CHECK(!j.is_discarded());
|
||||
CHECK_EQ(j["a"].get<uint64_t>(), 1u);
|
||||
CHECK(parse_json_bounded("{\"a\":\"\xff\"}", 0, &over, &deep).is_discarded());
|
||||
CHECK(parse_json_bounded("{\"a\":\"\xc3\x28\"}", 0, &over, &deep).is_discarded());
|
||||
CHECK(parse_json_bounded("{\"a\":\"\xed\xa0\x80\"}", 0, &over, &deep).is_discarded());
|
||||
CHECK(!parse_json_bounded("{\"a\":\"\xc3\xa9\"}", 0, &over, &deep).is_discarded());
|
||||
}
|
||||
/* Number typing is pinned, because the request parser's checks read it. */
|
||||
{
|
||||
bool over = false, deep = false;
|
||||
const json j = parse_json_bounded(
|
||||
"{\"u\":5,\"n\":-5,\"big\":9223372036854775808,\"huge\":18446744073709551616}",
|
||||
0, &over, &deep);
|
||||
CHECK(j["u"].is_number_unsigned());
|
||||
CHECK(!j["n"].is_number_unsigned() && j["n"].is_number_integer());
|
||||
CHECK(j["big"].is_number_unsigned());
|
||||
CHECK(j["huge"].is_number_float());
|
||||
/* Duplicate keys: the last value at the first key's position. */
|
||||
const json d = parse_json_bounded("{\"a\":1,\"b\":0,\"a\":2}", 0, &over, &deep);
|
||||
CHECK_EQ(d.dump(), std::string("{\"a\":2,\"b\":0}"));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_bounded_body_reader_keeps_the_value_and_depth_boundaries) {
|
||||
auto ask = [](const std::string& s, bool* over, bool* deep, int64_t ctx = 0) {
|
||||
*over = *deep = false;
|
||||
return parse_json_bounded(s, ctx, over, deep);
|
||||
};
|
||||
auto nested = [](int n, bool scalar) {
|
||||
std::string s((size_t)n, '[');
|
||||
if (scalar) s += '1';
|
||||
return s + std::string((size_t)n, ']');
|
||||
};
|
||||
bool over, deep;
|
||||
/* A value nested kJsonMaxDepth below the root is the deepest accepted. The innermost
|
||||
* empty container sits one level above its would-be elements, hence the off-by-one
|
||||
* between the scalar and empty shapes: both are the reference reader's boundaries. */
|
||||
ask(nested(kJsonMaxDepth, true), &over, &deep);
|
||||
CHECK(!deep && !over);
|
||||
ask(nested(kJsonMaxDepth + 1, true), &over, &deep);
|
||||
CHECK(deep && !over);
|
||||
ask(nested(kJsonMaxDepth + 1, false), &over, &deep);
|
||||
CHECK(!deep && !over);
|
||||
ask(nested(kJsonMaxDepth + 2, false), &over, &deep);
|
||||
CHECK(deep && !over);
|
||||
|
||||
/* Every value counts once -- containers included, keys excluded. The budget at ctx 0 is
|
||||
* the floor. One repeated key in the object shape: a million distinct keys would pay
|
||||
* the ordered map's quadratic insert for no extra information. */
|
||||
const int64_t budget = json_value_budget(0);
|
||||
auto flat = [](int64_t n, bool object) {
|
||||
std::string s = object ? "{" : "[";
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
if (i) s += ',';
|
||||
s += object ? "\"k\":1" : "1";
|
||||
}
|
||||
return s + (object ? '}' : ']');
|
||||
};
|
||||
ask(flat(budget - 1, false), &over, &deep); /* root + elements == budget */
|
||||
CHECK(!over && !deep);
|
||||
ask(flat(budget, false), &over, &deep);
|
||||
CHECK(over && !deep);
|
||||
ask(flat(budget - 1, true), &over, &deep);
|
||||
CHECK(!over && !deep);
|
||||
ask(flat(budget, true), &over, &deep);
|
||||
CHECK(over && !deep);
|
||||
|
||||
/* An over-deep or over-budget body still returns a usable (null) value rather than a
|
||||
* discarded one, matching the reference reader: a caller tests discarded for "not JSON"
|
||||
* before it tests the flags. */
|
||||
CHECK(!ask(nested(kJsonMaxDepth + 5, true), &over, &deep).is_discarded());
|
||||
CHECK(deep);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
#include "place/xstats.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <dirent.h>
|
||||
#include <unistd.h>
|
||||
@@ -230,7 +230,7 @@ TEST(the_file_is_json_written_at_boot_and_replaced_through_a_rename) {
|
||||
ExpertStats xs;
|
||||
CHECK_OK(xs.init(path, m, info, 0.05));
|
||||
|
||||
nlohmann::json j = nlohmann::json::parse(slurp(path), nullptr, false);
|
||||
Json j = Json::parse(slurp(path), nullptr, false);
|
||||
REQUIRE(!j.is_discarded());
|
||||
CHECK_EQ(j["format"].get<std::string>(), std::string("radiance-expert-stats/1"));
|
||||
CHECK_EQ(j["model"].get<std::string>(), info.model);
|
||||
@@ -246,16 +246,16 @@ TEST(the_file_is_json_written_at_boot_and_replaced_through_a_rename) {
|
||||
xs.start();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
xs.stop();
|
||||
j = nlohmann::json::parse(slurp(path), nullptr, false);
|
||||
j = Json::parse(slurp(path), nullptr, false);
|
||||
REQUIRE(!j.is_discarded());
|
||||
CHECK(j["counts"]["decode"][0] == nlohmann::json({ 0, 1, 1, 0 }));
|
||||
CHECK(j["counts"]["decode"][0] == Json({ 0, 1, 1, 0 }));
|
||||
CHECK_EQ(j["selections"]["decode"][0].get<uint64_t>(), (uint64_t)2);
|
||||
CHECK_EQ(j["observed_tokens"]["decode"][0].get<uint64_t>(), (uint64_t)1);
|
||||
CHECK_EQ(j["tokens"]["decode"].get<uint64_t>(), (uint64_t)1);
|
||||
CHECK(j["uptime_s"].get<double>() > 0.0);
|
||||
|
||||
CHECK_OK(xs.write(true));
|
||||
j = nlohmann::json::parse(slurp(path), nullptr, false);
|
||||
j = Json::parse(slurp(path), nullptr, false);
|
||||
REQUIRE(!j.is_discarded());
|
||||
CHECK_EQ(j["final"].get<bool>(), true);
|
||||
|
||||
|
||||
Reference in new issue
Block a user