Archived
Merge upstream main (v1.15.1 -> v1.17.0, 152 commits) into the SYCL port
Conflicts, both sides kept:
- abi: RAD_ABI_VERSION 37 (upstream); the fork's RadBuildCtx.plain_norm after upstream's
expert_file_tier, widened to int64_t so it starts past ABI 37's 208-byte struct instead of in
its tail padding (abi_layout_test); RadSyclStream rows after RadShapeGen*.
- arch/common/rad_block_gdn_fp8.h: upstream's q8_rot guard and the fork's o_plain guard
combined; the decode-row q_o.step only where q_o is declared (!o_plain).
- docs/OPS.md: upstream's optional params on sample_logprobs, the fork's q_temp on
mtp_couple_propose.
Also ignores /baseline-models/ (local model copies).
Host tests: arch_test's MTP lint/graph-pin failures are unchanged from before the merge (the
fork's mtp.fc LinearFP8, 10a99a5); avx_check's hand-built moe_gemm_q w4a8 case also fails on
upstream's own files; images/videos need FFmpeg; three binaries over their CPU budget on this VM.
SYCL card tests 3/3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
45f3b510c7
365 files changed
+56942
-6331
No files matched your search
+59
-27
@@ -10,12 +10,12 @@
|
||||
# fast every test with none of slow, gpu, oot and perf, set at the end of this file: the
|
||||
# inner loop (`ctest --preset fast`, or `ctest -L fast`)
|
||||
#
|
||||
# arch_test and glm5next_test do not link rad_core: they supply their own recording fake of the
|
||||
# declare-phase C ABI (arch_fakes.h), so plugins are tested without depending on core/build/'s
|
||||
# builder. With the archive linked, a new ABI call missing from the fake would pull in
|
||||
# rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a single
|
||||
# undefined reference.
|
||||
set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test)
|
||||
# arch_test, glm5next_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply
|
||||
# their own recording fake of the declare-phase C ABI (arch_fakes.h), so plugins are tested without
|
||||
# depending on core/build/'s builder. With the archive linked, a new ABI call missing from the fake
|
||||
# would pull in rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a
|
||||
# single undefined reference.
|
||||
set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test spark25_arch_test nemotronh_test)
|
||||
|
||||
# fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and
|
||||
# the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and
|
||||
@@ -166,6 +166,9 @@ string(APPEND RAD_PERF_SCRIPT "include([==[${CMAKE_CURRENT_SOURCE_DIR}/perf_entr
|
||||
set(RAD_TESTS_WHOLE_CORE shipped_plugins_test)
|
||||
|
||||
file(GLOB RAD_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*_test.cpp)
|
||||
if(NOT RAD_HIP_FOUND)
|
||||
list(FILTER RAD_TESTS EXCLUDE REGEX "/dspark_device_test\\.cpp$")
|
||||
endif()
|
||||
foreach(t ${RAD_TESTS})
|
||||
get_filename_component(n ${t} NAME_WE)
|
||||
if(n IN_LIST RAD_TESTS_NO_CORE)
|
||||
@@ -263,16 +266,28 @@ foreach(t ${RAD_TESTS})
|
||||
if(n STREQUAL "mem_test")
|
||||
set_target_properties(${n} PROPERTIES ENABLE_EXPORTS ON)
|
||||
endif()
|
||||
if(DEFINED RAD_TEST_SHARDS_${n})
|
||||
math(EXPR last "${RAD_TEST_SHARDS_${n}} - 1")
|
||||
foreach(k RANGE ${last})
|
||||
rad_unit_test(${n}_shard${k} ${n} --shard ${k}/${RAD_TEST_SHARDS_${n}})
|
||||
endforeach()
|
||||
if(n STREQUAL "dspark_device_test")
|
||||
if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
add_dependencies(${n} libr4d)
|
||||
add_test(NAME ${n} COMMAND ${n} ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
|
||||
set_tests_properties(${n} PROPERTIES
|
||||
LABELS gpu
|
||||
SKIP_RETURN_CODE 77
|
||||
TIMEOUT ${RAD_TEST_TIMEOUT}
|
||||
ENVIRONMENT "${RAD_TEST_CARD_ENV}")
|
||||
endif()
|
||||
else()
|
||||
rad_unit_test(${n} ${n})
|
||||
if(DEFINED RAD_TEST_SHARDS_${n})
|
||||
math(EXPR last "${RAD_TEST_SHARDS_${n}} - 1")
|
||||
foreach(k RANGE ${last})
|
||||
rad_unit_test(${n}_shard${k} ${n} --shard ${k}/${RAD_TEST_SHARDS_${n}})
|
||||
endforeach()
|
||||
else()
|
||||
rad_unit_test(${n} ${n})
|
||||
endif()
|
||||
string(APPEND RAD_PERF_SCRIPT
|
||||
"rad_perf_entry(${n} [==[${t}]==] [==[${CMAKE_BINARY_DIR}/tests/${n}]==])\n")
|
||||
endif()
|
||||
string(APPEND RAD_PERF_SCRIPT
|
||||
"rad_perf_entry(${n} [==[${t}]==] [==[${CMAKE_BINARY_DIR}/tests/${n}]==])\n")
|
||||
endforeach()
|
||||
|
||||
# ================================================================== perf_ cases
|
||||
@@ -333,6 +348,11 @@ if(TARGET spechub)
|
||||
add_dependencies(sample_test spechub)
|
||||
endif()
|
||||
|
||||
if(TARGET spark25_recipe_test)
|
||||
target_compile_definitions(spark25_recipe_test PRIVATE
|
||||
RAD_SPARK25_RECIPE_DIR="${CMAKE_SOURCE_DIR}/data/recipes")
|
||||
endif()
|
||||
|
||||
# ================================================================== whole models on the CPU
|
||||
#
|
||||
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
|
||||
@@ -344,12 +364,14 @@ set(RAD_E2E_DEPS radiance rad-convert libref libquant nemotron35_embed qwen35_bf
|
||||
if(TARGET libavx)
|
||||
list(APPEND RAD_E2E_DEPS libavx)
|
||||
endif()
|
||||
foreach(t engine_e2e_test convert_test clef_decision_test laya_decision_test)
|
||||
foreach(t engine_e2e_test convert_test clef_decision_test laya_decision_test spark25_convert_test)
|
||||
if(TARGET ${t})
|
||||
target_compile_definitions(${t} PRIVATE
|
||||
RAD_E2E_SERVER="$<TARGET_FILE:radiance>" RAD_E2E_CONVERT="$<TARGET_FILE:rad-convert>"
|
||||
RAD_E2E_HOME="${RAD_PLUGIN_OUT}" RAD_E2E_RECIPES="${CMAKE_SOURCE_DIR}/data/recipes")
|
||||
if(t STREQUAL "clef_decision_test")
|
||||
if(t STREQUAL "spark25_convert_test")
|
||||
add_dependencies(${t} rad-convert libref spark25_bf16)
|
||||
elseif(t STREQUAL "clef_decision_test")
|
||||
# The tiny clef's golden (tests/mkclefgolden.py) and the one plugin a clef container selects.
|
||||
target_compile_definitions(${t} PRIVATE
|
||||
RAD_CLEF_GOLDEN="${CMAKE_CURRENT_SOURCE_DIR}/data/golden/clef_tiny.json")
|
||||
@@ -384,10 +406,10 @@ if(TARGET abi_layout_test)
|
||||
COMPILE_OPTIONS "-std=c11;-pedantic-errors;-Wall;-Wextra")
|
||||
endif()
|
||||
|
||||
# arch_test reads libref's vocabulary from $RADIANCE_HOME/kernels to check that each architecture
|
||||
# declares on it, and glm5next_test the loaded libraries' op schemas, so libref is built before
|
||||
# them.
|
||||
foreach(t arch_test glm5next_test)
|
||||
# arch_test and nemotronh_test read libref's vocabulary from $RADIANCE_HOME/kernels to check that
|
||||
# each architecture declares on it, and glm5next_test the loaded libraries' op schemas, so libref is
|
||||
# built before them.
|
||||
foreach(t arch_test glm5next_test nemotronh_test)
|
||||
if(TARGET libref AND TARGET ${t})
|
||||
add_dependencies(${t} libref)
|
||||
endif()
|
||||
@@ -430,11 +452,13 @@ endif()
|
||||
#
|
||||
# libhalo serves gfx1151 behind libr4d's exact interface (libhalo/halo_parity.cpp): the same op
|
||||
# schemas and rows, so every model plugin runs on either. Host-only (the tables, no device calls);
|
||||
# present when one build produces both plugins.
|
||||
# present when one build produces both plugins. Labelled `parity`: it fails while libr4d has ops
|
||||
# libhalo has not ported yet (every one printed as "only in libr4d"), which the image's test stage
|
||||
# leaves out; a schema both declare must still agree, or the loader refuses the second library.
|
||||
if(TARGET halo_parity)
|
||||
add_test(NAME halo_parity
|
||||
COMMAND halo_parity ${RAD_PLUGIN_OUT}/kernels/libr4d.so ${RAD_PLUGIN_OUT}/kernels/libhalo.so)
|
||||
set_tests_properties(halo_parity PROPERTIES LABELS "fast" TIMEOUT 60)
|
||||
set_tests_properties(halo_parity PROPERTIES LABELS "fast;parity" TIMEOUT 60)
|
||||
endif()
|
||||
|
||||
# ================================================================== the device layer without SVM
|
||||
@@ -535,11 +559,12 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
|
||||
${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_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_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)
|
||||
dsa m2xfp4 lili)
|
||||
set(R4D_EMU_BUILT OFF)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# No fiber switch for this ISA.
|
||||
@@ -580,7 +605,8 @@ else()
|
||||
${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_moefuse.cpp ${R4D_EMU}/test_kvres.cpp
|
||||
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp ${R4D_EMU}/cfg_stub.cpp)
|
||||
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp ${R4D_EMU}/test_lili.cpp
|
||||
${R4D_EMU}/cfg_stub.cpp)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -617,7 +643,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)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa m2xfp4 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,
|
||||
@@ -628,7 +654,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_dsa r4d_emu_m2xfp4 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
|
||||
@@ -810,6 +836,12 @@ find_program(RAD_PYTHON3 NAMES python3)
|
||||
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})
|
||||
add_test(NAME spark25_validation_test
|
||||
COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/spark25_validation_test.py)
|
||||
set_tests_properties(spark25_validation_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
|
||||
add_test(NAME dspark_qos_regression_test
|
||||
COMMAND ${RAD_PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/dspark_qos_regression_test.py)
|
||||
set_tests_properties(dspark_qos_regression_test PROPERTIES LABELS "unit;fast" TIMEOUT ${RAD_TEST_TIMEOUT})
|
||||
endif()
|
||||
|
||||
# ================================================================== the shipped plugins, out of tree
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 32 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 37 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. */
|
||||
{ "RadArchProbe", "", 0, 120 },
|
||||
{ "RadArchProbe", "", 0, 128 },
|
||||
{ "RadArchProbe", "draft_depth", 0, 4 },
|
||||
{ "RadArchProbe", "draft_depth_fixed", 4, 4 },
|
||||
{ "RadArchProbe", "shape_probe_ok", 8, 4 },
|
||||
@@ -22,7 +22,8 @@
|
||||
{ "RadArchProbe", "tree_pays", 96, 8 },
|
||||
{ "RadArchProbe", "gen_max_pixels", 104, 8 },
|
||||
{ "RadArchProbe", "gen_max_refs", 112, 8 },
|
||||
{ "RadArgs", "", 0, 64 },
|
||||
{ "RadArchProbe", "gen_shape", 120, 4 },
|
||||
{ "RadArgs", "", 0, 72 },
|
||||
{ "RadArgs", "t", 0, 8 },
|
||||
{ "RadArgs", "n_t", 8, 4 },
|
||||
{ "RadArgs", "p", 16, 8 },
|
||||
@@ -32,7 +33,9 @@
|
||||
{ "RadArgs", "instance", 48, 8 },
|
||||
{ "RadArgs", "rank", 56, 4 },
|
||||
{ "RadArgs", "world_size", 60, 4 },
|
||||
{ "RadBatch", "", 0, 408 },
|
||||
{ "RadArgs", "kv_used_max_h", 64, 4 },
|
||||
{ "RadArgs", "wgp_count", 68, 4 },
|
||||
{ "RadBatch", "", 0, 480 },
|
||||
{ "RadBatch", "phase", 0, 4 },
|
||||
{ "RadBatch", "step", 4, 4 },
|
||||
{ "RadBatch", "n_tok", 8, 8 },
|
||||
@@ -89,6 +92,15 @@
|
||||
{ "RadBatch", "plugin_cu", 384, 8 },
|
||||
{ "RadBatch", "plugin_words_h", 392, 8 },
|
||||
{ "RadBatch", "plugin_cu_h", 400, 8 },
|
||||
{ "RadBatch", "sgen_b", 408, 8 },
|
||||
{ "RadBatch", "kv_used_max_h", 416, 8 },
|
||||
{ "RadBatch", "positions_h", 424, 8 },
|
||||
{ "RadBatch", "n_bidi", 432, 8 },
|
||||
{ "RadBatch", "bidi_row", 440, 8 },
|
||||
{ "RadBatch", "bidi_n", 448, 8 },
|
||||
{ "RadBatch", "bidi_seq", 456, 8 },
|
||||
{ "RadBatch", "bidi_used", 464, 8 },
|
||||
{ "RadBatch", "anchor_rows", 472, 8 },
|
||||
{ "RadBufDecl", "", 0, 80 },
|
||||
{ "RadBufDecl", "dtype", 0, 4 },
|
||||
{ "RadBufDecl", "rank", 4, 4 },
|
||||
@@ -97,7 +109,7 @@
|
||||
{ "RadBufDecl", "domain", 60, 4 },
|
||||
{ "RadBufDecl", "derive", 64, 8 },
|
||||
{ "RadBufDecl", "kv", 72, 4 },
|
||||
{ "RadBuildCtx", "", 0, 200 },
|
||||
{ "RadBuildCtx", "", 0, 208 },
|
||||
{ "RadBuildCtx", "rank", 0, 4 },
|
||||
{ "RadBuildCtx", "world_size", 4, 4 },
|
||||
{ "RadBuildCtx", "max_tok", 8, 8 },
|
||||
@@ -130,6 +142,7 @@
|
||||
{ "RadBuildCtx", "calib_tokens", 176, 8 },
|
||||
{ "RadBuildCtx", "gen_max_pixels", 184, 8 },
|
||||
{ "RadBuildCtx", "gen_max_refs", 192, 8 },
|
||||
{ "RadBuildCtx", "expert_file_tier", 200, 4 },
|
||||
{ "RadAudioGenBatch", "", 0, 344 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
@@ -485,7 +498,7 @@
|
||||
{ "RadGeneratorDecl", "chunk_bos", 364, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_eos", 368, 4 },
|
||||
{ "RadGeneratorDecl", "cond_opts", 372, 4 },
|
||||
{ "RadKVGroupBatch", "", 0, 80 },
|
||||
{ "RadKVGroupBatch", "", 0, 88 },
|
||||
{ "RadKVGroupBatch", "group", 0, 4 },
|
||||
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
|
||||
{ "RadKVGroupBatch", "block_table", 16, 8 },
|
||||
@@ -496,6 +509,7 @@
|
||||
{ "RadKVGroupBatch", "block_size", 56, 8 },
|
||||
{ "RadKVGroupBatch", "max_blocks", 64, 8 },
|
||||
{ "RadKVGroupBatch", "stream", 72, 8 },
|
||||
{ "RadKVGroupBatch", "seqused_h", 80, 8 },
|
||||
{ "RadKVGroupDecl", "", 0, 56 },
|
||||
{ "RadKVGroupDecl", "kind", 0, 4 },
|
||||
{ "RadKVGroupDecl", "dtype", 4, 4 },
|
||||
@@ -514,7 +528,7 @@
|
||||
{ "RadKVStream", "host_layer_stride", 48, 8 },
|
||||
{ "RadKVStream", "slots", 56, 8 },
|
||||
{ "RadKVStream", "host_bytes", 64, 8 },
|
||||
{ "RadKernelInfo", "", 0, 168 },
|
||||
{ "RadKernelInfo", "", 0, 176 },
|
||||
{ "RadKernelInfo", "name", 0, 8 },
|
||||
{ "RadKernelInfo", "op", 8, 8 },
|
||||
{ "RadKernelInfo", "family", 16, 8 },
|
||||
@@ -537,6 +551,7 @@
|
||||
{ "RadKernelInfo", "opd_shape", 144, 8 },
|
||||
{ "RadKernelInfo", "unrelayout", 152, 8 },
|
||||
{ "RadKernelInfo", "replaces", 160, 8 },
|
||||
{ "RadKernelInfo", "capabilities", 168, 8 },
|
||||
{ "RadLayout", "", 0, 80 },
|
||||
{ "RadLayout", "tag", 0, 8 },
|
||||
{ "RadLayout", "dtype", 8, 4 },
|
||||
@@ -695,6 +710,44 @@
|
||||
{ "RadSampleParams", "mask_row", 84, 4 },
|
||||
{ "RadSampleParams", "flags", 88, 4 },
|
||||
{ "RadSampleParams", "dry_rep_limit", 92, 4 },
|
||||
{ "RadShapeGenBatch", "", 0, 112 },
|
||||
{ "RadShapeGenBatch", "lane", 0, 4 },
|
||||
{ "RadShapeGenBatch", "patches", 8, 8 },
|
||||
{ "RadShapeGenBatch", "step", 16, 4 },
|
||||
{ "RadShapeGenBatch", "n_steps", 20, 4 },
|
||||
{ "RadShapeGenBatch", "sigma", 24, 8 },
|
||||
{ "RadShapeGenBatch", "sigma_next", 32, 8 },
|
||||
{ "RadShapeGenBatch", "cfg", 40, 8 },
|
||||
{ "RadShapeGenBatch", "pair", 48, 8 },
|
||||
{ "RadShapeGenBatch", "lanes", 56, 8 },
|
||||
{ "RadShapeGenBatch", "flags", 64, 8 },
|
||||
{ "RadShapeGenBatch", "seed", 72, 8 },
|
||||
{ "RadShapeGenBatch", "lat_cu", 80, 8 },
|
||||
{ "RadShapeGenBatch", "n_query", 88, 8 },
|
||||
{ "RadShapeGenBatch", "query", 96, 8 },
|
||||
{ "RadShapeGenBatch", "query_cu", 104, 8 },
|
||||
{ "RadShapeGenDecl", "", 0, 200 },
|
||||
{ "RadShapeGenDecl", "name", 0, 8 },
|
||||
{ "RadShapeGenDecl", "canvas", 8, 8 },
|
||||
{ "RadShapeGenDecl", "border_ratio", 16, 8 },
|
||||
{ "RadShapeGenDecl", "enc_size", 24, 8 },
|
||||
{ "RadShapeGenDecl", "enc_patch", 32, 8 },
|
||||
{ "RadShapeGenDecl", "pix_mean", 40, 24 },
|
||||
{ "RadShapeGenDecl", "pix_std", 64, 24 },
|
||||
{ "RadShapeGenDecl", "latent_rows", 88, 8 },
|
||||
{ "RadShapeGenDecl", "latent_channels", 96, 8 },
|
||||
{ "RadShapeGenDecl", "step_rows", 104, 8 },
|
||||
{ "RadShapeGenDecl", "default_steps", 112, 8 },
|
||||
{ "RadShapeGenDecl", "max_steps", 120, 8 },
|
||||
{ "RadShapeGenDecl", "default_guidance", 128, 8 },
|
||||
{ "RadShapeGenDecl", "bounds", 136, 8 },
|
||||
{ "RadShapeGenDecl", "level", 144, 8 },
|
||||
{ "RadShapeGenDecl", "default_resolution", 152, 8 },
|
||||
{ "RadShapeGenDecl", "min_resolution", 160, 8 },
|
||||
{ "RadShapeGenDecl", "max_resolution", 168, 8 },
|
||||
{ "RadShapeGenDecl", "max_lanes", 176, 8 },
|
||||
{ "RadShapeGenDecl", "max_query", 184, 8 },
|
||||
{ "RadShapeGenDecl", "field_out", 192, 4 },
|
||||
{ "RadTensor", "", 0, 112 },
|
||||
{ "RadTensor", "data", 0, 8 },
|
||||
{ "RadTensor", "dtype", 8, 4 },
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
|
||||
* struct's listed fields account for its size, so the list in rad_abi_layout_rows.h is complete; and
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 32 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 37 and RAD_FORMAT_VER 2. Under
|
||||
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
|
||||
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
|
||||
* headers: nothing else states the layout. When it disagrees the test prints the live table.
|
||||
@@ -59,8 +59,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 32 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 32, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 37 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 37, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
+10
-6
@@ -158,7 +158,7 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) {
|
||||
int32_t cards[Slab::kSeq];
|
||||
for (int i = 0; i < Slab::kSeq; ++i) cards[i] = i;
|
||||
for (int i = Slab::kSeq - 1; i > 0; --i) std::swap(cards[i], cards[lcg(rng) % (i + 1)]);
|
||||
struct Want { int card, rout, acc, tok, head; } want[4];
|
||||
struct Want { int card, rout, acc, tok, head, hrow; } want[4];
|
||||
for (int i = 0; i < n_rows; ++i) {
|
||||
const int kind = (int)(lcg(rng) % 4); /* 0: mid-prefill, 1: last chunk, else decode */
|
||||
const int n_spec = kind >= 2 ? (int)(lcg(rng) % 9) : 0;
|
||||
@@ -178,7 +178,7 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) {
|
||||
: 1 + (int32_t)(lcg(rng) % 3);
|
||||
if (rout >= 0) s.src[rout + j] = target[j];
|
||||
}
|
||||
want[i] = { cards[i], rout, -1, 0, 0 };
|
||||
want[i] = { cards[i], rout, -1, 0, 0, 0 };
|
||||
if (rout >= 0) {
|
||||
int32_t out[9] = {}, acc = -1;
|
||||
CHECK_OK(accept_greedy(draft, n_spec, target, out, &acc));
|
||||
@@ -188,6 +188,7 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) {
|
||||
want[i].acc = cut;
|
||||
want[i].tok = out[cut];
|
||||
want[i].head = ctx + (rtok - k) + cut;
|
||||
want[i].hrow = rtok + cut; /* the row of the last accepted position */
|
||||
out_row += 1 + n_spec;
|
||||
}
|
||||
k += n_tok;
|
||||
@@ -202,7 +203,8 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) {
|
||||
ok = std::memcmp(&S, &untouched, sizeof S) == 0;
|
||||
} else {
|
||||
ok = S.acc == want[i].acc && S.tok[0] == want[i].tok && S.n_acc == want[i].acc + 1 &&
|
||||
S.head == want[i].head && S.ctx == want[i].head + 1;
|
||||
S.head == want[i].head && S.ctx == want[i].head + 1 &&
|
||||
S.hrow == want[i].hrow;
|
||||
}
|
||||
if (!ok) {
|
||||
bad = 1;
|
||||
@@ -244,7 +246,7 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
|
||||
|
||||
const int n_rows = 1 + (int)(lcg(rng) % 4);
|
||||
int k = 0, out_row = 0;
|
||||
struct Want { int card, acc, tok, head; int32_t path[8]; } want[4];
|
||||
struct Want { int card, acc, tok, head, hrow; int32_t path[8]; } want[4];
|
||||
for (int i = 0; i < n_rows; ++i) {
|
||||
const int n_spec = (int)(lcg(rng) % 9);
|
||||
const int n_tok = 1 + n_spec;
|
||||
@@ -270,7 +272,8 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
|
||||
const int32_t cut = accept_cut_at_eog(out, acc, is_eog);
|
||||
deep += cut >= 2;
|
||||
cut_cases += cut < acc;
|
||||
want[i] = { i, cut, out[cut], ctx + cut, {} };
|
||||
/* the row of the last node on the accepted path: rows are nodes, in order */
|
||||
want[i] = { i, cut, out[cut], ctx + cut, rtok + (cut == 0 ? 0 : path[cut - 1]), {} };
|
||||
std::memcpy(want[i].path, path, sizeof path);
|
||||
out_row += 1 + n_spec;
|
||||
k += n_tok;
|
||||
@@ -279,7 +282,8 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
|
||||
for (int i = 0; i < n_rows && !bad; ++i) {
|
||||
const StepSlot& S = s.st[want[i].card];
|
||||
bool ok = S.acc == want[i].acc && S.tok[0] == want[i].tok && S.n_acc == want[i].acc + 1 &&
|
||||
S.head == want[i].head && S.ctx == want[i].head + 1 && S.npath == want[i].acc;
|
||||
S.head == want[i].head && S.ctx == want[i].head + 1 && S.npath == want[i].acc &&
|
||||
S.hrow == want[i].hrow;
|
||||
for (int t = 0; ok && t < want[i].acc; ++t) ok = S.path[t] == want[i].path[t];
|
||||
if (!ok) {
|
||||
bad = 1;
|
||||
|
||||
+11
-2
@@ -70,6 +70,7 @@ struct RecMap {
|
||||
int mode = 0;
|
||||
std::vector<std::string> src;
|
||||
int concat_dim = 0;
|
||||
std::vector<int> src_index; /* RadNameMap::src_index, one per source */
|
||||
};
|
||||
struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; bool replicated = false;
|
||||
bool dense = false; };
|
||||
@@ -99,6 +100,7 @@ struct RadBuilder {
|
||||
/* Ops the fake kernel hierarchy refuses, to drive the fused-op fallback; and ops no loaded
|
||||
* library declares (rad_op_declared), as without an optional library. */
|
||||
std::set<std::string> refuse;
|
||||
std::set<std::pair<std::string, std::string>> refuse_dtype; /* (op, dtype) forms */
|
||||
std::set<std::string> undeclared;
|
||||
/* When set, the only ops any loaded library declares (a CPU-only engine's: libref's
|
||||
* vocabulary); every other op is undeclared. */
|
||||
@@ -217,7 +219,10 @@ extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* par
|
||||
r.p.push_back(p);
|
||||
}
|
||||
for (int i = 0; i < n_weights; ++i) r.w.push_back(weights[i]);
|
||||
r.resolved = b->refuse.count(r.op) == 0;
|
||||
bool dtype_refused = false;
|
||||
for (const auto& p : r.p)
|
||||
if (p.key == "dtype" && b->refuse_dtype.count({r.op, p.sval})) dtype_refused = true;
|
||||
r.resolved = b->refuse.count(r.op) == 0 && !dtype_refused;
|
||||
b->ops.push_back(r);
|
||||
/* Declare always completes. An unresolved op is RAD_NULL_HANDLE, an error only if the plugin
|
||||
* issues it (rad_builder.h). */
|
||||
@@ -274,7 +279,10 @@ extern "C" int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) {
|
||||
r.declared = m->declared;
|
||||
r.mode = m->mode;
|
||||
r.concat_dim = m->concat_dim;
|
||||
for (int i = 0; i < m->n_src; ++i) r.src.push_back(m->src[i]);
|
||||
for (int i = 0; i < m->n_src; ++i) {
|
||||
r.src.push_back(m->src[i]);
|
||||
r.src_index.push_back(m->src_index[i]);
|
||||
}
|
||||
b->maps.push_back(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -524,6 +532,7 @@ 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; }
|
||||
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). */
|
||||
extern "C" RadStream rad_stream(RadCtx* c) { return (RadStream)c; }
|
||||
extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; }
|
||||
|
||||
+580
-19
@@ -1882,6 +1882,109 @@ RadModelMeta qwen4exp_meta() {
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
TEST(qwen4exp_pass_key_reuses_only_proven_uniform_prefill_grids) {
|
||||
RadModelMeta meta = qwen4exp_meta();
|
||||
RadBuildCtx build = build_ctx(0, 1);
|
||||
build.max_tok = 64; build.max_seqs = 2; build.max_spec = 0; build.max_ctx = 65536;
|
||||
RadBuilder graph;
|
||||
REQUIRE_EQ(qwen4exp_fp8::declare(&graph, &meta, &build), RAD_OK);
|
||||
rad_kvgroup kv_full = 0;
|
||||
for (size_t i = 0; i < graph.kv_groups.size(); ++i)
|
||||
if (graph.kv_groups[i].name.find("kv_attn") != std::string::npos) {
|
||||
kv_full = (rad_kvgroup)(i + 1);
|
||||
break;
|
||||
}
|
||||
REQUIRE(kv_full != 0);
|
||||
|
||||
RadCtx ctx{};
|
||||
RadKVGroupBatch group{};
|
||||
group.group = kv_full;
|
||||
RadBatch batch{};
|
||||
batch.phase = RAD_PHASE_PREFILL;
|
||||
batch.n_tok = 64; batch.n_seq = 1; batch.max_q_len = 64;
|
||||
/* The split law uses the declared launch context, not this rounded live-batch bound. */
|
||||
batch.max_ctx_len = 1024; batch.n_kv_groups = 1; batch.kv = &group;
|
||||
int32_t used[1] = {2304};
|
||||
const uint64_t key6 = qwen4exp_fp8::pass_key(&ctx, &batch, used);
|
||||
CHECK(key6 != 0);
|
||||
used[0] = 2305;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), key6);
|
||||
used[0] = 3072;
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != key6);
|
||||
|
||||
/* Same rounded live bound, different exact grids under the launcher's model context. */
|
||||
used[0] = 896;
|
||||
const uint64_t key_896 = qwen4exp_fp8::pass_key(&ctx, &batch, used);
|
||||
used[0] = 1152;
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != key_896);
|
||||
|
||||
/* A shorter one-sequence chunk still proves q_len = n_tok; do not require the model max_tok. */
|
||||
used[0] = 2304;
|
||||
batch.n_tok = 32; batch.max_q_len = 32;
|
||||
const uint64_t key_chunk = qwen4exp_fp8::pass_key(&ctx, &batch, used);
|
||||
CHECK(key_chunk != 0);
|
||||
CHECK(key_chunk != key6);
|
||||
batch.n_tok = 64; batch.max_q_len = 64;
|
||||
|
||||
batch.phase = RAD_PHASE_MIXED;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), (uint64_t)0);
|
||||
batch.phase = RAD_PHASE_PREFILL; batch.draft_pass = 0; batch.n_seq = 2;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), (uint64_t)0);
|
||||
batch.n_seq = 1; used[0] = 0;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), (uint64_t)0);
|
||||
}
|
||||
|
||||
/* Decode, verify and draft passes are recorded, keyed by the cap their live KV length puts on a
|
||||
* split launcher (eight 48-key tiles a split, binding below 64 splits): one key within a level, another
|
||||
* across it, the same past the last level, and none without a host summary or in a mixed pass. A pass
|
||||
* left unkeyed (0) is issued op by op on every step (issue #402). */
|
||||
TEST(qwen4exp_pass_key_keys_decode_verify_and_draft_by_the_split_cap) {
|
||||
RadModelMeta meta = qwen4exp_meta();
|
||||
RadBuildCtx build = build_ctx(0, 1);
|
||||
build.max_tok = 64; build.max_seqs = 2; build.max_spec = 5; build.max_ctx = 65536;
|
||||
RadBuilder graph;
|
||||
REQUIRE_EQ(qwen4exp_fp8::declare(&graph, &meta, &build), RAD_OK);
|
||||
rad_kvgroup kv_full = 0;
|
||||
for (size_t i = 0; i < graph.kv_groups.size(); ++i)
|
||||
if (graph.kv_groups[i].name.find("kv_attn") != std::string::npos) {
|
||||
kv_full = (rad_kvgroup)(i + 1);
|
||||
break;
|
||||
}
|
||||
REQUIRE(kv_full != 0);
|
||||
|
||||
RadCtx ctx{};
|
||||
RadKVGroupBatch group{};
|
||||
group.group = kv_full;
|
||||
RadBatch batch{};
|
||||
batch.phase = RAD_PHASE_DECODE; batch.n_spec = 5;
|
||||
batch.n_tok = 6; batch.n_seq = 1; batch.max_q_len = 6;
|
||||
batch.max_ctx_len = 1024; batch.n_kv_groups = 1; batch.kv = &group;
|
||||
int32_t used[1] = {400}; /* 9 tiles: level 1 (337-720 keys) */
|
||||
const uint64_t verify1 = qwen4exp_fp8::pass_key(&ctx, &batch, used);
|
||||
CHECK(verify1 != 0);
|
||||
used[0] = 720;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), verify1);
|
||||
used[0] = 721; /* 16 tiles: level 2 */
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != verify1);
|
||||
used[0] = 300; /* 7 tiles: level 0 */
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != verify1);
|
||||
used[0] = 30000; /* past 64 splits' 24,576 keys: one key */
|
||||
const uint64_t verify_long = qwen4exp_fp8::pass_key(&ctx, &batch, used);
|
||||
used[0] = 60000;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), verify_long);
|
||||
|
||||
used[0] = 400;
|
||||
batch.n_spec = 0; batch.n_tok = 1; batch.max_q_len = 1;
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != 0); /* plain decode */
|
||||
batch.draft_pass = -1;
|
||||
CHECK(qwen4exp_fp8::pass_key(&ctx, &batch, used) != 0); /* the MTP head's draft pass */
|
||||
|
||||
used[0] = 0;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), (uint64_t)0);
|
||||
used[0] = 400; batch.draft_pass = 0; batch.phase = RAD_PHASE_MIXED;
|
||||
CHECK_EQ(qwen4exp_fp8::pass_key(&ctx, &batch, used), (uint64_t)0);
|
||||
}
|
||||
|
||||
TEST(qwen4exp_yarn_reaches_attention_indexer_and_compressed_keys) {
|
||||
RadModelMeta meta = qwen4exp_meta();
|
||||
std::vector<const char*> keys(meta.kv_key, meta.kv_key + meta.n_kv);
|
||||
@@ -4950,6 +5053,130 @@ TEST(the_gemma4_31b_form_reads_asymmetric_int4_and_int5_linears) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Gemma 4 12B (`gemma4_unified`, served here through the arch id's alias) on the same twelve
|
||||
* layers: width 3840, 16 query heads over 8 sliding KV heads and ONE global KV head, its layer
|
||||
* schedule from layer_types. */
|
||||
const char* k_gem12_keys[] = {
|
||||
"model_type", "sliding_window", "global_head_dim", "num_global_key_value_heads",
|
||||
"rope_parameters.sliding_attention.rope_theta", "rope_parameters.full_attention.rope_theta",
|
||||
"rope_parameters.full_attention.partial_rotary_factor", "num_kv_shared_layers",
|
||||
"final_logit_softcapping", "attention_k_eq_v", "hidden_size_per_layer_input", "layer_types",
|
||||
};
|
||||
const char* k_gem12_vals[] = {
|
||||
"gemma4_unified", "1024", "512", "1", "10000", "1000000", "0.25", "0", "30", "1", "0",
|
||||
"sliding_attention sliding_attention sliding_attention sliding_attention sliding_attention "
|
||||
"full_attention sliding_attention sliding_attention sliding_attention sliding_attention "
|
||||
"sliding_attention full_attention",
|
||||
};
|
||||
|
||||
RadModelMeta gemma4_12b_meta() {
|
||||
RadModelMeta m = gemma4_meta();
|
||||
m.name = "test-gemma4-12b-form";
|
||||
m.n_embd = 3840;
|
||||
m.n_head = 16;
|
||||
m.n_head_kv = 8;
|
||||
m.n_ff = 15360;
|
||||
m.n_kv = (int)(sizeof(k_gem12_keys) / sizeof(k_gem12_keys[0]));
|
||||
m.kv_key = k_gem12_keys;
|
||||
m.kv_val = k_gem12_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
/* At one rank the global class is 16 q heads over one KV head (gqa 16). At two and four the
|
||||
* sliding heads split (4 and 2 a rank, gqa 2) and the global head is replicated: each rank keeps
|
||||
* a share of the q heads (gqa 8 and 4) and the whole k row (rows 0..511), as one span or as the k
|
||||
* part of a fused q|k. Each layer's attention reads its own cache in its class's group, and a
|
||||
* step reduces the lookup and two a layer. */
|
||||
TEST(the_gemma4_12b_form_declares_and_steps_at_one_two_and_four_ranks) {
|
||||
const int64_t L = 12, hs = 256, hg = 512;
|
||||
for (bool fused : { false, true }) {
|
||||
for (int world : { 1, 2, 4 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
RadBuilder b;
|
||||
if (fused) {
|
||||
const RadEncoding e = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
|
||||
b.encs = { { "attn_qkv.", e }, { "attn_o.", e }, { "ffn_gate_up.", e },
|
||||
{ "ffn_down.", e } };
|
||||
}
|
||||
RadModelMeta meta = gemma4_12b_meta();
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ(gemma4_bf16::g_model[rank].fuse, fused);
|
||||
REQUIRE_EQ((int)b.kv_groups.size(), 2);
|
||||
CHECK_EQ(b.kv_groups[0].d.n_head_kv, 8 / world);
|
||||
CHECK_EQ(b.kv_groups[0].d.head_dim, hs);
|
||||
CHECK_EQ(b.kv_groups[1].d.n_head_kv, 1);
|
||||
CHECK_EQ(b.kv_groups[1].d.head_dim, hg);
|
||||
const int64_t nq = 16 / world;
|
||||
if (!fused) {
|
||||
const RecOp* as = find_op(b, "attn_paged", 0);
|
||||
const RecOp* ag = find_op(b, "attn_paged", 5);
|
||||
REQUIRE(as != nullptr && ag != nullptr);
|
||||
CHECK_EQ(pint(as, "head_dim"), hs);
|
||||
CHECK_EQ(pint(as, "n_head"), nq);
|
||||
CHECK_EQ(pint(as, "gqa"), 2);
|
||||
CHECK_EQ(pint(as, "window"), 1024);
|
||||
CHECK_EQ(pint(ag, "head_dim"), hg);
|
||||
CHECK_EQ(pint(ag, "n_head"), nq);
|
||||
CHECK_EQ(pint(ag, "gqa"), 16 / world);
|
||||
CHECK_EQ(pint(ag, "window"), 0);
|
||||
const RecWeight* q0 = find_w(b, "blk.0.attn_q.weight");
|
||||
const RecWeight* k0 = find_w(b, "blk.0.attn_k.weight");
|
||||
const RecWeight* q5 = find_w(b, "blk.5.attn_q.weight");
|
||||
const RecWeight* k5 = find_w(b, "blk.5.attn_k.weight");
|
||||
REQUIRE(q0 && k0 && q5 && k5);
|
||||
CHECK_EQ(q0->d.shape[0], nq * hs); CHECK_EQ(q0->d.shape[1], 3840);
|
||||
CHECK_EQ(k0->d.shape[0], (8 / world) * hs);
|
||||
CHECK_EQ(q5->d.shape[0], nq * hg);
|
||||
CHECK_EQ(k5->d.shape[0], hg);
|
||||
CHECK(find_w(b, "blk.5.attn_v.weight") == nullptr); /* k == v */
|
||||
CHECK(!k0->span_set); /* an even share */
|
||||
CHECK_EQ(k5->span_set, world > 1);
|
||||
if (world > 1) { CHECK_EQ(k5->span_lo, 0); CHECK_EQ(k5->span_hi, hg); }
|
||||
} else {
|
||||
const RecWeight* s0 = find_w(b, "blk.0.attn_qkv.weight");
|
||||
REQUIRE(s0 != nullptr);
|
||||
CHECK_EQ(s0->n_part_spans, 0); /* even shares */
|
||||
for (const char* v : { "weight", "scale" }) {
|
||||
const RecWeight* w = find_w(b, std::string("blk.5.attn_qkv.") + v);
|
||||
REQUIRE(w != nullptr);
|
||||
if (world == 1) { CHECK_EQ(w->n_part_spans, 0); continue; }
|
||||
REQUIRE_EQ(w->n_part_spans, 2); /* q and k, no v */
|
||||
CHECK_EQ(w->part_lo[0], rank * nq * hg);
|
||||
CHECK_EQ(w->part_hi[0], (rank + 1) * nq * hg);
|
||||
CHECK_EQ(w->part_total[0], 16 * hg);
|
||||
CHECK_EQ(w->part_lo[1], 0);
|
||||
CHECK_EQ(w->part_hi[1], hg);
|
||||
CHECK_EQ(w->part_total[1], hg);
|
||||
}
|
||||
}
|
||||
|
||||
RadBatch batch = decode_batch();
|
||||
RadCtx c; c.b = &b; c.rank = rank; c.world = world; c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
std::vector<std::pair<int, int64_t>> kv;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || (o->op != "attn_paged" && o->op != "attn_paged_qrow")) continue;
|
||||
REQUIRE(i.opd.size() > 1);
|
||||
CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_KV);
|
||||
kv.push_back({ (int)i.opd[1].handle, (int64_t)i.opd[1].offset });
|
||||
}
|
||||
REQUIRE_EQ((int)kv.size(), (int)L);
|
||||
for (int l = 0; l < (int)L; ++l) {
|
||||
CHECK_EQ(kv[(size_t)l].first, (l % 6 == 5) ? 2 : 1);
|
||||
CHECK_EQ(kv[(size_t)l].second, (int64_t)l);
|
||||
}
|
||||
const std::vector<std::string> ops = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(ops, "all_reduce") + count_issued(ops, "ar_rmsnorm_quant_i8"),
|
||||
world > 1 ? (int)(1 + 2 * L) : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_attention_shapes_for_both_classes) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_meta();
|
||||
@@ -5486,6 +5713,104 @@ TEST(gemma4_probe_names_the_heads_operating_depth) {
|
||||
CHECK_EQ(q.draft_depth, 0);
|
||||
}
|
||||
|
||||
/* The 12B's assistant: the same head under the name Gemma4UnifiedAssistantForCausalLM, width
|
||||
* 1024 over a 3840 trunk, 16 q heads over the trunk's 8 sliding and one global KV head. */
|
||||
const char* k_gem12d_keys[] = {
|
||||
"model_type", "sliding_window", "global_head_dim", "num_global_key_value_heads",
|
||||
"rope_parameters.sliding_attention.rope_theta", "rope_parameters.full_attention.rope_theta",
|
||||
"rope_parameters.full_attention.partial_rotary_factor", "num_kv_shared_layers",
|
||||
"final_logit_softcapping", "attention_k_eq_v", "hidden_size_per_layer_input", "layer_types",
|
||||
"draft.architectures", "draft.backbone_hidden_size", "draft.use_ordered_embeddings",
|
||||
"draft.text_config.hidden_size", "draft.text_config.num_hidden_layers",
|
||||
"draft.text_config.layer_types", "draft.text_config.num_attention_heads",
|
||||
"draft.text_config.num_key_value_heads", "draft.text_config.num_global_key_value_heads",
|
||||
"draft.text_config.head_dim", "draft.text_config.global_head_dim",
|
||||
"draft.text_config.intermediate_size", "draft.text_config.sliding_window",
|
||||
"draft.text_config.vocab_size", "draft.text_config.rms_norm_eps",
|
||||
"draft.text_config.rope_parameters.sliding_attention.rope_theta",
|
||||
"draft.text_config.rope_parameters.full_attention.rope_theta",
|
||||
"draft.text_config.rope_parameters.full_attention.partial_rotary_factor",
|
||||
};
|
||||
std::vector<const char*> gem12d_vals() {
|
||||
std::vector<const char*> v(std::begin(k_gem12_vals), std::end(k_gem12_vals));
|
||||
for (const char* s : { "Gemma4UnifiedAssistantForCausalLM", "3840", "0", "1024", "4",
|
||||
"sliding_attention sliding_attention sliding_attention full_attention",
|
||||
"16", "8", "1", "256", "512", "8192", "1024", "262144", "1e-06", "10000",
|
||||
"1000000", "0.25" })
|
||||
v.push_back(s);
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Declared at one, two and four ranks: the head's full layer is gqa 16, 8 and 4 over the trunk's
|
||||
* one (replicated) global KV head, its sliding layers gqa 2. A pass reads layers 10 and 11. A head
|
||||
* stating another global KV count than the trunk's is still refused. */
|
||||
TEST(the_gemma4_12b_assistant_is_declared_at_one_two_and_four_ranks) {
|
||||
const std::vector<const char*> vals = gem12d_vals();
|
||||
REQUIRE_EQ(vals.size(), sizeof(k_gem12d_keys) / sizeof(k_gem12d_keys[0]));
|
||||
for (int world : { 1, 2, 4 }) {
|
||||
for (int rank : { 0, world - 1 }) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_12b_meta();
|
||||
meta.n_kv = (int)vals.size(); meta.kv_key = k_gem12d_keys; meta.kv_val = vals.data();
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
ctx.max_spec = 3;
|
||||
CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_SERIAL);
|
||||
CHECK_EQ(b.drafter.depth, 3);
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 16);
|
||||
const int64_t nq = 16 / world;
|
||||
for (int l = 0; l < 4; ++l) {
|
||||
const RecOp* at = find_op(b, "attn_paged", 12 + l);
|
||||
REQUIRE(at != nullptr);
|
||||
CHECK_EQ(pint(at, "n_head"), nq);
|
||||
CHECK_EQ(pint(at, "head_dim"), l == 3 ? 512 : 256);
|
||||
CHECK_EQ(pint(at, "gqa"), l == 3 ? nq : 2);
|
||||
}
|
||||
const RecWeight* wq3 = find_w(b, "mtp.blk.3.attn_q.weight");
|
||||
const RecWeight* pre = find_w(b, "mtp.pre_proj.weight");
|
||||
const RecWeight* post = find_w(b, "mtp.post_proj.weight");
|
||||
REQUIRE(wq3 && pre && post);
|
||||
CHECK_EQ(wq3->d.shape[0], nq * 512); CHECK_EQ(wq3->d.shape[1], 1024);
|
||||
CHECK_EQ(pre->d.shape[0], 1024); CHECK_EQ(pre->d.shape[1], 2 * 3840);
|
||||
CHECK_EQ(post->d.shape[0], 3840); CHECK_EQ(post->d.shape[1], 1024);
|
||||
const RecMap* mpre = find_map(b, "mtp.pre_proj.weight");
|
||||
REQUIRE(mpre != nullptr);
|
||||
CHECK_EQ(mpre->src[0], std::string("draft.pre_projection.weight"));
|
||||
|
||||
RadBatch batch = head_batch(-1);
|
||||
RadCtx c; c.b = &b; c.rank = rank; c.world = world; c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
int seen = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || o->op != "attn_paged") continue;
|
||||
REQUIRE(i.opd.size() > 1);
|
||||
CHECK_EQ((int)i.opd[1].handle, seen < 3 ? 1 : 2);
|
||||
CHECK_EQ((long long)i.opd[1].offset, seen < 3 ? 10LL : 11LL);
|
||||
++seen;
|
||||
}
|
||||
CHECK_EQ(seen, 4);
|
||||
}
|
||||
}
|
||||
std::vector<const char*> two = gem12d_vals();
|
||||
two[20] = "2"; /* draft.text_config.num_global_key_value_heads */
|
||||
for (int world : { 1, 2 }) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_12b_meta();
|
||||
meta.n_kv = (int)two.size(); meta.kv_key = k_gem12d_keys; meta.kv_val = two.data();
|
||||
RadBuildCtx ctx = build_ctx(0, world);
|
||||
ctx.max_spec = 3;
|
||||
CHECK_EQ(stderr_of_rc([&] { return gemma4_bf16::declare(&b, &meta, &ctx); }),
|
||||
(int)RAD_E_INVAL);
|
||||
}
|
||||
RadArchProbe p{};
|
||||
RadModelMeta with = gemma4_12b_meta();
|
||||
with.n_kv = (int)vals.size(); with.kv_key = k_gem12d_keys; with.kv_val = vals.data();
|
||||
CHECK_OK(gemma4_bf16::probe(&with, &p));
|
||||
CHECK_EQ(p.draft_depth, gemma4_bf16::kHeadDepth);
|
||||
}
|
||||
|
||||
/* ===================== gemma4: the 26B-A4B, a dense and a routed arm side by side ===================== */
|
||||
|
||||
namespace {
|
||||
@@ -7734,7 +8059,11 @@ TEST(gemma4_31b_dflash2_fc_splits_by_rows_without_changing_a_bit) {
|
||||
}
|
||||
if (o.op == "all_gather" && pint(&o, "row") == cs.share) {
|
||||
++fc_gathers;
|
||||
CHECK_EQ(pint(&o, "numel"), (long long)(2048 * E)); /* the trunk's instance */
|
||||
/* The trunk's instance, and a range: a sizing declare may not change it. */
|
||||
const RecParam* ne = param(&o, "numel");
|
||||
REQUIRE(ne != nullptr);
|
||||
CHECK_EQ(ne->kind, (int)RAD_P_RANGE);
|
||||
CHECK_EQ(ne->ihi, (long long)(2048 * E));
|
||||
CHECK_EQ(pint(&o, "world_size"), (long long)cs.world);
|
||||
}
|
||||
}
|
||||
@@ -9421,9 +9750,11 @@ int w8a8_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The `_had_quant_i8g` producers, which libr4d serves and libref does not. */
|
||||
/* The `_had_quant_i8g` producers and the ops that write those codes in their epilogue (the
|
||||
* attention gate's, the delta net's decode conv fold's), which libr4d serves and libref does not. */
|
||||
const char* const kW8a8Fused[] = { "rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g",
|
||||
"gated_had_quant_i8g" };
|
||||
"gated_had_quant_i8g", "gate_had_quant_i8g",
|
||||
"gdn_conv_recurrent_update_had" };
|
||||
|
||||
/* Where the `_had_quant_i8g` producers are not served, every trunk linear of a rotated int8
|
||||
* container is an i8a8h GEMM right behind its own had_quant_act_i8g, at one rank and two: 2
|
||||
@@ -9458,11 +9789,13 @@ TEST(qwen35_w8a8_serves_every_trunk_linear_rotated_int8) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Where they are served, the norms and the gated product write had_quant_act_i8g's codes into the
|
||||
* int8 pair, and the projections reading them declare no quantiser: had_quant_act_i8g is left only
|
||||
* before the attention and delta-net output projections (2 + 6), every norm is the rotated twin (at
|
||||
* two ranks with its fused all-reduce form beside it), and every feed-forward's product is
|
||||
* gated_had_quant_i8g. No E4M3 norm or gated quantiser is left, and the 36 GEMMs are unchanged. */
|
||||
/* Where they are served, the norms, the gated product, the attention gate and the delta net's
|
||||
* decode conv fold write had_quant_act_i8g's codes into the int8 pair, and the projections reading
|
||||
* them declare no quantiser: had_quant_act_i8g is left only as the delta net's quantiser of the
|
||||
* rows its decode fold does not serve (6), every norm is the rotated twin (at two ranks with its
|
||||
* fused all-reduce form beside it), every feed-forward's product is gated_had_quant_i8g and every
|
||||
* attention gate gate_had_quant_i8g. No E4M3 norm or gated quantiser is left, and the 36 GEMMs are
|
||||
* unchanged. */
|
||||
TEST(qwen35_w8a8_feeds_its_rotated_codes_from_the_producers_where_libr4d_serves_them) {
|
||||
MetaKV mk = q35w8a8_meta();
|
||||
for (int world : { 1, 2 }) {
|
||||
@@ -9473,9 +9806,11 @@ TEST(qwen35_w8a8_feeds_its_rotated_codes_from_the_producers_where_libr4d_serves_
|
||||
int rot = 0;
|
||||
for (const RecOp& o : b.ops) rot += o.op == "gemm_nt_q" && pstr(&o, "dtype") == "i8a8h";
|
||||
CHECK_EQ(rot, 2 * 4 + 6 * 2 + 8 * 2);
|
||||
CHECK_EQ(count_op(b, "had_quant_act_i8g"), 2 + 6);
|
||||
CHECK_EQ(count_op(b, "had_quant_act_i8g"), 6);
|
||||
CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 8 + 8);
|
||||
CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 8);
|
||||
CHECK_EQ(count_op(b, "gate_had_quant_i8g"), 2);
|
||||
CHECK_EQ(count_op(b, "gdn_conv_recurrent_update_had"), 6);
|
||||
for (const char* op : { "rmsnorm_quant_fp8", "ar_rmsnorm_quant_fp8", "gated_quant_fp8",
|
||||
"quant_act_i8g" })
|
||||
CHECK_EQ(count_op(b, op), 0);
|
||||
@@ -10358,6 +10693,232 @@ TEST(nomicbert_probe_reads_the_model_type) {
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
/* Gemma 4 12B's media embedders (rad_block_gemma4_unified.h) in place of the tower and the
|
||||
* conformer: a picture patch is a 48 x 48 window and an audio frame 640 samples, each one row. The
|
||||
* position table [npos, 2, width] is read as its taps 0 (column) and 1 (row) of dimension 1; a
|
||||
* vision pass is LayerNorm, the dense with its bias, LayerNorm, the two position rows (the column
|
||||
* from coordinate plane 1, the row from plane 0) added in, LayerNorm (eps 1e-5, no config states it),
|
||||
* the weightless RMS norm and the projection; an audio pass the norm and its projection. Every rank
|
||||
* runs both whole and both lint clean; the probe says one patch a row and 750 frames. */
|
||||
TEST(the_gemma4_12b_embeds_images_and_audio_without_an_encoder) {
|
||||
std::vector<const char*> keys(std::begin(k_gem12_keys), std::end(k_gem12_keys));
|
||||
std::vector<const char*> vals(std::begin(k_gem12_vals), std::end(k_gem12_vals));
|
||||
const char* mk[] = { "vision_config.model_type", "vision_config.mm_embed_dim",
|
||||
"vision_config.mm_posemb_size", "vision_config.model_patch_size",
|
||||
"vision_config.output_proj_dims", "vision_config.rms_norm_eps",
|
||||
"vision_config.patch_size", "vision_config.pooling_kernel_size",
|
||||
"audio_config.model_type", "audio_config.audio_embed_dim",
|
||||
"audio_config.rms_norm_eps", "processor.feature_extractor.sampling_rate",
|
||||
"processor.feature_extractor.audio_samples_per_token",
|
||||
"processor.audio_seq_length" };
|
||||
const char* mv[] = { "gemma4_unified_vision", "3840", "1120", "48", "3840", "1e-06", "16", "3",
|
||||
"gemma4_unified_audio", "640", "1e-06", "16000", "640", "750" };
|
||||
keys.insert(keys.end(), std::begin(mk), std::end(mk));
|
||||
vals.insert(vals.end(), std::begin(mv), std::end(mv));
|
||||
RadModelMeta meta = gemma4_12b_meta();
|
||||
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
|
||||
|
||||
RadArchProbe pr{};
|
||||
REQUIRE_EQ(gemma4_bf16::probe(&meta, &pr), RAD_OK);
|
||||
CHECK_EQ(pr.enc_merge, 1);
|
||||
CHECK_EQ(pr.audio_frames, 750);
|
||||
|
||||
for (int world : { 1, 2, 4 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
ctx.max_enc_patches = 1120;
|
||||
ctx.max_audio_frames = 750;
|
||||
REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK);
|
||||
CHECK_EQ(b.encoder_name, std::string("vision"));
|
||||
CHECK_EQ(b.encoder.patch_dim, 6912);
|
||||
CHECK_EQ(b.encoder.merge, 1);
|
||||
CHECK_EQ(b.encoder.max_patches, 1120);
|
||||
CHECK_EQ(b.encoder.n_embd, 3840);
|
||||
CHECK_EQ(b.audio_encoder_name, std::string("audio"));
|
||||
CHECK_EQ(b.audio_encoder.patch_dim, 640);
|
||||
CHECK_EQ(b.audio_encoder.merge, 1);
|
||||
CHECK_EQ(b.audio_encoder.max_patches, 750);
|
||||
CHECK_EQ(count_op(b, "scatter_rows"), 1);
|
||||
for (int t = 0; t < 2; ++t) {
|
||||
const RecMap* pos = find_map(b, t ? "v.pos_y.weight" : "v.pos_x.weight");
|
||||
REQUIRE(pos != nullptr);
|
||||
CHECK_EQ(pos->mode, (int)RAD_MAP_TAP);
|
||||
CHECK_EQ(pos->concat_dim, 1);
|
||||
CHECK(pos->src == std::vector<std::string>{ "model.vision_embedder.pos_embedding" });
|
||||
REQUIRE_EQ(pos->src_index.size(), (size_t)1);
|
||||
CHECK_EQ(pos->src_index[0], t);
|
||||
const RecWeight* w = find_w(b, t ? "v.pos_y.weight" : "v.pos_x.weight");
|
||||
REQUIRE(w != nullptr);
|
||||
CHECK_EQ(w->d.shape[0], 1120);
|
||||
CHECK_EQ(w->d.shape[1], 3840);
|
||||
}
|
||||
const struct { const char* d; const char* s; } src[] = {
|
||||
{ "v.ln1.weight", "model.vision_embedder.patch_ln1.weight" },
|
||||
{ "v.ln1.bias", "model.vision_embedder.patch_ln1.bias" },
|
||||
{ "v.in.weight", "model.vision_embedder.patch_dense.weight" },
|
||||
{ "v.in.bias", "model.vision_embedder.patch_dense.bias" },
|
||||
{ "v.ln2.weight", "model.vision_embedder.patch_ln2.weight" },
|
||||
{ "v.ln2.bias", "model.vision_embedder.patch_ln2.bias" },
|
||||
{ "v.pn.weight", "model.vision_embedder.pos_norm.weight" },
|
||||
{ "v.pn.bias", "model.vision_embedder.pos_norm.bias" },
|
||||
{ "v.embed.weight", "model.embed_vision.embedding_projection.weight" },
|
||||
{ "a.embed.weight", "model.embed_audio.embedding_projection.weight" } };
|
||||
for (const auto& e : src) {
|
||||
const RecMap* mp = find_map(b, e.d);
|
||||
REQUIRE(mp != nullptr);
|
||||
CHECK(mp->src == std::vector<std::string>{ e.s });
|
||||
CHECK(find_w(b, e.d) != nullptr);
|
||||
}
|
||||
const RecWeight* dense = find_w(b, "v.in.weight");
|
||||
REQUIRE(dense != nullptr);
|
||||
CHECK_EQ(dense->d.shape[0], 3840);
|
||||
CHECK_EQ(dense->d.shape[1], 6912);
|
||||
CHECK_EQ(dense->d.shard, (int)RAD_SHARD_NONE);
|
||||
CHECK(find_w(b, "v.blk.0.qkv") == nullptr); /* no tower */
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "layernorm") CHECK_NEAR(pflt(&o, "eps"), 1e-5, 0.0);
|
||||
|
||||
const auto vis = enc_pass(RAD_MM_IMAGE, 280, 6912);
|
||||
RadCtx cv{ .b = &b, .batch = &vis->b };
|
||||
cv.rank = rank; cv.world = world;
|
||||
gemma4_bf16::step(&cv, &vis->b);
|
||||
CHECK(cv.step_fail.empty());
|
||||
CHECK_LINT(b, &cv);
|
||||
const std::vector<std::string> want = { "layernorm", "gemm_nt_bias", "layernorm",
|
||||
"embed_lookup", "embed_lookup", "add", "add",
|
||||
"layernorm", "rmsnorm", "gemm_nt" };
|
||||
CHECK_EQ(join(issued_ops(b, cv)), join(want));
|
||||
REQUIRE_EQ(cv.issues.size(), want.size());
|
||||
CHECK(cv.issues[0].opd[0].raw == vis->pix.data());
|
||||
CHECK(cv.issues[3].opd[0].raw == vis->coord.data() + 280); /* the column */
|
||||
CHECK(cv.issues[4].opd[0].raw == vis->coord.data()); /* the row */
|
||||
CHECK_EQ(cv.issues[3].opd[1].handle, (uint32_t)gemma4_bf16::g_model[rank].uvis.w_px);
|
||||
CHECK_EQ(cv.issues[4].opd[1].handle, (uint32_t)gemma4_bf16::g_model[rank].uvis.w_py);
|
||||
CHECK_EQ(cv.issues.back().n, 280);
|
||||
CHECK_EQ(cv.issues.back().opd.back().handle, b.encoder.out);
|
||||
|
||||
const auto aud = enc_pass(RAD_MM_AUDIO, 125, 640);
|
||||
RadCtx ca{ .b = &b, .batch = &aud->b };
|
||||
ca.rank = rank; ca.world = world;
|
||||
gemma4_bf16::step(&ca, &aud->b);
|
||||
CHECK(ca.step_fail.empty());
|
||||
CHECK_LINT(b, &ca);
|
||||
CHECK_EQ(join(issued_ops(b, ca)), join({ "rmsnorm", "gemm_nt" }));
|
||||
CHECK_EQ(ca.issues.back().n, 125);
|
||||
CHECK_EQ(ca.issues.back().opd.back().handle, b.audio_encoder.out);
|
||||
|
||||
/* More patches than declared is refused, issuing nothing. */
|
||||
const auto big = enc_pass(RAD_MM_IMAGE, 1121, 6912);
|
||||
RadCtx cb{ .b = &b, .batch = &big->b };
|
||||
gemma4_bf16::step(&cb, &big->b);
|
||||
CHECK(!cb.step_fail.empty());
|
||||
CHECK(cb.issues.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The 12B (and the 31B) read a picture's placeholders both ways (use_bidirectional_attention
|
||||
* "vision") on the sliding layers; the global layers stay causal, as transformers' Gemma 4 masks
|
||||
* and KerasHub's have it. Every sliding layer declares a second attention without the causal
|
||||
* bound (its window two-sided), the encoder says so to the core (RadEncoderDecl::bidirectional),
|
||||
* and on a pass with a run (RadBatch::n_bidi) each sliding layer attends the run's rows again over
|
||||
* their sequence's cache up to the run's end, written over the causal result in the same rows.
|
||||
* Without the config key, nothing of it. */
|
||||
TEST(the_gemma4_12b_reads_a_pictures_rows_both_ways) {
|
||||
std::vector<const char*> keys(std::begin(k_gem12_keys), std::end(k_gem12_keys));
|
||||
std::vector<const char*> vals(std::begin(k_gem12_vals), std::end(k_gem12_vals));
|
||||
const char* mk[] = { "vision_config.model_type", "vision_config.mm_embed_dim",
|
||||
"vision_config.mm_posemb_size", "vision_config.model_patch_size",
|
||||
"use_bidirectional_attention" };
|
||||
const char* mv[] = { "gemma4_unified_vision", "3840", "1120", "48", "vision" };
|
||||
keys.insert(keys.end(), std::begin(mk), std::end(mk));
|
||||
vals.insert(vals.end(), std::begin(mv), std::end(mv));
|
||||
static const int32_t row[] = { 40 }, seq[] = { 1 }, used[] = { 30 };
|
||||
const int64_t L_sliding = 10; /* layers 5 and 11 are global */
|
||||
/* A run of 10 rows within the window, and one longer than a window of 8, whose rows read the
|
||||
* keys behind them only through the window (attn_paged_ahead). */
|
||||
const int32_t run = 10;
|
||||
static const int32_t rows[] = { run };
|
||||
for (const int win : { 1024, 8 })
|
||||
for (int mode = 0; mode < 2; ++mode) { /* 0 on, 1 no key */
|
||||
std::vector<const char*> wvals = vals;
|
||||
for (size_t k = 0; k < keys.size(); ++k)
|
||||
if (!std::strcmp(keys[k], "sliding_window")) wvals[k] = win == 8 ? "8" : "1024";
|
||||
for (bool fused : { false, true }) {
|
||||
for (int world : { 1, 2 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
RadBuilder b;
|
||||
if (fused) {
|
||||
const RadEncoding e = rad_enc_affine(RAD_I4, RAD_F16, 1, 128);
|
||||
b.encs = { { "attn_qkv.", e }, { "attn_o.", e }, { "ffn_gate_up.", e },
|
||||
{ "ffn_down.", e } };
|
||||
}
|
||||
RadModelMeta meta = gemma4_12b_meta();
|
||||
meta.n_kv = (int)keys.size() - (mode == 1 ? 1 : 0);
|
||||
meta.kv_key = keys.data(); meta.kv_val = wvals.data();
|
||||
RadBuildCtx ctx = build_ctx(rank, world);
|
||||
ctx.max_enc_patches = 1120;
|
||||
const int rc = gemma4_bf16::declare(&b, &meta, &ctx);
|
||||
REQUIRE_EQ(rc, RAD_OK);
|
||||
const bool on = mode == 0;
|
||||
CHECK_EQ(b.encoder.bidirectional, on ? 1 : 0);
|
||||
int nc = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if ((o.op == "attn_paged" || o.op == "attn_paged_qrow") && pint(&o, "causal") == 0) {
|
||||
++nc;
|
||||
CHECK_EQ(pint(&o, "window"), win);
|
||||
CHECK_EQ(pint(&o, "head_dim"), 256);
|
||||
}
|
||||
CHECK_EQ(nc, on ? (int)L_sliding : 0);
|
||||
int na = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "attn_paged_ahead" || o.op == "attn_paged_qrow_ahead") {
|
||||
++na;
|
||||
CHECK_EQ(pint(&o, "causal"), 0);
|
||||
CHECK_EQ(pint(&o, "window"), win);
|
||||
}
|
||||
CHECK_EQ(na, on ? (int)L_sliding : 0);
|
||||
|
||||
RadBatch batch = prefill_batch();
|
||||
batch.n_bidi = 1;
|
||||
batch.bidi_row = row; batch.bidi_n = rows; batch.bidi_seq = seq;
|
||||
batch.bidi_used = used;
|
||||
RadCtx c; c.b = &b; c.rank = rank; c.world = world; c.batch = &batch;
|
||||
gemma4_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
int again = 0;
|
||||
rad_op last_attn = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || (o->op != "attn_paged" && o->op != "attn_paged_qrow" &&
|
||||
o->op != "attn_paged_ahead" && o->op != "attn_paged_qrow_ahead"))
|
||||
continue;
|
||||
if (pint(o, "causal") == 1) { last_attn = i.op; continue; }
|
||||
++again;
|
||||
CHECK(last_attn != 0); /* behind the causal pass */
|
||||
const bool ahead = o->op.size() > 6 && o->op.compare(o->op.size() - 6, 6, "_ahead") == 0;
|
||||
CHECK_EQ(ahead, run > win);
|
||||
CHECK_EQ(i.n, run);
|
||||
REQUIRE(i.opd.size() == 8);
|
||||
CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_KV);
|
||||
CHECK(i.opd[3].raw == used);
|
||||
CHECK_EQ(i.opd[3].rows, 1);
|
||||
CHECK_EQ(i.opd[2].rows, 1); /* the run's sequence's table */
|
||||
CHECK(i.opd[6].kind == RAD_OPK_NONE);
|
||||
const int64_t qd = (16 / world) * (pint(o, "head_dim"));
|
||||
CHECK_EQ(i.opd[7].offset, 40 * qd); /* its rows of the output */
|
||||
CHECK_EQ(i.opd[7].rows, run);
|
||||
last_attn = 0;
|
||||
}
|
||||
CHECK_EQ(again, on ? (int)L_sliding : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== qwenimage21 */
|
||||
|
||||
namespace {
|
||||
@@ -11012,22 +11573,22 @@ struct ArchCases {
|
||||
qwen35_bf16::step, 0, {}, 0xf82117051023e608ull);
|
||||
add("qwen35_fp8 + MTP", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 3); return qwen35_fp8::declare(b, q35.meta(), &c); },
|
||||
qwen35_fp8::step, 3, {}, 0x20ab9ed24e409329ull);
|
||||
qwen35_fp8::step, 3, {}, 0x958b83102809266bull);
|
||||
add("qwen35_fp8 + MTP, two ranks", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(2, 3); return qwen35_fp8::declare(b, q35.meta(), &c); },
|
||||
nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x5b52afb1706a954eull);
|
||||
nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x91408682a38a1754ull);
|
||||
add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); },
|
||||
qwen35_fp8::step, 7, {}, 0x365e4cbb415ac284ull);
|
||||
qwen35_fp8::step, 7, {}, 0x60d33ded99aa451eull);
|
||||
add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); },
|
||||
qwen35_w8a8::step, 7, {}, 0x742a596708bbda1dull);
|
||||
qwen35_w8a8::step, 7, {}, 0x570d3bc8fc15f701ull);
|
||||
add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); },
|
||||
nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x93b6390d30e59953ull);
|
||||
nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x6c5267846652829full);
|
||||
add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) {
|
||||
auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); },
|
||||
qwen35moe_fp8::step, 3, {}, 0x4c7e42e71f167042ull);
|
||||
qwen35moe_fp8::step, 3, {}, 0x325d0299495a0dd8ull);
|
||||
add("qwen4exp_fp8", [this](RadBuilder* b) {
|
||||
auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); },
|
||||
qwen4exp_fp8::step, 3, {}, 0x9454e9dff6db286bull);
|
||||
@@ -11770,10 +12331,10 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) {
|
||||
{ "qwen4exp_fp8", 2, 1, 0x4bc19e44d0743e49ull, 0x959ef6b7c6f57d8bull },
|
||||
{ "qwen4exp_fp8", 4, 0, 0xea29df78a9297c5cull, 0xfbe74f2b9d7020bfull },
|
||||
{ "qwen4exp_fp8", 4, 3, 0x1e4ba87a0d9619f4ull, 0x36df57cac613c6cfull },
|
||||
{ "qwen35_fp8", 1, 0, 0xc56a518087e3f4b4ull, 0xa7ec3cf6252cd441ull },
|
||||
{ "qwen35_fp8", 2, 1, 0x6e644b3d13bac619ull, 0xdd5d65ef158c4136ull },
|
||||
{ "qwen35moe_fp8", 1, 0, 0x7a9330e0da08f97cull, 0x2b5989b2a6dbc7dfull },
|
||||
{ "qwen35moe_fp8", 2, 0, 0x3a2761e9546797f1ull, 0x4a597c66b5868eeeull },
|
||||
{ "qwen35_fp8", 1, 0, 0x0f08ba5027cba71aull, 0xa7ec3cf6252cd441ull },
|
||||
{ "qwen35_fp8", 2, 1, 0xe7780f241685a18bull, 0xdd5d65ef158c4136ull },
|
||||
{ "qwen35moe_fp8", 1, 0, 0xb1e6173bd121dc2aull, 0x2b5989b2a6dbc7dfull },
|
||||
{ "qwen35moe_fp8", 2, 0, 0x46d061a0de9a8933ull, 0x4a597c66b5868eeeull },
|
||||
};
|
||||
for (const Case& cs : cases) {
|
||||
RadBuilder b;
|
||||
|
||||
@@ -1925,6 +1925,21 @@ TEST(config_json_fills_the_model_meta_as_each_family_spells_it) {
|
||||
"lfm2", 0, 1024, 16, 8, 64, 0, 0, 0, 0, 0, 0, 1e-5, 1e4,
|
||||
{ { "layer_types", "conv full_attention conv" }, { "hidden_size", "7" },
|
||||
{ "vision_config.hidden_size", "768" } } },
|
||||
{ "Gemma 4 12B: the unified wrapper maps to gemma4, its model_type stays, null experts",
|
||||
R"({"model_type":"gemma4_unified","eos_token_id":[1,106],
|
||||
"text_config":{"model_type":"gemma4_unified_text","hidden_size":3840,
|
||||
"num_attention_heads":16,"num_key_value_heads":8,"num_global_key_value_heads":1,
|
||||
"head_dim":256,"global_head_dim":512,"num_hidden_layers":48,
|
||||
"intermediate_size":15360,"moe_intermediate_size":null,"num_experts":null,
|
||||
"rms_norm_eps":1e-06,"vocab_size":262144,"max_position_embeddings":262144,
|
||||
"rope_parameters":{"full_attention":{"rope_theta":1000000.0},
|
||||
"sliding_attention":{"rope_theta":10000.0}}},
|
||||
"vision_config":{"model_type":"gemma4_unified_vision"}})",
|
||||
"gemma4", 48, 3840, 16, 8, 256, 15360, 262144, 262144, 0, 0, 0, 1e-6, 1e4,
|
||||
{ { "model_type", "gemma4_unified" }, { "global_head_dim", "512" },
|
||||
{ "num_global_key_value_heads", "1" },
|
||||
{ "rope_parameters.full_attention.rope_theta", "1000000" },
|
||||
{ "vision_config.model_type", "gemma4_unified_vision" } } },
|
||||
{ "rope_parameters wins over rope_theta",
|
||||
R"({"model_type":"llama","rope_theta":10000,"rope_parameters":{"rope_theta":5000000}})",
|
||||
"llama", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1e-6, 5e6, {} },
|
||||
|
||||
+58
-2
@@ -455,11 +455,27 @@ TEST(prefill_interleave_takes_a_step_count_up_to_64) {
|
||||
Config d;
|
||||
REQUIRE_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK_EQ(d.prefill_interleave, 0);
|
||||
CHECK(!d.prefill_interleave_set); /* not given: bring-up serves auto:1 */
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "4" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.prefill_interleave, 4);
|
||||
CHECK(c.prefill_interleave_set);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "65" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "-1" }, &c), RAD_E_INVAL);
|
||||
/* auto sizes the hold from measured step costs (Scheduler::interleave_steps) */
|
||||
Config a;
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto" }, &a), RAD_OK);
|
||||
CHECK_EQ(a.prefill_interleave, -1);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "automatic" }, &c), RAD_E_INVAL);
|
||||
/* auto:SHARE gives decode-only steps SHARE of a chunk step's time, in (0, 4] */
|
||||
Config h;
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto:1" }, &h), RAD_OK);
|
||||
CHECK_EQ(h.prefill_interleave, -1);
|
||||
CHECK(h.prefill_interleave_share == 1.0);
|
||||
CHECK(a.prefill_interleave_share == 0.25);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto:0" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto:5" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--prefill-interleave", "auto:x" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* ================================================================== the table, the parser and the help agree
|
||||
@@ -507,7 +523,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--preempt-wait-ms", { "5000" } },
|
||||
{ "--max-num-seqs", { "4" } },
|
||||
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
|
||||
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
|
||||
{ "--gpu-memory-mib", { "16384" } }, { "--gpu-headroom-mib", { "128" } },
|
||||
{ "--kv-cache-dtype", { "fp8" } },
|
||||
{ "--state-cache-dtype", { "f16" } }, { "--attn-prefill-fp8", { "both" } },
|
||||
{ "--kv-resident", { "65536" } },
|
||||
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
|
||||
@@ -901,9 +918,28 @@ TEST(the_ngram_table_takes_a_directory_for_a_shared_ram_copy) {
|
||||
CHECK(s.ngram_placement == TablePlacement::Ram);
|
||||
CHECK(s.ngram_share_dir.empty());
|
||||
Config c;
|
||||
for (const char* bad : { "ram=", "vram=/tmp/x", "disk=/tmp/x", "auto=/tmp/x" })
|
||||
for (const char* bad : { "ram=", "disk=", "vram=/tmp/x", "auto=/tmp/x" })
|
||||
CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--embedding-placement", "ram=/tmp/x" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--embedding-placement", "disk=/tmp/x" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* disk=DIR is disk read from the table's own file in DIR (#130); it and ram=DIR replace each
|
||||
* other, and a plain placement drops both directories. */
|
||||
TEST(the_ngram_table_takes_a_directory_for_its_own_file_on_disk) {
|
||||
Config s;
|
||||
CHECK_EQ(parse({ "--ngram-placement", "disk=/mnt/optane" }, &s), RAD_OK);
|
||||
CHECK(s.ngram_placement == TablePlacement::Disk);
|
||||
CHECK_EQ(s.ngram_disk_dir, std::string("/mnt/optane"));
|
||||
CHECK(s.ngram_share_dir.empty());
|
||||
CHECK_EQ(parse({ "--ngram-placement", "disk=/mnt/optane", "--ngram-placement", "ram=/dev/shm" },
|
||||
&s), RAD_OK);
|
||||
CHECK(s.ngram_placement == TablePlacement::Ram);
|
||||
CHECK(s.ngram_disk_dir.empty());
|
||||
CHECK_EQ(s.ngram_share_dir, std::string("/dev/shm"));
|
||||
CHECK_EQ(parse({ "--ngram-placement", "disk=/mnt/optane", "--ngram-placement", "disk" }, &s),
|
||||
RAD_OK);
|
||||
CHECK(s.ngram_disk_dir.empty());
|
||||
}
|
||||
|
||||
/* --draft-window takes exactly two names; the default is kDraftWindowDefault, which the help text
|
||||
@@ -1387,6 +1423,26 @@ TEST(gpu_headroom_parses_under_both_spellings) {
|
||||
CHECK_EQ(d.gpu_headroom_mib, 96ll);
|
||||
}
|
||||
|
||||
/* --gpu-memory-mib is the inverse of --gpu-headroom-mib; they cannot be combined. The default
|
||||
* headroom is not "given", so memory alone is legal and leaves the default until the resolver. */
|
||||
TEST(gpu_memory_mib_parses_and_excludes_headroom) {
|
||||
Config a;
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "28000" }, &a), RAD_OK);
|
||||
CHECK_EQ(a.gpu_memory_mib, 28000ll);
|
||||
CHECK_EQ(a.gpu_headroom_mib, 96ll);
|
||||
CHECK(a.given.count("--gpu-memory-mib"));
|
||||
CHECK(!a.given.count("--gpu-headroom-mib"));
|
||||
|
||||
Config z;
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "0" }, &z), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "-1" }, &z), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "8x" }, &z), RAD_E_INVAL);
|
||||
|
||||
Config b, c;
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "28000", "--gpu-headroom-mib", "96" }, &b), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--gpu-memory-mib", "28000", "--gpu-headroom", "96" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_kernel_hierarchy_is_separated_by_commas_or_colons_and_ordered) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--kernels", "libr4d.so,libref.so" }, &c), RAD_OK);
|
||||
|
||||
@@ -615,6 +615,34 @@ TEST(lora_map_refusals_name_the_target_the_sums_or_the_flag) {
|
||||
CHECK(!exists(d / "c.rad"));
|
||||
}
|
||||
|
||||
/* A checkpoint tensor no declared weight reads is not written (a tower or head the plugin does not
|
||||
* know), and the run names it; a tensor beside one that is read (its scale) is not named, nor is
|
||||
* anything when every tensor is read. */
|
||||
TEST(a_checkpoint_tensor_no_weight_reads_is_named) {
|
||||
World& w = world();
|
||||
REQUIRE(w.ok);
|
||||
CHECK(w.log.find("read by no declared weight") == std::string::npos);
|
||||
tiny::TempDir d("convert_u");
|
||||
const std::string ck = d / "llama";
|
||||
REQUIRE(mkdir(ck.c_str(), 0755) == 0);
|
||||
for (const char* f : { "config.json", "tokenizer.json" })
|
||||
REQUIRE(copy_file(w.ckpt + "/" + f, ck + "/" + f));
|
||||
std::vector<tiny::Tensor> ts = tiny::read_safetensors(w.ckpt + "/model.safetensors");
|
||||
const size_t n = ts.size();
|
||||
ts.push_back({ "model.vision_embedder.patch_dense.weight", "BF16", { 4, 4 },
|
||||
std::vector<uint8_t>(32, 0) });
|
||||
ts.push_back({ "model.layers.0.mlp.down_proj.weight_scale", "BF16", { 1 },
|
||||
std::vector<uint8_t>(2, 0) });
|
||||
REQUIRE(tiny::write_safetensors(ck + "/model.safetensors", ts));
|
||||
std::string log;
|
||||
REQUIRE_EQ(convert(ck, { "-o", d / "u.rad", "--recipe", w.recipe }, &log), 0);
|
||||
const std::string want = "1 of " + std::to_string(n + 2) + " checkpoint tensors are read by no "
|
||||
"declared weight and are not written: model.vision_embedder.patch_dense.weight";
|
||||
if (log.find(want) == std::string::npos) fprintf(stderr, " log:\n%s\n", log.c_str());
|
||||
CHECK(log.find(want) != std::string::npos);
|
||||
CHECK(log.find("down_proj.weight_scale") == std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== --in-place */
|
||||
|
||||
/* Extending a container with nothing new keeps every weight at its offset, and the .pre-append
|
||||
|
||||
@@ -32,6 +32,7 @@ struct StatsScheduler : FakeScheduler {
|
||||
r.slot = 2;
|
||||
r.age_s = 4.5;
|
||||
r.ttft_s = 0.25;
|
||||
r.prefill_s = 0.20;
|
||||
r.decode_tps = 61.0;
|
||||
out->assign(1, r);
|
||||
return 1;
|
||||
@@ -221,6 +222,7 @@ TEST(stats_carries_the_engine_the_requests_and_the_snapshot) {
|
||||
CHECK_EQ(r.value("state", ""), std::string("decode"));
|
||||
CHECK_EQ(r.value("kv_tokens", (int64_t)0), (int64_t)960);
|
||||
CHECK_NEAR(r.value("ttft_s", -1.0), 0.25, 1e-12);
|
||||
CHECK_NEAR(r.value("prefill_s", -1.0), 0.20, 1e-12);
|
||||
REQUIRE(s["cards"].size() == 1);
|
||||
CHECK_EQ(s["cards"][0].value("name", ""), std::string("R9700"));
|
||||
REQUIRE(s["experts"]["tiers"].size() == (size_t)kTierCount);
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
/* Focused device/CPU DSpark differential. Build with hipcc, then pass libr4d.so.
|
||||
* This intentionally calls the real exported launchers, not the host SIMT emulator.
|
||||
* See docs/DSPARK-VALIDATION-WIP.md for a scoped invocation and its limitations. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <hip/hip_runtime.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static void check(bool b, const char* s) { if (!b) { std::fprintf(stderr, "FAIL %s\n", s); std::exit(1); } }
|
||||
static void hipcheck(hipError_t e) { if (e != hipSuccess) { std::fprintf(stderr, "HIP: %s\n", hipGetErrorString(e)); std::exit(1); } }
|
||||
static uint16_t bf(float f) { uint32_t x; std::memcpy(&x, &f, 4); x += 0x7fff + ((x >> 16) & 1); return x >> 16; }
|
||||
static float fb(uint16_t b) { uint32_t x = (uint32_t)b << 16; float f; std::memcpy(&f, &x, 4); return f; }
|
||||
template<class T> struct Device {
|
||||
T* p = nullptr; size_t n;
|
||||
explicit Device(const std::vector<T>& v): n(v.size()) { hipcheck(hipMalloc(&p, n*sizeof(T))); hipcheck(hipMemcpy(p, v.data(), n*sizeof(T), hipMemcpyHostToDevice)); }
|
||||
~Device() { (void)hipFree(p); }
|
||||
std::vector<T> get() { std::vector<T> v(n); hipcheck(hipMemcpy(v.data(), p, n*sizeof(T), hipMemcpyDeviceToHost)); return v; }
|
||||
};
|
||||
static RadTensor t(void* p, int dt, std::initializer_list<int64_t> sh) {
|
||||
RadTensor x{}; x.data=p; x.dtype=dt; x.rank=sh.size(); int i=0; for (auto d:sh) x.shape[i++]=d; rad_tensor_pack(&x); return x;
|
||||
}
|
||||
static RadParam pi(const char* k, long long v) { RadParam p{}; p.key=k; p.kind=RAD_P_INT; p.ival=v; return p; }
|
||||
static RadParam ps(const char* k, const char* v) { RadParam p{}; p.key=k; p.kind=RAD_P_STR; p.sval=v; return p; }
|
||||
static Fn symbol(void* h, const char* name) { auto f = reinterpret_cast<Fn>(dlsym(h,name)); check(f != nullptr, name); return f; }
|
||||
|
||||
static void markov(Fn fn, int R, bool f32) {
|
||||
constexpr int M=2, S=2, V=130, T=3, LP=137, SP=5, TP=7, OP=4;
|
||||
std::vector<uint16_t> l(M*S*LP,bf(0)), p(V*R,bf(0)), u(V*R,bf(0));
|
||||
for (int m=0;m<M;++m) for(int v=0;v<16;++v) l[(m*S)*LP+v]=bf(100-v);
|
||||
p[1*R]=bf(1); u[127*R]=bf(200); u[129*R]=bf(200);
|
||||
p[127*R+1]=bf(1); u[100*R+1]=bf(100);
|
||||
p[2*R+2]=bf(1); u[80*R+2]=bf(200);
|
||||
p[80*R+3]=bf(1); u[101*R+3]=bf(90);
|
||||
std::vector<int> anchor{1,-1,2,-1}, ti(M*TP,-777), out(M*OP,-777);
|
||||
std::vector<float> ts(M*SP,-777.f);
|
||||
std::vector<float> lf(l.size()); for(size_t i=0;i<l.size();++i) lf[i]=fb(l[i]);
|
||||
Device<uint16_t> dl(l), dp(p), du(u); Device<int> da(anchor), di(ti), dout(out);
|
||||
Device<float> ds(ts), dlf(lf);
|
||||
RadTensor a[]={t(f32 ? (void*)dlf.p : (void*)dl.p,f32 ? RAD_F32 : RAD_BF16,{M*S,V}),t(da.p,RAD_I32,{M,2}),t(dp.p,RAD_BF16,{V,R}),t(du.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(di.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,S})};
|
||||
a[0].stride[0]=LP; a[4].stride[0]=SP; a[5].stride[0]=TP; a[6].stride[0]=OP;
|
||||
RadParam par[]={pi("M",M),pi("steps",S),pi("rank",R),pi("n_vocab",V),pi("anchor_stride",2),ps("dtype","bf16")};
|
||||
RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=6;
|
||||
check(fn(&args,nullptr)==RAD_OK,"markov launch"); hipcheck(hipDeviceSynchronize());
|
||||
auto go=dout.get(); auto gs=ds.get(); auto gi=di.get();
|
||||
// Independent scalar oracle. Values are deliberately exactly representable so reduction order
|
||||
// cannot explain a discrepancy. Sequential conditioning and tile winners are both checked.
|
||||
for(int m=0;m<M;++m) { int prev=anchor[m*2];
|
||||
for(int s=0;s<S;++s) { float best=-INFINITY; int winner=0;
|
||||
for(int v=0;v<V;++v) { float score=fb(l[(m*S+s)*LP+v]);
|
||||
for(int r=0;r<R;++r) score+=fb(p[prev*R+r])*fb(u[v*R+r]);
|
||||
if(score>best) { best=score; winner=v; }
|
||||
}
|
||||
check(go[m*OP+s]==winner,"markov CPU winner"); prev=winner;
|
||||
}
|
||||
for(int tile=0;tile<T;++tile) { float best=-INFINITY; int win=tile*64; int prev_final=go[m*OP];
|
||||
for(int v=tile*64;v<std::min(V,(tile+1)*64);++v) { float score=fb(l[(m*S+1)*LP+v]);
|
||||
for(int r=0;r<R;++r) score+=fb(p[prev_final*R+r])*fb(u[v*R+r]);
|
||||
if(score>best) {best=score; win=v;}
|
||||
}
|
||||
check(gs[m*SP+tile]==best && gi[m*TP+tile]==win,"markov pitched tile oracle");
|
||||
}
|
||||
for(int i=T;i<SP;++i) check(gs[m*SP+i]==-777.f,"score row padding guard");
|
||||
for(int i=T;i<TP;++i) check(gi[m*TP+i]==-777,"token row padding guard");
|
||||
for(int i=S;i<OP;++i) check(go[m*OP+i]==-777,"output padding guard");
|
||||
}
|
||||
check(go[0]==127 && go[1]==100 && go[OP]==80 && go[OP+1]==101,"top16/tie/sequential controls");
|
||||
a[4].stride[1]=2; check(fn(&args,nullptr)!=RAD_OK,"reject non-unit scratch inner stride"); a[4].stride[1]=1;
|
||||
a[5].stride[0]=T-1; check(fn(&args,nullptr)!=RAD_OK,"reject overlapping scratch rows");
|
||||
a[5].stride[0]=LLONG_MAX; check(fn(&args,nullptr)!=RAD_OK,"reject overflowing scratch span");
|
||||
std::printf("markov logits=%s rank=%d padded scores=%d tokens=%d: PASS\n",f32?"f32":"bf16",R,SP,TP);
|
||||
}
|
||||
|
||||
// A controlled precision counterexample, not a measurement of real checkpoint logits.
|
||||
static void near_tie(Fn fn, Fn fn_f32) {
|
||||
constexpr int R=32, V=2;
|
||||
std::vector<uint16_t> l{bf(1.001f),bf(1.002f)}, w(V*R,bf(0));
|
||||
std::vector<int> anchor{0}, token{-1}, tile{-1}; std::vector<float> score{-1};
|
||||
check(l[0]==l[1],"near tie quantizes identically");
|
||||
Device<uint16_t> dl(l), dw(w); Device<int> da(anchor), dt(tile), dout(token); Device<float> ds(score);
|
||||
RadTensor a[]={t(dl.p,RAD_BF16,{1,V}),t(da.p,RAD_I32,{1}),t(dw.p,RAD_BF16,{V,R}),t(dw.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{1,1}),t(dt.p,RAD_I32,{1,1}),t(dout.p,RAD_I32,{1,1})};
|
||||
RadParam par[]={pi("steps",1),pi("rank",R),pi("n_vocab",V),pi("anchor_stride",1)};
|
||||
RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=4;
|
||||
check(fn(&args,nullptr)==RAD_OK,"near tie launch"); hipcheck(hipDeviceSynchronize());
|
||||
check(dout.get()[0]==0 && 1.002f>1.001f,"BF16/F32 near tie divergence");
|
||||
std::vector<float> full{1.001f,1.002f}; Device<float> df(full);
|
||||
a[0]=t(df.p,RAD_F32,{1,V});
|
||||
check(fn(&args,nullptr)!=RAD_OK,"BF16 op refuses F32 logits");
|
||||
check(fn_f32(&args,nullptr)==RAD_OK,"F32 near tie launch"); hipcheck(hipDeviceSynchronize());
|
||||
check(dout.get()[0]==1,"F32 near tie retains winner");
|
||||
a[0]=t(dl.p,RAD_BF16,{1,V});
|
||||
check(fn_f32(&args,nullptr)!=RAD_OK,"F32 op refuses BF16 logits");
|
||||
std::puts("near tie: F32 argmax=1, BF16 input argmax=0: PASS (synthetic)");
|
||||
}
|
||||
|
||||
// Real device head -> F32 Markov chain, with an exactly representable BF16-input near tie.
|
||||
static void head_chain(Fn head, Fn walk) {
|
||||
constexpr int K=8, V=2, R=32;
|
||||
std::vector<uint16_t> x(K,bf(0)), w(V*K,bf(0)), cb(V*R,bf(0));
|
||||
x[0]=bf(1); x[1]=bf(0.001953125f); w[0]=bf(1); w[K]=bf(1); w[K+1]=bf(1);
|
||||
std::vector<float> logits(V,-1), scores(1,-1);
|
||||
std::vector<int> anchor{0}, tile{-1}, out{-1};
|
||||
Device<uint16_t> dx(x), dw(w), dc(cb); Device<float> dl(logits), ds(scores);
|
||||
Device<int> da(anchor), dt(tile), dout(out);
|
||||
RadTensor h[]={t(dx.p,RAD_BF16,{1,K}),t(dw.p,RAD_BF16,{V,K}),t(dl.p,RAD_F32,{1,V})};
|
||||
RadParam hp[]={pi("M",1),pi("n_vocab",V),pi("n_embd",K),ps("dtype","bf16")};
|
||||
RadArgs ha{}; ha.t=h; ha.n_t=3; ha.p=hp; ha.n_p=4;
|
||||
check(head(&ha,nullptr)==RAD_OK,"F32 logits head launch"); hipcheck(hipDeviceSynchronize());
|
||||
auto got=dl.get(); check(got[0]==1.f && got[1]==1.001953125f,"F32 logits head CPU dot oracle");
|
||||
check(bf(got[0])==bf(got[1]),"head-chain BF16 negative control");
|
||||
RadTensor a[]={t(dl.p,RAD_F32,{1,V}),t(da.p,RAD_I32,{1}),t(dc.p,RAD_BF16,{V,R}),t(dc.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{1,1}),t(dt.p,RAD_I32,{1,1}),t(dout.p,RAD_I32,{1,1})};
|
||||
RadParam par[]={pi("M",1),pi("steps",1),pi("rank",R),pi("n_vocab",V),ps("dtype","bf16")};
|
||||
RadArgs args{}; args.t=a; args.n_t=7; args.p=par; args.n_p=5;
|
||||
check(walk(&args,nullptr)==RAD_OK,"head-chain walk launch"); hipcheck(hipDeviceSynchronize());
|
||||
check(dout.get()[0]==1,"F32 head-chain winner");
|
||||
std::puts("F32 head -> Markov near tie and BF16 negative control: PASS");
|
||||
}
|
||||
|
||||
static void attention(Fn shared, Fn ordinary, int G, int ctx0, int ctx1, int causal) {
|
||||
constexpr int M=2, Q=7, H=256, BS=16, W=513;
|
||||
const int ctx[M]={ctx0,ctx1}, blocks=(std::max(ctx0,ctx1)+15)/16, nblocks=M*blocks;
|
||||
std::vector<uint16_t> q(M*Q*G*H,bf(0)), kv((size_t)nblocks*BS*2*H,bf(0)), out(M*Q*G*H,bf(0));
|
||||
std::vector<int> bt(M*blocks), su{ctx0,ctx1}, cu{0,Q,2*Q};
|
||||
// Reverse physical pages: the oracle must consult block_table rather than logical positions.
|
||||
for(int s=0;s<M;++s) for(int b=0;b<blocks;++b) bt[s*blocks+b]=nblocks-1-(s*blocks+b);
|
||||
for(int s=0;s<M;++s) for(int j=0;j<ctx[s];++j) {
|
||||
size_t base=((size_t)bt[s*blocks+j/BS]*BS+j%BS)*2*H;
|
||||
kv[base]=bf((j%5-2)*0.25f);
|
||||
float v=(j%7-3)*0.25f;
|
||||
int anchor=ctx[s]-Q;
|
||||
if(j==anchor-W) v=512;
|
||||
if(j==anchor-W+1) v=64;
|
||||
if(j==ctx[s]-1) v=256;
|
||||
kv[base+H]=bf(v);
|
||||
}
|
||||
for(int row=0;row<M*Q;++row) for(int h=0;h<G;++h) q[((row*G+h)*H)]=bf(h%2 ? -1.f : 1.f);
|
||||
Device<uint16_t> dq(q), dk(kv), dout(out); Device<int> db(bt), ds(su), dc(cu);
|
||||
RadTensor a[]={t(dq.p,RAD_BF16,{M*Q,G,H}),t(dk.p,RAD_BF16,{nblocks,1,BS,2*H}),
|
||||
t(db.p,RAD_I32,{M,blocks}),t(ds.p,RAD_I32,{M}),RadTensor{},RadTensor{},
|
||||
t(dc.p,RAD_I32,{M+1}),t(dout.p,RAD_BF16,{M*Q,G,H})};
|
||||
RadParam par[]={pi("q_len",Q),pi("head_dim",H),pi("gqa",G),pi("block_size",BS),
|
||||
pi("causal",causal),pi("window",W),pi("n_head",G),pi("max_seqs",M),
|
||||
ps("q_dtype","bf16"),ps("kv_dtype","bf16")};
|
||||
RadArgs args{}; args.t=a; args.n_t=8; args.p=par; args.n_p=10;
|
||||
check(shared(&args,nullptr)==RAD_OK,"shared anchor attention launch"); hipcheck(hipDeviceSynchronize());
|
||||
auto got=dout.get(); std::vector<double> expected(M*Q*G);
|
||||
for(int s=0;s<M;++s) for(int row=0;row<Q;++row) for(int h=0;h<G;++h) {
|
||||
int anchor=ctx[s]-Q, lo=std::max(0,anchor-W+1), hi=causal?anchor+1:ctx[s];
|
||||
double sum=0, acc=0;
|
||||
for(int j=lo;j<hi;++j) {
|
||||
size_t base=((size_t)bt[s*blocks+j/BS]*BS+j%BS)*2*H;
|
||||
double weight=std::exp((h%2?-1.:1.)*fb(kv[base])/16.0);
|
||||
sum+=weight; acc+=weight*fb(kv[base+H]);
|
||||
}
|
||||
double want=acc/sum; size_t i=(s*Q+row)*G+h;
|
||||
expected[i]=want;
|
||||
check(std::abs(fb(got[i*H])-want)<0.012,"attention scalar oracle");
|
||||
check(fb(got[i*H+1])==0,"attention zero channel");
|
||||
}
|
||||
// The ordinary per-query window must fail this fixture; this guards against a vacuous test.
|
||||
check(ordinary(&args,nullptr)==RAD_OK,"ordinary attention negative control launch");
|
||||
hipcheck(hipDeviceSynchronize()); auto wrong=dout.get(); bool distinguished=false;
|
||||
for(size_t i=0;i<expected.size();++i)
|
||||
if(std::abs(fb(wrong[i*H])-expected[i])>0.03) distinguished=true;
|
||||
check(distinguished,"attention per-row window negative control");
|
||||
std::printf("attention gqa=%d ctx=%d,%d causal=%d shared oracle and negative control: PASS\n",G,ctx0,ctx1,causal);
|
||||
}
|
||||
|
||||
// Real checkpoint head slice, but synthetic BF16 activations and zero Markov weights. This tests
|
||||
// head arithmetic, not full-graph/reference equivalence or real hidden-state acceptance.
|
||||
static void checkpoint_head(Fn head, Fn walk, const char* weights_path) {
|
||||
constexpr int M=16, V=1025, K=2560, R=32, T=(V+63)/64;
|
||||
std::vector<uint16_t> w((size_t)V*K), x((size_t)M*K), cb((size_t)V*R,bf(0));
|
||||
std::ifstream f(weights_path,std::ios::binary); check((bool)f,"open checkpoint head slice");
|
||||
f.read(reinterpret_cast<char*>(w.data()),w.size()*sizeof(uint16_t));
|
||||
check((size_t)f.gcount()==w.size()*sizeof(uint16_t) && f.peek()==EOF,"exact head slice size");
|
||||
uint32_t rng=123456789; for(auto& v:x) { rng=rng*1664525u+1013904223u; v=bf(((int)(rng>>24)-128)/128.f); }
|
||||
std::vector<float> logits((size_t)M*V,0), scores((size_t)M*T,0);
|
||||
std::vector<int> anchor(M,0), tile((size_t)M*T,-1), out(M,-1);
|
||||
Device<uint16_t> dx(x), dw(w), dc(cb); Device<float> dl(logits), ds(scores);
|
||||
Device<int> da(anchor), dt(tile), dout(out);
|
||||
RadTensor h[]={t(dx.p,RAD_BF16,{M,K}),t(dw.p,RAD_BF16,{V,K}),t(dl.p,RAD_F32,{M,V})};
|
||||
RadParam hp[]={pi("M",M),pi("n_vocab",V),pi("n_embd",K),ps("dtype","bf16")};
|
||||
RadArgs ha{}; ha.t=h; ha.n_t=3; ha.p=hp; ha.n_p=4;
|
||||
check(head(&ha,nullptr)==RAD_OK,"checkpoint head launch"); hipcheck(hipDeviceSynchronize());
|
||||
auto got=dl.get(); double maxerr=0, se=0, sr=0, minmargin=INFINITY; int changed=0,ties=0;
|
||||
std::vector<int> refwin(M);
|
||||
for(int m=0;m<M;++m) { double best=-INFINITY, second=-INFINITY; int winner=0;
|
||||
for(int v=0;v<V;++v) { double ref=0; for(int k=0;k<K;++k) ref+=(double)fb(x[m*K+k])*fb(w[(size_t)v*K+k]);
|
||||
double err=std::abs(got[(size_t)m*V+v]-ref); maxerr=std::max(maxerr,err); se+=err*err; sr+=ref*ref;
|
||||
check(std::isfinite(got[(size_t)m*V+v]),"finite checkpoint head logits");
|
||||
if(ref>best) {second=best;best=ref;winner=v;} else if(ref>second) second=ref;
|
||||
}
|
||||
refwin[m]=winner; minmargin=std::min(minmargin,best-second);
|
||||
int gw=0,bw=0,nmax=0; float gmax=-INFINITY, bmax=-INFINITY;
|
||||
for(int v=0;v<V;++v) {float y=got[(size_t)m*V+v], by=fb(bf(y));
|
||||
if(y>gmax) {gmax=y;gw=v;} if(by>bmax) {bmax=by;bw=v;nmax=1;} else if(by==bmax) ++nmax;
|
||||
}
|
||||
if(gw!=bw) ++changed; if(nmax>1) ++ties;
|
||||
check(gw==winner,"checkpoint head F32 top1 versus FP64 oracle");
|
||||
}
|
||||
RadTensor a[]={t(dl.p,RAD_F32,{M,V}),t(da.p,RAD_I32,{M}),t(dc.p,RAD_BF16,{V,R}),t(dc.p,RAD_BF16,{V,R}),t(ds.p,RAD_F32,{M,T}),t(dt.p,RAD_I32,{M,T}),t(dout.p,RAD_I32,{M,1})};
|
||||
RadParam p[]={pi("M",M),pi("steps",1),pi("rank",R),pi("n_vocab",V),ps("dtype","bf16")};
|
||||
RadArgs args{};args.t=a;args.n_t=7;args.p=p;args.n_p=5;
|
||||
check(walk(&args,nullptr)==RAD_OK,"checkpoint head walk"); hipcheck(hipDeviceSynchronize());
|
||||
auto picks=dout.get(); for(int m=0;m<M;++m) check(picks[m]==refwin[m],"checkpoint F32 chain top1");
|
||||
std::printf("real head slice V=%d K=%d synthetic rows=%d: max_abs=%.9g rel_l2=%.9g min_top_margin=%.9g F32_vs_FP64_top1_mismatch=0 BF16_rounded_top1_changed=%d BF16_top_ties=%d\n",V,K,M,maxerr,std::sqrt(se/sr),minmargin,changed,ties);
|
||||
}
|
||||
|
||||
int main(int argc,char** argv) {
|
||||
check(argc==2 || (argc==4 && !std::strcmp(argv[2],"--head-weights")),"usage: dspark_device_test libr4d.so [--head-weights file]");
|
||||
int n_devices = 0;
|
||||
if (hipGetDeviceCount(&n_devices) != hipSuccess || n_devices == 0) return 77;
|
||||
void* h=dlopen(argv[1],RTLD_NOW|RTLD_LOCAL);
|
||||
if(!h) { std::fprintf(stderr,"dlopen: %s\n",dlerror()); return 1; }
|
||||
Fn fn=symbol(h,"r4d_rad_dflash_markov_greedy");
|
||||
Fn fn_f32=symbol(h,"r4d_rad_dflash_markov_greedy_f32");
|
||||
if(argc==4) { checkpoint_head(symbol(h,"r4d_rad_logits_gemm"),fn_f32,argv[3]); dlclose(h); return 0; }
|
||||
for(int r:{32,64,128,512}) { markov(fn,r,false); markov(fn_f32,r,true); }
|
||||
near_tie(fn,fn_f32);
|
||||
head_chain(symbol(h,"r4d_rad_logits_gemm"),fn_f32);
|
||||
for(int g:{1,2}) {
|
||||
const char* shared=g==1?"r4d_rad_attn_anchor_window_h256_gqa1_bf16kv":"r4d_rad_attn_anchor_window_h256_gqa2_bf16kv";
|
||||
const char* ordinary=g==1?"r4d_rad_attn_window_h256_gqa1_bf16":"r4d_rad_attn_window_h256_gqa2_bf16";
|
||||
for(int causal:{0,1}) {
|
||||
attention(symbol(h,shared),symbol(h,ordinary),g,520,1049,causal);
|
||||
attention(symbol(h,shared),symbol(h,ordinary),g,521,1050,causal);
|
||||
}
|
||||
}
|
||||
dlclose(h); std::puts("DSpark device differential: PASS");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract a read-only BF16 head slice for dspark_device_test --head-weights.
|
||||
|
||||
The device probe expects the first 1025 rows of a [131072, 2560] BF16 embedding.
|
||||
Output is created exclusively, never overwriting an existing artifact or model.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("safetensors", type=Path)
|
||||
p.add_argument("output", type=Path)
|
||||
args = p.parse_args()
|
||||
with args.safetensors.open("rb") as f:
|
||||
raw = f.read(8)
|
||||
if len(raw) != 8:
|
||||
raise ValueError("short safetensors header")
|
||||
n = struct.unpack("<Q", raw)[0]
|
||||
if n > 100_000_000:
|
||||
raise ValueError("unreasonably large safetensors header")
|
||||
header = json.loads(f.read(n))
|
||||
t = header["model.embedding.weight"]
|
||||
if t["dtype"] != "BF16" or t["shape"] != [131072, 2560]:
|
||||
raise ValueError("expected Spark BF16 embedding [131072, 2560]")
|
||||
start, end = t["data_offsets"]
|
||||
size = 1025 * 2560 * 2
|
||||
if end - start < size:
|
||||
raise ValueError("short tensor")
|
||||
f.seek(8 + n + start)
|
||||
data = f.read(size)
|
||||
if len(data) != size:
|
||||
raise ValueError("short read")
|
||||
with args.output.open("xb") as f:
|
||||
f.write(data)
|
||||
print(f"{args.safetensors}: model.embedding.weight rows 0..1024; "
|
||||
f"bytes={len(data)} sha256={hashlib.sha256(data).hexdigest()} -> {args.output}")
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host unit tests for the DSpark QoS harness's evidence checks (no server/GPU)."""
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
path = Path(__file__).resolve().parents[1] / "scripts" / "dspark_qos_regression.py"
|
||||
spec = importlib.util.spec_from_file_location("dspark_qos", path)
|
||||
qos = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(qos)
|
||||
|
||||
|
||||
class HarnessChecks(unittest.TestCase):
|
||||
def test_counter_delta_requires_both_samples_and_rejects_reset(self):
|
||||
self.assertEqual(qos.metric_delta({"x": 4}, {"x": 7}, "x"), 3)
|
||||
for before, after in (({}, {"x": 7}), ({"x": 4}, {}), ({"x": 7}, {"x": 4})):
|
||||
with self.assertRaises(qos.HarnessError):
|
||||
qos.metric_delta(before, after, "x")
|
||||
|
||||
def test_calibration_brackets_safely_then_finds_largest_prompt(self):
|
||||
seen = []
|
||||
phrase = "rollover-boundary marker "
|
||||
def fake(_base, _model, messages, **_options):
|
||||
count = len(messages[0]["content"]) // len(phrase)
|
||||
seen.append(count)
|
||||
if count > 64:
|
||||
raise AssertionError("calibration overflowed a short server context")
|
||||
return {"prompt_tokens": 10 + count * 3}
|
||||
with patch.object(qos, "chat_request", side_effect=fake):
|
||||
prompt, tokens = qos.calibrated_rollover_prompt("", "", None, 1, target=100)
|
||||
self.assertEqual(len(prompt) // len(phrase), 30)
|
||||
self.assertEqual(tokens, 100)
|
||||
self.assertEqual(seen[:5], [1, 2, 4, 8, 16])
|
||||
self.assertLessEqual(max(seen), 32)
|
||||
|
||||
def test_missing_usage_refuses_calibration(self):
|
||||
with patch.object(qos, "chat_request", return_value={}):
|
||||
with self.assertRaises(qos.HarnessError):
|
||||
qos.calibrated_rollover_prompt("", "", None, 1)
|
||||
|
||||
def test_stream_first_event_is_not_first_text(self):
|
||||
event_only = b'data: {"choices":[{"delta":{"role":"assistant"}}]}\n\ndata: [DONE]\n\n'
|
||||
with patch.object(qos, "fetch", return_value=io.BytesIO(event_only)):
|
||||
r = qos.stream_request("", "", "test", api_key=None, timeout=1)
|
||||
self.assertEqual(r["events"], 1)
|
||||
self.assertIsNotNone(r["first_event_s"])
|
||||
self.assertIsNone(r["first_text_s"])
|
||||
reasoning = b'data: {"choices":[{"delta":{"reasoning_content":"think"}}]}\n\ndata: [DONE]\n\n'
|
||||
with patch.object(qos, "fetch", return_value=io.BytesIO(reasoning)):
|
||||
r = qos.stream_request("", "", "test", api_key=None, timeout=1)
|
||||
self.assertIsNotNone(r["first_text_s"])
|
||||
|
||||
def test_draft_token_total_reports_observed_trials(self):
|
||||
self.assertEqual(qos.observed_draft_token_total([{"draft_tokens": 168}, {"draft_tokens": 189}]), 357)
|
||||
self.assertEqual(qos.observed_draft_token_total([]), 0)
|
||||
|
||||
def test_seeded_repeat_requires_nonempty_matching_content_and_usage(self):
|
||||
sample = {"content": "A bright comet crosses the sky.", "finish_reason": "stop",
|
||||
"completion_tokens": 7}
|
||||
self.assertTrue(qos.seeded_sample_reproduced(sample, dict(sample)))
|
||||
for first, repeat in (
|
||||
({**sample, "content": ""}, {**sample, "content": ""}),
|
||||
({**sample, "content": " "}, {**sample, "content": " "}),
|
||||
(sample, {**sample, "content": "A different comet."}),
|
||||
(sample, {**sample, "finish_reason": "length"}),
|
||||
(sample, {**sample, "completion_tokens": 8}),
|
||||
(sample, {**sample, "completion_tokens": 7.0}),
|
||||
(sample, {**sample, "completion_tokens": None}),
|
||||
({**sample, "completion_tokens": 1}, {**sample, "completion_tokens": True}),
|
||||
({**sample, "finish_reason": None}, {**sample, "finish_reason": None}),
|
||||
):
|
||||
with self.subTest(first=first, repeat=repeat):
|
||||
self.assertFalse(qos.seeded_sample_reproduced(first, repeat))
|
||||
|
||||
def test_chat_request_forwards_reasoning_effort(self):
|
||||
payload = {"choices": [{"finish_reason": "stop", "message": {"content": "OK"}}],
|
||||
"usage": {"completion_tokens": 1}}
|
||||
with patch.object(qos, "fetch", return_value=io.BytesIO(json.dumps(payload).encode())) as fetch:
|
||||
result = qos.chat_request("http://localhost", "spark", [{"role": "user", "content": "test"}],
|
||||
api_key=None, timeout=1, reasoning_effort="none")
|
||||
self.assertEqual(result["content"], "OK")
|
||||
sent = json.loads(fetch.call_args.kwargs["data"])
|
||||
self.assertEqual(sent["reasoning_effort"], "none")
|
||||
|
||||
def test_stop_requires_control_and_exact_prefix(self):
|
||||
marker = "STOP"
|
||||
stopped = {"finish_reason": "stop", "content": "prefix "}
|
||||
self.assertTrue(qos.stop_sequence_observed({"content": "prefix STOP after"}, stopped, marker))
|
||||
self.assertFalse(qos.stop_sequence_observed({"content": "prefix "}, stopped, marker))
|
||||
self.assertFalse(qos.stop_sequence_observed({"content": "prefix STOP"},
|
||||
{"finish_reason": "length", "content": "prefix "}, marker))
|
||||
self.assertFalse(qos.stop_sequence_observed({"content": "prefix STOP"},
|
||||
{"finish_reason": "stop", "content": "other"}, marker))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -85,9 +85,12 @@ std::vector<std::string> serving_argv(const std::string& model,
|
||||
}
|
||||
|
||||
/* The shape the preemption cases run in: four sequences of at most 512 tokens, 256 a step. Their
|
||||
* small KV pool comes from a small device, whose size small_device() finds. */
|
||||
* small KV pool comes from a small device, whose size small_device() finds. --prefill-interleave 0
|
||||
* pins the schedule these cases are sized for: the bring-up default auto:1 follows measured step
|
||||
* times, so on a loaded host the four sequences may never overlap enough to preempt. */
|
||||
std::vector<std::string> small_pool_args() {
|
||||
return { "--max-num-seqs", "4", "--max-num-batched-tokens", "256", "--max-model-len", "512" };
|
||||
return { "--max-num-seqs", "4", "--max-num-batched-tokens", "256", "--max-model-len", "512",
|
||||
"--prefill-interleave", "0" };
|
||||
}
|
||||
std::vector<std::string> device_env(int device_mib) {
|
||||
return { "RADIANCE_HOST_VRAM_MIB=" + std::to_string(device_mib) };
|
||||
|
||||
@@ -1240,6 +1240,52 @@ TEST(a_weight_tables_experts_are_drawn_from_its_encoding) {
|
||||
CHECK(via_draw == cb);
|
||||
}
|
||||
|
||||
/* A kernel that lays out its experts (libr4d's 4-bit tables) is handed each expert's arrangement of
|
||||
* the planes kf_draw_table decodes, stacked one laid expert apart; a kernel with no layout reads the
|
||||
* decoded table, and a layout that changes an expert's size cannot be stacked. */
|
||||
TEST(a_weight_tables_experts_are_each_laid_out_by_the_kernel) {
|
||||
KfOperand codes = fp8_weight(128, 256, { "codes" });
|
||||
codes.role = RAD_OPD_WTAB;
|
||||
codes.shape.insert(codes.shape.begin(), 3);
|
||||
const KfEntryPlanes drawn = [&](int64_t e, std::vector<std::vector<uint8_t>>* pl) {
|
||||
kf_draw_entry_planes(codes, 2, e, pl);
|
||||
return (int)RAD_OK;
|
||||
};
|
||||
RadKernelInfo ki{};
|
||||
RadLayout lay{};
|
||||
std::vector<uint8_t> out;
|
||||
CHECK_EQ(kf_lay_table(&ki, nullptr, 0, 2, codes, drawn, &lay, &out), RAD_E_UNSUPPORTED);
|
||||
ki.layout = lay_identity;
|
||||
CHECK_EQ(kf_lay_table(&ki, nullptr, 0, 2, codes, drawn, &lay, &out), RAD_E_UNSUPPORTED);
|
||||
ki.layout = lay_reverse;
|
||||
ki.relayout = relay_reverse;
|
||||
REQUIRE_EQ(kf_lay_table(&ki, nullptr, 0, 2, codes, drawn, &lay, &out), RAD_OK);
|
||||
const size_t per = (size_t)128 * 256;
|
||||
REQUIRE_EQ(out.size(), 3 * per);
|
||||
CHECK_EQ(lay.bytes, (int64_t)per);
|
||||
std::vector<std::vector<uint8_t>> pl;
|
||||
for (int64_t e = 0; e < 3; ++e) {
|
||||
kf_draw_entry_planes(codes, 2, e, &pl);
|
||||
CHECK(std::equal(out.begin() + (long)(per * e), out.begin() + (long)(per * (e + 1)),
|
||||
pl[0].rbegin()));
|
||||
}
|
||||
/* The entries the kernel reads are the ones the oracle decodes. */
|
||||
std::vector<uint8_t> logical;
|
||||
std::string why;
|
||||
REQUIRE_EQ(kf_draw_table(codes, 2, &logical, &why), RAD_OK);
|
||||
kf_draw_entry_planes(codes, 2, 1, &pl);
|
||||
CHECK(std::equal(logical.begin() + (long)per, logical.begin() + (long)(2 * per),
|
||||
pl[0].begin()));
|
||||
/* Laid out to a size the declared expert does not stride by. */
|
||||
ki.layout = [](const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor* t, int, RadLayout* o) {
|
||||
o->dtype = t[0].dtype;
|
||||
o->bytes = rad_dtype_bytes(t[0].dtype, t[0].shape[0] * t[0].shape[1]) + 256;
|
||||
return (int)RAD_OK;
|
||||
};
|
||||
CHECK_EQ(kf_lay_table(&ki, nullptr, 0, 2, codes, drawn, &lay, &out), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* ================================================================== routing */
|
||||
|
||||
/* moe_scatter's offsets are a prefix array: non-decreasing from 0 to the row count. A uniform draw
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fcntl.h>
|
||||
#include <fstream>
|
||||
#include <functional>
|
||||
#include <signal.h>
|
||||
#include <string>
|
||||
@@ -26,6 +27,7 @@
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -453,6 +455,70 @@ TEST(a_table_copied_into_locked_memory_is_the_mapping_byte_for_byte) {
|
||||
f.close();
|
||||
}
|
||||
|
||||
/* --ngram-placement disk=DIR (#130): the first open fills the table's own file from the container,
|
||||
* renamed into place whole; the mapping holds the container's bytes and is that file's (the disk
|
||||
* gather finds the file behind its mapping); a second open reuses it unfilled; a file that is not
|
||||
* this table is refused rather than served. */
|
||||
TEST(a_table_file_on_another_disk_is_filled_once_and_mapped_in_place_of_the_container) {
|
||||
const std::string p = radtest::tmp_path("tfile");
|
||||
RadWriter w;
|
||||
REQUIRE(w.begin(p.c_str()) >= 0);
|
||||
w.set_arch("radtest");
|
||||
const RadWriter::Weight x = mkw("ngram.weight", plain_bf16(), 1500, 999, -1, -1, 0);
|
||||
const Planes want = planes_of(x, 7);
|
||||
REQUIRE(w.add_weight(x, want.ptr.data()) >= 0);
|
||||
REQUIRE(w.finish() >= 0);
|
||||
RadFile f;
|
||||
REQUIRE(f.open(p.c_str()) >= 0);
|
||||
const RadFilePlane& pl = f.plane(*f.find("ngram.weight"), 0);
|
||||
const uint8_t* src = f.data(pl);
|
||||
const int64_t n = (int64_t)pl.bytes;
|
||||
const std::string tab = radtest::tmp_path("tfile-table");
|
||||
::unlink(tab.c_str());
|
||||
|
||||
TableCopy a;
|
||||
bool filled = false;
|
||||
std::string why;
|
||||
REQUIRE_EQ(table_file_open(f, src, n, (int64_t)pl.offset, tab, &a, &filled, &why), (int)RAD_OK);
|
||||
CHECK(filled);
|
||||
CHECK_EQ(a.bytes, (size_t)n);
|
||||
CHECK(std::memcmp(a.base, src, (size_t)n) == 0);
|
||||
CHECK(::access((tab + ".part").c_str(), F_OK) != 0);
|
||||
/* The mapping is the file's, as /proc/self/maps names it. */
|
||||
{
|
||||
std::ifstream maps("/proc/self/maps");
|
||||
bool backed = false;
|
||||
for (std::string line; std::getline(maps, line);) {
|
||||
unsigned long long lo = 0, hi = 0;
|
||||
if (std::sscanf(line.c_str(), "%llx-%llx", &lo, &hi) != 2) continue;
|
||||
if ((uintptr_t)a.base >= lo && (uintptr_t)a.base < hi)
|
||||
backed = line.size() >= tab.size() && line.compare(line.size() - tab.size(), tab.size(), tab) == 0;
|
||||
}
|
||||
CHECK(backed);
|
||||
}
|
||||
::munmap(a.base, a.bytes);
|
||||
|
||||
TableCopy b;
|
||||
REQUIRE_EQ(table_file_open(f, src, n, (int64_t)pl.offset, tab, &b, &filled, &why), (int)RAD_OK);
|
||||
CHECK(!filled);
|
||||
CHECK(std::memcmp(b.base, src, (size_t)n) == 0);
|
||||
::munmap(b.base, b.bytes);
|
||||
|
||||
/* Same size, other bytes: refused, and left for the operator to remove. */
|
||||
{
|
||||
std::fstream t(tab, std::ios::in | std::ios::out | std::ios::binary);
|
||||
t.seekp(0);
|
||||
const char junk[16] = "not the table..";
|
||||
t.write(junk, sizeof junk);
|
||||
}
|
||||
TableCopy c;
|
||||
CHECK_EQ(table_file_open(f, src, n, (int64_t)pl.offset, tab, &c, &filled, &why), (int)RAD_E_IO);
|
||||
CHECK(c.base == nullptr);
|
||||
CHECK(why.find("does not match") != std::string::npos);
|
||||
::unlink(tab.c_str());
|
||||
f.close();
|
||||
}
|
||||
|
||||
/* --ngram-placement ram=DIR: the first holder to open the file fills it, a later one finds it
|
||||
* ready (a second descriptor in one process is a second holder, since flock locks belong to the
|
||||
* open file description), and the file goes when the last holder leaves. A file whose header is
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/* gemma4u_golden.h -- GENERATED by mkgemma4ugolden.py from transformers 5.15.0; do not edit. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
struct GoldGemma4uPic { int32_t f, h, w, budget, grid_h, grid_w, soft; uint64_t fnv; uint16_t head[8]; };
|
||||
static const GoldGemma4uPic kGoldGemma4uPics[] = {
|
||||
{ 2, 336, 480, 70, 7, 10, 70, 0x24f3317a5fdef4e5ull, { 16238, 16186, 16218, 16199, 16083, 15857, 16213, 16219 } },
|
||||
{ 6, 432, 672, 140, 9, 14, 126, 0x1f2f65633d037b7dull, { 15929, 16244, 16077, 16212, 15665, 16130, 15985, 15993 } },
|
||||
};
|
||||
static const int32_t kGoldGemma4uClipFrames[] = { 4, 5, 6 };
|
||||
static const int32_t kGoldGemma4uClipH = 336, kGoldGemma4uClipW = 432, kGoldGemma4uClipGridH = 7, kGoldGemma4uClipGridW = 9, kGoldGemma4uClipSoft = 63;
|
||||
static const uint64_t kGoldGemma4uClipFnv = 0xfee282f9d3bab92bull;
|
||||
static const int32_t kGoldGemma4uAudioN = 16037, kGoldGemma4uAudioFrames = 26;
|
||||
static const uint64_t kGoldGemma4uAudioFnv = 0x27a5cc012ee3ad6dull;
|
||||
@@ -258,4 +258,31 @@ TEST(gen_config_reads_the_ngram_ban) {
|
||||
CHECK_EQ(greedy.onto(SamplingParams{}).ngram_ban_n, 0);
|
||||
}
|
||||
|
||||
TEST(gen_config_reads_suppress_tokens) {
|
||||
/* Gemma 4's generation_config.json: the end-of-image and end-of-audio markers. */
|
||||
GenSampling g;
|
||||
CHECK(gen_sampling_parse(R"({"temperature": 1.0, "suppress_tokens": [258883, 258882]})",
|
||||
"test", &g));
|
||||
CHECK_EQ((int)g.suppress.size(), 2);
|
||||
CHECK_EQ(g.suppress[0], 258883);
|
||||
CHECK_EQ(g.suppress[1], 258882);
|
||||
const SamplingParams sp = g.onto(SamplingParams{});
|
||||
CHECK_EQ((int)sp.suppress_tokens.size(), 2);
|
||||
CHECK(SamplingParams{}.suppress_tokens.empty());
|
||||
|
||||
/* The container's flattened copy: the array as a space-separated string. */
|
||||
GenSampling kv;
|
||||
CHECK(gen_sampling_from_kv(kv_of({ { "suppress_tokens", "258883 258882" } }), &kv));
|
||||
CHECK_EQ((int)kv.suppress.size(), 2);
|
||||
CHECK_EQ(kv.suppress[1], 258882);
|
||||
|
||||
/* An entry that is no id is dropped on its own, and a non-array is dropped whole. */
|
||||
GenSampling bad;
|
||||
CHECK(gen_sampling_parse(R"({"top_k": 64, "suppress_tokens": [7, -1, "x", 9]})", "test", &bad));
|
||||
CHECK_EQ((int)bad.suppress.size(), 2);
|
||||
GenSampling flat;
|
||||
CHECK(gen_sampling_parse(R"({"top_k": 64, "suppress_tokens": 7})", "test", &flat));
|
||||
CHECK(flat.suppress.empty());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+314
-66
@@ -611,8 +611,12 @@ TEST(
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11);
|
||||
// Two rows stay under the split threshold: 42 routers and 11 index heads, replicated.
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53);
|
||||
// Two rows stay under the split threshold, and their history fits the selection
|
||||
// (DsaCache::takes_all): the 42 routers run, the 11 index heads and scorers do not.
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 42);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "dsa_query"), 0);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "dsa_score"), 0);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "qsa_select"), 11);
|
||||
CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0);
|
||||
// The split is declared on every rank whatever its step size; only rank 0 issues it here.
|
||||
const bool split = world > 1;
|
||||
@@ -661,6 +665,21 @@ TEST(
|
||||
batch.out_ids = &last;
|
||||
batch.draft_pass = 0;
|
||||
batch.max_q_len = 512;
|
||||
{
|
||||
// 512 rows whose history fits the selection: the indexer takes every
|
||||
// block and does not split, so no index head runs and nothing of its is
|
||||
// gathered, while the routers, mHC reads and MLA still split.
|
||||
ctx.issues.clear();
|
||||
glm5next::step(&ctx, &batch);
|
||||
CHECK(ctx.step_fail.empty());
|
||||
const auto fit_ops = issued_ops(b, ctx);
|
||||
CHECK_EQ(std::count(fit_ops.begin(), fit_ops.end(), "gemm_nt_f32"), 42);
|
||||
CHECK_EQ(std::count(fit_ops.begin(), fit_ops.end(), "dsa_score"), 0);
|
||||
CHECK_EQ(std::count(fit_ops.begin(), fit_ops.end(), "qsa_select"), 11);
|
||||
CHECK_EQ(std::count(fit_ops.begin(), fit_ops.end(), "all_gather"),
|
||||
world > 1 ? 42 + 90 + 11 : 0);
|
||||
}
|
||||
batch.max_ctx_len = 3000; // live blocks past the top-k: the indexer scores
|
||||
ctx.issues.clear();
|
||||
glm5next::step(&ctx, &batch);
|
||||
CHECK(ctx.step_fail.empty());
|
||||
@@ -668,7 +687,7 @@ TEST(
|
||||
// 512 rows reach the split: each router runs on its column slice, each mHC
|
||||
// read on its chunks, each indexer, its head gates included, on its run
|
||||
// of query rows, and each MLA on its run of rows, all gathered but the
|
||||
// gates; at TP1 nothing changes.
|
||||
// gates. At TP1 the step does not split, and the indexer scores whole.
|
||||
const auto long_ops = issued_ops(b, ctx);
|
||||
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53);
|
||||
CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"),
|
||||
@@ -801,8 +820,39 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
|
||||
CHECK_EQ(b.bufs[w.selected - 1].d.shape[0], world * most);
|
||||
CHECK_EQ(b.bufs[w.codes - 1].d.shape[0], world * most * 32);
|
||||
CHECK_EQ(b.bufs[w.sel_part - 1].d.shape[0], most);
|
||||
// Two decode rows beside a 498-row chunk: 500 rows, runs of R.
|
||||
auto k = kit(b, { 1, 1 }, { 498 }, 100);
|
||||
// Wide page tables, so that live blocks follow the history past the selection.
|
||||
auto widen = [](Kit& kt) {
|
||||
const int64_t pitch = 1024;
|
||||
kt.table.resize((size_t)(kt.b.n_seq * pitch));
|
||||
for (int64_t i = 0; i < kt.b.n_seq * pitch; ++i) kt.table[(size_t)i] = (int32_t)i;
|
||||
for (auto& g : kt.kv) {
|
||||
g.block_table = kt.table.data();
|
||||
g.block_table_pitch = g.max_blocks = pitch;
|
||||
}
|
||||
};
|
||||
{
|
||||
// 500 rows whose history fits the selection take every block without splitting:
|
||||
// each rank selects the whole step from the unscored plane, and nothing gathers.
|
||||
auto fit = kit(b, { 1, 1 }, { 498 }, 100);
|
||||
widen(*fit);
|
||||
auto fits = run_passes(b, glm5next::step, { fit.get() }, rank, world);
|
||||
CHECK_PASSES(b, fits);
|
||||
int all = 0;
|
||||
for (const auto& issue : fits[0]->issues) {
|
||||
CHECK(issue.op != cache.op_score_part && issue.op != cache.op_gather_sel &&
|
||||
issue.op != cache.op_score);
|
||||
if (issue.op == cache.op_select_all) {
|
||||
++all;
|
||||
CHECK_EQ(issue.n, 500);
|
||||
CHECK_EQ(issue.opd[0].handle, w.unscored);
|
||||
}
|
||||
}
|
||||
CHECK_EQ(all, 1);
|
||||
}
|
||||
// Two decode rows beside a 498-row chunk of 3000 tokens of history: 500 rows that
|
||||
// score, in runs of R.
|
||||
auto k = kit(b, { 1, 1 }, { 498 }, 3000);
|
||||
widen(*k);
|
||||
const int64_t T = 500, R = DsaCache::part_rows(T, world), r0 = rank * R,
|
||||
have = std::min(R, T - r0);
|
||||
auto passes = run_passes(b, glm5next::step, { k.get() }, rank, world);
|
||||
@@ -859,8 +909,19 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
|
||||
CHECK_EQ(gathered, 1);
|
||||
CHECK_EQ(replicated, 0);
|
||||
CHECK_EQ(fronts, 4);
|
||||
// Under the threshold every rank scores and selects the whole step.
|
||||
auto small = kit(b, {}, { 255 });
|
||||
// Under the threshold every rank scores and selects the whole step. 3000 tokens of
|
||||
// history reach 815 blocks, past the selection, and 255 rows of them stay under
|
||||
// kSplitWork.
|
||||
auto small = kit(b, {}, { 255 }, 3000);
|
||||
{
|
||||
const int64_t pitch = 1024;
|
||||
small->table.resize((size_t)pitch);
|
||||
for (int64_t i = 0; i < pitch; ++i) small->table[(size_t)i] = (int32_t)i;
|
||||
for (auto& g : small->kv) {
|
||||
g.block_table = small->table.data();
|
||||
g.block_table_pitch = g.max_blocks = pitch;
|
||||
}
|
||||
}
|
||||
auto under = run_passes(b, glm5next::step, { small.get() }, rank, world);
|
||||
CHECK_PASSES(b, under);
|
||||
int whole = 0;
|
||||
@@ -874,6 +935,27 @@ TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) {
|
||||
if (issue.op == index.op_head) CHECK_EQ(issue.n, 255);
|
||||
}
|
||||
CHECK_EQ(whole, 1);
|
||||
// Without that history every row selects all its blocks: no rank runs the query side
|
||||
// or scores, and the selection reads zeros over the selection's width.
|
||||
auto fits = kit(b, {}, { 255 });
|
||||
auto all = run_passes(b, glm5next::step, { fits.get() }, rank, world);
|
||||
CHECK_PASSES(b, all);
|
||||
int unscored = 0, picks = 0;
|
||||
for (const auto& issue : all[0]->issues) {
|
||||
CHECK(issue.op != cache.op_score && issue.op != cache.op_score_part &&
|
||||
issue.op != cache.op_query && issue.op != index.op_query_copy &&
|
||||
issue.op != index.op_head && issue.op != index.query.op);
|
||||
if (issue.op == cache.op_unscored) {
|
||||
++unscored;
|
||||
CHECK_EQ(issue.n, 255);
|
||||
CHECK_EQ(issue.opd[0].handle, w.unscored);
|
||||
CHECK_EQ(b.bufs[w.unscored - 1].d.shape[1], cache.unscored_cols());
|
||||
}
|
||||
CHECK(issue.op != cache.op_select);
|
||||
picks += issue.op == cache.op_select_all;
|
||||
}
|
||||
CHECK_EQ(unscored, 1);
|
||||
CHECK_EQ(picks, 1);
|
||||
// A verify of eight sequences at 32k of context (48 rows x 8014 blocks) splits too, a
|
||||
// single sequence's six rows do not; a rank whose run lies past the step still writes
|
||||
// the runs it gathers.
|
||||
@@ -1024,8 +1106,8 @@ TEST(glm53_refusals_name_what_was_refused) {
|
||||
return err;
|
||||
};
|
||||
RadBuildCtx c = ok;
|
||||
c.kv_dtype = RAD_F8E4M3;
|
||||
CHECK(has(refusal(meta, c), "--kv-cache-dtype fp8"));
|
||||
c.kv_dtype = RAD_F16;
|
||||
CHECK(has(refusal(meta, c), "--kv-cache-dtype f16"));
|
||||
c = ok;
|
||||
c.max_spec = 32;
|
||||
CHECK(has(refusal(meta, c), "--num-speculative-tokens 32"));
|
||||
@@ -1055,6 +1137,70 @@ TEST(glm53_refusals_name_what_was_refused) {
|
||||
}
|
||||
}
|
||||
|
||||
/* --kv-cache-dtype fp8 narrows the latent attention cache alone to E4M3: its group, every latent
|
||||
* store (plain and streamed) and every latent attention (head form, row form, the MTP layer's)
|
||||
* 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) {
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
RadModelMeta meta{};
|
||||
meta.n_layers = 45;
|
||||
meta.n_embd = 4096;
|
||||
meta.n_vocab = 154880;
|
||||
meta.rms_eps = 1e-5f;
|
||||
meta.n_kv = 4;
|
||||
meta.kv_key = keys;
|
||||
meta.kv_val = vals;
|
||||
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
|
||||
for (int kv_dtype : { (int)RAD_DT_INVALID, (int)RAD_BF16, (int)RAD_F8E4M3 }) {
|
||||
const bool narrow = kv_dtype == RAD_F8E4M3;
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
|
||||
{ "mtp.blk.45.ffn_down_exps", fp8 },
|
||||
{ "ffn_gate_up_exps", mx },
|
||||
{ "ffn_down_exps", mx },
|
||||
{ "ffn_gate_up_shexp", mx },
|
||||
{ "ffn_down_shexp", mx },
|
||||
{ "ffn_gate_up.weight", fp8 },
|
||||
{ "ffn_down.weight", fp8 } };
|
||||
RadBuildCtx build{};
|
||||
build.rank = 0;
|
||||
build.world_size = 4;
|
||||
build.max_tok = 512;
|
||||
build.max_seqs = 4;
|
||||
build.max_ctx = 4096;
|
||||
build.max_spec = 3;
|
||||
build.tp_attn_rows = 1;
|
||||
build.kv_dtype = kv_dtype;
|
||||
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
|
||||
std::map<std::string, uint32_t> dtypes;
|
||||
for (const auto& g : b.kv_groups) dtypes[g.name] = g.d.dtype;
|
||||
CHECK_EQ(dtypes["kv_latent"], narrow ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(dtypes["kv_index_tail"], (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(dtypes["kv_dsa_index"], (uint32_t)RAD_U8);
|
||||
CHECK_EQ(dtypes["kv_kda"], (uint32_t)RAD_F32);
|
||||
CHECK_EQ(dtypes["kv_kda_conv"], (uint32_t)RAD_BF16);
|
||||
int stores = 0, attns = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op == "kv_store" || o.op == "kv_store_streamed") {
|
||||
++stores;
|
||||
CHECK_EQ(pstr(&o, "kv_dtype"), narrow ? "fp8_e4m3" : "bf16");
|
||||
}
|
||||
if (o.op == "mla_attn") {
|
||||
++attns;
|
||||
CHECK_EQ(pstr(&o, "kv_dtype"), narrow ? "fp8_e4m3" : "<absent>");
|
||||
}
|
||||
}
|
||||
// 11 MLA layers and the MTP layer, each a store and a head-form attention; 11 row forms.
|
||||
CHECK(stores >= 12);
|
||||
CHECK_EQ(attns, 12 + 11);
|
||||
}
|
||||
}
|
||||
|
||||
/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill
|
||||
* (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the
|
||||
* launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's
|
||||
@@ -1230,6 +1376,7 @@ TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ri
|
||||
w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 });
|
||||
w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 });
|
||||
w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 });
|
||||
w.unscored = decl_b(&b, "unscored", RAD_F32, { 32, 513 });
|
||||
w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 });
|
||||
w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 });
|
||||
w.length = decl_b(&b, "len", RAD_I32, { 32 });
|
||||
@@ -1258,54 +1405,85 @@ TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ri
|
||||
RAD_OK);
|
||||
CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8);
|
||||
CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17);
|
||||
int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{};
|
||||
RadKVGroupBatch kv[3]{};
|
||||
kv[0].group = index;
|
||||
kv[0].block_table = ibt;
|
||||
kv[0].block_table_pitch = 8;
|
||||
kv[1].group = tail;
|
||||
kv[1].state_index = sidx;
|
||||
kv[1].state_index_pitch = 6;
|
||||
kv[2].group = attn;
|
||||
kv[2].block_table = abt;
|
||||
kv[2].block_table_pitch = 8;
|
||||
RadBatch batch{};
|
||||
batch.n_tok = 8;
|
||||
batch.n_seq = 2;
|
||||
batch.n_spec = 2;
|
||||
batch.kv = kv;
|
||||
batch.n_kv_groups = 3;
|
||||
batch.positions = pos;
|
||||
batch.cu_seqlens = cu;
|
||||
batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns.
|
||||
RadCtx ctx;
|
||||
ctx.b = &b;
|
||||
ctx.batch = &batch;
|
||||
if (front) {
|
||||
indexer.step(&ctx, &batch);
|
||||
REQUIRE_EQ(ctx.issues.size(), (size_t)12);
|
||||
CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy);
|
||||
CHECK_EQ(ctx.issues[1].opd[1].rows, 256);
|
||||
CHECK_EQ(ctx.issues[3].op, indexer.op_norm);
|
||||
CHECK_EQ(ctx.issues[4].opd[0].offset, 128);
|
||||
CHECK_EQ(ctx.issues[5].op, indexer.op_head);
|
||||
ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6);
|
||||
} else
|
||||
block.step(&ctx, &batch);
|
||||
REQUIRE_EQ(ctx.issues.size(), (size_t)6);
|
||||
CHECK_EQ(ctx.issues[0].n, 256);
|
||||
CHECK(ctx.issues[1].opd[5].raw == ibt);
|
||||
CHECK_EQ(ctx.issues[1].opd[4].cols, 6);
|
||||
CHECK_EQ(ctx.issues[2].op, block.op_pool);
|
||||
CHECK_EQ(ctx.issues[2].opd[5].handle, index);
|
||||
CHECK_EQ(ctx.issues[3].op, block.op_tail);
|
||||
CHECK_EQ(ctx.issues[4].opd[0].rows, 256);
|
||||
CHECK_EQ(ctx.issues[4].opd[3].handle, index);
|
||||
CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE);
|
||||
CHECK(ctx.issues[4].opd[5].raw == ibt);
|
||||
CHECK_EQ(ctx.issues[4].opd[8].cols, 8);
|
||||
CHECK_EQ(ctx.issues[5].opd[0].cols, 8);
|
||||
CHECK(ctx.issues[5].opd[1].raw == abt);
|
||||
/* Eight table columns cap the live reach below the selection, so every row takes all its
|
||||
* blocks (DsaCache::takes_all); 4000 tokens of history over 1024 columns reach 1004 blocks,
|
||||
* past it, and score. */
|
||||
for (const int64_t pitch : { 8, 1024 }) {
|
||||
const bool scores = pitch > 8;
|
||||
std::vector<int32_t> ibt((size_t)(2 * pitch)), abt((size_t)(2 * pitch));
|
||||
int32_t sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{};
|
||||
RadKVGroupBatch kv[3]{};
|
||||
kv[0].group = index;
|
||||
kv[0].block_table = ibt.data();
|
||||
kv[0].block_table_pitch = pitch;
|
||||
kv[1].group = tail;
|
||||
kv[1].state_index = sidx;
|
||||
kv[1].state_index_pitch = 6;
|
||||
kv[2].group = attn;
|
||||
kv[2].block_table = abt.data();
|
||||
kv[2].block_table_pitch = pitch;
|
||||
RadBatch batch{};
|
||||
batch.n_tok = 8;
|
||||
batch.n_seq = 2;
|
||||
batch.n_spec = 2;
|
||||
batch.kv = kv;
|
||||
batch.n_kv_groups = 3;
|
||||
batch.positions = pos;
|
||||
batch.cu_seqlens = cu;
|
||||
// At eight columns the mixed-row bound exceeds the physical table.
|
||||
batch.max_ctx_len = scores ? 4000 : 64;
|
||||
const int64_t live = scores ? 1004 : 8;
|
||||
CHECK_EQ(block.live_blocks(&batch), live);
|
||||
CHECK_EQ(block.takes_all(&batch), !scores);
|
||||
RadCtx ctx;
|
||||
ctx.b = &b;
|
||||
ctx.batch = &batch;
|
||||
if (front) {
|
||||
indexer.step(&ctx, &batch);
|
||||
if (scores) {
|
||||
REQUIRE_EQ(ctx.issues.size(), (size_t)12);
|
||||
CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy);
|
||||
CHECK_EQ(ctx.issues[1].opd[1].rows, 256);
|
||||
CHECK_EQ(ctx.issues[3].op, indexer.op_norm);
|
||||
CHECK_EQ(ctx.issues[4].opd[0].offset, 128);
|
||||
CHECK_EQ(ctx.issues[5].op, indexer.op_head);
|
||||
ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6);
|
||||
} else {
|
||||
// The key side alone: key and gate projection, norm, gate copy.
|
||||
REQUIRE_EQ(ctx.issues.size(), (size_t)8);
|
||||
CHECK_EQ(ctx.issues[1].op, indexer.op_norm);
|
||||
CHECK_EQ(ctx.issues[2].op, indexer.op_gate_copy);
|
||||
ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 3);
|
||||
}
|
||||
} else
|
||||
block.step(&ctx, &batch);
|
||||
const size_t q = scores ? 1 : 0; // the query quantiser leads a scored step
|
||||
REQUIRE_EQ(ctx.issues.size(), 5 + q);
|
||||
if (scores) CHECK_EQ(ctx.issues[0].n, 256);
|
||||
CHECK(ctx.issues[q].opd[5].raw == ibt.data());
|
||||
CHECK_EQ(ctx.issues[q].opd[4].cols, 6);
|
||||
CHECK_EQ(ctx.issues[q + 1].op, block.op_pool);
|
||||
CHECK_EQ(ctx.issues[q + 1].opd[5].handle, index);
|
||||
CHECK_EQ(ctx.issues[q + 2].op, block.op_tail);
|
||||
const auto& fill = ctx.issues[q + 3];
|
||||
if (scores) {
|
||||
CHECK_EQ(fill.op, block.op_score);
|
||||
CHECK_EQ(fill.opd[0].rows, 256);
|
||||
CHECK_EQ(fill.opd[3].handle, index);
|
||||
CHECK_EQ(fill.opd[4].kind, RAD_OPK_NONE);
|
||||
CHECK(fill.opd[5].raw == ibt.data());
|
||||
CHECK_EQ(fill.opd[8].cols, live);
|
||||
} else {
|
||||
CHECK_EQ(fill.op, block.op_unscored);
|
||||
CHECK_EQ(fill.n, 8);
|
||||
CHECK_EQ(fill.opd[0].handle, w.unscored);
|
||||
CHECK_EQ(fill.opd[0].rows, 8);
|
||||
}
|
||||
CHECK_EQ(ctx.issues[q + 4].op, scores ? block.op_select : block.op_select_all);
|
||||
CHECK_EQ(ctx.issues[q + 4].opd[0].handle, scores ? w.score : w.unscored);
|
||||
CHECK_EQ(ctx.issues[q + 4].opd[0].cols, live);
|
||||
CHECK(ctx.issues[q + 4].opd[1].raw == abt.data());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1610,16 +1788,23 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
|
||||
int world;
|
||||
uint64_t graph, steps;
|
||||
bool heads_only = false; /* the default: the graph before the row form */
|
||||
bool file_tier = false; /* --weights-disk-tier: whole experts at four ranks and up */
|
||||
};
|
||||
/* Pins from this test's own `pin:` printout: the head form (heads_only, which declares the
|
||||
* streamed ops) and the row form, at one and eight ranks. Re-recorded after every graph
|
||||
* change -- the merge re-recorded them for main's builder plus this branch's file-direct
|
||||
* expert ops. */
|
||||
const Case cases[] = { { 1, 0x8e12725b3ed3548dull, 0x68ffc03d2b640d51ull },
|
||||
/* World 8 is this branch's expert-parallel graph (288/world whole
|
||||
* experts, file-direct), so its pins differ from main's. */
|
||||
{ 8, 0x6232b56d6f971d61ull, 0x1b80576ba8f1ecc7ull },
|
||||
{ 8, 0x3e4b89352f01b57bull, 0xed8cc595e8eeb593ull, true } };
|
||||
* expert ops, and the graphs again when the routing counts became RAD_BUF_PERSIST (the
|
||||
* steps did not change). */
|
||||
const Case cases[] = { { 1, 0xce4368c09bfdbbeeull, 0x19679d4fcc0321ebull },
|
||||
/* Two ranks keep whole experts; four and eight split them by width. */
|
||||
{ 2, 0xab04b95724840abeull, 0x76865603b1390635ull },
|
||||
{ 4, 0xfdee91cd1c985b0aull, 0xde7ebe5b604c3cd2ull },
|
||||
{ 8, 0x59112e7ad7d77fdeull, 0xb9c29d30003a6df7ull },
|
||||
{ 8, 0xf1bb904ab21d8813ull, 0xfb28d3dcd8ec5ae1ull, true },
|
||||
/* The file tier's whole experts, file-direct, at four and eight. */
|
||||
{ 4, 0x1918906f91fad4e7ull, 0x07d518b9a0f32986ull, false, true },
|
||||
{ 8, 0x553f81a93cec76bfull, 0x17f0a90d3bed9713ull, false, true },
|
||||
{ 8, 0x9685be82c8d55813ull, 0x75e775f0568636b5ull, true, true } };
|
||||
for (const Case& cs : cases) {
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
@@ -1636,17 +1821,78 @@ TEST(glm53_is_the_pinned_graph_and_steps) {
|
||||
ctx.max_seqs = 8;
|
||||
ctx.max_ctx = 200000;
|
||||
ctx.tp_attn_rows = cs.heads_only ? 0 : 1;
|
||||
ctx.expert_file_tier = cs.file_tier;
|
||||
REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK);
|
||||
const uint64_t g = graph_hash(b);
|
||||
const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world);
|
||||
fprintf(stderr, " pin: glm5next world %d%s: graph 0x%016llxull, steps 0x%016llxull\n",
|
||||
cs.world, cs.heads_only ? " heads only" : "",
|
||||
fprintf(stderr, " pin: glm5next world %d%s%s: graph 0x%016llxull, steps 0x%016llxull\n",
|
||||
cs.world, cs.heads_only ? " heads only" : "", cs.file_tier ? " file tier" : "",
|
||||
(unsigned long long)g, (unsigned long long)s);
|
||||
CHECK_EQ(g, cs.graph);
|
||||
CHECK_EQ(s, cs.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) {
|
||||
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
|
||||
"index_topk" };
|
||||
const char* vals[] = { "1", "4", "288", "2048" };
|
||||
RadModelMeta meta{};
|
||||
meta.n_layers = 45;
|
||||
meta.n_embd = 4096;
|
||||
meta.n_vocab = 154880;
|
||||
meta.rms_eps = 1e-5f;
|
||||
meta.n_kv = 4;
|
||||
meta.kv_key = keys;
|
||||
meta.kv_val = vals;
|
||||
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
|
||||
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
|
||||
const auto bf = rad_enc_plain(RAD_BF16);
|
||||
const auto declare = [&](const RadEncoding& first, const RadEncoding& rest, bool tier,
|
||||
int world, uint64_t* graph) {
|
||||
RadBuilder b;
|
||||
b.kv_block = 4;
|
||||
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
|
||||
{ "mtp.blk.45.ffn_down_exps", fp8 },
|
||||
{ "blk.3.ffn_gate_up_exps.0.", first },
|
||||
{ "blk.3.ffn_down_exps.0.", first },
|
||||
{ "blk.3.ffn_gate_up_exps.1.", first },
|
||||
{ "blk.3.ffn_down_exps.1.", first },
|
||||
{ "ffn_gate_up_exps", rest },
|
||||
{ "ffn_down_exps", rest },
|
||||
{ "ffn_gate_up_shexp", rest },
|
||||
{ "ffn_down_shexp", rest },
|
||||
{ "ffn_gate_up.weight", fp8 },
|
||||
{ "ffn_down.weight", fp8 } };
|
||||
RadBuildCtx ctx = spec_ctx(0, world, 3);
|
||||
ctx.max_tok = 4096;
|
||||
ctx.max_seqs = 8;
|
||||
ctx.max_ctx = 200000;
|
||||
ctx.expert_file_tier = tier;
|
||||
const int rc = glm5next::declare(&b, &meta, &ctx);
|
||||
if (rc == RAD_OK) *graph = graph_hash(b);
|
||||
return rc;
|
||||
};
|
||||
for (const int world : { 4, 8 }) {
|
||||
uint64_t whole = 0, g = 0;
|
||||
REQUIRE_EQ(declare(bf, bf, true, world, &whole), RAD_OK);
|
||||
REQUIRE_EQ(declare(bf, bf, false, world, &g), RAD_OK); /* was refused: slices every expert */
|
||||
CHECK_EQ(g, whole);
|
||||
REQUIRE_EQ(declare(fp8, fp8, true, world, &whole), RAD_OK);
|
||||
REQUIRE_EQ(declare(fp8, fp8, false, world, &g), RAD_OK);
|
||||
CHECK_EQ(g, whole);
|
||||
REQUIRE_EQ(declare(mx, mx, true, world, &whole), RAD_OK);
|
||||
uint64_t width = 0;
|
||||
REQUIRE_EQ(declare(mx, mx, false, world, &width), RAD_OK);
|
||||
CHECK(width != whole);
|
||||
REQUIRE_EQ(declare(bf, mx, true, world, &whole), RAD_OK);
|
||||
REQUIRE_EQ(declare(bf, mx, false, world, &g), RAD_OK); /* a protected pair */
|
||||
CHECK_EQ(g, whole);
|
||||
}
|
||||
}
|
||||
|
||||
/* ==================================================================== GLM-5.3's vision tower */
|
||||
namespace {
|
||||
|
||||
@@ -2166,7 +2412,9 @@ TEST(glm53_streamed_decode_resolves_after_select_and_before_attention_with_the_e
|
||||
};
|
||||
auto check_layer_order = [&](const glm5next::Layer& l) {
|
||||
const size_t store = find_issue(l.mla.op_store_stream);
|
||||
const size_t sel = find_issue(l.index.cache.op_select);
|
||||
// A short history takes every block (DsaCache::takes_all), a long one scores.
|
||||
const size_t sel = std::min(find_issue(l.index.cache.op_select),
|
||||
find_issue(l.index.cache.op_select_all));
|
||||
const size_t res_i = find_issue(l.mla.op_resolve);
|
||||
const size_t attn = find_issue(l.mla.core.op_attn);
|
||||
REQUIRE(store != SIZE_MAX);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Dashboard page tests
|
||||
|
||||
The dashboard is one C++ string: `core/server/dashboard.cpp` embeds the whole page,
|
||||
so its JavaScript has no file of its own to test. These harnesses extract the page
|
||||
from the translation unit (`page.js`) and **execute the shipped functions**, sliced
|
||||
by line range, against mocked DOM. A retyped copy would test the copy, not the bytes
|
||||
that ship, and each harness calls the functions it slices: one that is only defined proves
|
||||
nothing.
|
||||
|
||||
node tests/js/poll_spark.test.js
|
||||
node tests/js/extremes.test.js
|
||||
node tests/js/history.test.js
|
||||
node tests/js/download.test.js
|
||||
|
||||
## What each one covers
|
||||
|
||||
| file | the shipped code it drives |
|
||||
| --- | --- |
|
||||
| `poll_spark.test.js` | the cadence fields, the sparkline |
|
||||
| `extremes.test.js` | `noteSample`, `triple`, `acceptTriple`, `resetWindows`, `newEngineRun` |
|
||||
| `history.test.js` | the history summary line: how it groups, and how it wraps |
|
||||
| `download.test.js` | the Requests-header JSON export: its markup and its handler |
|
||||
|
||||
Each asserts structure, not just text. `history.test.js` inspects the DOM the page builds and the
|
||||
CSS it ships, because the rules it guards -- a category wraps whole, the category break is a dot
|
||||
and the break within one is a pipe -- are not properties of any string the code builds.
|
||||
`download.test.js` invokes the click handler against stubs and checks it really builds a file,
|
||||
names it, clicks it and releases the blob URL: a button that looks clickable and does nothing is
|
||||
the failure it exists to catch.
|
||||
|
||||
## The render check (manual, needs Chrome)
|
||||
|
||||
`render_align.js` is not a unit test and cannot be: it answers whether the download glyph is
|
||||
level with the caption by loading the page in headless Chrome, screenshotting the header at 4x,
|
||||
and comparing the lowest inked pixel row of each. It needs puppeteer and a Chrome binary, which
|
||||
are deliberately not repo dependencies:
|
||||
|
||||
npm i puppeteer && npx puppeteer browsers install chrome
|
||||
node tests/js/render_align.js http://127.0.0.1:8800/
|
||||
|
||||
Exits nonzero when the two bottoms land on different device rows. Run it after touching glyph or
|
||||
header geometry: alignment cannot be read off the CSS and the SVG viewBox (collapsed whitespace can
|
||||
make a separator zero pixels wide, and an SVG flush with the baseline still floats, because the
|
||||
baseline sits above the box bottom), so measure the rendered page.
|
||||
|
||||
## Why these are not in ctest
|
||||
|
||||
They need node, which is not a build dependency of this project and will not be
|
||||
present on a contributor's box or in the ROCm build image. Wiring them into ctest
|
||||
would turn a missing optional tool into a red build, so they stay opt-in and are run
|
||||
by hand when the page changes. `dashboard_test` covers the C++ side only.
|
||||
@@ -0,0 +1,128 @@
|
||||
/* The Requests-header JSON export. It used to be a "json" text button in the history row that
|
||||
* copied to the clipboard; it is now a download icon that saves a file. A button that looks
|
||||
* clickable and silently does nothing is the failure this guards: so drive the SHIPPED handler
|
||||
* against stubs and assert it actually builds a file, names it, clicks it, and cleans up. */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const src = require("./page.js"); // the <script> block: the handler lives here
|
||||
/* The MARKUP lives in the page body, which page.js does not return (the JS suites have no
|
||||
reason to read it). Read the whole shipped page for markup assertions. */
|
||||
const cpp = fs.readFileSync(path.join(__dirname, "..", "..", "core", "server", "dashboard.cpp"), "utf8");
|
||||
const page = (cpp.match(/R"HTML\(([\s\S]*)\)HTML"/) || [, ""])[1];
|
||||
const css = (cpp.match(/<style>([\s\S]*?)<\/style>/) || [, ""])[1];
|
||||
const L = src.split("\n");
|
||||
let fails = 0, checks = 0;
|
||||
const ok = (c, m) => { checks++; if (!c) { fails++; console.log(" FAIL " + m); } };
|
||||
const eq = (a, b, m) => { checks++; if (a !== b) { fails++; console.log(" FAIL " + m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); } };
|
||||
|
||||
console.log("== the export lives in the Requests header, not the history row ==");
|
||||
ok(/id="reqjson"/.test(page), "a #reqjson control exists");
|
||||
ok(!/id="hjson"/.test(page), "the old #hjson button in the history row is gone");
|
||||
/* The button spans several source lines, so match the whole element, not one line. */
|
||||
const btn = (page.match(/<button[^>]*id="reqjson"[\s\S]*?<\/button>/) || [""])[0];
|
||||
ok(btn.length > 0, "found the reqjson button element");
|
||||
ok(/title="Download JSON file"/.test(btn), "the tooltip says 'Download JSON file'");
|
||||
ok(/aria-label="Download JSON file"/.test(btn), "and is labelled for assistive tech");
|
||||
ok(/<svg[\s\S]*<\/svg>/.test(btn), "it holds an icon, not a text label");
|
||||
ok(!/>\s*json\s*</.test(btn), "no leftover 'json' text label inside the button");
|
||||
/* Two things put the tray bar level with the bottom of the caption's letters, and BOTH are
|
||||
load-bearing -- measured in headless Chrome, not reasoned out:
|
||||
|
||||
1. the glyph fills its box: the bar's STROKE bottom lands on the viewBox bottom, so there is
|
||||
no dead space inside the SVG. An inset bar (the original sat at 13.5 of 16) shifts the
|
||||
bar up and the nudge below would then be the wrong size.
|
||||
2. the glyph is nudged down 2px: align-items:baseline puts the SVG's BOX on the text
|
||||
baseline, but the baseline sits ABOVE the box bottom, so even a box-filling glyph floated
|
||||
~2px high. The nudge is what actually closes the gap.
|
||||
|
||||
The first version of this guard checked only (1) and asserted it "sits on the baseline" --
|
||||
that claim was false, and the passing test is why the float survived a commit. */
|
||||
const vb = +(btn.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/) || [, , 0])[2];
|
||||
const sw = +(btn.match(/stroke-width="([\d.]+)"/) || [, 0])[1];
|
||||
const bar = +(btn.match(/M[\d.]+ ([\d.]+)h/) || [, 0])[1];
|
||||
ok(vb > 0 && sw > 0 && bar > 0, "parsed the glyph geometry (viewBox " + vb + ", stroke " + sw + ", bar " + bar + ")");
|
||||
eq(Math.round((bar + sw / 2) * 1000) / 1000, vb,
|
||||
"the glyph fills its box: the tray bar's stroke bottom is flush with the viewBox bottom");
|
||||
/* The nudge that actually delivers the alignment. Pinned because it is a measured value, not a
|
||||
taste value: at 2px the bar's bottom and the caption's bottom land on the same device row. */
|
||||
const nudge = css.match(/#reqjson svg \{[^}]*transform:\s*translateY\(([\d.]+)px\)/);
|
||||
ok(nudge, "the download glyph carries an explicit vertical nudge");
|
||||
eq(nudge ? +nudge[1] : NaN, 2, "the nudge is the measured 2px (removing it floats the bar ~2px high)");
|
||||
/* It must sit in the Requests header, in the LEFT group, before the right-hand aside. Index
|
||||
ordering is sturdier than a regex across the whole block. */
|
||||
const iLeft = page.indexOf('class="pleft"');
|
||||
const iBtn = page.indexOf('id="reqjson"');
|
||||
const iAside= page.indexOf('id="reqaside"');
|
||||
ok(iLeft >= 0 && iBtn > iLeft, "reqjson comes after the phead left-group opens");
|
||||
ok(iAside > iBtn, "reqjson comes before the right-hand aside (so it sits on the LEFT)");
|
||||
/* Exactly one: a duplicate id is invalid HTML and getElementById binds only the first, so a
|
||||
second button would render and do nothing -- the silent-dead-control failure itself. */
|
||||
const nBtn = (page.match(/id="reqjson"/g) || []).length;
|
||||
eq(nBtn, 1, "exactly one reqjson control (a duplicate id would leave one dead)");
|
||||
/* And it is inside the Requests panel, not some other phead: the phead that opens with
|
||||
class="pleft" is the Requests one (only that header gained the group). */
|
||||
const iCap = page.indexOf('<span class="cap">Requests</span>');
|
||||
ok(iCap >= 0, "the Requests caption exists (indexOf -1 would make the order check vacuous)");
|
||||
ok(iCap >= 0 && iCap < iBtn, "the button is in the Requests header, after its title");
|
||||
|
||||
console.log("== the shipped handler builds a real download ==");
|
||||
const si = L.findIndex((x) => x.startsWith('$("reqjson").addEventListener'));
|
||||
if (si < 0) throw new Error("no reqjson handler");
|
||||
let ei = -1;
|
||||
for (let k = si; k < L.length; k++) if (L[k] === "});") { ei = k; break; }
|
||||
if (ei < 0) throw new Error("no handler end");
|
||||
const HANDLER = L.slice(si, ei + 1).join("\n");
|
||||
|
||||
/* Stubs: capture the click handler, then invoke it and watch what it builds. */
|
||||
let clickHandler = null;
|
||||
const seq = []; /* one ordered log: the ORDER of DOM ops is the bug class, not the counts */
|
||||
const fakeEl = (tag) => ({ tag, href: "", download: "", clicked: 0, removed: 0,
|
||||
click() { this.clicked++; seq.push("click"); }, remove() { this.removed++; seq.push("remove"); } });
|
||||
const anchors = [];
|
||||
const el = (t) => { const a = fakeEl(t); anchors.push(a); return a; };
|
||||
const body = { appended: [], appendChild(n) { this.appended.push(n); seq.push("append"); } };
|
||||
const created = [];
|
||||
const URL = { createObjectURL(b) { const u = "blob:fake/" + created.length; created.push({ b, u }); return u; },
|
||||
revoked: [], revokeObjectURL(u) { this.revoked.push(u); seq.push("revoke"); } };
|
||||
class Blob { constructor(parts, opts) { this.parts = parts; this.type = opts && opts.type; } }
|
||||
let timeoutFn = null;
|
||||
const setTimeout = (fn, ms) => { timeoutFn = fn; return 1; };
|
||||
const hRows = [{ tps: 208, pf: 651, ttft: 796 }, { tps: 190 }];
|
||||
|
||||
const $ = (id) => ({ addEventListener(ev, fn) { if (ev === "click") clickHandler = fn; } });
|
||||
new Function("$", "el", "document", "URL", "Blob", "setTimeout", "hRows", HANDLER)(
|
||||
$, el, { body }, URL, Blob, setTimeout, hRows);
|
||||
|
||||
ok(clickHandler !== null, "a click handler was registered on #reqjson");
|
||||
clickHandler();
|
||||
|
||||
eq(anchors.length, 1, "exactly one anchor built");
|
||||
const a = anchors[0];
|
||||
eq(a.tag, "a", "it is an anchor");
|
||||
eq(a.download, "radiance-history.json", "it names a downloadable file");
|
||||
ok(a.href.startsWith("blob:"), "href is a blob URL: " + a.href);
|
||||
eq(a.clicked, 1, "the anchor was clicked (that is what triggers the save)");
|
||||
eq(body.appended.length, 1, "the anchor was attached to the document (Firefox needs it in the DOM)");
|
||||
eq(a.removed, 1, "the anchor was removed afterwards");
|
||||
/* Order, not just occurrence: Firefox ignores a click on an anchor that is not yet in the DOM, so
|
||||
appendChild MUST precede click, and remove must follow it. Counts alone let a reordered handler
|
||||
pass while the button is dead in the browser. */
|
||||
const iApp = seq.indexOf("append"), iClick = seq.indexOf("click"), iRem = seq.indexOf("remove");
|
||||
ok(iApp >= 0 && iClick >= 0 && iApp < iClick,
|
||||
"the anchor is in the DOM BEFORE it is clicked (Firefox needs it): " + JSON.stringify(seq));
|
||||
ok(iClick >= 0 && iRem > iClick, "the anchor is removed only AFTER the click: " + JSON.stringify(seq));
|
||||
eq(created[0].b.type, "application/json", "the blob is typed application/json");
|
||||
const payload = JSON.parse(created[0].b.parts[0]);
|
||||
ok(Array.isArray(payload) && payload.length === 2, "the file holds the stored rows as JSON");
|
||||
eq(payload[0].tps, 208, "the row data survived serialization");
|
||||
ok(created[0].b.parts[0].includes("\n"), "pretty-printed (indented), not one dense line");
|
||||
|
||||
console.log("== cleanup: the blob URL is revoked, not leaked ==");
|
||||
eq(URL.revoked.length, 0, "not revoked synchronously (the click must finish first)");
|
||||
ok(typeof timeoutFn === "function", "a revoke was scheduled");
|
||||
timeoutFn();
|
||||
eq(URL.revoked.length, 1, "the revoke ran and released the blob URL");
|
||||
eq(URL.revoked[0], a.href, "and revoked exactly the URL it handed the anchor");
|
||||
|
||||
console.log(fails ? "\n" + fails + " FAILURE(S) of " + checks : "\nALL " + checks + " CHECKS PASS on the shipped download");
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,178 @@
|
||||
/* Session extremes: the age clause, and the gap/restart split. Executes the shipped
|
||||
noteSample / triple / acceptTriple / resetWindows / newEngineRun / poll, sliced by line
|
||||
range out of the page and CALLED -- defining a sliced function proves nothing.
|
||||
pctn/pct are the SHIPPED formatters rather than a re-typed stand-in: a copy of a formatter
|
||||
drifts from the real one, and an assertion on its output then silently means nothing.
|
||||
nowS is declared here because in the page it is module-level, so it is invisible inside
|
||||
new Function. */
|
||||
const src = require("./page.js");
|
||||
const L = src.split("\n");
|
||||
let fails = 0, checks = 0;
|
||||
const ok = (c, m) => { checks++; if (!c) { fails++; console.log(" FAIL " + m); } };
|
||||
const eq = (a, b, m) => { checks++; if (a !== b) { fails++; console.log(" FAIL " + m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); } };
|
||||
function lines(a, b) {
|
||||
const i = L.findIndex((x) => x.startsWith(a));
|
||||
if (i < 0) throw new Error("no start line: " + a);
|
||||
let j = -1;
|
||||
for (let k = i; k < L.length; k++) if (L[k].startsWith(b)) { j = k; break; }
|
||||
if (j < 0) throw new Error("no end line: " + b);
|
||||
return L.slice(i, j + 1).join("\n");
|
||||
}
|
||||
const COMMON = [
|
||||
"let nowS = 0;",
|
||||
'const DASH = "\\u2013";',
|
||||
"const finite = (v) => v != null && isFinite(v);",
|
||||
/* resetWindows() clears these; they are not under test but it READS them. */
|
||||
"const hist = {}, moveHist = { up: [], down: [] };",
|
||||
"let prev = null, prevAt = 0, accPrev = null;",
|
||||
lines("function pctn(", "}"),
|
||||
lines("const pct =", "const pct ="),
|
||||
lines("function dur(", "}"),
|
||||
lines("const RECENT_S =", "const RECENT_PREFILL_S"),
|
||||
lines("const extAt =", "let lastActiveC"),
|
||||
lines("function noteSample(", "}"),
|
||||
lines("function triple(", "}"),
|
||||
lines("function acceptTriple(", "}"),
|
||||
lines("const accPool =", "const accPool ="),
|
||||
lines("function resetWindows", "}"),
|
||||
lines("function newEngineRun", "}"),
|
||||
].join("\n");
|
||||
|
||||
function fresh() {
|
||||
const box = {};
|
||||
new Function("box", COMMON + "\nbox.api={noteSample,triple,acceptTriple,resetWindows,newEngineRun,extAt,winAt,extAtS,accPool,setNow:(v)=>{nowS=v;}};")(box);
|
||||
return box.api;
|
||||
}
|
||||
const F = (v) => v + " t/s";
|
||||
|
||||
async function main() {
|
||||
console.log("== the age clause appears only when the extreme stands alone ==");
|
||||
let b = fresh();
|
||||
b.setNow(100); b.noteSample("dec", 1, 500, 15, true);
|
||||
let out = b.triple("dec", 1, "best", F);
|
||||
ok(!out.includes("ago"), "window full: no age clause (got " + JSON.stringify(out) + ")");
|
||||
ok(out.includes("recent"), "and the window figures still render");
|
||||
b.resetWindows(); b.setNow(150);
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(/best 500 t\/s \| 50\.0 s ago$/.test(out), "extreme alone: age names the span (got " + JSON.stringify(out) + ")");
|
||||
b.setNow(100.4);
|
||||
ok(!b.triple("dec", 1, "best", F).includes("ago"), "an extreme set 0.4s ago is current: no clause");
|
||||
|
||||
console.log("== a stale extreme is distinguishable from a fresh one ==");
|
||||
b = fresh(); b.setNow(100); b.noteSample("dec", 1, 500, 15, false); b.setNow(1000);
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(out.includes("15m 00s ago"), "15-minute-old extreme says so (got " + JSON.stringify(out) + ")");
|
||||
ok(out.includes("best 500"), "and still shows the figure itself");
|
||||
|
||||
console.log("== the stamp marks when the EXTREME was set, not when anything was sampled ==");
|
||||
/* Re-sampling a key with a WORSE value must not refresh the stamp: the age belongs to the
|
||||
figure on the left. Refreshing it on every sample makes every age read ~0 -- wrong output,
|
||||
not missing output, which is the hardest kind of defect for a label to survive. */
|
||||
b = fresh(); b.setNow(100); b.noteSample("dec", 1, 500, 15, false);
|
||||
b.setNow(200); b.noteSample("dec", 1, 400, 15, false); /* not a new extreme */
|
||||
b.setNow(260);
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(out.includes("best 500"), "the extreme is still the earlier, better figure (got " + JSON.stringify(out) + ")");
|
||||
ok(out.includes("2m 40s ago"), "age is measured from the extreme, not the last sample (got " + JSON.stringify(out) + ")");
|
||||
b.setNow(300); b.noteSample("dec", 1, 900, 15, false); /* a NEW extreme */
|
||||
b.setNow(330);
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(out.includes("best 900") && out.includes("30.0 s ago"), "a new extreme restamps (got " + JSON.stringify(out) + ")");
|
||||
|
||||
console.log("== acceptTriple's age clause is exercised on a LIVE extreme ==");
|
||||
/* The restart case below clears extAt first, so acceptTriple returns at its guard and never
|
||||
reaches the clause. Nothing else drove it, so the clause could be deleted unnoticed. */
|
||||
b = fresh(); b.setNow(100); b.noteSample("accept", 1, 0.75, 15, false);
|
||||
b.setNow(100.5);
|
||||
ok(!b.acceptTriple(1).includes("ago"), "an acceptance extreme set 0.5s ago is current: no clause (got " + JSON.stringify(b.acceptTriple(1)) + ")");
|
||||
b.setNow(400);
|
||||
out = b.acceptTriple(1);
|
||||
ok(/^highest 75% \| 5m 00s ago$/.test(out), "once it stands alone it names its age (got " + JSON.stringify(out) + ")");
|
||||
b.accPool[1] = [{ dr: 10, da: 8 }, { dr: 10, da: 6 }];
|
||||
out = b.acceptTriple(1);
|
||||
ok(out.includes("recent") && !out.includes("ago"), "with a ring: window figures, no age clause (got " + JSON.stringify(out) + ")");
|
||||
|
||||
console.log("== a GAP keeps the extreme, and says how old it is ==");
|
||||
b = fresh(); b.setNow(100); b.noteSample("dec", 1, 500, 15, true); b.noteSample("accept", 1, 0.9, 15, false);
|
||||
b.setNow(400); b.resetWindows();
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(out.includes("best 500"), "the session extreme survives a gap (got " + JSON.stringify(out) + ")");
|
||||
ok(out.includes("5m 00s ago"), "and names its age (got " + JSON.stringify(out) + ")");
|
||||
eq(Object.keys(b.extAt).length, 2, "extAt untouched by a gap");
|
||||
|
||||
console.log("== a RESTART drops the extremes: a new process inherits nothing ==");
|
||||
b = fresh(); b.setNow(100); b.noteSample("dec", 1, 500, 15, true); b.noteSample("accept", 1, 0.9, 15, false);
|
||||
b.setNow(400); b.newEngineRun();
|
||||
eq(Object.keys(b.extAt).length, 0, "extAt cleared by newEngineRun");
|
||||
eq(Object.keys(b.extAtS).length, 0, "extAtS cleared by newEngineRun");
|
||||
eq(b.triple("dec", 1, "best", F), "", "the previous run's extreme no longer renders");
|
||||
eq(b.acceptTriple(1), "", "the previous run's acceptance extreme no longer renders");
|
||||
b.setNow(200); b.noteSample("dec", 1, 700, 15, false);
|
||||
out = b.triple("dec", 1, "best", F);
|
||||
ok(!out.includes("ago"), "a fresh extreme carries no age clause (got " + JSON.stringify(out) + ")");
|
||||
ok(/best 700 t\/s$/.test(out), "and reads as the new run's own figure");
|
||||
|
||||
/* ------------------------------------------------------------------ poll() itself
|
||||
* The restart DETECTION lives in poll(), not in newEngineRun(). Calling newEngineRun() directly
|
||||
* proves only that the function clears things -- deleting the detection line in poll() would
|
||||
* leave every such assertion green. So drive poll() with a scripted /stats sequence and assert
|
||||
* what it decides. resetWindows / newEngineRun / update are replaced with counters here on
|
||||
* purpose: this is testing the decision, not the clearing (covered above). */
|
||||
const POLL = lines("async function poll() {", "}");
|
||||
function makePoller(seq, clock) {
|
||||
const body = COMMON + "\n" + [
|
||||
"let lastPollAt = 0;",
|
||||
"const GAP_S = 60; let pollIdleMs = 500;",
|
||||
"const calls = { run: 0, gap: 0, update: 0 };",
|
||||
"function resetWindows() { calls.gap++; }",
|
||||
"function newEngineRun() { calls.run++; }",
|
||||
"function update() { calls.update++; }",
|
||||
"function schedulePoll() {}",
|
||||
"function pollCadence() { return 500; }",
|
||||
"const els = {};",
|
||||
"function $(id) { return els[id] || (els[id] = { hidden: false, className: \"\", classList: { remove() {} } }); }",
|
||||
"let i = 0;",
|
||||
"async function api() { const s = seq[Math.min(i++, seq.length - 1)]; return { ok: true, json: async () => JSON.parse(JSON.stringify(s)) }; }",
|
||||
POLL,
|
||||
"return { poll, calls };",
|
||||
].join("\n");
|
||||
return new Function("document", "performance", "Date", "seq", "clock", body)(
|
||||
{ hidden: false }, { now: () => 0 }, { now: () => clock.wall }, seq, clock);
|
||||
}
|
||||
const fixed = { wall: 1000 }; /* a fixed clock keeps the GAP path out of these assertions */
|
||||
console.log("== poll() detects a new engine process ==");
|
||||
let p = makePoller([
|
||||
{ started_at: 100, uptime_s: 10 }, /* first poll: baseline, clears nothing */
|
||||
{ started_at: 100, uptime_s: 20 }, /* same process, uptime rising: nothing happens */
|
||||
{ started_at: 200, uptime_s: 5 }, /* started_at moved: a new process */
|
||||
], fixed);
|
||||
await p.poll(); eq(p.calls.run, 0, "the first poll is a baseline, not a restart");
|
||||
await p.poll(); eq(p.calls.run, 0, "same started_at with a rising uptime is the same process");
|
||||
await p.poll(); eq(p.calls.run, 1, "a changed started_at clears the extremes");
|
||||
|
||||
console.log("== uptime_s is derived, so it is not a restart signal ==");
|
||||
/* uptime_s is unix_now() - started_at_, both whole seconds, so started_at + uptime_s is exactly
|
||||
the wall clock at that poll. A later poll of the SAME process therefore always reports a
|
||||
larger uptime; a smaller one means the wall clock moved backwards, which is an NTP adjustment
|
||||
and not a new process. Clearing on it would throw away the session's extremes on a clock
|
||||
correction, so nothing here treats it as a restart. */
|
||||
p = makePoller([
|
||||
{ started_at: 100, uptime_s: 40 },
|
||||
{ started_at: 100, uptime_s: 2 }, /* same started_at, uptime went backwards */
|
||||
], fixed);
|
||||
await p.poll(); await p.poll();
|
||||
eq(p.calls.run, 0, "a backward uptime with an unchanged started_at is a clock step, not a restart");
|
||||
|
||||
console.log("== poll() takes the GAP path, not the restart path, when only the clock moved ==");
|
||||
const slow = { wall: 1000 };
|
||||
p = makePoller([{ started_at: 100, uptime_s: 10 }, { started_at: 100, uptime_s: 130 }], slow);
|
||||
await p.poll();
|
||||
slow.wall = 1000 + 90 * 1000; /* 90s with nothing polled: a gap */
|
||||
await p.poll();
|
||||
eq(p.calls.gap, 1, "a long quiet span clears the windows");
|
||||
eq(p.calls.run, 0, "and is NOT read as a restart: the extremes survive it");
|
||||
}
|
||||
main().then(() => {
|
||||
console.log(fails ? "\n" + fails + " FAILURE(S) of " + checks : "\nALL " + checks + " CHECKS PASS on the shipped extreme code");
|
||||
process.exit(fails ? 1 : 0);
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
/* The history summary line: how it groups, and how it wraps.
|
||||
*
|
||||
* The line packs several categories into one strip -- a count, tok/s, prefill, ttft -- and each
|
||||
* category carries its own figures. Two rules the page must keep:
|
||||
*
|
||||
* a category is ATOMIC. If it does not fit on the line it moves whole to the next line. It
|
||||
* must never break mid-figure: "810" at the end of one line and "ms" on the next is worse
|
||||
* than the wrap it replaced.
|
||||
* the category break is a DOT and the break between figures inside one category is a PIPE.
|
||||
*
|
||||
* Both rules are structural, not string-level: HTML collapses runs of spaces, so the width of a
|
||||
* category break cannot come from spaces in the joined string. It comes from a padded element.
|
||||
* That is why these checks inspect the DOM the shipped code builds rather than the string it
|
||||
* used to build -- a string assertion here would have passed while the page rendered wrong. */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const src = require("./page.js"); // the page's <script> block
|
||||
/* The CSS lives in the <style> block, which page.js does not return (the JS tests have no
|
||||
reason to read it). Read it from the same shipped file rather than widen page.js's export and
|
||||
break the two suites that treat its result as a plain string. */
|
||||
const cpp = fs.readFileSync(path.join(__dirname, "..", "..", "core", "server", "dashboard.cpp"), "utf8");
|
||||
const css = (cpp.match(/<style>([\s\S]*?)<\/style>/) || [, ""])[1];
|
||||
const L = src.split("\n");
|
||||
let fails = 0, checks = 0;
|
||||
const ok = (c, m) => { checks++; if (!c) { fails++; console.log(" FAIL " + m); } };
|
||||
const eq = (a, b, m) => { checks++; if (a !== b) { fails++; console.log(" FAIL " + m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); } };
|
||||
function lines(a, b) {
|
||||
const i = L.findIndex((x) => x.startsWith(a));
|
||||
if (i < 0) throw new Error("no start line: " + a);
|
||||
let j = -1;
|
||||
for (let k = i; k < L.length; k++) if (L[k].startsWith(b)) { j = k; break; }
|
||||
if (j < 0) throw new Error("no end line: " + b);
|
||||
return L.slice(i, j + 1).join("\n");
|
||||
}
|
||||
|
||||
console.log("== the CSS makes a category atomic and the break actually wide ==");
|
||||
const grpCss = css.match(/#hist \.hgrp \{([^}]*)\}/);
|
||||
ok(css.length > 200, "read the page <style> block (" + css.length + " chars)");
|
||||
ok(grpCss, "#hist .hgrp rule exists");
|
||||
ok(/white-space:\s*nowrap/.test(grpCss ? grpCss[1] : ""), "a category cannot break mid-figure");
|
||||
const sepCss = css.match(/#hist \.hsep \{([^}]*)\}/);
|
||||
ok(sepCss, "#hist .hsep rule exists");
|
||||
const padM = sepCss ? sepCss[1].match(/padding:\s*0\s+(\d+)px/) : null;
|
||||
ok(padM, "the category break gets width from padding, not spaces");
|
||||
const pad = padM ? +padM[1] : 0;
|
||||
ok(pad >= 4, "the padding is wide enough to read as a break (" + pad + "px, want >= 4)");
|
||||
|
||||
console.log("== the shipped summary assembly builds one atomic group per category ==");
|
||||
/* Slice ONLY the summary-line assembly (mean/group -> the forEach that fills #hsum), not the
|
||||
whole renderer: the rest of histRender draws the table and needs a dozen module globals that
|
||||
have nothing to do with how the line groups or wraps. */
|
||||
const si = L.findIndex((x) => x.startsWith(" const mean = (a) =>"));
|
||||
if (si < 0) throw new Error("no summary start");
|
||||
const ai = L.findIndex((x, k) => k > si && x.includes("hsum.appendChild(g);"));
|
||||
if (ai < 0) throw new Error("no assembly anchor");
|
||||
let ei = -1;
|
||||
for (let k = ai; k < L.length; k++) if (L[k] === " });") { ei = k; break; }
|
||||
if (ei < 0) throw new Error("no assembly end");
|
||||
const BLOCK = L.slice(si, ei + 1).join("\n");
|
||||
ok(BLOCK.includes("hgrp") && BLOCK.includes("hsep"), "slice captured the grouping code (" + BLOCK.length + " chars)");
|
||||
|
||||
function mk(tag, cls, txt) {
|
||||
const o = { tag, cls, _t: txt || "", kids: [],
|
||||
appendChild(c) { this.kids.push(c); return c; },
|
||||
set textContent(v) { this._t = v; if (v === "") this.kids = []; },
|
||||
get textContent() { return this._t || ""; } };
|
||||
Object.defineProperty(o, "txt", { get() { return o._t || ""; } });
|
||||
return o;
|
||||
}
|
||||
const hsum = mk("span", "hsum");
|
||||
const el = (t, c, x) => mk(t, c, x);
|
||||
const doc = { createTextNode: (t) => ({ tag: "#text", cls: null, txt: t }) };
|
||||
/* The formatters come from the SHIPPED source, not re-typed here: a guard that asserts against a
|
||||
stub's own " ms" tests the stub. Slice DASH..dur (self-contained: ladder, sig3, cnt, pctn all
|
||||
inside) and drive the real tps/cnt3/dur. */
|
||||
/* lines() is INCLUSIVE of the end anchor, which would leave a dangling `const stepTime =` and
|
||||
throw a SyntaxError inside new Function. Slice to the line BEFORE it instead. */
|
||||
const fi = L.findIndex((x) => x.startsWith("const DASH = "));
|
||||
const fj = L.findIndex((x) => x.startsWith("const stepTime = "));
|
||||
if (fi < 0 || fj < 0 || fj <= fi) throw new Error("formatter block not located");
|
||||
const FMT = L.slice(fi, fj).join("\n");
|
||||
const { tps: tpsF, cnt3: cnt3F, dur: durF } = new Function(FMT + "\nreturn { tps, cnt3, dur };")();
|
||||
/* Fixture with DISTINCT means: the old cycling values made mean(all) == mean(last 20) by
|
||||
coincidence, so a window mutation could not show up in the figures. */
|
||||
const mkRows = (n) => Array.from({ length: n }, (_, i) => ({ tps: 100 + i, pf: 600 + 2 * i, ttft: 0.5 + 0.1 * i, age: i * 3 }));
|
||||
const rows = mkRows(24);
|
||||
new Function("el", "document", "$", "hRows", "tps", "cnt3", "dur", BLOCK)(
|
||||
el, doc, () => hsum, rows, tpsF, cnt3F, durF);
|
||||
|
||||
/* #hsum now holds the four category groups AND the zero-width-space break points between them,
|
||||
so select by class rather than assuming every child is a group. */
|
||||
const groups = hsum.kids.filter((k) => k.cls === "hgrp");
|
||||
const zwsps = hsum.kids.filter((k) => k.tag === "#text" && k.txt === "\u200b");
|
||||
eq(groups.length, 4, "four categories: count, tok/s, prefill, ttft");
|
||||
console.log("== the line has a break point, so a long summary wraps instead of clipping ==");
|
||||
/* The groups are nowrap; without a break opportunity between them the whole line is one
|
||||
* unbreakable run that overflows the row and clips whatever follows it. */
|
||||
eq(zwsps.length, 3, "a zero-width break point between each pair of categories");
|
||||
ok(hsum.kids.every((k) => k.cls === "hgrp" || (k.tag === "#text" && k.txt === "\u200b")),
|
||||
"#hsum holds only groups and break points, nothing else");
|
||||
/* The break point must sit BETWEEN groups, not inside one: a ZWSP inside a nowrap span cannot
|
||||
* break, so it would buy nothing. */
|
||||
for (let i = 1; i < groups.length; i++) {
|
||||
const first = hsum.kids.indexOf(groups[i]);
|
||||
eq(hsum.kids[first - 1].txt, "\u200b", "break point immediately precedes category " + i);
|
||||
}
|
||||
ok(!JSON.stringify(groups.map((g) => g.kids)).includes("\u200b"),
|
||||
"no break point buried inside a nowrap group, where it could not act");
|
||||
console.log("== the dot introduces its category and travels with it ==");
|
||||
eq(groups[0].kids.filter((k) => k.cls === "hsep").length, 0, "the first category carries no leading dot");
|
||||
[1, 2, 3].forEach((i) => {
|
||||
const seps = groups[i].kids.filter((k) => k.cls === "hsep");
|
||||
eq(seps.length, 1, "category " + i + " carries exactly one dot");
|
||||
eq(groups[i].kids[0].cls, "hsep", "the dot is the FIRST child of its own group, not a sibling of it");
|
||||
eq(groups[i].kids[0].txt, "\u00b7", "and it is a middle dot, not a pipe");
|
||||
});
|
||||
console.log("== within a category the fields are separated by pipes ==");
|
||||
const textOf = (g) => g.kids.map((k) => (k.txt || "")).join("");
|
||||
/* The category's own text, excluding the leading dot that introduces it (that dot is the
|
||||
category BREAK and is SUPPOSED to be a dot; "no dot inside" is about the figures. */
|
||||
const ownText = (g) => g.kids.filter((k) => k.cls !== "hsep").map((k) => k.txt || "").join("");
|
||||
const tpsGroup = textOf(groups[1]);
|
||||
const tpsOwn = ownText(groups[1]);
|
||||
ok(tpsGroup.includes("|"), "tok/s separates mean / last 20 / last 5 with pipes: " + JSON.stringify(tpsGroup));
|
||||
ok(!tpsOwn.includes("\u00b7"), "no dot among a category's own figures (the dot means category change): " + JSON.stringify(tpsOwn));
|
||||
ok(/last 20:.*\|.*last 5:/.test(tpsGroup), "both windows present and pipe-separated");
|
||||
console.log("== each figure is the mean of the rows its label names ==");
|
||||
/* Computed independently of the shipped group(): if the shipped slice or threshold drifts
|
||||
(slice(-20) -> slice(-100) survived the old suite), rendered and expected diverge. */
|
||||
const mean = (a) => a.reduce((p, c) => p + c, 0) / a.length;
|
||||
const tv = rows.map((r) => r.tps), pv = rows.map((r) => r.pf);
|
||||
const wantTps = "tok/s mean " + tpsF(mean(tv)) + " | last 20: " + tpsF(mean(tv.slice(-20))) + " | last 5: " + tpsF(mean(tv.slice(-5)));
|
||||
ok(tpsOwn === wantTps, "tok/s figures are the means of all / last 20 / last 5: " + JSON.stringify(tpsOwn) + " want " + JSON.stringify(wantTps));
|
||||
const pfOwn = ownText(groups[2]);
|
||||
const wantPf = "prefill mean " + cnt3F(mean(pv)) + " | last 20: " + cnt3F(mean(pv.slice(-20))) + " | last 5: " + cnt3F(mean(pv.slice(-5)));
|
||||
ok(pfOwn === wantPf, "prefill figures are the means of all / last 20 / last 5: " + JSON.stringify(pfOwn) + " want " + JSON.stringify(wantPf));
|
||||
console.log("== nothing can orphan a unit ==");
|
||||
/* The failure this exists to prevent: "ttft median 810" ending a line and "ms" starting the next.
|
||||
* That happens when the value and its unit are separate wrap opportunities. */
|
||||
const ttft = textOf(groups[3]);
|
||||
const ttftGroup = groups[3];
|
||||
const textNodes = ttftGroup.kids.filter((k) => k.cls !== "hsep");
|
||||
eq(textNodes.length, 1, "the ttft category is a single text node, so value and unit cannot split");
|
||||
const tfsSorted = rows.map((r) => r.ttft).sort((a, b) => a - b);
|
||||
const wantTtft = "ttft median " + durF(tfsSorted[Math.floor(tfsSorted.length / 2)]);
|
||||
ok(textNodes[0].txt === wantTtft,
|
||||
"value and unit are one string, rendered by the shipped dur(): " + JSON.stringify(textNodes[0].txt) + " want " + JSON.stringify(wantTtft));
|
||||
console.log("== the window thresholds: last 20 needs 20 rows, last 5 needs 5 ==");
|
||||
/* Every count sits ADJACENT to a threshold, because that is the only place a threshold can move
|
||||
unnoticed: 19/20 pins the 20 boundary (>=19 fails at 19), 4/5 pins the 5 boundary (>=6 or >=7
|
||||
fails at 5). Counts spaced further apart leave the off-by-one free to move. */
|
||||
for (const [n, want20, want5] of [[4, false, false], [5, false, true], [6, false, true],
|
||||
[7, false, true], [12, false, true], [19, false, true],
|
||||
[20, true, true], [24, true, true]]) {
|
||||
const box = mk("span", "hsum");
|
||||
new Function("el", "document", "$", "hRows", "tps", "cnt3", "dur", BLOCK)(
|
||||
el, doc, () => box, mkRows(n), tpsF, cnt3F, durF);
|
||||
const t = box.kids.filter((k) => k.cls === "hgrp").map((g) => g.kids.map((k) => k.txt || "").join("")).join(" ");
|
||||
eq(t.includes("last 20:"), want20, n + " rows: last 20 " + (want20 ? "shows" : "stays hidden (it would repeat the overall mean)"));
|
||||
eq(t.includes("last 5:"), want5, n + " rows: last 5 " + (want5 ? "shows" : "stays hidden"));
|
||||
}
|
||||
console.log("== the shipped formatters render these exact strings ==");
|
||||
/* The window guards above call tpsF/cnt3F/durF on BOTH sides, so a formatter bug cancels out --
|
||||
replacing tps with a constant passed the whole suite. These literals are the only place the
|
||||
formatters are pinned to something that is not themselves. Values derived from the shipped
|
||||
source; DASH is U+2013, not a hyphen. */
|
||||
eq(tpsF(58), "58.0", "tps keeps one decimal through the middle band");
|
||||
eq(tpsF(54), "54.0", "tps: the GUIDE's F1 example figure");
|
||||
eq(tpsF(9.995), "10.0", "tps lower band boundary is inclusive");
|
||||
eq(tpsF(9.994), "9.99", "tps just under the lower boundary keeps two decimals (kills sig3 9.995->9.994)");
|
||||
eq(tpsF(99.949), "99.9", "tps just under the upper boundary keeps a decimal");
|
||||
eq(tpsF(99.95), "100", "tps upper band boundary is exclusive");
|
||||
eq(tpsF(120), "120", "tps above the band is an integer");
|
||||
eq(tpsF(0), "0", "tps of zero is 0, not 0.00");
|
||||
eq(tpsF(NaN), "\u2013", "tps of a non-finite is the en-dash");
|
||||
eq(cnt3F(691), "691", "cnt3 below the kilo step is a plain integer");
|
||||
eq(cnt3F(1234567), "1.23M", "cnt3 steps to M with three significant figures");
|
||||
eq(durF(0.813), "813 ms", "dur under a second is whole milliseconds");
|
||||
eq(durF(0), "0 ms", "dur of zero is 0 ms");
|
||||
eq(durF(1.7), "1.70 s", "dur just over a second carries two decimals");
|
||||
eq(durF(59.97), "1m 00s", "dur rounds to the shown resolution BEFORE splitting (not 60.0 s)");
|
||||
|
||||
console.log("== the median is falsifiable: an ODD row count ==");
|
||||
/* At n=24 floor(12) and ceil(12) are the same row, so floor->ceil in the shipped median passed
|
||||
every earlier fixture. Only an odd count makes the two candidates differ. */
|
||||
const box25 = mk("span", "hsum");
|
||||
const r25 = mkRows(25);
|
||||
const s25 = r25.map((r) => r.ttft).sort((a, b) => a - b);
|
||||
if (s25[Math.floor(25 / 2)] === s25[Math.ceil(25 / 2)]) throw new Error(
|
||||
"fixture broken: n=25 must make floor and ceil pick different rows");
|
||||
new Function("el", "document", "$", "hRows", "tps", "cnt3", "dur", BLOCK)(
|
||||
el, doc, () => box25, r25, tpsF, cnt3F, durF);
|
||||
const ttft25 = box25.kids.filter((k) => k.cls === "hgrp")[3].kids
|
||||
.filter((k) => k.cls !== "hsep").map((k) => k.txt || "").join("");
|
||||
eq(ttft25, "ttft median 1.70 s", "the shipped median takes the floor row at n=25");
|
||||
|
||||
console.log(fails ? "\n" + fails + " FAILURE(S) of " + checks : "\nALL " + checks + " CHECKS PASS on the shipped history line");
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,15 @@
|
||||
/* Extract the embedded dashboard page's <script> from core/server/dashboard.cpp.
|
||||
The page lives inside a C++ raw string, so a JS test has to pull it out of the
|
||||
translation unit it ships in. Reading the real file is the point: a copy of the
|
||||
page would test the copy. */
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const cpp = fs.readFileSync(
|
||||
path.join(__dirname, "..", "..", "core", "server", "dashboard.cpp"),
|
||||
"utf8",
|
||||
);
|
||||
const page = cpp.match(/R"HTML\(([\s\S]*)\)HTML"/);
|
||||
if (!page) throw new Error("no R\"HTML(...)HTML\" page block in dashboard.cpp");
|
||||
const script = page[1].match(/<script>([\s\S]*)<\/script>/);
|
||||
if (!script) throw new Error("no <script> block in the dashboard page");
|
||||
module.exports = script[1];
|
||||
@@ -0,0 +1,108 @@
|
||||
/* Poll cadence and the time-proportional sparkline. Executes the shipped clampMs,
|
||||
pollCadence, pollSummary, spark and setMetric, sliced by line range out of the page.
|
||||
The window expectations DERIVE from the shipped HIST_S rather than hardcoding 60, so
|
||||
changing the constant moves the expectation instead of silently passing. */
|
||||
const src = require("./page.js");
|
||||
const L = src.split("\n");
|
||||
let fails = 0, checks = 0;
|
||||
const ok = (c, m) => { checks++; if (!c) { fails++; console.log(" FAIL " + m); } };
|
||||
const eq = (a, b, m) => { checks++; if (a !== b) { fails++; console.log(" FAIL " + m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); } };
|
||||
function lines(a, b) {
|
||||
const i = L.findIndex((x) => x.startsWith(a));
|
||||
if (i < 0) throw new Error("no start line: " + a);
|
||||
let j = -1;
|
||||
for (let k = i; k < L.length; k++) if (L[k].startsWith(b)) { j = k; break; }
|
||||
if (j < 0) throw new Error("no end line: " + b);
|
||||
return L.slice(i, j + 1).join("\n");
|
||||
}
|
||||
const HIST_S_SRC = lines("const HIST_S =", "const HIST_S =");
|
||||
const HS = parseInt(HIST_S_SRC.match(/HIST_S\s*=\s*([0-9]+)/)[1], 10);
|
||||
const SPARK = lines("function spark(key, pts) {", "}");
|
||||
const CADENCE = lines("const POLL_K", "const pollCadence =");
|
||||
const SUMMARY = lines("function pollSummary(", "}");
|
||||
const SETMETRIC = lines("function setMetric(key, value, text) {", "}");
|
||||
|
||||
console.log("== the window is a constant, and the expectations read it ==");
|
||||
eq(HS, 60, "HIST_S is 60 as documented");
|
||||
|
||||
function cadence(raw) {
|
||||
const els = {};
|
||||
const lsGet = () => raw;
|
||||
const $ = (id) => (els[id] || (els[id] = { textContent: "" }));
|
||||
return new Function("lsGet", "$", CADENCE + "\n" + SUMMARY +
|
||||
"\npollSummary();\nreturn {clampMs, pollCadence, idle:()=>pollIdleMs, busy:()=>pollBusyMs, sum:()=>$('advsum').textContent};")(lsGet, $);
|
||||
}
|
||||
console.log("== clamp: the field cannot be talked out of a sane rate ==");
|
||||
let c = cadence(null);
|
||||
eq(c.clampMs(50, 500), 100, "below floor clamps to the floor");
|
||||
eq(c.clampMs(9999, 500), 5000, "above ceiling clamps to the ceiling");
|
||||
eq(c.clampMs("", 500), 500, "blank field falls back to its default");
|
||||
eq(c.clampMs("abc", 300), 300, "garbage falls back to its default");
|
||||
eq(c.clampMs(1500, 500), 1500, "in-range passes through");
|
||||
console.log("== defaults, and the in-flight trigger ==");
|
||||
eq(c.idle(), 500, "shipped idle default"); eq(c.busy(), 300, "shipped busy default");
|
||||
eq(c.pollCadence(0), 500, "idle when nothing in flight");
|
||||
eq(c.pollCadence(3), 300, "busy when requests are in flight");
|
||||
console.log("== stored values, and the old key migrating to a flat rate ==");
|
||||
let m = cadence(JSON.stringify({ idle: 700, busy: 200 }));
|
||||
eq(m.idle(), 700, "stored idle honored"); eq(m.busy(), 200, "stored busy honored");
|
||||
m = cadence(JSON.stringify({ ms: 800, adaptive: true }));
|
||||
eq(m.idle(), 800, "old {ms} migrates to idle"); eq(m.busy(), 800, "old {ms} migrates to a FLAT rate");
|
||||
m = cadence("{ not json");
|
||||
eq(m.idle(), 500, "corrupt storage falls back to the default");
|
||||
eq(m.busy(), 300, "corrupt storage keeps the busy default");
|
||||
eq(cadence(JSON.stringify({ idle: 50 })).idle(), 100, "a stored sub-floor value is clamped on read");
|
||||
console.log("== the summary label never lies about what is set ==");
|
||||
eq(c.sum(), "500 ms idle | 300 ms busy", "two values shown when they differ");
|
||||
eq(cadence(JSON.stringify({ idle: 500, busy: 500 })).sum(), "500 ms", "one value shown when equal");
|
||||
|
||||
let lastD = null;
|
||||
const M = {}, hist = {};
|
||||
let nowS = 0;
|
||||
eval(HIST_S_SRC + "\n" + SPARK);
|
||||
const xs = (d) => (d.match(/[ML]([0-9.]+)/g) || []).map((s) => parseFloat(s.slice(1)));
|
||||
console.log("== the sparkline's x axis is time, not sample index ==");
|
||||
M.k = { line: { setAttribute: (n, v) => { if (n === "d") lastD = v; } } };
|
||||
let pts = []; for (let i = 0; i < 60; i++) pts.push({ t: i, v: 50 + (i % 7) });
|
||||
spark("k", pts); let X = xs(lastD);
|
||||
eq(X.length, 60, "all 60 points drawn");
|
||||
ok(Math.abs(X[59] - 200) < 0.06, "newest sample sits on the right edge (got " + X[59] + ")");
|
||||
ok(Math.abs(X[0] - 200 * (1 - 59 / HS)) < 0.06, "oldest of a 59s span sits at its time position (got " + X[0] + ")");
|
||||
pts = []; for (let i = 0; i < 10; i++) pts.push({ t: i * 0.1, v: 1 });
|
||||
for (let i = 1; i <= 10; i++) pts.push({ t: 0.9 + i, v: 1 });
|
||||
spark("k", pts); X = xs(lastD);
|
||||
const ratio = (X[9] - X[0]) / (X[19] - X[0]);
|
||||
const want = 0.9 / 10.9;
|
||||
ok(Math.abs(ratio - want) < 0.01, "the busy stretch gets its 0.9s of the 10.9s span (got " + ratio.toFixed(4) + " want " + want.toFixed(4) + ")");
|
||||
ok(Math.abs(ratio - 0.5) > 0.2, "and NOT the 10/20 index-spacing answer 0.5 (got " + ratio.toFixed(4) + ")");
|
||||
console.log("== startup fills in from the right; a sample gap draws as a line gap ==");
|
||||
spark("k", [{ t: 100, v: 1 }, { t: 101, v: 2 }, { t: 102, v: 3 }]); X = xs(lastD);
|
||||
ok(X[0] > 190, "3 samples spanning 2s all sit near the right edge (leftmost x=" + X[0] + ")");
|
||||
spark("k", [{ t: 0, v: 1 }, { t: 1, v: 2 }, { t: 50, v: 3 }]); X = xs(lastD);
|
||||
ok(X[2] - X[1] > 10 * (X[1] - X[0]), "a 49s gap draws far wider than a 1s step");
|
||||
spark("k", [{ t: 1, v: 1 }, { t: 2, v: 2 }]); eq(lastD, "", "2 points draw nothing");
|
||||
console.log("== the prune is the SHIPPED setMetric, actually called ==");
|
||||
function shippedPrune(seed, nowSVal, value) {
|
||||
const Mm = { m: { n: { firstChild: { nodeValue: "" } }, line: { setAttribute: () => {} } } };
|
||||
const hh = { m: seed.slice() };
|
||||
/* v is passed as a parameter, not interpolated into the source: interpolating the string
|
||||
"null" and the literal null produce the same text, so the null case would not be null. */
|
||||
new Function("M", "hist", "nowS", "spark", "HIST_S", "v", SETMETRIC + "\nsetMetric('m', v, 'x');\nreturn hist;")(Mm, hh, nowSVal, () => {}, HS, value);
|
||||
return hh.m;
|
||||
}
|
||||
let fast = []; for (let i = 0; i < 600; i++) fast.push({ t: i * 0.1, v: 1 });
|
||||
let r = shippedPrune(fast, 60, 1);
|
||||
eq(r.length, 601, HS + "s of 100ms samples: nothing pruned, plus the sample just recorded");
|
||||
eq(r[r.length - 1].t, 60, "the new sample is stamped with nowS");
|
||||
let slow = []; for (let i = 0; i < 600; i++) slow.push({ t: i * 5, v: 1 });
|
||||
r = shippedPrune(slow, 3000, 1);
|
||||
eq(r.length, Math.ceil(HS / 5) + 1, HS + "s of 5s samples keeps " + Math.ceil(HS / 5) + " plus the new one, not 601");
|
||||
eq(r[0].t, 3000 - HS, "the oldest survivor is the first sample inside the window");
|
||||
let edge = []; for (let i = 0; i < 5; i++) edge.push({ t: 1000 + i, v: 1 });
|
||||
eq(shippedPrune(edge, 1000 + HS, 1).length, 6, "a sample exactly at nowS-HIST_S survives (exclusive <)");
|
||||
eq(shippedPrune(edge, 1001 + HS, 1).length, 5, "one second later that same sample is pruned");
|
||||
r = shippedPrune([{ t: 10, v: 1 }], 1005, null);
|
||||
eq(r.length, 1, "a null reading records nothing and prunes nothing");
|
||||
eq(r[0].t, 10, "the earlier sample is untouched");
|
||||
console.log(fails ? "\n" + fails + " FAILURE(S) of " + checks : "\nALL " + checks + " CHECKS PASS on the shipped page JS");
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -0,0 +1,109 @@
|
||||
/* MANUAL render check -- not part of the suite, and not wired into CMake.
|
||||
*
|
||||
* It loads the dashboard in headless Chrome, screenshots the Requests header at 4x, and finds
|
||||
* the lowest inked pixel row of the caption's letters and of the download glyph's tray bar.
|
||||
* That is the only way to answer "is the icon level with the text": the CSS says where the
|
||||
* BOX goes, and the box is not the glyph.
|
||||
*
|
||||
* Needs puppeteer + a Chrome binary, which are NOT repo dependencies:
|
||||
* npm i puppeteer && npx puppeteer browsers install chrome
|
||||
* Then, with the page served (the viewer on :8900, or production on :8800):
|
||||
* node tests/js/render_align.js [url]
|
||||
* Exits nonzero if the two bottoms are not on the same device pixel row.
|
||||
*
|
||||
* Why this exists: the separator and glyph work went through three commits that each asserted
|
||||
* an alignment from the geometry -- "13px per boundary", "flush with the viewBox bottom, so it
|
||||
* sits on the baseline" -- and both claims were false. The first collapsed to zero width in
|
||||
* HTML; the second aligned the SVG box to the baseline while the baseline sits above the box
|
||||
* bottom, leaving the bar 2px high. A unit test cannot see either, because neither is about the
|
||||
* string the code builds. Measure the pixels.
|
||||
*/
|
||||
const puppeteer = require("puppeteer");
|
||||
const URL0 = process.argv[2] || "http://127.0.0.1:8900/";
|
||||
(async () => {
|
||||
const browser = await puppeteer.launch({
|
||||
headless: "new",
|
||||
args: ["--no-sandbox", "--disable-setuid-sandbox", "--font-render-hinting=none"],
|
||||
});
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport({ width: 1400, height: 900, deviceScaleFactor: 4 });
|
||||
await page.goto(URL0, { waitUntil: "networkidle2", timeout: 30000 });
|
||||
await page.waitForSelector("#reqjson", { timeout: 10000 });
|
||||
|
||||
// the Requests caption and the download glyph, as laid out on the real page
|
||||
const boxes = await page.evaluate(() => {
|
||||
const btn = document.getElementById("reqjson");
|
||||
const cap = btn.closest(".pleft").querySelector(".cap");
|
||||
const svg = btn.querySelector("svg");
|
||||
const cs = getComputedStyle(cap);
|
||||
const r = (e) => { const b = e.getBoundingClientRect(); return {x:b.x,y:b.y,w:b.width,h:b.height,bottom:b.bottom}; };
|
||||
return { cap: r(cap), svg: r(svg), btn: r(btn), font: cs.fontFamily, size: cs.fontSize,
|
||||
align: getComputedStyle(btn.closest(".pleft")).alignItems };
|
||||
});
|
||||
console.log("cap ", JSON.stringify(boxes.cap));
|
||||
console.log("svg ", JSON.stringify(boxes.svg));
|
||||
console.log("align-items:", boxes.align, " font:", boxes.size, boxes.font.slice(0, 40));
|
||||
|
||||
// screenshot the strip containing both, then decode IN THE BROWSER and find ink rows
|
||||
const x0 = Math.floor(boxes.cap.x) - 2, x1 = Math.ceil(boxes.svg.x + boxes.svg.w) + 2;
|
||||
const y0 = Math.floor(Math.min(boxes.cap.y, boxes.svg.y)) - 4;
|
||||
const y1 = Math.ceil(Math.max(boxes.cap.bottom, boxes.svg.bottom)) + 6;
|
||||
const shot = await page.screenshot({ encoding: "base64",
|
||||
clip: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } });
|
||||
|
||||
const res = await page.evaluate(async (b64, capX, svgX, x0, y0, scale) => {
|
||||
const img = new Image();
|
||||
img.src = "data:image/png;base64," + b64;
|
||||
await img.decode();
|
||||
const c = document.createElement("canvas");
|
||||
c.width = img.width; c.height = img.height;
|
||||
const g = c.getContext("2d", { willReadFrequently: true });
|
||||
g.drawImage(img, 0, 0);
|
||||
const d = g.getImageData(0, 0, c.width, c.height).data;
|
||||
// ink = pixel meaningfully brighter than the near-black background
|
||||
const rowInk = (xFrom, xTo) => {
|
||||
const xa = Math.max(0, Math.round((xFrom - x0) * scale));
|
||||
const xb = Math.min(c.width, Math.round((xTo - x0) * scale));
|
||||
const rows = [];
|
||||
for (let y = 0; y < c.height; y++) {
|
||||
let mx = 0;
|
||||
for (let x = xa; x < xb; x++) {
|
||||
const i = (y * c.width + x) * 4;
|
||||
mx = Math.max(mx, d[i], d[i + 1], d[i + 2]);
|
||||
}
|
||||
rows.push(mx);
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
const lastInk = (rows, thr) => { for (let y = rows.length - 1; y >= 0; y--) if (rows[y] > thr) return y; return -1; };
|
||||
const firstInk = (rows, thr) => { for (let y = 0; y < rows.length; y++) if (rows[y] > thr) return y; return -1; };
|
||||
const capRows = rowInk(capX.x, capX.x + capX.w);
|
||||
const svgRows = rowInk(svgX.x, svgX.x + svgX.w);
|
||||
const T = 60; // background is ~#0a0a0a; text/icon are #7b7b7b / #4d4d4d
|
||||
return {
|
||||
imgH: c.height, scale,
|
||||
capFirst: firstInk(capRows, T), capLast: lastInk(capRows, T),
|
||||
svgFirst: firstInk(svgRows, T), svgLast: lastInk(svgRows, T),
|
||||
peakCap: Math.max(...capRows), peakSvg: Math.max(...svgRows),
|
||||
};
|
||||
}, shot, boxes.cap, boxes.svg, x0, y0, 4);
|
||||
|
||||
console.log("url:", URL0);
|
||||
console.log("decoded:", JSON.stringify(res));
|
||||
if (res.capLast < 0 || res.svgLast < 0) { console.log("MEASUREMENT FAILED: no ink found in a region"); }
|
||||
else {
|
||||
const gapDevice = res.svgLast - res.capLast;
|
||||
const gapCss = gapDevice / 4;
|
||||
console.log("\n bottom of REQUESTS ink : device row " + res.capLast);
|
||||
console.log(" bottom of tray-bar ink : device row " + res.svgLast);
|
||||
console.log(" GAP = " + gapDevice + " device px = " + gapCss.toFixed(2) + " CSS px");
|
||||
console.log(" " + (gapCss === 0 ? "PERFECTLY FLUSH" :
|
||||
(gapCss > 0 ? "icon sits " + gapCss.toFixed(2) + "px BELOW the letters"
|
||||
: "icon sits " + Math.abs(gapCss).toFixed(2) + "px ABOVE the letters")));
|
||||
}
|
||||
const flush = res.capLast >= 0 && res.svgLast >= 0 && res.svgLast === res.capLast;
|
||||
console.log(flush ? "\nPASS: tray bar and caption bottoms share a device row"
|
||||
: "\nFAIL: not level (see GAP above)");
|
||||
await browser.close();
|
||||
process.exit(flush ? 0 : 1);
|
||||
})().catch((e) => { console.log("ERROR: " + e.message); process.exit(1); });
|
||||
@@ -15,7 +15,7 @@ command -v python3 >/dev/null 2>&1 || { echo " SKIP python3 not present"; exit
|
||||
python3 - "$REPORT" <<'PY'
|
||||
import re, sys
|
||||
lines = open(sys.argv[1]).read().split("\n")
|
||||
pat = re.compile(r"`lib\w+`: (\d+) row\(s\) not reached:")
|
||||
pat = re.compile(r"`\w+`: (\d+) row\(s\) not reached:")
|
||||
heads = [(i, m.group(1)) for i, l in enumerate(lines) if (m := pat.match(l))]
|
||||
bad = 0
|
||||
for j, (a, claimed) in enumerate(heads):
|
||||
|
||||
@@ -4363,6 +4363,31 @@ TEST(the_session_view_says_what_a_return_reuses_and_what_is_off_the_card) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Conversations under one shared first block (a decision model's instructions, which no request
|
||||
* evicts) keep at most 1024 rows: the least recently used row goes, the newest stay. Before, every
|
||||
* request added a row and each insert walked all of them (#375). */
|
||||
TEST(a_shared_root_keeps_a_bounded_session_table) {
|
||||
IdleTiers t;
|
||||
CHECK_OK(t.configure(tier_config(0, 1024)));
|
||||
constexpr uint64_t kRows = 1500;
|
||||
for (uint64_t i = 1; i <= kRows; ++i)
|
||||
t.note_session(i, {bh(1), bh(1000 + i)}, 32, i * SEC);
|
||||
std::vector<IdleTiers::SessionInfo> s = t.sessions();
|
||||
CHECK_EQ(s.size(), 1024u);
|
||||
bool newest = false, oldest = false;
|
||||
for (const auto& r : s) {
|
||||
newest |= r.id == kRows;
|
||||
oldest |= r.id == 1;
|
||||
}
|
||||
CHECK(newest);
|
||||
CHECK(!oldest);
|
||||
/* A later turn of a kept conversation still absorbs its row. */
|
||||
t.note_session(kRows + 1, {bh(1), bh(1000 + kRows), bh(7)}, 48, (kRows + 1) * SEC);
|
||||
s = t.sessions();
|
||||
CHECK_EQ(s.size(), 1024u);
|
||||
for (const auto& r : s) CHECK(r.id != kRows);
|
||||
}
|
||||
|
||||
TEST(tiers_stay_off_until_a_size_is_given) {
|
||||
IdleTiers t;
|
||||
CHECK_OK(t.configure(tier_config(0, 1024)));
|
||||
@@ -7273,6 +7298,76 @@ TEST(the_prefill_stage_is_two_layers_of_what_the_card_leaves_off) {
|
||||
}
|
||||
}
|
||||
|
||||
/* --gpu-memory-mib N is --gpu-headroom-mib (card - N): the same split, the same pools. Over the
|
||||
* card is a named refuse, and the trial still writes nothing. */
|
||||
TEST(gpu_memory_mib_is_the_inverse_of_gpu_headroom_mib) {
|
||||
constexpr int64_t MiB = 1 << 20;
|
||||
constexpr int64_t cap_mib = 16384;
|
||||
{
|
||||
Config via_head = derive_config();
|
||||
via_head.gpu_headroom_mib = 256;
|
||||
Config via_mem = derive_config();
|
||||
via_mem.gpu_memory_mib = cap_mib - 256;
|
||||
VramBudget bh, bm;
|
||||
int rc_h = 0, rc_m = 0;
|
||||
stderr_of([&] {
|
||||
rc_h = vram_budget_resolve(via_head, { hand_facts(false) }, &bh);
|
||||
rc_m = vram_budget_resolve(via_mem, { hand_facts(false) }, &bm);
|
||||
});
|
||||
CHECK_OK(rc_h);
|
||||
CHECK_OK(rc_m);
|
||||
CHECK_EQ(bh.headroom, bm.headroom);
|
||||
CHECK_EQ(bh.claimable, bm.claimable);
|
||||
CHECK_EQ(via_head.vram_weights_mib, via_mem.vram_weights_mib);
|
||||
CHECK_EQ(via_head.vram_kv_mib, via_mem.vram_kv_mib);
|
||||
CHECK_EQ(via_mem.gpu_headroom_mib, 256ll);
|
||||
CHECK_EQ(via_mem.given["--gpu-headroom-mib"], std::string("derived from --gpu-memory-mib"));
|
||||
}
|
||||
{
|
||||
Config c = derive_config();
|
||||
c.gpu_memory_mib = cap_mib; /* headroom 0 */
|
||||
VramBudget b;
|
||||
int rc = 0;
|
||||
stderr_of([&] { rc = vram_budget_resolve(c, { hand_facts(false) }, &b); });
|
||||
CHECK_OK(rc);
|
||||
CHECK_EQ(c.gpu_headroom_mib, 0ll);
|
||||
CHECK_EQ(b.headroom, 0ll);
|
||||
CHECK_EQ(b.claimable, (15096 + 96) * MiB);
|
||||
}
|
||||
{
|
||||
Config c = derive_config();
|
||||
c.gpu_memory_mib = cap_mib + 1;
|
||||
VramBudget b;
|
||||
int rc = 0;
|
||||
stderr_of([&] { rc = vram_budget_resolve(c, { hand_facts(false) }, &b); });
|
||||
CHECK_EQ(rc, RAD_E_INVAL);
|
||||
CHECK(has(b.report, "--gpu-memory-mib"));
|
||||
CHECK_EQ(c.gpu_headroom_mib, 96ll); /* not rewritten on refuse */
|
||||
}
|
||||
{
|
||||
Config c = derive_config();
|
||||
c.gpu_memory_mib = cap_mib - 256;
|
||||
const Config before = c;
|
||||
VramBudget t;
|
||||
CHECK_OK(vram_budget_trial(c, { hand_facts(false) }, &t));
|
||||
CHECK_EQ(c.gpu_headroom_mib, before.gpu_headroom_mib);
|
||||
CHECK_EQ(c.vram_weights_mib, before.vram_weights_mib);
|
||||
CHECK_EQ(c.vram_kv_mib, before.vram_kv_mib);
|
||||
CHECK_EQ(t.headroom, 256 * MiB);
|
||||
}
|
||||
/* A device with no capacity has nothing to claim: the flag is ignored. */
|
||||
{
|
||||
Config c = derive_config();
|
||||
c.gpu_memory_mib = 4096;
|
||||
VramFacts f{};
|
||||
f.kv_ceiling = 300LL << 20;
|
||||
VramBudget b;
|
||||
CHECK_OK(vram_budget_resolve(c, { f }, &b));
|
||||
CHECK_EQ(c.gpu_headroom_mib, 96ll);
|
||||
CHECK_EQ(c.vram_kv_mib, 300ll);
|
||||
}
|
||||
}
|
||||
|
||||
/* Over random cards and programs the split either refuses by name or hands out no more than the
|
||||
* card: every granted pool plus every fixed term fits the capacity, with at most the MiB each of
|
||||
* the two pools may round into the headroom. The shares add up to the elastic part, the static
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""mkgemma4ugolden.py OUT.h -- goldens for tests/mm_test.cpp's Gemma 4 12B ("unified") cases, every number
|
||||
from transformers' own code (transformers 5.15 or later, torch, torchvision and numpy).
|
||||
|
||||
The reference is the processors google/gemma-4-12B-it's processor_config.json names, with its settings:
|
||||
Gemma4UnifiedImageProcessor (rescale u / 255, no normalisation), Gemma4UnifiedVideoProcessor (rescale
|
||||
and an identity normalisation, mean 0 and deviation 1) and Gemma4UnifiedAudioFeatureExtractor.
|
||||
|
||||
* pictures already at their size: the grid of 48-pixel windows, the soft-token count, and the FNV-1a
|
||||
of every merged patch as the embedder reads it (the processor's float32 cast to bfloat16), patches
|
||||
in the reference's order, which is row-major. Exact.
|
||||
* a three-frame clip at a size its budget keeps, every patch value exactly;
|
||||
* a 16037-sample clip of audio: the frames, their count, and the FNV-1a of every sample cast to
|
||||
bfloat16. The sample at i is ((i * 7919) % 2001 - 1000) / 1000 in float32.
|
||||
|
||||
The pixel at (frame f, row y, column x, channel c) is mm_test's splitmix hash.
|
||||
"""
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import transformers
|
||||
from PIL import Image
|
||||
from transformers.models.gemma4.image_processing_pil_gemma4 import get_aspect_ratio_preserving_size
|
||||
from transformers.models.gemma4_unified.feature_extraction_gemma4_unified import \
|
||||
Gemma4UnifiedAudioFeatureExtractor
|
||||
from transformers.models.gemma4_unified.image_processing_gemma4_unified import Gemma4UnifiedImageProcessor
|
||||
from transformers.models.gemma4_unified.video_processing_gemma4_unified import Gemma4UnifiedVideoProcessor
|
||||
|
||||
PATCH, POOL = 16, 3
|
||||
U = np.uint64
|
||||
|
||||
|
||||
def picture(f, h, w):
|
||||
"""[h, w, 3] uint8, mm_test's pix(f, y, x, c)."""
|
||||
with np.errstate(over="ignore"):
|
||||
y = np.arange(h, dtype=U).reshape(h, 1, 1)
|
||||
x = np.arange(w, dtype=U).reshape(1, w, 1)
|
||||
c = np.arange(3, dtype=U).reshape(1, 1, 3)
|
||||
z = (U(f) * U(0x9E3779B97F4A7C15) + y * U(0xBF58476D1CE4E5B9) +
|
||||
x * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345))
|
||||
z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9)
|
||||
z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB)
|
||||
return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8)
|
||||
|
||||
|
||||
def fnv16(bits):
|
||||
h = 0xcbf29ce484222325
|
||||
for v in bits.astype(np.uint16).ravel().tolist():
|
||||
for b in (v & 255, v >> 8):
|
||||
h = ((h ^ b) * 0x100000001b3) & ((1 << 64) - 1)
|
||||
return h
|
||||
|
||||
|
||||
def bf16(a):
|
||||
t = torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32))
|
||||
return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16)
|
||||
|
||||
|
||||
def raster_ok(pos, gh, gw):
|
||||
k = np.arange(gh * gw)
|
||||
return (pos[:, 0] == k % gw).all() and (pos[:, 1] == k // gw).all()
|
||||
|
||||
|
||||
def main(out):
|
||||
L = ["/* gemma4u_golden.h -- GENERATED by mkgemma4ugolden.py from transformers %s; do not edit. */"
|
||||
% transformers.__version__, "#pragma once", "#include <cstdint>", ""]
|
||||
ip = Gemma4UnifiedImageProcessor(patch_size=PATCH, pooling_kernel_size=POOL, do_normalize=False,
|
||||
image_mean=[0.0] * 3, image_std=[1.0] * 3)
|
||||
L.append("struct GoldGemma4uPic { int32_t f, h, w, budget, grid_h, grid_w, soft; uint64_t fnv; "
|
||||
"uint16_t head[8]; };")
|
||||
L.append("static const GoldGemma4uPic kGoldGemma4uPics[] = {")
|
||||
for f, h, w, budget in [(2, 336, 480, 70), (6, 432, 672, 140)]:
|
||||
assert get_aspect_ratio_preserving_size(h, w, PATCH, budget * POOL * POOL, POOL) == (h, w)
|
||||
r = ip(images=[Image.fromarray(picture(f, h, w), "RGB")], max_soft_tokens=budget, return_tensors="np")
|
||||
pos = np.asarray(r["image_position_ids"][0])
|
||||
real = pos[:, 0] >= 0
|
||||
gw, gh = int(pos[real, 0].max()) + 1, int(pos[real, 1].max()) + 1
|
||||
assert raster_ok(pos[real], gh, gw)
|
||||
bits = bf16(np.asarray(r["pixel_values"][0])[real])
|
||||
L.append(" { %d, %d, %d, %d, %d, %d, %d, 0x%016xull, { %s } }," %
|
||||
(f, h, w, budget, gh, gw, int(r["num_soft_tokens_per_image"][0]), fnv16(bits),
|
||||
", ".join(str(int(v)) for v in bits.ravel()[:8])))
|
||||
L.append("};")
|
||||
|
||||
vp = Gemma4UnifiedVideoProcessor(patch_size=PATCH, pooling_kernel_size=POOL, do_normalize=True,
|
||||
image_mean=[0.0] * 3, image_std=[1.0] * 3)
|
||||
fh, fw, frames = 336, 432, [4, 5, 6]
|
||||
assert get_aspect_ratio_preserving_size(fh, fw, PATCH, 70 * POOL * POOL, POOL) == (fh, fw)
|
||||
clip = np.stack([picture(f, fh, fw) for f in frames])
|
||||
assert (clip == 127).any(), "the clip holds no byte 127"
|
||||
r = vp(videos=[clip], max_soft_tokens=70, do_sample_frames=False, return_tensors="pt")
|
||||
pv = r["pixel_values_videos"].reshape(len(frames), -1, r["pixel_values_videos"].shape[-1]).numpy()
|
||||
pos = r["video_position_ids"].reshape(len(frames), -1, 2).numpy()
|
||||
real = pos[0, :, 0] >= 0
|
||||
gw, gh = int(pos[0, real, 0].max()) + 1, int(pos[0, real, 1].max()) + 1
|
||||
assert all(raster_ok(pos[i, real], gh, gw) for i in range(len(frames)))
|
||||
L.append("static const int32_t kGoldGemma4uClipFrames[] = { %s };" % ", ".join(map(str, frames)))
|
||||
L.append("static const int32_t kGoldGemma4uClipH = %d, kGoldGemma4uClipW = %d, kGoldGemma4uClipGridH "
|
||||
"= %d, kGoldGemma4uClipGridW = %d, kGoldGemma4uClipSoft = %d;" %
|
||||
(fh, fw, gh, gw, int(r["num_soft_tokens_per_video"][0])))
|
||||
L.append("static const uint64_t kGoldGemma4uClipFnv = 0x%016xull;" % fnv16(bf16(pv[:, real, :])))
|
||||
|
||||
fe = Gemma4UnifiedAudioFeatureExtractor(feature_size=640, sampling_rate=16000, audio_samples_per_token=640)
|
||||
n = 16037
|
||||
x = ((np.arange(n, dtype=np.int64) * 7919 % 2001 - 1000) / 1000.0).astype(np.float32)
|
||||
r = fe(x, return_tensors="np")
|
||||
feats = np.asarray(r["input_features"][0])
|
||||
assert int(np.asarray(r["input_features_mask"][0]).sum()) == feats.shape[0]
|
||||
L.append("static const int32_t kGoldGemma4uAudioN = %d, kGoldGemma4uAudioFrames = %d;" % (n, feats.shape[0]))
|
||||
L.append("static const uint64_t kGoldGemma4uAudioFnv = 0x%016xull;" % fnv16(bf16(feats)))
|
||||
with open(out, "w") as f:
|
||||
f.write("\n".join(L) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1])
|
||||
@@ -22,7 +22,9 @@
|
||||
#include "mm/media.h"
|
||||
#include "mm/processor.h"
|
||||
#include "gemma4_golden.h"
|
||||
#include "gemma4u_golden.h"
|
||||
#include "glm5_golden.h"
|
||||
#include "radio_golden.h"
|
||||
#include "imaging_golden.h"
|
||||
#include "lfm2_golden.h"
|
||||
#include "mm/resample.h"
|
||||
@@ -584,6 +586,62 @@ std::vector<uint16_t> raster(const Item& it, int32_t s) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
VisionConfig radio_cfg() {
|
||||
VisionConfig c;
|
||||
c.family = Family::Radio;
|
||||
c.patch = kRadioPatch;
|
||||
c.merge = kRadioMerge;
|
||||
c.temporal = 1;
|
||||
c.radio_min_patches = kRadioMinP;
|
||||
c.radio_max_patches = kRadioMaxP;
|
||||
c.radio_max_len = kRadioMaxLen;
|
||||
c.radio_video_patches = kRadioVideoP;
|
||||
c.radio_tubelet = 2;
|
||||
c.radio_prefix = 10;
|
||||
return c;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* NVIDIA's tile rule, Python's round-half-even included (a side that is an odd multiple of 16
|
||||
* takes one patch more than an even one), for pictures and video frames. */
|
||||
TEST(radio_sizes_are_the_references) {
|
||||
const VisionConfig c = radio_cfg();
|
||||
for (const GoldRadioSize& g : kGoldRadioSize) {
|
||||
int32_t pw = 0, ph = 0, vw = 0, vh = 0;
|
||||
radio_size(g.w, g.h, c, &pw, &ph);
|
||||
radio_video_size(g.w, g.h, c, &vw, &vh);
|
||||
if (pw != g.pw || ph != g.ph || vw != g.vw || vh != g.vh)
|
||||
std::fprintf(stderr, " %lld x %lld: tile %d x %d, frame %d x %d; reference %d x %d, "
|
||||
"%d x %d\n", (long long)g.w, (long long)g.h, pw, ph, vw, vh, g.pw, g.ph,
|
||||
g.vw, g.vh);
|
||||
CHECK_EQ(pw, g.pw);
|
||||
CHECK_EQ(ph, g.ph);
|
||||
CHECK_EQ(vw, g.vw);
|
||||
CHECK_EQ(vh, g.vh);
|
||||
}
|
||||
}
|
||||
|
||||
/* torch's antialiased bicubic on float pixels, shrinking and growing, overshoot kept. */
|
||||
TEST(radio_resize_is_torchs_antialiased_bicubic_on_floats) {
|
||||
Frame f;
|
||||
f.w = 7;
|
||||
f.h = 5;
|
||||
f.rgb.resize(7 * 5 * 3);
|
||||
for (int y = 0; y < 5; ++y)
|
||||
for (int x = 0; x < 7; ++x)
|
||||
for (int c = 0; c < 3; ++c)
|
||||
f.rgb[((size_t)y * 7 + x) * 3 + c] = (uint8_t)((37 * x + 11 * y + 53 * c) % 256);
|
||||
struct Case { int w, h; const float* want; };
|
||||
const Case cases[] = { { 4, 3, kGoldRadioAa43 }, { 9, 6, kGoldRadioAa96 } };
|
||||
for (const Case& k : cases) {
|
||||
std::vector<float> out;
|
||||
resize_bicubic_aa_f32(f, k.w, k.h, &out);
|
||||
REQUIRE_EQ(out.size(), (size_t)(k.w * k.h * 3));
|
||||
for (size_t i = 0; i < out.size(); ++i) CHECK_NEAR(out[i], k.want[i], 2e-3);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_sizes_are_the_references) {
|
||||
for (const GoldGemma4Size& g : kGoldGemma4Size) {
|
||||
int64_t oh = 0, ow = 0;
|
||||
@@ -733,6 +791,182 @@ TEST(gemma4_frames_are_sampled_as_the_reference_does) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== Gemma 4 12B's processor
|
||||
*
|
||||
* gemma4u_golden.h: the 12B's processors with its processor_config.json's settings
|
||||
* (Gemma4UnifiedImageProcessor, Gemma4UnifiedVideoProcessor, Gemma4UnifiedAudioFeatureExtractor). A
|
||||
* patch is a whole 48 x 48 pooling window (merge 1), its values u / 255; the reference's patches are
|
||||
* row-major, as merge 1 makes this processor's. */
|
||||
namespace {
|
||||
|
||||
VisionConfig gemma4u_cfg(int32_t image_soft, int32_t video_soft) {
|
||||
VisionConfig c = gemma4_cfg(image_soft, video_soft);
|
||||
c.patch = kGemma4Patch * kGemma4Pool;
|
||||
c.merge = 1;
|
||||
c.unit_pixels = true;
|
||||
c.max_patches = 1120;
|
||||
return c;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A 48-pixel window as one patch sizes a picture as the 16-pixel patches pooled 3 x 3 do. */
|
||||
TEST(gemma4_unified_sizes_are_the_references) {
|
||||
for (const GoldGemma4Size& g : kGoldGemma4Size) {
|
||||
int64_t oh = 0, ow = 0;
|
||||
std::string why;
|
||||
const int rc = gemma4_size(g.h, g.w, kGemma4Patch * kGemma4Pool, 1, g.budget, &oh, &ow, &why);
|
||||
if (g.oh == 0) {
|
||||
CHECK(rc < 0);
|
||||
continue;
|
||||
}
|
||||
CHECK_EQ(rc, RAD_OK);
|
||||
CHECK_EQ(oh, g.oh);
|
||||
CHECK_EQ(ow, g.ow);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(gemma4_unified_pictures_patchify_as_the_reference_does) {
|
||||
for (const GoldGemma4uPic& g : kGoldGemma4uPics) {
|
||||
Processor p;
|
||||
REQUIRE_EQ(p.init(gemma4u_cfg(g.budget, 70), [](const std::string&) {
|
||||
return std::vector<int32_t>{};
|
||||
}), RAD_OK);
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.image_from(frame(g.f, g.h, g.w), &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
CHECK_EQ(it->grid_h, g.grid_h);
|
||||
CHECK_EQ(it->grid_w, g.grid_w);
|
||||
REQUIRE_EQ(it->n_seg, 1);
|
||||
CHECK_EQ(it->n_rows(), (int64_t)g.soft);
|
||||
REQUIRE_EQ(it->patch_dim, (int64_t)3 * 48 * 48);
|
||||
const std::vector<uint16_t> r = raster(*it, 0);
|
||||
CHECK(r == it->pixels);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(r[(size_t)i], g.head[i]);
|
||||
if (fnv(r) != g.fnv)
|
||||
std::fprintf(stderr, " picture %d x %d at %d soft tokens: patches differ\n", g.h, g.w,
|
||||
g.budget);
|
||||
CHECK_EQ(fnv(r), g.fnv);
|
||||
REQUIRE_EQ(it->expand.size(), (size_t)g.soft + 2);
|
||||
CHECK_EQ(it->expand.front(), 255999);
|
||||
CHECK_EQ(it->expand.back(), 258882);
|
||||
CHECK_EQ((int64_t)std::count(it->expand.begin(), it->expand.end(), 258880), (int64_t)g.soft);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_gemma4_unified_clip_patchifies_as_the_reference_does) {
|
||||
Processor p;
|
||||
REQUIRE_EQ(p.init(gemma4u_cfg(280, 70), [](const std::string&) {
|
||||
return std::vector<int32_t>{};
|
||||
}), RAD_OK);
|
||||
Video v;
|
||||
v.info.n_frames = 8;
|
||||
v.info.fps = 1.0;
|
||||
v.info.w = kGoldGemma4uClipW;
|
||||
v.info.h = kGoldGemma4uClipH;
|
||||
for (int32_t f : kGoldGemma4uClipFrames) {
|
||||
v.index.push_back(f);
|
||||
v.frames.push_back(frame(f, kGoldGemma4uClipH, kGoldGemma4uClipW));
|
||||
}
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.video_from(v, &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
REQUIRE_EQ(it->n_seg, (int32_t)v.frames.size());
|
||||
CHECK_EQ(it->grid_h, kGoldGemma4uClipGridH);
|
||||
CHECK_EQ(it->grid_w, kGoldGemma4uClipGridW);
|
||||
CHECK_EQ(it->seg_rows, kGoldGemma4uClipSoft);
|
||||
if (fnv(it->pixels) != kGoldGemma4uClipFnv)
|
||||
std::fprintf(stderr, " unified clip: patches differ\n");
|
||||
CHECK_EQ(fnv(it->pixels), kGoldGemma4uClipFnv);
|
||||
}
|
||||
|
||||
/* The 12B's audio: frames of 640 samples as they are, the last zero-padded, one placeholder each
|
||||
* between <boa> and <eoa>; read from what a converted container states. */
|
||||
TEST(a_gemma4_unified_clip_of_audio_is_its_samples_in_frames) {
|
||||
const char* keys[] = { "audio_config.model_type", "audio_config.audio_embed_dim",
|
||||
"processor.feature_extractor.sampling_rate",
|
||||
"processor.feature_extractor.audio_samples_per_token",
|
||||
"processor.audio_seq_length", "audio_token_id", "boa_token_id",
|
||||
"eoa_token_index" };
|
||||
const char* vals[] = { "gemma4_unified_audio", "640", "16000", "640", "750", "258881", "256000",
|
||||
"258883" };
|
||||
RadModelMeta m{};
|
||||
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
|
||||
m.kv_key = keys;
|
||||
m.kv_val = vals;
|
||||
mm::AudioConfig c;
|
||||
std::string why;
|
||||
REQUIRE_EQ(c.from_meta(m, &why), RAD_OK);
|
||||
CHECK(c.family == mm::AudioFamily::Gemma4Unified);
|
||||
CHECK_EQ(c.n_mels, 640);
|
||||
CHECK_EQ(c.max_samples, (int64_t)480000);
|
||||
CHECK_EQ(c.tok_end, 258883);
|
||||
c.merge = 1;
|
||||
c.max_frames = 750;
|
||||
mm::Processor p;
|
||||
REQUIRE_EQ(p.init_audio(c, &why), RAD_OK);
|
||||
const int n = kGoldGemma4uAudioN;
|
||||
std::vector<float> x((size_t)n);
|
||||
for (int i = 0; i < n; ++i) x[(size_t)i] = (float)((double)((int64_t)i * 7919 % 2001 - 1000) / 1000.0);
|
||||
std::shared_ptr<mm::Item> it;
|
||||
REQUIRE_EQ(p.audio_from(x, &it, &why), RAD_OK);
|
||||
REQUIRE(it != nullptr);
|
||||
CHECK_EQ(it->grid_h, kGoldGemma4uAudioFrames);
|
||||
CHECK_EQ(it->seg_rows, kGoldGemma4uAudioFrames);
|
||||
CHECK_EQ(it->patch_dim, (int64_t)640);
|
||||
CHECK_EQ(fnv(it->pixels), kGoldGemma4uAudioFnv);
|
||||
REQUIRE_EQ(it->expand.size(), (size_t)kGoldGemma4uAudioFrames + 2);
|
||||
CHECK_EQ(it->expand.front(), 256000);
|
||||
CHECK_EQ(it->expand[1], 258881);
|
||||
CHECK_EQ(it->expand.back(), 258883);
|
||||
/* 30 s at most: a longer clip is cut there; a frame more than a pass holds is refused. */
|
||||
std::vector<float> longer(480000 + 6400, 0.25f);
|
||||
REQUIRE_EQ(p.audio_from(longer, &it, &why), RAD_OK);
|
||||
CHECK_EQ(it->grid_h, 750);
|
||||
c.max_frames = 100;
|
||||
mm::Processor q;
|
||||
REQUIRE_EQ(q.init_audio(c, &why), RAD_OK);
|
||||
CHECK_EQ(q.audio_from(longer, &it, &why), RAD_E_INVAL);
|
||||
/* No samples: <boa><eoa> and nothing to encode. */
|
||||
REQUIRE_EQ(p.audio_from({}, &it, &why), RAD_OK);
|
||||
CHECK(it->encoded);
|
||||
CHECK_EQ(it->expand.size(), (size_t)2);
|
||||
}
|
||||
|
||||
/* What a converted 12B container states for its pictures: Gemma 4's family with the window as the
|
||||
* patch and u / 255 values, the budget from processor_config.json. */
|
||||
TEST(gemma4_unified_vision_config_from_the_container) {
|
||||
const char* keys[] = { "vision_config.model_type", "vision_config.patch_size",
|
||||
"vision_config.pooling_kernel_size", "vision_config.model_patch_size",
|
||||
"image_token_id", "video_token_id", "boi_token_id", "eoi_token_id",
|
||||
"processor.image_processor.max_soft_tokens",
|
||||
"processor.video_processor.max_soft_tokens" };
|
||||
const char* vals[] = { "gemma4_unified_vision", "16", "3", "48", "258880", "258884", "255999",
|
||||
"258882", "280", "70" };
|
||||
RadModelMeta m{};
|
||||
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
|
||||
m.kv_key = keys;
|
||||
m.kv_val = vals;
|
||||
VisionConfig c;
|
||||
std::string why;
|
||||
CHECK_OK(c.from_meta(m, &why));
|
||||
CHECK(c.family == Family::Gemma4);
|
||||
CHECK(c.unit_pixels);
|
||||
CHECK_EQ(c.patch, 48);
|
||||
CHECK_EQ(c.merge, 1);
|
||||
CHECK_EQ(c.patch_dim(), (int64_t)6912);
|
||||
CHECK_EQ(c.image_soft_tokens, 280);
|
||||
CHECK_EQ(c.video_soft_tokens, 70);
|
||||
vals[0] = "gemma4_vision";
|
||||
VisionConfig d;
|
||||
CHECK_OK(d.from_meta(m, &why));
|
||||
CHECK(!d.unit_pixels);
|
||||
CHECK_EQ(d.patch, 16);
|
||||
CHECK_EQ(d.merge, 3);
|
||||
}
|
||||
|
||||
/* ================================================================== GLM-5.3's processor
|
||||
*
|
||||
* glm5_golden.h: Glm5NextProcessor as the checkpoint's processor_config.json sets it up
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
/* nemotronh_test.cpp -- Nemotron-3.5-Bolt's plugin (nemotronh) with its LiLiCorr drafter, declared
|
||||
* and stepped against the recording builder of arch_fakes.h.
|
||||
*
|
||||
* The metadata is a nine-block cut of the released config, as rad-info --meta prints a container
|
||||
* converted from it (the vision tower's keys left out): every block kind, one attention block, and
|
||||
* the drafter with 32 query heads over 2 KV heads of 128. */
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
|
||||
#include "arch_fakes.h"
|
||||
|
||||
#include <iterator>
|
||||
|
||||
/* ==================================================================== the plugin under test */
|
||||
#include "../arch/nemotronh/nemotronh.cpp"
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const k_nemo[][2] = {
|
||||
{ "tie_word_embeddings", "0" },
|
||||
{ "attention_bias", "0" },
|
||||
{ "block_configs.1.moe_intermediate_size", "2048" },
|
||||
{ "block_configs.1.n_routed_experts", "240" },
|
||||
{ "block_configs.1.num_experts_per_tok", "9" },
|
||||
{ "block_configs.3.moe_intermediate_size", "1536" },
|
||||
{ "block_configs.3.n_routed_experts", "240" },
|
||||
{ "block_configs.3.num_experts_per_tok", "9" },
|
||||
{ "block_configs.5.moe_intermediate_size", "2048" },
|
||||
{ "block_configs.5.n_routed_experts", "240" },
|
||||
{ "block_configs.5.num_experts_per_tok", "9" },
|
||||
{ "block_configs.8.moe_intermediate_size", "2304" },
|
||||
{ "block_configs.8.n_routed_experts", "304" },
|
||||
{ "block_configs.8.num_experts_per_tok", "9" },
|
||||
{ "conv_kernel", "4" },
|
||||
{ "hidden_act", "relu2" },
|
||||
{ "layers_block_type", "mamba moe mamba moe mamba moe mamba attention moe" },
|
||||
{ "mamba_head_dim", "64" },
|
||||
{ "mamba_hidden_act", "silu" },
|
||||
{ "mamba_num_heads", "128" },
|
||||
{ "mamba_proj_bias", "0" },
|
||||
{ "mlp_bias", "0" },
|
||||
{ "mlp_hidden_act", "relu2" },
|
||||
{ "moe_latent_size", "1024" },
|
||||
{ "moe_shared_expert_intermediate_size", "5376" },
|
||||
{ "n_group", "1" },
|
||||
{ "n_groups", "8" },
|
||||
{ "n_shared_experts", "1" },
|
||||
{ "norm_topk_prob", "1" },
|
||||
{ "num_nextn_predict_layers", "0" },
|
||||
{ "residual_in_fp32", "0" },
|
||||
{ "routed_scaling_factor", "5" },
|
||||
{ "scoring_func", "sigmoid" },
|
||||
{ "ssm_state_size", "128" },
|
||||
{ "topk_group", "1" },
|
||||
{ "use_bias", "0" },
|
||||
{ "use_conv_bias", "1" },
|
||||
{ "draft.architectures", "LiLiCorrDraftModel" },
|
||||
{ "draft.attention_sink_bias", "1" },
|
||||
{ "draft.block_size", "8" },
|
||||
{ "draft.dflash_config.attention_sink_bias", "1" },
|
||||
{ "draft.dflash_config.causal", "0" },
|
||||
{ "draft.dflash_config.conv_group_size", "16" },
|
||||
{ "draft.dflash_config.conv_kernel_size", "2" },
|
||||
{ "draft.dflash_config.lilicorr_candidate_topk", "8" },
|
||||
{ "draft.dflash_config.lilicorr_enabled", "1" },
|
||||
{ "draft.dflash_config.lilicorr_factor_dim", "1024" },
|
||||
{ "draft.dflash_config.lilicorr_hidden_size", "1024" },
|
||||
{ "draft.dflash_config.lilicorr_logit_scale", "8" },
|
||||
{ "draft.dflash_config.lilicorr_mlp_ratio", "2" },
|
||||
{ "draft.dflash_config.lilicorr_num_heads", "8" },
|
||||
{ "draft.dflash_config.lilicorr_num_layers", "2" },
|
||||
{ "draft.dflash_config.lilicorr_vector_eps", "0.0001" },
|
||||
{ "draft.dflash_config.mask_token_id", "990" },
|
||||
{ "draft.dflash_config.projector_type", "lilicorr" },
|
||||
{ "draft.dflash_config.swa_window_size", "1024" },
|
||||
{ "draft.dflash_config.target_layer_ids", "[1,2,3,5,6,8]" },
|
||||
{ "draft.dflash_config.use_swa", "1" },
|
||||
{ "draft.head_dim", "128" },
|
||||
{ "draft.hidden_size", "4096" },
|
||||
{ "draft.intermediate_size", "12288" },
|
||||
{ "draft.layer_types", "sliding_attention sliding_attention sliding_attention "
|
||||
"sliding_attention sliding_attention" },
|
||||
{ "draft.num_attention_heads", "32" },
|
||||
{ "draft.num_hidden_layers", "5" },
|
||||
{ "draft.num_key_value_heads", "2" },
|
||||
{ "draft.rms_norm_eps", "9.9999999999999995e-07" },
|
||||
{ "draft.rope_theta", "10000" },
|
||||
{ "draft.sliding_window", "1024" },
|
||||
{ "draft.use_sliding_window", "1" },
|
||||
{ "draft.vocab_size", "131072" },
|
||||
};
|
||||
|
||||
struct Nemo {
|
||||
std::vector<const char*> keys, vals;
|
||||
Nemo() {
|
||||
for (const auto& kv : k_nemo) {
|
||||
keys.push_back(kv[0]);
|
||||
vals.push_back(kv[1]);
|
||||
}
|
||||
}
|
||||
RadModelMeta meta() const {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "nemotronh";
|
||||
m.name = "test-nemotron-3.5-bolt-c9";
|
||||
m.quant = "";
|
||||
m.n_layers = 9;
|
||||
m.n_embd = 4096;
|
||||
m.n_head = 32;
|
||||
m.n_head_kv = 2;
|
||||
m.head_dim = 128;
|
||||
m.n_ff = 2688;
|
||||
m.n_vocab = 131072;
|
||||
m.n_ctx_train = 262144;
|
||||
m.rms_eps = 1e-5f;
|
||||
m.rope_theta = 10000.0f;
|
||||
m.rope_scale = 1.0f;
|
||||
m.n_kv = (int)keys.size();
|
||||
m.kv_key = keys.data();
|
||||
m.kv_val = vals.data();
|
||||
return m;
|
||||
}
|
||||
};
|
||||
|
||||
/* The weights as the release recipes store them: the drafter's linears and every trunk linear block
|
||||
* fp8, dt's rows of in_proj bf16 (32 a rank at four ranks, no whole scale block). The drafter's
|
||||
* keys come first: the fake answers the first key a name contains. */
|
||||
void nemo_encs(RadBuilder& b) {
|
||||
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
|
||||
b.encs = { { "dflash.fc.", fp8 }, { "dflash.blk.", fp8 }, { "ssm_dt", rad_enc_plain(RAD_BF16) },
|
||||
{ "blk.", fp8 } };
|
||||
}
|
||||
|
||||
int buf_named(const RadBuilder& b, const char* name) {
|
||||
for (size_t i = 0; i < b.bufs.size(); ++i)
|
||||
if (b.bufs[i].name == name) return (int)(i + 1);
|
||||
return 0;
|
||||
}
|
||||
bool noted(const RadBuilder& b, const char* text) {
|
||||
for (const auto& n : b.notes)
|
||||
if (n.find(text) != std::string::npos) return true;
|
||||
return false;
|
||||
}
|
||||
rad_kvgroup kv_named(const RadBuilder& b, const char* name) {
|
||||
for (size_t i = 0; i < b.kv_groups.size(); ++i)
|
||||
if (b.kv_groups[i].name == name) return (rad_kvgroup)(i + 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
RadBuildCtx nemo_ctx(int rank, int world) {
|
||||
RadBuildCtx c = build_ctx(rank, world);
|
||||
c.max_spec = 7; /* LiLiCorr's trained block of 8 */
|
||||
return c;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* drafter_geom keeps refusing fewer KV heads than ranks unless the drafter block reads k and v at
|
||||
* kv_off; with `kv_repl_ok` it replicates them as geom_from does the target's: one head a rank,
|
||||
* ranks {0, 1} on head 0 and {2, 3} on head 1. The target's own kv_off is not inherited. */
|
||||
TEST(drafter_geom_replicates_kv_heads_only_when_the_block_asks) {
|
||||
using namespace rad::arch;
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int world : { 2, 4 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
const RadBuildCtx ctx = nemo_ctx(rank, world);
|
||||
Geom t{};
|
||||
REQUIRE_EQ(geom_from(t, &meta, &ctx, "bf16", RAD_BF16), RAD_OK);
|
||||
Geom dg{};
|
||||
if (world == 4) {
|
||||
CHECK_EQ(t.kv_off, (int64_t)(rank / 2) * 128); /* the target replicates too */
|
||||
CHECK_EQ(drafter_geom(dg, t, &meta, "LiLiCorr"), (int)RAD_E_INVAL);
|
||||
}
|
||||
REQUIRE_EQ(drafter_geom(dg, t, &meta, "LiLiCorr", true), RAD_OK);
|
||||
CHECK_EQ(dg.n_head, 32 / world);
|
||||
CHECK_EQ(dg.n_head_kv, 1);
|
||||
CHECK_EQ(dg.n_head_kv_all, 2);
|
||||
CHECK_EQ(dg.gqa(), 32 / world);
|
||||
CHECK_EQ(dg.kv_off, world == 4 ? (int64_t)(rank / 2) * 128 : (int64_t)0);
|
||||
}
|
||||
}
|
||||
|
||||
/* The drafter at two and four ranks. Each rank keeps one KV head in `kv_draft`; at four its k and v
|
||||
* are the rows of its replicated head, [kv_off, kv_off + 128) of the 256-row projection (codes, and
|
||||
* the scale plane in 128-row blocks), and q stays an even share. The sinked attention then runs 8
|
||||
* 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) {
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int world : { 2, 4 })
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
RadBuilder b;
|
||||
nemo_encs(b);
|
||||
const RadBuildCtx ctx = nemo_ctx(rank, world);
|
||||
REQUIRE_EQ(nemotronh::declare(&b, &meta, &ctx), RAD_OK);
|
||||
CHECK(nemotronh::models[rank]->have_df);
|
||||
const rad_kvgroup kvd = kv_named(b, "kv_draft");
|
||||
REQUIRE(kvd != 0);
|
||||
CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 1);
|
||||
CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 128);
|
||||
CHECK_EQ(b.bufs[buf_named(b, "df_q") - 1].d.shape[1], (int64_t)(32 / world) * 128);
|
||||
CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], (int64_t)128);
|
||||
CHECK_EQ(b.bufs[buf_named(b, "df_cv") - 1].d.shape[1], (int64_t)128);
|
||||
int sinks = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "attn_paged_sink") {
|
||||
CHECK_EQ(pint(&o, "gqa"), 32 / world);
|
||||
CHECK_EQ(pint(&o, "n_head"), 32 / world);
|
||||
CHECK_EQ(pint(&o, "head_dim"), 128);
|
||||
++sinks;
|
||||
}
|
||||
CHECK_EQ(sinks, 5);
|
||||
const int64_t kv0 = (rank / 2) * 128;
|
||||
for (int l = 0; l < 5; ++l) {
|
||||
for (const char* kv : { "attn_k", "attn_v" }) {
|
||||
const std::string base = "dflash.blk." + std::to_string(l) + "." + kv;
|
||||
const RecWeight* w = find_w(b, base + ".weight");
|
||||
const RecWeight* s = find_w(b, base + ".scale");
|
||||
REQUIRE(w != nullptr && s != nullptr);
|
||||
CHECK_EQ(w->d.shape[0], 128);
|
||||
CHECK_EQ(w->span_set, world == 4);
|
||||
CHECK_EQ(s->span_set, world == 4);
|
||||
if (world == 4) {
|
||||
CHECK_EQ(w->span_lo, kv0);
|
||||
CHECK_EQ(w->span_hi, kv0 + 128);
|
||||
CHECK_EQ(s->span_lo, kv0 / 128);
|
||||
CHECK_EQ(s->span_hi, kv0 / 128 + 1);
|
||||
}
|
||||
}
|
||||
const RecWeight* q =
|
||||
find_w(b, "dflash.blk." + std::to_string(l) + ".attn_q.weight");
|
||||
REQUIRE(q != nullptr);
|
||||
CHECK(!q->span_set);
|
||||
CHECK_EQ(q->d.shape[0], (int64_t)(32 / world) * 128);
|
||||
}
|
||||
/* the target's attention replicates its two heads the same way */
|
||||
const rad_kvgroup kva = kv_named(b, "kv_attn");
|
||||
REQUIRE(kva != 0);
|
||||
CHECK_EQ(b.kv_groups[kva - 1].d.n_head_kv, 1);
|
||||
CHECK(noted(b, world == 4 ? "kv (replicated) x 128" : "/ 1 kv x 128"));
|
||||
}
|
||||
}
|
||||
|
||||
/* 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) {
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int rank : { 0, 3 }) {
|
||||
RadBuilder b;
|
||||
nemo_encs(b);
|
||||
const RadBuildCtx ctx = nemo_ctx(rank, 4);
|
||||
REQUIRE_EQ(nemotronh::declare(&b, &meta, &ctx), RAD_OK);
|
||||
auto trunk = kit(b, { 8, 8 }, {});
|
||||
auto cpass = context_pass(b, *trunk);
|
||||
auto qpass = query_pass(b, 2, 8, 7);
|
||||
std::vector<int32_t> anchors = { 7, 15 }; /* each sequence's last committed row */
|
||||
qpass->b.anchor_rows = anchors.data();
|
||||
auto v = run_passes(b, nemotronh::step, { trunk.get(), cpass.get(), qpass.get() }, rank, 4);
|
||||
CHECK_PASSES(b, v);
|
||||
/* the drafter ran: its five layers' sinked attention and its keys into the cache */
|
||||
const std::vector<std::string> q = issued_ops(b, *v[2]);
|
||||
CHECK_EQ(count_issued(q, "attn_paged_sink"), 5);
|
||||
CHECK_EQ(count_issued(q, "kv_store"), 5);
|
||||
CHECK_EQ(count_issued(issued_ops(b, *v[1]), "kv_store"), 5);
|
||||
}
|
||||
}
|
||||
|
||||
/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and
|
||||
* must get the real declare's graph: the same ops with the same fixed parameters, only ranged row
|
||||
* 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) {
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
for (int world : { 2, 4 })
|
||||
for (int64_t R : { 256, 1024 }) {
|
||||
RadBuildCtx c = nemo_ctx(1, world);
|
||||
c.max_tok = 4096;
|
||||
c.max_seqs = 16;
|
||||
RadBuilder full;
|
||||
nemo_encs(full);
|
||||
REQUIRE_EQ(nemotronh::declare(&full, &meta, &c), RAD_OK);
|
||||
RadBuildCtx p = c;
|
||||
p.max_tok = R;
|
||||
p.shape_probe = 1;
|
||||
RadBuilder small;
|
||||
nemo_encs(small);
|
||||
REQUIRE_EQ(nemotronh::declare(&small, &meta, &p), RAD_OK);
|
||||
REQUIRE_EQ(small.ops.size(), full.ops.size());
|
||||
int differ = 0;
|
||||
for (size_t i = 0; i < full.ops.size(); ++i) {
|
||||
if (small.ops[i].op != full.ops[i].op) {
|
||||
++differ;
|
||||
continue;
|
||||
}
|
||||
REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size());
|
||||
for (size_t k = 0; k < full.ops[i].p.size(); ++k) {
|
||||
const RecParam& a = full.ops[i].p[k];
|
||||
const RecParam& q = small.ops[i].p[k];
|
||||
if (a.kind == RAD_P_RANGE) continue;
|
||||
if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) {
|
||||
fprintf(stderr, " world %d R %lld: op %zu '%s' param '%s': %lld real, "
|
||||
"%lld small\n", world, (long long)R, i,
|
||||
full.ops[i].op.c_str(), a.key.c_str(), a.ival, q.ival);
|
||||
++differ;
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_EQ(differ, 0);
|
||||
REQUIRE_EQ(small.bufs.size(), full.bufs.size());
|
||||
for (size_t i = 0; i < full.bufs.size(); ++i)
|
||||
for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d)
|
||||
CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]);
|
||||
}
|
||||
}
|
||||
|
||||
/* The probe states LiLiCorr's fixed depth, the trained block less its anchor: what --tp 4 serves
|
||||
* with `--num-speculative-tokens 7`. */
|
||||
TEST(nemotronh_probe_names_lilicorrs_depth) {
|
||||
Nemo f;
|
||||
const RadModelMeta meta = f.meta();
|
||||
RadArchProbe pr{};
|
||||
REQUIRE_EQ(nemotronh::probe(&meta, &pr), RAD_OK);
|
||||
CHECK_EQ(pr.draft_depth, 7);
|
||||
CHECK_EQ(pr.draft_depth_fixed, 1);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -171,6 +171,13 @@ run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 ONEAPI_DEVICE_SELECTOR="!lev
|
||||
"$P/bin/rad-kbench" --fixture "$P/share/radiance/kernels.rkb" --max-cases 1 \
|
||||
--max-bytes 2048 --op rmsnorm --op quant_act_fp8 --op silu_mul
|
||||
grep -E "passed|failed" "$W/logs/kbench.log" | tail -3
|
||||
# rad-kbench fails only on a case that ran and failed, so a replay that skipped every case would
|
||||
# pass unseen: its summary must name at least one passed case and no failed one.
|
||||
sum=$(grep -E '^[0-9]+ checked, [0-9]+ passed, [0-9]+ failed' "$W/logs/kbench.log" | tail -1)
|
||||
n_pass=$(printf '%s\n' "$sum" | sed -nE 's/^[0-9]+ checked, ([0-9]+) passed, ([0-9]+) failed.*/\1/p')
|
||||
n_fail=$(printf '%s\n' "$sum" | sed -nE 's/^[0-9]+ checked, ([0-9]+) passed, ([0-9]+) failed.*/\2/p')
|
||||
[ -n "$n_pass" ] && [ "$n_pass" -gt 0 ] && [ "$n_fail" -eq 0 ] ||
|
||||
fail "the installed rad-kbench replay checked nothing or failed: '$sum' (log: $W/logs/kbench.log)"
|
||||
say "4. the installed rad-kbench replays fixture ops from the out-of-tree home: $(ls "$HH/kernels" | tr '\n' ' ')"
|
||||
|
||||
# 5. The device library's machine code, against the tree's, object by object. A code object also
|
||||
|
||||
@@ -1460,6 +1460,535 @@ TEST(the_file_stager_reads_each_routed_layer_from_the_container) {
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* Every weight of `f` in a container image, each on RAD_ALIGN_UNIT in declared order with a 2 MiB
|
||||
* hole between layers, written to `path` with each byte container_byte(offset). Empty when the
|
||||
* working directory has no O_DIRECT (the caller skips). */
|
||||
std::vector<uint8_t> write_container(Fixture& f, const std::string& path) {
|
||||
int64_t off = 4 * (int64_t)RAD_ALIGN_UNIT;
|
||||
int32_t prev = -1;
|
||||
for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w) {
|
||||
WeightInfo& wi = f.prog.weights[w];
|
||||
if (prev >= 0 && wi.decl.group.layer != prev) off += 2 * MiB;
|
||||
prev = wi.decl.group.layer;
|
||||
wi.stored_bytes = wi.logical_bytes;
|
||||
wi.file_offset = (uint64_t)off;
|
||||
off = align_up(off + wi.stored_bytes, RAD_ALIGN_UNIT);
|
||||
}
|
||||
std::vector<uint8_t> img((size_t)off);
|
||||
for (int64_t i = 0; i < off; ++i) img[(size_t)i] = container_byte(i);
|
||||
FILE* fp = std::fopen(path.c_str(), "wb");
|
||||
if (!fp) return {};
|
||||
const bool wrote = std::fwrite(img.data(), 1, img.size(), fp) == img.size();
|
||||
std::fclose(fp);
|
||||
DirectFile probe;
|
||||
if (!wrote || probe.open(path.c_str(), RAD_DIO_READ) < 0) {
|
||||
std::remove(path.c_str());
|
||||
return {};
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
/* A routing-count source like Ctx::route_counts_device over a MoE block declared once: one counts
|
||||
* buffer that every routed layer's router rewrites (glm5next shares its counts this way), so a
|
||||
* read that took the counts before its own layer's router ran would see another layer's. A layer
|
||||
* in `missing` has not reported yet. `asked` counts the stager's questions. */
|
||||
struct SharedCounts {
|
||||
int32_t* dev = nullptr;
|
||||
int64_t n = 0;
|
||||
std::vector<int32_t> missing;
|
||||
int asked = 0;
|
||||
explicit SharedCounts(int64_t n_expert) : n(n_expert) {
|
||||
dev = (int32_t*)rad_dev_alloc(n_expert * (int64_t)sizeof(int32_t), RAD_MEM_DEVICE);
|
||||
}
|
||||
~SharedCounts() { if (dev) rad_dev_free(dev, RAD_MEM_DEVICE); }
|
||||
/* The router of the rows about to run, on the host backend's shared memory. */
|
||||
void route(std::initializer_list<int32_t> c) {
|
||||
int64_t i = 0;
|
||||
for (int32_t v : c) dev[i++] = v;
|
||||
}
|
||||
static const int32_t* get(void* ud, int32_t layer, int64_t* n_expert) {
|
||||
SharedCounts& s = *(SharedCounts*)ud;
|
||||
++s.asked;
|
||||
*n_expert = 0;
|
||||
if (std::find(s.missing.begin(), s.missing.end(), layer) != s.missing.end()) return nullptr;
|
||||
*n_expert = s.n;
|
||||
return s.dev;
|
||||
}
|
||||
};
|
||||
|
||||
/* What one routed unit's weights are published as right now: the container's bytes, the zero
|
||||
* region (a skipped expert), or nothing. */
|
||||
enum class Pub { Bytes, Zeros, Null, Other };
|
||||
Pub published(Mover& m, const Plan& p, const Program& prog, int32_t unit,
|
||||
const std::vector<uint8_t>& img, RadStream s) {
|
||||
Pub got = Pub::Bytes;
|
||||
for (rad_weight w : p.units[(size_t)unit].weights) {
|
||||
const WeightSlot* slot = m.residency()->lookup(w);
|
||||
if (!slot || !slot->ptr) return Pub::Null;
|
||||
if (published_matches(m, prog, w, img, s)) continue;
|
||||
std::vector<uint8_t> head(256);
|
||||
rad_stream_sync(m.transfer_stream());
|
||||
if (rad_memcpy_async(head.data(), slot->ptr, (int64_t)head.size(), s) < 0) return Pub::Other;
|
||||
rad_stream_sync(s);
|
||||
bool zero = true;
|
||||
for (uint8_t v : head) zero = zero && v == 0;
|
||||
got = zero ? Pub::Zeros : Pub::Other;
|
||||
}
|
||||
return got;
|
||||
}
|
||||
|
||||
int32_t unit_at(const Plan& p, int32_t layer, int32_t expert) {
|
||||
for (int32_t i = 0; i < (int32_t)p.units.size(); ++i)
|
||||
if (p.units[(size_t)i].layer == layer && p.units[(size_t)i].expert == expert) return i;
|
||||
return -1;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* A layer is read with the counts its own router wrote, at its own trigger. Three routed layers
|
||||
* of four 3 MiB experts, 1 and 3 on the file tier, every router writing one shared counts buffer.
|
||||
* A read taken before a layer's router ran -- at the pass's first op, or ahead at the previous
|
||||
* layer's trigger -- would filter the layer by another layer's counts and leave a routed expert
|
||||
* to be computed from the zero region. A second slice of a layer's rows routes again, and what it
|
||||
* routes that the first did not is read then. */
|
||||
TEST(the_file_stager_reads_a_layer_with_the_counts_its_own_router_wrote) {
|
||||
Fixture f;
|
||||
const int L = 3;
|
||||
build_moe_layers(f, L, 4, 2 * MiB + 1000, MiB + 24);
|
||||
f.prog.meta.n_expert = 4;
|
||||
const std::string path = "place_test_counts.rad";
|
||||
const std::vector<uint8_t> img = write_container(f, path);
|
||||
if (img.empty()) {
|
||||
std::printf(" SKIP the working directory has no O_DIRECT\n");
|
||||
return;
|
||||
}
|
||||
std::vector<RadFileProfile> prof;
|
||||
for (int l = 0; l < L; ++l)
|
||||
for (int e = 0; e < 4; ++e)
|
||||
prof.push_back(RadFileProfile{l, e, e == 0 ? 0.5f : e == 2 ? 0.4f : 0.01f, 0.0f});
|
||||
/* Six residents, the two file buffers and the embedding fill the card; the host pool is the
|
||||
* file tier's staging and nothing more. */
|
||||
const int64_t stride = align_up(align_up(2 * MiB + 1000, RAD_ALIGN_UNIT) + MiB + 24,
|
||||
RAD_ALIGN_UNIT);
|
||||
Config c = base_config();
|
||||
c.placement = "expert_tiered";
|
||||
c.deterministic = true;
|
||||
c.vram_weights_mib = 32;
|
||||
c.host_pool_mib = (RAD_PLACE_FILE_STAGE_SLOTS * stride +
|
||||
RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES) / MiB + 1;
|
||||
c.weights_disk_tier = true;
|
||||
PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()};
|
||||
Plan p;
|
||||
CHECK_OK(Planner(in).plan(&p));
|
||||
for (const MoveUnit& mu : p.units)
|
||||
if (mu.expert >= 0) CHECK(mu.tier == ((mu.expert & 1) ? Tier::SSD : Tier::VRAM));
|
||||
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
mc.container_path = path;
|
||||
CHECK_OK(m.init(f.prog, p, mc));
|
||||
RadStream s = nullptr;
|
||||
CHECK_OK(rad_stream_create(&s, 0));
|
||||
CHECK_OK(m.bind_compute_stream(s));
|
||||
SharedCounts counts(4);
|
||||
/* What the last pass's last router left: both file-tier experts of every layer routed. */
|
||||
counts.route({0, 1, 0, 1});
|
||||
FileStager fs;
|
||||
CHECK_OK(fs.init(f.prog, p, &m, &SharedCounts::get, &counts));
|
||||
REQUIRE_EQ(fs.n_layers(), (size_t)L);
|
||||
auto pub = [&](int l, int e) { return published(m, p, f.prog, unit_at(p, l, e), img, s); };
|
||||
auto none = [&](int l) { return pub(l, 1) == Pub::Null && pub(l, 3) == Pub::Null; };
|
||||
|
||||
/* Op 0 is the embedding; layer l's expert ops are 2l+1 and 2l+2. */
|
||||
RadBatch b{};
|
||||
CHECK(fs.begin_pass(&b));
|
||||
bool resync = false;
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
/* Nothing yet: no counts for layer 0 exist before its router has run. */
|
||||
CHECK(!resync);
|
||||
for (int l = 0; l < L; ++l) CHECK(none(l));
|
||||
|
||||
counts.route({0, 2, 0, 0}); /* layer 0's router: expert 1 only */
|
||||
CHECK_OK(fs.before_op(1, s, &resync));
|
||||
CHECK(resync);
|
||||
CHECK(pub(0, 1) == Pub::Bytes);
|
||||
CHECK(pub(0, 3) == Pub::Zeros); /* not routed: the zero region, not read */
|
||||
CHECK(none(1)); /* layer 1's router has not run */
|
||||
CHECK(none(2));
|
||||
CHECK_OK(fs.after_op(1, s));
|
||||
/* A second slice of layer 0's rows that routes nothing new reads and publishes nothing. */
|
||||
const int64_t waits0 = fs.waits();
|
||||
counts.route({0, 5, 0, 0});
|
||||
CHECK_OK(fs.before_op(1, s, &resync));
|
||||
CHECK(!resync);
|
||||
CHECK_EQ(fs.waits(), waits0);
|
||||
CHECK(pub(0, 1) == Pub::Bytes && pub(0, 3) == Pub::Zeros);
|
||||
CHECK_OK(fs.after_op(1, s));
|
||||
CHECK_OK(fs.before_op(2, s, &resync));
|
||||
|
||||
counts.route({0, 0, 0, 5}); /* layer 1's router: expert 3 only */
|
||||
CHECK_OK(fs.before_op(3, s, &resync));
|
||||
CHECK(none(0)); /* released */
|
||||
CHECK(pub(1, 3) == Pub::Bytes);
|
||||
CHECK(pub(1, 1) == Pub::Zeros);
|
||||
CHECK(none(2));
|
||||
/* A second slice of layer 1's rows routes expert 1 as well: read now, and waited on. */
|
||||
const int64_t waits = fs.waits();
|
||||
counts.route({0, 7, 0, 0});
|
||||
CHECK_OK(fs.before_op(3, s, &resync));
|
||||
CHECK(resync);
|
||||
CHECK_EQ(fs.waits(), waits + 1);
|
||||
CHECK(pub(1, 1) == Pub::Bytes);
|
||||
CHECK(pub(1, 3) == Pub::Bytes);
|
||||
/* A third routes nothing new: no read, no wait. */
|
||||
counts.route({0, 0, 0, 1});
|
||||
CHECK_OK(fs.before_op(3, s, &resync));
|
||||
CHECK(!resync);
|
||||
CHECK_EQ(fs.waits(), waits + 1);
|
||||
CHECK_OK(fs.before_op(4, s, &resync));
|
||||
|
||||
counts.route({0, 1, 0, 1});
|
||||
CHECK_OK(fs.before_op(5, s, &resync));
|
||||
CHECK(none(0) && none(1));
|
||||
CHECK(pub(2, 1) == Pub::Bytes && pub(2, 3) == Pub::Bytes);
|
||||
CHECK_OK(fs.before_op(6, s, &resync));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
for (int l = 0; l < L; ++l) CHECK(none(l));
|
||||
/* Two experts skipped at a trigger (layer 0's 3, layer 1's 1), one of them read by the
|
||||
* second slice; five units read, each once. */
|
||||
CHECK_EQ(m.stats().ssd_skipped_units, (uint64_t)2);
|
||||
CHECK_EQ(m.stats().ssd_units, (uint64_t)5);
|
||||
|
||||
/* A layer the source has no counts for (it has not reported) is read whole, so it can be read
|
||||
* ahead as before: layer 1 at layer 0's trigger. A counted one is not. */
|
||||
counts.missing = {1};
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
counts.route({0, 0, 0, 3});
|
||||
CHECK_OK(fs.before_op(1, s, &resync));
|
||||
CHECK(pub(0, 3) == Pub::Bytes && pub(0, 1) == Pub::Zeros);
|
||||
CHECK(pub(1, 1) == Pub::Bytes && pub(1, 3) == Pub::Bytes);
|
||||
CHECK(none(2));
|
||||
CHECK_OK(fs.before_op(2, s, &resync));
|
||||
CHECK_OK(fs.before_op(3, s, &resync));
|
||||
CHECK(pub(1, 1) == Pub::Bytes && pub(1, 3) == Pub::Bytes);
|
||||
CHECK(none(2));
|
||||
CHECK_OK(fs.before_op(4, s, &resync));
|
||||
counts.route({0, 4, 0, 0});
|
||||
CHECK_OK(fs.before_op(5, s, &resync));
|
||||
CHECK(pub(2, 1) == Pub::Bytes && pub(2, 3) == Pub::Zeros);
|
||||
CHECK_OK(fs.before_op(6, s, &resync));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
for (int l = 0; l < L; ++l) CHECK(none(l));
|
||||
|
||||
/* With no layer counted, the first one is read at the pass's first op, as before. */
|
||||
counts.missing = {0, 1, 2};
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
CHECK(resync);
|
||||
CHECK(pub(0, 1) == Pub::Bytes && pub(0, 3) == Pub::Bytes);
|
||||
CHECK(none(1));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
for (int l = 0; l < L; ++l) CHECK(none(l));
|
||||
|
||||
/* A pass whose rows route nearly every expert -- 64 rows an expert on average, here four
|
||||
* experts at top-1, so 256 rows -- is read whole and ahead like a layer without counts: the
|
||||
* counts are never asked for, so no trigger drains the stream, though they are there. One
|
||||
* row fewer is read exactly. */
|
||||
f.prog.meta.n_expert_used = 1;
|
||||
counts.missing.clear();
|
||||
FileStager wf;
|
||||
CHECK_OK(wf.init(f.prog, p, &m, &SharedCounts::get, &counts));
|
||||
CHECK_EQ(wf.whole_rows(), (int64_t)256);
|
||||
CHECK_EQ(fs.whole_rows(), (int64_t)0); /* top-k unknown: always exact */
|
||||
counts.route({0, 0, 0, 0}); /* routes nothing, were it asked */
|
||||
const int asked = counts.asked;
|
||||
RadBatch big{};
|
||||
big.n_tok = 256;
|
||||
CHECK(wf.begin_pass(&big));
|
||||
CHECK_OK(wf.before_op(0, s, &resync));
|
||||
CHECK(resync);
|
||||
CHECK(pub(0, 1) == Pub::Bytes && pub(0, 3) == Pub::Bytes);
|
||||
CHECK(none(1));
|
||||
CHECK_OK(wf.before_op(1, s, &resync));
|
||||
CHECK(pub(0, 1) == Pub::Bytes && pub(0, 3) == Pub::Bytes);
|
||||
CHECK(pub(1, 1) == Pub::Bytes && pub(1, 3) == Pub::Bytes); /* ahead, at layer 0's trigger */
|
||||
CHECK_OK(wf.before_op(1, s, &resync)); /* another slice: nothing left to read */
|
||||
CHECK(!resync);
|
||||
CHECK_OK(wf.before_op(2, s, &resync));
|
||||
CHECK_OK(wf.before_op(3, s, &resync));
|
||||
CHECK(none(0));
|
||||
CHECK(pub(2, 1) == Pub::Bytes && pub(2, 3) == Pub::Bytes);
|
||||
for (rad_op op = 4; op <= 6; ++op) CHECK_OK(wf.before_op(op, s, &resync));
|
||||
CHECK_OK(wf.end_pass(s));
|
||||
CHECK_EQ(counts.asked, asked);
|
||||
for (int l = 0; l < L; ++l) CHECK(none(l));
|
||||
|
||||
big.n_tok = 255;
|
||||
CHECK(wf.begin_pass(&big));
|
||||
CHECK_OK(wf.before_op(0, s, &resync));
|
||||
CHECK(none(0));
|
||||
counts.route({0, 2, 0, 0});
|
||||
CHECK_OK(wf.before_op(1, s, &resync));
|
||||
CHECK(pub(0, 1) == Pub::Bytes && pub(0, 3) == Pub::Zeros);
|
||||
CHECK(none(1));
|
||||
CHECK(counts.asked > asked);
|
||||
CHECK_OK(wf.end_pass(s));
|
||||
|
||||
rad_stream_sync(m.transfer_stream());
|
||||
rad_stream_destroy(s);
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
/* The pool is a cache of the file tier under a dynamic plan. A read that finds it full gives its
|
||||
* coldest pooled unit back to the file tier when that unit is colder than the one read, never one
|
||||
* of the layer being read or of one whose ops are about to run; the unit given back -- here one
|
||||
* the plan put in the pool, in a layer with nothing on the file tier -- is read back by its own
|
||||
* layer's trigger; and a read whose only copy is a deposit is waited on before the layer's ops. */
|
||||
TEST(a_full_pool_gives_back_its_coldest_unit_and_the_stager_reads_it_again) {
|
||||
Fixture f;
|
||||
const int L = 3;
|
||||
build_moe_layers(f, L, 4, MiB + 1000, MiB / 2 + 24);
|
||||
f.prog.meta.n_expert = 4;
|
||||
const std::string path = "place_test_cache.rad";
|
||||
const std::vector<uint8_t> img = write_container(f, path);
|
||||
if (img.empty()) {
|
||||
std::printf(" SKIP the working directory has no O_DIRECT\n");
|
||||
return;
|
||||
}
|
||||
/* Rank order: layer 0's experts, then layer 1's, then layer 2's. Layer 0's four fill the
|
||||
* pool and the rest go to the file tier, so layer 0 has nothing there. The card holds the
|
||||
* embedding and the two file buffers; a resident would also need a hot-cache shadow slot,
|
||||
* and the plan has no room for the pair. */
|
||||
std::vector<RadFileProfile> prof;
|
||||
for (int l = 0; l < L; ++l)
|
||||
for (int e = 0; e < 4; ++e)
|
||||
prof.push_back(RadFileProfile{l, e, 0.9f - 0.3f * (float)l - 0.05f * (float)e, 0.0f});
|
||||
const int64_t stride = align_up(align_up(MiB + 1000, RAD_ALIGN_UNIT) + MiB / 2 + 24,
|
||||
RAD_ALIGN_UNIT);
|
||||
Config c = base_config();
|
||||
c.placement = "expert_tiered";
|
||||
c.vram_weights_mib = 15;
|
||||
const int64_t reserve = RAD_PLACE_FILE_STAGE_SLOTS * stride +
|
||||
RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES;
|
||||
c.host_pool_mib = (reserve + 4 * stride) / MiB + 1;
|
||||
c.weights_disk_tier = true;
|
||||
PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()};
|
||||
Plan p;
|
||||
CHECK_OK(Planner(in).plan(&p));
|
||||
REQUIRE(p.dynamic);
|
||||
auto tier_of = [&](int l, int e) { return p.units[(size_t)unit_at(p, l, e)].tier; };
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
REQUIRE(tier_of(0, e) == Tier::HostPinned);
|
||||
REQUIRE(tier_of(1, e) == Tier::SSD);
|
||||
REQUIRE(tier_of(2, e) == Tier::SSD);
|
||||
}
|
||||
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
mc.container_path = path;
|
||||
CHECK_OK(m.init(f.prog, p, mc));
|
||||
RadStream s = nullptr;
|
||||
CHECK_OK(rad_stream_create(&s, 0));
|
||||
CHECK_OK(m.bind_compute_stream(s));
|
||||
HeatEngine h;
|
||||
CHECK_OK(h.init(p, HeatParams{}));
|
||||
REQUIRE(h.enabled());
|
||||
SharedCounts counts(4);
|
||||
FileStager fs;
|
||||
CHECK_OK(fs.init(f.prog, p, &m, &SharedCounts::get, &counts));
|
||||
/* Layer 0 is covered though the plan put none of it on the file tier: a deposit may give its
|
||||
* pooled units back to the file tier. */
|
||||
REQUIRE_EQ(fs.n_layers(), (size_t)L);
|
||||
auto pub = [&](int l, int e) { return published(m, p, f.prog, unit_at(p, l, e), img, s); };
|
||||
|
||||
/* Where the pooled units are published: their pool slots, which this test never fills (the
|
||||
* load phase does), so they are compared by address. */
|
||||
auto addr = [&](int l, int e) {
|
||||
return m.residency()->lookup(p.units[(size_t)unit_at(p, l, e)].weights.front())->ptr;
|
||||
};
|
||||
void* const pooled[3] = { addr(0, 1), addr(0, 2), addr(0, 3) };
|
||||
for (void* q : pooled) CHECK(q != nullptr);
|
||||
|
||||
/* Layer 2's expert 0 has routed before; nothing else has. */
|
||||
const int32_t hist[4] = {3, 0, 0, 0};
|
||||
h.observe(2, hist, 4);
|
||||
CHECK_OK(m.begin_dispatch(1, &h));
|
||||
|
||||
RadBatch b{};
|
||||
bool resync = false;
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
counts.route({1, 0, 0, 0});
|
||||
CHECK_OK(fs.before_op(1, s, &resync)); /* layer 0: nothing on the file tier */
|
||||
CHECK(!resync);
|
||||
CHECK_OK(fs.before_op(2, s, &resync));
|
||||
/* Layer 1's expert 2 is as cold as every pooled unit: not worth a slot, read into the
|
||||
* buffer. */
|
||||
counts.route({0, 0, 2, 0});
|
||||
CHECK_OK(fs.before_op(3, s, &resync));
|
||||
CHECK(pub(1, 2) == Pub::Bytes);
|
||||
CHECK_EQ(m.stats().pool_evictions, (uint64_t)0);
|
||||
CHECK_OK(fs.before_op(4, s, &resync));
|
||||
/* Layer 2's expert 0 is warmer: the coldest pooled unit outside layer 2 goes back to the file
|
||||
* tier, the lowest of the equally cold ones -- layer 0's expert 0 -- and its weights point at
|
||||
* the zero region until its own layer reads it. */
|
||||
counts.route({3, 0, 0, 0});
|
||||
CHECK_OK(fs.before_op(5, s, &resync));
|
||||
CHECK(pub(2, 0) == Pub::Bytes);
|
||||
CHECK_EQ(m.stats().pool_evictions, (uint64_t)1);
|
||||
CHECK(pub(0, 0) == Pub::Zeros);
|
||||
CHECK(m.on_file_tier({unit_at(p, 0, 0)}));
|
||||
CHECK(addr(0, 1) == pooled[0] && addr(0, 2) == pooled[1] && addr(0, 3) == pooled[2]);
|
||||
CHECK_OK(fs.before_op(6, s, &resync));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
|
||||
/* The pool slot it gave up comes back after its quarantine. */
|
||||
for (int d = 2; d < 5; ++d) {
|
||||
CHECK_OK(rad_stream_sync(s));
|
||||
CHECK_OK(m.begin_dispatch(d, &h));
|
||||
}
|
||||
|
||||
/* Layer 0's trigger routes the unit back: it is read into the free pool slot -- a read
|
||||
* whose only copy is that deposit, which the stream waits on all the same. */
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
counts.route({1, 0, 0, 0});
|
||||
const int64_t waits = fs.waits();
|
||||
CHECK_OK(fs.before_op(1, s, &resync));
|
||||
CHECK(resync);
|
||||
CHECK_EQ(m.stats().ssd_deposits, (uint64_t)1);
|
||||
CHECK_EQ(fs.waits(), waits + 1);
|
||||
CHECK(pub(0, 0) == Pub::Bytes);
|
||||
CHECK(!m.on_file_tier({unit_at(p, 0, 0)}));
|
||||
counts.route({0, 0, 0, 0});
|
||||
for (rad_op op = 2; op <= 6; ++op) CHECK_OK(fs.before_op(op, s, &resync));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
/* A deposit outlives the pass: the unit stays in its pool slot. */
|
||||
CHECK(pub(0, 0) == Pub::Bytes);
|
||||
|
||||
rad_stream_sync(m.transfer_stream());
|
||||
rad_stream_sync(s);
|
||||
rad_stream_destroy(s);
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
/* A layer with nothing on the file tier is held by neither buffer, yet its ops are about to be
|
||||
* issued: a read-ahead of the next layer that finds the pool full must not give one of its pooled
|
||||
* units back (the weights would point at the zero region for an op still to come), while the same
|
||||
* pass's read-ahead from the next layer on is free to take it. */
|
||||
TEST(a_read_ahead_never_takes_a_pooled_unit_of_the_layer_about_to_run) {
|
||||
Fixture f;
|
||||
const int L = 3;
|
||||
build_moe_layers(f, L, 4, MiB + 1000, MiB / 2 + 24);
|
||||
f.prog.meta.n_expert = 4;
|
||||
const std::string path = "place_test_cache2.rad";
|
||||
const std::vector<uint8_t> img = write_container(f, path);
|
||||
if (img.empty()) {
|
||||
SKIP("the working directory has no O_DIRECT");
|
||||
}
|
||||
/* Rank order: layer 0's experts, then layer 1's, then layer 2's. Layer 0's four fill the
|
||||
* pool and the rest go to the file tier, so layer 0 has nothing there. The card holds the
|
||||
* embedding and the two file buffers; a resident would also need a hot-cache shadow slot,
|
||||
* and the plan has no room for the pair. */
|
||||
std::vector<RadFileProfile> prof;
|
||||
for (int l = 0; l < L; ++l)
|
||||
for (int e = 0; e < 4; ++e)
|
||||
prof.push_back(RadFileProfile{l, e, 0.9f - 0.3f * (float)l - 0.05f * (float)e, 0.0f});
|
||||
const int64_t stride = align_up(align_up(MiB + 1000, RAD_ALIGN_UNIT) + MiB / 2 + 24,
|
||||
RAD_ALIGN_UNIT);
|
||||
Config c = base_config();
|
||||
c.placement = "expert_tiered";
|
||||
c.vram_weights_mib = 15;
|
||||
const int64_t reserve = RAD_PLACE_FILE_STAGE_SLOTS * stride +
|
||||
RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES;
|
||||
c.host_pool_mib = (reserve + 4 * stride) / MiB + 1;
|
||||
c.weights_disk_tier = true;
|
||||
PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()};
|
||||
Plan p;
|
||||
CHECK_OK(Planner(in).plan(&p));
|
||||
REQUIRE(p.dynamic);
|
||||
auto tier_of = [&](int l, int e) { return p.units[(size_t)unit_at(p, l, e)].tier; };
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
REQUIRE(tier_of(0, e) == Tier::HostPinned);
|
||||
REQUIRE(tier_of(1, e) == Tier::SSD);
|
||||
REQUIRE(tier_of(2, e) == Tier::SSD);
|
||||
}
|
||||
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
mc.container_path = path;
|
||||
CHECK_OK(m.init(f.prog, p, mc));
|
||||
RadStream s = nullptr;
|
||||
CHECK_OK(rad_stream_create(&s, 0));
|
||||
CHECK_OK(m.bind_compute_stream(s));
|
||||
HeatEngine h;
|
||||
CHECK_OK(h.init(p, HeatParams{}));
|
||||
REQUIRE(h.enabled());
|
||||
SharedCounts counts(4);
|
||||
FileStager fs;
|
||||
CHECK_OK(fs.init(f.prog, p, &m, &SharedCounts::get, &counts));
|
||||
/* Layer 0 is covered though the plan put none of it on the file tier: a deposit may give its
|
||||
* pooled units back to the file tier. */
|
||||
REQUIRE_EQ(fs.n_layers(), (size_t)L);
|
||||
auto pub = [&](int l, int e) { return published(m, p, f.prog, unit_at(p, l, e), img, s); };
|
||||
|
||||
/* Where the pooled units are published: their pool slots, which this test never fills (the
|
||||
* load phase does), so they are compared by address. */
|
||||
auto addr = [&](int l, int e) {
|
||||
return m.residency()->lookup(p.units[(size_t)unit_at(p, l, e)].weights.front())->ptr;
|
||||
};
|
||||
void* const pooled[3] = { addr(0, 1), addr(0, 2), addr(0, 3) };
|
||||
for (void* q : pooled) CHECK(q != nullptr);
|
||||
|
||||
void* const pooled0 = addr(0, 0);
|
||||
/* Layers 1 and 2 are read whole, ahead (no counts for them); each has one warm expert. */
|
||||
counts.missing = {1, 2};
|
||||
const int32_t hist1[4] = {0, 0, 5, 0}, hist2[4] = {3, 0, 0, 0};
|
||||
h.observe(1, hist1, 4);
|
||||
h.observe(2, hist2, 4);
|
||||
CHECK_OK(m.begin_dispatch(1, &h));
|
||||
|
||||
RadBatch b{};
|
||||
bool resync = false;
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
counts.route({1, 0, 0, 0});
|
||||
CHECK_OK(fs.before_op(1, s, &resync)); /* layer 0 starts; layer 1 read ahead */
|
||||
CHECK_EQ(m.stats().pool_evictions, (uint64_t)0);
|
||||
CHECK(addr(0, 0) == pooled0);
|
||||
CHECK(addr(0, 1) == pooled[0] && addr(0, 2) == pooled[1] && addr(0, 3) == pooled[2]);
|
||||
CHECK(pub(1, 2) == Pub::Bytes);
|
||||
CHECK_OK(fs.before_op(2, s, &resync));
|
||||
CHECK_OK(fs.before_op(3, s, &resync)); /* layer 1 starts; layer 2 read ahead */
|
||||
CHECK_EQ(m.stats().pool_evictions, (uint64_t)1);
|
||||
CHECK(pub(2, 0) == Pub::Bytes);
|
||||
CHECK_OK(fs.before_op(4, s, &resync));
|
||||
CHECK_OK(fs.before_op(5, s, &resync));
|
||||
CHECK_OK(fs.before_op(6, s, &resync));
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
|
||||
/* A read-ahead the pass never reaches still copied (a deposit into the pool, say), and the
|
||||
* stream is ordered behind it when the pass ends. Once the slot layer 0 gave up is back, layer
|
||||
* 1 is read ahead at layer 0's trigger and the pass stops there. */
|
||||
for (int d = 2; d < 5; ++d) {
|
||||
CHECK_OK(rad_stream_sync(s));
|
||||
CHECK_OK(m.begin_dispatch(d, &h));
|
||||
}
|
||||
CHECK(fs.begin_pass(&b));
|
||||
CHECK_OK(fs.before_op(0, s, &resync));
|
||||
counts.route({1, 0, 0, 0});
|
||||
CHECK_OK(fs.before_op(1, s, &resync));
|
||||
const int64_t waits = fs.waits();
|
||||
CHECK_OK(fs.end_pass(s));
|
||||
CHECK_EQ(fs.waits(), waits + 1);
|
||||
|
||||
rad_stream_sync(m.transfer_stream());
|
||||
rad_stream_sync(s);
|
||||
rad_stream_destroy(s);
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
TEST(mover_promotes_and_demotes_through_the_shadow_slots) {
|
||||
HeatFixture hf;
|
||||
HeatEngine h;
|
||||
|
||||
@@ -272,6 +272,25 @@ TEST(an_expert_reads_its_own_hessian_before_its_layers) {
|
||||
CHECK(same_planes(run(both, e11), run(only_pool, e11)));
|
||||
}
|
||||
|
||||
TEST(a_vocabulary_heads_width_class_reads_the_heads_hessian) {
|
||||
/* A calibration run records the lm_head's input as `output`; the vocabulary-weighted head's
|
||||
* classes (output.k3, output.k4, ...) are rows of that one weight and quantise against it, as
|
||||
* a weight named `output` does. With no Gram at all GPTQ rounds to nearest, which differs. */
|
||||
NEED_LIBQUANT();
|
||||
const TempDir t("rad_quant_vhead"), e("rad_quant_novhead");
|
||||
REQUIRE(!t.path.empty() && !e.path.empty());
|
||||
REQUIRE(write_gram(t.path + "/gram.r0.output.bin", kC, kT, H()));
|
||||
auto run = [&](const std::string& dir, const char* name) -> Quantised {
|
||||
Opts o;
|
||||
o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str());
|
||||
Quantised q = quantise(quantizer("gptq"), o, name, kR, kC, weight());
|
||||
CHECK_EQ(q.status, RAD_OK);
|
||||
return q;
|
||||
};
|
||||
CHECK(same_planes(run(t.path, "output.k4.weight"), run(t.path, "output.weight")));
|
||||
CHECK(!same_planes(run(t.path, "output.k4.weight"), run(e.path, "output.k4.weight")));
|
||||
}
|
||||
|
||||
TEST(gptq_through_lapack_matches_the_loops) {
|
||||
/* Where OpenBLAS was found the factorisations go through LAPACK; RAD_LQ_LAPACK=0 takes the
|
||||
* single-threaded loops, the reference. The same Gram in two directories (the factor cache is
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/* Drives libr4d's windowed attn_paged entry points (r4d_attn_paged_window.hip) through the SIMT
|
||||
* emulator and checks every output element against a port of libref's ref_attn_paged (same mask
|
||||
* predicates, f64 accumulation). */
|
||||
* predicates, f64 accumulation). The attn_paged_sink entries too: a sink logit a query head joins
|
||||
* the reference's maximum and sum. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
@@ -37,15 +38,31 @@ struct Case {
|
||||
int64_t scratch = 0; /* 0: no scratch */
|
||||
int qpitch_extra = 0; /* q as a column slice of a wider buffer */
|
||||
int expect_wmma = -1; /* 1: must take the WMMA kernel, 0: must not, -1: either */
|
||||
bool ahead = false; /* non-causal, the window bounds the keys behind only */
|
||||
bool sink = false; /* attn_paged_sink: a sink logit a query head */
|
||||
};
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static Fn pick(int hd, int gqa, bool fp8) {
|
||||
static Fn pick(int hd, int gqa, bool fp8, 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;
|
||||
A(1) A(2) A(4) A(8)
|
||||
#undef A
|
||||
return nullptr;
|
||||
}
|
||||
#define P(H, G) if (hd == H && gqa == G) return fp8 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(128, 1) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
P(512, 16)
|
||||
#undef P
|
||||
return nullptr;
|
||||
}
|
||||
static Fn pick_sink(int hd, int gqa, bool fp8) {
|
||||
if (hd == 128 && gqa == 8)
|
||||
return fp8 ? r4d_rad_attn_window_sink_h128_gqa8_fp8 : 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 nullptr;
|
||||
}
|
||||
|
||||
static int run(const Case& c) {
|
||||
const int n_seq = (int)c.qlen.size(), HD = c.hd, kvh = c.kvh, qh = kvh * c.gqa;
|
||||
@@ -93,7 +110,11 @@ static int run(const Case& c) {
|
||||
std::vector<char> scratch(c.scratch + 64);
|
||||
char* sp = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
|
||||
RadTensor t[8];
|
||||
/* Sinks spread around the scores' scale, a few far above them (the sink takes the maximum) and
|
||||
* one far below (it vanishes). */
|
||||
std::vector<float> sinks(qh);
|
||||
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[2] = tens(bt.data(), RAD_I32, {n_seq, maxb});
|
||||
@@ -102,20 +123,22 @@ static int run(const Case& c) {
|
||||
t[5] = c.descale ? tens(vd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
t[6] = c.ragged ? tens(cu.data(), RAD_I32, {n_seq + 1}) : RadTensor{};
|
||||
t[7] = tens(out.data(), RAD_BF16, {rows, qh, HD});
|
||||
if (c.sink) { t[8] = t[7]; t[7] = tens(sinks.data(), RAD_F32, {qh}); }
|
||||
int qmax = 0; for (int q : c.qlen) qmax = std::max(qmax, q);
|
||||
std::vector<RadParam> p;
|
||||
auto pi = [&](const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); };
|
||||
auto ps = [&](const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = v; p.push_back(x); };
|
||||
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); pi("window", c.window);
|
||||
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");
|
||||
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 = 8; a.p = p.data(); a.n_p = (int)p.size();
|
||||
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 = pick(HD, c.gqa, c.fp8);
|
||||
Fn fn = c.sink ? pick_sink(HD, c.gqa, c.fp8) : pick(HD, c.gqa, c.fp8, 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);
|
||||
const int launches = emu_grids - g0;
|
||||
@@ -127,7 +150,7 @@ static int run(const Case& c) {
|
||||
const int tok = cu[s] + i, kh = h / c.gqa, pos = c.ctx[s] - c.qlen[s] + i;
|
||||
auto visible = [&](int j) {
|
||||
if (c.causal ? j > pos : j >= c.ctx[s]) return false;
|
||||
if (c.window > 0) { const int d = pos - j; if (c.causal ? d >= c.window : (d >= c.window || d <= -c.window)) return false; }
|
||||
if (c.window > 0) { const int d = pos - j; if (c.causal ? d >= c.window : (d >= c.window || (!c.ahead && d <= -c.window))) return false; }
|
||||
return bt[s * maxb + j / 16] >= 0;
|
||||
};
|
||||
std::vector<double> sc(c.ctx[s], -INFINITY); double mx = -INFINITY;
|
||||
@@ -138,13 +161,16 @@ static int run(const Case& c) {
|
||||
sc[j] = dot * scale; mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(HD, 0.0); double sum = 0;
|
||||
if (mx > -INFINITY)
|
||||
const bool any = mx > -INFINITY;
|
||||
if (c.sink && any) mx = std::max(mx, (double)sinks[h]);
|
||||
if (any)
|
||||
for (int j = 0; j < c.ctx[s]; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx); sum += w;
|
||||
const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot;
|
||||
for (int d = 0; d < HD; ++d) acc[d] += w * kvf[kb + HD + d] * vd[s * kvh + kh];
|
||||
}
|
||||
if (c.sink && any) sum += std::exp((double)sinks[h] - mx);
|
||||
for (int d = 0; d < HD; ++d) {
|
||||
const double ref = sum > 0 ? acc[d] / sum : 0.0;
|
||||
const float got = rad_bf16_to_f32(out[((size_t)tok * qh + h) * HD + d]);
|
||||
@@ -197,6 +223,13 @@ int main(int argc, char** argv) {
|
||||
{"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512},
|
||||
{"h256 gqa2 swa w1024 verify, ragged, splits", 256, 2, 2, true, true, true, true, 1024, {3, 5}, {20, 900}, -1, 262144, s256},
|
||||
{"h512 gqa2 full ragged", 512, 2, 2, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}},
|
||||
/* 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 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},
|
||||
/* the coverage the rows claim beyond Gemma: non-causal, two-sided window, a missing block */
|
||||
{"h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {6, 2}, {70, 30}, 2},
|
||||
{"h512 gqa1 noncausal full", 512, 1, 1, false, false, false, false, 0, {4}, {37}},
|
||||
@@ -208,11 +241,49 @@ int main(int argc, char** argv) {
|
||||
{"wmma h512 gqa8 prefill fp8+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 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 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},
|
||||
/* 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 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 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},
|
||||
/* 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 */
|
||||
{"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},
|
||||
-1, 262144, s128, 0, -1, false, true},
|
||||
{"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96},
|
||||
{400}, -1, 0, 0, 0, 0, false, true},
|
||||
{"sink h128 gqa16 missing-block", 128, 16, 1, false, false, false, false, 1024, {8}, {70}, 1,
|
||||
0, 0, 0, -1, false, true},
|
||||
/* and at TP 4, 8 query heads over the rank's replicated KV head */
|
||||
{"sink h128 gqa8 kvh1 block8 w1024", 128, 8, 1, false, false, false, false, 1024, {8}, {1500},
|
||||
-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},
|
||||
-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},
|
||||
/* and what must stay scalar: a verify batch, many sequences, a few rows each */
|
||||
{"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16},
|
||||
{40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0},
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/* LiLiCorr's correlator (r4d_lili.hip) through the SIMT emulator, at the drafter's geometry: seven
|
||||
* positions of eight candidates, eight heads of 128, a 1024-wide lattice. Each kernel against a host
|
||||
* port of libref's ref_lili.cpp in double: lili_cand over two ranks' disjoint vocabulary halves (ids
|
||||
* exact, features and the additive part to bf16), lili_attn and lili_factor to bf16, lili_walk's
|
||||
* scores to f32 rounding and its tokens exactly wherever the winning margin is not a near-tie. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::mt19937 rng(77);
|
||||
static float nrm() { static std::normal_distribution<float> d(0.f, 1.f); return d(rng); }
|
||||
|
||||
static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) { t.shape[i] = shape[i]; t.stride[i] = st; st *= shape[i]; }
|
||||
return t;
|
||||
}
|
||||
static std::vector<uint16_t> bfv(size_t n, float sc, std::vector<float>* f) {
|
||||
std::vector<uint16_t> b(n);
|
||||
f->resize(n);
|
||||
for (size_t i = 0; i < n; ++i) { b[i] = rad_f32_to_bf16(nrm() * sc); (*f)[i] = rad_bf16_to_f32(b[i]); }
|
||||
return b;
|
||||
}
|
||||
struct Params {
|
||||
std::vector<RadParam> p;
|
||||
std::vector<std::string> s;
|
||||
void i(const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); }
|
||||
void f(const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); }
|
||||
void str(const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = v; p.push_back(x); }
|
||||
};
|
||||
/* rel_l2 and the worst element relative to the reference's scale */
|
||||
static bool close(const char* what, const std::vector<double>& ref, const std::vector<float>& got, double tol) {
|
||||
double se = 0, sr = 0, worst = 0, scale = 1e-30;
|
||||
long nan = 0;
|
||||
for (double r : ref) scale = std::max(scale, std::fabs(r));
|
||||
for (size_t i = 0; i < ref.size(); ++i) {
|
||||
if (std::isnan(got[i])) { ++nan; continue; }
|
||||
const double e = std::fabs(got[i] - ref[i]);
|
||||
se += e * e; sr += ref[i] * ref[i];
|
||||
worst = std::max(worst, e / scale);
|
||||
}
|
||||
const double rel = std::sqrt(se / std::max(sr, 1e-30));
|
||||
const bool ok = nan == 0 && rel < tol && worst < 8 * tol;
|
||||
std::printf(" %-34s rel_l2 %.2e worst %.2e nan %ld %s\n", what, rel, worst, nan, ok ? "PASS" : "FAIL");
|
||||
return ok;
|
||||
}
|
||||
|
||||
static int test_cand() {
|
||||
const int K = 8, RK = 9, W = 2, S = 7, N = 1024, M = 2 * S, V = 131072, w = 2 + 2 * RK;
|
||||
/* stats: each rank's row of its own vocabulary half, sorted, a tie across the ranks on row 3 */
|
||||
std::vector<float> st((size_t)M * W * w);
|
||||
std::vector<double> lse(M);
|
||||
std::vector<std::vector<std::pair<float, int>>> all(M);
|
||||
for (int m = 0; m < M; ++m) {
|
||||
double tot = 0, gmx = -INFINITY;
|
||||
std::vector<double> mxr(W), sumr(W);
|
||||
for (int r = 0; r < W; ++r) {
|
||||
std::vector<std::pair<float, int>> v;
|
||||
for (int j = 0; j < K; ++j) v.push_back({ 2.f * nrm() + 3.f, r * (V / W) + (int)(rng() % (V / W)) });
|
||||
if (m == 3 && r == 1) v[0] = { all[m][0].first, all[m][0].second + V / W }; /* a tie */
|
||||
std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); });
|
||||
const float mx = v[0].first, sum = 1.0f + 300.f * (float)(rng() % 100) / 100.f;
|
||||
float* row = &st[((size_t)m * W + r) * w];
|
||||
row[0] = mx; row[1] = sum;
|
||||
for (int j = 0; j < K; ++j) { row[2 + 2 * j] = (float)v[j].second; row[3 + 2 * j] = v[j].first; all[m].push_back(v[j]); }
|
||||
/* the ninth pair, below the eighth: carried for the all-gather's 16-byte rows, never kept */
|
||||
row[2 + 2 * K] = (float)(r * (V / W)); row[3 + 2 * K] = v[K - 1].first - 1.0f;
|
||||
mxr[r] = mx; sumr[r] = sum; gmx = std::max(gmx, (double)mx);
|
||||
}
|
||||
for (int r = 0; r < W; ++r) tot += sumr[r] * std::exp(mxr[r] - gmx);
|
||||
lse[m] = gmx + std::log(tot);
|
||||
std::sort(all[m].begin(), all[m].end(), [](auto& a, auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); });
|
||||
}
|
||||
std::vector<float> pasf, slotf, rankf;
|
||||
auto pas = bfv((size_t)M * N, 1.f, &pasf), slot = bfv((size_t)S * N, 0.5f, &slotf), rank = bfv((size_t)K * N, 0.5f, &rankf);
|
||||
std::vector<float> lnw(5), lnb(5), upw((size_t)N * 5), upb(N);
|
||||
for (auto* v : { &lnw, &lnb, &upw, &upb }) for (auto& x : *v) x = nrm() * 0.7f;
|
||||
std::vector<int32_t> cand((size_t)M * K, -7);
|
||||
std::vector<uint16_t> feat((size_t)M * K * N), base((size_t)M * K * N);
|
||||
RadTensor t[11] = {
|
||||
tens(st.data(), RAD_F32, { M, W * w }), tens(pas.data(), RAD_BF16, { M, N }),
|
||||
tens(lnw.data(), RAD_F32, { 5 }), tens(lnb.data(), RAD_F32, { 5 }),
|
||||
tens(upw.data(), RAD_F32, { N, 5 }), tens(upb.data(), RAD_F32, { N }),
|
||||
tens(slot.data(), RAD_BF16, { S, N }), tens(rank.data(), RAD_BF16, { K, N }),
|
||||
tens(cand.data(), RAD_I32, { M, K }), tens(feat.data(), RAD_BF16, { M * K, N }),
|
||||
tens(base.data(), RAD_BF16, { M * K, N }),
|
||||
};
|
||||
Params P;
|
||||
P.i("M", M); P.i("k", K); P.i("world", W); P.i("steps", S); P.i("n", N); P.str("dtype", "bf16"); P.f("eps", 1e-5);
|
||||
P.i("row_k", RK);
|
||||
RadArgs a{}; a.t = t; a.n_t = 11; a.p = P.p.data(); a.n_p = (int)P.p.size();
|
||||
const int rc = r4d_rad_lili_cand(&a, nullptr);
|
||||
if (rc != RAD_OK) { std::printf(" lili_cand launch %d\n", rc); return 1; }
|
||||
bool ok = true;
|
||||
std::vector<double> rf, rb;
|
||||
std::vector<float> gf, gb;
|
||||
for (int m = 0; m < M; ++m) {
|
||||
double lp[8];
|
||||
for (int j = 0; j < K; ++j) {
|
||||
ok = ok && cand[(size_t)m * K + j] == all[m][j].second;
|
||||
lp[j] = all[m][j].first - lse[m];
|
||||
}
|
||||
for (int j = 0; j < K; ++j) {
|
||||
const double f[5] = { lp[j], std::exp(lp[j]), lp[j] - lp[0], (double)j / (K - 1), j == 0 ? 1.0 : 0.0 };
|
||||
double mean = 0, var = 0;
|
||||
for (double x : f) mean += x;
|
||||
mean /= 5;
|
||||
for (double x : f) var += (x - mean) * (x - mean);
|
||||
var /= 5;
|
||||
double y[5];
|
||||
for (int i = 0; i < 5; ++i) y[i] = (f[i] - mean) / std::sqrt(var + 1e-5) * lnw[i] + lnb[i];
|
||||
for (int c = 0; c < N; ++c) {
|
||||
double u = upb[c];
|
||||
for (int i = 0; i < 5; ++i) u += upw[(size_t)c * 5 + i] * y[i];
|
||||
rf.push_back(u / (1 + std::exp(-u)));
|
||||
rb.push_back((double)pasf[(size_t)m * N + c] + slotf[(size_t)(m % S) * N + c] + rankf[(size_t)j * N + c]);
|
||||
gf.push_back(rad_bf16_to_f32(feat[((size_t)m * K + j) * N + c]));
|
||||
gb.push_back(rad_bf16_to_f32(base[((size_t)m * K + j) * N + c]));
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf(" lili_cand ids (two ranks, a tie) %s\n", ok ? "PASS" : "FAIL");
|
||||
ok = close("lili_cand features", rf, gf, 5e-3) && ok;
|
||||
ok = close("lili_cand additive part", rb, gb, 5e-3) && ok;
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
static int test_attn() {
|
||||
const int S = 7, K = 8, L = S * K, NH = 8, HD = 128, N = NH * HD, NS = 2, M = NS * L;
|
||||
std::vector<float> qf;
|
||||
auto qkv = bfv((size_t)M * 3 * N, 0.25f, &qf);
|
||||
std::vector<float> rel((size_t)NH * (2 * S + 1)), same(NH);
|
||||
for (auto& x : rel) x = nrm();
|
||||
for (auto& x : same) x = nrm();
|
||||
std::vector<uint16_t> out((size_t)M * N, 0xffff);
|
||||
RadTensor t[4] = { tens(qkv.data(), RAD_BF16, { M, 3 * N }), tens(rel.data(), RAD_F32, { NH, 2 * S + 1 }),
|
||||
tens(same.data(), RAD_F32, { NH }), tens(out.data(), RAD_BF16, { M, N }) };
|
||||
Params P;
|
||||
P.i("M", M); P.i("steps", S); P.i("k", K); P.i("n_head", NH); P.i("head_dim", HD); P.str("dtype", "bf16");
|
||||
RadArgs a{}; a.t = t; a.n_t = 4; a.p = P.p.data(); a.n_p = (int)P.p.size();
|
||||
const int rc = r4d_rad_lili_attn(&a, nullptr);
|
||||
if (rc != RAD_OK) { std::printf(" lili_attn launch %d\n", rc); return 1; }
|
||||
std::vector<double> ref((size_t)M * N);
|
||||
const double scale = 1.0 / std::sqrt((double)HD);
|
||||
for (int i = 0; i < M; ++i) for (int h = 0; h < NH; ++h) {
|
||||
const int q0 = i / L * L, si = (i - q0) / K;
|
||||
std::vector<double> sc(L);
|
||||
double mx = -INFINITY;
|
||||
for (int j = 0; j < L; ++j) {
|
||||
double d = 0;
|
||||
for (int e = 0; e < HD; ++e) d += (double)qf[(size_t)i * 3 * N + h * HD + e] * qf[(size_t)(q0 + j) * 3 * N + N + h * HD + e];
|
||||
const int sj = j / K;
|
||||
sc[j] = d * scale + rel[(size_t)h * (2 * S + 1) + si - sj + S] + (si == sj ? same[h] : 0.f);
|
||||
mx = std::max(mx, sc[j]);
|
||||
}
|
||||
double sum = 0;
|
||||
for (auto& x : sc) { x = std::exp(x - mx); sum += x; }
|
||||
for (int e = 0; e < HD; ++e) {
|
||||
double acc = 0;
|
||||
for (int j = 0; j < L; ++j) acc += sc[j] * qf[(size_t)(q0 + j) * 3 * N + 2 * N + h * HD + e];
|
||||
ref[(size_t)i * N + h * HD + e] = acc / sum;
|
||||
}
|
||||
}
|
||||
std::vector<float> got(out.size());
|
||||
for (size_t i = 0; i < out.size(); ++i) got[i] = rad_bf16_to_f32(out[i]);
|
||||
return close("lili_attn two lattices", ref, got, 5e-3) ? 0 : 1;
|
||||
}
|
||||
|
||||
static int test_factor() {
|
||||
const int L = 56, N = 1024, NS = 3, M = NS * L;
|
||||
std::vector<float> hf, af;
|
||||
auto h = bfv((size_t)M * N, 1.f, &hf), an = bfv((size_t)NS * N, 1.f, &af);
|
||||
std::vector<uint16_t> y((size_t)M * 3 * N);
|
||||
RadTensor t[3] = { tens(h.data(), RAD_BF16, { M, N }), tens(an.data(), RAD_BF16, { NS, N }),
|
||||
tens(y.data(), RAD_BF16, { M, 3 * N }) };
|
||||
Params P;
|
||||
P.i("M", M); P.i("L", L); P.i("n", N); P.str("dtype", "bf16");
|
||||
RadArgs a{}; a.t = t; a.n_t = 3; a.p = P.p.data(); a.n_p = (int)P.p.size();
|
||||
if (r4d_rad_lili_factor(&a, nullptr) != RAD_OK) { std::printf(" lili_factor launch failed\n"); return 1; }
|
||||
long bad = 0;
|
||||
for (int i = 0; i < M; ++i) for (int c = 0; c < N; ++c) {
|
||||
const uint16_t* r = &y[(size_t)i * 3 * N];
|
||||
bad += r[c] != h[(size_t)i * N + c];
|
||||
bad += r[N + c] != an[(size_t)(i / L) * N + c];
|
||||
bad += r[2 * N + c] != rad_f32_to_bf16(hf[(size_t)i * N + c] * af[(size_t)(i / L) * N + c]);
|
||||
}
|
||||
std::printf(" %-34s bad %ld %s\n", "lili_factor (bit for bit)", bad, bad ? "FAIL" : "PASS");
|
||||
return bad ? 1 : 0;
|
||||
}
|
||||
|
||||
static int test_walk() {
|
||||
const int S = 7, K = 8, N = 1024, M = 5, R = S * K;
|
||||
std::vector<float> ef, af;
|
||||
auto ed = bfv((size_t)M * R * 2 * N, 1.f, &ef), ao = bfv((size_t)M * N, 1.f, &af);
|
||||
std::vector<int32_t> cand((size_t)M * S * K), tok((size_t)M * S, -9);
|
||||
for (auto& c : cand) c = (int32_t)(rng() % 131072);
|
||||
std::vector<float> scores((size_t)M * S * K * K);
|
||||
RadTensor t[5] = { tens(ed.data(), RAD_BF16, { M * R, 2 * N }), tens(ao.data(), RAD_BF16, { M, N }),
|
||||
tens(cand.data(), RAD_I32, { M * S, K }), tens(tok.data(), RAD_I32, { M, S }),
|
||||
tens(scores.data(), RAD_F32, { M, S, K, K }) };
|
||||
Params P;
|
||||
P.i("M", M); P.i("steps", S); P.i("k", K); P.i("n", N); P.str("dtype", "bf16"); P.f("eps", 1e-4); P.f("scale", 8.0);
|
||||
RadArgs a{}; a.t = t; a.n_t = 5; a.p = P.p.data(); a.n_p = (int)P.p.size();
|
||||
if (r4d_rad_lili_walk(&a, nullptr) != RAD_OK) { std::printf(" lili_walk launch failed\n"); return 1; }
|
||||
std::vector<double> ref((size_t)M * S * K * K);
|
||||
long tbad = 0, near = 0;
|
||||
for (int m = 0; m < M; ++m) {
|
||||
auto vec = [&](const float* p, std::vector<double>& v) {
|
||||
double ss = 0;
|
||||
v.assign(p, p + N);
|
||||
for (double x : v) ss += x * x;
|
||||
const double inv = 1.0 / std::max(std::sqrt(ss), 1e-4);
|
||||
for (double& x : v) x *= inv;
|
||||
};
|
||||
std::vector<std::vector<double>> vo(R), vi(R);
|
||||
std::vector<double> va;
|
||||
vec(&af[(size_t)m * N], va);
|
||||
for (int r = 0; r < R; ++r) {
|
||||
vec(&ef[((size_t)m * R + r) * 2 * N], vo[r]);
|
||||
vec(&ef[((size_t)m * R + r) * 2 * N + N], vi[r]);
|
||||
}
|
||||
auto dot = [&](const std::vector<double>& x, const std::vector<double>& y) {
|
||||
double s = 0;
|
||||
for (int c = 0; c < N; ++c) s += x[c] * y[c];
|
||||
return 8.0 * s;
|
||||
};
|
||||
double* sc = &ref[(size_t)m * S * K * K];
|
||||
for (int j = 0; j < K; ++j) { const double v = dot(va, vi[j]); for (int i = 0; i < K; ++i) sc[i * K + j] = v; }
|
||||
for (int s = 1; s < S; ++s) for (int i = 0; i < K; ++i) for (int j = 0; j < K; ++j)
|
||||
sc[(s * K + i) * K + j] = dot(vo[(s - 1) * K + i], vi[s * K + j]);
|
||||
/* The walk on the reference scores; a step whose two best differ by less than f32 noise
|
||||
* may legitimately go the other way, and then the rest of the path is not compared. */
|
||||
int prev = 0;
|
||||
for (int s = 0; s < S; ++s) {
|
||||
const double* row = sc + (s * K + prev) * K;
|
||||
int best = 0;
|
||||
for (int j = 1; j < K; ++j) if (row[j] > row[best]) best = j;
|
||||
double second = -INFINITY;
|
||||
for (int j = 0; j < K; ++j) if (j != best) second = std::max(second, row[j]);
|
||||
if (row[best] - second < 1e-4) { ++near; break; }
|
||||
tbad += tok[(size_t)m * S + s] != cand[((size_t)m * S + s) * K + best];
|
||||
prev = best;
|
||||
}
|
||||
}
|
||||
std::printf(" %-34s bad %ld near-ties %ld %s\n", "lili_walk tokens", tbad, near, tbad ? "FAIL" : "PASS");
|
||||
const bool ok = close("lili_walk scores", ref, scores, 1e-4) && tbad == 0;
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = 0;
|
||||
fails += test_cand();
|
||||
fails += test_attn();
|
||||
fails += test_factor();
|
||||
fails += test_walk();
|
||||
std::printf("lili: %d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -714,6 +715,172 @@ int periodic_report() {
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
/* mla_attn_paged (Ling-3.0's MLA) under speculation: the k + 1 rows of a verify, launched
|
||||
* together, against k + 1 single-row decodes at the same positions, each with the table its own
|
||||
* step carries and scratch as the hook sizes it. Greedy output equals the run without
|
||||
* speculation only if they agree bit for bit; a split taken from the launch's rows (16, 16 and
|
||||
* 11 ways at eight heads for one, two and three rows) or from its longest table does not. */
|
||||
int run_paged_verify(int heads, int context, std::mt19937& rng) {
|
||||
constexpr int PB = 16, RD = 64, W = D + RD, kMaxRows = 32;
|
||||
const int pages = (context + kMaxRows + PB - 1) / PB;
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> kvb((size_t)pages * PB * W), qb((size_t)kMaxRows * heads * D),
|
||||
rb((size_t)kMaxRows * heads * RD), gb((size_t)kMaxRows * heads);
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : rb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : gb) v = rad_f32_to_bf16(nrm(rng));
|
||||
std::vector<int> page(pages);
|
||||
for (int i = 0; i < pages; ++i) page[i] = i;
|
||||
std::shuffle(page.begin(), page.end(), rng);
|
||||
/* Rows [row0, row0 + rows) of one sequence whose context after the step is `used`. */
|
||||
auto launch = [&](int row0, int rows, int used, std::vector<uint16_t>& out) {
|
||||
const int blocks = (used + PB - 1) / PB;
|
||||
std::vector<int> bt(page.begin(), page.begin() + blocks), su = { used }, cu = { 0, rows };
|
||||
RadTensor t[8] = { tens(qb.data() + (size_t)row0 * heads * D, RAD_BF16, { rows, heads, D }),
|
||||
tens(rb.data() + (size_t)row0 * heads * RD, RAD_BF16,
|
||||
{ rows, heads, RD }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, PB, W }),
|
||||
tens(bt.data(), RAD_I32, { 1, blocks }),
|
||||
tens(su.data(), RAD_I32, { 1 }),
|
||||
tens(cu.data(), RAD_I32, { 2 }),
|
||||
tens(gb.data() + (size_t)row0 * heads, RAD_BF16, { rows, heads }),
|
||||
tens(out.data() + (size_t)row0 * heads * D, RAD_BF16,
|
||||
{ rows, heads, D }) };
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "heads", "latent_dim", "rope_dim", "block_size" };
|
||||
const long long vals[5] = { rows, heads, D, RD, PB };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 1.0 / std::sqrt(192.0);
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 8;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
const int64_t need = r4d_rad_mla_attn_paged_scratch(&a);
|
||||
if (need < 0) return (int)need;
|
||||
std::vector<char> scratch((size_t)need + 16, 0);
|
||||
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
return r4d_rad_mla_attn_paged(&a, nullptr);
|
||||
};
|
||||
int fails = 0;
|
||||
for (int rows : { 2, 3, 4, 5, 8, kMaxRows }) {
|
||||
std::vector<uint16_t> verify((size_t)rows * heads * D), single(verify.size());
|
||||
int rc = launch(0, rows, context + rows, verify);
|
||||
for (int i = 0; i < rows && rc == RAD_OK; ++i) rc = launch(i, 1, context + i + 1, single);
|
||||
int same = 0;
|
||||
for (int i = 0; i < rows; ++i)
|
||||
same += !std::memcmp(&verify[(size_t)i * heads * D], &single[(size_t)i * heads * D],
|
||||
(size_t)heads * D * 2);
|
||||
const bool ok = rc == RAD_OK && same == rows;
|
||||
std::printf("paged verify: %2d heads, context %4d, %2d rows: %2d/%2d rows equal the "
|
||||
"single-row decode bit for bit %s\n",
|
||||
heads, context, rows, same, rows, ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The E4M3-cache twins (r4d_rad_mla_attn*_fp8kv): every E4M3 value is a bf16, so each kernel form
|
||||
* on a cache of codes must give the bytes its bf16 instance gives on the same cache decoded to
|
||||
* bf16. Each launcher also refuses the other cache dtype. */
|
||||
int run_fp8kv(const Case& c, std::mt19937& rng) {
|
||||
const int M = c.rows, H = c.heads, B = c.blocks;
|
||||
std::vector<int> bt, len;
|
||||
const int pages = fill_tables(c, rng, bt, len);
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
|
||||
std::vector<uint8_t> kv8(kvb.size());
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (size_t i = 0; i < kv8.size(); ++i) {
|
||||
/* Codes over most exponents, subnormals included. */
|
||||
const float x = nrm(rng);
|
||||
kv8[i] = rad_f32_to_fp8e4m3(x * x * x * 4.0f);
|
||||
kvb[i] = rad_f32_to_bf16(rad_fp8e4m3_to_f32(kv8[i]));
|
||||
if (rad_bf16_to_f32(kvb[i]) != rad_fp8e4m3_to_f32(kv8[i])) {
|
||||
std::printf("%-40s E4M3 code %u is not a bf16 FAIL\n", c.name.c_str(), kv8[i]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
std::vector<char> scratch;
|
||||
typedef int (*Launch)(const RadArgs*, RadStream);
|
||||
auto launch = [&](Launch fn, bool fp8, std::vector<uint16_t>& out) {
|
||||
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
|
||||
fp8 ? tens(kv8.data(), RAD_F8E4M3, { pages, 1, BS, D })
|
||||
: tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
|
||||
tens(out.data(), RAD_BF16, { M, H, D }) };
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { M, D, H, B, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 0.0625;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
if (c.scratch) {
|
||||
const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a);
|
||||
scratch.assign((size_t)need + 16, 0);
|
||||
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
}
|
||||
return fn(&a, nullptr);
|
||||
};
|
||||
struct Form {
|
||||
const char* name;
|
||||
Launch bf16, fp8;
|
||||
void (*pin)(int);
|
||||
int form;
|
||||
};
|
||||
std::vector<Form> forms = { { "wave", r4d_rad_mla_attn, r4d_rad_mla_attn_fp8kv, nullptr, 0 } };
|
||||
if (H % 8 == 0) {
|
||||
forms.push_back({ "matrix", r4d_rad_mla_attn_matrix, r4d_rad_mla_attn_matrix_fp8kv,
|
||||
r4d_mla_matrix_pin_form, 0 });
|
||||
forms.push_back({ "matrix, element load", r4d_rad_mla_attn_matrix,
|
||||
r4d_rad_mla_attn_matrix_fp8kv, r4d_mla_matrix_pin_form, 1 });
|
||||
}
|
||||
if (H % 32 == 0)
|
||||
for (int form : { 0, 3, 1, 2 })
|
||||
forms.push_back({ "rows", r4d_rad_mla_attn_rows, r4d_rad_mla_attn_rows_fp8kv,
|
||||
r4d_mla_rows_pin_form, form });
|
||||
int fails = 0;
|
||||
for (const Form& f : forms) {
|
||||
std::vector<uint16_t> want((size_t)M * H * D, 0xffff), got(want.size(), 0xffff);
|
||||
if (f.pin) f.pin(f.form);
|
||||
const int rb = launch(f.bf16, false, want), rf = launch(f.fp8, true, got);
|
||||
std::vector<uint16_t> spare(want.size(), 0xffff);
|
||||
const int refuse_b = launch(f.bf16, true, spare), refuse_f = launch(f.fp8, false, spare);
|
||||
if (f.pin) f.pin(0);
|
||||
size_t differ = 0;
|
||||
for (size_t i = 0; i < got.size(); ++i) differ += got[i] != want[i];
|
||||
const bool untouched = std::all_of(spare.begin(), spare.end(),
|
||||
[](uint16_t v) { return v == 0xffff; });
|
||||
const bool ok = rb == RAD_OK && rf == RAD_OK && !differ && refuse_b == RAD_E_DTYPE &&
|
||||
refuse_f == RAD_E_DTYPE && untouched;
|
||||
std::printf("%-40s fp8kv %-20s form %d rc %d/%d %zu differ from bf16, refusals %d/%d "
|
||||
"%s\n",
|
||||
c.name.c_str(), f.name, f.form, rb, rf, differ, refuse_b, refuse_f,
|
||||
ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
@@ -766,6 +933,19 @@ int main(int argc, char** argv) {
|
||||
std::mt19937 rng(20261020u + (unsigned)i);
|
||||
fails += run_rows(rows_cases[i], rng);
|
||||
}
|
||||
/* The E4M3-cache twins against their bf16 instances. */
|
||||
std::vector<Case> fp8_cases = {
|
||||
{ "fp8kv: ragged, holes and bad pages", 7, 8, 17, Fill::ragged },
|
||||
{ "fp8kv: prefill, 16 heads, split", 4, 16, 33, Fill::prefill, 0, 0, true },
|
||||
{ "fp8kv: topk d=4, 8 heads", 6, 8, 33, Fill::topk, 4, 400 },
|
||||
{ "fp8kv: rows, ragged", 3, 64, 17, Fill::ragged },
|
||||
{ "fp8kv: rows, topk d=4, split", 2, 64, 33, Fill::topk, 4, 400, true },
|
||||
};
|
||||
for (size_t i = 0; i < fp8_cases.size(); ++i) {
|
||||
if (filter && fp8_cases[i].name.find(filter) == std::string::npos) continue;
|
||||
std::mt19937 rng(20261028u + (unsigned)i);
|
||||
fails += run_fp8kv(fp8_cases[i], rng);
|
||||
}
|
||||
if (!filter || std::strstr("rowwise", filter)) {
|
||||
std::mt19937 rng(20261022u);
|
||||
fails += run_rowwise(rng);
|
||||
@@ -783,6 +963,13 @@ int main(int argc, char** argv) {
|
||||
std::mt19937 rng(20261021u + (unsigned)i);
|
||||
fails += run_split(splits[i].name, splits[i].world, splits[i].fresh, rng);
|
||||
}
|
||||
/* Eight heads is a TP4 rank of Ling-3.0, 32 one card; a context of 40 is under the old
|
||||
* clamp by table length, 700 past it. */
|
||||
if (!filter || std::strstr("paged verify", filter)) {
|
||||
std::mt19937 rng(20261031u);
|
||||
for (int heads : { 8, 32 })
|
||||
for (int context : { 40, 700 }) fails += run_paged_verify(heads, context, rng);
|
||||
}
|
||||
if (!filter) fails += periodic_report();
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/* radio_golden.h -- from NVIDIA's image_processing_nemotron_h_omni.py (its _compute_target_patches
|
||||
* and _compute_target_patches_video, verbatim, at the checkpoint's preprocessor_config.json) and
|
||||
* torch 2.11's F.interpolate(bicubic, align_corners=False, antialias=True); do not edit. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
static const int32_t kRadioPatch = 16, kRadioMerge = 2, kRadioMinP = 1024, kRadioMaxP = 13312;
|
||||
static const int32_t kRadioMaxLen = 16384, kRadioVideoP = 1024;
|
||||
|
||||
/* A w x h picture's tile (pw x ph patches) and a video frame's (vw x vh). */
|
||||
struct GoldRadioSize { int64_t w, h; int32_t pw, ph, vw, vh; };
|
||||
static const GoldRadioSize kGoldRadioSize[] = {
|
||||
{ 1, 1, 32, 32, 32, 32 },
|
||||
{ 16, 16, 32, 32, 32, 32 },
|
||||
{ 48, 48, 32, 32, 32, 32 },
|
||||
{ 800, 400, 50, 26, 44, 22 },
|
||||
{ 768, 512, 48, 32, 38, 26 },
|
||||
{ 800, 560, 50, 36, 38, 26 },
|
||||
{ 896, 640, 56, 40, 38, 26 },
|
||||
{ 640, 720, 40, 46, 30, 34 },
|
||||
{ 1920, 1080, 120, 68, 42, 24 },
|
||||
{ 1080, 1920, 68, 120, 24, 42 },
|
||||
{ 3840, 2160, 154, 86, 42, 24 },
|
||||
{ 4000, 3000, 132, 100, 36, 28 },
|
||||
{ 512, 512, 32, 32, 32, 32 },
|
||||
{ 496, 496, 32, 32, 32, 32 },
|
||||
{ 500, 333, 40, 26, 38, 26 },
|
||||
{ 4096, 64, 256, 4, 256, 4 },
|
||||
{ 64, 4096, 4, 256, 4, 256 },
|
||||
{ 1000, 1000, 64, 64, 32, 32 },
|
||||
{ 1600, 48, 160, 8, 184, 6 },
|
||||
{ 33, 17, 40, 28, 44, 22 },
|
||||
{ 2048, 2048, 116, 114, 32, 32 },
|
||||
{ 1280, 720, 80, 46, 42, 24 },
|
||||
{ 720, 1280, 46, 80, 24, 42 },
|
||||
{ 240, 160, 42, 26, 38, 26 },
|
||||
{ 2560, 1440, 154, 86, 42, 24 },
|
||||
{ 1824, 1824, 114, 114, 32, 32 },
|
||||
{ 1840, 1840, 116, 114, 32, 32 },
|
||||
};
|
||||
|
||||
/* A 7 x 5 picture, channel c of pixel (x, y) = (37 x + 11 y + 53 c) mod 256, resized as float to
|
||||
* 4 x 3 and to 9 x 6: [h, w, 3]. Shrinking widens the filter; growing overshoots 0..255. */
|
||||
static const float kGoldRadioAa43[] = {
|
||||
18.68736f, 71.68737f, 124.68736f, 80.90739f, 133.72572f, 194.65350f, 148.87723f, 213.02129f, 152.70291f, 211.09726f, 126.56811f, 55.45514f, 36.79506f, 89.79505f, 142.43031f, 99.01508f, 156.68340f, 218.53284f, 166.63049f, 187.91020f, 85.37108f, 234.45689f, 48.12016f, 68.77328f, 54.90274f, 107.90273f, 166.63322f, 117.12276f, 176.20847f, 186.10544f, 190.66121f, 193.38731f, 58.40165f, 164.79666f, 38.00973f, 93.24097f };
|
||||
static const float kGoldRadioAa96[] = {
|
||||
-2.15752f, 50.84248f, 103.84248f, 22.05824f, 75.05824f, 128.05823f, 53.03841f, 106.03841f, 159.03842f, 81.81619f, 134.81619f, 187.63474f, 110.59396f, 163.59395f, 216.59395f, 139.37173f, 192.37170f, 271.01746f, 168.14951f, 238.70782f, 133.00426f, 199.12965f, 169.84392f, 30.16899f, 223.34544f, 8.22708f, 73.34544f, 6.05768f, 59.05768f, 112.05769f, 30.27345f, 83.27344f, 136.27345f, 61.25361f, 114.25362f, 167.25362f, 90.03139f, 143.03140f, 199.85938f, 118.80916f, 171.80916f, 224.80916f, 147.58691f, 199.40474f, 92.79315f, 176.36472f, 258.14157f, 39.83767f, 207.34486f, 191.24995f, 53.29689f, 231.56065f, 15.60972f, 81.56065f, 15.66519f, 68.66520f, 121.66520f, 39.88095f, 92.88096f, 145.88097f, 70.86112f, 123.86114f, 176.86115f, 99.63892f, 152.63893f, 210.80418f, 128.41669f, 181.41669f, 234.41670f, 157.19443f, 220.58044f, 40.21658f, 185.97224f, 157.96931f, 15.63081f, 216.95239f, 71.77780f, 67.87831f, 241.16818f, 33.36428f, 91.16816f, 24.83185f, 77.83186f, 130.83186f, 49.04762f, 102.04762f, 155.04762f, 80.02779f, 133.02780f, 185.31654f, 108.80557f, 161.80557f, 222.22914f, 137.58333f, 190.58334f, 256.54630f, 166.36110f, 237.78807f, 63.46646f, 194.24980f, 90.82895f, 30.38097f, 230.28572f, -8.77776f, 76.11905f, 263.91144f, 48.19390f, 100.33482f, 34.43936f, 87.43935f, 140.43936f, 58.65512f, 111.65513f, 164.65514f, 89.63529f, 142.63531f, 198.74486f, 118.41308f, 171.41309f, 218.36819f, 147.19084f, 200.19084f, 196.51909f, 175.96861f, 246.17574f, 59.60552f, 208.63335f, 112.01243f, 43.80931f, 217.51062f, 14.44085f, 85.72655f, 200.58788f, 56.94232f, 109.94233f, 42.65456f, 95.65456f, 148.65459f, 66.87033f, 119.87034f, 172.87033f, 97.85049f, 150.85052f, 218.41563f, 126.62828f, 179.62830f, 186.20245f, 155.40605f, 208.40605f, -4.04360f, 184.18382f, 254.39093f, 27.43979f, 231.16805f, 120.22764f, 63.48009f, 158.61864f, 22.65605f, 93.94176f, -9.85780f, 65.15753f, 118.15753f };
|
||||
+731
-9
@@ -411,6 +411,152 @@ TEST(kda_prefill_commits_final_state_and_uses_absolute_cu_offsets) {
|
||||
CHECK_EQ(out.at(2), 0.0f);
|
||||
}
|
||||
|
||||
/* dt = 0 with no bias gives softplus(0) = ln 2, so A_log 0 and ln 2 decay by exactly 1/2 and 1/4. */
|
||||
TEST(ssd_prefill_decays_per_head_and_adds_the_skip) {
|
||||
const float l2 = std::log(2.0f);
|
||||
T x(RAD_F32, {2, 2, 1}); x.f({1, 2, 3, 4});
|
||||
T B(RAD_F32, {2, 1, 2}); B.f({1, 0, 0, 1});
|
||||
T C(RAD_F32, {2, 1, 2}); C.f({1, 1, 1, 0});
|
||||
T dt(RAD_F32, {2, 2}), dtb(RAD_F32, {2});
|
||||
T alog(RAD_F32, {2}); alog.f({0, l2});
|
||||
T D(RAD_F32, {2}); D.f({1, 0});
|
||||
T state(RAD_F32, {1, 2, 1, 2}); state.f({9, 9, 9, 9});
|
||||
T idx(RAD_I32, {1, 1}); idx.n({0});
|
||||
T cu(RAD_I32, {2}); cu.n({0, 2});
|
||||
T init(RAD_I32, {1}); init.n({0});
|
||||
T out(RAD_F32, {2, 2, 1});
|
||||
A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).tnull().t(init).t(out)
|
||||
.i("M", 2).i("heads", 2).i("head_dim", 1).i("d_state", 2).i("groups", 1)
|
||||
.s("mode", "prefill").s("dtype", "f32");
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
/* has_init 0 ignores the 9s; head 0 carries D = 1, head 1 none. */
|
||||
CHECK_NEAR(out.at(0), l2 + 1, 3e-6);
|
||||
CHECK_NEAR(out.at(1), 2 * l2, 3e-6);
|
||||
CHECK_NEAR(out.at(2), l2 / 2 + 3, 3e-6);
|
||||
CHECK_NEAR(out.at(3), l2 / 2, 3e-6);
|
||||
CHECK_NEAR(state.at(0), l2 / 2, 3e-6);
|
||||
CHECK_NEAR(state.at(1), 3 * l2, 3e-6);
|
||||
CHECK_NEAR(state.at(2), l2 / 2, 3e-6);
|
||||
CHECK_NEAR(state.at(3), 4 * l2, 3e-6);
|
||||
/* Above softplus's threshold of 20 dt passes through: e^{-25} is zero to f32 at this scale. */
|
||||
dt.f({25, 0, 0, 0});
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 25 + 1, 3e-5);
|
||||
a.ps[4].ival = 3;
|
||||
CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(ssd_candidate_states_restore_the_accepted_prefix) {
|
||||
const float l2 = std::log(2.0f);
|
||||
T x(RAD_F32, {2, 1, 1}); x.f({2, 2});
|
||||
T B(RAD_F32, {2, 1, 1}); B.f({1, 1});
|
||||
T C(RAD_F32, {2, 1, 1}); C.f({1, 1});
|
||||
T dt(RAD_F32, {2, 1}), alog(RAD_F32, {1}), dtb(RAD_F32, {1}), D(RAD_F32, {1});
|
||||
T state(RAD_F32, {3, 1, 1, 1}); state.f({4, 0, 123});
|
||||
T idx(RAD_I32, {1, 2}); idx.n({0, 1});
|
||||
T cu(RAD_I32, {2}); cu.n({0, 2});
|
||||
T accepted(RAD_I32, {1}); accepted.n({1});
|
||||
T out(RAD_F32, {2, 1, 1});
|
||||
A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).t(accepted).tnull().t(out)
|
||||
.i("M", 2).i("heads", 1).i("head_dim", 1).i("d_state", 1).i("groups", 1)
|
||||
.s("mode", "verify").s("dtype", "f32");
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 2 + 2 * l2, 3e-6);
|
||||
CHECK_NEAR(out.at(1), 1 + 3 * l2, 3e-6);
|
||||
CHECK_NEAR(state.at(0), 2 + 2 * l2, 3e-6);
|
||||
CHECK_NEAR(state.at(1), 1 + 3 * l2, 3e-6);
|
||||
CHECK_EQ(state.at(2), 123.0f);
|
||||
/* The next step keeps only candidate 0 and reads its slot. */
|
||||
cu.n({0, 1});
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 1 + 3 * l2, 3e-6);
|
||||
/* Keeping both instead starts from slot 1. */
|
||||
state.f({4, 1 + 3 * l2, 123});
|
||||
accepted.n({2});
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 0.5f * (1 + 3 * l2) + 2 * l2, 3e-6);
|
||||
accepted.n({3});
|
||||
CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* The anchor form against the per-candidate one over two verify windows: the same outputs, and the
|
||||
* committed state after a window is the candidate state its accepted prefix left, bit for bit. */
|
||||
TEST(ssd_anchor_replays_only_the_accepted_prefix_of_the_previous_window) {
|
||||
constexpr int H = 2, P = 8, N = 16, W = 3;
|
||||
for (int accepted : { 1, 2, 3 }) {
|
||||
T x(RAD_F32, { W, H, P }), B(RAD_F32, { W, 1, N }), C(RAD_F32, { W, 1, N });
|
||||
T dt(RAD_F32, { W, H }), al(RAD_F32, { H }), dtb(RAD_F32, { H }), D(RAD_F32, { H });
|
||||
T anchor(RAD_F32, { 2, H, P, N }), candidate(RAD_F32, { W, H, P, N });
|
||||
T ai(RAD_I32, { 1, 6 }), ci(RAD_I32, { 1, W }), cu(RAD_I32, { 2 }), na(RAD_I32, { 1 }),
|
||||
init(RAD_I32, { 1 });
|
||||
T ao(RAD_F32, { W, H, P }), co(RAD_F32, { W, H, P });
|
||||
std::vector<float> v(W * H * P);
|
||||
for (size_t j = 0; j < v.size(); ++j) v[j] = (float)((int)(j % 13) - 6) * 0.125f;
|
||||
x.f(v);
|
||||
std::vector<float> bc(W * N);
|
||||
for (size_t j = 0; j < bc.size(); ++j) bc[j] = (float)((int)(j % 7) - 3) * 0.25f;
|
||||
B.f(bc);
|
||||
for (size_t j = 0; j < bc.size(); ++j) bc[j] = (float)((int)(j % 5) - 2) * 0.5f;
|
||||
C.f(bc);
|
||||
dt.f({ 0.5f, -1, 0, 1, -0.5f, 2 });
|
||||
al.f({ 0, -0.5f });
|
||||
dtb.f({ 0.25f, -0.25f });
|
||||
D.f({ 1, 0.5f });
|
||||
anchor.f(std::vector<float>(2 * H * P * N, 0));
|
||||
candidate.f(std::vector<float>(W * H * P * N, 0));
|
||||
ai.n({ 0, 0, 0, 1, 1, 1 });
|
||||
ci.n({ 0, 1, 2 });
|
||||
cu.n({ 0, W });
|
||||
na.n({ 1 });
|
||||
init.n({ 1 });
|
||||
auto args = [&](T& state, T& idx, T& out, bool anc) {
|
||||
A a;
|
||||
a.t(x).t(B).t(C).t(dt).t(al).t(dtb).t(D).t(state).t(idx).t(cu).t(na).t(init).t(out)
|
||||
.i("M", W).i("heads", H).i("head_dim", P).i("d_state", N).i("groups", 1)
|
||||
.s("mode", "verify").s("dtype", "f32");
|
||||
if (anc) a.s("state_form", "anchor");
|
||||
return a;
|
||||
};
|
||||
A a = args(anchor, ai, ao, true), c = args(candidate, ci, co, false);
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
REQUIRE_EQ(run("ssd_update", c), RAD_OK);
|
||||
for (int j = 0; j < W * H * P; ++j) CHECK_EQ(ao.at(j), co.at(j));
|
||||
/* Nothing is committed before the next step says how much was accepted. */
|
||||
for (int j = 0; j < H * P * N; ++j) CHECK_EQ(anchor.at(j), 0);
|
||||
std::vector<float> committed(H * P * N);
|
||||
for (int j = 0; j < H * P * N; ++j)
|
||||
committed[j] = candidate.at((accepted - 1) * H * P * N + j);
|
||||
na.n({ accepted });
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
REQUIRE_EQ(run("ssd_update", c), RAD_OK);
|
||||
for (int j = 0; j < W * H * P; ++j) CHECK_EQ(ao.at(j), co.at(j));
|
||||
for (int j = 0; j < H * P * N; ++j) CHECK_EQ(anchor.at(j), committed[j]);
|
||||
const auto saved = anchor.mem;
|
||||
na.n({ 4 });
|
||||
CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE);
|
||||
CHECK(anchor.mem == saved);
|
||||
}
|
||||
}
|
||||
|
||||
/* Head h reads group h / (heads / groups): heads 0 and 1 share group 0, not heads 0 and 2. */
|
||||
TEST(ssd_heads_read_their_group_in_blocks) {
|
||||
const float l2 = std::log(2.0f);
|
||||
T x(RAD_F32, {1, 4, 1}); x.f({1, 1, 1, 1});
|
||||
T B(RAD_F32, {1, 2, 2}); B.f({1, 0, 0, 1});
|
||||
T C(RAD_F32, {1, 2, 2}); C.f({1, 0, 0, 2});
|
||||
T dt(RAD_F32, {1, 4}), alog(RAD_F32, {4}), dtb(RAD_F32, {4}), D(RAD_F32, {4});
|
||||
T state(RAD_F32, {1, 4, 1, 2});
|
||||
T idx(RAD_I32, {1, 1}); idx.n({0});
|
||||
T cu(RAD_I32, {2}); cu.n({0, 1});
|
||||
T out(RAD_F32, {1, 4, 1});
|
||||
A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).tnull().tnull().t(out)
|
||||
.i("M", 1).i("heads", 4).i("head_dim", 1).i("d_state", 2).i("groups", 2)
|
||||
.s("mode", "prefill").s("dtype", "f32");
|
||||
REQUIRE_EQ(run("ssd_update", a), RAD_OK);
|
||||
const float want[] = {l2, l2, 2 * l2, 2 * l2};
|
||||
for (int h = 0; h < 4; ++h) CHECK_NEAR(out.at(h), want[h], 3e-6);
|
||||
}
|
||||
|
||||
TEST(mla_attention_reads_one_latent_and_masks_the_last_selected_page) {
|
||||
T q(RAD_F32, { 1, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 2 }), bt(RAD_I32, { 1, 2 });
|
||||
T len(RAD_I32, { 1 }), out(RAD_F32, { 1, 1, 2 });
|
||||
@@ -451,6 +597,34 @@ TEST(mla_attention_reads_one_latent_and_masks_the_last_selected_page) {
|
||||
CHECK_EQ(out.at(1), 0);
|
||||
}
|
||||
|
||||
/* An E4M3 cache (kv_dtype fp8_e4m3, kv_store_fp8 at descale 1) is read as the codes' values: the
|
||||
* first case above with the latent as E4M3 codes and a bf16 query and output. */
|
||||
TEST(mla_attention_reads_an_e4m3_latent_cache_as_its_values) {
|
||||
T q(RAD_BF16, { 1, 1, 2 }), kv(RAD_F8E4M3, { 2, 1, 2, 2 }), bt(RAD_I32, { 1, 2 });
|
||||
T len(RAD_I32, { 1 }), out(RAD_BF16, { 1, 1, 2 });
|
||||
q.f({ 0, 0 });
|
||||
kv.f({ 3, 5, 448, -448, 1, 0, 0, 1 });
|
||||
bt.n({ 1, 0 });
|
||||
len.n({ 3 });
|
||||
A a;
|
||||
a.t(q)
|
||||
.t(kv)
|
||||
.t(bt)
|
||||
.t(len)
|
||||
.t(out)
|
||||
.i("M", 7)
|
||||
.i("latent_dim", 2)
|
||||
.i("heads", 1)
|
||||
.i("blocks", 2)
|
||||
.i("block_size", 2)
|
||||
.d("scale", 1)
|
||||
.s("dtype", "bf16")
|
||||
.s("kv_dtype", "fp8_e4m3");
|
||||
REQUIRE_EQ(run("mla_attn", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 4.0 / 3, 1e-2);
|
||||
CHECK_EQ(out.at(1), 2);
|
||||
}
|
||||
|
||||
TEST(dsa_score_relu_is_per_head_before_signed_weights_and_masks_invalid_history) {
|
||||
T q(RAD_F8E4M3, { 2, 2, 2 }), qs(RAD_F32, { 2, 2 }), gate(RAD_F32, { 2, 2 });
|
||||
T k(RAD_F8E4M3, { 3, 2 }), ks(RAD_F32, { 3 }), bt(RAD_I32, { 2, 3 });
|
||||
@@ -832,6 +1006,88 @@ TEST(swiglu_clamping_is_asymmetric_and_precedes_the_activation) {
|
||||
CHECK_EQ(run("swiglu_clamped", bad), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(swiglu_step_clips_the_activation_not_the_gate) {
|
||||
T gu(RAD_F32, { 1, 8 }), y(RAD_F32, { 1, 4 });
|
||||
gu.f({ -20, 2, 4.02f, 20, 9, 9, 9, -9 });
|
||||
A a;
|
||||
a.t(gu).t(y).i("M", 9).i("n", 4).d("limit", 4).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("swiglu_step", a), RAD_OK);
|
||||
auto silu = [](float g) { return g / (1 + std::exp(-g)); };
|
||||
CHECK_NEAR(y.at(0), silu(-20) * 4, 1e-6); // a negative activation is not clipped
|
||||
CHECK_NEAR(y.at(1), silu(2) * 4, 1e-5);
|
||||
CHECK_NEAR(y.at(2), silu(4.02f) * 4, 1e-5); // silu(4.02) is under 4: unclipped
|
||||
CHECK_EQ(y.at(3), -16.0f); // silu(20) clips to exactly 4, up to -4
|
||||
T gc(RAD_F32, { 1, 4 });
|
||||
A c;
|
||||
c.t(gu).t(gc).i("M", 9).i("n", 4).d("limit", 4).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("swiglu_clamped", c), RAD_OK);
|
||||
CHECK(gc.at(3) > y.at(3)); // the gate-first form stops at silu(4) * -4
|
||||
}
|
||||
|
||||
TEST(group_router_selects_only_inside_the_best_groups) {
|
||||
T lg(RAD_F32, { 1, 8 }), bias(RAD_F32, { 8 }), ids(RAD_I32, { 1, 2 }), w(RAD_F32, { 1, 2 });
|
||||
auto logit = [](float p) { return std::log(p / (1 - p)); };
|
||||
// Group sums of the top two: 1.0, 1.5, 0.86, 1.2 -> groups 1 and 3 are kept, so the single
|
||||
// best experts (0 at 0.9, 4 at 0.85) are out and 2 and 3 are chosen.
|
||||
lg.f({ logit(0.9f), logit(0.1f), logit(0.8f), logit(0.7f), logit(0.85f), logit(0.01f),
|
||||
logit(0.6f), logit(0.6f) });
|
||||
bias.f({ 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
A a;
|
||||
a.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 8).i("top_k", 2).i("n_group", 4)
|
||||
.i("topk_group", 2).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 2);
|
||||
CHECK_EQ(ids.at(1), 3);
|
||||
CHECK_NEAR(w.at(0), 2.5 * 0.8 / 1.5, 1e-5);
|
||||
CHECK_NEAR(w.at(1), 2.5 * 0.7 / 1.5, 1e-5);
|
||||
// The bias ranks groups and experts and never weights them.
|
||||
bias.f({ 0, 0, 0, 0, 0, 0, 1, 0 });
|
||||
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 6);
|
||||
CHECK_EQ(ids.at(1), 2);
|
||||
CHECK_NEAR(w.at(0), 2.5 * 0.6 / 1.4, 1e-5);
|
||||
A bad;
|
||||
bad.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 8).i("top_k", 2).i("n_group", 3)
|
||||
.i("topk_group", 2).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32");
|
||||
CHECK_EQ(run("router_sigmoid_group_topk", bad), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(paged_latent_attention_is_causal_adds_the_rotary_part_and_gates_per_head) {
|
||||
// One sequence of three tokens, the last two queried (positions 1 and 2). Token 0 and 1 sit
|
||||
// in page 1, token 2 in page 0; a row is the latent (2) then the rotary part (2).
|
||||
T q(RAD_F32, { 2, 1, 2 }), qr(RAD_F32, { 2, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 4 });
|
||||
T bt(RAD_I32, { 1, 2 }), su(RAD_I32, { 1 }), cu(RAD_I32, { 2 }), out(RAD_F32, { 2, 1, 2 });
|
||||
q.f({ 0, 0, 0, 0 });
|
||||
qr.f({ 0, 0, 0, 0 });
|
||||
kv.f({ 5, 6, 0, 0, 77, 77, 77, 77, 1, 2, 1, 0, 3, 4, 0, 0 });
|
||||
bt.n({ 1, 0 });
|
||||
su.n({ 3 });
|
||||
cu.n({ 0, 2 });
|
||||
A a;
|
||||
a.t(q).t(qr).t(kv).t(bt).t(su).t(cu).tnull().t(out).i("M", 9).i("heads", 1)
|
||||
.i("latent_dim", 2).i("rope_dim", 2).i("block_size", 2).d("scale", 1).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mla_attn_paged", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 2, 1e-6); // position 1 sees tokens 0 and 1
|
||||
CHECK_NEAR(out.at(1), 3, 1e-6);
|
||||
CHECK_NEAR(out.at(2), 3, 1e-6); // position 2 sees all three
|
||||
CHECK_NEAR(out.at(3), 4, 1e-6);
|
||||
// The rotary part alone scores token 0 at ln 3 and token 1 at 0: weights 3/4 and 1/4.
|
||||
qr.f({ std::log(3.0f), 0, 0, 0 });
|
||||
REQUIRE_EQ(run("mla_attn_paged", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 1.5, 1e-6);
|
||||
CHECK_NEAR(out.at(1), 2.5, 1e-6);
|
||||
// A gate logit of 0 halves the head.
|
||||
T gate(RAD_F32, { 2, 1 });
|
||||
gate.f({ 0, 0 });
|
||||
A g;
|
||||
g.t(q).t(qr).t(kv).t(bt).t(su).t(cu).t(gate).t(out).i("M", 9).i("heads", 1)
|
||||
.i("latent_dim", 2).i("rope_dim", 2).i("block_size", 2).d("scale", 1).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mla_attn_paged", g), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 0.75, 1e-6);
|
||||
CHECK_NEAR(out.at(1), 1.25, 1e-6);
|
||||
CHECK_NEAR(out.at(2), 1.5, 1e-6);
|
||||
}
|
||||
|
||||
TEST(sigmoid_router_uses_correction_only_for_selection_and_stable_ties) {
|
||||
T lg(RAD_F32, { 1, 4 }), bias(RAD_F32, { 4 }), ids(RAD_I32, { 1, 2 }), w(RAD_F32, { 1, 2 });
|
||||
lg.f({ -std::log(3.0f), std::log(3.0f), 0, 0 });
|
||||
@@ -966,15 +1222,19 @@ TEST(op_vocabulary) {
|
||||
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "hc_project",
|
||||
"mtp_enter",
|
||||
"mhc_pre", "mhc_pre_partial", "mhc_pre_finish", "mhc_post", "mhc_contract", "swiglu_clamped", "router_sigmoid_topk", "dsa_pool", "dsa_query", "dsa_score", "mla_attn", "mla_project", "gemm_nt_f32",
|
||||
"kda_update",
|
||||
"swiglu_step", "router_sigmoid_group_topk", "mla_attn_paged",
|
||||
"kda_update", "ssd_update",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
|
||||
"seg_softmax_pool",
|
||||
"seg_mean_bf16_sum",
|
||||
"pool_rows", "pool_cols", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw",
|
||||
"pool_rows", "pool_cols", "point_fourier", "relu", "clamp", "conv2d", "conv2d_unfold",
|
||||
"conv1d_dw",
|
||||
"rel_sinusoid",
|
||||
"seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale",
|
||||
"fill",
|
||||
"gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "causal_conv1d",
|
||||
/* Mamba-2's conv1d (Nemotron-3.5-Bolt): ple_conv with a bias inside the silu. */
|
||||
"ple_conv_bias",
|
||||
"embed_lookup_q", "cast",
|
||||
"scale_rows",
|
||||
"softmax",
|
||||
@@ -984,16 +1244,18 @@ TEST(op_vocabulary) {
|
||||
/* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run
|
||||
* from failing with "site 'host' is unavailable for this band". */
|
||||
"rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select",
|
||||
"dflash_markov_greedy", "dflash_markov_greedy_f32",
|
||||
/* Tree verification (rad_drafter_tree): the drafter's tree and the attention over it. */
|
||||
"dflash_tree", "attn_paged_tree",
|
||||
"dflash_tree", "attn_paged_tree", "attn_paged_anchor_window",
|
||||
"rmsnorm_had_quant_i8",
|
||||
"gated_had_quant_i8",
|
||||
"dequant",
|
||||
"dequant", "dequant_w4",
|
||||
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
|
||||
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
|
||||
"lora_shrink", "lora_expand", "lora_expand_mm",
|
||||
"grid_embed_aa",
|
||||
"grid_embed_aa", "grid_embed_cpe",
|
||||
"attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table",
|
||||
"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",
|
||||
@@ -1064,6 +1326,8 @@ TEST(op_vocabulary) {
|
||||
/* A pipelined prefill's first-piece KV length, a device length less a device offset. */
|
||||
"sub_i32",
|
||||
"position_scale", "embed_attn", "ministral_rope", "pixtral_rope", "pixtral_merge",
|
||||
/* LiLiCorr's candidate correlator (Nemotron-3.5-Bolt's drafter). */
|
||||
"lili_cand", "lili_attn", "lili_factor", "lili_walk",
|
||||
};
|
||||
for (const char* op : kOps) {
|
||||
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
|
||||
@@ -1072,16 +1336,18 @@ TEST(op_vocabulary) {
|
||||
CHECK_EQ(api().kernel_count(), (int)(sizeof(kOps) / sizeof(kOps[0])));
|
||||
|
||||
/* The structural constraint on the paged block, and only that; everything else must match
|
||||
* anything. attn_paged_tree is attn_paged's row with the tree operand, the same constraint. */
|
||||
* anything. attn_paged_tree, attn_paged_anchor_window and attn_paged_sink take attn_paged's. */
|
||||
CHECK_EQ(kern("attn_paged")->n_constraints, 1);
|
||||
CHECK(std::strcmp(kern("attn_paged")->constraints[0].key, "block_size") == 0);
|
||||
CHECK_EQ(kern("attn_paged_tree")->n_constraints, 1);
|
||||
CHECK_EQ(kern("attn_paged_sink")->n_constraints, 1);
|
||||
CHECK(std::strcmp(kern("attn_paged_sink")->constraints[0].key, "block_size") == 0);
|
||||
CHECK_EQ(kern("kv_store")->n_constraints, 1);
|
||||
CHECK_EQ(kern("gemm_nt")->n_constraints, 0);
|
||||
CHECK_EQ(kern("gdn_chunk_scan")->n_constraints, 0);
|
||||
int constrained = 0;
|
||||
for (int i = 0; i < api().kernel_count(); ++i) constrained += api().kernel_at(i)->n_constraints > 0;
|
||||
CHECK_EQ(constrained, 3);
|
||||
CHECK_EQ(constrained, 5);
|
||||
}
|
||||
|
||||
/* ================================================================== the numerics
|
||||
@@ -1636,6 +1902,34 @@ TEST(op_ple_gate) {
|
||||
* accumulate to 100a + 10b + c and any misread tap changes a digit. silu is applied after, so
|
||||
* the expectation is silu of that number.
|
||||
*/
|
||||
/* Mamba-2's conv1d: ple_conv_bias at dilation one and with no residual. The bias
|
||||
* must sit inside the activation, so silu(b + conv) and not b + silu(conv). */
|
||||
TEST(op_ple_conv_bias_is_inside_the_silu) {
|
||||
auto silu = [](float v) { return v / (1.0f + std::exp(-v)); };
|
||||
T x(RAD_F32, {3, 2}); x.f({ 1, 10, 2, 20, 3, 30 });
|
||||
T w(RAD_F32, {2, 2}); w.f({ 1, 1, 0.5f, -1 });
|
||||
T cs(RAD_F32, {1, 2, 1}); cs.f({ 4, 8 });
|
||||
T cu(RAD_I32, {2}); cu.n({ 0, 3 });
|
||||
T ci(RAD_I32, {1}); ci.n({ 0 });
|
||||
T hi(RAD_I32, {1}); hi.n({ 1 });
|
||||
T y(RAD_F32, {3, 2});
|
||||
T b(RAD_F32, {2}); b.f({ -2, 3 });
|
||||
A a; a.t(x).t(w).t(cs).t(cu).tnull().t(ci).t(hi).tnull().t(b).t(y)
|
||||
.i("M", 3).i("n", 2).i("width", 2).i("dilation", 1).s("dtype", "f32");
|
||||
CHECK_OK(run("ple_conv_bias", a));
|
||||
/* channel 0: taps (prev, cur) * (1, 1) - 2; channel 1: (prev, cur) * (0.5, -1) + 3 */
|
||||
CHECK_NEAR(y.at(0), silu(4 + 1 - 2.0f), 1e-5);
|
||||
CHECK_NEAR(y.at(1), silu(0.5f * 8 - 10 + 3.0f), 1e-5);
|
||||
CHECK_NEAR(y.at(2), silu(1 + 2 - 2.0f), 1e-5);
|
||||
CHECK_NEAR(y.at(5), silu(0.5f * 20 - 30 + 3.0f), 1e-5);
|
||||
/* the window keeps the inputs, not the biased sums */
|
||||
CHECK_EQ(cs.at(0), 3.0f);
|
||||
CHECK_EQ(cs.at(1), 30.0f);
|
||||
T bad(RAD_F32, {3});
|
||||
a.ts[8] = bad.t;
|
||||
CHECK_EQ(run("ple_conv_bias", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(op_ple_conv) {
|
||||
auto silu = [](float v) { return v / (1.0f + std::exp(-v)); };
|
||||
const int n = 1, wid = 3, dil = 2, hist = (wid - 1) * dil; /* 4 */
|
||||
@@ -1758,6 +2052,54 @@ TEST(op_grid_embed_aa_is_torchs_antialiased_bilinear) {
|
||||
}
|
||||
}
|
||||
|
||||
/* RADIO's cropped position embedding, against torch's F.interpolate(bilinear, align_corners=False)
|
||||
* onto a d x d square cropped to the grid (values from torch 2.11). A 3 x 5 grid upsamples the
|
||||
* 4 x 4 table to 5 x 5 and keeps three rows; a 2 x 2 grid downsamples it, which antialias would
|
||||
* change, so the two cases tell this op from grid_embed_aa. */
|
||||
TEST(op_grid_embed_cpe_is_torchs_bilinear_on_a_square_cropped) {
|
||||
const int side = 4, n = 2;
|
||||
T tab(RAD_F32, {side * side, n});
|
||||
tab.f({ -5.0f, -1.75f, 2.0f, 5.25f, -2.0f, 1.25f, 5.0f, -2.75f, 1.0f, 4.25f, -3.0f, 0.25f,
|
||||
4.0f, -3.75f, 0.0f, 3.25f, -4.0f, -0.75f, 3.0f, -4.75f, -1.0f, 2.25f, -5.0f, -1.75f,
|
||||
2.0f, 5.25f, -2.0f, 1.25f, 5.0f, -2.75f, 1.0f, 4.25f });
|
||||
struct G { int h, w; std::vector<float> want; };
|
||||
const G cases[] = {
|
||||
{ 3, 5, { -5.0f, -1.75f, -0.1f, 3.15f, 0.0f, 3.25f, 0.1f, 0.05f, 5.0f, -2.75f, -0.8f,
|
||||
2.45f, -1.29f, 1.96f, 0.35f, -0.25f, 1.99f, -1.14f, 1.5f, 1.45f, -1.5f, 1.75f,
|
||||
-0.45f, -1.05f, 0.75f, -1.5f, 0.3f, -0.3f, -2.5f, 0.75f } },
|
||||
{ 2, 2, { -1.25f, 2.0f, 1.75f, -0.5f, -0.25f, 0.25f, 0.0f, 0.5f } },
|
||||
};
|
||||
for (const G& g : cases) {
|
||||
const int M = g.h * g.w;
|
||||
T x(RAD_F32, {M, n});
|
||||
std::vector<float> zero((size_t)(M * n), 0.0f);
|
||||
x.f(zero);
|
||||
T crd(RAD_I32, {4, M});
|
||||
std::vector<int64_t> c((size_t)(4 * M));
|
||||
for (int r = 0; r < M; ++r) {
|
||||
c[(size_t)r] = r / g.w;
|
||||
c[(size_t)(M + r)] = r % g.w;
|
||||
c[(size_t)(2 * M + r)] = g.h;
|
||||
c[(size_t)(3 * M + r)] = g.w;
|
||||
}
|
||||
crd.n(c);
|
||||
A a; a.t(x).t(tab).t(crd).i("M", M).i("n", n).i("side", side).s("dtype", "f32");
|
||||
CHECK_OK(run("grid_embed_cpe", a));
|
||||
for (int i = 0; i < M * n; ++i) CHECK_NEAR(x.at(i), g.want[(size_t)i], 2e-5);
|
||||
}
|
||||
/* The rows ahead of a segment's patches: row coordinate -1, the column naming the prefix row.
|
||||
* Two of them, then the 2 x 2 grid's (1, 0), which still takes the resampled table. */
|
||||
T pre(RAD_F32, {2, n}); pre.f({ 10.0f, 11.0f, 20.0f, 21.0f });
|
||||
T x(RAD_F32, {3, n}); x.f({ 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f });
|
||||
T crd(RAD_I32, {4, 3}); crd.n({ -1, -1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2 });
|
||||
A a; a.t(x).t(tab).t(crd).t(pre).i("M", 3).i("n", n).i("side", side).i("n_prefix", 2)
|
||||
.s("dtype", "f32");
|
||||
CHECK_OK(run("grid_embed_cpe", a));
|
||||
CHECK_NEAR(x.at(0), 20.5f, 1e-6); CHECK_NEAR(x.at(1), 21.5f, 1e-6); /* 0.5 + prefix row 1 */
|
||||
CHECK_NEAR(x.at(2), 10.0f, 1e-6); CHECK_NEAR(x.at(3), 11.0f, 1e-6); /* prefix row 0 */
|
||||
CHECK_NEAR(x.at(4), -0.25f, 2e-5); CHECK_NEAR(x.at(5), 0.25f, 2e-5); /* torch's (1, 0) */
|
||||
}
|
||||
|
||||
/* LFM2's short convolution: ple_conv's window at dilation one, with no activation. */
|
||||
TEST(op_causal_conv1d) {
|
||||
const int n = 1, wid = 3;
|
||||
@@ -3111,6 +3453,47 @@ TEST(op_attn_paged) {
|
||||
CHECK_NEAR(out2.at(5), 1.0f, 1e-6);
|
||||
}
|
||||
|
||||
TEST(op_attn_paged_sink) {
|
||||
/* op_attn_paged's cache and queries, non-causal, with a sink logit a head: token 0 now sees both
|
||||
* keys too, and each sink adds exp(sink) to the denominator only. Head 0, token 0, q = [1,0]:
|
||||
* scores 1/sqrt(2) and 0, so weights 1, exp(-1/sqrt(2)) and exp(sink0 - 1/sqrt(2)). */
|
||||
const float sc = 1.0f / 1.41421356f;
|
||||
T q(RAD_F32, {2, 2, 2});
|
||||
q.f({ 1, 0, 0, 1,
|
||||
0, 1, 1, 0 });
|
||||
T kv(RAD_F32, {1, 1, 2, 4});
|
||||
kv.f({ 1, 0, 1, 0,
|
||||
0, 1, 0, 1 });
|
||||
T bt(RAD_I32, {1, 1}); bt.n({0});
|
||||
T su(RAD_I32, {1}); su.n({2});
|
||||
T sk(RAD_F32, {2}); sk.f({ 0.5f, 3.0f }); /* head 1's sink lies above every score */
|
||||
T out(RAD_F32, {2, 2, 2});
|
||||
A a; a.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(sk).t(out)
|
||||
.i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2)
|
||||
.i("causal", 0).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32");
|
||||
CHECK_OK(run("attn_paged_sink", a));
|
||||
const float w = std::exp(-sc);
|
||||
const float d0 = 1.0f + w + std::exp(0.5f - sc); /* head 0, either token */
|
||||
CHECK_NEAR(out.at(0), 1.0f / d0, 1e-6); CHECK_NEAR(out.at(1), w / d0, 1e-6);
|
||||
CHECK_NEAR(out.at(4), w / d0, 1e-6); CHECK_NEAR(out.at(5), 1.0f / d0, 1e-6);
|
||||
const float d1 = 1.0f + w + std::exp(3.0f - sc); /* head 1 */
|
||||
CHECK_NEAR(out.at(2), w / d1, 1e-6); CHECK_NEAR(out.at(3), 1.0f / d1, 1e-6);
|
||||
CHECK_NEAR(out.at(6), 1.0f / d1, 1e-6); CHECK_NEAR(out.at(7), w / d1, 1e-6);
|
||||
|
||||
/* A sink far below every score changes nothing: attn_paged's values, causal. */
|
||||
T sk2(RAD_F32, {2}); sk2.f({ -1e30f, -1e30f });
|
||||
T o1(RAD_F32, {2, 2, 2}), o2(RAD_F32, {2, 2, 2});
|
||||
A b; b.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(o1)
|
||||
.i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2)
|
||||
.i("causal", 1).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32");
|
||||
CHECK_OK(run("attn_paged", b));
|
||||
A c; c.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(sk2).t(o2)
|
||||
.i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2)
|
||||
.i("causal", 1).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32");
|
||||
CHECK_OK(run("attn_paged_sink", c));
|
||||
for (int i = 0; i < 8; ++i) CHECK_NEAR(o2.at(i), o1.at(i), 1e-7);
|
||||
}
|
||||
|
||||
TEST(op_attn_paged_ragged) {
|
||||
/* A ragged batch, as a serving step really looks: sequence 0 prefills two tokens while
|
||||
* sequence 1 decodes one. total_q is 3 and n_seq is 2, so without cu_seqlens this batch cannot
|
||||
@@ -3153,6 +3536,43 @@ TEST(op_attn_paged_ragged) {
|
||||
* right after a one-token prompt is (core/sched/advance_impl.h ADV_HIST ends the context at the
|
||||
* last committed position). Rows sit at seqused - q_len + j = -2, -1, 0, 1: the first two see no
|
||||
* key and are zero, not NaN, and the last two are as if the run were two rows. */
|
||||
TEST(op_attn_paged_anchor_window_is_exact_at_512_history_and_shared_across_rows) {
|
||||
constexpr int qlen = 7, ctx = 520, bs = 16, seqs = 2, window = 513;
|
||||
const int blocks = (ctx + bs - 1) / bs;
|
||||
T q(RAD_F32, {seqs * qlen, 1, 1});
|
||||
T kv(RAD_F32, {seqs * blocks, 1, bs, 2});
|
||||
for (int s = 0; s < seqs; ++s) {
|
||||
const int slot_base = s * blocks * bs;
|
||||
const float before = s == 0 ? 500.0f : 700.0f; /* anchor - 513: masked */
|
||||
const float edge = s == 0 ? 10.0f : 20.0f; /* anchor - 512: visible */
|
||||
const float future = s == 0 ? 1000.0f : 2000.0f;
|
||||
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + 0) * 2 + 1, before);
|
||||
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + 1) * 2 + 1, edge);
|
||||
st_dt(RAD_F32, kv.t.data, (int64_t)(slot_base + ctx - 1) * 2 + 1, future);
|
||||
}
|
||||
T bt(RAD_I32, {seqs, blocks});
|
||||
std::vector<int64_t> block_ids(seqs * blocks);
|
||||
for (int s = 0; s < seqs; ++s)
|
||||
for (int b = 0; b < blocks; ++b) block_ids[s * blocks + b] = s * blocks + b;
|
||||
bt.n(block_ids);
|
||||
T su(RAD_I32, {seqs}); su.n({ctx, ctx});
|
||||
T cu(RAD_I32, {seqs + 1}); cu.n({0, qlen, 2 * qlen});
|
||||
T out(RAD_F32, {seqs * qlen, 1, 1});
|
||||
for (int causal : {0, 1}) {
|
||||
A a; a.t(q).t(kv).t(bt).t(su).tnull().tnull().t(cu).t(out)
|
||||
.i("q_len", qlen).i("head_dim", 1).i("gqa", 1).i("block_size", bs)
|
||||
.i("causal", causal).i("window", window).s("q_dtype", "f32").s("kv_dtype", "f32");
|
||||
CHECK_OK(run("attn_paged_anchor_window", a));
|
||||
const float denom = causal ? 513.0f : 519.0f;
|
||||
const float expected0 = causal ? 10.0f / denom : 1010.0f / denom;
|
||||
const float expected1 = causal ? 20.0f / denom : 2020.0f / denom;
|
||||
for (int i = 0; i < qlen; ++i) {
|
||||
CHECK_NEAR(out.at(i), expected0, 1e-6);
|
||||
CHECK_NEAR(out.at(qlen + i), expected1, 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(op_attn_paged_rows_before_the_context) {
|
||||
const float sc = 1.0f / 1.41421356f;
|
||||
T q(RAD_F32, {4, 1, 2});
|
||||
@@ -3253,10 +3673,22 @@ TEST(op_act_mul) {
|
||||
CHECK_NEAR(y.at(1), gt(-2) * 4, 1e-5);
|
||||
CHECK_NEAR(y.at(2), gt(0.5f) * -1, 1e-5);
|
||||
CHECK_NEAR(y.at(3), 0.0f, 1e-6);
|
||||
A bad; bad.t(g).t(u).t(y).i("M", 2).i("n", 2).s("act", "relu").s("dtype", "f32");
|
||||
A bad; bad.t(g).t(u).t(y).i("M", 2).i("n", 2).s("act", "tanh").s("dtype", "f32");
|
||||
CHECK(run("act_mul", bad) < 0);
|
||||
}
|
||||
|
||||
/* act_mul's relu over one tensor in both operands: relu(x)^2, zero below. */
|
||||
TEST(op_act_mul_relu_of_one_tensor_squares_it) {
|
||||
T x(RAD_F32, {1, 4}); x.f({ 3, -2, 0.5f, 0 });
|
||||
T y(RAD_F32, {1, 4});
|
||||
A a; a.t(x).t(x).t(y).i("M", 1).i("n", 4).s("act", "relu").s("dtype", "f32");
|
||||
CHECK_OK(run("act_mul", a));
|
||||
CHECK_NEAR(y.at(0), 9.0f, 1e-6);
|
||||
CHECK_NEAR(y.at(1), 0.0f, 1e-6);
|
||||
CHECK_NEAR(y.at(2), 0.25f, 1e-6);
|
||||
CHECK_NEAR(y.at(3), 0.0f, 1e-6);
|
||||
}
|
||||
|
||||
/* seg_mean: one row per segment, an empty segment a zero row. */
|
||||
TEST(op_seg_mean) {
|
||||
T x(RAD_F32, {4, 2}); x.f({ 1, 2, 3, 4, 5, 6, 7, 9 });
|
||||
@@ -3508,6 +3940,30 @@ TEST(op_pool_cols) {
|
||||
CHECK(run("pool_cols", bad) < 0);
|
||||
}
|
||||
|
||||
/* point_fourier: [x | sin(x 2^j) | cos(x 2^j)], sines and cosines each value-major then octave;
|
||||
* with `pi`, the octaves times pi. */
|
||||
TEST(op_point_fourier) {
|
||||
T x(RAD_F32, {2, 2}); x.f({ 0.5f, -0.25f, 1.0f, 0.0f });
|
||||
T y(RAD_F32, {2, 10});
|
||||
A a; a.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("point_fourier", a));
|
||||
const float v[2][2] = { { 0.5f, -0.25f }, { 1.0f, 0.0f } };
|
||||
for (int r = 0; r < 2; ++r)
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
CHECK_EQ(y.at(r * 10 + i), v[r][i]);
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
const float t = v[r][i] * (float)(1 << j);
|
||||
CHECK_NEAR(y.at(r * 10 + 2 + i * 2 + j), std::sin(t), 1e-6);
|
||||
CHECK_NEAR(y.at(r * 10 + 6 + i * 2 + j), std::cos(t), 1e-6);
|
||||
}
|
||||
}
|
||||
A b; b.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 2).i("pi", 1).s("dtype", "f32");
|
||||
CHECK_OK(run("point_fourier", b));
|
||||
CHECK_NEAR(y.at(3), std::sin(0.5f * 2.0f * 3.14159265f), 1e-6);
|
||||
A bad; bad.t(x).t(y).i("M", 2).i("n", 2).i("freqs", 3).s("dtype", "f32");
|
||||
CHECK(run("point_fourier", bad) < 0);
|
||||
}
|
||||
|
||||
/* rmsnorm with no gain: a unit gain. */
|
||||
TEST(op_rmsnorm_no_gain) {
|
||||
T x(RAD_F32, {1, 2}); x.f({ 3, 4 });
|
||||
@@ -9293,6 +9749,225 @@ TEST(dflash_select_walks_from_its_own_previous_pick) {
|
||||
CHECK_EQ(tok.iat(1), 0LL);
|
||||
}
|
||||
|
||||
/* The DSpark reference scores all vocabulary entries after applying the Markov bias. Both
|
||||
* sequences choose tokens outside their base-logit top 16; step 1 conditions on the prior greedy
|
||||
* choice, and the step-0 tie across tile boundaries resolves to the lower token id. */
|
||||
TEST(dflash_markov_greedy_scans_full_vocab_and_keeps_sequences_independent) {
|
||||
constexpr int V = 130, R = 32, M = 2, steps = 2, tiles = 3;
|
||||
std::vector<float> logits_values(M * steps * V, 0.0f);
|
||||
for (int r = 0; r < M * steps; r += 2)
|
||||
for (int v = 0; v < 16; ++v) logits_values[r * V + v] = 100 - v;
|
||||
T logits(RAD_BF16, {M * steps, V}); logits.f(logits_values);
|
||||
T anchor(RAD_I32, {M, 2}); anchor.n({1, -1, 2, -1});
|
||||
std::vector<float> pred_values(V * R, 0.0f), succ_values(V * R, 0.0f);
|
||||
pred_values[1 * R + 0] = 1; /* sequence 0, step 0 predecessor */
|
||||
succ_values[127 * R + 0] = 200; /* outside the base top 16 */
|
||||
succ_values[129 * R + 0] = 200; /* equal biased score in a later tile */
|
||||
pred_values[127 * R + 1] = 1; /* sequence 0 step 1 depends on token 127 */
|
||||
succ_values[100 * R + 1] = 100;
|
||||
pred_values[2 * R + 2] = 1; /* sequence 1 has a separate anchor/codebook walk */
|
||||
succ_values[80 * R + 2] = 200;
|
||||
pred_values[80 * R + 3] = 1;
|
||||
succ_values[101 * R + 3] = 90;
|
||||
T pred(RAD_BF16, {V, R}); pred.f(pred_values);
|
||||
T succ(RAD_BF16, {V, R}); succ.f(succ_values);
|
||||
T tile_scores(RAD_F32, {M, tiles});
|
||||
T tile_tokens(RAD_I32, {M, tiles});
|
||||
T out(RAD_I32, {M, steps});
|
||||
A a; a.t(logits).t(anchor).t(pred).t(succ).t(tile_scores).t(tile_tokens).t(out)
|
||||
.i("M", M).i("steps", steps).i("rank", R).i("n_vocab", V)
|
||||
.i("anchor_stride", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("dflash_markov_greedy", a));
|
||||
CHECK_EQ(out.iat(0), 127LL);
|
||||
CHECK_EQ(out.iat(1), 100LL);
|
||||
CHECK_EQ(out.iat(2), 80LL);
|
||||
CHECK_EQ(out.iat(3), 101LL);
|
||||
CHECK_EQ(tile_tokens.iat(0), 0LL);
|
||||
CHECK_EQ(tile_tokens.iat(1), 100LL);
|
||||
CHECK_EQ(tile_tokens.iat(2), 128LL);
|
||||
CHECK_EQ(tile_scores.at(0), 0.0f);
|
||||
CHECK_EQ(tile_scores.at(1), 100.0f);
|
||||
CHECK_EQ(tile_scores.at(2), 0.0f);
|
||||
}
|
||||
|
||||
TEST(dflash_markov_f32_preserves_a_near_tie_and_refuses_bf16) {
|
||||
T logits(RAD_F32, {1, 2}); logits.f({1.001f, 1.002f});
|
||||
T anchor(RAD_I32, {1}); anchor.n({0});
|
||||
T pred(RAD_BF16, {2, 32}), succ(RAD_BF16, {2, 32});
|
||||
T score(RAD_F32, {1, 1}), token(RAD_I32, {1, 1}), out(RAD_I32, {1, 1});
|
||||
A a; a.t(logits).t(anchor).t(pred).t(succ).t(score).t(token).t(out)
|
||||
.i("M", 1).i("steps", 1).i("rank", 32).i("n_vocab", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("dflash_markov_greedy_f32", a));
|
||||
CHECK_EQ(out.iat(0), 1);
|
||||
T bad_anchor(RAD_F32, {1}); bad_anchor.f({0});
|
||||
a.ts[1] = bad_anchor.t;
|
||||
CHECK_EQ(run("dflash_markov_greedy_f32", a), RAD_E_SHAPE);
|
||||
a.ts[1] = anchor.t;
|
||||
CHECK(run("dflash_markov_greedy", a) != RAD_OK);
|
||||
T bf_logits(RAD_BF16, {1, 2}); bf_logits.f({1.001f, 1.002f});
|
||||
a.ts[0] = bf_logits.t;
|
||||
CHECK(run("dflash_markov_greedy_f32", a) != RAD_OK);
|
||||
CHECK_OK(run("dflash_markov_greedy", a));
|
||||
CHECK_EQ(out.iat(0), 0);
|
||||
}
|
||||
|
||||
/* Independent pitches in the two scratch arrays are part of the tensor contract. Guard cells
|
||||
* distinguish correct row addressing from treating both outputs as tightly packed. */
|
||||
TEST(dflash_markov_greedy_padded_scratch_rows) {
|
||||
constexpr int V=130, R=32, M=2, tiles=3;
|
||||
T logits(RAD_BF16, {M, V}), anchor(RAD_I32, {M}); anchor.n({1, 2});
|
||||
T pred(RAD_BF16, {V, R}), succ(RAD_BF16, {V, R});
|
||||
st_dt(RAD_BF16, pred.t.data, R, 1); st_dt(RAD_BF16, pred.t.data, 2*R+1, 1);
|
||||
st_dt(RAD_BF16, succ.t.data, 129*R, 4); st_dt(RAD_BF16, succ.t.data, 80*R+1, 8);
|
||||
T scores(RAD_F32, {M, 5}); scores.f(std::vector<float>(10, -777));
|
||||
T tokens(RAD_I32, {M, 7}); tokens.n(std::vector<int64_t>(14, -777));
|
||||
scores.t.shape[1]=tiles; tokens.t.shape[1]=tiles;
|
||||
T out(RAD_I32, {M, 1});
|
||||
A a; a.t(logits).t(anchor).t(pred).t(succ).t(scores).t(tokens).t(out)
|
||||
.i("M", M).i("steps", 1).i("rank", R).i("n_vocab", V).s("dtype", "bf16");
|
||||
CHECK_OK(run("dflash_markov_greedy", a));
|
||||
CHECK_EQ(out.iat(0), 129); CHECK_EQ(out.iat(1), 80);
|
||||
CHECK_EQ(tokens.iat(2), 129); CHECK_EQ(tokens.iat(7+1), 80);
|
||||
CHECK_EQ(scores.at(2), 4); CHECK_EQ(scores.at(5+1), 8);
|
||||
for (int i : {3,4,8,9}) CHECK_EQ(scores.at(i), -777);
|
||||
for (int i : {3,4,5,6,10,11,12,13}) CHECK_EQ(tokens.iat(i), -777);
|
||||
}
|
||||
|
||||
/* A one-row, one-layer DSpark oracle assembled from libref's ordinary ops. The literals check the
|
||||
* architecture-specific chain rather than only each primitive: each tap has its own RMS gain,
|
||||
* the normalized taps feed fc/h_norm then context K/V projections, context and draft K/V land in
|
||||
* the paged cache, and a gated attention residual plus the exact-GELU MLP gives the layer output. */
|
||||
TEST(dspark_taps_context_kv_and_layer_output_match_hand_oracle) {
|
||||
T tap0_src(RAD_F32, {1, 2}); tap0_src.f({1, 1});
|
||||
T tap0_gain(RAD_BF16, {2}); tap0_gain.f({1, 2});
|
||||
T tap0(RAD_BF16, {1, 2});
|
||||
A tap0a; tap0a.t(tap0_src).t(tap0_gain).t(tap0)
|
||||
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
|
||||
CHECK_OK(run("rmsnorm", tap0a));
|
||||
CHECK_EQ(tap0.at(0), 1.0f); CHECK_EQ(tap0.at(1), 2.0f);
|
||||
|
||||
T tap1_src(RAD_F32, {1, 2}); tap1_src.f({2, 2});
|
||||
T tap1_gain(RAD_BF16, {2}); tap1_gain.f({2, 1});
|
||||
T tap1(RAD_BF16, {1, 2});
|
||||
A tap1a; tap1a.t(tap1_src).t(tap1_gain).t(tap1)
|
||||
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
|
||||
CHECK_OK(run("rmsnorm", tap1a));
|
||||
CHECK_EQ(tap1.at(0), 2.0f); CHECK_EQ(tap1.at(1), 1.0f);
|
||||
|
||||
T taps(RAD_BF16, {1, 4}); taps.f({tap0.at(0), tap0.at(1), tap1.at(0), tap1.at(1)});
|
||||
T fc_w(RAD_BF16, {2, 4}); fc_w.f({1, 0, 0, 0, 0, 0, 0, 1});
|
||||
T context(RAD_BF16, {1, 2});
|
||||
A fca; fca.t(taps).t(fc_w).t(context).i("M", 1).i("N", 2).i("K", 4).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", fca));
|
||||
CHECK_EQ(context.at(0), 1.0f); CHECK_EQ(context.at(1), 1.0f);
|
||||
|
||||
T context_gain(RAD_BF16, {2}); context_gain.f({1, 1});
|
||||
T context_norm(RAD_BF16, {1, 2});
|
||||
A cna; cna.t(context).t(context_gain).t(context_norm)
|
||||
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
|
||||
CHECK_OK(run("rmsnorm", cna));
|
||||
CHECK_EQ(context_norm.at(0), 1.0f); CHECK_EQ(context_norm.at(1), 1.0f);
|
||||
|
||||
T wq(RAD_BF16, {2, 2}); wq.f({0, 0, 0, 0});
|
||||
T wk(RAD_BF16, {2, 2}); wk.f({0, 0, 0, 0});
|
||||
T wv(RAD_BF16, {2, 2}); wv.f({0, 0, 1, 1});
|
||||
T q_proj(RAD_BF16, {1, 2}), k_ctx(RAD_BF16, {1, 2}), v_ctx(RAD_BF16, {1, 2});
|
||||
A qa; qa.t(context_norm).t(wq).t(q_proj).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
A ka; ka.t(context_norm).t(wk).t(k_ctx).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
A va; va.t(context_norm).t(wv).t(v_ctx).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", qa)); CHECK_OK(run("gemm_nt", ka)); CHECK_OK(run("gemm_nt", va));
|
||||
CHECK_EQ(k_ctx.at(0), 0.0f); CHECK_EQ(k_ctx.at(1), 0.0f);
|
||||
CHECK_EQ(v_ctx.at(0), 0.0f); CHECK_EQ(v_ctx.at(1), 2.0f);
|
||||
|
||||
/* The query projection is from the draft row, but has the same simple normalized input. */
|
||||
T query_src(RAD_F32, {1, 2}); query_src.f({1, 1});
|
||||
T query_norm(RAD_BF16, {1, 2});
|
||||
A qna; qna.t(query_src).t(context_gain).t(query_norm)
|
||||
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
|
||||
CHECK_OK(run("rmsnorm", qna));
|
||||
T k_query(RAD_BF16, {1, 2}), v_query(RAD_BF16, {1, 2});
|
||||
A kqa; kqa.t(query_norm).t(wk).t(k_query).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
A vqa; vqa.t(query_norm).t(wv).t(v_query).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", kqa)); CHECK_OK(run("gemm_nt", vqa));
|
||||
|
||||
T keys(RAD_BF16, {2, 1, 2}); keys.f({k_ctx.at(0), k_ctx.at(1), k_query.at(0), k_query.at(1)});
|
||||
T values(RAD_BF16, {2, 1, 2}); values.f({v_ctx.at(0), v_ctx.at(1), v_query.at(0), v_query.at(1)});
|
||||
T slots(RAD_I32, {2}); slots.n({0, 1});
|
||||
T cache(RAD_BF16, {1, 1, 2, 4});
|
||||
A store; store.t(keys).t(values).t(slots).t(cache)
|
||||
.i("M", 2).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2).s("kv_dtype", "bf16");
|
||||
CHECK_OK(run("kv_store", store));
|
||||
for (int slot = 0; slot < 2; ++slot) {
|
||||
CHECK_EQ(cache.at(slot * 4 + 0), 0.0f); CHECK_EQ(cache.at(slot * 4 + 1), 0.0f);
|
||||
CHECK_EQ(cache.at(slot * 4 + 2), 0.0f); CHECK_EQ(cache.at(slot * 4 + 3), 2.0f);
|
||||
}
|
||||
|
||||
T q(RAD_BF16, {1, 1, 2}); q.f({q_proj.at(0), q_proj.at(1)});
|
||||
T bt(RAD_I32, {1, 1}); bt.n({0});
|
||||
T used(RAD_I32, {1}); used.n({2});
|
||||
T attended(RAD_BF16, {1, 1, 2});
|
||||
A attn; attn.t(q).t(cache).t(bt).t(used).tnull().tnull().tnull().t(attended)
|
||||
.i("q_len", 1).i("head_dim", 2).i("gqa", 1).i("block_size", 2)
|
||||
.i("causal", 0).i("window", 513).i("n_head", 1)
|
||||
.s("q_dtype", "bf16").s("kv_dtype", "bf16");
|
||||
CHECK_OK(run("attn_paged_anchor_window", attn));
|
||||
CHECK_EQ(attended.at(0), 0.0f); CHECK_EQ(attended.at(1), 2.0f);
|
||||
|
||||
T gate_w(RAD_BF16, {1, 2}); gate_w.f({0, 0});
|
||||
T gate_logit(RAD_BF16, {1, 1}), gate(RAD_BF16, {1, 1});
|
||||
A ga; ga.t(query_norm).t(gate_w).t(gate_logit)
|
||||
.i("M", 1).i("N", 1).i("K", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", ga));
|
||||
A sig; sig.t(gate_logit).t(gate).i("M", 1).i("n", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("sigmoid", sig));
|
||||
CHECK_EQ(gate.at(0), 0.5f);
|
||||
T gated(RAD_BF16, {1, 2});
|
||||
A scale; scale.t(attended).t(gate).tnull().t(gated)
|
||||
.i("M", 1).i("n", 2).s("act", "none").s("dtype", "bf16");
|
||||
CHECK_OK(run("scale_rows", scale));
|
||||
CHECK_EQ(gated.at(0), 0.0f); CHECK_EQ(gated.at(1), 1.0f);
|
||||
|
||||
T wo(RAD_BF16, {2, 2}); wo.f({1, 0, 0, 1});
|
||||
T delta(RAD_BF16, {1, 2});
|
||||
A oa; oa.t(gated).t(wo).t(delta).i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", oa));
|
||||
CHECK_EQ(delta.at(0), 0.0f); CHECK_EQ(delta.at(1), 1.0f);
|
||||
T residual(RAD_F32, {1, 2}); residual.f({1, 1});
|
||||
T after_attn(RAD_F32, {1, 2});
|
||||
A adda; adda.t(residual).t(delta).t(after_attn).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("add", adda));
|
||||
CHECK_EQ(after_attn.at(0), 1.0f); CHECK_EQ(after_attn.at(1), 2.0f);
|
||||
|
||||
T ff_norm(RAD_BF16, {1, 2});
|
||||
A fna; fna.t(after_attn).t(context_gain).t(ff_norm)
|
||||
.i("M", 1).i("n", 2).d("eps", 0).s("dtype", "bf16");
|
||||
CHECK_OK(run("rmsnorm", fna));
|
||||
T ff_w(RAD_BF16, {2, 2}); ff_w.f({1, 0, 1, 0});
|
||||
T gate_up(RAD_BF16, {1, 2});
|
||||
A fua; fua.t(ff_norm).t(ff_w).t(gate_up)
|
||||
.i("M", 1).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", fua));
|
||||
T ff(RAD_BF16, {1, 1});
|
||||
A act; act.t(gate_up).t(gate_up).t(ff)
|
||||
.i("M", 1).i("n", 1).s("act", "gelu").s("dtype", "bf16");
|
||||
CHECK_OK(run("act_mul", act));
|
||||
T down_w(RAD_BF16, {2, 1}); down_w.f({1, 0});
|
||||
T down(RAD_BF16, {1, 2});
|
||||
A da; da.t(ff).t(down_w).t(down).i("M", 1).i("N", 2).i("K", 1).s("dtype", "bf16");
|
||||
CHECK_OK(run("gemm_nt", da));
|
||||
const float normalized = bf16_to_f32((uint16_t)f32_to_bf16(1.0f / std::sqrt(2.5f)));
|
||||
const float gelu = 0.5f * normalized * (1.0f + std::erf(normalized / std::sqrt(2.0f)));
|
||||
const float rounded_gelu = bf16_to_f32((uint16_t)f32_to_bf16(gelu));
|
||||
const float expected_ff = bf16_to_f32((uint16_t)f32_to_bf16(rounded_gelu * normalized));
|
||||
CHECK_NEAR(ff.at(0), expected_ff, 1e-6);
|
||||
CHECK_EQ(down.at(0), expected_ff); CHECK_EQ(down.at(1), 0.0f);
|
||||
T layer_out(RAD_F32, {1, 2});
|
||||
A outa; outa.t(after_attn).t(down).t(layer_out).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("add", outa));
|
||||
CHECK_NEAR(layer_out.at(0), 1.0f + expected_ff, 1e-6);
|
||||
CHECK_EQ(layer_out.at(1), 2.0f);
|
||||
}
|
||||
|
||||
TEST(gemm_nt_q_bias_adds_a_bias_per_column) {
|
||||
T a_(RAD_I8, {1, 2}); a_.n({1, 2});
|
||||
T as(RAD_F32, {1}); as.f({0.5f});
|
||||
@@ -9645,6 +10320,14 @@ std::vector<Geo> geometries() {
|
||||
G("mtp_enter", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")),
|
||||
G("grid_embed", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
|
||||
G("grid_embed_aa", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
|
||||
G("grid_embed_cpe", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
|
||||
G("lili_cand", "M", 3, a.i("M", R).i("k", 4).i("world", 1).i("steps", 3).i("n", 8)
|
||||
.s("dtype", "f32")),
|
||||
G("lili_attn", "M", 8, a.i("M", R).i("steps", 2).i("k", 2).i("n_head", 2).i("head_dim", 4)
|
||||
.s("dtype", "f32")),
|
||||
G("lili_factor", "M", 8, a.i("M", R).i("L", 4).i("n", 8).s("dtype", "f32")),
|
||||
G("lili_walk", "M", 2, a.i("M", R).i("steps", 3).i("k", 2).i("n", 8).s("dtype", "f32")
|
||||
.d("eps", 1e-4).d("scale", 8.0)),
|
||||
G("layernorm", "M", 3, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "f32")),
|
||||
G("add", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("mul", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
@@ -9655,6 +10338,7 @@ std::vector<Geo> geometries() {
|
||||
G("seg_mean_bf16_sum", "M", 6, a.i("M", R).i("n", 8).s("dtype", "bf16").i("n_seq", 2)),
|
||||
G("pool_rows", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")),
|
||||
G("pool_cols", "M", 6, a.i("M", R).i("n", 8).i("k", 2).s("dtype", "f32")),
|
||||
G("point_fourier", "M", 3, a.i("M", R).i("n", 3).i("freqs", 2).s("dtype", "f32")),
|
||||
G("relu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("clamp", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("conv2d", "M", 8, a.i("M", R).i("width", 4).i("cin", 2).i("cout", 3).i("kh", 3).i("kw", 3)
|
||||
@@ -9679,6 +10363,8 @@ std::vector<Geo> geometries() {
|
||||
G("scatter_rows", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
|
||||
G("ple_gate", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")),
|
||||
G("ple_conv", "M", 6, a.i("M", R).i("n", 8).i("width", 3).i("dilation", 2).s("dtype", "f32")),
|
||||
G("ple_conv_bias", "M", 6, a.i("M", R).i("n", 8).i("width", 4).i("dilation", 1)
|
||||
.s("dtype", "f32")),
|
||||
G("causal_conv1d", "M", 6, a.i("M", R).i("n", 8).i("width", 4).s("dtype", "f32")),
|
||||
G("ngram_ids", "M", 4, a.i("M", R).i("heads", 2).i("ngram", 3).i("eos", 1)),
|
||||
G("cast", "M", 3, a.i("M", R).i("n", 8).s("from", "f32").s("to", "bf16")),
|
||||
@@ -9698,6 +10384,10 @@ std::vector<Geo> geometries() {
|
||||
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")),
|
||||
G("dequant_w4", "N", 16, a.i("N", R).i("K", 128).i("group", 128).i("twos", 0)
|
||||
.s("dtype", "w4a8")),
|
||||
G("rmsnorm_quant_fp8", "M", 3, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16)
|
||||
.s("dtype", "bf16")),
|
||||
G("gated_quant_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "bf16")
|
||||
@@ -9708,6 +10398,12 @@ std::vector<Geo> geometries() {
|
||||
.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)
|
||||
.i("n_vocab", 130).i("anchor_stride", 1)
|
||||
.s("dtype", "bf16")),
|
||||
G("dflash_markov_greedy_f32", "M", 2, a.i("M", R).i("steps", 3).i("rank", 32)
|
||||
.i("n_vocab", 130).i("anchor_stride", 1)
|
||||
.s("dtype", "bf16")),
|
||||
G("dflash_tree", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8)
|
||||
.i("n_vocab", 30).i("nodes", 3).s("dtype", "bf16")),
|
||||
G("gemm_nt", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")),
|
||||
@@ -9722,10 +10418,17 @@ std::vector<Geo> geometries() {
|
||||
G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4)
|
||||
.i("causal", 1).i("window", 0).s("q_dtype", "f32")
|
||||
.s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
|
||||
G("attn_paged_anchor_window", "q_len", 3,
|
||||
a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4).i("causal", 1)
|
||||
.i("window", 4).s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
|
||||
G("attn_paged_tree", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2)
|
||||
.i("block_size", 4).i("causal", 1).i("window", 0)
|
||||
.s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4)
|
||||
.i("ctx", 9)),
|
||||
G("attn_paged_sink", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2)
|
||||
.i("block_size", 4).i("causal", 0).i("window", 0)
|
||||
.s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4)
|
||||
.i("ctx", 9)),
|
||||
G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1)
|
||||
.s("dtype", "f32").i("n_head", 4)),
|
||||
/* One-row segments, so M is also the segment count (n_seq, the description's hint for
|
||||
@@ -9772,6 +10475,14 @@ std::vector<Geo> geometries() {
|
||||
.s("a_order", "token").s("dtype", "f32")),
|
||||
G("moe_gemm_q", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 4).i("top_k", 2)
|
||||
.i("group", 128).s("a_order", "token").s("dtype", "fp8a8")),
|
||||
G("moe_gemm_q", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 4).i("top_k", 2)
|
||||
.i("group", 128).s("a_order", "token").s("dtype", "w4a8")),
|
||||
G("moe_gemm_q", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 4).i("top_k", 2)
|
||||
.i("group", 128).s("a_order", "sorted").s("dtype", "w4a8")),
|
||||
G("moe_gemm_q", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 4).i("top_k", 2)
|
||||
.i("group", 128).s("a_order", "token").s("dtype", "w4a4")),
|
||||
G("moe_gemm_q", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 4).i("top_k", 2)
|
||||
.i("group", 128).s("a_order", "sorted").s("dtype", "w4a4")),
|
||||
G("moe_gemm_q_mod4", "M", 3, a.i("M", R).i("N", 16).i("K", 128).i("n_expert", 5)
|
||||
.i("top_k", 2).i("group", 128).s("a_order", "sorted")
|
||||
.s("dtype", "fp8a8")),
|
||||
@@ -9864,16 +10575,25 @@ std::vector<Geo> geometries() {
|
||||
G("kda_update", "M", 3, a.i("M", R).i("heads", 2).i("head_k", 8).i("head_v", 8)
|
||||
.d("lower_bound", -5.0).d("scale", 0.35).d("l2_eps", 1e-6)
|
||||
.s("mode", "prefill").s("dtype", "f32")),
|
||||
G("ssd_update", "M", 3, a.i("M", R).i("heads", 4).i("head_dim", 4).i("d_state", 8)
|
||||
.i("groups", 2).s("mode", "prefill").s("dtype", "f32")),
|
||||
G("mla_attn", "M", 3, a.i("M", R).i("latent_dim", 8).i("heads", 2).i("blocks", 2)
|
||||
.i("block_size", 4).d("scale", 0.125).s("dtype", "f32")),
|
||||
G("mla_project", "M", 3, a.i("M", R).i("heads", 2).i("head_dim", 4).i("latent_dim", 6)
|
||||
.s("mode", "absorb").s("dtype", "bf16")),
|
||||
G("mla_attn_paged", "M", 3, a.i("M", R).i("heads", 2).i("latent_dim", 8).i("rope_dim", 4)
|
||||
.i("block_size", 4).d("scale", 0.25).i("ctx", 6)
|
||||
.s("dtype", "f32")),
|
||||
G("dsa_score", "M", 4, a.i("M", R).i("n", 8).i("heads", 2).i("blocks", 3).i("seqs", 2)
|
||||
.s("dtype", "fp8_e4m3")),
|
||||
G("dsa_pool", "M", 3, a.i("M", R).i("n", 8).i("ratio", 4).s("dtype", "bf16")),
|
||||
G("dsa_query", "M", 3, a.i("M", R).i("n", 8).s("dtype", "bf16")),
|
||||
G("gemm_nt_f32", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "bf16")),
|
||||
G("swiglu_clamped", "M", 3, a.i("M", R).i("n", 8).d("limit", 0.5).s("dtype", "f32")),
|
||||
G("swiglu_step", "M", 3, a.i("M", R).i("n", 8).d("limit", 0.5).s("dtype", "f32")),
|
||||
G("router_sigmoid_group_topk", "M", 3, a.i("M", R).i("n_expert", 8).i("top_k", 2)
|
||||
.i("n_group", 4).i("topk_group", 2).i("norm", 1)
|
||||
.d("route_scale", 2.5).s("dtype", "f32")),
|
||||
G("router_sigmoid_topk", "M", 3, a.i("M", R).i("n_expert", 6).i("top_k", 2).i("norm", 1)
|
||||
.d("route_scale", 2.5).s("dtype", "f32")),
|
||||
G("conv1d", "M", 8, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("dil", 1)
|
||||
@@ -9989,7 +10709,9 @@ 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") ||
|
||||
!std::strcmp(op, "pixtral_merge");
|
||||
!std::strcmp(op, "pixtral_merge") ||
|
||||
/* sample_logprobs rows (sorted pairs, positive sums): avx_check_hand.cpp builds them */
|
||||
!std::strcmp(op, "lili_cand");
|
||||
}
|
||||
|
||||
uint32_t lcg(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; }
|
||||
|
||||
+183
-3
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
#include "host_kargs_main.h"
|
||||
#include "rad_prefill_split.h"
|
||||
|
||||
#include "device/device.h"
|
||||
#include "runtime/arena.h"
|
||||
@@ -49,6 +50,7 @@ struct Rec {
|
||||
RadTensor t[8]{};
|
||||
long long M = -1;
|
||||
int rank = 0, world = 0;
|
||||
int32_t kv_used_max_h = -1;
|
||||
void* scratch = nullptr;
|
||||
int64_t scratch_bytes = 0;
|
||||
void* instance = nullptr;
|
||||
@@ -66,6 +68,7 @@ static int record(const char* name, const RadArgs* a, RadStream s) {
|
||||
rad_args_geti(a, "M", &r.M);
|
||||
r.rank = a->rank;
|
||||
r.world = a->world_size;
|
||||
r.kv_used_max_h = a->kv_used_max_h;
|
||||
r.scratch = a->scratch;
|
||||
r.scratch_bytes = a->scratch_bytes;
|
||||
r.instance = a->instance;
|
||||
@@ -234,12 +237,14 @@ struct Fixture {
|
||||
return (rad_op)(P.ops.size() - 1);
|
||||
}
|
||||
|
||||
int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false) {
|
||||
int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false,
|
||||
uint64_t (*pass_key)(RadCtx*, const RadBatch*, const int32_t*) = nullptr) {
|
||||
CtxDesc d;
|
||||
d.program = &P;
|
||||
d.rank = 1;
|
||||
d.world_size = 2;
|
||||
d.arch_step = arch_step_trampoline;
|
||||
d.arch_pass_key = pass_key;
|
||||
d.residency = res;
|
||||
d.profile_ops = profile;
|
||||
d.kv = kv;
|
||||
@@ -741,6 +746,42 @@ TEST(route_report_is_asynchronous_and_drains_oldest_first) {
|
||||
CHECK_EQ(f.ctx.route_report(99, &r), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* The file stager reads a layer's counts through the address the layer's last report named, at
|
||||
* the layer's next trigger. That holds for a buffer in the arena's fixed region or outside the
|
||||
* arena. A transient buffer is at another offset at another arena level, and a later transient
|
||||
* may share its bytes since no declared op reads the counts, so the source declines it and the
|
||||
* stager reads that layer whole. */
|
||||
TEST(the_counts_source_declines_a_transient_buffer) {
|
||||
Fixture f;
|
||||
f.P.arena_fixed_bytes = 4096;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
CHECK_OK(f.start());
|
||||
char* const base = (char*)f.ctx.arena_base();
|
||||
REQUIRE(base != nullptr);
|
||||
int64_t n = -1;
|
||||
CHECK(f.ctx.route_counts_device(0, &n) == nullptr); /* nothing reported yet */
|
||||
CHECK_EQ(n, (int64_t)0);
|
||||
|
||||
RadRouting r{};
|
||||
r.n_expert = 4;
|
||||
r.top_k = 2;
|
||||
r.expert_count = (const int32_t*)(base + 256); /* the fixed region */
|
||||
CHECK_OK(f.step(1, 0, [&](Ctx& c) { CHECK_OK(c.route_report(0, &r)); }));
|
||||
CHECK(f.ctx.route_counts_device(0, &n) == r.expert_count);
|
||||
CHECK_EQ(n, (int64_t)4);
|
||||
|
||||
r.expert_count = (const int32_t*)(base + 4096 + 512); /* a transient */
|
||||
CHECK_OK(f.step(1, 1, [&](Ctx& c) { CHECK_OK(c.route_report(1, &r)); }));
|
||||
CHECK(f.ctx.route_counts_device(1, &n) == nullptr);
|
||||
CHECK_EQ(n, (int64_t)0);
|
||||
|
||||
static const int32_t outside[4] = { 1, 2, 3, 4 }; /* not the arena's */
|
||||
r.expert_count = outside;
|
||||
CHECK_OK(f.step(1, 2, [&](Ctx& c) { CHECK_OK(c.route_report(1, &r)); }));
|
||||
CHECK(f.ctx.route_counts_device(1, &n) == outside);
|
||||
CHECK_OK(rad_stream_sync(f.ctx.stream()));
|
||||
}
|
||||
|
||||
/* A step that drafts reports the same layer once per pass, all into the step's one bank. The drain
|
||||
* runs before every pass, so it must not take that bank until the step is over; taken early, it
|
||||
* would cover only the passes so far and miss the rest. */
|
||||
@@ -2175,12 +2216,14 @@ int k_copy(const RadArgs* a, RadStream s) {
|
||||
}
|
||||
|
||||
/* A host row for every band of `op`, from a library that is not the reference. */
|
||||
void attach_host_row(Fixture& f, rad_op op, RadLaunchFn fn, const char* name) {
|
||||
void attach_host_row(Fixture& f, rad_op op, RadLaunchFn fn, const char* name,
|
||||
uint64_t capabilities = 0) {
|
||||
for (rad::Band& band : f.P.ops[op].bands) {
|
||||
f.infos.push_back(RadKernelInfo{});
|
||||
RadKernelInfo& ki = f.infos.back();
|
||||
ki.name = name; ki.op = "rope"; ki.family = "test"; ki.domain = RAD_DOMAIN_HOST;
|
||||
ki.launch = fn;
|
||||
ki.capabilities = capabilities;
|
||||
f.rows.push_back(rad::KernelRow{});
|
||||
rad::KernelRow& kr = f.rows.back();
|
||||
kr.info = &ki;
|
||||
@@ -2328,6 +2371,142 @@ TEST(a_program_with_a_calibration_tap_records_no_passes) {
|
||||
* and runtime state a pass's shape or arguments read, and must not change with the step number
|
||||
* alone. A field missing from the key replays stale arguments until the next audit. A pass that
|
||||
* cannot be recorded (encoder, generator, encoder rows) keys to 0. */
|
||||
static uint64_t test_prefill_geometry_key(RadCtx* c, const RadBatch* b, const int32_t* used) {
|
||||
if (!c || !b || !used) return 0;
|
||||
const int bq = 192, tile = 48, kv_heads = 4, threads = 768;
|
||||
const int wgps = rad_ctx_wgp_count(c);
|
||||
constexpr int declared_max_ctx = 65536;
|
||||
const int splits = rad_prefill_splits_for_live(bq, tile, (int)b->max_q_len,
|
||||
(int)b->n_tok, (int)b->n_seq, kv_heads,
|
||||
declared_max_ctx, used[0], wgps);
|
||||
return rad_prefill_grid_key((int)b->max_q_len, bq, splits, kv_heads, (int)b->n_seq, threads);
|
||||
}
|
||||
|
||||
TEST(legacy_prefill_keying_only_fails_closed_for_dynamic_split_rows) {
|
||||
{
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
rad_op op = loose_op(f);
|
||||
attach_host_row(f, op, k_host_read, "unaffected_prefill");
|
||||
CHECK_OK(f.start());
|
||||
|
||||
RadBatch b{};
|
||||
b.phase = RAD_PHASE_PREFILL;
|
||||
b.n_tok = 128; b.n_seq = 1; b.max_q_len = 128;
|
||||
CHECK(f.ctx.pass_key(&b) != 0); // Unaffected legacy prefill retains reuse.
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
rad_op op = loose_op(f);
|
||||
attach_host_row(f, op, k_host_read, "live_split_prefill",
|
||||
RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
RadBatch b{};
|
||||
b.phase = RAD_PHASE_PREFILL;
|
||||
b.n_tok = 128; b.n_seq = 1; b.max_q_len = 128;
|
||||
CHECK_EQ(f.ctx.pass_key(&b), (uint64_t)0);
|
||||
b.phase = RAD_PHASE_MIXED;
|
||||
CHECK_EQ(f.ctx.pass_key(&b), (uint64_t)0);
|
||||
/* Decode, verify and draft passes stay recordable: their launches read the keyed
|
||||
* context bound, not the live maximum (issue_passes_only_proven_kv_host_summaries). */
|
||||
b.phase = RAD_PHASE_DECODE; b.n_spec = 1;
|
||||
CHECK(f.ctx.pass_key(&b) != 0);
|
||||
b.n_spec = 0; b.draft_pass = -1;
|
||||
CHECK(f.ctx.pass_key(&b) != 0);
|
||||
b.draft_pass = 0;
|
||||
CHECK(f.ctx.pass_key(&b) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(issue_passes_only_proven_kv_host_summaries) {
|
||||
Fixture f;
|
||||
rad_op op = f.add_op("rope", "M", { 8192 }, { k_pre }, { "prefill" }, nullptr, {});
|
||||
CHECK_OK(f.start());
|
||||
|
||||
int32_t used_device[2] = { 896, 1152 }, used_host[2] = { 896, 1152 };
|
||||
int32_t positions_device[128]{}, positions_host[128]{};
|
||||
for (int i = 0; i < 128; ++i) positions_host[i] = 2048 + i;
|
||||
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.positions = positions_device;
|
||||
f.batch.positions_h = positions_host;
|
||||
|
||||
auto issue = [&](const int32_t* ptr, int rows, int batch_seqs, int phase, int n_spec) -> int32_t {
|
||||
f.batch.phase = phase;
|
||||
f.batch.n_tok = 128;
|
||||
f.batch.n_seq = batch_seqs;
|
||||
f.batch.n_spec = n_spec;
|
||||
g_rec.clear();
|
||||
g_body = [&](Ctx& c) {
|
||||
const RadOperand arg[1] = { RAD_P_T2(ptr, RAD_I32, rows, 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(used_device, 2, 2, RAD_PHASE_PREFILL, 0), 1152); // full group maximum
|
||||
CHECK_EQ(issue(used_device + 1, 1, 2, RAD_PHASE_PREFILL, 0), 1152); // exact sequence slice
|
||||
CHECK_EQ(issue(used_device, 1, 2, RAD_PHASE_PREFILL, 0), 896); // first sequence only
|
||||
CHECK_EQ(issue(used_device, 3, 2, RAD_PHASE_PREFILL, 0), -1); // out-of-range span
|
||||
CHECK_EQ(issue(used_device + 1, 1, 2, RAD_PHASE_MIXED, 0), 1152); // mixed prefill slice
|
||||
CHECK_EQ(issue(used_device, 2, 2, RAD_PHASE_PREFILL, 1), 1152); // exact speculative operand
|
||||
CHECK_EQ(issue(positions_device + 64, 1, 1, RAD_PHASE_PREFILL, 0), positions_host[64]);
|
||||
CHECK_EQ(issue(positions_device + 128, 1, 1, RAD_PHASE_PREFILL, 0), -1); // past step end
|
||||
CHECK_EQ(issue(positions_device + 64, 1, 1, RAD_PHASE_MIXED, 0), -1);
|
||||
CHECK_EQ(issue(positions_device + 64, 1, 1, RAD_PHASE_PREFILL, 1), -1);
|
||||
/* A plugin with no pass-key callback records its decode passes, so a launch there reads the
|
||||
* step's context bound plus its longest query, which the key holds, never the live maximum. */
|
||||
f.batch.max_ctx_len = 2048;
|
||||
f.batch.max_q_len = 2;
|
||||
CHECK_EQ(issue(used_device, 2, 2, RAD_PHASE_DECODE, 1), 2050);
|
||||
CHECK_EQ(issue(used_device + 1, 1, 2, RAD_PHASE_DECODE, 0), 2050);
|
||||
CHECK_EQ(issue(used_device, 3, 2, RAD_PHASE_DECODE, 1), -1); // still nothing to bound
|
||||
CHECK_EQ(issue(used_device, 2, 2, RAD_PHASE_PREFILL, 0), 1152); // prefill keeps the exact one
|
||||
}
|
||||
|
||||
TEST(the_prefill_geometry_key_reuses_equal_grids_and_separates_changed_grids) {
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
rad_op op = loose_op(f);
|
||||
attach_host_row(f, op, k_host_read, "host_read");
|
||||
CHECK_OK(f.start(nullptr, false, false, test_prefill_geometry_key));
|
||||
|
||||
RadKVGroupBatch kv{};
|
||||
kv.group = 3;
|
||||
RadBatch b{};
|
||||
b.phase = RAD_PHASE_PREFILL; b.n_tok = 128; b.n_seq = 1;
|
||||
b.max_q_len = 128; b.max_ctx_len = 4096; b.n_kv_groups = 1; b.kv = &kv;
|
||||
int32_t used[1] = {2304};
|
||||
b.kv_used_max_h = used;
|
||||
const int split6 = rad_prefill_splits_law(192, 48, 128, 128, 1, 4, used[0], 32);
|
||||
const uint64_t k6 = f.ctx.pass_key(&b);
|
||||
used[0] = 2305;
|
||||
const int same_split = rad_prefill_splits_law(192, 48, 128, 128, 1, 4, used[0], 32);
|
||||
CHECK_EQ(split6, 6);
|
||||
CHECK_EQ(same_split, 6);
|
||||
CHECK_EQ(f.ctx.pass_key(&b), k6);
|
||||
|
||||
used[0] = 3072;
|
||||
const int split8 = rad_prefill_splits_law(192, 48, 128, 128, 1, 4, used[0], 32);
|
||||
const uint64_t k8 = f.ctx.pass_key(&b);
|
||||
CHECK_EQ(split8, 8);
|
||||
CHECK(k8 != k6);
|
||||
CHECK_EQ(((128 + 192 - 1) / 192) * split6 * 768, 4608);
|
||||
CHECK_EQ(((128 + 192 - 1) / 192) * split8 * 768, 6144);
|
||||
CHECK_EQ(rad_ctx_wgp_count((RadCtx*)&f.ctx), 32);
|
||||
}
|
||||
|
||||
TEST(the_pass_key_changes_with_every_field_a_pass_depends_on) {
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
@@ -2343,7 +2522,8 @@ TEST(the_pass_key_changes_with_every_field_a_pass_depends_on) {
|
||||
std::memset(&b, 0, sizeof b);
|
||||
std::memset(kv, 0, sizeof kv);
|
||||
b.phase = RAD_PHASE_DECODE; b.step = 5; b.n_tok = 4; b.n_seq = 2; b.n_out = 2;
|
||||
b.max_q_len = 2; b.max_ctx_len = 1024; b.n_kv_groups = 2; b.kv = kv; b.n_spec = 1;
|
||||
b.max_q_len = 2; b.max_ctx_len = 1024;
|
||||
b.n_kv_groups = 2; b.kv = kv; b.n_spec = 1;
|
||||
b.n_seq_decode = 2; b.n_tok_decode = 4; b.max_q_len_decode = 2;
|
||||
int k = 0;
|
||||
b.token_ids = arr[k++]; b.positions = arr[k++]; b.cu_seqlens = arr[k++];
|
||||
|
||||
@@ -3560,4 +3560,124 @@ TEST(the_coupled_evidence_survives_the_drafters_greedy_build) {
|
||||
CHECK_EQ(ev.rows, (int64_t)6);
|
||||
}
|
||||
|
||||
/* The planes are sized for the rows a step can sample: one per token the step carries, so never
|
||||
* more than max_tok, and never fewer than max_seqs (a drafter's greedy pass). */
|
||||
TEST(the_sampler_rows_are_bounded_by_the_steps_tokens) {
|
||||
Registry reg;
|
||||
(void)reg.load_plugin(home() + "/kernels/libref.so", 0);
|
||||
RadModelMeta meta{};
|
||||
meta.arch_id = "sampler_rows";
|
||||
meta.name = "sampler_rows";
|
||||
RadBuildCtx bc{};
|
||||
bc.max_seqs = 4;
|
||||
bc.max_tok = 8;
|
||||
bc.max_ctx = 64;
|
||||
bc.max_spec = 7;
|
||||
bc.scope = "";
|
||||
Builder b(reg, meta, bc);
|
||||
Sampler s;
|
||||
SamplerConfig cfg;
|
||||
cfg.n_vocab = 16;
|
||||
cfg.n_vocab_local = 16;
|
||||
cfg.max_seqs = 4;
|
||||
cfg.max_spec = 7;
|
||||
cfg.max_tok = 8;
|
||||
cfg.max_hist = 16;
|
||||
cfg.max_candidates = 8;
|
||||
CHECK_OK(s.declare(&b, cfg));
|
||||
const int32_t d[7] = { 1, 2, 3, 4, 5, 6, 7 };
|
||||
Request r = make_req(1, { 1 }, greedy_params());
|
||||
r.n_draft = 7;
|
||||
r.draft = d;
|
||||
CHECK_OK(s.build_step({ &r }));
|
||||
Request q = make_req(2, { 1 }, greedy_params());
|
||||
CHECK_EQ(s.build_step({ &r, &q }), RAD_E_FULL);
|
||||
CHECK_OK(s.build_greedy(4));
|
||||
|
||||
/* A token bound below the sequences: a greedy pass still fits every sequence. */
|
||||
Builder b2(reg, meta, bc);
|
||||
Sampler t;
|
||||
cfg.max_tok = 2;
|
||||
CHECK_OK(t.declare(&b2, cfg));
|
||||
CHECK_OK(t.build_greedy(4));
|
||||
CHECK_EQ(t.build_greedy(5), RAD_E_FULL);
|
||||
}
|
||||
|
||||
/* A DRAFT PASS'S BUILD LEAVES THE STEP'S STAGING TO ITS UPLOAD.
|
||||
*
|
||||
* issue_serial_drafter and block_pass build their greedy passes right after the step's chain was
|
||||
* issued, and on a card that chain's uploads read the pinned staging only when the stream reaches
|
||||
* them, behind the step's forward pass. build_greedy zeroed the n-gram pairs there, so on a server
|
||||
* with a drafter a banning request uploaded n = 0 and was never banned on the card. Host-site ops
|
||||
* join their stream before they run, so the race itself cannot show on the host backend; the
|
||||
* pairs are checked instead, and the ban still runs in the step after the greedy build. */
|
||||
TEST(a_drafters_greedy_build_leaves_the_steps_ngram_pairs_to_its_upload) {
|
||||
HostChain ch(16, 2, 0);
|
||||
NEED_CHAIN(ch)
|
||||
SamplingParams sp = greedy_params();
|
||||
sp.ngram_ban_n = 2;
|
||||
sp.ngram_window = 8;
|
||||
/* 4 followed 3 once, so after the last 3 the ban removes 4 and 5 is the argmax. */
|
||||
std::vector<float> lg(16, 0.0f);
|
||||
lg[4] = 2.0f;
|
||||
lg[5] = 1.0f;
|
||||
Request a = make_req(1, { 3, 4, 3 }, sp);
|
||||
std::vector<int32_t> tok;
|
||||
CHECK_OK(ch.step({ &a }, lg, &tok));
|
||||
CHECK_EQ(tok[0], 5);
|
||||
CHECK_EQ(ch.s.staged_ngram(0)[0], 2);
|
||||
CHECK_EQ(ch.s.staged_ngram(0)[1], 8);
|
||||
|
||||
CHECK_OK(ch.s.build_greedy(2));
|
||||
CHECK_EQ(ch.s.staged_ngram(0)[0], 2);
|
||||
CHECK_EQ(ch.s.staged_ngram(0)[1], 8);
|
||||
|
||||
Request b = make_req(2, { 3, 4, 3 }, sp);
|
||||
CHECK_OK(ch.step({ &b }, lg, &tok));
|
||||
CHECK_EQ(tok[0], 5);
|
||||
}
|
||||
|
||||
/* A top-1 row keeps its one candidate through every cut, so a step of top-1 rows issues none: a
|
||||
* greedy row asking for logprobs (a top-1 chain row, as every greedy row is under a split
|
||||
* vocabulary) with top-p, min-p, typical and XTC set samples its argmax and its logprob without
|
||||
* them. A row with more than one candidate issues all four. Every row of a drafter's greedy pass
|
||||
* is top-1 too, with those fields at 0; under a split vocabulary it issued top-p and typical, a
|
||||
* max and a sum over the candidate width a row, every round. */
|
||||
TEST(a_top1_row_issues_no_candidate_cut) {
|
||||
HostChain ch(32, 2, 0);
|
||||
NEED_CHAIN(ch)
|
||||
auto issued = [&](const char* name) {
|
||||
ch.ctx.flush_issued();
|
||||
for (const OpInfo& o : ch.prog.ops)
|
||||
if (o.op == name && o.issued) return true;
|
||||
return false;
|
||||
};
|
||||
static const char* const kCuts[] = { "sample_topp", "sample_minp", "sample_typical",
|
||||
"sample_xtc" };
|
||||
SamplingParams g = greedy_params();
|
||||
g.n_probs = 1;
|
||||
g.top_p = 0.5f;
|
||||
g.min_p = 0.1f;
|
||||
g.typical_p = 0.5f;
|
||||
g.xtc_probability = 1.0f;
|
||||
g.xtc_threshold = 0.01f;
|
||||
std::vector<float> lg(32);
|
||||
for (int t = 0; t < 32; ++t) lg[(size_t)t] = 0.1f * (float)t;
|
||||
Request a = make_req(1, { 1 }, g);
|
||||
std::vector<int32_t> tok;
|
||||
CHECK_OK(ch.step({ &a }, lg, &tok));
|
||||
CHECK_EQ(tok[0], 31);
|
||||
TokenLogprobs lp;
|
||||
CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
|
||||
CHECK_NEAR(lp.logprob, lg[31] - log_sum_exp(lg), 1e-5);
|
||||
for (const char* op : kCuts) CHECK(!issued(op));
|
||||
|
||||
SamplingParams two = g;
|
||||
two.temp = 1.0f;
|
||||
two.top_k = 2;
|
||||
Request b = make_req(2, { 1 }, two);
|
||||
CHECK_OK(ch.step({ &b }, lg, &tok));
|
||||
for (const char* op : kCuts) CHECK(issued(op));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+535
-2
@@ -1942,6 +1942,29 @@ TEST(a_preempted_prefill_ignores_a_kv_group_that_holds_no_blocks) {
|
||||
f.commit_plain();
|
||||
}
|
||||
|
||||
/* A preempted request publishes what it computed, as a finished one does: its prompt stays in the
|
||||
* cache, and the recompute adopts it instead of computing it again (a 96.6k-token prompt took about
|
||||
* 25 s of a pair of cards). The blocks stay reclaimable: the cache gives them back under pressure. */
|
||||
TEST(a_preempted_request_publishes_its_prefix) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
|
||||
f.cfg.preempt_wait_ms = 60000;
|
||||
CHECK_OK(f.start());
|
||||
uint64_t a = f.submit(287, 64, /*priority=*/5);
|
||||
uint64_t b = f.submit(128, 64, /*priority=*/0);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
const size_t before = f.pc.published.size();
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
REQUIRE_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
|
||||
bool found = false;
|
||||
for (size_t i = before; i < f.pc.published.size(); ++i)
|
||||
if (f.pc.published[i].seq == b && f.pc.published[i].n_tokens >= 128) found = true;
|
||||
CHECK(found);
|
||||
f.commit_plain();
|
||||
(void)a;
|
||||
}
|
||||
|
||||
/* The gate's wait is bounded: after --preempt-wait-ms an overdue preempted prefill gets room by
|
||||
|
||||
* preempting the lowest-priority running request before the step is planned, so it cannot queue
|
||||
@@ -1973,6 +1996,49 @@ TEST(a_preempted_prefill_falls_back_to_a_running_victim_after_the_wait) {
|
||||
f.commit_plain();
|
||||
}
|
||||
|
||||
/* An overdue preempted prefill the pool still refuses keeps its place: nothing queued behind it is
|
||||
* admitted in that step, since the room the overdue path makes is for it. Asking the next request
|
||||
* instead let a request just forced off for it come straight back (its prompt published, so its
|
||||
* recompute needed almost nothing) and take that room again: under KV pressure the same victim was
|
||||
* forced off and re-admitted 26 times in 16 s while the overdue request waited. */
|
||||
TEST(an_overdue_preempted_prefill_keeps_its_place_ahead_of_the_queue) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
|
||||
f.cfg.preempt_wait_ms = 0; /* overdue from the next step */
|
||||
CHECK_OK(f.start());
|
||||
|
||||
uint64_t a = f.submit(287, 64, /*priority=*/5);
|
||||
uint64_t b = f.submit(128, 64, /*priority=*/0);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
REQUIRE_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
|
||||
f.commit_plain();
|
||||
|
||||
/* B is overdue and does not fit beside A. C, queued behind it, would fit; it must wait. */
|
||||
uint64_t c = f.submit(16, 4, /*priority=*/0);
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
|
||||
CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Waiting);
|
||||
f.commit_plain();
|
||||
}
|
||||
/* Once A finishes, B goes in first. */
|
||||
for (int i = 0; i < 80 && f.sch.find(a) && f.sch.find(a)->state != ReqState::Finished; ++i) {
|
||||
if (!f.sch.step()) break;
|
||||
f.commit_plain();
|
||||
}
|
||||
bool b_first = false;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
if (!f.sch.step()) continue;
|
||||
const ReqState bs = f.sch.find(b)->state, cs = f.sch.find(c)->state;
|
||||
if (bs == ReqState::Running) { b_first = true; f.commit_plain(); break; }
|
||||
CHECK(cs != ReqState::Running);
|
||||
f.commit_plain();
|
||||
}
|
||||
CHECK(b_first);
|
||||
}
|
||||
|
||||
/* A lower-priority overdue prefill may stay queued while a higher-priority runner keeps its
|
||||
* blocks. Forcing that runner off just swaps who is at zero. The priority-5 request must not be
|
||||
* the one left in Preempted while someone else still runs. */
|
||||
@@ -2002,6 +2068,58 @@ TEST(overdue_preempted_prefills_keep_forcing_until_one_fits) {
|
||||
(void)b; (void)c;
|
||||
}
|
||||
|
||||
/* The overdue path fails a preempted prefill only when waiting cannot help. A restore that waits a
|
||||
* step for a deferred release is a wait: failing it on an idle engine lost two of ten preempted
|
||||
* requests under KV pressure once their prompts were published at the preemption (1. 11. 2026). */
|
||||
TEST(an_overdue_preempted_prefill_whose_restore_waits_a_step_is_not_failed) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
|
||||
f.cfg.preempt_wait_ms = 0;
|
||||
f.cfg.n_spec = 7;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
uint64_t a = f.submit(287, /*max_tokens=*/64, /*priority=*/5);
|
||||
uint64_t b = f.submit(128, 64, /*priority=*/0);
|
||||
/* B's growth meets A's blocks: B is preempted while A runs. */
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
if (f.sch.find(b)->state == ReqState::Preempted) break;
|
||||
}
|
||||
REQUIRE_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
|
||||
REQUIRE_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
|
||||
|
||||
/* A is cancelled while a drafter pass names its blocks: they come back only at the next
|
||||
* commit, and nothing runs. */
|
||||
Scheduler::BlockRow rows[4];
|
||||
REQUIRE_EQ(f.sch.block_begin(/*block=*/8, /*depth=*/7, /*window=*/0, /*mask=*/99, rows, 4), 1);
|
||||
REQUIRE(f.sch.block_context(1) != nullptr);
|
||||
CHECK_OK(f.sch.cancel(a));
|
||||
f.sch.block_end();
|
||||
REQUIRE(f.sch.has_deferred());
|
||||
REQUIRE_EQ(f.sch.metrics().running, 0);
|
||||
|
||||
/* B's restore waits a step for that release; B must still be there after it. The cache
|
||||
* gives back what it holds when asked. */
|
||||
f.pc.decline_whole = true;
|
||||
f.pc.evict_frees = true;
|
||||
f.pc.evict_grant = 1 << 20;
|
||||
if (!f.sch.step() && f.sch.has_deferred()) f.sch.release_deferred();
|
||||
CHECK(f.sch.find(b)->state != ReqState::Failed);
|
||||
/* As the engine does when a step plans nothing: it drains, then releases what was deferred. */
|
||||
bool ran = false;
|
||||
for (int i = 0; i < 4 && !ran; ++i) {
|
||||
if (!f.sch.step()) {
|
||||
if (f.sch.has_deferred()) f.sch.release_deferred();
|
||||
continue;
|
||||
}
|
||||
ran = f.sch.find(b)->state == ReqState::Running;
|
||||
f.commit_plain();
|
||||
}
|
||||
CHECK(ran);
|
||||
CHECK(f.sch.find(b)->state != ReqState::Failed);
|
||||
}
|
||||
|
||||
TEST(a_mixed_step_has_the_right_boundaries_and_slot_mapping) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
@@ -2060,6 +2178,7 @@ TEST(a_mixed_step_has_the_right_boundaries_and_slot_mapping) {
|
||||
CHECK_EQ(g0.block_table[128], btb[0]);
|
||||
CHECK_EQ(g0.seqused[0], 101);
|
||||
CHECK_EQ(g0.seqused[1], 64);
|
||||
CHECK_EQ(s2->kv_used_max_h[0], std::max(g0.seqused[0], g0.seqused[1]));
|
||||
|
||||
/* The linear group is per sequence, not per token: every token of a sequence maps to its one
|
||||
* state instance, and the block table row is that slot. */
|
||||
@@ -3075,12 +3194,17 @@ struct Interleaved {
|
||||
int64_t steps_held = 0;
|
||||
};
|
||||
|
||||
static Interleaved interleave_run(int64_t n, bool decoder, int steps) {
|
||||
/* `chunk_s` / `decode_s`: step costs fed to --prefill-interleave auto before the run (none when
|
||||
* 0), standing in for step_finished's wall times. */
|
||||
static Interleaved interleave_run(int64_t n, bool decoder, int steps, double chunk_s = 0,
|
||||
double decode_s = 0) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
f.cfg.prefill_interleave = n;
|
||||
CHECK_OK(f.start());
|
||||
f.sch.set_stage_rows(64);
|
||||
if (chunk_s > 0) f.sch.note_step_cost(true, chunk_s);
|
||||
if (decode_s > 0) f.sch.note_step_cost(false, decode_s);
|
||||
if (decoder) {
|
||||
f.submit(100, 512);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
@@ -3140,6 +3264,70 @@ TEST(interleave_leaves_a_lone_prefill_alone) {
|
||||
CHECK_EQ(r.steps_held, 0);
|
||||
}
|
||||
|
||||
/* auto: as many decode-only steps as fit in a quarter of a chunk step's measured time at a decode
|
||||
* step's (rounded down, at most 16), one until both are measured, none where a decode step costs
|
||||
* more than that quarter. */
|
||||
TEST(interleave_auto_fits_decode_steps_in_a_quarter_of_a_chunk_step) {
|
||||
auto steps = [](double chunk_s, double decode_s) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
f.cfg.prefill_interleave = -1;
|
||||
CHECK_OK(f.start());
|
||||
if (chunk_s > 0) f.sch.note_step_cost(true, chunk_s);
|
||||
if (decode_s > 0) f.sch.note_step_cost(false, decode_s);
|
||||
return f.sch.interleave_steps();
|
||||
};
|
||||
CHECK_EQ(steps(0, 0), 1);
|
||||
CHECK_EQ(steps(0.4, 0), 1);
|
||||
CHECK_EQ(steps(0, 0.03), 1);
|
||||
CHECK_EQ(steps(0.4, 0.03), 3); /* 0.1 s of 0.03 s steps */
|
||||
CHECK_EQ(steps(0.4, 0.05), 2);
|
||||
CHECK_EQ(steps(0.4, 0.2), 0); /* a decode step dearer than the quarter */
|
||||
CHECK_EQ(steps(1.0, 0.001), 64); /* capped at kInterleaveAutoMax */
|
||||
/* auto:SHARE: SHARE of the chunk step's time instead of a quarter. */
|
||||
Fixture k;
|
||||
k.build();
|
||||
k.cfg.prefill_interleave = -1;
|
||||
k.cfg.prefill_interleave_share = 1.0;
|
||||
CHECK_OK(k.start());
|
||||
k.sch.note_step_cost(true, 0.4);
|
||||
k.sch.note_step_cost(false, 0.04);
|
||||
CHECK_EQ(k.sch.interleave_steps(), 10); /* 0.4 s of 0.04 s steps */
|
||||
/* A number is used as given, whatever was measured. */
|
||||
Fixture g;
|
||||
g.build();
|
||||
g.cfg.prefill_interleave = 5;
|
||||
CHECK_OK(g.start());
|
||||
g.sch.note_step_cost(true, 1.0);
|
||||
g.sch.note_step_cost(false, 0.001);
|
||||
CHECK_EQ(g.sch.interleave_steps(), 5);
|
||||
/* The costs are running means: a chunk step of 0.4 s, then one of 0.8 s, reads 0.5 s. */
|
||||
Fixture h;
|
||||
h.build();
|
||||
h.cfg.prefill_interleave = -1;
|
||||
CHECK_OK(h.start());
|
||||
h.sch.note_step_cost(true, 0.4);
|
||||
h.sch.note_step_cost(true, 0.8);
|
||||
h.sch.note_step_cost(false, 0.05);
|
||||
CHECK_EQ(h.sch.interleave_steps(), 2); /* 0.125 / 0.05 */
|
||||
}
|
||||
|
||||
/* auto schedules the measured count after every chunk beside a decoder, holds nothing for a lone
|
||||
* prefill, and with decode steps too dear for the quarter puts a chunk in every step. */
|
||||
TEST(interleave_auto_holds_each_chunk_for_the_steps_its_costs_allow) {
|
||||
const Interleaved r = interleave_run(-1, /*decoder=*/true, 10, 0.4, 0.05);
|
||||
CHECK_EQ(r.shape, std::string("CDDCDDCDDC"));
|
||||
CHECK_EQ(r.steps_held, 6);
|
||||
const Interleaved first = interleave_run(-1, /*decoder=*/true, 6); /* nothing measured */
|
||||
CHECK_EQ(first.shape, std::string("CDCDCD"));
|
||||
const Interleaved dear = interleave_run(-1, /*decoder=*/true, 8, 0.4, 0.2);
|
||||
CHECK_EQ(dear.shape, std::string("CCCCCCCC"));
|
||||
CHECK_EQ(dear.steps_held, 0);
|
||||
const Interleaved lone = interleave_run(-1, /*decoder=*/false, 8, 0.4, 0.01);
|
||||
CHECK_EQ(lone.shape, std::string("CCCCCCCC"));
|
||||
CHECK_EQ(lone.steps_held, 0);
|
||||
}
|
||||
|
||||
/* After a prompt's last chunk there is nothing to interleave: the next request is admitted in the
|
||||
* next step. */
|
||||
TEST(interleave_does_not_hold_after_a_prompts_last_chunk) {
|
||||
@@ -6972,8 +7160,18 @@ TEST(a_preempted_ring_sequence_replays_its_output_a_token_a_step) {
|
||||
* nothing. */
|
||||
int64_t at = 0;
|
||||
for (int k = 0; k < 8 && at < 160; ++k) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
const RadBatch* chunk = f.sch.step();
|
||||
REQUIRE(chunk != nullptr);
|
||||
REQUIRE_EQ(f.sch.plan().e.size(), (size_t)1);
|
||||
const RadKVGroupBatch& paged = chunk->kv[0];
|
||||
REQUIRE(paged.seqused_h != nullptr);
|
||||
REQUIRE(chunk->positions_h != nullptr);
|
||||
CHECK_EQ(paged.seqused_h[0], paged.seqused[0]);
|
||||
CHECK_EQ(chunk->positions_h[0], chunk->positions[0]);
|
||||
int32_t used_max = 0;
|
||||
for (int64_t i = 0; i < chunk->n_seq; ++i)
|
||||
used_max = std::max(used_max, paged.seqused[i]);
|
||||
CHECK_EQ(chunk->kv_used_max_h[0], used_max);
|
||||
CHECK_EQ(f.sch.plan().e[0].ctx_len, at);
|
||||
at += f.sch.plan().e[0].n_tokens;
|
||||
CHECK(at <= 160);
|
||||
@@ -6985,6 +7183,11 @@ TEST(a_preempted_ring_sequence_replays_its_output_a_token_a_step) {
|
||||
/* The replayed output token on its own, which samples the next. */
|
||||
const RadBatch* rb = f.sch.step();
|
||||
REQUIRE(rb != nullptr);
|
||||
CHECK_EQ(rb->kv_used_max_h[0], rb->kv[0].seqused[0]);
|
||||
REQUIRE(rb->kv[0].seqused_h != nullptr);
|
||||
REQUIRE(rb->positions_h != nullptr);
|
||||
CHECK_EQ(rb->kv[0].seqused_h[0], rb->kv[0].seqused[0]);
|
||||
CHECK_EQ(rb->positions_h[0], rb->positions[0]);
|
||||
CHECK_EQ(f.sch.plan().e[0].ctx_len, 160);
|
||||
CHECK_EQ(f.sch.plan().e[0].n_tokens, 1);
|
||||
CHECK(f.sch.plan().e[0].produces_token);
|
||||
@@ -7069,6 +7272,121 @@ TEST(media_rows_are_staged_by_chunk_at_the_tokens_that_take_them) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== runs read both ways */
|
||||
/* A picture whose placeholders the model reads both ways (RadEncoderDecl::bidirectional) is never
|
||||
* cut by a chunk: the chunk ends before it on the quantum (64 here, the linear group's chunk), or,
|
||||
* starting at it, runs past its end, and the pass names the run's rows and the keys they see
|
||||
* (RadBatch::n_bidi). Tokens 200..299 here; without the flag the first chunk would end at the
|
||||
* checkpoint interval (256), inside the picture. A run longer than any step is cut where its chunk
|
||||
* falls, and its rows then see the run up to the cut. An audio clip is read causally and cut
|
||||
* anywhere. */
|
||||
namespace {
|
||||
|
||||
std::unique_ptr<Request> with_run(Fixture& f, int n_prompt, int tok, int n, mm::Kind kind) {
|
||||
auto item = std::make_shared<mm::Item>();
|
||||
item->kind = kind;
|
||||
item->n_seg = 1;
|
||||
item->seg_rows = n;
|
||||
item->encoded = true;
|
||||
item->embd.assign((size_t)n * 4, 0);
|
||||
auto req = f.request(n_prompt, 4);
|
||||
req->media = std::make_shared<mm::PromptMedia>();
|
||||
req->media->items.push_back(mm::Placed{ item, tok - 1 });
|
||||
mm::RopeLayout::Run run;
|
||||
run.tok = tok; run.n = n; run.w = n; run.base = tok; run.shift = 0; run.item = 0; run.flat = true;
|
||||
req->media->rope.runs.push_back(run);
|
||||
return req;
|
||||
}
|
||||
|
||||
void media_fixture(Fixture& f, int64_t max_tok, int32_t bidi) {
|
||||
f.build(/*blocks=*/4096, /*states=*/64, max_tok);
|
||||
f.prog.encoder.modalities = RAD_MM_IMAGE;
|
||||
f.prog.encoder.n_embd = 4;
|
||||
f.prog.encoder.patch_dim = 4;
|
||||
f.prog.encoder.merge = 1;
|
||||
f.prog.encoder.max_patches = 1024;
|
||||
f.prog.encoder.bidirectional = bidi;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(a_run_read_both_ways_is_never_cut_by_a_chunk) {
|
||||
Fixture f;
|
||||
media_fixture(f, 256, 1);
|
||||
CHECK_OK(f.start());
|
||||
f.add(with_run(f, 400, 200, 100, mm::Kind::Image));
|
||||
const RadBatch* b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)192);
|
||||
CHECK_EQ(b->n_bidi, (int64_t)0);
|
||||
f.commit_plain();
|
||||
b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)128); /* 192 .. 319, past the run's end */
|
||||
REQUIRE_EQ(b->n_bidi, (int64_t)1);
|
||||
CHECK_EQ(b->bidi_row[0], 8);
|
||||
CHECK_EQ(b->bidi_n[0], 100);
|
||||
CHECK_EQ(b->bidi_seq[0], 0);
|
||||
CHECK_EQ(b->bidi_used[0], 300);
|
||||
CHECK_EQ(b->n_mm_rows, (int64_t)100);
|
||||
f.commit_plain();
|
||||
b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)64); /* to the tail checkpoint, text only */
|
||||
CHECK_EQ(b->n_bidi, (int64_t)0);
|
||||
|
||||
/* bidi_fit itself: inside the run, from before it, from its start, and with too small a
|
||||
* budget (wait) or a run no step holds (cut as it falls). */
|
||||
auto r = with_run(f, 400, 200, 100, mm::Kind::Image);
|
||||
CHECK_EQ(f.sch.bidi_fit(*r, 0, 400, 256, 256), 192);
|
||||
CHECK_EQ(f.sch.bidi_fit(*r, 0, 400, 192, 256), 192);
|
||||
CHECK_EQ(f.sch.bidi_fit(*r, 192, 400, 64, 256), 128);
|
||||
CHECK_EQ(f.sch.bidi_fit(*r, 192, 400, 64, 100), 0);
|
||||
CHECK_EQ(f.sch.bidi_fit(*r, 0, 250, 250, 256), 250); /* the sequence ends inside it */
|
||||
auto big = with_run(f, 800, 200, 400, mm::Kind::Image);
|
||||
CHECK_EQ(f.sch.bidi_fit(*big, 192, 800, 64, 256), 64);
|
||||
/* Two video frames, <eoi><boi> apart: back past both, or on past both. */
|
||||
auto vid = with_run(f, 400, 100, 70, mm::Kind::Video);
|
||||
mm::RopeLayout::Run second = vid->media->rope.runs[0];
|
||||
second.tok = 172;
|
||||
vid->media->rope.runs.push_back(second);
|
||||
CHECK_EQ(f.sch.bidi_fit(*vid, 0, 400, 200, 256), 64);
|
||||
CHECK_EQ(f.sch.bidi_fit(*vid, 64, 400, 64, 256), 192);
|
||||
CHECK_EQ(f.sch.bidi_fit(*vid, 64, 400, 64, 128), 0);
|
||||
}
|
||||
|
||||
TEST(a_run_longer_than_a_step_is_cut_and_reads_up_to_the_cut) {
|
||||
Fixture f;
|
||||
media_fixture(f, 256, 1);
|
||||
CHECK_OK(f.start());
|
||||
f.add(with_run(f, 800, 200, 400, mm::Kind::Image));
|
||||
const RadBatch* b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)192);
|
||||
f.commit_plain();
|
||||
b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)64);
|
||||
REQUIRE_EQ(b->n_bidi, (int64_t)1);
|
||||
CHECK_EQ(b->bidi_row[0], 8);
|
||||
CHECK_EQ(b->bidi_n[0], 56);
|
||||
CHECK_EQ(b->bidi_used[0], 256);
|
||||
}
|
||||
|
||||
TEST(runs_are_cut_anywhere_without_the_flag_and_for_audio) {
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
Fixture f;
|
||||
media_fixture(f, 256, k == 0 ? 0 : 1);
|
||||
CHECK_OK(f.start());
|
||||
f.add(with_run(f, 400, 200, 100, k == 0 ? mm::Kind::Image : mm::Kind::Audio));
|
||||
const RadBatch* b = f.sch.step();
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->n_tok, (int64_t)256);
|
||||
CHECK_EQ(b->n_bidi, (int64_t)0);
|
||||
CHECK_EQ(b->n_mm_rows, (int64_t)56);
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== scored rows (KL mode) */
|
||||
/* In KL mode a scored prompt names a logits row at every position it prefills, after the
|
||||
* sampler's rows and in entry order, which is the order Engine::score_rows maps back. A row
|
||||
@@ -7373,3 +7691,218 @@ TEST(without_a_span_the_scheduler_plans_and_stages_the_pinned_steps) {
|
||||
CHECK_EQ(h, c.want);
|
||||
}
|
||||
}
|
||||
|
||||
/* A recycled slot keeps its struct: add_locked only allocates when the slot's pointer is null, so
|
||||
* every field it does not list survives from the request before. admitted_us is the one such field
|
||||
* with no backstop where it is read -- the prefill figure is computed from it whenever it is
|
||||
* non-zero, and a stamp left by an earlier request is always older, so the interval is inflated and
|
||||
* reads as a slow prefill rather than as missing data. Admission cannot precede arrival, so
|
||||
* prefill_s may never exceed ttft_s: that is the invariant that catches a stamp carried over from
|
||||
* another request. */
|
||||
TEST(a_recycled_slot_does_not_carry_the_previous_request_s_admission) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
|
||||
const uint64_t a = f.submit(8, 4);
|
||||
REQUIRE(a != 0);
|
||||
for (int i = 0; i < 80 && f.sch.find(a)->state != ReqState::Finished; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
}
|
||||
REQUIRE_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished);
|
||||
|
||||
/* The slot A held, read while its row is still published. The whole case rests on B landing
|
||||
* in this same slot: if the reap ever defers, or the free list is pre-populated, B gets a
|
||||
* fresh struct, the stale stamp is gone by construction, and the invariant below would hold
|
||||
* with the bug unpatched. So the precondition is asserted rather than trusted. */
|
||||
int slot_a = -1;
|
||||
{
|
||||
std::vector<Scheduler::ReqStat> st(8);
|
||||
const int n = f.sch.requests(st.data(), 8);
|
||||
for (int j = 0; j < n; ++j) if (st[(size_t)j].id == a) slot_a = st[(size_t)j].slot;
|
||||
}
|
||||
REQUIRE(slot_a >= 0);
|
||||
CHECK_OK(f.sch.reap(a));
|
||||
|
||||
/* A's slot is on the free list, so B takes the slot and the struct that came with it. */
|
||||
const uint64_t b = f.submit(8, 4);
|
||||
REQUIRE(b != 0);
|
||||
for (int i = 0; i < 80; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
std::vector<Scheduler::ReqStat> st(8);
|
||||
const int n = f.sch.requests(st.data(), 8);
|
||||
for (int j = 0; j < n; ++j) {
|
||||
if (st[(size_t)j].id != b) continue;
|
||||
if (st[(size_t)j].ttft_s < 0) break; /* no first token yet */
|
||||
/* Both figures describe this request alone, so prefill -- admission to first token --
|
||||
* is bounded by ttft, arrival to first token. */
|
||||
CHECK_EQ(st[(size_t)j].slot, slot_a); /* the reuse this case is about */
|
||||
CHECK(st[(size_t)j].prefill_s >= 0);
|
||||
CHECK(st[(size_t)j].prefill_s <= st[(size_t)j].ttft_s);
|
||||
return;
|
||||
}
|
||||
}
|
||||
CHECK(!"the second request never reached its first token");
|
||||
}
|
||||
|
||||
/* ================================================================== a burst of long prompts, timed
|
||||
*
|
||||
* Not a check: a measurement harness for scheduling policy, run on request only:
|
||||
*
|
||||
* RAD_SCHED_SIM=1 [SIM_N=32 SIM_LEN=131072 SIM_OUT=512 SIM_MAXTOK=2048 SIM_INTERVAL=2048
|
||||
* SIM_BUSY=-1 SIM_IL=0 SIM_SHARE=0.25 SIM_SEQS=32 SIM_DECODERS=0
|
||||
* SIM_TRACE=1] sched_test sim_burst
|
||||
*
|
||||
* SIM_DECODERS sequences of 64-token prompts are decoding (SIM_DEC_OUT tokens each, default
|
||||
* 4096) before the burst arrives. The summary counts the steps that carried a chunk per
|
||||
* checkpoint interval prefilled.
|
||||
*
|
||||
* SIM_N prompts of SIM_LEN tokens arrive at once, each then decodes SIM_OUT tokens with three
|
||||
* drafts a step (a uniform 0..3 accepted), the stager arming at 1025 rows, under
|
||||
* --prefix-resume exact. SIM_BUSY and SIM_IL are --busy-prefill-chunk and --prefill-interleave
|
||||
* (-1 for auto, at SIM_SHARE of a chunk step's time: SIM_IL=-1 SIM_SHARE=1 is auto:1). Each step's
|
||||
* time is a cost model in seconds: SIM_DEC0 + SIM_DECR per decode row when it has one, plus
|
||||
* SIM_PF0 + SIM_PFB per row when it carries a chunk. The defaults are fitted to Qwen3.8-Flash-Next
|
||||
* at TP2 (a lone prefill at ~5.4K tokens/s on 2048-token chunks; one sequence decoding ~145
|
||||
* tokens/s, sixteen ~650 with MTP), not measured per step shape: the schedule is the scheduler's
|
||||
* own, the times are an estimate. Prints the aggregate prefill rate,
|
||||
* the time-to-first-token spread and the decode rate of sequences decoding while some prompt still
|
||||
* waits for its first token. */
|
||||
static double sim_env(const char* k, double d) {
|
||||
const char* v = std::getenv(k);
|
||||
return v ? std::atof(v) : d;
|
||||
}
|
||||
|
||||
TEST(sim_burst_of_long_prompts) {
|
||||
if (!std::getenv("RAD_SCHED_SIM")) return;
|
||||
const int N = (int)sim_env("SIM_N", 32);
|
||||
const int64_t L = (int64_t)sim_env("SIM_LEN", 131072);
|
||||
const int OUT = (int)sim_env("SIM_OUT", 512);
|
||||
const int64_t MT = (int64_t)sim_env("SIM_MAXTOK", 2048);
|
||||
const double dec0 = sim_env("SIM_DEC0", 0.014), decr = sim_env("SIM_DECR", 0.003);
|
||||
const double pf0 = sim_env("SIM_PF0", 0.075), pfb = sim_env("SIM_PFB", 0.147e-3);
|
||||
Fixture f;
|
||||
const int64_t ctx = L + OUT + 4096;
|
||||
f.build(/*blocks=*/(int64_t)N * (ctx / 16 + 8) + 1024, /*states=*/2 * N + 8, MT, ctx);
|
||||
f.cfg.checkpoint_interval = (int64_t)sim_env("SIM_INTERVAL", 2048);
|
||||
f.cfg.busy_prefill_chunk = (int64_t)sim_env("SIM_BUSY", -1);
|
||||
f.cfg.prefill_interleave = (int64_t)sim_env("SIM_IL", 0);
|
||||
f.cfg.prefill_interleave_share = sim_env("SIM_SHARE", 0.25);
|
||||
f.cfg.max_seqs = (int64_t)sim_env("SIM_SEQS", 32);
|
||||
f.cfg.prefix_exact = true;
|
||||
f.cfg.n_spec = 3;
|
||||
CHECK_OK(f.start());
|
||||
f.sch.set_stage_rows(1025);
|
||||
uint32_t rng = 12345;
|
||||
int32_t draft[3] = { 7, 7, 7 };
|
||||
/* The decoders, decoding before the burst arrives. */
|
||||
std::vector<uint64_t> decs;
|
||||
const int ND = (int)sim_env("SIM_DECODERS", 0);
|
||||
const int DOUT = (int)sim_env("SIM_DEC_OUT", 4096);
|
||||
for (int i = 0; i < ND; ++i) decs.push_back(f.submit(64, DOUT, 0, /*ignore_eos=*/true));
|
||||
auto draft_all = [&](const std::vector<uint64_t>& v) {
|
||||
for (uint64_t id : v) {
|
||||
const Request* r = f.sch.find(id);
|
||||
if (r && r->state == ReqState::Running && r->n_computed >= (int64_t)r->prompt.size())
|
||||
(void)f.sch.set_draft(id, draft, 3);
|
||||
}
|
||||
};
|
||||
for (int k = 0; k < 16 && ND > 0; ++k) {
|
||||
draft_all(decs);
|
||||
if (!f.sch.step()) break;
|
||||
CHECK_OK(f.commit(7, 0, [&](const StepEntry& e) { return random_accept(rng, e); }));
|
||||
}
|
||||
std::vector<uint64_t> ids;
|
||||
for (int i = 0; i < N; ++i) {
|
||||
auto r = f.request((int)L, OUT);
|
||||
for (size_t k = 0; k < r->prompt.size(); ++k)
|
||||
r->prompt[k] = 1000 + (int32_t)(((int64_t)k * 7 + i * 13) % 60000);
|
||||
r->ignore_eos = true;
|
||||
ids.push_back(f.add(std::move(r)));
|
||||
}
|
||||
std::vector<double> ttft(ids.size(), -1), done(ids.size(), -1);
|
||||
double t = 0, t_pf = 0, dec_s = 0;
|
||||
int64_t pf_tok = 0, steps = 0, mixed = 0, small = 0, dec_tok = 0, chunk_steps = 0;
|
||||
auto idx = [&](uint64_t id) { return (size_t)(id - ids[0]); };
|
||||
while (steps < 200000) {
|
||||
draft_all(ids);
|
||||
draft_all(decs);
|
||||
if (!f.sch.step()) break;
|
||||
const StepPlan& p = f.sch.plan();
|
||||
int64_t P = 0, D = 0, nd = 0;
|
||||
for (const StepEntry& e : p.e) {
|
||||
if (e.is_prefill) P += e.n_tokens;
|
||||
else { D += e.n_tokens; ++nd; }
|
||||
}
|
||||
const double dt = (nd ? dec0 + decr * (double)nd : 0.0) +
|
||||
(P ? pf0 + pfb * (double)(P + D) : 0.0);
|
||||
if (std::getenv("SIM_TRACE") && (steps < 12 || steps % 97 == 0)) {
|
||||
std::printf("step %lld t=%.1f:", (long long)steps, t);
|
||||
for (const StepEntry& e : p.e)
|
||||
std::printf(" %llu:%s%d@%d", (unsigned long long)e.seq, e.is_prefill ? "P" : "d",
|
||||
e.n_tokens, e.ctx_len);
|
||||
std::printf("\n");
|
||||
}
|
||||
++steps;
|
||||
chunk_steps += P > 0;
|
||||
mixed += P && nd;
|
||||
small += P && P < 1025;
|
||||
pf_tok += P;
|
||||
if (P) t_pf += dt;
|
||||
bool waiting = false;
|
||||
int64_t decoders = 0;
|
||||
for (size_t k = 0; k < ids.size(); ++k) {
|
||||
if (done[k] >= 0) continue;
|
||||
if (ttft[k] >= 0) ++decoders; else waiting = true;
|
||||
}
|
||||
for (uint64_t id : decs) decoders += f.sch.find(id) != nullptr;
|
||||
std::vector<std::pair<uint64_t, size_t>> before;
|
||||
for (const StepEntry& e : p.e) before.push_back({ e.seq, e.req->output.size() });
|
||||
CHECK_OK(f.commit(7, 0, [&](const StepEntry& e) { return random_accept(rng, e); }));
|
||||
f.sch.note_step_cost(P > 0, dt);
|
||||
t += dt;
|
||||
if (waiting) dec_s += dt * (double)decoders;
|
||||
for (const auto& b : before) {
|
||||
const Request* r = f.sch.find(b.first);
|
||||
if (!r) continue;
|
||||
const bool burst = b.first >= ids[0];
|
||||
if (burst && b.second == 0 && !r->output.empty() && ttft[idx(b.first)] < 0)
|
||||
ttft[idx(b.first)] = t;
|
||||
else if (waiting && b.second > 0) dec_tok += (int64_t)(r->output.size() - b.second);
|
||||
}
|
||||
std::vector<uint64_t> c;
|
||||
f.sch.take_completed(&c);
|
||||
for (uint64_t id : c) {
|
||||
if (id >= ids[0]) done[idx(id)] = t;
|
||||
(void)f.sch.reap(id);
|
||||
}
|
||||
/* The decoders outlive the burst; the run ends with its last prompt. */
|
||||
bool left = false;
|
||||
for (double d : done) left = left || d < 0;
|
||||
if (!left) break;
|
||||
}
|
||||
std::vector<double> tt;
|
||||
for (double x : ttft) if (x >= 0) tt.push_back(x);
|
||||
std::sort(tt.begin(), tt.end());
|
||||
if (tt.empty()) return;
|
||||
auto pct = [&](double q) { return tt[std::min(tt.size() - 1, (size_t)(q * (double)tt.size()))]; };
|
||||
const double intervals = (double)pf_tok / (double)std::max<int64_t>(f.cfg.checkpoint_interval, 1);
|
||||
char il[32];
|
||||
if (f.cfg.prefill_interleave < 0)
|
||||
std::snprintf(il, sizeof il, "auto:%g", f.cfg.prefill_interleave_share);
|
||||
else
|
||||
std::snprintf(il, sizeof il, "%lld", (long long)f.cfg.prefill_interleave);
|
||||
std::printf("sim: %d x %lld tokens beside %d decoders, max_tok %lld, busy %lld, "
|
||||
"interleave %s: %lld steps (%lld mixed, %lld with a chunk under 1025, %.2f with a "
|
||||
"chunk per interval); prefill %.0f tokens/s over the steps with a "
|
||||
"chunk, %.0f to the last first token; TTFT p50 %.0f p95 %.0f max %.0f s; decode "
|
||||
"while prompts wait %.1f tokens/s a sequence; all done at %.0f s\n",
|
||||
N, (long long)L, ND, (long long)MT, (long long)f.cfg.busy_prefill_chunk,
|
||||
il, (long long)steps, (long long)mixed,
|
||||
(long long)small, (double)chunk_steps / std::max(intervals, 1e-9),
|
||||
(double)pf_tok / std::max(t_pf, 1e-9),
|
||||
(double)N * (double)L / tt.back(), pct(0.5), pct(0.95), tt.back(),
|
||||
dec_s > 0 ? (double)dec_tok / dec_s : 0.0, t);
|
||||
}
|
||||
@@ -3720,6 +3720,25 @@ TEST(messages_refuse_a_field_they_do_not_know) {
|
||||
CHECK(f.sched.submitted.empty());
|
||||
}
|
||||
|
||||
/* The chat path's history penalties and min-p are taken at the top level under the chat path's
|
||||
* names and reach the sampler as there; out of range they are refused by name, as there. */
|
||||
TEST(messages_carry_the_penalties_and_min_p_to_the_sampler) {
|
||||
Fixture f;
|
||||
f.sched.reply = "fine";
|
||||
const HttpResponse r = post_messages(f, R"("presence_penalty":1.5,"frequency_penalty":0.25,)"
|
||||
R"("repetition_penalty":1.05,"min_p":0.05,)"
|
||||
R"("repeat_last_n":256)");
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK_NEAR(f.sched.last_sp.pres_penalty, 1.5f, 1e-6);
|
||||
CHECK_NEAR(f.sched.last_sp.freq_penalty, 0.25f, 1e-6);
|
||||
CHECK_NEAR(f.sched.last_sp.rep_penalty, 1.05f, 1e-6);
|
||||
CHECK_NEAR(f.sched.last_sp.min_p, 0.05f, 1e-6);
|
||||
CHECK_EQ(f.sched.last_sp.penalty_last_n, 256);
|
||||
Fixture g;
|
||||
CHECK(anthropic_refusal(post_messages(g, R"("presence_penalty":3)"), "presence_penalty"));
|
||||
CHECK(g.sched.submitted.empty());
|
||||
}
|
||||
|
||||
/* What cannot change the answer here is taken and not acted on: capacity and placement,
|
||||
* prompt-cache control, and the inputs of Anthropic's own classifiers and fallbacks. */
|
||||
TEST(messages_take_the_fields_that_change_nothing_here) {
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
/* shape_test.cpp -- the shape generator's host geometry (core/gen/shape.h) and its pass driver
|
||||
* (core/gen/shape_driver.h). The plugin's side of each pass is played by the test: a query pass is
|
||||
* answered with a sphere's field at the points the driver staged.
|
||||
*/
|
||||
#include "sched_fakes.h"
|
||||
|
||||
using namespace sched_fake;
|
||||
|
||||
#include "gen/shape_driver.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A small declaration: a 28-pixel encoder picture in 14-pixel patches, a latent of 8 rows of 4,
|
||||
* a step of both branches with 5 conditioning rows each. */
|
||||
RadShapeGenDecl decl_small() {
|
||||
RadShapeGenDecl d{};
|
||||
d.canvas = 32;
|
||||
d.border_ratio = 0.15;
|
||||
d.enc_size = 28;
|
||||
d.enc_patch = 14;
|
||||
for (int c = 0; c < 3; ++c) { d.pix_mean[c] = 0.5; d.pix_std[c] = 0.25; }
|
||||
d.latent_rows = 8;
|
||||
d.latent_channels = 4;
|
||||
d.step_rows = 2 * (5 + 8);
|
||||
d.default_steps = 4;
|
||||
d.max_steps = 8;
|
||||
d.default_guidance = 5.0;
|
||||
d.bounds = 1.0;
|
||||
d.level = 0.0;
|
||||
d.default_resolution = 64;
|
||||
d.min_resolution = 8;
|
||||
d.max_resolution = 128;
|
||||
d.max_lanes = 2;
|
||||
d.max_query = 4096;
|
||||
d.field_out = 1;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* An RGBA picture w x h, opaque inside the box [x0, x1) x [y0, y1) and transparent elsewhere. */
|
||||
mm::FrameRGBA picture(int32_t w, int32_t h, int32_t x0, int32_t y0, int32_t x1, int32_t y1) {
|
||||
mm::FrameRGBA f;
|
||||
f.w = w;
|
||||
f.h = h;
|
||||
f.rgba.assign((size_t)w * h * 4, 0);
|
||||
for (int32_t y = y0; y < y1; ++y)
|
||||
for (int32_t x = x0; x < x1; ++x) {
|
||||
uint8_t* p = &f.rgba[((size_t)y * w + x) * 4];
|
||||
p[0] = 200; p[1] = 50; p[2] = 10; p[3] = 255;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
gen::ShapeGenInfo info_small() { return gen::shape_info(decl_small(), "test"); }
|
||||
|
||||
/* A sphere of radius `r` at the origin, as an occupancy logit: positive inside. */
|
||||
float sphere(float x, float y, float z, float r) { return r - std::sqrt(x * x + y * y + z * z); }
|
||||
|
||||
/* The field of a sphere on level r's grid. */
|
||||
std::vector<float> sphere_grid(int32_t r, double bounds, float radius) {
|
||||
const std::vector<float> ax = gen::shape_axis(bounds, r);
|
||||
const int64_t n = (int64_t)r + 1;
|
||||
std::vector<float> f((size_t)(n * n * n));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
for (int64_t k = 0; k < n; ++k)
|
||||
f[(size_t)((i * n + j) * n + k)] = sphere(ax[(size_t)i], ax[(size_t)j],
|
||||
ax[(size_t)k], radius);
|
||||
return f;
|
||||
}
|
||||
|
||||
struct ShapeFixture {
|
||||
Program prog;
|
||||
gen::ShapeDriver drv;
|
||||
void build() {
|
||||
prog.shape_gen = decl_small();
|
||||
prog.sgen_name = "test";
|
||||
prog.ctx.max_tok = 4096;
|
||||
prog.ctx.max_seqs = 1;
|
||||
}
|
||||
int start() { return drv.init(prog, { gen::ShapeDriver::RankIO{} }); }
|
||||
std::unique_ptr<gen::ShapeRequest> req(int32_t steps = 0, int32_t res = 16) {
|
||||
auto r = std::make_unique<gen::ShapeRequest>();
|
||||
std::string why;
|
||||
if (gen::shape_picture(info_small(), picture(40, 30, 5, 3, 30, 27), &r->patches, &why) < 0)
|
||||
return nullptr;
|
||||
r->steps = steps;
|
||||
r->resolution = res;
|
||||
r->seed = 7;
|
||||
r->ticket = std::make_shared<gen::ShapeTicket>();
|
||||
return r;
|
||||
}
|
||||
/* The plugin's answer to a query pass: the sphere's field at each staged point, steepened
|
||||
* `gain` times as an occupancy logit is (the model's cross zero within a cell or two). */
|
||||
void answer(const RadBatch* b, float radius, float gain = 20.0f) {
|
||||
const RadShapeGenBatch* S = b->sgen_b;
|
||||
for (const gen::IPassDriver::Readback& rb : drv.readbacks()) {
|
||||
float* x = static_cast<float*>(rb.host);
|
||||
for (int64_t i = 0; i < S->n_query; ++i)
|
||||
x[i] = gain * sphere(S->query[3 * i], S->query[3 * i + 1], S->query[3 * i + 2],
|
||||
radius);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
char kind_of(int gen) {
|
||||
switch (gen) {
|
||||
case RAD_GEN_PASS_SCOND: return 'C';
|
||||
case RAD_GEN_PASS_SSTEP: return 'S';
|
||||
case RAD_GEN_PASS_SLATENT: return 'L';
|
||||
case RAD_GEN_PASS_SQUERY: return 'Q';
|
||||
default: return '?';
|
||||
}
|
||||
}
|
||||
|
||||
/* Every edge of a closed, consistently wound mesh is in exactly two faces, once each way. */
|
||||
bool watertight(const gen::ShapeMesh& m) {
|
||||
std::map<std::pair<uint32_t, uint32_t>, int> e;
|
||||
for (size_t t = 0; t + 2 < m.f.size(); t += 3)
|
||||
for (int q = 0; q < 3; ++q) ++e[{ m.f[t + q], m.f[t + (q + 1) % 3] }];
|
||||
for (const auto& [k, n] : e) {
|
||||
if (n != 1) return false;
|
||||
auto it = e.find({ k.second, k.first });
|
||||
if (it == e.end() || it->second != 1) return false;
|
||||
}
|
||||
return !e.empty();
|
||||
}
|
||||
|
||||
/* The signed volume of a closed mesh: positive when its faces wind counter-clockwise seen from
|
||||
* outside. */
|
||||
double volume(const gen::ShapeMesh& m) {
|
||||
double v = 0.0;
|
||||
for (size_t t = 0; t + 2 < m.f.size(); t += 3) {
|
||||
const float* a = &m.v[(size_t)m.f[t] * 3];
|
||||
const float* b = &m.v[(size_t)m.f[t + 1] * 3];
|
||||
const float* c = &m.v[(size_t)m.f[t + 2] * 3];
|
||||
v += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) +
|
||||
a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The sampler's grid points are numpy's linspace(0, 1) in f32, the last exactly 1. */
|
||||
TEST(the_sigmas_are_linspace_from_noise_to_the_shape) {
|
||||
const std::vector<float> s = gen::shape_sigmas(50);
|
||||
REQUIRE_EQ(s.size(), (size_t)50);
|
||||
CHECK_EQ(s.front(), 0.0f);
|
||||
CHECK_EQ(s.back(), 1.0f);
|
||||
CHECK_EQ(s[1], (float)(1.0 / 49.0));
|
||||
CHECK_EQ(s[30], (float)(30 * (1.0 / 49.0)));
|
||||
for (size_t i = 1; i < s.size(); ++i) CHECK(s[i] > s[i - 1]);
|
||||
CHECK(gen::shape_sigmas(1).empty());
|
||||
CHECK_EQ(gen::shape_sigmas(2).size(), (size_t)2);
|
||||
}
|
||||
|
||||
/* The grid's levels: halved while at least 63, coarsest first; one level below 63. */
|
||||
TEST(the_grid_levels_halve_down_to_63) {
|
||||
CHECK(gen::shape_levels(256) == (std::vector<int32_t>{ 64, 128, 256 }));
|
||||
CHECK(gen::shape_levels(384) == (std::vector<int32_t>{ 96, 192, 384 }));
|
||||
CHECK(gen::shape_levels(512) == (std::vector<int32_t>{ 64, 128, 256, 512 }));
|
||||
CHECK(gen::shape_levels(63) == (std::vector<int32_t>{ 63 }));
|
||||
CHECK(gen::shape_levels(32) == (std::vector<int32_t>{ 32 }));
|
||||
CHECK(gen::shape_levels(130) == (std::vector<int32_t>{ 65, 130 }));
|
||||
const std::vector<float> a = gen::shape_axis(1.01, 4);
|
||||
REQUIRE_EQ(a.size(), (size_t)5);
|
||||
CHECK_EQ(a[0], -1.01f);
|
||||
CHECK_EQ(a[2], (float)(2 * (2.02 / 4) - 1.01));
|
||||
CHECK_EQ(a[4], 1.01f);
|
||||
}
|
||||
|
||||
/* The finer level samples a shell around the coarse surface and nothing far from it. */
|
||||
TEST(refinement_samples_only_near_the_surface) {
|
||||
const int32_t rp = 32, r = 64;
|
||||
const float radius = 0.5f;
|
||||
const std::vector<float> coarse = sphere_grid(rp, 1.0, radius);
|
||||
for (bool last : { false, true }) {
|
||||
const std::vector<uint32_t> pts = gen::shape_refine(coarse, rp, r, 0.0, last);
|
||||
REQUIRE(!pts.empty());
|
||||
const std::vector<float> ax = gen::shape_axis(1.0, r);
|
||||
const int64_t n = r + 1;
|
||||
double far = 0.0;
|
||||
for (uint32_t p : pts) {
|
||||
const float d = std::fabs(sphere(ax[p / (n * n)], ax[p / n % n], ax[p % n], radius));
|
||||
far = std::max(far, (double)d);
|
||||
}
|
||||
/* Within 0.95 of zero counts as near (the field here is a distance), plus the dilation. */
|
||||
CHECK(far < 0.95 + 4.0 * 2.0 / rp);
|
||||
CHECK((int64_t)pts.size() < n * n * n);
|
||||
/* Every fine cell the surface crosses has all eight corners sampled. */
|
||||
std::vector<char> in((size_t)(n * n * n), 0);
|
||||
for (uint32_t p : pts) in[p] = 1;
|
||||
bool covered = true;
|
||||
for (int64_t i = 0; i + 1 < n && covered; ++i)
|
||||
for (int64_t j = 0; j + 1 < n && covered; ++j)
|
||||
for (int64_t k = 0; k + 1 < n && covered; ++k) {
|
||||
int pos = 0, neg = 0;
|
||||
for (int c = 0; c < 8; ++c) {
|
||||
const float v = sphere(ax[i + (c & 1)], ax[j + (c >> 1 & 1)],
|
||||
ax[k + (c >> 2 & 1)], radius);
|
||||
(v > 0 ? pos : neg)++;
|
||||
}
|
||||
if (!pos || !neg) continue;
|
||||
for (int c = 0; c < 8; ++c)
|
||||
covered = covered &&
|
||||
in[(size_t)(((i + (c & 1)) * n + j + (c >> 1 & 1)) * n + k +
|
||||
(c >> 2 & 1))];
|
||||
}
|
||||
CHECK(covered);
|
||||
}
|
||||
}
|
||||
|
||||
/* Marching cubes over a sphere: a closed surface wound outwards, its vertices on the sphere
|
||||
* (scaled by r / (r + 1), the reference's placement), its volume the ball's. */
|
||||
TEST(marching_cubes_makes_a_closed_outward_sphere) {
|
||||
const int32_t r = 48;
|
||||
const float radius = 0.6f;
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(sphere_grid(r, 1.0, radius), r, 1.0, 0.0, &m);
|
||||
REQUIRE(!m.f.empty());
|
||||
CHECK(watertight(m));
|
||||
const double scale = (double)r / (r + 1);
|
||||
double worst = 0.0;
|
||||
for (size_t i = 0; i + 2 < m.v.size(); i += 3) {
|
||||
const double x = m.v[i] + 1.0 / (r + 1), y = m.v[i + 1] + 1.0 / (r + 1),
|
||||
z = m.v[i + 2] + 1.0 / (r + 1);
|
||||
worst = std::max(worst, std::fabs(std::sqrt(x * x + y * y + z * z) - radius * scale));
|
||||
}
|
||||
CHECK(worst < 2.0 / r);
|
||||
const double ball = 4.0 / 3.0 * M_PI * std::pow(radius * scale, 3);
|
||||
CHECK(volume(m) > 0.0);
|
||||
CHECK(std::fabs(volume(m) - ball) / ball < 0.02);
|
||||
}
|
||||
|
||||
/* Every inside/outside pattern of a cube gives a closed surface: a field of random signs. */
|
||||
TEST(marching_cubes_is_closed_for_every_cube_case) {
|
||||
const int32_t r = 12;
|
||||
const int64_t n = r + 1;
|
||||
std::vector<float> f((size_t)(n * n * n));
|
||||
uint32_t s = 12345;
|
||||
for (float& v : f) {
|
||||
s = s * 1664525u + 1013904223u;
|
||||
v = (float)((s >> 8) & 0xffff) / 65535.0f - 0.5f;
|
||||
}
|
||||
/* A border outside the shape, so the surface closes inside the grid. */
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
for (int64_t k = 0; k < n; ++k)
|
||||
if (!i || !j || !k || i == r || j == r || k == r)
|
||||
f[(size_t)((i * n + j) * n + k)] = -1.0f;
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(f, r, 1.0, 0.0, &m);
|
||||
REQUIRE(!m.f.empty());
|
||||
CHECK(watertight(m));
|
||||
CHECK(volume(m) > 0.0);
|
||||
}
|
||||
|
||||
/* A cube with a corner not sampled makes nothing, and an unsampled grid no surface. */
|
||||
TEST(marching_cubes_skips_unsampled_cubes) {
|
||||
const int32_t r = 16;
|
||||
std::vector<float> f = sphere_grid(r, 1.0, 0.5f);
|
||||
gen::ShapeMesh whole;
|
||||
gen::shape_mesh(f, r, 1.0, 0.0, &whole);
|
||||
std::vector<float> holes = f;
|
||||
const int64_t n = r + 1;
|
||||
holes[(size_t)((8 * n + 8) * n + 4)] = NAN; /* a point on the sphere's surface band */
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(holes, r, 1.0, 0.0, &m);
|
||||
CHECK(m.f.size() < whole.f.size());
|
||||
std::vector<float> none(f.size(), NAN);
|
||||
gen::shape_mesh(none, r, 1.0, 0.0, &m);
|
||||
CHECK(m.f.empty());
|
||||
}
|
||||
|
||||
/* The files: a GLB with its header and chunks sized, and the three others. */
|
||||
TEST(the_mesh_exports_as_glb_obj_ply_and_stl) {
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(sphere_grid(16, 1.0, 0.5f), 16, 1.0, 0.0, &m);
|
||||
REQUIRE(!m.f.empty());
|
||||
std::string bytes, mime, why;
|
||||
CHECK_OK(gen::shape_export(m, "glb", &bytes, &mime, &why));
|
||||
CHECK_EQ(mime, std::string("model/gltf-binary"));
|
||||
REQUIRE(bytes.size() > 28);
|
||||
uint32_t hdr[5];
|
||||
std::memcpy(hdr, bytes.data(), sizeof hdr);
|
||||
CHECK_EQ(hdr[0], 0x46546C67u);
|
||||
CHECK_EQ(hdr[1], 2u);
|
||||
CHECK_EQ(hdr[2], (uint32_t)bytes.size());
|
||||
CHECK_EQ(hdr[3] % 4, 0u);
|
||||
CHECK_EQ(hdr[4], 0x4E4F534Au);
|
||||
uint32_t bin[2];
|
||||
std::memcpy(bin, bytes.data() + 20 + hdr[3], sizeof bin);
|
||||
CHECK_EQ(bin[1], 0x004E4942u);
|
||||
CHECK_EQ((size_t)bin[0], m.v.size() * 4 * 2 + m.f.size() * 4);
|
||||
CHECK_OK(gen::shape_export(m, "obj", &bytes, &mime, &why));
|
||||
CHECK(bytes.rfind("v ", 0) == 0);
|
||||
CHECK_OK(gen::shape_export(m, "ply", &bytes, &mime, &why));
|
||||
CHECK(bytes.rfind("ply\n", 0) == 0);
|
||||
CHECK_OK(gen::shape_export(m, "stl", &bytes, &mime, &why));
|
||||
CHECK_EQ(bytes.size(), (size_t)84 + m.f.size() / 3 * 50);
|
||||
CHECK(gen::shape_export(m, "fbx", &bytes, &mime, &why) < 0);
|
||||
}
|
||||
|
||||
/* The picture: the alpha's box centred on white, normalised, cut into patches; an empty alpha
|
||||
* refused. */
|
||||
TEST(the_picture_is_recentred_on_white_and_cut_into_patches) {
|
||||
const gen::ShapeGenInfo g = info_small();
|
||||
std::vector<float> p;
|
||||
std::string why;
|
||||
CHECK_OK(gen::shape_picture(g, picture(40, 30, 5, 3, 30, 27), &p, &why));
|
||||
REQUIRE_EQ(p.size(), (size_t)(2 * 2 * 3 * 14 * 14));
|
||||
/* The corners are white, (1 - 0.5) / 0.25 = 2 in every channel; the centre the colour. */
|
||||
const float white = (float)((1.0 - 0.5) / 0.25);
|
||||
CHECK_NEAR(p[0], white, 1e-3);
|
||||
CHECK_NEAR(p[(size_t)(2 * 14 * 14)], white, 1e-3); /* blue, pixel (0, 0) */
|
||||
const int64_t pd = 3 * 14 * 14;
|
||||
/* Patch (1, 1) holds pixels (14.., 14..); its first pixel, red channel, is the box's colour. */
|
||||
CHECK_NEAR(p[(size_t)(3 * pd)], (float)((200.0 / 255.0 - 0.5) / 0.25), 0.1);
|
||||
CHECK(gen::shape_picture(g, picture(20, 20, 0, 0, 0, 0), &p, &why) < 0);
|
||||
CHECK(gen::shape_picture(g, picture(20, 20, 5, 5, 6, 15), &p, &why) < 0);
|
||||
}
|
||||
|
||||
/* A request runs its picture, its steps, the latent, then the grid level by level; the field the
|
||||
* ticket hands back meshes into the sphere the queries were answered with. */
|
||||
TEST(a_request_runs_cond_steps_latent_and_the_grid_levels) {
|
||||
ShapeFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
auto r = f.req(4, 128);
|
||||
REQUIRE(r != nullptr);
|
||||
auto t = r->ticket;
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
CHECK_EQ(t->steps, 3);
|
||||
CHECK_EQ(t->resolution, 128);
|
||||
std::string kinds;
|
||||
const std::vector<float> sig = gen::shape_sigmas(4);
|
||||
int steps = 0;
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadShapeGenBatch* S = b->sgen_b;
|
||||
REQUIRE(S != nullptr);
|
||||
kinds += kind_of(b->gen);
|
||||
CHECK_EQ(S->lanes[0], S->lane);
|
||||
CHECK_EQ(S->lat_cu[2], 16);
|
||||
if (b->gen == RAD_GEN_PASS_SCOND) CHECK_EQ(b->n_tok, (int64_t)4);
|
||||
if (b->gen == RAD_GEN_PASS_SSTEP) {
|
||||
CHECK_EQ(b->n_tok, (int64_t)26);
|
||||
CHECK_EQ(S->sigma[0], sig[(size_t)steps]);
|
||||
CHECK_EQ(S->sigma_next[0], sig[(size_t)steps + 1]);
|
||||
CHECK_EQ(S->cfg[0], 5.0f);
|
||||
CHECK_EQ(S->pair[0], 1);
|
||||
CHECK_EQ(S->pair[1], -2);
|
||||
CHECK_EQ(S->flags[0], steps == 0 ? (int32_t)RAD_GEN_F_FIRST : 0);
|
||||
CHECK_EQ(S->flags[1], 0);
|
||||
CHECK_EQ(S->seed[0], 7u);
|
||||
++steps;
|
||||
}
|
||||
if (b->gen == RAD_GEN_PASS_SQUERY) {
|
||||
CHECK(S->n_query > 0 && S->n_query <= 4096);
|
||||
CHECK_EQ(S->query_cu[1], (int32_t)S->n_query);
|
||||
f.answer(b, 0.5f);
|
||||
}
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
/* 65^3 coarse points in passes of 4096, then the finer level's shell. */
|
||||
REQUIRE(kinds.size() > 5);
|
||||
CHECK_EQ(kinds.substr(0, 5), std::string("CSSSL"));
|
||||
CHECK(kinds.find_first_not_of('Q', 5) == std::string::npos);
|
||||
CHECK((int64_t)(kinds.size() - 5) >= (65 * 65 * 65 + 4095) / 4096);
|
||||
REQUIRE(t->finished());
|
||||
CHECK_OK(t->status());
|
||||
int32_t res = 0;
|
||||
std::vector<float> field = t->take_field(&res);
|
||||
CHECK_EQ(res, 128);
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(field, res, 1.0, 0.0, &m);
|
||||
REQUIRE(!m.f.empty());
|
||||
CHECK(watertight(m));
|
||||
CHECK(volume(m) > 0.0);
|
||||
/* Hierarchical sampling queried far fewer points than the dense grid has. */
|
||||
CHECK(t->points > 65 * 65 * 65);
|
||||
CHECK(t->points < (int64_t)129 * 129 * 129 / 4);
|
||||
}
|
||||
|
||||
/* Dense sampling queries every point of the finest grid, in one level. */
|
||||
TEST(dense_sampling_queries_every_point_once) {
|
||||
ShapeFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
auto r = f.req(2, 20);
|
||||
REQUIRE(r != nullptr);
|
||||
r->dense = true;
|
||||
auto t = r->ticket;
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
if (b->gen == RAD_GEN_PASS_SQUERY) f.answer(b, 0.5f);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
REQUIRE(t->finished());
|
||||
CHECK_EQ(t->points, (int64_t)21 * 21 * 21);
|
||||
}
|
||||
|
||||
/* What a request may not name is refused at submit, with the range. */
|
||||
TEST(a_request_out_of_range_is_refused_at_submit) {
|
||||
ShapeFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(9);
|
||||
CHECK(f.drv.submit(std::move(r), &why) < 0);
|
||||
CHECK(why.find("num_inference_steps") != std::string::npos);
|
||||
r = f.req(4, 200);
|
||||
CHECK(f.drv.submit(std::move(r), &why) < 0);
|
||||
CHECK(why.find("octree_resolution") != std::string::npos);
|
||||
r = f.req(4);
|
||||
r->guidance = -1.0;
|
||||
CHECK(f.drv.submit(std::move(r), &why) < 0);
|
||||
r = f.req(4);
|
||||
r->patches.pop_back();
|
||||
CHECK(f.drv.submit(std::move(r), &why) < 0);
|
||||
}
|
||||
|
||||
/* A field that crosses the level nowhere finishes after the coarsest level. */
|
||||
TEST(a_field_without_a_surface_ends_after_its_first_level) {
|
||||
ShapeFixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
auto r = f.req(2, 128);
|
||||
auto t = r->ticket;
|
||||
std::string why;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
int queries = 0;
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
if (b->gen == RAD_GEN_PASS_SQUERY) {
|
||||
f.answer(b, -5.0f); /* a sphere of negative radius: outside everywhere */
|
||||
++queries;
|
||||
}
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
REQUIRE(t->finished());
|
||||
CHECK_EQ(queries, (65 * 65 * 65 + 4095) / 4096);
|
||||
int32_t res = 0;
|
||||
gen::ShapeMesh m;
|
||||
gen::shape_mesh(t->take_field(&res), res, 1.0, 0.0, &m);
|
||||
CHECK(m.f.empty());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,217 @@
|
||||
/* tests/shapes_test.cpp -- Hunyuan3D-2's API over a shape generator (core/server/shapes.cpp).
|
||||
*
|
||||
* The generator is faked here: it finishes every request on submit with a sphere's field on the
|
||||
* request's grid, so these pin what the server owns: which requests are refused and under which
|
||||
* field, the request it hands the generator (the prepared picture, the steps, the resolution, the
|
||||
* guidance, the seed), the mesh file /generate answers with, and the background job seen through
|
||||
* /send and /status.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
|
||||
#include "gen/shape.h"
|
||||
#include "mm/media.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
|
||||
struct FakeShapeGen : IShapeGen {
|
||||
gen::ShapeGenInfo inf;
|
||||
int finish_status = RAD_OK;
|
||||
std::string finish_why;
|
||||
/* What each request asked, kept after the request itself goes. */
|
||||
struct Seen {
|
||||
int32_t steps, resolution;
|
||||
double guidance;
|
||||
uint64_t seed;
|
||||
bool dense;
|
||||
size_t n;
|
||||
};
|
||||
std::vector<Seen> got;
|
||||
mutable std::mutex got_m;
|
||||
|
||||
FakeShapeGen() {
|
||||
RadShapeGenDecl d{};
|
||||
d.canvas = 32;
|
||||
d.border_ratio = 0.15;
|
||||
d.enc_size = 28;
|
||||
d.enc_patch = 14;
|
||||
for (int c = 0; c < 3; ++c) { d.pix_mean[c] = 0.5; d.pix_std[c] = 0.25; }
|
||||
d.default_steps = 50;
|
||||
d.max_steps = 200;
|
||||
d.default_guidance = 5.0;
|
||||
d.bounds = 1.01;
|
||||
d.level = 0.0;
|
||||
d.default_resolution = 24;
|
||||
d.min_resolution = 8;
|
||||
d.max_resolution = 48;
|
||||
d.max_lanes = 2;
|
||||
inf = gen::shape_info(d, "fake-shape");
|
||||
}
|
||||
const gen::ShapeGenInfo& info() const override { return inf; }
|
||||
int submit(std::unique_ptr<gen::ShapeRequest> r, std::string*) override {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
const int32_t res = r->resolution > 0 ? r->resolution : (int32_t)inf.default_resolution;
|
||||
got.push_back({ r->steps, r->resolution, r->guidance, r->seed, r->dense,
|
||||
r->patches.size() });
|
||||
gen::ShapeTicket& t = *r->ticket;
|
||||
t.steps = (r->steps > 0 ? r->steps : 50) - 1;
|
||||
t.resolution = res;
|
||||
if (finish_status == RAD_OK) {
|
||||
const std::vector<float> ax = gen::shape_axis(inf.bounds, res);
|
||||
const int64_t n = (int64_t)res + 1;
|
||||
std::vector<float> f((size_t)(n * n * n));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
const float x = ax[(size_t)i], y = ax[(size_t)j], z = ax[(size_t)k];
|
||||
f[(size_t)((i * n + j) * n + k)] = 0.5f - std::sqrt(x * x + y * y + z * z);
|
||||
}
|
||||
t.set_field(std::move(f), res);
|
||||
}
|
||||
t.finish(finish_status, finish_why);
|
||||
return RAD_OK;
|
||||
}
|
||||
int64_t queued() const override { return 0; }
|
||||
int64_t running() const override { return 0; }
|
||||
Seen last() const {
|
||||
std::lock_guard<std::mutex> lk(got_m);
|
||||
return got.back();
|
||||
}
|
||||
};
|
||||
|
||||
/* A 16 x 16 PNG, opaque inside [4, 12)^2 and transparent around it, as base64. */
|
||||
std::string picture_b64(bool opaque_anywhere = true) {
|
||||
std::vector<uint8_t> px((size_t)16 * 16 * 4, 0);
|
||||
for (int y = 4; y < 12 && opaque_anywhere; ++y)
|
||||
for (int x = 4; x < 12; ++x) {
|
||||
uint8_t* p = &px[((size_t)y * 16 + x) * 4];
|
||||
p[0] = 30; p[1] = 120; p[2] = 220; p[3] = 255;
|
||||
}
|
||||
std::vector<uint8_t> file;
|
||||
std::string why;
|
||||
if (mm::encode_image(px.data(), 16, 16, 4, "png", 0, &file, &why) < 0) return "";
|
||||
return base64_encode(file.data(), file.size());
|
||||
}
|
||||
|
||||
struct Shapes {
|
||||
FakeShapeGen gen;
|
||||
std::unique_ptr<Fixture> f;
|
||||
Shapes() {
|
||||
f.reset(new Fixture(Fixture::Tweak{ [this](ServerOptions& o, Deps& d) {
|
||||
d.shapes = &gen;
|
||||
o.shape_model = true;
|
||||
} }));
|
||||
}
|
||||
static json body(json extra = json::object()) {
|
||||
json b = { { "image", picture_b64() } };
|
||||
for (auto it = extra.begin(); it != extra.end(); ++it) b[it.key()] = it.value();
|
||||
return b;
|
||||
}
|
||||
HttpResponse generate(const json& b) { return f->post("/generate", b.dump()); }
|
||||
std::string refused(const json& b, int status = 400) {
|
||||
HttpResponse r = generate(b);
|
||||
CHECK_EQ(r.status, status);
|
||||
return str_at(json::parse(r.body, nullptr, false)["error"], "param");
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A request that cannot be served is a 400 naming its field before anything is queued. */
|
||||
TEST(a_shape_request_that_cannot_be_served_names_its_field) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Shapes s;
|
||||
CHECK_EQ(s.refused(json::object()), std::string("image"));
|
||||
CHECK_EQ(s.refused({ { "image", "not base64 !" } }), std::string("image"));
|
||||
CHECK_EQ(s.refused({ { "image", picture_b64(false) } }), std::string("image"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "texture", true } })), std::string("texture"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "text", "a penguin" } })), std::string("text"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "mesh", "Z2xURg==" } })), std::string("mesh"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "type", "fbx" } })), std::string("type"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "num_inference_steps", 1 } })),
|
||||
std::string("num_inference_steps"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "octree_resolution", 4096 } })),
|
||||
std::string("octree_resolution"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "guidance_scale", -1 } })), std::string("guidance_scale"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "volume_decoding", "flashvdm" } })),
|
||||
std::string("volume_decoding"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "mc_algo", "dmc" } })), std::string("mc_algo"));
|
||||
CHECK_EQ(s.refused(Shapes::body({ { "temperature", 1 } })), std::string("temperature"));
|
||||
CHECK_EQ(s.gen.got.size(), (size_t)0);
|
||||
}
|
||||
|
||||
/* The generator gets the prepared picture and the request's numbers; the answer is the mesh as
|
||||
* the file `type` names. */
|
||||
TEST(generate_answers_with_the_mesh_file) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Shapes s;
|
||||
HttpResponse r = s.generate(Shapes::body({ { "num_inference_steps", 30 },
|
||||
{ "octree_resolution", 32 },
|
||||
{ "guidance_scale", 7.5 }, { "seed", 99 },
|
||||
{ "face_count", 40000 }, { "mc_algo", "mc" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(r.content_type, std::string("model/gltf-binary"));
|
||||
REQUIRE(r.body.size() > 12);
|
||||
CHECK_EQ(r.body.substr(0, 4), std::string("glTF"));
|
||||
const FakeShapeGen::Seen q = s.gen.last();
|
||||
CHECK_EQ(q.steps, 30);
|
||||
CHECK_EQ(q.resolution, 32);
|
||||
CHECK_EQ(q.guidance, 7.5);
|
||||
CHECK_EQ(q.seed, (uint64_t)99);
|
||||
CHECK(!q.dense);
|
||||
CHECK_EQ(q.n, (size_t)(2 * 2 * 3 * 14 * 14));
|
||||
/* The reference's defaults: seed 1234, the model's steps and resolution. */
|
||||
r = s.generate(Shapes::body({ { "type", "obj" }, { "volume_decoding", "dense" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(r.content_type, std::string("model/obj"));
|
||||
CHECK(r.body.rfind("v ", 0) == 0);
|
||||
CHECK_EQ(s.gen.last().seed, (uint64_t)1234);
|
||||
CHECK_EQ(s.gen.last().steps, 0);
|
||||
CHECK(s.gen.last().dense);
|
||||
}
|
||||
|
||||
/* A failed shape is the generator's reason, not a file. */
|
||||
TEST(a_failed_shape_reports_the_reason) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Shapes s;
|
||||
s.gen.finish_status = RAD_E_STATE;
|
||||
s.gen.finish_why = "the engine stopped";
|
||||
HttpResponse r = s.generate(Shapes::body());
|
||||
CHECK(r.status >= 400);
|
||||
CHECK(r.body.find("the engine stopped") != std::string::npos);
|
||||
}
|
||||
|
||||
/* /send queues the shape and answers with its uid; /status reports it until the file is in
|
||||
* `model_base64`, and an unknown uid is a 404. */
|
||||
TEST(send_and_status_make_the_shape_in_the_background) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Shapes s;
|
||||
HttpResponse r = s.f->post("/send", Shapes::body({ { "type", "stl" } }).dump());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const std::string uid = str_at(json::parse(r.body, nullptr, false), "uid");
|
||||
REQUIRE(!uid.empty());
|
||||
json o;
|
||||
for (int i = 0; i < 400; ++i) {
|
||||
o = json::parse(s.f->get(("/status/" + uid).c_str()).body, nullptr, false);
|
||||
if (str_at(o, "status") != "processing") break;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
REQUIRE_EQ(str_at(o, "status"), std::string("completed"));
|
||||
std::vector<uint8_t> file;
|
||||
REQUIRE(base64_decode(str_at(o, "model_base64"), &file));
|
||||
CHECK(file.size() > 84);
|
||||
CHECK_EQ(s.f->get("/status/shape_nope").status, 404);
|
||||
}
|
||||
|
||||
/* A model that makes no shapes answers the routes with a 501. */
|
||||
TEST(the_shape_routes_need_a_shape_model) {
|
||||
Fixture f;
|
||||
CHECK_EQ(f.post("/generate", "{}").status, 501);
|
||||
CHECK_EQ(f.post("/send", "{}").status, 501);
|
||||
CHECK_EQ(f.get("/status/x").status, 501);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -262,6 +262,38 @@ TEST(a_stacked_vector_is_cut_in_every_part) {
|
||||
CHECK(why.find("declared parts") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A vector's parts may differ in width: a Mamba convolution's bias is [x | B | C], and a rank takes
|
||||
* its heads' x and its groups' B and C. The parts lie end to end as one row of the share. */
|
||||
TEST(a_stacked_vector_may_have_parts_of_different_widths) {
|
||||
const RadEncoding e = rad_enc_plain(RAD_BF16);
|
||||
WeightInfo w;
|
||||
w.enc = e;
|
||||
w.enc_known = true;
|
||||
w.decl.shard = RAD_SHARD_ROW;
|
||||
w.decl.rank = 1;
|
||||
w.decl.shape[0] = 12;
|
||||
w.decl.n_row_parts = 3;
|
||||
w.decl.row_parts[0] = 8;
|
||||
w.decl.row_parts[1] = 2;
|
||||
w.decl.row_parts[2] = 2;
|
||||
w.n_sel = 1;
|
||||
w.sel[0] = 0;
|
||||
w.sel_rows[0] = 1;
|
||||
w.sel_cols[0] = 12;
|
||||
/* entry [24]: x 0..15, B 16..19, C 20..23; rank 1 owns x 8..15, B 18..19 and C 22..23 */
|
||||
const int64_t shape[1] = { 24 };
|
||||
PlaneShare s[RAD_ENC_MAX_PLANES];
|
||||
REQUIRE_EQ(weight_share(w, e, 1, shape, 2, 1, s, nullptr), RAD_OK);
|
||||
REQUIRE_EQ(s[0].rects.size(), (size_t)3);
|
||||
CHECK_EQ(s[0].rects[0].byte0, (int64_t)(8 * 2));
|
||||
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(8 * 2));
|
||||
CHECK_EQ(s[0].rects[1].byte0, (int64_t)(18 * 2));
|
||||
CHECK_EQ(s[0].rects[1].bytes, (int64_t)(2 * 2));
|
||||
CHECK_EQ(s[0].rects[2].byte0, (int64_t)(22 * 2));
|
||||
CHECK_EQ(s[0].rects[2].bytes, (int64_t)(2 * 2));
|
||||
CHECK_EQ(s[0].dense_bytes(), (int64_t)(12 * 2));
|
||||
}
|
||||
|
||||
/* A reshape: a conv kernel [O, C, T, H, W] declared as the [O, C*T*H*W] matrix it is. The bytes
|
||||
* do not move, so the share is the whole plane in the declared view; a shard of a reshape would
|
||||
* be a different cut, so it is refused. */
|
||||
|
||||
@@ -90,17 +90,18 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second);
|
||||
}
|
||||
const std::set<std::pair<std::string, std::string>> want = {
|
||||
{ "anima", "" }, { "breeze", "" }, { "clef", "" }, { "clef", "fp8_e4m3" },
|
||||
{ "embeddinggemma2", "" },
|
||||
{ "anima", "" }, { "bailinghybrid", "" }, { "breeze", "" }, { "clef", "" },
|
||||
{ "clef", "fp8_e4m3" }, { "embeddinggemma2", "" },
|
||||
{ "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" },
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
|
||||
{ "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
|
||||
{ "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
|
||||
{ "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "sdxl", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },
|
||||
{ "spark25", "" }, { "spark25", "w8a8_fwht128" }, { "sdxl", "" },
|
||||
{ "unlimitedocr", "" } };
|
||||
std::set<std::pair<std::string, std::string>> got;
|
||||
for (const auto& [k, name] : keys) got.insert(k);
|
||||
|
||||
@@ -0,0 +1,869 @@
|
||||
/* Spark's declaration and step, without a GPU or checkpoint. */
|
||||
#define RAD_ARCH_NO_EXPORTS 1
|
||||
#include "arch_fakes.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "../arch/spark25_bf16/spark25_bf16.cpp"
|
||||
#include "../arch/spark25_w8a8/spark25_w8a8.cpp"
|
||||
|
||||
using namespace rad_fake;
|
||||
|
||||
static MetaKV spark_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "spark25";
|
||||
m.n_layers = 4;
|
||||
m.n_embd = 2560;
|
||||
m.n_head = 16;
|
||||
m.n_head_kv = 4;
|
||||
m.head_dim = 256;
|
||||
m.n_ff = 10240;
|
||||
m.n_vocab = 131072;
|
||||
m.n_ctx_train = 1048576;
|
||||
m.rms_eps = 1e-6f;
|
||||
m.rope_theta = 10000;
|
||||
MetaKV k(m);
|
||||
k.set("tie_word_embeddings", "1").set("headwise_attn_output_gate", "1")
|
||||
.set("gate_attn_act_mode", "sigmoid").set("hidden_act", "gelu")
|
||||
.set("layer_types", "sliding_attention sliding_attention sliding_attention full_attention")
|
||||
.set("sliding_window", "512")
|
||||
.set("rope_parameters.sliding_attention.rope_theta", "10000")
|
||||
.set("rope_parameters.sliding_attention.partial_rotary_factor", "1")
|
||||
.set("rope_parameters.full_attention.rope_theta", "5000000")
|
||||
.set("rope_parameters.full_attention.partial_rotary_factor", "0.25");
|
||||
return k;
|
||||
}
|
||||
|
||||
TEST(layer_schedule_rope_and_window_follow_the_checkpoint) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
CHECK(spark25_bf16::chat_format(k.meta()) != nullptr);
|
||||
REQUIRE_EQ(count_op(b, "attn_paged"), 4);
|
||||
REQUIRE_EQ(count_op(b, "rope"), 8);
|
||||
REQUIRE_EQ(b.binds.size(), (size_t)4);
|
||||
for (int l = 0; l < 4; ++l) {
|
||||
const RecOp* a = find_op(b, "attn_paged", l);
|
||||
const RecOp* q = find_op(b, "rope", 2*l);
|
||||
const RecOp* key = find_op(b, "rope", 2*l+1);
|
||||
REQUIRE(a && q && key);
|
||||
CHECK_EQ(pint(a, "window"), l == 3 ? 0 : 512);
|
||||
CHECK_EQ(pint(a, "gqa"), 4);
|
||||
CHECK_EQ(pint(q, "rotary_dim"), l == 3 ? 64 : 256);
|
||||
CHECK_EQ(pint(key, "rotary_dim"), l == 3 ? 64 : 256);
|
||||
CHECK_EQ(pflt(q, "theta"), l == 3 ? 5000000.0 : 10000.0);
|
||||
CHECK_EQ(pflt(key, "theta"), pflt(q, "theta"));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(uses_fp32_residual_exact_gelu_and_one_sigmoid_per_head) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
const RecBuf* x = find_b(b, "x");
|
||||
REQUIRE(x);
|
||||
CHECK_EQ(x->d.dtype, (uint32_t)RAD_F32);
|
||||
CHECK_EQ(count_op(b, "sigmoid"), 4);
|
||||
CHECK_EQ(count_op(b, "scale_rows"), 4);
|
||||
CHECK_EQ(count_op(b, "act_mul"), 4);
|
||||
for (int l = 0; l < 4; ++l) {
|
||||
CHECK_EQ(pstr(find_op(b, "act_mul", l), "act"), std::string("gelu"));
|
||||
CHECK_EQ(pint(find_op(b, "scale_rows", l), "n"), 256);
|
||||
CHECK_EQ(pstr(find_op(b, "scale_rows", l), "act"), std::string("none"));
|
||||
}
|
||||
for (const auto& o : b.ops) if (o.resolved) CHECK(o.uses_declared);
|
||||
for (const auto& w : b.weights) if (!w.d.source) CHECK(find_map(b, w.name) != nullptr);
|
||||
}
|
||||
|
||||
TEST(prefill_and_decode_issue_a_liveness_safe_graph) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
for (int n : {1, 8}) {
|
||||
RadBatch batch = decode_batch();
|
||||
batch.n_tok = n;
|
||||
batch.max_q_len = n;
|
||||
RadCtx c{.b = &b, .batch = &batch};
|
||||
spark25_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(tensor_parallel_covers_heads_and_ffn_without_changing_gqa) {
|
||||
for (int world = 1; world <= 8; ++world) {
|
||||
std::vector<int> query_owners(16, 0), ffn_owners(10240, 0), vocab_owners(131072, 0);
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = world;
|
||||
ctx.rank = rank;
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
const auto& g = spark25_bf16::models[rank].g;
|
||||
const RecWeight* q = find_w(b, "blk.0.attn_q.weight");
|
||||
const RecWeight* key = find_w(b, "blk.0.attn_k.weight");
|
||||
const RecWeight* gate = find_w(b, "blk.0.attn_gate.weight");
|
||||
const RecWeight* out = find_w(b, "blk.0.attn_output.weight");
|
||||
const RecWeight* gu = find_w(b, "blk.0.ffn_gate_up.weight");
|
||||
const RecWeight* down = find_w(b, "blk.0.ffn_down.weight");
|
||||
const RecWeight* tok = find_w(b, "token_embd.weight");
|
||||
REQUIRE(q && key && gate && out && gu && down && tok);
|
||||
CHECK_EQ(q->d.shard, RAD_SHARD_ROW);
|
||||
CHECK_EQ(gate->d.shard, RAD_SHARD_ROW);
|
||||
CHECK_EQ(out->d.shard, RAD_SHARD_COL);
|
||||
CHECK_EQ(gu->d.shard, RAD_SHARD_ROW);
|
||||
CHECK_EQ(down->d.shard, RAD_SHARD_COL);
|
||||
CHECK_EQ(gu->d.n_row_parts, 2);
|
||||
CHECK_EQ(gu->d.row_parts[0], g.n_ff);
|
||||
CHECK_EQ(gu->d.row_parts[1], g.n_ff);
|
||||
const int64_t q0 = q->span_set ? q->span_lo / g.head_dim : rank * g.n_head;
|
||||
const int64_t k0 = key->span_set ? key->span_lo / g.head_dim : rank * g.n_head_kv;
|
||||
const int64_t f0 = gu->span_set ? gu->span_lo : rank * g.n_ff;
|
||||
const int64_t v0 = tok->span_set ? tok->span_lo : rank * g.n_vocab;
|
||||
CHECK_EQ(gate->span_set ? gate->span_lo : rank * g.n_head, q0);
|
||||
CHECK_EQ(out->span_set ? out->span_lo : rank * g.q_dim(), q0 * g.head_dim);
|
||||
CHECK_EQ(down->span_set ? down->span_lo : rank * g.n_ff, f0);
|
||||
CHECK_EQ(v0, g.vocab_off);
|
||||
for (int64_t h = 0; h < g.n_head; ++h) {
|
||||
REQUIRE(q0 + h < (int64_t)query_owners.size());
|
||||
++query_owners[(size_t)(q0 + h)];
|
||||
CHECK_EQ(k0 + h / g.gqa(), (q0 + h) / 4);
|
||||
}
|
||||
for (int64_t i = 0; i < g.n_ff; ++i) ++ffn_owners[(size_t)(f0 + i)];
|
||||
for (int64_t i = 0; i < g.n_vocab; ++i) ++vocab_owners[(size_t)(v0 + i)];
|
||||
CHECK_EQ(count_op(b, "all_reduce"), world == 1 ? 0 : 9);
|
||||
int reductions = 0;
|
||||
for (const auto& op : b.ops) if (op.op == "all_reduce") {
|
||||
CHECK_EQ(pstr(&op, "dtype"), std::string(reductions++ == 0 ? "fp32" : "bf16"));
|
||||
CHECK_EQ(pint(&op, "exact"), 1);
|
||||
CHECK_EQ(pint(&op, "world_size"), world);
|
||||
}
|
||||
RadBatch batch = decode_batch();
|
||||
batch.n_tok = batch.max_q_len = 8;
|
||||
RadCtx c{.b = &b, .batch = &batch, .rank = rank, .world = world};
|
||||
spark25_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
}
|
||||
CHECK(std::all_of(query_owners.begin(), query_owners.end(), [](int n) { return n == 1; }));
|
||||
CHECK(std::all_of(ffn_owners.begin(), ffn_owners.end(), [](int n) { return n == 1; }));
|
||||
CHECK(std::all_of(vocab_owners.begin(), vocab_owners.end(), [](int n) { return n == 1; }));
|
||||
}
|
||||
}
|
||||
|
||||
static void spark_iq8r_encodings(RadBuilder& b, bool rotated = true) {
|
||||
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
|
||||
if (rotated) rad_enc_copy_str(e.transform, "fwht128");
|
||||
for (const char* name : {"attn_q.weight", "attn_k.weight", "attn_v.weight",
|
||||
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight"})
|
||||
b.encs.emplace_back(name, e);
|
||||
b.encs.emplace_back("output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128));
|
||||
}
|
||||
|
||||
TEST(iq8r_graph_uses_rotated_codes_and_is_liveness_safe) {
|
||||
for (int world = 1; world <= 8; ++world) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
MetaKV k = spark_meta();
|
||||
k.m.quant = "w8a8_fwht128";
|
||||
k.set("quantization_config.quant_method", "w8a8")
|
||||
.set("quantization_config.fmt", "fwht128");
|
||||
RadBuilder b;
|
||||
spark_iq8r_encodings(b);
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = world;
|
||||
ctx.rank = rank;
|
||||
REQUIRE_EQ(spark25_w8a8::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
int quantized = 0;
|
||||
for (const auto& op : b.ops) if (op.op == "gemm_nt_q") {
|
||||
CHECK_EQ(pstr(&op, "dtype"), std::string("i8a8h"));
|
||||
++quantized;
|
||||
}
|
||||
CHECK_EQ(quantized, 24); /* six linears x four layers */
|
||||
CHECK_EQ(count_op(b, "all_reduce"), world == 1 ? 0 : 9);
|
||||
for (int n : {1, 8}) {
|
||||
RadBatch batch = decode_batch();
|
||||
batch.n_tok = batch.max_q_len = n;
|
||||
RadCtx c{.b = &b, .batch = &batch, .rank = rank, .world = world};
|
||||
spark25_w8a8::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(iq8r_rejects_unrotated_weights_and_missing_collectives) {
|
||||
MetaKV k = spark_meta();
|
||||
k.m.quant = "w8a8_fwht128";
|
||||
k.set("quantization_config.quant_method", "w8a8")
|
||||
.set("quantization_config.fmt", "fwht128");
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
RadBuilder unrotated;
|
||||
spark_iq8r_encodings(unrotated, false);
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&unrotated, k.meta(), &ctx); }),
|
||||
RAD_E_DTYPE);
|
||||
RadBuilder missing;
|
||||
spark_iq8r_encodings(missing);
|
||||
missing.refuse.insert("all_reduce");
|
||||
ctx.world_size = 2;
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&missing, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
TEST(iq8r_refuses_containers_with_a_different_format) {
|
||||
for (const auto& [method, fmt] : {std::pair{"w8a8", "fwht64"},
|
||||
std::pair{"fp8", "fwht128"}}) {
|
||||
MetaKV k = spark_meta();
|
||||
k.m.quant = "w8a8_fwht128";
|
||||
k.set("quantization_config.quant_method", method)
|
||||
.set("quantization_config.fmt", fmt);
|
||||
RadBuilder b;
|
||||
spark_iq8r_encodings(b);
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(tp_rejects_missing_all_reduce_instead_of_skipping_it) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
b.refuse.insert("all_reduce");
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = 2;
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
|
||||
/* No collective is required for single-device inference. */
|
||||
RadBuilder single;
|
||||
single.refuse.insert("all_reduce");
|
||||
ctx.world_size = 1;
|
||||
CHECK_EQ(spark25_bf16::declare(&single, k.meta(), &ctx), RAD_OK);
|
||||
}
|
||||
|
||||
TEST(tp_projection_rounds_to_bf16_before_the_fp32_residual_add) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = 2;
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
const auto& m = spark25_bf16::models[0];
|
||||
RadBatch batch = decode_batch();
|
||||
RadCtx c{.b = &b, .batch = &batch, .world = 2};
|
||||
spark25_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
REQUIRE(c.step_fail.empty());
|
||||
|
||||
/* Both partials are exactly bf16. Their sum is halfway between 1 and the next bf16 value,
|
||||
* so the merged projection must round to 1. The residual's low bits must survive the add. */
|
||||
constexpr float partial = 0.5f, peer = 0.50390625f, residual = 0.0009765625f;
|
||||
const float merged = rad_bf16_to_f32(rad_f32_to_bf16(partial + peer));
|
||||
REQUIRE_EQ(merged, 1.0f);
|
||||
auto rounded = [&](rad_buf buf, float value) {
|
||||
const uint32_t dtype = b.bufs.at(buf - 1).d.dtype;
|
||||
CHECK(dtype == RAD_BF16 || dtype == RAD_F32);
|
||||
return dtype == RAD_BF16 ? rad_bf16_to_f32(rad_f32_to_bf16(value)) : value;
|
||||
};
|
||||
for (const auto& layer : m.layers) {
|
||||
for (const auto& tail : {std::pair{layer.op, layer.add_attn},
|
||||
std::pair{layer.dp, layer.add_ffn}}) {
|
||||
std::map<rad_buf, float> values{{m.h, partial}, {m.x, residual}};
|
||||
bool active = false, added = false;
|
||||
int reductions = 0;
|
||||
/* Evaluate one channel of the tail the real step issued, not a separately spelled
|
||||
* cast/reduce/add sequence. The collective's peer contributes its projection shard. */
|
||||
for (const auto& issue : c.issues) {
|
||||
if (!active) { active = issue.op == tail.first; continue; }
|
||||
const RecOp* op = b.op_of(issue.op);
|
||||
REQUIRE(op != nullptr);
|
||||
REQUIRE_EQ(op->writes.size(), (size_t)1);
|
||||
REQUIRE(!op->reads.empty());
|
||||
REQUIRE(values.count(op->reads[0]) != 0);
|
||||
float value = values.at(op->reads[0]);
|
||||
if (op->op == "all_reduce") {
|
||||
CHECK_EQ(rad_dtype_parse(pstr(op, "dtype").c_str()),
|
||||
b.bufs.at(op->writes[0] - 1).d.dtype);
|
||||
value += peer;
|
||||
++reductions;
|
||||
} else if (op->op == "add") {
|
||||
REQUIRE_EQ(op->reads.size(), (size_t)2);
|
||||
REQUIRE(values.count(op->reads[1]) != 0);
|
||||
value += values.at(op->reads[1]);
|
||||
} else {
|
||||
REQUIRE_EQ(op->op, std::string("cast"));
|
||||
}
|
||||
values[op->writes[0]] = rounded(op->writes[0], value);
|
||||
if (issue.op == tail.second) { added = true; break; }
|
||||
}
|
||||
REQUIRE(added);
|
||||
CHECK_EQ(reductions, 1);
|
||||
CHECK_EQ(values.at(m.x), residual + merged);
|
||||
CHECK(values.at(m.x) != residual + partial + peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(tp2_refuses_without_the_exact_fp32_embedding_collective) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
b.refuse_dtype.insert({"all_reduce", "fp32"});
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = 2;
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
REQUIRE_EQ(count_op(b, "all_reduce"), 1);
|
||||
const RecOp* embedding = find_op(b, "all_reduce");
|
||||
REQUIRE(embedding);
|
||||
CHECK_EQ(pstr(embedding, "dtype"), std::string("fp32"));
|
||||
CHECK_EQ(pint(embedding, "exact"), 1);
|
||||
CHECK_EQ(pint(embedding, "world_size"), 2);
|
||||
CHECK(!embedding->resolved);
|
||||
}
|
||||
|
||||
TEST(tp2_refuses_without_the_exact_bf16_projection_collective) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
b.refuse_dtype.insert({"all_reduce", "bf16"});
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.world_size = 2;
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
REQUIRE_EQ(count_op(b, "all_reduce"), 3);
|
||||
const RecOp* embedding = find_op(b, "all_reduce");
|
||||
const RecOp* attn = find_op(b, "all_reduce", 1);
|
||||
const RecOp* ffn = find_op(b, "all_reduce", 2);
|
||||
REQUIRE(embedding && attn && ffn);
|
||||
CHECK_EQ(pstr(embedding, "dtype"), std::string("fp32"));
|
||||
CHECK(embedding->resolved);
|
||||
CHECK_EQ(pstr(attn, "dtype"), std::string("bf16"));
|
||||
CHECK_EQ(pstr(ffn, "dtype"), std::string("bf16"));
|
||||
CHECK_EQ(pint(attn, "exact"), 1);
|
||||
CHECK_EQ(pint(ffn, "exact"), 1);
|
||||
CHECK_EQ(pint(attn, "world_size"), 2);
|
||||
CHECK_EQ(pint(ffn, "world_size"), 2);
|
||||
CHECK(!attn->resolved);
|
||||
CHECK(!ffn->resolved);
|
||||
}
|
||||
|
||||
TEST(tp1_works_without_collectives) {
|
||||
MetaKV k = spark_meta();
|
||||
RadBuilder b;
|
||||
b.refuse.insert("all_reduce");
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
CHECK_EQ(count_op(b, "all_reduce"), 0);
|
||||
const auto& m = spark25_bf16::models[ctx.rank];
|
||||
CHECK_EQ(m.reduce_embed, (rad_op)0);
|
||||
for (const auto& layer : m.layers) {
|
||||
CHECK_EQ(layer.reduce_attn, (rad_op)0);
|
||||
CHECK_EQ(layer.reduce_ffn, (rad_op)0);
|
||||
}
|
||||
RadBatch batch = decode_batch();
|
||||
RadCtx c{.b = &b, .batch = &batch};
|
||||
spark25_bf16::step(&c, &batch);
|
||||
CHECK_LINT(b, &c);
|
||||
CHECK(c.step_fail.empty());
|
||||
const auto issued = issued_ops(b, c);
|
||||
CHECK(std::find(issued.begin(), issued.end(), "all_reduce") == issued.end());
|
||||
}
|
||||
|
||||
TEST(spark_prefill_keys_match_live_r4d_split_grid) {
|
||||
#ifdef SPARK25_HAVE_PREFILL_SPLIT
|
||||
spark25_prefill_key::Request r;
|
||||
r.phase = RAD_PHASE_PREFILL; r.n_tok = r.max_q_len = 256; r.n_seq = 1;
|
||||
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;
|
||||
const uint64_t k4 = spark25_prefill_key::pass_key(r);
|
||||
CHECK_EQ(rad_prefill_splits_for_live(96, 48, 256, 256, 1, 4, 65536, 1536, 32), 4);
|
||||
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);
|
||||
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;
|
||||
CHECK_EQ(spark25_prefill_key::pass_key(r), (uint64_t)0);
|
||||
|
||||
MetaKV meta = spark_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
RadBuilder bf16_builder;
|
||||
REQUIRE_EQ(spark25_bf16::declare(&bf16_builder, meta.meta(), &ctx), RAD_OK);
|
||||
RadKVGroupBatch kv{}; kv.group = spark25_bf16::models[0].kv;
|
||||
RadBatch batch{}; batch.phase = RAD_PHASE_PREFILL; batch.n_tok = batch.max_q_len = 256;
|
||||
batch.n_seq = batch.n_kv_groups = 1; batch.kv = &kv;
|
||||
int32_t used[1] = {1536}; RadCtx c{};
|
||||
const uint64_t bf16_k4 = spark25_bf16::pass_key(&c, &batch, used);
|
||||
REQUIRE(bf16_k4 != 0);
|
||||
used[0] = 2048;
|
||||
CHECK(spark25_bf16::pass_key(&c, &batch, used) != bf16_k4);
|
||||
|
||||
MetaKV iqmeta = spark_meta();
|
||||
iqmeta.m.quant = "w8a8_fwht128";
|
||||
iqmeta.set("quantization_config.quant_method", "w8a8")
|
||||
.set("quantization_config.fmt", "fwht128");
|
||||
RadBuilder iq_builder; spark_iq8r_encodings(iq_builder);
|
||||
REQUIRE_EQ(spark25_w8a8::declare(&iq_builder, iqmeta.meta(), &ctx), RAD_OK);
|
||||
kv.group = spark25_w8a8::models[0].kv;
|
||||
used[0] = 1536;
|
||||
const uint64_t iq_k4 = spark25_w8a8::pass_key(&c, &batch, used);
|
||||
REQUIRE(iq_k4 != 0);
|
||||
used[0] = 2048;
|
||||
CHECK(spark25_w8a8::pass_key(&c, &batch, used) != iq_k4);
|
||||
#else
|
||||
CHECK_EQ(spark25_prefill_key::pass_key({}), (uint64_t)0);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* A DSpark drafter merged under `draft.`, as `--draft-model` writes it: five sliding layers over a
|
||||
* trunk, a seven-token block, a rank-256 Markov head, and the tap list the published Spark drafts
|
||||
* carry (translated into the layers whose output is tapped). */
|
||||
static MetaKV with_dspark(MetaKV k) {
|
||||
k.set("draft.architectures", "DSparkDraftModel")
|
||||
.set("draft.model_type", "dspark")
|
||||
.set("draft.num_hidden_layers", "5")
|
||||
.set("draft.hidden_size", "2560")
|
||||
.set("draft.intermediate_size", "10240")
|
||||
.set("draft.num_attention_heads", "16")
|
||||
.set("draft.num_key_value_heads", "4")
|
||||
.set("draft.head_dim", "256")
|
||||
.set("draft.rms_norm_eps", "1e-06")
|
||||
.set("draft.rope_theta", "10000")
|
||||
.set("draft.vocab_size", "131072")
|
||||
.set("draft.partial_rotary_factor", "1")
|
||||
.set("draft.hidden_act", "gelu")
|
||||
.set("draft.is_causal", "0")
|
||||
.set("draft.use_sliding_window", "1")
|
||||
.set("draft.sliding_window", "512")
|
||||
.set("draft.block_size", "7")
|
||||
.set("draft.sample_from_anchor", "1")
|
||||
.set("draft.mask_token_id", "2")
|
||||
.set("draft.target_layer_ids", "1 3")
|
||||
.set("draft.gguf_target_layers", "2 4")
|
||||
.set("draft.tie_word_embeddings", "1")
|
||||
.set("draft.headwise_attn_output_gate", "1")
|
||||
.set("draft.gate_attn_act_mode", "sigmoid")
|
||||
.set("draft.fc_norm", "1")
|
||||
.set("draft.markov_rank", "256")
|
||||
.set("draft.markov_head_type", "vanilla")
|
||||
.set("draft.has_confidence_head", "1");
|
||||
return k;
|
||||
}
|
||||
|
||||
static RadBuildCtx spec_ctx(int max_spec) {
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = max_spec;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
TEST(a_dspark_drafter_is_declared_over_the_trunk) {
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
|
||||
/* What the core drives: a block drafter, seven rows and seven drafts, staged against the
|
||||
* window the plugin gated its own attention with. */
|
||||
CHECK_EQ(b.drafter.kind, (int)RAD_DRAFT_BLOCK);
|
||||
CHECK_EQ(b.drafter.depth, 7);
|
||||
CHECK_EQ(b.drafter.block, 7); /* every row predicts, the anchor included */
|
||||
CHECK_EQ(b.drafter.mask_token, 2);
|
||||
CHECK_EQ(b.drafter.window, 513); /* 512-key history plus anchor */
|
||||
CHECK(b.drafter.proposal != 0);
|
||||
CHECK_EQ(b.drafter.proposal_pitch, (int64_t)7);
|
||||
CHECK_EQ(b.drafter_name, std::string("dspark"));
|
||||
|
||||
/* Its own exact anchor-aligned KV window, and its layers bound past the trunk's four. */
|
||||
REQUIRE_EQ(b.kv_groups.size(), (size_t)2);
|
||||
const RecKV& draft_kv = b.kv_groups[1];
|
||||
CHECK_EQ(draft_kv.d.kind, (int)RAD_KV_WINDOW);
|
||||
CHECK_EQ(draft_kv.d.window, (int64_t)513);
|
||||
CHECK_EQ(draft_kv.d.n_head_kv, (int64_t)4);
|
||||
CHECK_EQ(draft_kv.d.head_dim, (int64_t)256);
|
||||
for (int l = 0; l < 5; ++l) {
|
||||
auto it = std::find_if(b.binds.begin(), b.binds.end(),
|
||||
[&](const std::pair<int, rad_kvgroup>& p) { return p.first == 4 + l; });
|
||||
REQUIRE(it != b.binds.end());
|
||||
CHECK_EQ(it->second, (rad_kvgroup)2); /* the drafter's group, not the trunk's */
|
||||
}
|
||||
|
||||
/* The taps: two column slices of one f32 stream, copied out of the trunk as it passes. */
|
||||
const RecBuf* src = find_b(b, "draft_src");
|
||||
REQUIRE(src);
|
||||
CHECK_EQ(src->d.dtype, (uint32_t)RAD_F32);
|
||||
CHECK_EQ(src->d.rank, 2u);
|
||||
CHECK_EQ(src->d.shape[1], (int64_t)2 * 2560);
|
||||
CHECK_EQ(count_op(b, "cast") >= 1, true);
|
||||
|
||||
/* The drafter's weights, at the names the container carries -- including the gate under the
|
||||
* `g_proj` spelling the target uses, and the Markov pair as vocabulary-wide codebooks. */
|
||||
const RecWeight* fc = find_w(b, "dspark.fc.weight");
|
||||
REQUIRE(fc);
|
||||
CHECK_EQ(fc->d.dtype, (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(fc->d.rank, 2u);
|
||||
CHECK_EQ(fc->d.shape[0], (int64_t)2560);
|
||||
CHECK_EQ(fc->d.shape[1], (int64_t)2 * 2560);
|
||||
const RecMap* fc_map = find_map(b, "dspark.fc.weight");
|
||||
REQUIRE(fc_map);
|
||||
CHECK_EQ(fc_map->src[0], std::string("draft.fc.weight"));
|
||||
REQUIRE(find_w(b, "dspark.fc_norm.0.weight") != nullptr);
|
||||
REQUIRE(find_w(b, "dspark.fc_norm.1.weight") != nullptr);
|
||||
const RecWeight* gate = find_w(b, "dspark.blk.0.attn_gate");
|
||||
REQUIRE(gate);
|
||||
CHECK_EQ(gate->d.shape[0], (int64_t)16); /* one gate a head */
|
||||
CHECK_EQ(gate->d.shape[1], (int64_t)2560);
|
||||
const RecMap* gate_map = find_map(b, "dspark.blk.0.attn_gate");
|
||||
REQUIRE(gate_map);
|
||||
CHECK_EQ(gate_map->src[0], std::string("draft.layers.0.self_attn.g_proj.weight"));
|
||||
/* Every drafter name, norms included, is the container's name under `draft.` -- a missing
|
||||
* separator here reads a tensor that is not there. */
|
||||
for (const auto& prm : {std::pair{"dspark.blk.0.attn_norm.weight",
|
||||
"draft.layers.0.input_layernorm.weight"},
|
||||
{"dspark.blk.0.ffn_norm.weight",
|
||||
"draft.layers.0.post_attention_layernorm.weight"},
|
||||
{"dspark.blk.4.ffn_norm.weight",
|
||||
"draft.layers.4.post_attention_layernorm.weight"}}) {
|
||||
const RecMap* m = find_map(b, prm.first);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->src[0], std::string(prm.second));
|
||||
}
|
||||
const RecWeight* gu = find_w(b, "dspark.blk.0.ffn_gate_up");
|
||||
REQUIRE(gu);
|
||||
CHECK_EQ(gu->d.n_row_parts, 2); /* [gate | up], one weight */
|
||||
const RecWeight* mk1 = find_w(b, "dspark.markov_w1");
|
||||
REQUIRE(mk1);
|
||||
CHECK_EQ(mk1->d.access, RAD_ACCESS_VOCAB);
|
||||
CHECK_EQ(mk1->d.shard, RAD_SHARD_NONE);
|
||||
CHECK_EQ(mk1->d.shape[0], (int64_t)131072);
|
||||
CHECK_EQ(mk1->d.shape[1], (int64_t)256);
|
||||
const RecWeight* head = find_w(b, "dspark.head.weight");
|
||||
REQUIRE(head);
|
||||
CHECK_EQ(head->d.dtype, (uint32_t)RAD_BF16);
|
||||
const RecMap* head_map = find_map(b, "dspark.head.weight");
|
||||
REQUIRE(head_map);
|
||||
CHECK_EQ(head_map->src[0], std::string("model.embedding.weight")); /* the target's tied table */
|
||||
|
||||
/* Its layers: non-causal attention over the exact shared anchor window, exact-erf gelu, one
|
||||
* sigmoid gate a head, and a rotary over the whole head. */
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 4);
|
||||
CHECK_EQ(count_op(b, "attn_paged_anchor_window"), 1);
|
||||
const RecOp* d_attn = find_op(b, "attn_paged_anchor_window", 0);
|
||||
REQUIRE(d_attn != nullptr);
|
||||
CHECK_EQ(pint(d_attn, "causal"), 0);
|
||||
CHECK_EQ(pint(d_attn, "window"), 513);
|
||||
CHECK_EQ(pint(d_attn, "gqa"), 4);
|
||||
/* The M range tops out at the block, not at a token count. */
|
||||
const RecParam* ql = nullptr;
|
||||
for (const auto& prm : d_attn->p) if (prm.key == "q_len") ql = &prm;
|
||||
REQUIRE(ql != nullptr);
|
||||
CHECK_EQ(ql->ival, 1);
|
||||
CHECK_EQ(ql->ihi, 7);
|
||||
CHECK_EQ(pstr(d_attn, "q_dtype"), std::string("bf16"));
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "act_mul") continue;
|
||||
CHECK_EQ(pstr(&o, "act"), std::string("gelu")); /* exact erf, as the trunk's */
|
||||
}
|
||||
CHECK_EQ(count_op(b, "rope") >= 4 * 2 + 1, true);
|
||||
const RecOp* markov = find_op(b, "dflash_markov_greedy_f32", 0);
|
||||
REQUIRE(markov);
|
||||
CHECK_EQ(pint(markov, "steps"), 7);
|
||||
CHECK_EQ(pint(markov, "rank"), 256);
|
||||
CHECK_EQ(pint(markov, "anchor_stride"), 7); /* token_ids is `block` a sequence */
|
||||
CHECK_EQ(pint(markov, "n_vocab"), (int64_t)131072);
|
||||
CHECK_EQ(pstr(markov, "dtype"), std::string("bf16"));
|
||||
CHECK_EQ(find_op(b, "dflash_select", 0), nullptr);
|
||||
CHECK_EQ(find_op(b, "row_topk", 0), nullptr);
|
||||
const RecBuf* best_scores = nullptr;
|
||||
const RecBuf* best_tokens = nullptr;
|
||||
for (const auto& bf : b.bufs) {
|
||||
if (bf.name == "ds_markov_score") best_scores = &bf;
|
||||
if (bf.name == "ds_markov_token") best_tokens = &bf;
|
||||
}
|
||||
REQUIRE(best_scores && best_tokens);
|
||||
CHECK_EQ(best_scores->d.shape[0], (int64_t)8);
|
||||
CHECK_EQ(best_scores->d.shape[1], (int64_t)(131072 + 63) / 64);
|
||||
const RecBuf* dlog = nullptr;
|
||||
for (const auto& bf : b.bufs) if (bf.name == "ds_dlog") dlog = &bf;
|
||||
REQUIRE(dlog != nullptr);
|
||||
CHECK_EQ(dlog->d.dtype, (uint32_t)RAD_F32);
|
||||
CHECK_EQ(count_op(b, "logits_gemm"), 2); /* trunk and draft F32 heads */
|
||||
CHECK(count_op(b, "gemm_nt") > 0);
|
||||
|
||||
/* The drafter is declared after the trunk, and the graph resolves: no op the plugin declared is
|
||||
* left unused, and every weight it reads came from a name map. */
|
||||
for (const auto& o : b.ops) if (o.resolved) CHECK(o.uses_declared);
|
||||
for (const auto& w : b.weights) if (!w.d.source) CHECK(find_map(b, w.name) != nullptr);
|
||||
const std::string notes = [&] {
|
||||
std::string n;
|
||||
for (const auto& s : b.notes) n += s + "\n";
|
||||
return n;
|
||||
}();
|
||||
CHECK(notes.find("DSpark drafter") != std::string::npos);
|
||||
CHECK(notes.find("after layer(s) 1, 3") != std::string::npos);
|
||||
}
|
||||
|
||||
/* HIP rmsnorm/sigmoid/scale_rows declare __restrict__ in and out. The production graph must not
|
||||
* pass the same allocation to both, including the Spark-gated attention path. */
|
||||
TEST(dspark_restrict_ops_do_not_alias_input_and_output) {
|
||||
auto name = [](const RadBuilder& b, rad_buf h) -> std::string {
|
||||
return h && h <= (rad_buf)b.bufs.size() ? b.bufs[h - 1].name : "?";
|
||||
};
|
||||
auto is_draft = [&](const RadBuilder& b, rad_buf h) {
|
||||
const std::string n = name(b, h);
|
||||
return n.rfind("ds_", 0) == 0 || n.rfind("draft", 0) == 0;
|
||||
};
|
||||
auto check = [&](const RadBuilder& b) {
|
||||
REQUIRE(find_b(b, "ds_cn"));
|
||||
REQUIRE(find_b(b, "ds_gaten"));
|
||||
REQUIRE(find_b(b, "ds_attng"));
|
||||
int checked = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "rmsnorm" && o.op != "sigmoid" && o.op != "scale_rows") continue;
|
||||
bool draft = false;
|
||||
for (rad_buf h : o.reads) draft = draft || is_draft(b, h);
|
||||
for (rad_buf h : o.writes) draft = draft || is_draft(b, h);
|
||||
if (!draft) continue;
|
||||
++checked;
|
||||
for (rad_buf w : o.writes) {
|
||||
for (rad_buf r : o.reads) {
|
||||
CHECK(r != w);
|
||||
if (r == w)
|
||||
fprintf(stderr, "aliased %s on %s\n", o.op.c_str(), name(b, w).c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK(checked >= 3);
|
||||
};
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
check(b);
|
||||
}
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
k.m.quant = "w8a8_fwht128";
|
||||
k.set("quantization_config.quant_method", "w8a8")
|
||||
.set("quantization_config.fmt", "fwht128");
|
||||
RadBuilder b;
|
||||
spark_iq8r_encodings(b);
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
REQUIRE_EQ(spark25_w8a8::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
check(b);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_drafter_passes_run_and_the_draft_is_proposed_from_the_block) {
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
|
||||
/* One engine step, as the scheduler drives it: a verify pass over the accepted block, the
|
||||
* drafter's context pass over what the trunk just committed, then its query pass over the
|
||||
* staged block (the anchor and six masks). */
|
||||
const auto ver = kit(b, std::vector<int>(4, 8), {});
|
||||
const auto ctx_pass = context_pass(b, *ver);
|
||||
const auto qry = query_pass(b, 4, 7, 7); /* seven rows, seven drafts */
|
||||
const auto v = run_passes(b, spark25_bf16::step, { ver.get(), ctx_pass.get(), qry.get() });
|
||||
CHECK_PASSES(b, v);
|
||||
|
||||
/* The query pass is the drafter alone: five attention layers, the head, and the walk that
|
||||
* writes the proposal buffer -- and no trunk layer at all. */
|
||||
RadCtx& q = *v[2];
|
||||
int attn = 0, gemm = 0;
|
||||
bool selected = false, proposed = false, draft_head = false;
|
||||
rad_buf head_logits = 0;
|
||||
for (const auto& i : q.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
REQUIRE(o != nullptr);
|
||||
if (o->op == "attn_paged_anchor_window") ++attn;
|
||||
if (o->op == "gemm_nt") ++gemm;
|
||||
if (o->op == "logits_gemm") {
|
||||
REQUIRE_EQ(i.opd.size(), (size_t)3);
|
||||
REQUIRE_EQ(i.opd[2].kind, (uint8_t)RAD_OPK_BUF);
|
||||
head_logits = i.opd[2].handle;
|
||||
REQUIRE(head_logits > 0 && head_logits <= b.bufs.size());
|
||||
CHECK_EQ(b.bufs[head_logits - 1].d.dtype, (uint32_t)RAD_F32);
|
||||
draft_head = true;
|
||||
}
|
||||
if (o->op == "dflash_markov_greedy_f32") {
|
||||
selected = true;
|
||||
REQUIRE_EQ(i.opd.size(), (size_t)7); /* logits, anchor, pred, succ, tiles, tokens */
|
||||
CHECK_EQ(i.opd[0].handle, head_logits);
|
||||
CHECK_EQ(i.opd[6].kind, (uint8_t)RAD_OPK_BUF);
|
||||
CHECK_EQ(i.opd[6].handle, b.drafter.proposal);
|
||||
proposed = i.opd[6].handle == b.drafter.proposal;
|
||||
}
|
||||
}
|
||||
CHECK(draft_head);
|
||||
CHECK_EQ(attn, 5);
|
||||
CHECK(gemm > 0);
|
||||
CHECK(selected);
|
||||
CHECK(proposed);
|
||||
|
||||
/* The context pass stores K and V for every committed token and proposes nothing. */
|
||||
RadCtx& h = *v[1];
|
||||
int stores = 0;
|
||||
for (const auto& i : h.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
REQUIRE(o != nullptr);
|
||||
if (o->op == "kv_store") ++stores;
|
||||
}
|
||||
CHECK_EQ(stores, 5);
|
||||
auto drafter_silent = [&](const RadCtx& pass) {
|
||||
for (const auto& i : pass.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || o->op == "dflash_markov_greedy_f32" || o->op == "dflash_select")
|
||||
return false;
|
||||
for (const auto& operand : i.opd)
|
||||
if (operand.kind == RAD_OPK_BUF &&
|
||||
(operand.handle == b.drafter.proposal || operand.handle == head_logits))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
CHECK(drafter_silent(h));
|
||||
CHECK(!drafter_silent(q)); /* negative control: a real draft pass must fail the silence test */
|
||||
|
||||
/* And the trunk's own step, with the drafter silent. */
|
||||
const auto dec = kit(b, { 1, 1, 1, 1 }, {});
|
||||
const auto d = run_passes(b, spark25_bf16::step, { dec.get() });
|
||||
CHECK_PASSES(b, d);
|
||||
CHECK(drafter_silent(*d[0]));
|
||||
}
|
||||
|
||||
TEST(a_drafter_is_refused_when_the_pair_or_the_depth_is_wrong) {
|
||||
/* A serve that asks for another depth: a block-diffusion drafter has no partial block. */
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(3);
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
/* The head is read replicated, so a vocab-sharded world cannot draft from it. */
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
ctx.world_size = 2;
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_UNSUPPORTED);
|
||||
}
|
||||
for (const auto& change : {std::pair{"draft.hidden_size", "4096"}, /* another target */
|
||||
std::pair{"draft.markov_rank", "0"}, /* no head to walk */
|
||||
std::pair{"draft.markov_rank", "24"}, /* not a strided rank */
|
||||
std::pair{"draft.sample_from_anchor", "0"}, /* a slot with no rows */
|
||||
std::pair{"draft.hidden_act", "gelu_tanh"}, /* not what it trained */
|
||||
std::pair{"draft.gate_attn_act_mode", "tanh"},
|
||||
std::pair{"draft.architectures", "DFlashDraftModel"},
|
||||
std::pair{"draft.sliding_window", "4"}, /* shorter than a block */
|
||||
std::pair{"draft.block_size", "0"}}) {
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
k.set(change.first, change.second);
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) != RAD_OK);
|
||||
}
|
||||
/* A library that only has the older per-query window or candidate-pruned selector must refuse
|
||||
* DSpark declaration, not silently substitute an operation with different semantics. */
|
||||
for (const char* op : {"attn_paged_anchor_window", "dflash_markov_greedy_f32"}) {
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
b.refuse.insert(op);
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) != RAD_OK);
|
||||
}
|
||||
/* A drafter whose tap list names only layers past the target's last reads nothing, which is not
|
||||
* a drafter. */
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
k.set("draft.target_layer_ids", "9 11");
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
|
||||
RAD_E_FORMAT);
|
||||
}
|
||||
/* With no speculation asked for, the drafter is not declared and its weights stay out of the
|
||||
* program -- but the container still serves. */
|
||||
{
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = spec_ctx(0);
|
||||
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
CHECK_EQ(b.drafter.kind, (int)RAD_DRAFT_NONE);
|
||||
CHECK(find_w(b, "dspark.fc.weight") == nullptr);
|
||||
}
|
||||
/* And the probe tells the engine what depth the container supports, before declare. */
|
||||
RadArchProbe p{};
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
REQUIRE_EQ(spark25_bf16::probe(k.meta(), &p), RAD_OK);
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
RadArchProbe plain{};
|
||||
MetaKV none = spark_meta();
|
||||
REQUIRE_EQ(spark25_bf16::probe(none.meta(), &plain), RAD_OK);
|
||||
CHECK_EQ(plain.draft_depth, 0);
|
||||
}
|
||||
|
||||
/* The int8 trunk carries the same drafter: the drafter reads the trunk's residual stream, which is
|
||||
* f32 whatever the linears are, so the wiring is the trunk's and the graph is the drafter's. */
|
||||
TEST(the_int8_trunk_carries_the_same_drafter) {
|
||||
MetaKV k = with_dspark(spark_meta());
|
||||
k.m.quant = "w8a8_fwht128";
|
||||
k.set("quantization_config.quant_method", "w8a8")
|
||||
.set("quantization_config.fmt", "fwht128");
|
||||
RadBuilder b;
|
||||
spark_iq8r_encodings(b);
|
||||
RadBuildCtx ctx = spec_ctx(7);
|
||||
REQUIRE_EQ(spark25_w8a8::declare(&b, k.meta(), &ctx), RAD_OK);
|
||||
CHECK_EQ(b.drafter.kind, (int)RAD_DRAFT_BLOCK);
|
||||
CHECK_EQ(b.drafter.depth, 7);
|
||||
CHECK_EQ(b.drafter.window, 513);
|
||||
CHECK(find_w(b, "dspark.fc.weight") != nullptr);
|
||||
CHECK_EQ(count_op(b, "attn_paged_anchor_window"), 1);
|
||||
CHECK_EQ(count_op(b, "dflash_markov_greedy_f32"), 1);
|
||||
CHECK_EQ(count_op(b, "dflash_select"), 0);
|
||||
const auto ver = kit(b, std::vector<int>(4, 8), {});
|
||||
const auto ctx_pass = context_pass(b, *ver);
|
||||
const auto qry = query_pass(b, 4, 7, 7);
|
||||
const auto v = run_passes(b, spark25_w8a8::step, { ver.get(), ctx_pass.get(), qry.get() });
|
||||
CHECK_PASSES(b, v);
|
||||
/* The trunk's quantised linears are untouched by the drafter's bf16 graph. */
|
||||
CHECK(count_op(b, "gemm_nt_q") > 0);
|
||||
|
||||
RadArchProbe p{};
|
||||
REQUIRE_EQ(spark25_w8a8::probe(k.meta(), &p), RAD_OK);
|
||||
CHECK_EQ(p.draft_depth, 7);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
}
|
||||
|
||||
TEST(refuses_unimplemented_variants) {
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
for (const auto& change : {std::pair{"tie_word_embeddings", "0"},
|
||||
std::pair{"headwise_attn_output_gate", "0"},
|
||||
std::pair{"gate_attn_act_mode", "silu"},
|
||||
std::pair{"hidden_act", "silu"},
|
||||
std::pair{"attention_bias", "1"},
|
||||
std::pair{"mlp_bias", "1"},
|
||||
std::pair{"layer_types", "sliding_attention"},
|
||||
std::pair{"rope_parameters.full_attention.rope_type", "dynamic"},
|
||||
std::pair{"rope_parameters.full_attention.partial_rotary_factor", "0.3"}}) {
|
||||
MetaKV k = spark_meta();
|
||||
k.set(change.first, change.second);
|
||||
RadBuilder b;
|
||||
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) != RAD_OK);
|
||||
}
|
||||
MetaKV k = spark_meta();
|
||||
k.set("rope_scaling.rope_type", "linear").set("rope_scaling.factor", "2");
|
||||
RadBuilder scaled;
|
||||
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&scaled, k.meta(), &ctx); }) == RAD_E_UNSUPPORTED);
|
||||
k = spark_meta();
|
||||
RadBuilder b;
|
||||
ctx.world_size = 17; /* more ranks than query heads */
|
||||
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) == RAD_E_INVAL);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,154 @@
|
||||
/* Spark's reasoning and XML/KV tool calls, including streaming at every byte. */
|
||||
#include "rad_test.h"
|
||||
#include "text/chat.h"
|
||||
#include "text/chatfmt.h"
|
||||
#include "text/chatparse.h"
|
||||
#include "../arch/spark25_bf16/chat.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
using namespace rad;
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
static const json& tools() {
|
||||
static const json t = json::parse(R"([
|
||||
{"type":"function","function":{"name":"weather","parameters":{"type":"object",
|
||||
"properties":{"city":{"type":"string"},"days":{"type":"integer"},
|
||||
"verbose":{"type":"boolean"},"units":{"type":"array","items":{"type":"string"}}}}}},
|
||||
{"type":"function","function":{"name":"ping","parameters":{"type":"object","properties":{}}}}
|
||||
])");
|
||||
return t;
|
||||
}
|
||||
|
||||
static ChatFormat format() {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(spark25_bf16::spark_chat_format(), &f, &why));
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
return f;
|
||||
}
|
||||
|
||||
static std::shared_ptr<const ReplyParser> parser(const std::string& prefix, bool with_tools = true) {
|
||||
std::string why;
|
||||
ChatFormat f = format();
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
std::shared_ptr<const ReplyParser> p;
|
||||
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
|
||||
ReplyOptions opts;
|
||||
opts.generation_prompt = prefix;
|
||||
opts.tools = with_tools ? &tools() : nullptr;
|
||||
if (rf) CHECK_OK(ReplyParser::create(rf, opts, &p, &why));
|
||||
return p;
|
||||
}
|
||||
|
||||
TEST(thinking_and_typed_calls_survive_one_byte_streaming) {
|
||||
auto p = parser("<|start▁of▁sentence|><|Bot|><think>");
|
||||
REQUIRE(p != nullptr);
|
||||
const std::string s = "I should look.</think>Checking."
|
||||
"<tool_call>weather<arg_key>city</arg_key><arg_value>Paris</arg_value>"
|
||||
"<arg_key>days</arg_key><arg_value>3</arg_value>"
|
||||
"<arg_key>verbose</arg_key><arg_value>true</arg_value>"
|
||||
"<arg_key>units</arg_key><arg_value>[\"C\",\"F\"]</arg_value></tool_call>"
|
||||
"<tool_call>ping</tool_call>";
|
||||
const ReplyMessage expected = reply_parse(*p, s);
|
||||
CHECK_EQ(expected.reasoning, std::string("I should look."));
|
||||
CHECK_EQ(expected.content, std::string("Checking."));
|
||||
REQUIRE_EQ(expected.calls.size(), (size_t)2);
|
||||
CHECK_EQ(expected.calls[0].name, std::string("weather"));
|
||||
CHECK(expected.calls[0].closed);
|
||||
const json args = json::parse(expected.calls[0].arguments);
|
||||
CHECK_EQ(args["city"].get<std::string>(), std::string("Paris"));
|
||||
CHECK_EQ(args["days"].get<int>(), 3);
|
||||
CHECK_EQ(args["verbose"].get<bool>(), true);
|
||||
CHECK(args["units"] == json::array({"C", "F"}));
|
||||
CHECK_EQ(expected.calls[1].name, std::string("ping"));
|
||||
CHECK(json::parse(expected.calls[1].arguments) == json::object());
|
||||
auto stream = p->open();
|
||||
for (char c : s) stream->feed(std::string_view(&c, 1), nullptr);
|
||||
stream->finish(nullptr);
|
||||
const ReplyMessage& got = stream->message();
|
||||
CHECK_EQ(got.reasoning, expected.reasoning);
|
||||
CHECK_EQ(got.content, expected.content);
|
||||
REQUIRE_EQ(got.calls.size(), expected.calls.size());
|
||||
for (size_t i = 0; i < got.calls.size(); ++i) {
|
||||
CHECK_EQ(got.calls[i].name, expected.calls[i].name);
|
||||
CHECK_EQ(got.calls[i].arguments, expected.calls[i].arguments);
|
||||
CHECK(got.calls[i].closed);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(thinking_off_and_an_unclosed_thought_before_a_call) {
|
||||
auto off = parser("<|start▁of▁sentence|><|Bot|></think>", false);
|
||||
REQUIRE(off != nullptr);
|
||||
const ReplyMessage a = reply_parse(*off, "Hello.");
|
||||
CHECK(a.reasoning.empty());
|
||||
CHECK_EQ(a.content, std::string("Hello."));
|
||||
auto on = parser("<|start▁of▁sentence|><|Bot|><think>");
|
||||
REQUIRE(on != nullptr);
|
||||
const ReplyMessage b = reply_parse(*on, "Plan.<tool_call>ping</tool_call>");
|
||||
CHECK_EQ(b.reasoning, std::string("Plan."));
|
||||
REQUIRE_EQ(b.calls.size(), (size_t)1);
|
||||
CHECK_EQ(b.calls[0].name, std::string("ping"));
|
||||
}
|
||||
|
||||
TEST(grammar_starts_on_the_real_call_opener) {
|
||||
const ChatFormat f = format();
|
||||
ChatGrammarRequest req;
|
||||
req.tools = &tools();
|
||||
req.generation_prompt = "<think>";
|
||||
ChatGrammar g;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_grammar(f, req, &g, &why));
|
||||
CHECK(g.lazy);
|
||||
CHECK(!g.text.empty());
|
||||
REQUIRE_EQ(g.trigger_words.size(), (size_t)1);
|
||||
CHECK_EQ(g.trigger_words[0], std::string("<tool_call>"));
|
||||
}
|
||||
|
||||
/* Set this to the checkpoint's actual chat_template.jinja to exercise it without redistributing
|
||||
* model files in the repository. Ordinary CI still exercises the reply format above. */
|
||||
TEST(reference_template_defaults_to_thinking_and_allows_disabling_it) {
|
||||
const char* path = std::getenv("SPARK25_REFERENCE_TEMPLATE");
|
||||
if (!path || !*path) SKIP("set SPARK25_REFERENCE_TEMPLATE to the checkpoint's template");
|
||||
std::ifstream file(path);
|
||||
REQUIRE((bool)file);
|
||||
std::ostringstream s;
|
||||
s << file.rdbuf();
|
||||
ChatTemplate t;
|
||||
REQUIRE_EQ(t.load(s.str(), "<|start▁of▁sentence|>", "<|end▁of▁sentence|>"), RAD_OK);
|
||||
const json messages = json::array({{{"role", "user"}, {"content", "Hello"}}});
|
||||
for (bool think : {true, false}) {
|
||||
ChatOptions opt;
|
||||
opt.enable_thinking = think;
|
||||
ChatPrompt prompt;
|
||||
REQUIRE_EQ(t.apply(messages, json::array(), opt, &prompt), RAD_OK);
|
||||
const std::string suffix = think ? "<think>" : "</think>";
|
||||
CHECK(prompt.prompt.size() >= suffix.size());
|
||||
CHECK(prompt.prompt.ends_with(suffix));
|
||||
if (think) CHECK(prompt.prompt.find("thinking_effort=high") != std::string::npos);
|
||||
}
|
||||
ChatOptions low;
|
||||
low.template_kwargs["reasoning_effort"] = "\"low\"";
|
||||
ChatPrompt lp;
|
||||
REQUIRE_EQ(t.apply(messages, json::array(), low, &lp), RAD_OK);
|
||||
CHECK(lp.prompt.find("thinking_effort=low") != std::string::npos);
|
||||
|
||||
/* OpenAI tool arguments arrive as a JSON string; the checkpoint template requires a mapping. */
|
||||
const json history = json::parse(R"([
|
||||
{"role":"user","content":"Weather?"},
|
||||
{"role":"assistant","content":"","reasoning_content":"Check.","tool_calls":[
|
||||
{"id":"call_1","type":"function","function":{"name":"weather","arguments":"{\"city\":\"Paris\",\"days\":3}"}}]},
|
||||
{"role":"tool","tool_call_id":"call_1","content":"Sunny"}
|
||||
])");
|
||||
ChatPrompt hp;
|
||||
ChatOptions options;
|
||||
REQUIRE_EQ(t.apply(history, tools(), options, &hp), RAD_OK);
|
||||
CHECK(hp.prompt.find("<tool_call>weather<arg_key>city</arg_key><arg_value>Paris</arg_value>") != std::string::npos);
|
||||
CHECK(hp.prompt.find("<arg_key>days</arg_key><arg_value>3</arg_value></tool_call>") != std::string::npos);
|
||||
CHECK(hp.prompt.find("<tool_response>Sunny</tool_response>") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,81 @@
|
||||
/* A small Spark checkpoint converted with the production name map. */
|
||||
#include "rad_test.h"
|
||||
#include "tiny_model.h"
|
||||
#include "format/radfile.h"
|
||||
|
||||
#include <map>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
TEST(bf16_conversion_preserves_qkv_rows_gate_up_and_tied_head) {
|
||||
tiny::TempDir d("spark25_convert");
|
||||
REQUIRE(d.ok());
|
||||
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 = {
|
||||
{"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},
|
||||
{"vocab_size", V}, {"max_position_embeddings", 64}, {"rms_norm_eps", 1e-6},
|
||||
{"tie_word_embeddings", true}, {"headwise_attn_output_gate", true},
|
||||
{"gate_attn_act_mode", "sigmoid"}, {"hidden_act", "gelu"}, {"sliding_window", 4},
|
||||
{"layer_types", {"sliding_attention", "full_attention"}},
|
||||
{"rope_parameters", {{"sliding_attention", {{"rope_theta", 10000}, {"partial_rotary_factor", 1.0}}},
|
||||
{"full_attention", {{"rope_theta", 5000000}, {"partial_rotary_factor", 0.5}}}}}
|
||||
};
|
||||
tiny::Rng r(123);
|
||||
std::vector<tiny::Tensor> ts;
|
||||
ts.push_back(tiny::noise("model.embedding.weight", {V, H}, r, 0.2f));
|
||||
ts.push_back(tiny::noise("model.norm.weight", {H}, r, 0.1f, 1.0f));
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
const std::string p = "model.layers." + std::to_string(l) + ".";
|
||||
ts.push_back(tiny::noise(p + "input_layernorm.weight", {H}, r, 0.1f, 1.0f));
|
||||
ts.push_back(tiny::noise(p + "post_attention_layernorm.weight", {H}, r, 0.1f, 1.0f));
|
||||
ts.push_back(tiny::linear(p + "self_attn.q_k_v_proj.weight", Q + 2*K, H, r));
|
||||
ts.push_back(tiny::linear(p + "self_attn.g_proj.weight", 4, H, r));
|
||||
ts.push_back(tiny::linear(p + "self_attn.out_proj.weight", H, Q, r));
|
||||
ts.push_back(tiny::linear(p + "mlp.gate_proj.weight", F, H, r));
|
||||
ts.push_back(tiny::linear(p + "mlp.up_proj.weight", F, H, r));
|
||||
ts.push_back(tiny::linear(p + "mlp.down_proj.weight", H, F, r));
|
||||
}
|
||||
REQUIRE(tiny::write_checkpoint(ckpt, config, ts));
|
||||
std::map<std::string, std::string> source;
|
||||
for (const auto& t : ts) source[t.name] = std::string(t.bytes.begin(), t.bytes.end());
|
||||
std::string log;
|
||||
const int st = tiny::run({RAD_E2E_CONVERT, ckpt, "-o", d / "model.rad", "--max-ctx", "64",
|
||||
"--max-tok", "16"},
|
||||
{std::string("RADIANCE_HOME=") + RAD_E2E_HOME,
|
||||
"ROCR_VISIBLE_DEVICES=99", "OMP_NUM_THREADS=2", "OMP_WAIT_POLICY=passive"},
|
||||
&log);
|
||||
if (st) fprintf(stderr, "%s\n", log.c_str());
|
||||
REQUIRE_EQ(st, 0);
|
||||
RadFile f;
|
||||
REQUIRE_EQ(f.open((d / "model.rad").c_str()), RAD_OK);
|
||||
CHECK_EQ(std::string(f.str(f.header().arch_id)), std::string("spark25"));
|
||||
CHECK_EQ(f.entry_count(), (int64_t)21);
|
||||
auto check = [&](const std::string& name, const std::string& bytes) {
|
||||
const RadFileEntry* e = f.find(name);
|
||||
if (!e) { CHECK(e != nullptr); return; }
|
||||
CHECK_EQ(e->n_planes, (uint32_t)1);
|
||||
const RadFilePlane& p = f.plane(*e, 0);
|
||||
CHECK_EQ(p.bytes, (uint64_t)bytes.size());
|
||||
if (p.bytes == bytes.size()) CHECK(std::memcmp(f.data(p), bytes.data(), bytes.size()) == 0);
|
||||
};
|
||||
check("token_embd.weight", source.at("model.embedding.weight"));
|
||||
check("output.weight", source.at("model.embedding.weight"));
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
const std::string p = "model.layers." + std::to_string(l) + ".";
|
||||
const std::string name = "blk." + std::to_string(l) + ".";
|
||||
const std::string& qkv = source.at(p + "self_attn.q_k_v_proj.weight");
|
||||
const size_t row = H * 2;
|
||||
check(name + "attn_q.weight", qkv.substr(0, Q*row));
|
||||
check(name + "attn_k.weight", qkv.substr(Q*row, K*row));
|
||||
check(name + "attn_v.weight", qkv.substr((Q+K)*row, K*row));
|
||||
check(name + "ffn_gate_up.weight", source.at(p + "mlp.gate_proj.weight") +
|
||||
source.at(p + "mlp.up_proj.weight"));
|
||||
check(name + "attn_gate.weight", source.at(p + "self_attn.g_proj.weight"));
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""IQ8R differential for Spark X2.6 on the host kernels.
|
||||
|
||||
Builds the deterministic two-layer fixture (tests/spark25_reference.py's, at a geometry the
|
||||
group-128 rotated int8 grid takes), converts it twice -- as it stands, and on IQ8R's grid -- and
|
||||
serves both through the CPU kernels. The quantised model must stay close to its bf16 self and to
|
||||
the Transformers reference: activations fed unrotated into rotated weights, or a scale plane read
|
||||
at the wrong width, yields a model that runs, generates fluently and is wrong.
|
||||
|
||||
Requires torch, transformers and safetensors. GPUs are hidden from both processes; on a shared
|
||||
machine run it in a GPU-denying device cgroup (ROCm may open device nodes while probing).
|
||||
|
||||
tests/spark25_iq8r.py --reference <XHToken-Spark-X2.6-4B> --build <build dir>
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from spark25_reference import (PROMPTS, generate, load_reference, serve, write_tokenizer) # noqa: E402
|
||||
|
||||
# Rows a token and widths the group-128 grid takes: hidden and every contraction in whole 128s,
|
||||
# output rows in whole 16s. head_dim 32 x 8 heads keeps q and the o_proj contraction at 256.
|
||||
GEOM = dict(vocab_size=3584, hidden_size=256, intermediate_size=256, num_hidden_layers=2,
|
||||
num_attention_heads=8, num_key_value_heads=4, head_dim=32)
|
||||
TRUNK = ("attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", "ffn_down")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--reference", required=True, type=Path, help="directory with modeling_spark.py")
|
||||
ap.add_argument("--build", required=True, type=Path, help="Radiance build directory")
|
||||
ap.add_argument("--keep", type=Path, help="write the fixture and both containers here")
|
||||
ap.add_argument("--tp", type=int, choices=range(1, 9), default=1,
|
||||
help="number of fake host ranks (up to 8)")
|
||||
ap.add_argument("--wide-tp", action="store_true",
|
||||
help="use 128-wide heads and a 1024-wide FFN to exercise TP up to 8")
|
||||
args = ap.parse_args()
|
||||
if args.tp > 2 and not args.wide_tp:
|
||||
ap.error("--tp above 2 needs --wide-tp so every rank owns a whole scale group")
|
||||
import torch
|
||||
import transformers
|
||||
from safetensors.torch import save_file
|
||||
|
||||
torch.set_num_threads(2)
|
||||
cfgmod, modelmod = load_reference(args.reference.resolve())
|
||||
if int(transformers.__version__.split(".")[0]) >= 5:
|
||||
modelmod.Spark2_5ForCausalLM._tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}
|
||||
geom = dict(GEOM)
|
||||
if args.wide_tp:
|
||||
geom.update(intermediate_size=1024, head_dim=128)
|
||||
config = cfgmod.Spark2_5Config(
|
||||
**geom, hidden_act="gelu", max_position_embeddings=128, rms_norm_eps=1e-6,
|
||||
tie_word_embeddings=True, headwise_attn_output_gate=True, gate_attn_act_mode="sigmoid",
|
||||
sliding_window=8, layer_types=["sliding_attention", "full_attention"],
|
||||
rope_parameters={"sliding_attention": {"rope_theta": 10000.0, "partial_rotary_factor": 1.0},
|
||||
"full_attention": {"rope_theta": 5000000.0, "partial_rotary_factor": 0.5}},
|
||||
bos_token_id=256, eos_token_id=256, pad_token_id=256)
|
||||
torch.manual_seed(19)
|
||||
model = modelmod.Spark2_5ForCausalLM(config).eval().to(torch.bfloat16)
|
||||
with torch.no_grad():
|
||||
for name, w in model.named_parameters():
|
||||
if name.endswith("layernorm.weight") or name == "model.norm.weight":
|
||||
w.copy_((1 + 0.08 * torch.randn(w.shape)).to(w.dtype))
|
||||
# Scale the measured 4B weight standard deviations by sqrt(2560 / 256), so
|
||||
# this narrower random fixture has comparable projection and head logit magnitudes.
|
||||
elif name == "model.embedding.weight":
|
||||
w.copy_((0.09 * torch.randn(w.shape)).to(w.dtype))
|
||||
elif name.endswith("g_proj.weight"):
|
||||
w.copy_((0.055 * torch.randn(w.shape)).to(w.dtype))
|
||||
else:
|
||||
w.copy_((0.085 * torch.randn(w.shape)).to(w.dtype))
|
||||
|
||||
def reference(ids):
|
||||
n = len(ids)
|
||||
q, k = torch.arange(n)[:, None], torch.arange(n)[None, :]
|
||||
full = torch.where(k <= q, 0.0, float("-inf"))[None, None, :, :]
|
||||
local = torch.where((k <= q) & (k > q - config.sliding_window), 0.0,
|
||||
float("-inf"))[None, None, :, :]
|
||||
with torch.inference_mode():
|
||||
logits = model(torch.tensor([ids]), attention_mask={"full_attention": full,
|
||||
"sliding_attention": local}, use_cache=False).logits[0, -1].float()
|
||||
return torch.log_softmax(logits, dim=-1)
|
||||
|
||||
build = args.build.resolve()
|
||||
env = os.environ.copy()
|
||||
env.update(RADIANCE_HOME=str(build / "radiance_home"), RADIANCE_HOST_VRAM_MIB="2048",
|
||||
RADIANCE_HOST_DEVICES=str(args.tp))
|
||||
keep = args.keep.resolve() if args.keep else None
|
||||
root = keep or Path(tempfile.mkdtemp(prefix="spark25-iq8r-"))
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
ckpt = root / "checkpoint"
|
||||
ckpt.mkdir(exist_ok=True)
|
||||
config_json = config.to_dict()
|
||||
config_json.update(model_type="spark2_5", architectures=["Spark2_5ForCausalLM"])
|
||||
(ckpt / "config.json").write_text(json.dumps(config_json, indent=2))
|
||||
state = {k: v.contiguous().clone() for k, v in model.state_dict().items()
|
||||
if k != "lm_head.weight"}
|
||||
save_file(state, ckpt / "model.safetensors")
|
||||
write_tokenizer(ckpt)
|
||||
|
||||
bf16, trunk, full = root / "model-bf16.rad", root / "model-trunk.rad", root / "model-iq8r.rad"
|
||||
trunk_recipe = root / "iq8r-trunk.recipe"
|
||||
trunk_recipe.write_text("".join(f"blk.*.{w}.weight gptq codes=i8 group=128 scale=bf16 "
|
||||
f"transform=fwht128 clamp=sym rule=search\n" for w in TRUNK))
|
||||
full_recipe = root / "iq8r.recipe"
|
||||
full_recipe.write_text(trunk_recipe.read_text() +
|
||||
"output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym "
|
||||
"rule=search\n")
|
||||
sets = ["--set", "quantization_config.quant_method=w8a8", "--set",
|
||||
"quantization_config.fmt=fwht128"]
|
||||
for out, extra in ((bf16, []), (trunk, ["--recipe", str(trunk_recipe)] + sets),
|
||||
(full, ["--recipe", str(full_recipe)] + sets)):
|
||||
subprocess.run([str(build / "bin/rad-convert"), str(ckpt), "-o", str(out),
|
||||
"--max-ctx", "64", "--max-tok", "32"] + extra, env=env, check=True,
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
got = {}
|
||||
with (root / "server.log").open("w+") as log:
|
||||
for tag, container in (("bf16", bf16), ("trunk", trunk), ("iq8r", full)):
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
proc, url = serve(build, container, port, env, log, tp=args.tp)
|
||||
try:
|
||||
for prompt in PROMPTS:
|
||||
got.setdefault(tag, {})[prompt] = generate(url, prompt)
|
||||
except Exception:
|
||||
log.flush()
|
||||
log.seek(0)
|
||||
print(log.read(), file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
# What a step's token costs against the Transformers reference: the same rule
|
||||
# tests/spark25_reference.py holds the bf16 model to, with the margin the int8 grid buys. This
|
||||
# fixture is a random model, so its candidates sit close together and a quantised run can flip
|
||||
# a greedy token; what it may not do is drift far, which is what a connection fed unrotated
|
||||
# codes or a scale plane read at the wrong width produces.
|
||||
# Bounds cover BF16/TP reduction rounding and 8-bit grid error at this geometry, while
|
||||
# rejecting a wrong rotation or scale plane. Compare probabilities as well as the sampled id:
|
||||
# an apparently correct argmax alone can hide a badly corrupted distribution.
|
||||
bounds = {"bf16": (0.1, 0.15), "trunk": (0.35, 0.4), "iq8r": (0.35, 0.4)}
|
||||
for prompt in PROMPTS:
|
||||
for tag, (bound, logp_bound) in bounds.items():
|
||||
ids, exact, gap, max_error = list(prompt.encode()), 0, 0.0, 0.0
|
||||
for row in got[tag][prompt]:
|
||||
expected = reference(ids)
|
||||
gap = max(gap, float(expected.max() - expected[row["id"]]))
|
||||
for candidate in row["top_logprobs"]:
|
||||
max_error = max(max_error, abs(candidate["logprob"] - float(expected[candidate["id"]])))
|
||||
if row["id"] == int(expected.argmax()):
|
||||
exact += 1
|
||||
ids.append(row["id"])
|
||||
print(f"{tag:5s} {prompt!r}: {exact}/5 greedy tokens match the reference, worst step "
|
||||
f"{gap:.5f} nats behind the reference's best candidate, max top-10 logp error "
|
||||
f"{max_error:.5f}")
|
||||
if gap > bound:
|
||||
raise AssertionError(f"{tag} {prompt!r}: a step is {gap:.5f} nats behind the "
|
||||
f"reference's best candidate (bound {bound})")
|
||||
if max_error > logp_bound:
|
||||
raise AssertionError(f"{tag} {prompt!r}: top-10 logp error {max_error:.5f} "
|
||||
f"exceeds {logp_bound}")
|
||||
print(f"TP={args.tp}: iq8r stays within the test's configured reference bounds")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay severe sparse-KL rows with a private, artifact-bound candidate server.
|
||||
|
||||
Requires run.json from spark25_quality.py. The server is started here, using that
|
||||
run's candidate, executable, plugins and settings; an arbitrary external URL or
|
||||
served-model alias cannot establish the model's identity. Run the whole command
|
||||
inside the same exclusive GPU/device scope as the original measurement.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from spark25_validation import (plugin_hashes, reference_provenance, same_path, sha256,
|
||||
validate_reference, validate_report)
|
||||
|
||||
|
||||
def bound_run(run_path, ref_dir, report_path):
|
||||
run = json.loads(Path(run_path).read_text())
|
||||
ref = json.loads((ref_dir / "kld.json").read_text())
|
||||
report = json.loads(report_path.read_text())
|
||||
same_path(run["reference_dir"], ref_dir, "run reference directory")
|
||||
validate_reference(ref, run["reference_model"], run["corpus"])
|
||||
if run["reference_manifest"] != ref:
|
||||
raise ValueError("run reference manifest differs from the supplied reference")
|
||||
matches = [item for item in run["candidates"].values()
|
||||
if Path(item["report"]).resolve() == report_path]
|
||||
if len(matches) != 1:
|
||||
raise ValueError("report must identify exactly one candidate in run.json")
|
||||
candidate = matches[0]
|
||||
validate_report(report, ref_dir, run["reference_model"], run["corpus"],
|
||||
candidate["model"], ref["rows"])
|
||||
same_path(candidate["rows"], str(report_path) + ".rows", "candidate row file")
|
||||
for path, expected in ((report_path, candidate["report_sha256"]),
|
||||
(candidate["rows"], candidate["rows_sha256"]),
|
||||
(candidate["model"], candidate["sha256"]),
|
||||
(run["reference_model"], run["reference_sha256"]),
|
||||
(run["corpus"], run["corpus_sha256"]),
|
||||
(run["radiance"], run["radiance_sha256"])):
|
||||
if sha256(path) != expected:
|
||||
raise ValueError(f"artifact hash differs from run.json: {path}")
|
||||
plugins = plugin_hashes(run["radiance_home"])
|
||||
if any(run[key] != value for key, value in plugins.items()):
|
||||
raise ValueError("plugin inventory differs from the scored run")
|
||||
common = ["--radiance-home", run["radiance_home"], "--kernels", run["kernel_selector"],
|
||||
"--tp", str(run["tp"]), "--kv-cache-dtype", "bf16", "--max-num-seqs", "1",
|
||||
"--max-model-len", str(run["max_model_len"]), "--max-num-batched-tokens",
|
||||
str(run["max_num_batched_tokens"]), "--gpu-headroom-mib",
|
||||
str(run["gpu_headroom_mib"]), "--num-speculative-tokens", "0", "--no-prefix-cache"]
|
||||
inputs = {key: run[key] for key in ("reference_model", "reference_sha256", "corpus",
|
||||
"corpus_sha256", "corpus_fnv1a64", "radiance",
|
||||
"radiance_sha256")}
|
||||
inputs.update(plugins=plugins, arguments=common)
|
||||
if reference_provenance(ref_dir, inputs, reuse=True) != run["reference_provenance"]:
|
||||
raise ValueError("run reference provenance differs from the scored baseline")
|
||||
return run, candidate, ref, report, common
|
||||
|
||||
|
||||
def get(url, timeout):
|
||||
with urllib.request.urlopen(url, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def post(url, model, prompt, timeout):
|
||||
request = urllib.request.Request(url + "/v1/completions", json.dumps({
|
||||
"model": model, "prompt": prompt, "max_tokens": 1, "temperature": 0,
|
||||
"ignore_eos": True, "logprobs": 20}).encode(), {"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def candidate_server(run, candidate, common, log_path):
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
model = "spark-tail-" + uuid.uuid4().hex
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
command = [run["radiance"], "--model", candidate["model"], *common,
|
||||
"--host", "127.0.0.1", "--port", str(port), "--served-model-name", model]
|
||||
# Never truncate a prior artifact or follow a symlink to a model/input.
|
||||
with log_path.open("x") as log:
|
||||
env = os.environ.copy()
|
||||
env.pop("HF_TOKEN", None)
|
||||
proc = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
deadline = time.monotonic() + 240
|
||||
while time.monotonic() < deadline:
|
||||
if proc.poll() is not None:
|
||||
raise RuntimeError(f"candidate server exited; see {log_path}")
|
||||
try:
|
||||
get(url + "/health", 1)
|
||||
break
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError(f"candidate server readiness timeout; see {log_path}")
|
||||
models = get(url + "/v1/models", 5)
|
||||
if (proc.poll() is not None or
|
||||
model not in {item.get("id") for item in models.get("data", [])}):
|
||||
raise ValueError("private server identity does not match the launched candidate")
|
||||
yield {"url": url, "model": model, "pid": proc.pid, "command": command}
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--run", required=True, type=Path, help="bound quality run.json")
|
||||
parser.add_argument("--reference", required=True, type=Path)
|
||||
parser.add_argument("--report", required=True, type=Path, help="candidate KLD JSON with .rows")
|
||||
parser.add_argument("--out", required=True, type=Path)
|
||||
parser.add_argument("--limit", type=int, default=20)
|
||||
parser.add_argument("--threshold", type=float, default=1.0)
|
||||
parser.add_argument("--timeout", type=float, default=120)
|
||||
args = parser.parse_args()
|
||||
if (args.limit < 1 or not math.isfinite(args.threshold) or args.threshold < 0 or
|
||||
not math.isfinite(args.timeout) or args.timeout <= 0):
|
||||
parser.error("limit/timeout must be positive and threshold finite and nonnegative")
|
||||
run_path, ref_dir = args.run.resolve(), args.reference.resolve()
|
||||
report_path, out = args.report.resolve(), args.out.resolve()
|
||||
if out.exists():
|
||||
parser.error("replay receipt already exists; choose a fresh --out")
|
||||
run_digest = sha256(run_path)
|
||||
run, candidate, ref, report, common = bound_run(run_path, ref_dir, report_path)
|
||||
n = ref["rows"]
|
||||
raw_rows = Path(candidate["rows"]).read_bytes()
|
||||
if len(raw_rows) != n * 16:
|
||||
raise ValueError("candidate .rows file has an unexpected size")
|
||||
values = struct.unpack("<" + "f" * (n * 4), raw_rows)
|
||||
kls = [values[4 * i] for i in range(n)]
|
||||
# Preserve signed roundoff near zero from core/kld.cpp rather than clamp the data.
|
||||
if not all(math.isfinite(kl) for kl in kls):
|
||||
raise ValueError("candidate has non-finite coarsened KL rows")
|
||||
above = [i for i, kl in enumerate(kls) if kl > args.threshold]
|
||||
selected = set(sorted(range(n), key=kls.__getitem__, reverse=True)[:args.limit])
|
||||
selected.update(above)
|
||||
selected = sorted(selected, key=kls.__getitem__, reverse=True)
|
||||
docs = ref["docs"]
|
||||
tokens_raw = (ref_dir / "tokens.i32").read_bytes()
|
||||
if len(tokens_raw) % 4:
|
||||
raise ValueError("tokens.i32 has an unexpected size")
|
||||
tokens = struct.unpack("<" + "i" * (len(tokens_raw) // 4), tokens_raw)
|
||||
token_starts, total = [], 0
|
||||
for doc in docs:
|
||||
token_starts.append(total)
|
||||
total += int(doc["tokens"])
|
||||
if total != len(tokens):
|
||||
raise ValueError("tokens.i32 length does not match the reference manifest")
|
||||
spans = [(int(d["row0"]), int(d["row0"]) + int(d["tokens"]) - int(d["score_from"]) - 1)
|
||||
for d in docs]
|
||||
top_raw = (ref_dir / "top.bin").read_bytes()
|
||||
if len(top_raw) != n * 128 * 8:
|
||||
raise ValueError("top.bin has an unexpected size")
|
||||
results = []
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
with candidate_server(run, candidate, common, out.with_suffix(".server.log")) as server:
|
||||
for row in selected:
|
||||
doc_index = next((i for i, (lo, hi) in enumerate(spans) if lo <= row < hi), None)
|
||||
if doc_index is None:
|
||||
raise ValueError(f"row {row} is outside every reference document")
|
||||
doc = docs[doc_index]
|
||||
token_pos = int(doc["score_from"]) + row - int(doc["row0"])
|
||||
begin = token_starts[doc_index]
|
||||
prompt = list(tokens[begin:begin + token_pos + 1])
|
||||
if not prompt:
|
||||
raise ValueError(f"row {row} produced an empty replay prompt")
|
||||
ref_entries = [struct.unpack_from("<if", top_raw, (row * 128 + i) * 8)
|
||||
for i in range(128)]
|
||||
ref_top = sorted(ref_entries, key=lambda item: (-item[1], item[0]))[:20]
|
||||
response = post(server["url"], server["model"], prompt, args.timeout)
|
||||
usage = response.get("usage", {})
|
||||
if (usage.get("prompt_tokens") != len(prompt) or usage.get("completion_tokens") != 1 or
|
||||
usage.get("prompt_tokens_details", {}).get("cached_tokens") != 0):
|
||||
raise ValueError(f"row {row}: prefix, completion or cold-cache accounting mismatch")
|
||||
content = response["choices"][0]["logprobs"]["content"]
|
||||
if len(content) != 1 or len(content[0]["top_logprobs"]) != 20:
|
||||
raise ValueError(f"row {row}: expected one scored output with top20")
|
||||
got_top = [{"token_id": int(item["id"]), "logprob": float(item["logprob"])}
|
||||
for item in content[0]["top_logprobs"]]
|
||||
if not all(math.isfinite(item["logprob"]) for item in got_top):
|
||||
raise ValueError(f"row {row}: non-finite candidate logprob")
|
||||
result = {"row": row, "source": doc.get("source", ""), "document_index": doc_index,
|
||||
"token_position": token_pos, "prompt_tokens": len(prompt), "coarsened_kl": kls[row],
|
||||
"top1_agreement_from_kld": bool(values[4 * row + 3]),
|
||||
"reference_top20": [{"token_id": int(i), "logprob": float(lp)} for i, lp in ref_top],
|
||||
"candidate_top20": got_top}
|
||||
results.append(result)
|
||||
print(f"row={row} source={result['source']} token={token_pos} prompt={len(prompt)} "
|
||||
f"top128+tail-KL={kls[row]:.6g} top1-agree={result['top1_agreement_from_kld']}")
|
||||
# A changed binary/model/report cannot silently acquire a successful replay receipt.
|
||||
bound_run(run_path, ref_dir, report_path)
|
||||
if sha256(run_path) != run_digest:
|
||||
raise ValueError("run.json changed during replay")
|
||||
out.write_text(json.dumps({"source_run": str(run_path), "source_run_sha256": run_digest,
|
||||
"reference": str(ref_dir), "candidate_report": str(report_path),
|
||||
"candidate_model": candidate["model"], "candidate_sha256": candidate["sha256"],
|
||||
"radiance_sha256": run["radiance_sha256"], "server": server,
|
||||
**{key: run[key] for key in plugin_hashes(run["radiance_home"])},
|
||||
"ref_form": report["ref_form"], "threshold": args.threshold,
|
||||
"rows_above_threshold": len(above), "replayed": results}, indent=2) + "\n")
|
||||
print(f"Replay receipt: {out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (KeyError, OSError, ValueError, TypeError, struct.error, urllib.error.URLError,
|
||||
TimeoutError, RuntimeError) as exc:
|
||||
print(f"spark25_kld_tail: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable real-container Spark latency/throughput smoke (end-to-end, not decode-only).
|
||||
|
||||
Run this separately for BF16, full IQ8R, and keep12 under an exclusive device scope. Each run
|
||||
starts one server, disables speculation and prefix caching, and replays the same held-out prompt
|
||||
strings at the requested concurrency levels. It records artifact hashes, p50/p95/max request
|
||||
latency, and aggregate generated-token throughput; it does not claim task quality.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
from spark25_validation import plugin_hashes, sha256
|
||||
|
||||
|
||||
def quantile(values, q):
|
||||
values = sorted(values)
|
||||
if not values:
|
||||
return 0.0
|
||||
at = q * (len(values) - 1)
|
||||
lo = int(at)
|
||||
return values[lo] if lo + 1 == len(values) else values[lo] + (at - lo) * (values[lo + 1] - values[lo])
|
||||
|
||||
|
||||
def prompts_from(path, raw):
|
||||
prompts = []
|
||||
for line_no, line in enumerate(raw.decode('utf-8').splitlines(), 1):
|
||||
if not line:
|
||||
continue
|
||||
row = json.loads(line)
|
||||
if not isinstance(row.get("prompt"), str) or not row["prompt"].strip():
|
||||
raise ValueError(f"{path}:{line_no}: expected a nonempty string prompt")
|
||||
prompts.append({"source": row.get("source", ""), "prompt": row["prompt"]})
|
||||
if not prompts:
|
||||
raise ValueError(f"{path}: no prompts")
|
||||
return prompts
|
||||
|
||||
|
||||
def request(url, model, prompt, max_tokens, timeout):
|
||||
body = {"model": model, "prompt": prompt, "max_tokens": max_tokens,
|
||||
"temperature": 0, "ignore_eos": True}
|
||||
req = urllib.request.Request(url + "/v1/completions", json.dumps(body).encode(),
|
||||
{"Content-Type": "application/json"})
|
||||
start = time.perf_counter()
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
data = json.load(response)
|
||||
elapsed = time.perf_counter() - start
|
||||
usage = data.get("usage")
|
||||
if not isinstance(usage, dict):
|
||||
raise ValueError("response is missing usage")
|
||||
prompt_tokens, completed = usage.get("prompt_tokens"), usage.get("completion_tokens")
|
||||
if type(prompt_tokens) is not int or prompt_tokens <= 0:
|
||||
raise ValueError("response must report a positive integer prompt_tokens count")
|
||||
if type(completed) is not int or completed != max_tokens:
|
||||
raise ValueError(f"response must report exactly {max_tokens} completion tokens, got {completed!r}")
|
||||
choices = data.get("choices", [])
|
||||
if len(choices) != 1 or choices[0].get("finish_reason") != "length":
|
||||
raise ValueError("forced-length QoS response did not finish at its requested length")
|
||||
if not math.isfinite(elapsed) or elapsed <= 0:
|
||||
raise ValueError("request duration is not a positive finite measurement")
|
||||
return {"seconds": elapsed, "prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": completed, "finish_reason": "length"}
|
||||
|
||||
|
||||
def verify_server(url, served, proc):
|
||||
if proc.poll() is not None:
|
||||
raise RuntimeError("candidate server exited during measurement")
|
||||
with urllib.request.urlopen(url + "/v1/models", timeout=5) as response:
|
||||
models = json.load(response)
|
||||
if served not in {item.get("id") for item in models.get("data", [])} or proc.poll() is not None:
|
||||
raise RuntimeError("private server identity does not match the launched candidate")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--radiance", required=True, type=Path)
|
||||
p.add_argument("--home", required=True, type=Path)
|
||||
p.add_argument("--model", required=True, type=Path)
|
||||
p.add_argument("--prompts", required=True, type=Path, help="JSONL with prompt and optional source")
|
||||
p.add_argument("--out", required=True, type=Path)
|
||||
p.add_argument("--source-root", type=Path)
|
||||
p.add_argument("--kernels", default="libr4d")
|
||||
p.add_argument("--tp", type=int, default=1)
|
||||
p.add_argument("--concurrency", default="1,4,8", help="comma-separated sequence counts")
|
||||
p.add_argument("--requests", type=int, default=16, help="requests per concurrency/repetition")
|
||||
p.add_argument("--repeats", type=int, default=3)
|
||||
p.add_argument("--max-tokens", type=int, default=32)
|
||||
p.add_argument("--max-model-len", type=int, default=16384)
|
||||
p.add_argument("--max-num-batched-tokens", type=int, default=4096)
|
||||
p.add_argument("--gpu-headroom-mib", type=int, default=1024)
|
||||
p.add_argument("--timeout", type=float, default=600)
|
||||
args = p.parse_args()
|
||||
|
||||
radiance, home, model = args.radiance.resolve(), args.home.resolve(), args.model.resolve()
|
||||
prompt_path, out = args.prompts.resolve(), args.out.resolve()
|
||||
prompt_bytes = prompt_path.read_bytes()
|
||||
prompt_hash = hashlib.sha256(prompt_bytes).hexdigest()
|
||||
prompts = prompts_from(prompt_path, prompt_bytes)
|
||||
concurrencies = [int(x) for x in args.concurrency.split(",")]
|
||||
if not concurrencies or any(x < 1 for x in concurrencies):
|
||||
p.error("--concurrency must be comma-separated positive integers")
|
||||
if (args.requests < 1 or args.repeats < 1 or args.max_tokens < 1 or args.tp < 1 or
|
||||
args.max_model_len < 1 or args.max_num_batched_tokens < 1 or args.gpu_headroom_mib < 0 or
|
||||
not math.isfinite(args.timeout) or args.timeout <= 0):
|
||||
p.error("counts/limits/timeout must be positive and finite; headroom must be nonnegative")
|
||||
if args.requests < max(concurrencies):
|
||||
p.error("requests per repeat must be at least the largest requested concurrency")
|
||||
for path in (radiance, model):
|
||||
if not path.is_file():
|
||||
p.error(f"not a file: {path}")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
if (out / "qos.json").exists():
|
||||
p.error("qos.json already exists; choose a fresh --out for this measurement")
|
||||
plugins = plugin_hashes(home)
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
served = "spark-qos-" + uuid.uuid4().hex
|
||||
command = [str(radiance), "--model", str(model), "--radiance-home", str(home),
|
||||
"--kernels", args.kernels, "--host", "127.0.0.1", "--port", str(port),
|
||||
"--served-model-name", served, "--tp", str(args.tp), "--kv-cache-dtype", "bf16",
|
||||
"--max-num-seqs", str(max(concurrencies)), "--max-model-len", str(args.max_model_len),
|
||||
"--max-num-batched-tokens", str(args.max_num_batched_tokens),
|
||||
"--gpu-headroom-mib", str(args.gpu_headroom_mib),
|
||||
"--num-speculative-tokens", "0", "--no-prefix-cache"]
|
||||
receipt = {"model": str(model), "model_sha256": sha256(model),
|
||||
"radiance": str(radiance), "radiance_sha256": sha256(radiance),
|
||||
"radiance_home": str(home), "prompt_file": str(prompt_path),
|
||||
"prompt_file_sha256": prompt_hash, "kernels": args.kernels,
|
||||
"tp": args.tp, "kv_cache_dtype": "bf16", "prefix_cache": False,
|
||||
"speculation": 0, "max_num_seqs": max(concurrencies),
|
||||
"max_model_len": args.max_model_len,
|
||||
"max_num_batched_tokens": args.max_num_batched_tokens,
|
||||
"gpu_headroom_mib": args.gpu_headroom_mib,
|
||||
"requests_per_repeat": args.requests, "repeats": args.repeats,
|
||||
"max_tokens": args.max_tokens, "command": command, **plugins, "results": {}}
|
||||
if args.source_root:
|
||||
root = args.source_root.resolve()
|
||||
receipt["source"] = {
|
||||
"root": str(root),
|
||||
"revision": subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"],
|
||||
check=True, capture_output=True, text=True).stdout.strip(),
|
||||
"status_porcelain": subprocess.run(["git", "-C", str(root), "status", "--porcelain"],
|
||||
check=True, capture_output=True, text=True).stdout.strip(),
|
||||
}
|
||||
env = os.environ.copy()
|
||||
env.pop("HF_TOKEN", None)
|
||||
# Exclusive create refuses existing files and symlinks, including symlinks to inputs.
|
||||
server_log = (out / "server.log").open("x+")
|
||||
proc = subprocess.Popen(command, env=env, stdout=server_log, stderr=subprocess.STDOUT)
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
try:
|
||||
deadline = time.monotonic() + 240
|
||||
while time.monotonic() < deadline:
|
||||
if proc.poll() is not None:
|
||||
raise RuntimeError(f"Radiance exited before readiness; see {out / 'server.log'}")
|
||||
try:
|
||||
with urllib.request.urlopen(url + "/health", timeout=1):
|
||||
break
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise TimeoutError(f"Radiance did not become ready; see {out / 'server.log'}")
|
||||
|
||||
verify_server(url, served, proc)
|
||||
for concurrency in concurrencies:
|
||||
samples = []
|
||||
started = time.perf_counter()
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
for repeat in range(args.repeats):
|
||||
for base in range(0, args.requests, concurrency):
|
||||
prompts_for_batch = [prompts[(repeat * args.requests + base + i) % len(prompts)]
|
||||
for i in range(min(concurrency, args.requests - base))]
|
||||
futures = [pool.submit(request, url, served, item["prompt"],
|
||||
args.max_tokens, args.timeout)
|
||||
for item in prompts_for_batch]
|
||||
samples.extend(f.result() for f in futures)
|
||||
wall = time.perf_counter() - started
|
||||
latencies = [x["seconds"] for x in samples]
|
||||
generated = sum(x["completion_tokens"] for x in samples)
|
||||
if (len(samples) != args.requests * args.repeats or
|
||||
generated != args.requests * args.repeats * args.max_tokens or
|
||||
not math.isfinite(wall) or wall <= 0):
|
||||
raise ValueError("QoS measurement did not complete the expected work")
|
||||
summary = {"requests": len(samples), "wall_seconds": wall,
|
||||
"latency_seconds": {"p50": quantile(latencies, 0.50),
|
||||
"p95": quantile(latencies, 0.95),
|
||||
"max": max(latencies, default=0.0)},
|
||||
"generated_tokens": generated,
|
||||
"aggregate_completion_tokens_per_second": generated / wall if wall else 0.0,
|
||||
"samples": samples}
|
||||
verify_server(url, served, proc)
|
||||
receipt["results"][str(concurrency)] = summary
|
||||
print(f"concurrency={concurrency} requests={len(samples)} p50={summary['latency_seconds']['p50']:.3f}s "
|
||||
f"p95={summary['latency_seconds']['p95']:.3f}s max={summary['latency_seconds']['max']:.3f}s "
|
||||
f"aggregate={summary['aggregate_completion_tokens_per_second']:.2f} tok/s")
|
||||
finally:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
server_log.close()
|
||||
if (plugin_hashes(home) != plugins or sha256(radiance) != receipt["radiance_sha256"] or
|
||||
sha256(model) != receipt["model_sha256"] or sha256(prompt_path) != prompt_hash):
|
||||
raise ValueError("runtime, model, prompt file or plugin inventory changed during the measurement")
|
||||
report = out / "qos.json"
|
||||
with report.open("x") as stream:
|
||||
stream.write(json.dumps(receipt, indent=2) + "\n")
|
||||
print(f"QoS receipt: {report}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (KeyError, OSError, ValueError, urllib.error.URLError, TimeoutError, RuntimeError) as exc:
|
||||
print(f"spark25_qos: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Matched BF16-vs-IQ8R KLD run for real Spark containers (no conversion is done).
|
||||
|
||||
The KLD reference uses the exact same tokenized corpus for every candidate and records top-128
|
||||
reference tokens plus the remaining probability mass as one tail bucket. Per-position candidate
|
||||
rows are kept so severe cases can be replayed with spark25_kld_tail.py.
|
||||
|
||||
Example (run inside an externally managed GPU scope when using libr4d):
|
||||
python3 tests/spark25_quality.py --radiance build/bin/radiance \\
|
||||
--home build/radiance_home --reference /models/spark-bf16.rad \\
|
||||
--corpus /eval/independent-chat-eval.jsonl --provenance /eval/independent-chat-eval.manifest.json \\
|
||||
--out /tmp/spark-quality --candidate full=/models/spark-iq8r.rad \\
|
||||
--candidate keep12=/models/spark-iq8r-keep12.rad
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
from spark25_validation import (fnv1a64, plugin_hashes, reference_provenance, sha256,
|
||||
validate_reference, validate_report)
|
||||
|
||||
|
||||
class ScoreStaging:
|
||||
"""Clean normally, but retain recoverable backups if rollback itself fails."""
|
||||
def __init__(self, out):
|
||||
self.path = Path(tempfile.mkdtemp(prefix=".spark25-score-", dir=out))
|
||||
self.keep = False
|
||||
self.published = False
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, traceback):
|
||||
if not self.keep:
|
||||
try:
|
||||
shutil.rmtree(self.path)
|
||||
except OSError as cleanup_error:
|
||||
state = "published" if self.published else "not published"
|
||||
print(f"spark25_quality: cleanup failed; results {state}; "
|
||||
f"staging remains at {self.path}: {cleanup_error}", file=sys.stderr)
|
||||
|
||||
|
||||
def parse_candidate(spec):
|
||||
name, sep, path = spec.partition("=")
|
||||
if not sep or not name or not path or Path(name).name != name or name in (".", ".."):
|
||||
raise argparse.ArgumentTypeError("candidate must be NAME=/path/to/model.rad")
|
||||
return name, Path(path).resolve()
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--radiance", required=True, type=Path)
|
||||
p.add_argument("--home", required=True, type=Path, help="RADIANCE_HOME / plugin tree")
|
||||
p.add_argument("--reference", required=True, type=Path, help="BF16 .rad reference")
|
||||
p.add_argument("--corpus", required=True, type=Path, help="held-out KLD corpus JSONL")
|
||||
p.add_argument("--provenance", type=Path, help="evaluation manifest to hash into the run receipt")
|
||||
p.add_argument("--calibration-manifest", type=Path,
|
||||
help="calibration dataset manifest to hash into the run receipt")
|
||||
p.add_argument("--source-root", type=Path, help="git checkout to record the exact source revision")
|
||||
p.add_argument("--out", required=True, type=Path)
|
||||
p.add_argument("--candidate", required=True, action="append", type=parse_candidate,
|
||||
metavar="NAME=RAD", help="repeat for each candidate container")
|
||||
p.add_argument("--kernels", default="libr4d")
|
||||
p.add_argument("--tp", type=int, default=1)
|
||||
p.add_argument("--max-model-len", type=int, default=4096)
|
||||
p.add_argument("--max-num-batched-tokens", type=int, default=128,
|
||||
help="match the rowfix Spark quality replay (default: 128)")
|
||||
p.add_argument("--gpu-headroom-mib", type=int, default=1024)
|
||||
p.add_argument("--reuse-reference", action="store_true",
|
||||
help="reuse an existing compatible top-128 reference instead of recording it")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
args = p.parse_args()
|
||||
if (args.tp < 1 or args.max_model_len < 1 or args.max_num_batched_tokens < 1 or
|
||||
args.gpu_headroom_mib < 0):
|
||||
p.error("TP/model/chunk limits must be positive and headroom nonnegative")
|
||||
|
||||
radiance, home, reference = args.radiance.resolve(), args.home.resolve(), args.reference.resolve()
|
||||
corpus, out = args.corpus.resolve(), args.out.resolve()
|
||||
candidates = args.candidate
|
||||
if len({name for name, _ in candidates}) != len(candidates):
|
||||
p.error("candidate names must be unique")
|
||||
for path in (radiance, reference, corpus, *(model for _, model in candidates)):
|
||||
if not path.is_file():
|
||||
p.error(f"not a file: {path}")
|
||||
ref_dir = out / "bf16-top128-ref"
|
||||
common = ["--radiance-home", str(home), "--kernels", args.kernels, "--tp", str(args.tp),
|
||||
"--kv-cache-dtype", "bf16", "--max-num-seqs", "1", "--max-model-len",
|
||||
str(args.max_model_len), "--max-num-batched-tokens", str(args.max_num_batched_tokens),
|
||||
"--gpu-headroom-mib", str(args.gpu_headroom_mib),
|
||||
"--num-speculative-tokens", "0", "--no-prefix-cache"]
|
||||
record = [str(radiance), "--model", str(reference), *common, "--kld-record", str(ref_dir),
|
||||
"--kld-corpus", str(corpus), "--kld-top", "128"]
|
||||
if args.dry_run:
|
||||
print(" ".join(record))
|
||||
for name, model in candidates:
|
||||
print(" ".join([str(radiance), "--model", str(model), *common, "--kld-ref",
|
||||
str(ref_dir), "--kld-out", str(out / f"{name}-kld.json")]))
|
||||
return 0
|
||||
|
||||
inputs = [radiance, reference, corpus, *(model for _, model in candidates)]
|
||||
inputs += [path.resolve() for path in (args.provenance, args.calibration_manifest) if path]
|
||||
# Plugin symlinks can point outside the home; protect the target bytes too.
|
||||
inputs += [path.resolve() for sub in ("kernels", "architectures", "quantizers")
|
||||
for path in (home / sub).rglob("*.so")]
|
||||
destinations = [out / "run.json"]
|
||||
for name, _ in candidates:
|
||||
report = out / f"{name}-kld.json"
|
||||
destinations.extend((report, Path(str(report) + ".rows")))
|
||||
if out == home or home in out.parents:
|
||||
p.error("output directory must not be inside the plugin home")
|
||||
for dest in destinations:
|
||||
if dest.is_symlink() or dest.resolve() in inputs or (dest.exists() and not dest.is_file()):
|
||||
p.error(f"output path collides with an input, symlink or non-file: {dest}")
|
||||
if ref_dir.is_symlink():
|
||||
p.error("reference output directory must not be a symlink")
|
||||
if any(path == ref_dir or ref_dir in path.parents for path in inputs):
|
||||
p.error("an input is inside the reference output directory")
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
# A failed retry must not leave a previous run's receipt looking like its result.
|
||||
(out / "run.json").unlink(missing_ok=True)
|
||||
|
||||
def snapshot_inputs():
|
||||
return {
|
||||
"reference_model": str(reference), "reference_sha256": sha256(reference),
|
||||
"corpus": str(corpus), "corpus_sha256": sha256(corpus),
|
||||
"corpus_fnv1a64": fnv1a64(corpus), "radiance": str(radiance),
|
||||
"radiance_sha256": sha256(radiance), "plugins": plugin_hashes(home),
|
||||
"arguments": list(common),
|
||||
}
|
||||
|
||||
reference_inputs = snapshot_inputs()
|
||||
plugins = reference_inputs["plugins"]
|
||||
|
||||
def verify_inputs():
|
||||
if snapshot_inputs() != reference_inputs:
|
||||
raise ValueError("reference inputs changed during recording or scoring")
|
||||
|
||||
ref_meta_path = ref_dir / "kld.json"
|
||||
if args.reuse_reference:
|
||||
if not ref_meta_path.is_file():
|
||||
p.error(f"--reuse-reference requested but {ref_meta_path} is missing")
|
||||
ref_meta = json.loads(ref_meta_path.read_text())
|
||||
else:
|
||||
if ref_dir.exists():
|
||||
p.error(f"reference directory already exists: {ref_dir}; choose another --out or use --reuse-reference")
|
||||
ref_dir.mkdir(parents=True)
|
||||
env = os.environ.copy()
|
||||
subprocess.run(record, env=env, check=True)
|
||||
# Check before trusting or binding any output from the recorder.
|
||||
verify_inputs()
|
||||
ref_meta = json.loads(ref_meta_path.read_text())
|
||||
|
||||
validate_reference(ref_meta, reference, corpus)
|
||||
# Never publish a binding if the recorder may have observed different input bytes.
|
||||
verify_inputs()
|
||||
bound_reference = reference_provenance(ref_dir, reference_inputs, args.reuse_reference)
|
||||
|
||||
run = {
|
||||
"reference_model": str(reference), "reference_sha256": reference_inputs["reference_sha256"],
|
||||
"reference_dir": str(ref_dir), "reference_form": "top-128 + tail",
|
||||
"corpus": str(corpus), "corpus_sha256": reference_inputs["corpus_sha256"],
|
||||
"corpus_fnv1a64": reference_inputs["corpus_fnv1a64"], "evaluation_manifest": None,
|
||||
"radiance": str(radiance), "radiance_sha256": reference_inputs["radiance_sha256"],
|
||||
"radiance_home": str(home), "kernel_selector": args.kernels,
|
||||
"tp": args.tp, "kv_cache_dtype": "bf16", "max_num_seqs": 1,
|
||||
"max_model_len": args.max_model_len,
|
||||
"max_num_batched_tokens": args.max_num_batched_tokens,
|
||||
"gpu_headroom_mib": args.gpu_headroom_mib,
|
||||
"speculation": 0, "prefix_cache": False,
|
||||
"reference_manifest": ref_meta, "reference_provenance": bound_reference,
|
||||
**plugins, "candidates": {},
|
||||
}
|
||||
if args.provenance:
|
||||
prov = args.provenance.resolve()
|
||||
run["evaluation_manifest"] = {"path": str(prov), "sha256": sha256(prov),
|
||||
"contents": json.loads(prov.read_text())}
|
||||
if args.calibration_manifest:
|
||||
calib = args.calibration_manifest.resolve()
|
||||
run["calibration_manifest"] = {"path": str(calib), "sha256": sha256(calib),
|
||||
"contents": json.loads(calib.read_text())}
|
||||
if args.source_root:
|
||||
root = args.source_root.resolve()
|
||||
def git(*cmd):
|
||||
return subprocess.run(["git", "-C", str(root), *cmd], check=True,
|
||||
stdout=subprocess.PIPE, text=True).stdout.strip()
|
||||
run["source"] = {"root": str(root), "revision": git("rev-parse", "HEAD"),
|
||||
"status_porcelain": git("status", "--porcelain")}
|
||||
|
||||
expected_rows = ref_meta.get("rows")
|
||||
with ScoreStaging(out) as staging:
|
||||
staged_outputs = []
|
||||
for name, model in candidates:
|
||||
report = out / f"{name}-kld.json"
|
||||
row_path = Path(str(report) + ".rows")
|
||||
staged_report = staging.path / report.name
|
||||
staged_rows = Path(str(staged_report) + ".rows")
|
||||
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
|
||||
"--kld-out", str(staged_report)]
|
||||
candidate_sha256 = sha256(model)
|
||||
subprocess.run(command, env=os.environ.copy(), check=True)
|
||||
scored = json.loads(staged_report.read_text())
|
||||
validate_report(scored, ref_dir, reference, corpus, model, expected_rows)
|
||||
if sha256(model) != candidate_sha256:
|
||||
p.error(f"{name}: candidate changed during scoring")
|
||||
values = scored["all"]["kld"]
|
||||
raw = staged_rows.read_bytes()
|
||||
if len(raw) != expected_rows * 16:
|
||||
p.error(f"{name}: unexpected per-position rows size {len(raw)}")
|
||||
row_values = struct.unpack("<" + "f" * (expected_rows * 4), raw)
|
||||
kl = [row_values[i * 4] for i in range(expected_rows)]
|
||||
# core/kld.cpp's A/S - log(S) can retain tiny signed roundoff near zero.
|
||||
if not all(math.isfinite(value) for value in kl):
|
||||
p.error(f"{name}: non-finite coarsened KL row")
|
||||
run["candidates"][name] = {"model": str(model), "sha256": candidate_sha256,
|
||||
"report": str(report), "report_sha256": sha256(staged_report),
|
||||
"rows": str(row_path), "rows_sha256": sha256(staged_rows),
|
||||
"metrics": scored["all"],
|
||||
"positions_over_1_nat": sum(x > 1.0 for x in kl)}
|
||||
staged_outputs.extend(((staged_report, report), (staged_rows, row_path)))
|
||||
print(f"{name}: {expected_rows} positions; ref_form={scored['ref_form']}; "
|
||||
f"mean={values['mean']:.6g}, p99={values['p99']:.6g}, "
|
||||
f"p99.9={values['p99_9']:.6g}, max={values['max']:.6g}, "
|
||||
f">1 nat={run['candidates'][name]['positions_over_1_nat']}")
|
||||
|
||||
verify_inputs()
|
||||
reference_provenance(ref_dir, reference_inputs, reuse=True)
|
||||
receipt_temp = staging.path / "new-run.json"
|
||||
receipt_temp.write_text(json.dumps(run, indent=2) + "\n")
|
||||
backups = []
|
||||
promoted = []
|
||||
try:
|
||||
for index, (source, destination) in enumerate(staged_outputs):
|
||||
backup = staging.path / f"backup-{index}"
|
||||
if destination.exists():
|
||||
os.replace(destination, backup)
|
||||
backups.append((backup, destination))
|
||||
os.replace(source, destination)
|
||||
promoted.append(destination)
|
||||
os.replace(receipt_temp, out / "run.json")
|
||||
staging.published = True
|
||||
except BaseException as publication_error:
|
||||
# Continue after individual rollback errors; retain all remaining backups on failure.
|
||||
rollback_errors = []
|
||||
for destination in reversed(promoted):
|
||||
try:
|
||||
destination.unlink(missing_ok=True)
|
||||
except OSError as exc:
|
||||
rollback_errors.append(f"remove {destination}: {exc}")
|
||||
for backup, destination in reversed(backups):
|
||||
try:
|
||||
os.replace(backup, destination)
|
||||
except OSError as exc:
|
||||
rollback_errors.append(f"restore {backup} -> {destination}: {exc}")
|
||||
if rollback_errors:
|
||||
staging.keep = True
|
||||
raise RuntimeError(f"score publication failed ({publication_error}); rollback "
|
||||
f"incomplete; recover backups in {staging.path}: "
|
||||
+ "; ".join(rollback_errors)) from publication_error
|
||||
raise
|
||||
print(f"Run receipt: {out / 'run.json'}")
|
||||
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
|
||||
"tests/spark25_kld_tail.py. These are top-128-plus-tail KL values, not full-vocabulary KL.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except (KeyError, OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as exc:
|
||||
print(f"spark25_quality: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,71 @@
|
||||
/* Regression tests for the shipped Spark IQ8R recipe allocations. */
|
||||
#include "rad_test.h"
|
||||
#include "format/recipe.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
static bool load_recipe(const char* name, Recipe* recipe) {
|
||||
const std::string path = std::string(RAD_SPARK25_RECIPE_DIR) + "/" + name;
|
||||
std::ifstream in(path);
|
||||
if (!in) return false;
|
||||
std::ostringstream text;
|
||||
text << in.rdbuf();
|
||||
std::string why;
|
||||
return recipe->add_text(text.str(), path, &why) == RAD_OK;
|
||||
}
|
||||
|
||||
static std::string option(const RecipeRule& rule, const std::string& key) {
|
||||
for (const auto& [k, v] : rule.options)
|
||||
if (k == key) return v;
|
||||
return {};
|
||||
}
|
||||
|
||||
static void check_iq8r_rule(const RecipeRule* rule, const char* quantizer, bool calibrated) {
|
||||
REQUIRE(rule != nullptr);
|
||||
CHECK_EQ(rule->quantizer, std::string(quantizer));
|
||||
CHECK_EQ(option(*rule, "codes"), std::string("i8"));
|
||||
CHECK_EQ(option(*rule, "group"), std::string("128"));
|
||||
CHECK_EQ(option(*rule, "scale"), std::string("bf16"));
|
||||
CHECK_EQ(option(*rule, "clamp"), std::string("sym"));
|
||||
CHECK_EQ(option(*rule, "rule"), std::string("search"));
|
||||
if (calibrated) {
|
||||
CHECK_EQ(option(*rule, "transform"), std::string("fwht128"));
|
||||
CHECK_EQ(option(*rule, "calib"), std::string("/test/spark-grams"));
|
||||
} else {
|
||||
CHECK(option(*rule, "transform").empty());
|
||||
CHECK(option(*rule, "calib").empty());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(spark_iq8r_recipes_allocate_the_quality_and_full_variants_explicitly) {
|
||||
REQUIRE_EQ(::setenv("CALIB", "/test/spark-grams", 1), 0);
|
||||
const char* projections[] = {"attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", "ffn_down"};
|
||||
Recipe keep12, full;
|
||||
REQUIRE(load_recipe("spark-x26-4b-iq8r-keep12.recipe", &keep12));
|
||||
REQUIRE(load_recipe("spark-x26-4b-iq8r.recipe", &full));
|
||||
|
||||
for (int layer = 0; layer < 36; ++layer) {
|
||||
for (const char* projection : projections) {
|
||||
const std::string name = "blk." + std::to_string(layer) + "." + projection + ".weight";
|
||||
const RecipeRule* hybrid = keep12.match(name);
|
||||
if (layer < 12) {
|
||||
CHECK(hybrid == nullptr); // unmatched tensors retain source BF16
|
||||
} else {
|
||||
check_iq8r_rule(hybrid, "gptq", true);
|
||||
}
|
||||
check_iq8r_rule(full.match(name), "gptq", true);
|
||||
}
|
||||
}
|
||||
check_iq8r_rule(keep12.match("output.weight"), "rtn", false);
|
||||
check_iq8r_rule(full.match("output.weight"), "rtn", false);
|
||||
CHECK(keep12.match("blk.0.attn_gate.weight") == nullptr);
|
||||
CHECK(keep12.match("token_embd.weight") == nullptr);
|
||||
CHECK(full.match("blk.35.input_norm.weight") == nullptr);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CPU-only differential test against a Spark checkpoint's modeling_spark.py.
|
||||
|
||||
Requires torch, transformers and safetensors. It creates a tiny two-layer random checkpoint,
|
||||
converts and serves it on the host, then compares prefill and cached decode with the HF reference.
|
||||
--tp N runs the same fixture over N fake host devices (RADIANCE_HOST_DEVICES), which is how the
|
||||
tensor-parallel sharding and collectives are held to the reference without cards.
|
||||
No model weights are copied from the reference checkpoint, and GPUs are hidden from both processes.
|
||||
ROCm may still open device nodes when probing; use a GPU-denying device cgroup on shared machines.
|
||||
"""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import types
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
# Set before importing torch or launching a Radiance child, even on a HIP-enabled build.
|
||||
os.environ.update(ROCR_VISIBLE_DEVICES="GPU-no-such-device", HIP_VISIBLE_DEVICES="",
|
||||
CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS="2", OMP_WAIT_POLICY="passive")
|
||||
|
||||
|
||||
def load_reference(path):
|
||||
pkg = types.ModuleType("spark25_reference")
|
||||
pkg.__path__ = [str(path)]
|
||||
sys.modules[pkg.__name__] = pkg
|
||||
for name in ("configuration_spark", "modeling_spark"):
|
||||
spec = importlib.util.spec_from_file_location(pkg.__name__ + "." + name, path / (name + ".py"))
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError("cannot load " + name)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
return sys.modules[pkg.__name__ + ".configuration_spark"], sys.modules[pkg.__name__ + ".modeling_spark"]
|
||||
|
||||
|
||||
def write_tokenizer(path):
|
||||
def symbol(b):
|
||||
def printable(c):
|
||||
return 33 <= c <= 126 or 161 <= c <= 172 or 174 <= c <= 255
|
||||
return chr(b if printable(b) else 256 + sum(not printable(c) for c in range(b)))
|
||||
vocab = {symbol(b): b for b in range(256)}
|
||||
added = []
|
||||
for i, s in enumerate(("<|endoftext|>", "<|im_start|>", "<|im_end|>")):
|
||||
vocab[s] = 256 + i
|
||||
added.append(dict(id=256 + i, content=s, single_word=False, lstrip=False,
|
||||
rstrip=False, normalized=False, special=True))
|
||||
# Vocabulary shards are rounded to 128-row blocks; 3584 rows give worlds 1 to 8 a nonempty
|
||||
# shard, including ragged worlds such as TP=3.
|
||||
for i in range(259, 3584):
|
||||
s = f"<extra_{i}>"
|
||||
vocab[s] = i
|
||||
added.append(dict(id=i, content=s, single_word=False, lstrip=False,
|
||||
rstrip=False, normalized=False, special=False))
|
||||
bytelevel = dict(type="ByteLevel", add_prefix_space=False, trim_offsets=False, use_regex=True)
|
||||
tok = dict(version="1.0", added_tokens=added, normalizer=None, pre_tokenizer=bytelevel,
|
||||
post_processor=None, decoder=bytelevel,
|
||||
model=dict(type="BPE", dropout=None, unk_token=None, byte_fallback=False,
|
||||
vocab=vocab, merges=[]))
|
||||
(path / "tokenizer.json").write_text(json.dumps(tok, ensure_ascii=False))
|
||||
|
||||
|
||||
# The last prompt crosses the 32-token prefill chunk boundary; the third leaves the local window.
|
||||
PROMPTS = ("a", "hello", "longer prompt", "the quick brown fox jumps over the lazy dog twice")
|
||||
|
||||
|
||||
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",
|
||||
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)
|
||||
url = f"http://127.0.0.1:{port}"
|
||||
for _ in range(300):
|
||||
if proc.poll() is not None:
|
||||
proc.wait()
|
||||
raise RuntimeError("Radiance exited before listening")
|
||||
try:
|
||||
urllib.request.urlopen(url + "/health", timeout=1).close()
|
||||
return proc, url
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(0.1)
|
||||
stop(proc)
|
||||
raise RuntimeError("Radiance did not start")
|
||||
|
||||
|
||||
def stop(proc):
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
|
||||
|
||||
def generate(url, prompt, steps=5, logprobs=10):
|
||||
"""Greedy decode of `steps` tokens with the top candidates at each step."""
|
||||
data = json.dumps(dict(prompt=prompt, max_tokens=steps, temperature=0, logprobs=logprobs,
|
||||
ignore_eos=True)).encode()
|
||||
req = urllib.request.Request(url + "/v1/completions", data,
|
||||
{"Content-Type": "application/json"})
|
||||
rows = json.load(urllib.request.urlopen(req, timeout=30))["choices"][0]["logprobs"]["content"]
|
||||
if len(rows) != steps:
|
||||
raise AssertionError(f"{prompt!r}: expected {steps} decode rows, got {len(rows)}")
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--reference", required=True, type=Path, help="directory with modeling_spark.py")
|
||||
ap.add_argument("--build", required=True, type=Path, help="Radiance build directory")
|
||||
ap.add_argument("--tp", type=int, default=1, help="number of fake host ranks (up to 8)")
|
||||
args = ap.parse_args()
|
||||
if args.tp < 1 or args.tp > 8:
|
||||
ap.error("--tp must be between 1 and 8")
|
||||
import torch
|
||||
import transformers
|
||||
from safetensors.torch import save_file
|
||||
|
||||
torch.set_num_threads(2)
|
||||
cfgmod, modelmod = load_reference(args.reference.resolve())
|
||||
# The checkpoint targets Transformers 4.57; v5 changed this declaration from a list to a map.
|
||||
if int(transformers.__version__.split(".")[0]) >= 5:
|
||||
modelmod.Spark2_5ForCausalLM._tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}
|
||||
config = cfgmod.Spark2_5Config(
|
||||
vocab_size=3584, hidden_size=32, intermediate_size=64, num_hidden_layers=2,
|
||||
num_attention_heads=8, num_key_value_heads=4, head_dim=4, hidden_act="gelu",
|
||||
max_position_embeddings=128, rms_norm_eps=1e-6, tie_word_embeddings=True,
|
||||
headwise_attn_output_gate=True, gate_attn_act_mode="sigmoid", sliding_window=4,
|
||||
layer_types=["sliding_attention", "full_attention"],
|
||||
rope_parameters={"sliding_attention": {"rope_theta": 10000.0, "partial_rotary_factor": 1.0},
|
||||
"full_attention": {"rope_theta": 5000000.0, "partial_rotary_factor": 0.5}},
|
||||
bos_token_id=256, eos_token_id=256, pad_token_id=256)
|
||||
torch.manual_seed(19)
|
||||
model = modelmod.Spark2_5ForCausalLM(config).eval().to(torch.bfloat16)
|
||||
with torch.no_grad():
|
||||
for name, w in model.named_parameters():
|
||||
if name.endswith("layernorm.weight") or name == "model.norm.weight":
|
||||
w.copy_((1 + 0.08 * torch.randn(w.shape)).to(w.dtype))
|
||||
elif name == "model.embedding.weight":
|
||||
w.copy_((0.4 * torch.randn(w.shape)).to(w.dtype))
|
||||
elif name.endswith("g_proj.weight"):
|
||||
w.copy_((0.2 * torch.randn(w.shape)).to(w.dtype))
|
||||
else:
|
||||
w.copy_((0.16 * torch.randn(w.shape)).to(w.dtype))
|
||||
|
||||
def reference(ids):
|
||||
n = len(ids)
|
||||
q, k = torch.arange(n)[:, None], torch.arange(n)[None, :]
|
||||
full = torch.where(k <= q, 0.0, float("-inf"))[None, None, :, :]
|
||||
local = torch.where((k <= q) & (k > q - config.sliding_window), 0.0,
|
||||
float("-inf"))[None, None, :, :]
|
||||
# Explicit masks also bridge the Transformers 4.57/5.x mask-helper signature change.
|
||||
with torch.inference_mode():
|
||||
logits = model(torch.tensor([ids]), attention_mask={"full_attention": full,
|
||||
"sliding_attention": local}, use_cache=False).logits[0, -1].float()
|
||||
return torch.log_softmax(logits, dim=-1)
|
||||
|
||||
build = args.build.resolve()
|
||||
env = os.environ.copy()
|
||||
env.update(RADIANCE_HOME=str(build / "radiance_home"), RADIANCE_HOST_VRAM_MIB="512",
|
||||
RADIANCE_HOST_DEVICES=str(args.tp))
|
||||
with tempfile.TemporaryDirectory(prefix="spark25-reference-") as tmp:
|
||||
root = Path(tmp)
|
||||
ckpt = root / "checkpoint"
|
||||
ckpt.mkdir()
|
||||
config_json = config.to_dict()
|
||||
config_json.update(model_type="spark2_5", architectures=["Spark2_5ForCausalLM"])
|
||||
(ckpt / "config.json").write_text(json.dumps(config_json, indent=2))
|
||||
state = {k: v.contiguous().clone() for k, v in model.state_dict().items() if k != "lm_head.weight"}
|
||||
save_file(state, ckpt / "model.safetensors")
|
||||
write_tokenizer(ckpt)
|
||||
rad = root / "model.rad"
|
||||
subprocess.run([build / "bin/rad-convert", ckpt, "-o", rad, "--max-ctx", "64",
|
||||
"--max-tok", "32"], env=env, check=True)
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
with (root / "server.log").open("w+") as log:
|
||||
proc = None
|
||||
try:
|
||||
proc, url = serve(build, rad, port, env, log, tp=args.tp)
|
||||
# Compare cached decode with the same HF continuation.
|
||||
for prompt in PROMPTS:
|
||||
rows = generate(url, prompt)
|
||||
ids = list(prompt.encode())
|
||||
max_error = 0.0
|
||||
matches = 0
|
||||
for row in rows:
|
||||
expected = reference(ids)
|
||||
if row["id"] == int(expected.argmax()):
|
||||
matches += 1
|
||||
# A shard changes the order of a bf16 reduction, which can swap two
|
||||
# candidates closer than this. A wider gap is a wrong model, not rounding.
|
||||
elif float(expected.max() - expected[row["id"]]) > 0.1:
|
||||
raise AssertionError(
|
||||
f"{prompt!r}: token {row['id']} != reference "
|
||||
f"{int(expected.argmax())}, {float(expected.max() - expected[row['id']]):.5f} nats behind")
|
||||
for candidate in row["top_logprobs"]:
|
||||
max_error = max(max_error,
|
||||
abs(candidate["logprob"] - float(expected[candidate["id"]])))
|
||||
ids.append(row["id"])
|
||||
# BF16 logits / attention reduction order differ slightly from CPU torch.
|
||||
if max_error >= 0.15:
|
||||
raise AssertionError(f"{prompt!r}: max top-10 log-prob error {max_error:.5f}")
|
||||
print(f"TP={args.tp} {prompt!r}: {matches}/5 exact top-1, "
|
||||
f"max top-10 log-prob error {max_error:.5f}")
|
||||
except Exception:
|
||||
log.flush()
|
||||
log.seek(0)
|
||||
print(log.read(), file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
if proc is not None:
|
||||
stop(proc)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Artifact and reference bindings shared by the real-container Spark probes."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def sha256(path):
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def fnv1a64(path):
|
||||
# core/kld.cpp hashes each getline without its terminating LF.
|
||||
value = 1469598103934665603
|
||||
with Path(path).open("rb") as stream:
|
||||
for line in stream:
|
||||
if line.endswith(b"\n"):
|
||||
line = line[:-1]
|
||||
for byte in line:
|
||||
value = ((value ^ byte) * 1099511628211) & 0xffffffffffffffff
|
||||
return f"{value:016x}"
|
||||
|
||||
|
||||
def plugin_hashes(home):
|
||||
home = Path(home).resolve()
|
||||
if ":" in str(home):
|
||||
raise ValueError("these probes require one explicit RADIANCE_HOME, not a search path")
|
||||
result = {}
|
||||
for directory, key in (("kernels", "kernel_shared_objects"),
|
||||
("architectures", "architecture_shared_objects"),
|
||||
("quantizers", "quantizer_shared_objects")):
|
||||
result[key] = {str(path.relative_to(home)): sha256(path)
|
||||
for path in sorted((home / directory).rglob("*.so"))}
|
||||
if directory != "quantizers" and not result[key]:
|
||||
raise ValueError(f"no shared objects found in {home / directory}")
|
||||
return result
|
||||
|
||||
|
||||
def same_path(value, expected, label):
|
||||
if not isinstance(value, str) or not value or Path(value).resolve() != Path(expected).resolve():
|
||||
raise ValueError(f"{label} does not match {expected}")
|
||||
|
||||
|
||||
def validate_reference(meta, reference, corpus):
|
||||
if meta.get("format") != "radiance-kld-top-1" or meta.get("top") != 128:
|
||||
raise ValueError("reference must be radiance-kld-top-1 with top=128")
|
||||
same_path(meta.get("model"), reference, "reference model")
|
||||
same_path(meta.get("corpus"), corpus, "reference corpus")
|
||||
if meta.get("corpus_fnv1a64") != fnv1a64(corpus):
|
||||
raise ValueError("reference corpus hash does not match the corpus")
|
||||
if type(meta.get("rows")) is not int or meta["rows"] <= 0:
|
||||
raise ValueError("reference must have a positive integer row count")
|
||||
|
||||
|
||||
def validate_report(report, ref_dir, reference, corpus, candidate, rows):
|
||||
if report.get("ref_form") != "top-128 + tail":
|
||||
raise ValueError("report must use the top-128-plus-tail reference")
|
||||
for key, expected in (("ref_dir", ref_dir), ("reference", reference),
|
||||
("corpus", corpus), ("model", candidate)):
|
||||
same_path(report.get(key), expected, f"report {key}")
|
||||
if report.get("all", {}).get("positions") != rows:
|
||||
raise ValueError("report row count does not match the reference")
|
||||
|
||||
|
||||
def reference_provenance(ref_dir, inputs, reuse):
|
||||
"""Reject legacy/unbound references rather than relabel their baseline in a new receipt."""
|
||||
ref_dir = Path(ref_dir)
|
||||
path = ref_dir / "provenance.json"
|
||||
current = {"format": "spark25-reference-provenance-1", "inputs": inputs,
|
||||
"files": {name: sha256(ref_dir / name)
|
||||
for name in ("kld.json", "tokens.i32", "top.bin", "rows.f32")}}
|
||||
if reuse:
|
||||
if not path.is_file():
|
||||
raise ValueError("reference lacks provenance.json; record a fresh bound reference")
|
||||
if json.loads(path.read_text()) != current:
|
||||
raise ValueError("reused reference baseline, runtime, settings or data identity differs")
|
||||
else:
|
||||
if path.exists():
|
||||
raise ValueError(f"refusing to replace existing reference provenance: {path}")
|
||||
temporary = path.with_suffix(".json.tmp")
|
||||
temporary.write_text(json.dumps(current, indent=2) + "\n")
|
||||
temporary.replace(path)
|
||||
return current
|
||||
@@ -0,0 +1,549 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CPU-only positive/negative controls for Spark measurement attribution (not GPU evidence)."""
|
||||
import contextlib
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import spark25_kld_tail as tail
|
||||
import spark25_qos as qos
|
||||
import spark25_quality as quality
|
||||
from spark25_validation import fnv1a64, plugin_hashes, sha256, validate_report
|
||||
|
||||
|
||||
class MeasurementTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.home = self.root / "home"
|
||||
for directory in ("kernels", "architectures", "quantizers"):
|
||||
(self.home / directory).mkdir(parents=True)
|
||||
(self.home / directory / "fixture.so").write_bytes(directory.encode())
|
||||
self.reference = self.root / "bf16.rad"
|
||||
self.candidate = self.root / "candidate.rad"
|
||||
self.runtime = self.root / "radiance"
|
||||
self.corpus = self.root / "corpus.jsonl"
|
||||
self.reference.write_bytes(b"BF16 checkpoint")
|
||||
self.candidate.write_bytes(b"IQ8R checkpoint")
|
||||
self.runtime.write_bytes(b"not executed; subprocess is mocked")
|
||||
self.corpus.write_text('{"prompt":"a b", "score_from":0}\n')
|
||||
self.out = self.root / "quality"
|
||||
self.score_kl = .1
|
||||
|
||||
def fake_runtime(self, command, **kwargs):
|
||||
def arg(name):
|
||||
return command[command.index(name) + 1]
|
||||
if "--kld-record" in command:
|
||||
directory = Path(arg("--kld-record"))
|
||||
meta = {"format": "radiance-kld-top-1", "model": arg("--model"),
|
||||
"corpus": arg("--kld-corpus"), "corpus_fnv1a64": fnv1a64(self.corpus),
|
||||
"top": 128, "rows": 1,
|
||||
"docs": [{"tokens": 2, "score_from": 0, "row0": 0, "source": "fixture"}]}
|
||||
(directory / "kld.json").write_text(json.dumps(meta))
|
||||
(directory / "tokens.i32").write_bytes(struct.pack("<ii", 1, 2))
|
||||
(directory / "rows.f32").write_bytes(struct.pack("<fff", 0, 0, 0))
|
||||
(directory / "top.bin").write_bytes(b"".join(struct.pack("<if", i, -float(i + 1))
|
||||
for i in range(128)))
|
||||
else:
|
||||
directory = Path(arg("--kld-ref"))
|
||||
meta = json.loads((directory / "kld.json").read_text())
|
||||
report = {"model": arg("--model"), "reference": meta["model"],
|
||||
"ref_dir": str(directory), "corpus": meta["corpus"],
|
||||
"ref_form": "top-128 + tail", "all": {"positions": 1,
|
||||
"kld": {key: self.score_kl for key in ("mean", "p99", "p99_9", "max")}}}
|
||||
path = Path(arg("--kld-out"))
|
||||
path.write_text(json.dumps(report))
|
||||
Path(str(path) + ".rows").write_bytes(struct.pack("<ffff", self.score_kl, 0, 0, 1))
|
||||
|
||||
def quality_args(self, *extra):
|
||||
return ["spark25_quality.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--reference", str(self.reference), "--corpus", str(self.corpus),
|
||||
"--candidate", "full=" + str(self.candidate), "--out", str(self.out), *extra]
|
||||
|
||||
def record_quality(self, *extra):
|
||||
with patch.object(sys, "argv", self.quality_args(*extra)), \
|
||||
patch.object(quality.subprocess, "run", side_effect=self.fake_runtime) as execute, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(quality.main(), 0)
|
||||
return execute
|
||||
|
||||
def test_plugin_inventory_includes_architecture_and_optional_quantizer(self):
|
||||
inventory = plugin_hashes(self.home)
|
||||
for directory, key in (("kernels", "kernel_shared_objects"),
|
||||
("architectures", "architecture_shared_objects"),
|
||||
("quantizers", "quantizer_shared_objects")):
|
||||
self.assertEqual(inventory[key][directory + "/fixture.so"],
|
||||
sha256(self.home / directory / "fixture.so"))
|
||||
|
||||
def test_missing_architecture_inventory_rejected(self):
|
||||
(self.home / "architectures/fixture.so").unlink()
|
||||
with self.assertRaisesRegex(ValueError, "no shared objects"):
|
||||
plugin_hashes(self.home)
|
||||
|
||||
def test_valid_quality_receipt_and_reuse_are_bound(self):
|
||||
self.record_quality()
|
||||
run = json.loads((self.out / "run.json").read_text())
|
||||
self.assertIn("architectures/fixture.so", run["architecture_shared_objects"])
|
||||
self.assertEqual(run["reference_provenance"]["inputs"]["reference_sha256"], sha256(self.reference))
|
||||
self.assertEqual(run["candidates"]["full"]["report_sha256"], sha256(self.out / "full-kld.json"))
|
||||
execute = self.record_quality("--reuse-reference")
|
||||
self.assertEqual(execute.call_count, 1) # score only, no new reference recording
|
||||
|
||||
def test_recording_input_mutations_do_not_publish_provenance_or_receipt(self):
|
||||
paths = (self.reference, self.runtime, self.corpus, self.home / "architectures/fixture.so")
|
||||
for index, path in enumerate(paths):
|
||||
with self.subTest(path=path):
|
||||
self.out = self.root / f"record-mutation-{index}"
|
||||
original = path.read_bytes()
|
||||
|
||||
def mutate_during_record(command, **kwargs):
|
||||
self.fake_runtime(command, **kwargs)
|
||||
if "--kld-record" in command:
|
||||
path.write_bytes(original + b"changed")
|
||||
|
||||
try:
|
||||
with patch.object(sys, "argv", self.quality_args()), \
|
||||
patch.object(quality.subprocess, "run", side_effect=mutate_during_record) as execute:
|
||||
with self.assertRaisesRegex(ValueError, "reference inputs changed"):
|
||||
quality.main()
|
||||
self.assertEqual(execute.call_count, 1)
|
||||
self.assertFalse((self.out / "bf16-top128-ref/provenance.json").exists())
|
||||
self.assertFalse((self.out / "run.json").exists())
|
||||
finally:
|
||||
path.write_bytes(original)
|
||||
|
||||
def test_scoring_input_mutations_prevent_success_receipt(self):
|
||||
paths = (self.reference, self.runtime, self.corpus, self.home / "architectures/fixture.so")
|
||||
for index, path in enumerate(paths):
|
||||
with self.subTest(path=path):
|
||||
self.out = self.root / f"score-mutation-{index}"
|
||||
original = path.read_bytes()
|
||||
|
||||
def mutate_during_score(command, **kwargs):
|
||||
self.fake_runtime(command, **kwargs)
|
||||
if "--kld-ref" in command:
|
||||
path.write_bytes(original + b"changed")
|
||||
|
||||
try:
|
||||
with patch.object(sys, "argv", self.quality_args()), \
|
||||
patch.object(quality.subprocess, "run", side_effect=mutate_during_score), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaisesRegex(ValueError, "reference inputs changed"):
|
||||
quality.main()
|
||||
self.assertFalse((self.out / "run.json").exists())
|
||||
finally:
|
||||
path.write_bytes(original)
|
||||
|
||||
def test_failed_retry_removes_previous_success_receipt(self):
|
||||
self.record_quality()
|
||||
self.reference.write_bytes(b"changed")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")):
|
||||
with self.assertRaises(ValueError):
|
||||
quality.main()
|
||||
self.assertFalse((self.out / "run.json").exists())
|
||||
|
||||
def test_signed_kl_roundoff_is_preserved(self):
|
||||
self.score_kl = -1e-10
|
||||
self.record_quality()
|
||||
self.bind_tail()
|
||||
raw = (self.out / "full-kld.json.rows").read_bytes()
|
||||
self.assertLess(struct.unpack_from("<f", raw)[0], 0)
|
||||
|
||||
def test_nonfinite_kl_does_not_emit_success_receipt(self):
|
||||
for value in (float("nan"), float("inf")):
|
||||
with self.subTest(value=value):
|
||||
self.out = self.root / str(value)
|
||||
self.score_kl = value
|
||||
with patch.object(sys, "argv", self.quality_args()), \
|
||||
patch.object(quality.subprocess, "run", side_effect=self.fake_runtime), \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit):
|
||||
quality.main()
|
||||
self.assertFalse((self.out / "run.json").exists())
|
||||
|
||||
def test_reuse_rejects_changed_baseline_bytes_at_same_path(self):
|
||||
self.record_quality()
|
||||
self.reference.write_bytes(b"different BF16 checkpoint at the same path")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")), \
|
||||
patch.object(quality.subprocess, "run") as execute:
|
||||
with self.assertRaisesRegex(ValueError, "baseline, runtime, settings or data"):
|
||||
quality.main()
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_reuse_rejects_changed_architecture_before_scoring(self):
|
||||
self.record_quality()
|
||||
(self.home / "architectures/fixture.so").write_bytes(b"stale or rebuilt graph")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")), \
|
||||
patch.object(quality.subprocess, "run") as execute:
|
||||
with self.assertRaises(ValueError):
|
||||
quality.main()
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_reuse_rejects_unbound_legacy_reference(self):
|
||||
self.record_quality()
|
||||
(self.out / "bf16-top128-ref/provenance.json").unlink()
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")):
|
||||
with self.assertRaisesRegex(ValueError, "lacks provenance"):
|
||||
quality.main()
|
||||
|
||||
def test_reuse_rejects_changed_reference_payload(self):
|
||||
self.record_quality()
|
||||
(self.out / "bf16-top128-ref/top.bin").write_bytes(b"changed")
|
||||
with patch.object(sys, "argv", self.quality_args("--reuse-reference")):
|
||||
with self.assertRaises(ValueError):
|
||||
quality.main()
|
||||
|
||||
def test_report_mismatches_rejected_even_with_equal_row_counts(self):
|
||||
self.record_quality()
|
||||
report = json.loads((self.out / "full-kld.json").read_text())
|
||||
for key in ("ref_dir", "reference", "corpus", "model"):
|
||||
with self.subTest(key=key):
|
||||
bad = copy.deepcopy(report)
|
||||
bad[key] = str(self.root / "different-but-same-row-count")
|
||||
with self.assertRaisesRegex(ValueError, "does not match"):
|
||||
validate_report(bad, self.out / "bf16-top128-ref", self.reference,
|
||||
self.corpus, self.candidate, 1)
|
||||
|
||||
def bind_tail(self):
|
||||
return tail.bound_run(self.out / "run.json", self.out / "bf16-top128-ref",
|
||||
self.out / "full-kld.json")
|
||||
|
||||
def test_tail_binds_report_reference_candidate_and_runtime(self):
|
||||
self.record_quality()
|
||||
run, candidate, _, _, common = self.bind_tail()
|
||||
self.assertEqual(candidate["model"], str(self.candidate))
|
||||
self.assertIn(str(self.home), common)
|
||||
self.assertEqual(run["architecture_shared_objects"], plugin_hashes(self.home)["architecture_shared_objects"])
|
||||
|
||||
def test_tail_rejects_report_from_other_candidate(self):
|
||||
self.record_quality()
|
||||
path = self.out / "full-kld.json"
|
||||
report = json.loads(path.read_text())
|
||||
report["model"] = str(self.root / "other.rad")
|
||||
path.write_text(json.dumps(report))
|
||||
with self.assertRaisesRegex(ValueError, "report model"):
|
||||
self.bind_tail()
|
||||
|
||||
def test_tail_rejects_changed_candidate_or_row_scores(self):
|
||||
for changed in ("candidate", "rows"):
|
||||
with self.subTest(changed=changed):
|
||||
# Each subcase starts from one valid run, then invalidates exactly one artifact.
|
||||
if self.out.exists():
|
||||
import shutil
|
||||
shutil.rmtree(self.out)
|
||||
self.record_quality()
|
||||
path = self.candidate if changed == "candidate" else self.out / "full-kld.json.rows"
|
||||
path.write_bytes(path.read_bytes() + b"changed")
|
||||
with self.assertRaisesRegex(ValueError, "artifact hash"):
|
||||
self.bind_tail()
|
||||
|
||||
def test_private_server_uses_bound_candidate_and_rejects_foreign_alias(self):
|
||||
self.record_quality()
|
||||
run, candidate, _, _, common = self.bind_tail()
|
||||
for foreign in (False, True):
|
||||
with self.subTest(foreign=foreign):
|
||||
proc = Mock(pid=123)
|
||||
proc.poll.return_value = None
|
||||
commands = []
|
||||
def start(command, **kwargs):
|
||||
commands.append(command)
|
||||
return proc
|
||||
def get(url, timeout):
|
||||
return {"data": [{"id": "different-server" if foreign else commands[0][-1]}]}
|
||||
with patch.object(tail.subprocess, "Popen", side_effect=start), patch.object(tail, "get", side_effect=get):
|
||||
if foreign:
|
||||
with self.assertRaisesRegex(ValueError, "private server identity"):
|
||||
with tail.candidate_server(run, candidate, common, self.root / f"server-{foreign}.log"):
|
||||
self.fail("must not expose an unrelated server")
|
||||
else:
|
||||
with tail.candidate_server(run, candidate, common, self.root / f"server-{foreign}.log") as server:
|
||||
command = server["command"]
|
||||
self.assertEqual(command[command.index("--model") + 1], str(self.candidate))
|
||||
self.assertTrue(server["model"].startswith("spark-tail-"))
|
||||
proc.terminate.assert_called_once()
|
||||
|
||||
def response(self, data):
|
||||
return io.BytesIO(json.dumps(data).encode())
|
||||
|
||||
def test_qos_requires_complete_positive_usage(self):
|
||||
valid = {"usage": {"prompt_tokens": 3, "completion_tokens": 2},
|
||||
"choices": [{"finish_reason": "length"}]}
|
||||
with patch.object(qos.urllib.request, "urlopen", return_value=self.response(valid)):
|
||||
measured = qos.request("http://localhost", "spark", "a b", 2, 1)
|
||||
self.assertEqual(measured["completion_tokens"], 2)
|
||||
variants = [{}, {"usage": {}}, {"usage": None}]
|
||||
for missing in ("prompt_tokens", "completion_tokens"):
|
||||
bad = copy.deepcopy(valid)
|
||||
del bad["usage"][missing]
|
||||
variants.append(bad)
|
||||
for field, value in (("prompt_tokens", 0), ("prompt_tokens", "3"),
|
||||
("prompt_tokens", True), ("completion_tokens", 0),
|
||||
("completion_tokens", 1), ("completion_tokens", 3),
|
||||
("completion_tokens", "2"), ("completion_tokens", True)):
|
||||
bad = copy.deepcopy(valid)
|
||||
bad["usage"][field] = value
|
||||
variants.append(bad)
|
||||
bad = copy.deepcopy(valid)
|
||||
bad["choices"][0]["finish_reason"] = "stop"
|
||||
variants.append(bad)
|
||||
for bad in variants:
|
||||
with self.subTest(response=bad), \
|
||||
patch.object(qos.urllib.request, "urlopen", return_value=self.response(bad)):
|
||||
with self.assertRaises(ValueError):
|
||||
qos.request("http://localhost", "spark", "a b", 2, 1)
|
||||
|
||||
def test_complete_qos_records_architecture_and_expected_work(self):
|
||||
output = self.root / "complete-qos"
|
||||
args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--model", str(self.candidate), "--prompts", str(self.corpus), "--out", str(output),
|
||||
"--requests", "1", "--repeats", "1", "--concurrency", "1", "--max-tokens", "2"]
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
response = {"usage": {"prompt_tokens": 3, "completion_tokens": 2},
|
||||
"choices": [{"finish_reason": "length"}]}
|
||||
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
|
||||
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response(response)), \
|
||||
patch.object(qos, "verify_server"), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(qos.main(), 0)
|
||||
receipt = json.loads((output / "qos.json").read_text())
|
||||
self.assertIn("architectures/fixture.so", receipt["architecture_shared_objects"])
|
||||
self.assertEqual(receipt["results"]["1"]["generated_tokens"], 2)
|
||||
proc.terminate.assert_called_once()
|
||||
|
||||
def test_reuse_rejects_stale_or_partial_scorer_output(self):
|
||||
self.record_quality()
|
||||
for output in ('none', 'report', 'rows'):
|
||||
with self.subTest(output=output):
|
||||
# Restore an old valid report, then simulate a successful incomplete scorer.
|
||||
if not (self.out / 'run.json').exists():
|
||||
self.record_quality('--reuse-reference')
|
||||
def incomplete(command, **kwargs):
|
||||
report = self.out / 'full-kld.json'
|
||||
rows = Path(str(report) + '.rows')
|
||||
old_report, old_rows = self.saved_outputs
|
||||
if output == 'report':
|
||||
report.write_bytes(old_report)
|
||||
if output == 'rows':
|
||||
rows.write_bytes(old_rows)
|
||||
self.saved_outputs = ((self.out / 'full-kld.json').read_bytes(),
|
||||
(self.out / 'full-kld.json.rows').read_bytes())
|
||||
with patch.object(sys, 'argv', self.quality_args('--reuse-reference')), \
|
||||
patch.object(quality.subprocess, 'run', side_effect=incomplete):
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
quality.main()
|
||||
self.assertFalse((self.out / 'run.json').exists())
|
||||
self.assertEqual((self.out / 'full-kld.json').read_bytes(), self.saved_outputs[0])
|
||||
self.assertEqual((self.out / 'full-kld.json.rows').read_bytes(), self.saved_outputs[1])
|
||||
|
||||
def test_quality_rejects_output_collisions_before_deleting_inputs(self):
|
||||
for name in ('full-kld.json', 'full-kld.json.rows', 'run.json'):
|
||||
with self.subTest(name=name):
|
||||
self.out = self.root / ('collision-' + name)
|
||||
self.out.mkdir()
|
||||
colliding = self.out / name
|
||||
colliding.write_bytes(b'irreplaceable input')
|
||||
self.candidate = colliding
|
||||
with patch.object(sys, 'argv', self.quality_args()), \
|
||||
patch.object(quality.subprocess, 'run') as execute, \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit):
|
||||
quality.main()
|
||||
self.assertEqual(colliding.read_bytes(), b'irreplaceable input')
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_quality_protects_external_plugin_symlink_targets(self):
|
||||
for name in ('run.json', 'full-kld.json', 'full-kld.json.rows'):
|
||||
with self.subTest(name=name):
|
||||
self.out = self.root / ('plugin-' + name)
|
||||
self.out.mkdir()
|
||||
target = self.out / name
|
||||
target.write_bytes(b'plugin target')
|
||||
plugin = self.home / 'kernels/fixture.so'
|
||||
plugin.unlink()
|
||||
plugin.symlink_to(target)
|
||||
with patch.object(sys, 'argv', self.quality_args()), \
|
||||
patch.object(quality.subprocess, 'run') as execute, \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
with self.assertRaises(SystemExit):
|
||||
quality.main()
|
||||
self.assertEqual(target.read_bytes(), b'plugin target')
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_quality_rolls_back_scores_on_promotion_or_receipt_failure(self):
|
||||
for failure_name in ('full-kld.json.rows', 'run.json'):
|
||||
with self.subTest(failure_name=failure_name):
|
||||
self.out = self.root / ('promotion-' + failure_name)
|
||||
self.record_quality()
|
||||
paths = (self.out / 'full-kld.json', self.out / 'full-kld.json.rows')
|
||||
original = [path.read_bytes() for path in paths]
|
||||
real_replace = os.replace
|
||||
failed = False
|
||||
def fail_once(src, dst):
|
||||
nonlocal failed
|
||||
if not failed and Path(dst) == self.out / failure_name:
|
||||
failed = True
|
||||
raise OSError('simulated promotion failure')
|
||||
return real_replace(src, dst)
|
||||
with patch.object(sys, 'argv', self.quality_args('--reuse-reference')), \
|
||||
patch.object(quality.subprocess, 'run', side_effect=self.fake_runtime), \
|
||||
patch.object(quality.os, 'replace', side_effect=fail_once), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaisesRegex(OSError, 'simulated promotion failure'):
|
||||
quality.main()
|
||||
self.assertTrue(failed)
|
||||
self.assertEqual([path.read_bytes() for path in paths], original)
|
||||
self.assertFalse((self.out / 'run.json').exists())
|
||||
|
||||
def test_cleanup_failure_reports_publication_state_and_preserves_original_error(self):
|
||||
for scoring_fails in (False, True):
|
||||
with self.subTest(scoring_fails=scoring_fails):
|
||||
self.out = self.root / f'cleanup-{scoring_fails}'
|
||||
errors = io.StringIO()
|
||||
def run(command, **kwargs):
|
||||
if scoring_fails and '--kld-ref' in command:
|
||||
raise ValueError('original scoring failure')
|
||||
return self.fake_runtime(command, **kwargs)
|
||||
with patch.object(sys, 'argv', self.quality_args()), \
|
||||
patch.object(quality.subprocess, 'run', side_effect=run), \
|
||||
patch.object(quality.shutil, 'rmtree', side_effect=PermissionError('cleanup denied')), \
|
||||
contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(errors):
|
||||
if scoring_fails:
|
||||
with self.assertRaisesRegex(ValueError, 'original scoring failure'):
|
||||
quality.main()
|
||||
else:
|
||||
self.assertEqual(quality.main(), 0)
|
||||
self.assertEqual((self.out / 'run.json').exists(), not scoring_fails)
|
||||
self.assertIn('results not published' if scoring_fails else 'results published', errors.getvalue())
|
||||
self.assertIn('cleanup denied', errors.getvalue())
|
||||
retained = list(self.out.glob('.spark25-score-*'))
|
||||
self.assertEqual(len(retained), 1)
|
||||
self.assertIn(str(retained[0]), errors.getvalue())
|
||||
|
||||
def test_rollback_failure_retains_backup_and_restores_other_scores(self):
|
||||
self.record_quality()
|
||||
paths = (self.out / 'full-kld.json', self.out / 'full-kld.json.rows')
|
||||
original = [path.read_bytes() for path in paths]
|
||||
real_replace = os.replace
|
||||
failures = []
|
||||
def fail_publish_and_one_restore(src, dst):
|
||||
src, dst = Path(src), Path(dst)
|
||||
if dst == self.out / 'run.json':
|
||||
failures.append('publish')
|
||||
raise OSError('publication blocked')
|
||||
if src.name == 'backup-1':
|
||||
failures.append('restore')
|
||||
raise OSError('restore blocked')
|
||||
return real_replace(src, dst)
|
||||
with patch.object(sys, 'argv', self.quality_args('--reuse-reference')), \
|
||||
patch.object(quality.subprocess, 'run', side_effect=self.fake_runtime), \
|
||||
patch.object(quality.os, 'replace', side_effect=fail_publish_and_one_restore), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaisesRegex(RuntimeError, 'publication blocked.*recover backups') as error:
|
||||
quality.main()
|
||||
self.assertEqual(failures, ['publish', 'restore'])
|
||||
self.assertIsInstance(error.exception.__cause__, OSError)
|
||||
self.assertEqual(paths[0].read_bytes(), original[0])
|
||||
self.assertFalse(paths[1].exists())
|
||||
retained = list(self.out.glob('.spark25-score-*'))
|
||||
self.assertEqual(len(retained), 1)
|
||||
self.assertEqual((retained[0] / 'backup-1').read_bytes(), original[1])
|
||||
self.assertIn(str(retained[0]), str(error.exception))
|
||||
self.assertFalse((self.out / 'run.json').exists())
|
||||
|
||||
def test_tail_log_cannot_truncate_model_or_follow_symlink(self):
|
||||
self.record_quality()
|
||||
run, candidate, _, _, common = self.bind_tail()
|
||||
before = self.candidate.read_bytes()
|
||||
log = self.root / 'tail.server.log'
|
||||
log.symlink_to(self.candidate)
|
||||
for target in (log, self.candidate):
|
||||
with self.subTest(target=target), patch.object(tail.subprocess, 'Popen') as start:
|
||||
with self.assertRaises(FileExistsError):
|
||||
with tail.candidate_server(run, candidate, common, target):
|
||||
self.fail('must not start')
|
||||
start.assert_not_called()
|
||||
self.assertEqual(self.candidate.read_bytes(), before)
|
||||
|
||||
def test_qos_log_symlink_cannot_truncate_model(self):
|
||||
output = self.root / 'symlink-qos'
|
||||
output.mkdir()
|
||||
(output / 'server.log').symlink_to(self.candidate)
|
||||
before = self.candidate.read_bytes()
|
||||
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
|
||||
'--model', str(self.candidate), '--prompts', str(self.corpus), '--out', str(output),
|
||||
'--requests', '1', '--concurrency', '1']
|
||||
with patch.object(sys, 'argv', args), patch.object(qos.subprocess, 'Popen') as start:
|
||||
with self.assertRaises(FileExistsError):
|
||||
qos.main()
|
||||
self.assertEqual(self.candidate.read_bytes(), before)
|
||||
self.assertFalse((output / 'qos.json').exists())
|
||||
start.assert_not_called()
|
||||
|
||||
def test_qos_rejects_fewer_requests_than_concurrency(self):
|
||||
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
|
||||
'--model', str(self.candidate), '--prompts', str(self.corpus), '--out', str(self.root / 'qos'),
|
||||
'--requests', '1', '--concurrency', '4']
|
||||
with patch.object(sys, 'argv', args), contextlib.redirect_stderr(io.StringIO()), \
|
||||
patch.object(qos.subprocess, 'Popen') as start:
|
||||
with self.assertRaises(SystemExit):
|
||||
qos.main()
|
||||
start.assert_not_called()
|
||||
|
||||
def test_qos_rejects_foreign_server_and_dead_child(self):
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
with patch.object(qos.urllib.request, 'urlopen', return_value=self.response({'data': [{'id': 'foreign'}]})):
|
||||
with self.assertRaisesRegex(RuntimeError, 'identity'):
|
||||
qos.verify_server('http://localhost', 'unique-id', proc)
|
||||
proc.poll.return_value = 1
|
||||
with self.assertRaisesRegex(RuntimeError, 'exited'):
|
||||
qos.verify_server('http://localhost', 'unique-id', proc)
|
||||
proc.poll.return_value = None
|
||||
with patch.object(qos.urllib.request, 'urlopen', return_value=self.response({'data': [{'id': 'unique-id'}]})):
|
||||
qos.verify_server('http://localhost', 'unique-id', proc)
|
||||
|
||||
def test_qos_rejects_prompt_file_replacement_after_snapshot(self):
|
||||
output = self.root / 'changed-qos'
|
||||
args = ['spark25_qos.py', '--radiance', str(self.runtime), '--home', str(self.home),
|
||||
'--model', str(self.candidate), '--prompts', str(self.corpus), '--out', str(output),
|
||||
'--requests', '1', '--repeats', '1', '--concurrency', '1', '--max-tokens', '2']
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
response = {'usage': {'prompt_tokens': 3, 'completion_tokens': 2},
|
||||
'choices': [{'finish_reason': 'length'}]}
|
||||
def change(*args):
|
||||
self.corpus.write_text('{"prompt":"different"}\n')
|
||||
with patch.object(sys, 'argv', args), patch.object(qos.subprocess, 'Popen', return_value=proc), \
|
||||
patch.object(qos.urllib.request, 'urlopen', side_effect=lambda *a, **k: self.response(response)), \
|
||||
patch.object(qos, 'verify_server', side_effect=change), contextlib.redirect_stdout(io.StringIO()):
|
||||
with self.assertRaisesRegex(ValueError, 'prompt file'):
|
||||
qos.main()
|
||||
self.assertFalse((output / 'qos.json').exists())
|
||||
|
||||
def test_failed_qos_does_not_emit_success_receipt(self):
|
||||
output = self.root / "qos"
|
||||
args = ["spark25_qos.py", "--radiance", str(self.runtime), "--home", str(self.home),
|
||||
"--model", str(self.candidate), "--prompts", str(self.corpus), "--out", str(output),
|
||||
"--requests", "1", "--repeats", "1", "--concurrency", "1", "--max-tokens", "2"]
|
||||
proc = Mock()
|
||||
proc.poll.return_value = None
|
||||
with patch.object(sys, "argv", args), patch.object(qos.subprocess, "Popen", return_value=proc), \
|
||||
patch.object(qos.urllib.request, "urlopen", side_effect=lambda *a, **k: self.response({})), \
|
||||
patch.object(qos, "verify_server"):
|
||||
with self.assertRaisesRegex(ValueError, "missing usage"):
|
||||
qos.main()
|
||||
proc.terminate.assert_called_once()
|
||||
self.assertFalse((output / "qos.json").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+151
-6
@@ -9,7 +9,9 @@
|
||||
* a time, and the assembly must equal the buffered body built by the same server.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
#include "work_counter.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
@@ -558,12 +560,12 @@ Text text_streamed(const std::string& path, const std::string& body) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* What the server holds back while a reply runs (the longest stop string less a byte, an unfinished
|
||||
* character, a half-written escape) and releases at the end: for every split into two drains and
|
||||
* one byte a drain, the streamed text of chat, completions and llama-server's native completion is
|
||||
* the buffered text, and the finish agrees. A stop string's bytes never reach the wire, or the
|
||||
* concatenation would hold them. On chat a reply that starts inside its reasoning block applies
|
||||
* its stop strings only after the closer. */
|
||||
/* What the server holds back while a reply runs (a tail that may still become a stop string, an
|
||||
* unfinished character, a half-written escape) and releases at the end: for every split into two
|
||||
* drains and one byte a drain, the streamed text of chat, completions and llama-server's native
|
||||
* completion is the buffered text, and the finish agrees. A stop string's bytes never reach the
|
||||
* wire, or the concatenation would hold them. On chat a reply that starts inside its reasoning
|
||||
* block applies its stop strings only after the closer. */
|
||||
TEST(a_streamed_text_is_the_buffered_text_at_every_drain_boundary) {
|
||||
struct Case {
|
||||
const char* name;
|
||||
@@ -578,6 +580,8 @@ TEST(a_streamed_text_is_the_buffered_text_at_every_drain_boundary) {
|
||||
{ "characters around a stop", "\xC3\xA9STOP\xC3\xA9", "STOP", false },
|
||||
{ "escapes", "q\\u12\\\\\"x\\", "", false },
|
||||
{ "a stop longer than the reply's tail", "abcZZ", "ZZZ", false },
|
||||
{ "a tail that stops being a stop's start", "abSTxSTOPy", "STOP", false },
|
||||
{ "a stop's start that starts it again", "xSTASTARy", "STAR", false },
|
||||
};
|
||||
for (const char* path : { "/v1/chat/completions", "/v1/completions", "/completion" }) {
|
||||
for (const Case& c : cases) {
|
||||
@@ -608,6 +612,147 @@ TEST(a_streamed_text_is_the_buffered_text_at_every_drain_boundary) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A running choice holds back only a tail that may still become a stop string: what precedes it is
|
||||
* on the wire after the drain that produced it, on chat, completions and llama-server's native
|
||||
* completion. The hold-back this replaced kept the longest stop string less a byte off the wire
|
||||
* whatever the tail was, so with a ten-byte stop every delta trailed by nine bytes and a short
|
||||
* reply showed nothing before its end. */
|
||||
TEST(a_running_choice_holds_back_only_what_may_still_become_a_stop_string) {
|
||||
struct Step {
|
||||
const char* piece; /* the drain's new bytes */
|
||||
const char* wire; /* everything on the wire after it */
|
||||
};
|
||||
const Step steps[] = {
|
||||
{ "Hello", "Hello" },
|
||||
{ " ENDOF", "Hello " }, /* "ENDOF" may still become "ENDOFREPLY" */
|
||||
{ "X\n", "Hello ENDOFX" }, /* it cannot now, but "\n" may become "\n\n" */
|
||||
{ "ENDO", "Hello ENDOFX\n" }, /* "\nE" cannot, "ENDO" may become "ENDOFREPLY" */
|
||||
{ "FREPLY tail", "Hello ENDOFX\n" }, /* the stop is cut, and nothing of it went out */
|
||||
};
|
||||
for (const char* path : { "/v1/chat/completions", "/v1/completions", "/completion" }) {
|
||||
Fixture f;
|
||||
const std::string stop = R"(,"stop":["ENDOFREPLY","\n\n"],"stream":true})";
|
||||
const std::string body = std::string(path) == "/v1/chat/completions"
|
||||
? R"({"messages":[{"role":"user","content":"hi"}],"max_tokens":1000)" + stop
|
||||
: R"({"prompt":"hi","max_tokens":1000)" + stop;
|
||||
f.sched.manual = true;
|
||||
HttpResponse r = f.post(path, body);
|
||||
f.sched.manual = false;
|
||||
REQUIRE(r.status == 200);
|
||||
REQUIRE(r.streaming());
|
||||
const size_t i = f.sched.seen.size() - 1;
|
||||
std::string out, c;
|
||||
r.next(c);
|
||||
out += c;
|
||||
for (const Step& s : steps) {
|
||||
f.sched.push(i, s.piece);
|
||||
c.clear();
|
||||
r.next(c);
|
||||
out += c;
|
||||
const Text got = text_streamed(path, out);
|
||||
if (got.text == s.wire) continue;
|
||||
CHECK_EQ(got.text, std::string(s.wire));
|
||||
fprintf(stderr, " %s, after \"%s\"\n", path, s.piece);
|
||||
}
|
||||
f.sched.finish(i, Finish::Stop);
|
||||
for (int k = 0; k < 64; ++k) {
|
||||
c.clear();
|
||||
const bool more = r.next(c);
|
||||
out += c;
|
||||
if (!more) break;
|
||||
}
|
||||
r.on_close(true);
|
||||
const Text all = text_streamed(path, out);
|
||||
CHECK_EQ(all.text, std::string("Hello ENDOFX\n"));
|
||||
CHECK_EQ(all.finish, std::string(std::string(path) == "/completion" ? "word" : "stop"));
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* The work of 24 drains of a streamed completion, in radtest::Work's unit, each after a short
|
||||
* piece of text, once the text is longer than any stop string: what each drain holds back is then
|
||||
* looked for in as many tails as the longest stop string is long. 20 pieces of 300 bytes, each
|
||||
* the next byte of `fill`, come first. Also checks the text arrives. */
|
||||
uint64_t drains_work(const std::string& stops, const std::string& fill = "the quick brown ") {
|
||||
Fixture f;
|
||||
f.sched.manual = true;
|
||||
HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","max_tokens":100000,"stream":true,)"
|
||||
R"("stop":)" + stops + "}");
|
||||
f.sched.manual = false;
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(r.streaming());
|
||||
if (r.status != 200 || !r.streaming()) return 0;
|
||||
const size_t i = f.sched.seen.size() - 1;
|
||||
std::string out, c;
|
||||
r.next(c);
|
||||
out += c;
|
||||
std::string sent;
|
||||
for (int k = 0; k < 20; ++k) {
|
||||
const std::string part(300, fill[(size_t)k % fill.size()]);
|
||||
sent += part;
|
||||
f.sched.push(i, part);
|
||||
c.clear();
|
||||
r.next(c);
|
||||
out += c;
|
||||
}
|
||||
uint64_t w = 0;
|
||||
for (int k = 0; k < 24; ++k) {
|
||||
const std::string piece = "word " + std::to_string(k) + ", ";
|
||||
sent += piece;
|
||||
f.sched.push(i, piece);
|
||||
c.clear();
|
||||
w += radtest::work().of([&] { r.next(c); });
|
||||
out += c;
|
||||
}
|
||||
f.sched.finish(i, Finish::Stop);
|
||||
for (int k = 0; k < 64; ++k) {
|
||||
c.clear();
|
||||
const bool more = r.next(c);
|
||||
out += c;
|
||||
if (!more) break;
|
||||
}
|
||||
r.on_close(true);
|
||||
CHECK_EQ(text_streamed("/v1/completions", out).text, sent);
|
||||
return w;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A request may send 64 stop strings of 4 KiB, and a running choice's hold-back looks at the tails
|
||||
* of what it has not sent, up to the longest stop string, on each drain. A tail is compared only
|
||||
* where it starts with a byte some stop string starts with, so stop strings the text cannot start
|
||||
* cost a drain a lookup per tail: such a drain costs about as much as one with a single two-byte
|
||||
* stop. Comparing every tail with every stop string, 262 080 calls a drain, cost three hundred
|
||||
* times. */
|
||||
TEST(a_drain_looks_for_long_stop_strings_only_where_they_can_start) {
|
||||
json many = json::array();
|
||||
for (int k = 0; k < 64; ++k) many.push_back("~" + std::string(4095, (char)('a' + k % 26)));
|
||||
const uint64_t one = drains_work(R"(["~~"])"), all = drains_work(many.dump());
|
||||
std::fprintf(stderr, " one stop %llu, 64 of 4 KiB %llu %s, ratio %.2f\n",
|
||||
(unsigned long long)one, (unsigned long long)all, radtest::work().unit(),
|
||||
(double)all / (double)one);
|
||||
CHECK((double)all / (double)one < (radtest::work().exact() ? 20.0 : 40.0));
|
||||
}
|
||||
|
||||
/* The client sets the stop strings and steers the text: 64 stop strings of 4 KiB that all begin
|
||||
* with 4093 'a', and a reply that is thousands of 'a' and then something else, matches them for
|
||||
* as long as there are 'a' and then no more, at every one of the 4095 tails of every one of the
|
||||
* 64 strings, which is 500 million bytes compared on a drain with no bound. The comparisons share
|
||||
* a budget past which a drain holds back all it has not sent, so the cost of a drain is bounded
|
||||
* whatever the text. */
|
||||
TEST(a_drain_that_almost_matches_long_stop_strings_costs_a_bounded_amount) {
|
||||
json many = json::array();
|
||||
for (int k = 0; k < 64; ++k)
|
||||
many.push_back(std::string(4093, 'a') + (char)('0' + k / 8) + (char)('0' + k % 8));
|
||||
const uint64_t one = drains_work(R"(["~~"])");
|
||||
const uint64_t all = drains_work(many.dump(), "aaaaaaaaaaaaaaaaaaax");
|
||||
std::fprintf(stderr, " one stop %llu, 64 of 4 KiB almost matched %llu %s, ratio %.2f\n",
|
||||
(unsigned long long)one, (unsigned long long)all, radtest::work().unit(),
|
||||
(double)all / (double)one);
|
||||
CHECK((double)all / (double)one < (radtest::work().exact() ? 40.0 : 80.0));
|
||||
}
|
||||
|
||||
/* ================================================================== Anthropic's stop reasons */
|
||||
|
||||
/* Anthropic's stop_reason and stop_sequence say why a reply ended, buffered and streamed alike: a
|
||||
|
||||
@@ -463,13 +463,50 @@ TEST(match_at_is_leftmost_first_not_longest) {
|
||||
|
||||
/* Every construct outside the dialect is refused by name. The checked phrase is what a reader of
|
||||
* the load error needs to find the construct in a 200-character pattern. */
|
||||
/* A possessive repetition is taken only where the greedy reading gives the same matches: one class
|
||||
* at the top level, its tail classes that cannot take its codepoints. Ling-3.0's pattern is such a
|
||||
* case, and it splits as its greedy spelling does. */
|
||||
TEST(possessive_quantifiers_with_a_disjoint_tail_read_as_greedy) {
|
||||
const char* ling = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?+\\p{L}+|\\p{N}"
|
||||
"| ?[^\\s\\p{L}\\p{N}]++[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+";
|
||||
const char* greedy = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}"
|
||||
"| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]|\\s+(?!\\S)|\\s+";
|
||||
auto a = compile(ling), b = compile(greedy);
|
||||
REQUIRE(a != nullptr);
|
||||
REQUIRE(b != nullptr);
|
||||
const char* texts[] = {
|
||||
"Hello, world! It's 2026... \"quoted\" spaces\n\nnew lines\r\n--dashes--",
|
||||
"Die Patientin (67) hat seit 2 h Thoraxschmerzen; RR 158/94 mmHg, SpO\xe2\x82\x82 93 %.",
|
||||
" ...!!!??? x\t\ty \xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97 ,,; 'LL 'Ve",
|
||||
};
|
||||
for (const char* t : texts) {
|
||||
std::vector<rad::TokSpan> x, y;
|
||||
a->find_iter(t, x);
|
||||
b->find_iter(t, y);
|
||||
REQUIRE_EQ(x.size(), y.size());
|
||||
for (size_t i = 0; i < x.size(); ++i) {
|
||||
CHECK_EQ(x[i].begin, y[i].begin);
|
||||
CHECK_EQ(x[i].end, y[i].end);
|
||||
}
|
||||
}
|
||||
auto plus = compile("a++"), star = compile("[^b]*+b?");
|
||||
REQUIRE(plus != nullptr);
|
||||
REQUIRE(star != nullptr);
|
||||
CHECK_EQ(plus->match_at("aaab", 0), (int64_t)3);
|
||||
CHECK_EQ(star->match_at("xyzb", 0), (int64_t)4);
|
||||
}
|
||||
|
||||
TEST(constructs_outside_the_dialect_are_refused_by_name) {
|
||||
const struct { const char* pattern; const char* says; } refused[] = {
|
||||
{ "(a)\\1", "backreference" },
|
||||
{ "\\k<n>", "backreference" },
|
||||
{ "(?>a+)", "atomic group" },
|
||||
{ "a++", "possessive" },
|
||||
{ "a*+", "possessive" },
|
||||
{ "a++a", "possessive" },
|
||||
{ "[ab]*+b", "possessive" },
|
||||
{ "(?:a++)", "possessive" },
|
||||
{ "(a*+)b", "possessive" },
|
||||
{ "(?:ab)++", "possessive" },
|
||||
{ "\\s++(?!\\S)", "possessive" },
|
||||
{ "a{2}{3}", "quantifier applied to a quantifier" },
|
||||
{ "a{1,2}+", "quantifier applied to a quantifier" },
|
||||
{ "a**", "quantifier applied to a quantifier" },
|
||||
|
||||
+10
-3
@@ -416,13 +416,20 @@ void wait_windows(GbnfGrammar& g, const Vocab& vb, int n) {
|
||||
/* Waiting costs the same at any length. A lazy grammar sees every token of the reply until its
|
||||
* word appears, and each speculative window copies its state twice; the last tokens of a long
|
||||
* reply must cost what the first did. Counted in work, 20,000 windows at the start and again after
|
||||
* 200,000 more. */
|
||||
* 200,000 more, each the least of three runs: under the CPU-time fallback (a container build, tests
|
||||
* beside it) one run alone came out 1.65x the other. */
|
||||
TEST(lazy_grammar_waiting_work_does_not_grow_with_the_reply) {
|
||||
Vocab vb;
|
||||
auto g = make(vb, true, { "<tool_call>\n" }, {});
|
||||
const uint64_t first = radtest::work().of([&] { wait_windows(*g, vb, 20000); });
|
||||
auto least = [&] {
|
||||
uint64_t m = UINT64_MAX;
|
||||
for (int k = 0; k < 3; ++k)
|
||||
m = std::min(m, radtest::work().of([&] { wait_windows(*g, vb, 20000); }));
|
||||
return m;
|
||||
};
|
||||
const uint64_t first = least();
|
||||
wait_windows(*g, vb, 200000);
|
||||
const uint64_t last = radtest::work().of([&] { wait_windows(*g, vb, 20000); });
|
||||
const uint64_t last = least();
|
||||
CHECK(g->awaiting_trigger());
|
||||
std::printf(" lazy wait: %llu then %llu %s per 20k windows\n", (unsigned long long)first,
|
||||
(unsigned long long)last, radtest::work().unit());
|
||||
|
||||
@@ -1144,7 +1144,7 @@ TEST(input_reference_takes_the_models_h264_round_trip) {
|
||||
guided(v, 18);
|
||||
const std::string pic = png_rgb(301, 171, 200, 40, 90);
|
||||
HttpResponse r = v.create(Videos::body({ { "input_reference", png_url(pic) } }));
|
||||
if (r.status == 503) return; /* a build without libx264 refuses it, as it should */
|
||||
if (r.status == 501) return; /* a build without an H.264 encoder refuses it, as it should */
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& q = v.gen.last();
|
||||
REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3);
|
||||
|
||||
Reference in new issue
Block a user