Archived
merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port
Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.
Notable reconciliations:
* videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
(i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
so upstream models keep refusing them as unknown tasks; input_reference,
the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
coexist with refs/ref2va; the prompt put() helper hoisted to block scope
for the media branch.
* video_schedule(): upstream's (steps, video_tokens, refine) keeps its
positional slots; the port's shift_video/shift_audio overrides move to the
tail so upstream's schedule tests call unchanged.
* r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
upstream's wadd/norm_once/norm parameters.
* tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
staging dir -- plugin .so files still land in the absolute
RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
relative bin/, which needs no root.
Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
a1a75da7e9
415 files changed
+78837
-5310
No files matched your search
+46
-29
@@ -10,11 +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 does not link rad_core: it supplies its own recording fake of the declare-phase C ABI,
|
||||
# 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)
|
||||
# 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)
|
||||
|
||||
# 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
|
||||
@@ -45,7 +46,8 @@ set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test)
|
||||
# relayout_parity_test checks each kernel library's relayout of libquant's planes against a
|
||||
# recorded hash of the stored bytes. libr4d's layout sources are host-only, so they are compiled in,
|
||||
# with -ffp-contract=off as libr4d uses, so scale conversions round identically.
|
||||
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test)
|
||||
# r4d_ar_links_test checks libr4d's header-only link reader, so it needs only the include path.
|
||||
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test)
|
||||
|
||||
# ref2va_pack_test checks the Ref2VA sequence packing (arch/minimaxh3/rad_ref2va_pack.cpp, a
|
||||
# device-free TU of the plugin) against golden vectors generated from the reference implementation
|
||||
@@ -295,10 +297,13 @@ if(TARGET abi_layout_test)
|
||||
endif()
|
||||
|
||||
# arch_test reads libref's vocabulary from $RADIANCE_HOME/kernels to check that each architecture
|
||||
# declares on it, so libref is built before it.
|
||||
if(TARGET libref AND TARGET arch_test)
|
||||
add_dependencies(arch_test libref)
|
||||
endif()
|
||||
# declares on it, and glm5next_test the loaded libraries' op schemas, so libref is built before
|
||||
# them.
|
||||
foreach(t arch_test glm5next_test)
|
||||
if(TARGET libref AND TARGET ${t})
|
||||
add_dependencies(${t} libref)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
# kbench_mutant_test runs rad-kbench against the deliberately defective kernel libraries
|
||||
# (core/plugin/testplugin/kbmutant.cc) on the host backend, so it needs the tool, libref and the
|
||||
@@ -379,14 +384,18 @@ endif()
|
||||
# ================================================================== libr4d's kernels, on the host
|
||||
#
|
||||
# Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design
|
||||
# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of six units written
|
||||
# against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins,
|
||||
# expert_scale, the QSA block selection, whose four kernels a card-less build otherwise never
|
||||
# runs, and the runtime-LoRA pair. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread
|
||||
# is a fiber, and __syncthreads and cross-lane ops are barriers (one not reached uniformly is
|
||||
# reported as a deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select,
|
||||
# the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, and for the
|
||||
# LoRA pair libref itself when the test can load it.
|
||||
# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of fourteen units
|
||||
# written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins,
|
||||
# expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile
|
||||
# forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA
|
||||
# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings, GLM's MoE decode
|
||||
# fusions and GLM's DSA scoring split by query rows, whose kernels a card-less build otherwise
|
||||
# never runs. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread is a fiber, and
|
||||
# __syncthreads and cross-lane ops are barriers (one not reached uniformly is reported as a
|
||||
# deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, the host
|
||||
# arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, for the LoRA pair libref
|
||||
# itself when the test can load it, for KDA libref itself, and for the DSA split the unsplit
|
||||
# kernels.
|
||||
#
|
||||
# Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang
|
||||
# C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so
|
||||
@@ -398,8 +407,11 @@ set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d)
|
||||
set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu)
|
||||
set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip
|
||||
${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip
|
||||
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora)
|
||||
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
|
||||
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
|
||||
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
|
||||
${R4D_DIR}/r4d_dsa.hip)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
|
||||
set(R4D_EMU_BUILT OFF)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# No fiber switch for this ISA.
|
||||
@@ -435,7 +447,10 @@ else()
|
||||
set(objs "")
|
||||
foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp
|
||||
${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp
|
||||
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp)
|
||||
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
|
||||
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
|
||||
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
|
||||
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -452,7 +467,7 @@ else()
|
||||
list(APPEND objs ${dir}/${stem}.o)
|
||||
endif()
|
||||
endforeach()
|
||||
# test_lora opens libref with dlopen to hold the emulated kernels to it.
|
||||
# test_lora and test_kda open libref with dlopen to hold the emulated kernels to it.
|
||||
set(dl "")
|
||||
foreach(l ${CMAKE_DL_LIBS})
|
||||
list(APPEND dl -l${l})
|
||||
@@ -472,7 +487,7 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
if(R4D_EMU_BUILT)
|
||||
foreach(t pick norm escale qsa lora)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
|
||||
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,
|
||||
@@ -482,11 +497,13 @@ if(R4D_EMU_BUILT)
|
||||
COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3)
|
||||
endforeach()
|
||||
set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick
|
||||
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora
|
||||
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
|
||||
r4d_emu_dsa
|
||||
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.
|
||||
set_tests_properties(r4d_emu_lora PROPERTIES
|
||||
# load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within
|
||||
# rounding, and that test needs it.
|
||||
set_tests_properties(r4d_emu_lora r4d_emu_kda PROPERTIES
|
||||
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
|
||||
# A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at
|
||||
# about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it.
|
||||
@@ -529,13 +546,13 @@ endif()
|
||||
# Installs the build into a prefix, then configures, builds and installs every plugin directory
|
||||
# standalone against it with find_package(radiance). The result must match the tree's plugins,
|
||||
# vocabulary and registration, and serve rad-kbench's fixture through the installed tools
|
||||
# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler and
|
||||
# targets. Labelled `oot`: it rebuilds every plugin and takes minutes.
|
||||
# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler,
|
||||
# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes.
|
||||
set(RAD_OOT_HIP "")
|
||||
if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES)
|
||||
string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}")
|
||||
set(RAD_OOT_HIP ${CMAKE_HIP_COMPILER} "${RAD_OOT_R4D_ARCH}")
|
||||
set(RAD_OOT_HIP ${CMAKE_HIP_COMPILER} "${RAD_OOT_R4D_ARCH}" ${RAD_HIP_VOPD_REPEATABLE})
|
||||
endif()
|
||||
add_test(NAME oot_plugins
|
||||
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
|
||||
|
||||
@@ -16,6 +16,8 @@ ABI_FIELD(RadArchProbe, gen_patches)
|
||||
ABI_FIELD(RadArchProbe, gen_audio)
|
||||
ABI_FIELD(RadArchProbe, gen_ctx)
|
||||
ABI_FIELD(RadArchProbe, gen_video)
|
||||
ABI_FIELD(RadArchProbe, kv_quant_ok)
|
||||
ABI_FIELD(RadArchProbe, chain_pays)
|
||||
ABI_STRUCT(RadArgs)
|
||||
ABI_FIELD(RadArgs, t)
|
||||
ABI_FIELD(RadArgs, n_t)
|
||||
@@ -99,6 +101,8 @@ ABI_FIELD(RadBuildCtx, max_enc_patches)
|
||||
ABI_FIELD(RadBuildCtx, max_out_rows)
|
||||
ABI_FIELD(RadBuildCtx, max_audio_frames)
|
||||
ABI_FIELD(RadBuildCtx, max_mixed_tok)
|
||||
ABI_FIELD(RadBuildCtx, kv_quant)
|
||||
ABI_FIELD(RadBuildCtx, cvec)
|
||||
ABI_STRUCT(RadAudioGenBatch)
|
||||
ABI_FIELD(RadAudioGenBatch, n_lane)
|
||||
ABI_FIELD(RadAudioGenBatch, lane)
|
||||
@@ -167,6 +171,11 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole)
|
||||
ABI_FIELD(RadAudioGenDecl, first_frame)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_chunk)
|
||||
ABI_FIELD(RadAudioGenDecl, voc_context)
|
||||
ABI_STRUCT(RadControlVector)
|
||||
ABI_FIELD(RadControlVector, dir)
|
||||
ABI_FIELD(RadControlVector, scales)
|
||||
ABI_FIELD(RadControlVector, n_embd)
|
||||
ABI_FIELD(RadControlVector, n_layers)
|
||||
ABI_STRUCT(RadAudioFormat)
|
||||
ABI_FIELD(RadAudioFormat, struct_size)
|
||||
ABI_FIELD(RadAudioFormat, audio_open)
|
||||
@@ -347,6 +356,30 @@ ABI_FIELD(RadGenBatch, dec_lane)
|
||||
ABI_FIELD(RadGenBatch, dec_height)
|
||||
ABI_FIELD(RadGenBatch, dec_width)
|
||||
ABI_FIELD(RadGenBatch, dec_preview)
|
||||
ABI_FIELD(RadGenBatch, branch)
|
||||
ABI_FIELD(RadGenBatch, n_pad)
|
||||
ABI_FIELD(RadGenBatch, valid_cu)
|
||||
ABI_FIELD(RadGenBatch, n_img)
|
||||
ABI_FIELD(RadGenBatch, img_cu)
|
||||
ABI_FIELD(RadGenBatch, img_rows)
|
||||
ABI_FIELD(RadGenBatch, mode_cu)
|
||||
ABI_FIELD(RadGenBatch, rope_f)
|
||||
ABI_FIELD(RadGenBatch, mode_rows)
|
||||
ABI_FIELD(RadGenBatch, mode_src)
|
||||
ABI_FIELD(RadGenBatch, mode_ccu)
|
||||
ABI_FIELD(RadGenBatch, n_mode_h)
|
||||
ABI_FIELD(RadGenBatch, mode_rope_f)
|
||||
ABI_FIELD(RadGenBatch, n_aux)
|
||||
ABI_FIELD(RadGenBatch, aux_ids)
|
||||
ABI_FIELD(RadGenBatch, aux_cu)
|
||||
ABI_FIELD(RadGenBatch, sigma_prev)
|
||||
ABI_FIELD(RadGenBatch, timestep)
|
||||
ABI_FIELD(RadGenBatch, sampler)
|
||||
ABI_FIELD(RadGenBatch, step)
|
||||
ABI_FIELD(RadGenBatch, size_px)
|
||||
ABI_FIELD(RadGenBatch, entry_h)
|
||||
ABI_FIELD(RadGenBatch, tokens_h)
|
||||
ABI_FIELD(RadGenBatch, cond_opts)
|
||||
ABI_STRUCT(RadGeneratorDecl)
|
||||
ABI_FIELD(RadGeneratorDecl, name)
|
||||
ABI_FIELD(RadGeneratorDecl, layout)
|
||||
@@ -380,6 +413,29 @@ ABI_FIELD(RadGeneratorDecl, shift_terminal)
|
||||
ABI_FIELD(RadGeneratorDecl, default_cfg)
|
||||
ABI_FIELD(RadGeneratorDecl, max_lanes)
|
||||
ABI_FIELD(RadGeneratorDecl, image_out)
|
||||
ABI_FIELD(RadGeneratorDecl, cond_rows)
|
||||
ABI_FIELD(RadGeneratorDecl, rope_hw_scale)
|
||||
ABI_FIELD(RadGeneratorDecl, rope_text_l)
|
||||
ABI_FIELD(RadGeneratorDecl, pad_multiple)
|
||||
ABI_FIELD(RadGeneratorDecl, pad_token)
|
||||
ABI_FIELD(RadGeneratorDecl, cfg_original)
|
||||
ABI_FIELD(RadGeneratorDecl, default_negative)
|
||||
ABI_FIELD(RadGeneratorDecl, ref_shrink_only)
|
||||
ABI_FIELD(RadGeneratorDecl, aux_max_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, sigma_grid)
|
||||
ABI_FIELD(RadGeneratorDecl, min_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, aux_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_start)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_end)
|
||||
ABI_FIELD(RadGeneratorDecl, train_steps)
|
||||
ABI_FIELD(RadGeneratorDecl, beta_schedule)
|
||||
ABI_FIELD(RadGeneratorDecl, zero_snr)
|
||||
ABI_FIELD(RadGeneratorDecl, samplers)
|
||||
ABI_FIELD(RadGeneratorDecl, default_sampler)
|
||||
ABI_FIELD(RadGeneratorDecl, default_scheduler)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_tokens)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_bos)
|
||||
ABI_FIELD(RadGeneratorDecl, chunk_eos)
|
||||
ABI_STRUCT(RadKVGroupBatch)
|
||||
ABI_FIELD(RadKVGroupBatch, group)
|
||||
ABI_FIELD(RadKVGroupBatch, slot_mapping)
|
||||
@@ -626,6 +682,12 @@ ABI_FIELD(RadVideoGenBatch, enc_kind)
|
||||
ABI_FIELD(RadVideoGenBatch, ref_tab)
|
||||
ABI_FIELD(RadVideoGenBatch, mod_cu)
|
||||
ABI_FIELD(RadVideoGenBatch, sampler)
|
||||
ABI_FIELD(RadVideoGenBatch, n_neg)
|
||||
ABI_FIELD(RadVideoGenBatch, guidance_h)
|
||||
ABI_FIELD(RadVideoGenBatch, image)
|
||||
ABI_FIELD(RadVideoGenBatch, has_image)
|
||||
ABI_FIELD(RadVideoGenBatch, guidance)
|
||||
ABI_FIELD(RadVideoGenBatch, decoder)
|
||||
ABI_STRUCT(RadVideoGenDecl)
|
||||
ABI_FIELD(RadVideoGenDecl, name)
|
||||
ABI_FIELD(RadVideoGenDecl, tmpl)
|
||||
@@ -728,6 +790,30 @@ ABI_FIELD(RadVideoGenDecl, dbg_vd_n)
|
||||
ABI_FIELD(RadVideoGenDecl, dbg_vd_n_bytes)
|
||||
ABI_FIELD(RadVideoGenDecl, dbg_vd_pix)
|
||||
ABI_FIELD(RadVideoGenDecl, dbg_vd_pix_bytes)
|
||||
ABI_FIELD(RadVideoGenDecl, sched_kind)
|
||||
ABI_FIELD(RadVideoGenDecl, dyn_shift)
|
||||
ABI_FIELD(RadVideoGenDecl, base_shift)
|
||||
ABI_FIELD(RadVideoGenDecl, max_shift)
|
||||
ABI_FIELD(RadVideoGenDecl, base_seq)
|
||||
ABI_FIELD(RadVideoGenDecl, max_seq)
|
||||
ABI_FIELD(RadVideoGenDecl, shift_terminal)
|
||||
ABI_FIELD(RadVideoGenDecl, n_refine_rungs)
|
||||
ABI_FIELD(RadVideoGenDecl, refine_rungs)
|
||||
ABI_FIELD(RadVideoGenDecl, step_text_rows)
|
||||
ABI_FIELD(RadVideoGenDecl, guidance)
|
||||
ABI_FIELD(RadVideoGenDecl, guidance_default)
|
||||
ABI_FIELD(RadVideoGenDecl, default_negative)
|
||||
ABI_FIELD(RadVideoGenDecl, image_cond)
|
||||
ABI_FIELD(RadVideoGenDecl, image_crf)
|
||||
ABI_FIELD(RadVideoGenDecl, text_left_pad)
|
||||
ABI_FIELD(RadVideoGenDecl, audio_streams)
|
||||
ABI_FIELD(RadVideoGenDecl, upscale_exact)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_out)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_min)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_max)
|
||||
ABI_FIELD(RadVideoGenDecl, duration_dtype)
|
||||
ABI_FIELD(RadVideoGenDecl, decoders)
|
||||
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
|
||||
ABI_STRUCT(RadVideoGeom)
|
||||
ABI_FIELD(RadVideoGeom, n_text)
|
||||
ABI_FIELD(RadVideoGeom, frames)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and
|
||||
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 26 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, 72 },
|
||||
{ "RadArchProbe", "", 0, 80 },
|
||||
{ "RadArchProbe", "draft_depth", 0, 4 },
|
||||
{ "RadArchProbe", "draft_depth_fixed", 4, 4 },
|
||||
{ "RadArchProbe", "shape_probe_ok", 8, 4 },
|
||||
@@ -13,6 +13,8 @@
|
||||
{ "RadArchProbe", "gen_audio", 48, 4 },
|
||||
{ "RadArchProbe", "gen_ctx", 56, 8 },
|
||||
{ "RadArchProbe", "gen_video", 64, 4 },
|
||||
{ "RadArchProbe", "kv_quant_ok", 68, 4 },
|
||||
{ "RadArchProbe", "chain_pays", 72, 4 },
|
||||
{ "RadArgs", "", 0, 64 },
|
||||
{ "RadArgs", "t", 0, 8 },
|
||||
{ "RadArgs", "n_t", 8, 4 },
|
||||
@@ -79,7 +81,7 @@
|
||||
{ "RadBufDecl", "domain", 60, 4 },
|
||||
{ "RadBufDecl", "derive", 64, 8 },
|
||||
{ "RadBufDecl", "kv", 72, 4 },
|
||||
{ "RadBuildCtx", "", 0, 104 },
|
||||
{ "RadBuildCtx", "", 0, 120 },
|
||||
{ "RadBuildCtx", "rank", 0, 4 },
|
||||
{ "RadBuildCtx", "world_size", 4, 4 },
|
||||
{ "RadBuildCtx", "max_tok", 8, 8 },
|
||||
@@ -96,6 +98,8 @@
|
||||
{ "RadBuildCtx", "max_out_rows", 80, 8 },
|
||||
{ "RadBuildCtx", "max_audio_frames", 88, 8 },
|
||||
{ "RadBuildCtx", "max_mixed_tok", 96, 8 },
|
||||
{ "RadBuildCtx", "kv_quant", 104, 4 },
|
||||
{ "RadBuildCtx", "cvec", 112, 8 },
|
||||
{ "RadAudioGenBatch", "", 0, 264 },
|
||||
{ "RadAudioGenBatch", "n_lane", 0, 8 },
|
||||
{ "RadAudioGenBatch", "lane", 8, 8 },
|
||||
@@ -164,6 +168,11 @@
|
||||
{ "RadAudioGenDecl", "first_frame", 204, 4 },
|
||||
{ "RadAudioGenDecl", "voc_chunk", 208, 8 },
|
||||
{ "RadAudioGenDecl", "voc_context", 216, 8 },
|
||||
{ "RadControlVector", "", 0, 32 },
|
||||
{ "RadControlVector", "dir", 0, 8 },
|
||||
{ "RadControlVector", "scales", 8, 8 },
|
||||
{ "RadControlVector", "n_embd", 16, 8 },
|
||||
{ "RadControlVector", "n_layers", 24, 8 },
|
||||
{ "RadAudioFormat", "", 0, 72 },
|
||||
{ "RadAudioFormat", "struct_size", 0, 4 },
|
||||
{ "RadAudioFormat", "audio_open", 8, 8 },
|
||||
@@ -313,7 +322,7 @@
|
||||
{ "RadFuseStep", "n_p", 584, 4 },
|
||||
{ "RadFuseStep", "from", 588, 32 },
|
||||
{ "RadFuseStep", "n_from", 620, 4 },
|
||||
{ "RadGenBatch", "", 0, 224 },
|
||||
{ "RadGenBatch", "", 0, 408 },
|
||||
{ "RadGenBatch", "rows", 0, 8 },
|
||||
{ "RadGenBatch", "src", 8, 8 },
|
||||
{ "RadGenBatch", "rope", 16, 8 },
|
||||
@@ -344,7 +353,31 @@
|
||||
{ "RadGenBatch", "dec_height", 212, 4 },
|
||||
{ "RadGenBatch", "dec_width", 216, 4 },
|
||||
{ "RadGenBatch", "dec_preview", 220, 4 },
|
||||
{ "RadGeneratorDecl", "", 0, 248 },
|
||||
{ "RadGenBatch", "branch", 224, 4 },
|
||||
{ "RadGenBatch", "n_pad", 228, 4 },
|
||||
{ "RadGenBatch", "valid_cu", 232, 8 },
|
||||
{ "RadGenBatch", "n_img", 240, 8 },
|
||||
{ "RadGenBatch", "img_cu", 248, 8 },
|
||||
{ "RadGenBatch", "img_rows", 256, 8 },
|
||||
{ "RadGenBatch", "mode_cu", 264, 8 },
|
||||
{ "RadGenBatch", "rope_f", 272, 8 },
|
||||
{ "RadGenBatch", "mode_rows", 280, 8 },
|
||||
{ "RadGenBatch", "mode_src", 288, 8 },
|
||||
{ "RadGenBatch", "mode_ccu", 296, 8 },
|
||||
{ "RadGenBatch", "n_mode_h", 304, 8 },
|
||||
{ "RadGenBatch", "mode_rope_f", 312, 8 },
|
||||
{ "RadGenBatch", "n_aux", 320, 8 },
|
||||
{ "RadGenBatch", "aux_ids", 328, 8 },
|
||||
{ "RadGenBatch", "aux_cu", 336, 8 },
|
||||
{ "RadGenBatch", "sigma_prev", 344, 8 },
|
||||
{ "RadGenBatch", "timestep", 352, 8 },
|
||||
{ "RadGenBatch", "sampler", 360, 8 },
|
||||
{ "RadGenBatch", "step", 368, 8 },
|
||||
{ "RadGenBatch", "size_px", 376, 8 },
|
||||
{ "RadGenBatch", "entry_h", 384, 8 },
|
||||
{ "RadGenBatch", "tokens_h", 392, 8 },
|
||||
{ "RadGenBatch", "cond_opts", 400, 4 },
|
||||
{ "RadGeneratorDecl", "", 0, 376 },
|
||||
{ "RadGeneratorDecl", "name", 0, 8 },
|
||||
{ "RadGeneratorDecl", "layout", 8, 4 },
|
||||
{ "RadGeneratorDecl", "tmpl_text", 16, 8 },
|
||||
@@ -377,6 +410,29 @@
|
||||
{ "RadGeneratorDecl", "default_cfg", 224, 8 },
|
||||
{ "RadGeneratorDecl", "max_lanes", 232, 8 },
|
||||
{ "RadGeneratorDecl", "image_out", 240, 4 },
|
||||
{ "RadGeneratorDecl", "cond_rows", 248, 8 },
|
||||
{ "RadGeneratorDecl", "rope_hw_scale", 256, 8 },
|
||||
{ "RadGeneratorDecl", "rope_text_l", 264, 4 },
|
||||
{ "RadGeneratorDecl", "pad_multiple", 268, 4 },
|
||||
{ "RadGeneratorDecl", "pad_token", 272, 4 },
|
||||
{ "RadGeneratorDecl", "cfg_original", 276, 4 },
|
||||
{ "RadGeneratorDecl", "default_negative", 280, 8 },
|
||||
{ "RadGeneratorDecl", "ref_shrink_only", 288, 4 },
|
||||
{ "RadGeneratorDecl", "aux_max_tokens", 296, 8 },
|
||||
{ "RadGeneratorDecl", "sigma_grid", 304, 4 },
|
||||
{ "RadGeneratorDecl", "min_tokens", 308, 4 },
|
||||
{ "RadGeneratorDecl", "aux_tokens", 312, 4 },
|
||||
{ "RadGeneratorDecl", "beta_start", 320, 8 },
|
||||
{ "RadGeneratorDecl", "beta_end", 328, 8 },
|
||||
{ "RadGeneratorDecl", "train_steps", 336, 4 },
|
||||
{ "RadGeneratorDecl", "beta_schedule", 340, 4 },
|
||||
{ "RadGeneratorDecl", "zero_snr", 344, 4 },
|
||||
{ "RadGeneratorDecl", "samplers", 348, 4 },
|
||||
{ "RadGeneratorDecl", "default_sampler", 352, 4 },
|
||||
{ "RadGeneratorDecl", "default_scheduler", 356, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_tokens", 360, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_bos", 364, 4 },
|
||||
{ "RadGeneratorDecl", "chunk_eos", 368, 4 },
|
||||
{ "RadKVGroupBatch", "", 0, 72 },
|
||||
{ "RadKVGroupBatch", "group", 0, 4 },
|
||||
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
|
||||
@@ -588,7 +644,7 @@
|
||||
{ "RadTunable", "n_values", 16, 4 },
|
||||
{ "RadTunable", "deflt", 24, 8 },
|
||||
{ "RadTunable", "doc", 32, 8 },
|
||||
{ "RadVideoGenBatch", "", 0, 280 },
|
||||
{ "RadVideoGenBatch", "", 0, 320 },
|
||||
{ "RadVideoGenBatch", "lane", 0, 4 },
|
||||
{ "RadVideoGenBatch", "geom", 4, 24 },
|
||||
{ "RadVideoGenBatch", "geom_d", 32, 8 },
|
||||
@@ -623,7 +679,13 @@
|
||||
{ "RadVideoGenBatch", "ref_tab", 256, 8 },
|
||||
{ "RadVideoGenBatch", "mod_cu", 264, 8 },
|
||||
{ "RadVideoGenBatch", "sampler", 272, 4 },
|
||||
{ "RadVideoGenDecl", "", 0, 784 },
|
||||
{ "RadVideoGenBatch", "n_neg", 276, 4 },
|
||||
{ "RadVideoGenBatch", "guidance_h", 280, 8 },
|
||||
{ "RadVideoGenBatch", "image", 288, 8 },
|
||||
{ "RadVideoGenBatch", "has_image", 296, 4 },
|
||||
{ "RadVideoGenBatch", "guidance", 304, 8 },
|
||||
{ "RadVideoGenBatch", "decoder", 312, 4 },
|
||||
{ "RadVideoGenDecl", "", 0, 1008 },
|
||||
{ "RadVideoGenDecl", "name", 0, 8 },
|
||||
{ "RadVideoGenDecl", "tmpl", 8, 8 },
|
||||
{ "RadVideoGenDecl", "max_text", 16, 8 },
|
||||
@@ -725,6 +787,30 @@
|
||||
{ "RadVideoGenDecl", "dbg_vd_n_bytes", 760, 8 },
|
||||
{ "RadVideoGenDecl", "dbg_vd_pix", 768, 4 },
|
||||
{ "RadVideoGenDecl", "dbg_vd_pix_bytes", 776, 8 },
|
||||
{ "RadVideoGenDecl", "sched_kind", 784, 4 },
|
||||
{ "RadVideoGenDecl", "dyn_shift", 788, 4 },
|
||||
{ "RadVideoGenDecl", "base_shift", 792, 8 },
|
||||
{ "RadVideoGenDecl", "max_shift", 800, 8 },
|
||||
{ "RadVideoGenDecl", "base_seq", 808, 8 },
|
||||
{ "RadVideoGenDecl", "max_seq", 816, 8 },
|
||||
{ "RadVideoGenDecl", "shift_terminal", 824, 8 },
|
||||
{ "RadVideoGenDecl", "n_refine_rungs", 832, 4 },
|
||||
{ "RadVideoGenDecl", "refine_rungs", 840, 8 },
|
||||
{ "RadVideoGenDecl", "step_text_rows", 848, 8 },
|
||||
{ "RadVideoGenDecl", "guidance", 856, 4 },
|
||||
{ "RadVideoGenDecl", "guidance_default", 864, 64 },
|
||||
{ "RadVideoGenDecl", "default_negative", 928, 8 },
|
||||
{ "RadVideoGenDecl", "image_cond", 936, 4 },
|
||||
{ "RadVideoGenDecl", "image_crf", 940, 4 },
|
||||
{ "RadVideoGenDecl", "text_left_pad", 944, 8 },
|
||||
{ "RadVideoGenDecl", "audio_streams", 952, 4 },
|
||||
{ "RadVideoGenDecl", "upscale_exact", 956, 4 },
|
||||
{ "RadVideoGenDecl", "duration_out", 960, 4 },
|
||||
{ "RadVideoGenDecl", "duration_min", 968, 8 },
|
||||
{ "RadVideoGenDecl", "duration_max", 976, 8 },
|
||||
{ "RadVideoGenDecl", "duration_dtype", 984, 4 },
|
||||
{ "RadVideoGenDecl", "decoders", 992, 8 },
|
||||
{ "RadVideoGenDecl", "decoder_max_area", 1000, 8 },
|
||||
{ "RadVideoGeom", "", 0, 24 },
|
||||
{ "RadVideoGeom", "n_text", 0, 4 },
|
||||
{ "RadVideoGeom", "frames", 4, 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 abi_layout_rows.h is complete; and
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under
|
||||
* the layout agrees with the table below, taken at RAD_ABI_VERSION 26 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.
|
||||
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
|
||||
};
|
||||
}
|
||||
|
||||
/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 24, kTableFormat = 2;
|
||||
/* The layout at RAD_ABI_VERSION 26 / RAD_FORMAT_VER 2 (see the file header). */
|
||||
constexpr uint32_t kTableAbi = 26, kTableFormat = 2;
|
||||
const AbiRow kTable[] = {
|
||||
#include "abi_layout_table.h"
|
||||
};
|
||||
|
||||
@@ -419,4 +419,124 @@ TEST(the_card_stages_a_cacheless_head_at_the_committed_position) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the block drafter */
|
||||
|
||||
/* A block drafter's query row on the card: the anchor (the verify's chosen token) at the
|
||||
* committed end, the row's mask id (`aux`) at every position after it, slots through the row's
|
||||
* own table and the group's length to the block's end. The host staged the furthest the anchor
|
||||
* could be; a host row is left as staged. A wrong base drafts from the wrong position and
|
||||
* acceptance collapses with no error; a wrong slot writes the drafter's K/V into another block. */
|
||||
TEST(a_block_query_row_takes_its_anchor_and_position_from_the_step_slot) {
|
||||
Slab s(ADV_BLOCK, /*n_groups=*/1, /*block=*/4);
|
||||
/* Row 0: a block of four for card 3, staged at 60; the card has it at 50. */
|
||||
s.row(0, true, 0, 4, 60, 3, 0, -1, /*mask=*/4);
|
||||
for (int b = 0; b < Slab::kPitch; ++b) s.bt(0, 0)[b] = 100 + b;
|
||||
s.st[3].ctx = 50; s.st[3].tok[0] = 777;
|
||||
/* Row 1: host-staged, untouched. */
|
||||
s.row(1, false, 4, 2, 30, 4, 0, -1, 9);
|
||||
s.w[Slab::TOK + 4] = 900; s.w[Slab::TOK + 5] = 901;
|
||||
s.w[Slab::POS + 4] = 30; s.w[Slab::POS + 5] = 31;
|
||||
/* Row 2: card 1 at 7 with mask 9; its block 1 (positions 4..7) was never assigned. */
|
||||
s.row(2, true, 6, 4, 20, 1, 0, -1, 9);
|
||||
s.bt(0, 2)[1] = -1;
|
||||
s.st[1].ctx = 7; s.st[1].tok[0] = 555;
|
||||
s.run();
|
||||
|
||||
const int32_t tok[10] = { 777, 4, 4, 4, 900, 901, 555, 9, 9, 9 };
|
||||
const int32_t pos[10] = { 50, 51, 52, 53, 30, 31, 7, 8, 9, 10 };
|
||||
const int32_t slot[10] = { 112 * 4 + 2, 112 * 4 + 3, 113 * 4 + 0, 113 * 4 + 1, 0, 0,
|
||||
-1, 8, 9, 10 };
|
||||
for (int t = 0; t < 10; ++t) {
|
||||
CHECK_EQ(s.w[Slab::TOK + t], tok[t]);
|
||||
CHECK_EQ(s.w[Slab::POS + t], pos[t]);
|
||||
CHECK_EQ(s.slot(0, t), slot[t]);
|
||||
}
|
||||
CHECK_EQ(s.w[Slab::CTX + 0], 50);
|
||||
CHECK_EQ(s.w[Slab::CTX + 1], 30);
|
||||
CHECK_EQ(s.w[Slab::CTX + 2], 7);
|
||||
CHECK_EQ(s.used(0, 0), 54);
|
||||
CHECK_EQ(s.used(0, 2), 11);
|
||||
CHECK_EQ(s.st[3].tok[0], 777); /* the anchor stays the next verify's first token */
|
||||
}
|
||||
|
||||
/* The block's proposals go into the slot behind the anchor, row i's from i * src_pitch: exactly
|
||||
* the tokens the next verify reads after its first. The anchor and host rows are untouched. */
|
||||
TEST(a_block_take_puts_each_rows_proposals_behind_its_anchor) {
|
||||
Slab s(ADV_BTAKE);
|
||||
s.a.round = 3;
|
||||
s.a.src_pitch = 3;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
s.row(i, true, 4 * i, 4, 0, /*card=*/2 - i, 0, -1, 4);
|
||||
s.st[2 - i].tok[0] = 50 + i;
|
||||
for (int c = 0; c < 3; ++c) s.src[i * 3 + c] = 1000 * (i + 1) + c;
|
||||
}
|
||||
s.row(3, false, 12, 4, 0, 5, 0, -1, 4);
|
||||
s.src[9] = 4242;
|
||||
s.run();
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const StepSlot& S = s.st[2 - i];
|
||||
CHECK_EQ(S.tok[0], 50 + i);
|
||||
for (int c = 0; c < 3; ++c) CHECK_EQ(S.tok[1 + c], 1000 * (i + 1) + c);
|
||||
}
|
||||
CHECK(s.st[5].tok[1] != 4242);
|
||||
}
|
||||
|
||||
/* The chain a pipelined block-drafter step runs, row for row: the verify's acceptance, the query
|
||||
* block at the committed end, the take, then the step issued ahead. A verify at 101..105 (four
|
||||
* drafts) accepts two, so the anchor is the target's third pick at 104, and the next verify
|
||||
* starts there with the anchor and the block's proposals. */
|
||||
TEST(a_block_drafter_step_on_the_card_continues_where_the_verify_left_off) {
|
||||
StepSlot st;
|
||||
/* The verify: 7000 then drafts 7101..7104; the target picks 7101, 7102, 9999, ... */
|
||||
{
|
||||
Slab v(ADV_ACCEPT);
|
||||
v.row(0, false, 0, 5, 101, 1, 0, 0, 4);
|
||||
const int32_t t[5] = { 7000, 7101, 7102, 7103, 7104 };
|
||||
const int32_t y[5] = { 7101, 7102, 9999, 1, 2 };
|
||||
for (int j = 0; j < 5; ++j) { v.w[Slab::TOK + j] = t[j]; v.src[j] = y[j]; }
|
||||
v.run();
|
||||
st = v.st[1];
|
||||
}
|
||||
CHECK_EQ(st.acc, 2);
|
||||
CHECK_EQ(st.ctx, 104);
|
||||
CHECK_EQ(st.tok[0], 9999);
|
||||
/* The query block of four, staged at the furthest anchor, 106. */
|
||||
{
|
||||
Slab q(ADV_BLOCK);
|
||||
q.st[1] = st;
|
||||
q.row(0, true, 0, 4, 106, 1, 0, -1, 4);
|
||||
q.run();
|
||||
const int32_t tok[4] = { 9999, 4, 4, 4 };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
CHECK_EQ(q.w[Slab::TOK + j], tok[j]);
|
||||
CHECK_EQ(q.w[Slab::POS + j], 104 + j);
|
||||
}
|
||||
st = q.st[1];
|
||||
}
|
||||
/* Its three proposals, then the next verify of 1 + 3. */
|
||||
{
|
||||
Slab t(ADV_BTAKE);
|
||||
t.st[1] = st;
|
||||
t.a.round = 3;
|
||||
t.a.src_pitch = 3;
|
||||
t.row(0, true, 0, 4, 106, 1, 0, -1, 4);
|
||||
t.src[0] = 8001; t.src[1] = 8002; t.src[2] = 8003;
|
||||
t.run();
|
||||
st = t.st[1];
|
||||
}
|
||||
{
|
||||
Slab n(ADV_TRUNK);
|
||||
n.st[1] = st;
|
||||
n.row(0, true, 0, 4, 106, 1, 0, 0, 3);
|
||||
n.run();
|
||||
const int32_t tok[4] = { 9999, 8001, 8002, 8003 };
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
CHECK_EQ(n.w[Slab::TOK + j], tok[j]);
|
||||
CHECK_EQ(n.w[Slab::POS + j], 104 + j);
|
||||
}
|
||||
CHECK_EQ(n.w[Slab::CTX], 104);
|
||||
CHECK_EQ(n.w[Slab::ACC], 3);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+1196
File diff suppressed because it is too large.
Load diff
+2376
-1153
File diff suppressed because it is too large.
Load diff
+83
-2
@@ -751,6 +751,34 @@ TEST(kv_block_size_comes_off_the_kernel) {
|
||||
CHECK_EQ((int)gi.layers.size(), 2);
|
||||
}
|
||||
|
||||
TEST(glm_index_cache_pages_are_sized_by_the_real_pool_consumer) {
|
||||
Registry reg;
|
||||
REQUIRE_EQ(reg.load_dir(home() + "/kernels", { "libref" }), RAD_OK);
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = RAD_U8;
|
||||
kd.n_head_kv = 1;
|
||||
kd.head_dim = 17;
|
||||
const auto group = b.decl_kv_group("glm_index", &kd);
|
||||
RadWeightDecl wd{};
|
||||
wd.dtype = RAD_F32;
|
||||
wd.rank = 2;
|
||||
wd.shape[0] = 4;
|
||||
wd.shape[1] = 128;
|
||||
wd.access = RAD_ACCESS_PER_TOKEN;
|
||||
wd.shard = RAD_SHARD_NONE;
|
||||
const auto ape = b.decl_weight("pool_ape", &wd);
|
||||
const RadParam params[] = { RAD_RANGE("M", 1, 12), RAD_INT("n", 128), RAD_INT("ratio", 4),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("block_size", 4) };
|
||||
REQUIRE(b.decl_op("dsa_pool", params, 5, &ape, 1));
|
||||
CHECK_EQ(b.kv_block_size(group), 4);
|
||||
CHECK_OK(b.bind_layer_kv(0, group));
|
||||
CHECK_OK(b.bind_layer_kv(1, group));
|
||||
REQUIRE_EQ(b.finish(), RAD_OK);
|
||||
CHECK_EQ(b.program().kv_groups[group].bytes_per_block, (int64_t)(2 * 136));
|
||||
}
|
||||
|
||||
TEST(a_kv_group_with_no_layers_is_an_error) {
|
||||
NEED_PLUGIN(reg)
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
@@ -1538,6 +1566,46 @@ TEST(a_two_plane_weight_needs_a_kernel_that_joins_its_planes) {
|
||||
}
|
||||
}
|
||||
|
||||
/* A kernel that reads a weight's stored bytes without interpreting them (libr4d's prefetch into
|
||||
* the cache) answers RAD_LAYOUT_ANY: it takes the form another kernel chose, declared before it or
|
||||
* after, and claims none, so it never conflicts; a weight only it reads is stored as it is. */
|
||||
TEST(a_kernel_that_reads_any_stored_form_claims_none) {
|
||||
NEED_EXTRA(reg)
|
||||
const RadParam p[] = { RAD_RANGE("M", 1, 16), RAD_INT("N", 256), RAD_INT("K", 256),
|
||||
RAD_STR("dtype", "bf16") };
|
||||
auto weight = [](Builder& b) {
|
||||
RadWeightDecl d{};
|
||||
d.dtype = RAD_BF16;
|
||||
d.rank = 2;
|
||||
d.shape[0] = 256;
|
||||
d.shape[1] = 256;
|
||||
d.access = RAD_ACCESS_PER_TOKEN;
|
||||
d.group = rad_group_layer(0);
|
||||
return b.decl_weight("w.bf16", &d);
|
||||
};
|
||||
for (bool any_first : { false, true }) {
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
const rad_weight w = weight(b);
|
||||
rad_op a = 0, t = 0;
|
||||
if (any_first) a = b.decl_op("t_any", p, 4, &w, 1);
|
||||
t = b.decl_op("t_lay", p, 4, &w, 1);
|
||||
if (!any_first) a = b.decl_op("t_any", p, 4, &w, 1);
|
||||
REQUIRE(a != 0 && t != 0);
|
||||
CHECK_EQ(std::string(device_row(b.program().op(a), 0)), "t_any_read");
|
||||
CHECK_EQ(std::string(device_row(b.program().op(t), 0)), "t_lay_tiled");
|
||||
CHECK_OK(b.finish());
|
||||
CHECK(b.errors().empty());
|
||||
CHECK_EQ(b.program().weight(w)->layout_tag, std::string("tiled"));
|
||||
}
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
const rad_weight w = weight(b);
|
||||
REQUIRE(b.decl_op("t_any", p, 4, &w, 1) != 0);
|
||||
CHECK_OK(b.finish());
|
||||
CHECK(b.errors().empty());
|
||||
CHECK(b.program().weight(w)->layout_tag.empty());
|
||||
CHECK(b.program().weight(w)->identity);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A [256, 256] E4M3 weight with one f32 scale per 128x128 tile, declared over both planes. */
|
||||
@@ -1944,7 +2012,8 @@ TEST(the_home_search_path_splits_on_colons_and_the_first_home_with_a_file_wins)
|
||||
* selected by the (id, quantisation) pair, exactly. A checkpoint whose quantisation was imported
|
||||
* weight by weight names its producing tool, which no plugin claims: the family's one quantised
|
||||
* plugin serves it (or its only plugin), and two quantised plugins are refused by name rather than
|
||||
* chosen between. */
|
||||
* chosen between. A plugin that declines imports (rad_arch_serves_imports, radtest_archq_w8) is
|
||||
* still selected by its own descriptor, but is neither counted nor picked for an import. */
|
||||
TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) {
|
||||
const std::string archq = home() + "/testarchq";
|
||||
NEED_ARTIFACT(archq + "/radtest_archq_fp8.so");
|
||||
@@ -1978,7 +2047,9 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) {
|
||||
const std::string all = make_home({ "plain", "fp8", "w4" });
|
||||
const std::string one = make_home({ "plain", "fp8" });
|
||||
const std::string bare = make_home({ "plain" });
|
||||
REQUIRE(!all.empty() && !one.empty() && !bare.empty());
|
||||
const std::string w8 = make_home({ "plain", "fp8", "w8" });
|
||||
const std::string plain_w8 = make_home({ "plain", "w8" });
|
||||
REQUIRE(!all.empty() && !one.empty() && !bare.empty() && !w8.empty() && !plain_w8.empty());
|
||||
|
||||
LoadedPlugins lp;
|
||||
std::string log;
|
||||
@@ -2000,6 +2071,16 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) {
|
||||
CHECK_OK(pick(bare, "quark-mxfp4", true, &lp, &log));
|
||||
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain"));
|
||||
CHECK_EQ(pick(all, "fp8", false, &lp, &log), RAD_OK);
|
||||
|
||||
/* A second quantised plugin that declines imports leaves them to the first. */
|
||||
CHECK_OK(pick(w8, "quark-mxfp4", true, &lp, &log));
|
||||
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_fp8"));
|
||||
CHECK(!has(log, "more than one quantised plugin"));
|
||||
CHECK_OK(pick(w8, "w8", false, &lp, &log));
|
||||
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_w8"));
|
||||
CHECK_EQ(lp.arch_quant, std::string("w8"));
|
||||
CHECK_OK(pick(plain_w8, "quark-mxfp4", true, &lp, &log));
|
||||
CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain"));
|
||||
rad_tools_registry().close();
|
||||
}
|
||||
|
||||
|
||||
+62
-2
@@ -288,8 +288,8 @@ TEST(every_shipped_template_renders_as_reference_jinja_does) {
|
||||
"reference render " + first_difference(ref, got));
|
||||
}
|
||||
}
|
||||
/* Four templates, every case each one renders. */
|
||||
CHECK(compared >= 60);
|
||||
/* Five templates, every case each one renders. */
|
||||
CHECK(compared >= 74);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ reading the reply back */
|
||||
@@ -1016,6 +1016,66 @@ TEST(the_capability_probe_reads_what_the_template_actually_does) {
|
||||
CHECK(c.system_role);
|
||||
}
|
||||
|
||||
/* jinja2 reads `obj.0` as `obj[0]`, and GLM-5's template tests a tool result with
|
||||
* `m.content.0.type`. The engine threw on it, and the probe, which swallows a throw, reported a
|
||||
* template that renders tools as one that cannot: every request with `tools` was refused. */
|
||||
TEST(a_dotted_integer_is_an_index_as_in_jinja2) {
|
||||
ChatTemplate glm;
|
||||
CHECK_OK(glm.load(
|
||||
"{%- if tools %}<tools>{% for t in tools %}{{ t.function.name }};{% endfor %}</tools>{% endif %}"
|
||||
"{%- for m in messages %}"
|
||||
"{%- if m.role == 'tool' and m.content is not mapping and m.content.0.type == 'tool_reference' %}<ref/>"
|
||||
"{%- else %}<{{ m.role }}>{{ m.content }}"
|
||||
"{%- if m.tool_calls %}{% for c in m.tool_calls %}<call>{{ c.function.name }}</call>{% endfor %}{% endif %}"
|
||||
"</{{ m.role }}>{%- endif %}"
|
||||
"{%- endfor %}"
|
||||
"{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
|
||||
CHECK(glm.caps().tools);
|
||||
CHECK(glm.caps().tool_calls);
|
||||
/* The string-content probe hands the template an empty tools array, not [null]: this
|
||||
* template iterates `tools`, threw on the null, and lost string content. */
|
||||
CHECK(glm.caps().string_content);
|
||||
|
||||
ChatTemplate first;
|
||||
CHECK_OK(first.load("{{ messages.0.content }}|{{ messages.1.role }}", "", ""));
|
||||
json msgs = json::array();
|
||||
msgs.push_back({{"role", "user"}, {"content", "hi"}});
|
||||
msgs.push_back({{"role", "assistant"}, {"content", "hello"}});
|
||||
ChatPrompt p;
|
||||
CHECK_OK(first.apply(msgs, json(), ChatOptions{}, &p));
|
||||
CHECK_EQ(p.prompt, std::string("hi|assistant"));
|
||||
}
|
||||
|
||||
/* A template that takes one system message, first, as many do, against conversations the Chat
|
||||
* Completions API allows: a system message after a user turn, and two at the head. They are
|
||||
* rendered with the system messages merged, in order, into one at the head (#137). Any other
|
||||
* refusal comes back in the template's own words, without the parser-generation wrapper. */
|
||||
TEST(system_messages_a_template_takes_only_first_are_merged_at_the_head) {
|
||||
ChatTemplate t;
|
||||
CHECK_OK(t.load(
|
||||
"{%- for m in messages %}"
|
||||
"{%- if m.role == 'system' and not loop.first %}"
|
||||
"{{- raise_exception('System message must be at the beginning.') }}{%- endif %}"
|
||||
"{%- if m.role == 'user' and m.content == 'boom' %}{{- raise_exception('no boom') }}{%- endif %}"
|
||||
"<{{ m.role }}>{{ m.content }}</{{ m.role }}>"
|
||||
"{%- endfor %}{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
|
||||
ChatOptions opt;
|
||||
opt.quiet = true;
|
||||
auto render = [&](const json& msgs, ChatPrompt* p) { return t.apply(msgs, json(), opt, p); };
|
||||
ChatPrompt a, b, c, d;
|
||||
CHECK_OK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"hi"}])"), &a));
|
||||
CHECK_EQ(a.prompt, std::string("<system>s</system><user>hi</user><assistant>"));
|
||||
CHECK_OK(render(json::parse(R"([{"role":"user","content":"hi"},{"role":"system","content":"s"}])"), &b));
|
||||
CHECK_EQ(b.prompt, std::string("<system>s</system><user>hi</user><assistant>"));
|
||||
CHECK_OK(render(json::parse(R"([{"role":"system","content":"s1"},{"role":"system",
|
||||
"content":[{"type":"text","text":"s2"}]},{"role":"user","content":"hi"}])"), &c));
|
||||
CHECK_EQ(c.prompt, std::string("<system>s1\n\ns2</system><user>hi</user><assistant>"));
|
||||
CHECK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"boom"}])"),
|
||||
&d) < 0);
|
||||
CHECK(d.error.find("no boom") != std::string::npos);
|
||||
CHECK(d.error.find("Unable to generate parser") == std::string::npos);
|
||||
}
|
||||
|
||||
/* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value;
|
||||
* a throw would cross the bringup path. */
|
||||
TEST(a_template_that_does_not_parse_is_a_value_and_not_a_throw) {
|
||||
|
||||
@@ -196,7 +196,7 @@ TEST(an_older_struct_reads_the_object_fields_as_zero) {
|
||||
CHECK(!f.object_bare_keys);
|
||||
CHECK(!f.reasoning_anywhere);
|
||||
CHECK(chat_format_check(f, &why) == RAD_E_UNSUPPORTED);
|
||||
CHECK(why.find("name_suffix") != std::string::npos);
|
||||
CHECK(why.find("call_end") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) {
|
||||
|
||||
+344
-1
@@ -995,6 +995,8 @@ TEST(the_derived_formats_are_the_ones_in_service) {
|
||||
CHECK(refused.empty());
|
||||
CHECK_EQ(f.reasoning_open, std::string("<think>\n"));
|
||||
CHECK_EQ(f.reasoning_close, std::string("\n</think>\n\n"));
|
||||
/* Qwen writes a value on lines of its own, MiniCPM flush against its tags. */
|
||||
CHECK_EQ(f.value_newlines, is_qwen(m));
|
||||
if (is_qwen(m)) {
|
||||
CHECK_EQ(f.call_open, std::string("<tool_call>\n"));
|
||||
CHECK_EQ(f.call_close, std::string("</tool_call>"));
|
||||
@@ -1260,7 +1262,9 @@ TEST(a_format_the_parser_cannot_read_is_refused_by_name) {
|
||||
CHECK(refused([](RadChatFormat& c) { c.name_suffix = ""; }, "name_suffix"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.call_end = ""; }, "call_end"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = ""; }, "arg_value_suffix"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.arg_value_prefix = "\""; }, "both set"));
|
||||
CHECK(refused([](RadChatFormat& c) {
|
||||
c.call_open = ""; c.call_close = ""; c.name_suffix = ""; c.arg_prefix = "\n<parameter=";
|
||||
}, "whitespace"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.arg_prefix = "</function>\n"; }, "told apart"));
|
||||
CHECK(refused([](RadChatFormat& c) { c.reasoning_close = ""; }, "reasoning_close"));
|
||||
static const char* const other[] = { "<call>" };
|
||||
@@ -1442,6 +1446,48 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) {
|
||||
CHECK(why.find("a>b") != std::string::npos);
|
||||
}
|
||||
|
||||
/* GLM-5.3-Flash's template reads list items as `m.content.0.type`, jinja2's dotted index, and
|
||||
* writes calls as `<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value></tool_call>`. The
|
||||
* capability probe renders with tools and tool calls, so a runtime that throws on the dotted index
|
||||
* reports no tool support; and a name the opener opens, with no tag of its own, must be a format
|
||||
* the derivation describes, or every request with tools is refused. */
|
||||
TEST(glm53_serves_tools_from_its_template) {
|
||||
std::shared_ptr<Vocab> v = vocab_with(fixture("glm53"));
|
||||
REQUIRE(v != nullptr);
|
||||
server::ChatTemplateBridge br;
|
||||
CHECK_OK(br.init(*v));
|
||||
CHECK(br.supports_tools());
|
||||
CHECK_EQ(br.tool_refusal(), std::string());
|
||||
const server::ChatRender r = bridge_render(br, agent_tools());
|
||||
REQUIRE(!r.prompt.empty());
|
||||
CHECK(r.prompt.find("<tools>") != std::string::npos);
|
||||
for (const auto& t : agent_tools())
|
||||
CHECK(r.prompt.find("\"name\": \"" + t["function"]["name"].get<std::string>() + "\"") !=
|
||||
std::string::npos);
|
||||
CHECK(!r.grammar.empty());
|
||||
CHECK(r.grammar_lazy);
|
||||
REQUIRE(r.grammar_triggers.size() == 1);
|
||||
CHECK_EQ(r.grammar_triggers[0].type, 1);
|
||||
CHECK_EQ(r.grammar_triggers[0].value, std::string("<tool_call>"));
|
||||
/* Each tag is a marker of its own: one the decoder suppresses as a control token is
|
||||
* structure the parser never sees. */
|
||||
for (const char* t : { "<think>", "</think>", "<tool_call>", "</tool_call>", "<arg_key>",
|
||||
"</arg_key>", "<arg_value>", "</arg_value>" })
|
||||
CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), t) !=
|
||||
r.preserved_tokens.end());
|
||||
REQUIRE(r.parser != nullptr);
|
||||
std::unique_ptr<server::IReplyReader> rd = r.parser->open();
|
||||
rd->feed("Look.</think>\n<tool_call>read<arg_key>path</arg_key><arg_value>/a"
|
||||
"</arg_value><arg_key>limit</arg_key><arg_value>3</arg_value></tool_call>", nullptr);
|
||||
rd->finish(nullptr);
|
||||
const server::ParsedMessage pm = rd->message();
|
||||
CHECK_EQ(pm.reasoning, std::string("Look."));
|
||||
CHECK_EQ(pm.content, std::string());
|
||||
REQUIRE(pm.tool_calls.size() == 1);
|
||||
CHECK_EQ(pm.tool_calls[0].name, std::string("read"));
|
||||
CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":3}"));
|
||||
}
|
||||
|
||||
/* A template writing each call as a JSON object is not a describable format: the model still
|
||||
* chats with reasoning split, and a request with tools is refused with the reason. */
|
||||
TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) {
|
||||
@@ -1654,6 +1700,302 @@ TEST(an_object_format_the_parser_cannot_read_is_refused) {
|
||||
"name_prefix is empty"));
|
||||
}
|
||||
|
||||
/* ================================================================== a name the opener opens
|
||||
*
|
||||
* GLM-5 writes a call as `<tool_call>NAME<arg_key>K</arg_key><arg_value>V</arg_value>...
|
||||
* </tool_call>`: the per-call opener opens the name, nothing of its own closes it, and it ends at
|
||||
* the first argument or the call's close. Values are flush against their tags, strings raw and
|
||||
* anything else JSON. The legacy path reads the opener as a wrapper around a call with an empty
|
||||
* name tag, which is a different format, so these replies are checked against the messages they
|
||||
* were rendered from rather than against the old parser. */
|
||||
|
||||
static const char* const kGlmOpener[] = { "<tool_call>" };
|
||||
|
||||
static RadChatFormat glm_abi() {
|
||||
RadChatFormat c;
|
||||
std::memset(&c, 0, sizeof c);
|
||||
c.struct_size = sizeof c;
|
||||
c.name = "glm-declared";
|
||||
c.reasoning_open = "<think>";
|
||||
c.reasoning_close = "</think>";
|
||||
c.reasoning_breaks = kGlmOpener;
|
||||
c.n_reasoning_breaks = 1;
|
||||
c.name_prefix = "<tool_call>";
|
||||
c.name_suffix = "";
|
||||
c.call_end = "</tool_call>";
|
||||
c.arg_prefix = "<arg_key>";
|
||||
c.arg_name_suffix = "</arg_key>";
|
||||
c.arg_value_prefix = "<arg_value>";
|
||||
c.arg_value_suffix = "</arg_value>";
|
||||
c.string_value = RAD_CHAT_VALUE_CDATA;
|
||||
c.other_value = RAD_CHAT_VALUE_JSON;
|
||||
c.value_newlines = 0;
|
||||
c.triggers = kGlmOpener;
|
||||
c.n_triggers = 1;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* The agent's tools and one that takes no arguments. */
|
||||
static const json& glm_tools() {
|
||||
static const json t = [] {
|
||||
json v = agent_tools();
|
||||
v.push_back(json::parse(R"({"type":"function","function":{"name":"now",
|
||||
"description":"The time.","parameters":{"type":"object","properties":{}}}})"));
|
||||
return v;
|
||||
}();
|
||||
return t;
|
||||
}
|
||||
|
||||
/* GLM's template, the format derived from it, and the request every reply here answers. */
|
||||
struct Glm {
|
||||
ChatTemplate tmpl;
|
||||
ChatFormat f;
|
||||
ChatPrompt head;
|
||||
std::shared_ptr<const ReplyParser> parser;
|
||||
std::string grammar;
|
||||
};
|
||||
|
||||
static const Glm* glm() {
|
||||
static std::unique_ptr<Glm> g = []() -> std::unique_ptr<Glm> {
|
||||
auto g = std::make_unique<Glm>();
|
||||
std::string why, refused;
|
||||
const std::string src = fixture("glm53");
|
||||
if (g->tmpl.load(src, "", "<|user|>") < 0) return nullptr;
|
||||
if (chat_format_from_template(src, "", "<|user|>", &g->f, &refused, &why) < 0 ||
|
||||
!refused.empty())
|
||||
return nullptr;
|
||||
ChatOptions opt;
|
||||
opt.parallel_tool_calls = true;
|
||||
const json user = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } });
|
||||
if (g->tmpl.apply(user, glm_tools(), opt, &g->head) < 0) return nullptr;
|
||||
ReplyOptions ro;
|
||||
ro.generation_prompt = g->head.generation_prompt;
|
||||
ro.tools = &glm_tools();
|
||||
ro.terminators = { "<|user|>", "<|observation|>", "<|endoftext|>" };
|
||||
g->parser = parser_of(g->f, ro);
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &glm_tools();
|
||||
gq.generation_prompt = g->head.generation_prompt;
|
||||
ChatGrammar gr;
|
||||
if (chat_format_grammar(g->f, gq, &gr, &why) < 0) return nullptr;
|
||||
g->grammar = gr.text;
|
||||
return g->parser ? std::move(g) : nullptr;
|
||||
}();
|
||||
return g.get();
|
||||
}
|
||||
|
||||
/* The assistant turn as GLM's template writes it after the generation prompt. */
|
||||
static std::string glm_reply(const Glm& g, const json& assistant) {
|
||||
json msgs = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } });
|
||||
msgs.push_back(assistant);
|
||||
ChatOptions opt;
|
||||
opt.add_generation_prompt = false;
|
||||
opt.parallel_tool_calls = true;
|
||||
ChatPrompt whole;
|
||||
if (g.tmpl.apply(msgs, glm_tools(), opt, &whole) < 0) return "";
|
||||
const std::string& head = g.head.prompt;
|
||||
if (whole.prompt.compare(0, head.size(), head) != 0) return "";
|
||||
std::string r = whole.prompt.substr(head.size());
|
||||
while (!r.empty() && r.back() == '\n') r.pop_back();
|
||||
return r;
|
||||
}
|
||||
|
||||
static bool no_markup(const std::string& s) {
|
||||
for (const char* t : { "<tool_call>", "</tool_call>", "<arg_key>", "</arg_key>", "<arg_value>",
|
||||
"</arg_value>", "<think>", "</think>" })
|
||||
if (s.find(t) != std::string::npos) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(glm53_derives_a_name_the_opener_opens) {
|
||||
const Glm* g = glm();
|
||||
REQUIRE(g != nullptr);
|
||||
const ChatFormat& f = g->f;
|
||||
CHECK_EQ(f.reasoning_open, std::string("<think>"));
|
||||
CHECK_EQ(f.reasoning_close, std::string("</think>"));
|
||||
CHECK(f.call_open.empty() && f.call_close.empty());
|
||||
CHECK_EQ(f.name_prefix, std::string("<tool_call>"));
|
||||
CHECK(f.name_suffix.empty());
|
||||
CHECK_EQ(f.call_end, std::string("</tool_call>"));
|
||||
CHECK_EQ(f.arg_prefix, std::string("<arg_key>"));
|
||||
CHECK_EQ(f.arg_name_suffix, std::string("</arg_key>"));
|
||||
CHECK_EQ(f.arg_value_prefix, std::string("<arg_value>"));
|
||||
CHECK_EQ(f.arg_value_suffix, std::string("</arg_value>"));
|
||||
/* The template writes a value flush against its tags, so its newlines are its own. */
|
||||
CHECK(!f.value_newlines);
|
||||
CHECK(f.triggers == std::vector<std::string>{ "<tool_call>" });
|
||||
CHECK(f.reasoning_breaks == std::vector<std::string>{ "<tool_call>" });
|
||||
CHECK(g->head.generation_prompt.find("<think>") != std::string::npos);
|
||||
CHECK(g->parser->reasoning().starts_open);
|
||||
|
||||
/* A plugin declares the same format through the ABI, unchanged, and gets the same grammar. */
|
||||
RadChatFormat c = glm_abi();
|
||||
ChatFormat declared;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(&c, &declared, &why));
|
||||
CHECK_OK(chat_format_check(declared, &why));
|
||||
ChatFormat derived = f;
|
||||
derived.name = declared.name;
|
||||
CHECK_EQ(chat_format_describe(derived), chat_format_describe(declared));
|
||||
CHECK(chat_format_markers(derived) == chat_format_markers(declared));
|
||||
ChatGrammarRequest gq;
|
||||
gq.tools = &glm_tools();
|
||||
gq.generation_prompt = g->head.generation_prompt;
|
||||
ChatGrammar gr;
|
||||
CHECK_OK(chat_format_grammar(declared, gq, &gr, &why));
|
||||
CHECK_EQ(gr.text, g->grammar);
|
||||
CHECK(gr.lazy);
|
||||
CHECK(gr.trigger_words == std::vector<std::string>{ "<tool_call>" });
|
||||
|
||||
/* Wrapped, a suffixless name would make the bare name_prefix in prose a call. */
|
||||
c.call_open = "<calls>";
|
||||
c.call_close = "</calls>";
|
||||
static const char* const wrap[] = { "<calls>" };
|
||||
c.reasoning_breaks = wrap;
|
||||
CHECK_OK(chat_format_from_abi(&c, &declared, &why));
|
||||
CHECK(chat_format_check(declared, &why) < 0);
|
||||
CHECK(why.find("name_suffix") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(glm53_replies_read_back_as_the_messages_they_render) {
|
||||
const Glm* g = glm();
|
||||
REQUIRE(g != nullptr);
|
||||
const ReplyParser& p = *g->parser;
|
||||
struct Case { const char* what; json msg; };
|
||||
const std::vector<Case> cases = {
|
||||
{ "one call, string and integer",
|
||||
message("Look.", "", { call("read", { { "path", "/a" }, { "limit", 3 } }) }) },
|
||||
{ "two calls",
|
||||
message("Two.", "", { call("bash", { { "command", "ls -la" }, { "timeout", 30 } }),
|
||||
call("read", { { "path", "/b" } }) }) },
|
||||
{ "a call with no arguments", message("", "", { call("now", json::object()) }) },
|
||||
{ "content, then a call",
|
||||
message("Plan.", "I will read it.", { call("read", { { "path", "/c" } }) }) },
|
||||
{ "values holding tags and newlines",
|
||||
message("", "", { call("write", { { "path", "/x.html" },
|
||||
{ "content", "\n<p>a & b</p>\n<arg_key>k</arg_key> "
|
||||
"<tool_call>f</tool_call>\nend\n" } }) }) },
|
||||
{ "a structured value",
|
||||
message("", "", { call("edit", { { "path", "/d" },
|
||||
{ "edits", json::parse(R"([{"oldText":"a","newText":"b"}])") } }) }) },
|
||||
};
|
||||
for (const Case& k : cases) {
|
||||
const std::string reply = glm_reply(*g, k.msg);
|
||||
REQUIRE(!reply.empty());
|
||||
bool strict = false;
|
||||
const ReplyMessage m = reply_parse(p, reply, &strict);
|
||||
const std::string where = std::string(k.what) + ": " + quote(reply) + "\n " + show(m);
|
||||
if (!strict) ::radtest::fail(__FILE__, __LINE__, "left the grammar: " + where);
|
||||
CHECK_EQ(m.reasoning, k.msg.value("reasoning_content", std::string()));
|
||||
CHECK_EQ(m.content, k.msg["content"].get<std::string>());
|
||||
CHECK(no_markup(m.content));
|
||||
const json& calls = k.msg["tool_calls"];
|
||||
if (m.calls.size() != calls.size()) {
|
||||
::radtest::fail(__FILE__, __LINE__, "call count: " + where);
|
||||
continue;
|
||||
}
|
||||
for (size_t i = 0; i < calls.size(); ++i) {
|
||||
const json& fn = calls[i]["function"];
|
||||
CHECK_EQ(m.calls[i].name, fn["name"].get<std::string>());
|
||||
CHECK(m.calls[i].closed);
|
||||
/* The arguments as written, in the reply's order; JSON values keep their spacing. */
|
||||
CHECK(json::parse(m.calls[i].arguments) == json::parse(fn["arguments"].get<std::string>()));
|
||||
}
|
||||
const std::string s = stream_all(p, reply);
|
||||
if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, std::string(k.what) + ": " + s);
|
||||
/* What constrained decoding admits from the trigger on is the reply's call text. */
|
||||
const size_t at = reply.find("<tool_call>");
|
||||
REQUIRE(at != std::string::npos);
|
||||
CHECK_EQ(object_admits(g->grammar, reply.substr(at)), 1);
|
||||
}
|
||||
CHECK_EQ(reply_parse(p, glm_reply(*g, cases[0].msg)).calls[0].arguments,
|
||||
std::string("{\"path\":\"/a\",\"limit\":3}"));
|
||||
|
||||
/* Every message the other formats are checked with, too. */
|
||||
size_t n = 0;
|
||||
for (const json& msg : rendered_corpus()) {
|
||||
const std::string reply = glm_reply(*g, msg);
|
||||
if (reply.empty()) continue;
|
||||
const ReplyMessage m = reply_parse(p, reply);
|
||||
const size_t want = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0;
|
||||
bool ok = m.calls.size() == want && no_markup(m.content);
|
||||
for (size_t i = 0; ok && i < want; ++i) {
|
||||
const json& fn = msg["tool_calls"][i]["function"];
|
||||
ok = m.calls[i].name == fn["name"].get<std::string>() &&
|
||||
round_trips(json::parse(fn["arguments"].get<std::string>()),
|
||||
json::parse(m.calls[i].arguments), true);
|
||||
}
|
||||
if (!ok) ::radtest::fail(__FILE__, __LINE__, "rendered: " + quote(reply) + "\n " + show(m));
|
||||
const std::string s = stream_all(p, reply, 512);
|
||||
if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, "rendered: " + s + "\n " + quote(reply));
|
||||
++n;
|
||||
}
|
||||
CHECK(n > 10);
|
||||
}
|
||||
|
||||
/* Without a tag of its own the name is read until something shows it is no name, so an opener
|
||||
* in prose, a stray name and a reply cut off anywhere must all stay readable. */
|
||||
TEST(glm53_reads_what_strays_from_its_grammar) {
|
||||
const Glm* g = glm();
|
||||
REQUIRE(g != nullptr);
|
||||
const ReplyParser& p = *g->parser;
|
||||
bool strict = true;
|
||||
|
||||
ReplyMessage m = reply_parse(p, "</think>Wrap a call in <tool_call> tags, then stop.", &strict);
|
||||
CHECK(m.calls.empty());
|
||||
CHECK_EQ(m.content, std::string("Wrap a call in <tool_call> tags, then stop."));
|
||||
|
||||
/* GLM-4.5 put newlines around its tags. */
|
||||
m = reply_parse(p, "</think><tool_call>read\n<arg_key>path</arg_key><arg_value>/a</arg_value>\n"
|
||||
"</tool_call>", &strict);
|
||||
CHECK(strict);
|
||||
REQUIRE(m.calls.size() == 1);
|
||||
CHECK_EQ(m.calls[0].name, std::string("read"));
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"/a\"}"));
|
||||
|
||||
m = reply_parse(p, "</think><tool_call>\nread<arg_key>path</arg_key><arg_value>/a</arg_value>"
|
||||
"</tool_call>", &strict);
|
||||
CHECK(!strict);
|
||||
REQUIRE(m.calls.size() == 1);
|
||||
CHECK_EQ(m.calls[0].name, std::string("read"));
|
||||
|
||||
m = reply_parse(p, "</think><tool_call>nope<arg_key>a</arg_key><arg_value>1</arg_value>"
|
||||
"</tool_call>", &strict);
|
||||
CHECK(!strict);
|
||||
REQUIRE(m.calls.size() == 1);
|
||||
CHECK_EQ(m.calls[0].name, std::string("nope"));
|
||||
CHECK_EQ(m.calls[0].arguments, std::string("{\"a\":\"1\"}"));
|
||||
|
||||
/* An unclosed reasoning block ends where a call begins. */
|
||||
m = reply_parse(p, "thinking<tool_call>now</tool_call>", &strict);
|
||||
CHECK_EQ(m.reasoning, std::string("thinking"));
|
||||
REQUIRE(m.calls.size() == 1);
|
||||
CHECK_EQ(m.calls[0].name, std::string("now"));
|
||||
|
||||
/* Cut off anywhere, the reply holds no markup in its content and names no other call. */
|
||||
const std::string reply = glm_reply(*g, message("Look.", "Reading.",
|
||||
{ call("read", { { "path", "/a" }, { "limit", 3 } }), call("now", json::object()) }));
|
||||
for (size_t k = 0; k <= reply.size(); ++k) {
|
||||
const ReplyMessage t = reply_parse(p, reply.substr(0, k));
|
||||
if (!no_markup(t.content) || t.calls.size() > 2 ||
|
||||
(!t.calls.empty() && t.calls[0].name != "read") ||
|
||||
(t.calls.size() == 2 && t.calls[1].name != "now"))
|
||||
::radtest::fail(__FILE__, __LINE__, "cut at " + std::to_string(k) + ": " +
|
||||
quote(reply.substr(0, k)) + "\n " + show(t));
|
||||
}
|
||||
|
||||
/* A tool whose name runs into a tag that ends names is refused at admission, by name. */
|
||||
const json bad = json::parse(R"([{"type":"function","function":{"name":"a<arg_key>b"}}])");
|
||||
ReplyOptions ro;
|
||||
ro.tools = &bad;
|
||||
std::shared_ptr<const ReplyFormat> rf;
|
||||
std::shared_ptr<const ReplyParser> rp;
|
||||
std::string why;
|
||||
CHECK_OK(ReplyFormat::compile(g->f, &rf, &why));
|
||||
CHECK(ReplyParser::create(rf, ro, &rp, &why) < 0);
|
||||
CHECK(why.find("a<arg_key>b") != std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== cost
|
||||
*
|
||||
* The legacy path re-parses the whole reply per chunk, O(n^2). The parser's own count of what it
|
||||
@@ -1802,3 +2144,4 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) {
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
|
||||
@@ -128,6 +128,20 @@ TEST(the_metadata_names_the_architecture_and_the_quantisation) {
|
||||
CHECK_EQ(ck.dir(), dir);
|
||||
}
|
||||
|
||||
TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) {
|
||||
const std::string dir = write_checkpoint({ bf16("x", {2, 2}, 0) },
|
||||
"{\"model_type\":\"glm5_next\",\"text_config\":{\"hidden_size\":4096,"
|
||||
"\"num_attention_heads\":64,\"head_dim\":0,\"n_routed_experts\":288,"
|
||||
"\"n_shared_experts\":1,\"num_experts_per_tok\":8}}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK_EQ(ck.meta().arch, std::string("glm5next"));
|
||||
CHECK_EQ(ck.meta().m.n_expert, (int64_t)288);
|
||||
CHECK_EQ(ck.meta().m.n_expert_shared, (int64_t)1);
|
||||
CHECK_EQ(ck.meta().m.n_expert_used, (int64_t)8);
|
||||
CHECK_EQ(ck.meta().m.head_dim, (int64_t)0);
|
||||
}
|
||||
|
||||
/* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's
|
||||
* --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin,
|
||||
* so the container never names one format and selects another's plugin. */
|
||||
@@ -166,6 +180,78 @@ TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) {
|
||||
CHECK_EQ(std::memcmp(raw.data(), (const uint8_t*)ck.find("a.weight")->data + 32, 16), 0);
|
||||
}
|
||||
|
||||
/* A single-file SDXL checkpoint (Stability's sgm layout) is read under the names its adapters use:
|
||||
* the UNet and CLIP ViT-L as they are, OpenCLIP bigG in transformers' names with its fused
|
||||
* in_proj split into q/k/v rows and its (in, out) text_projection transposed, the VAE decoder in
|
||||
* diffusers' names with up blocks counted the other way, a v_pred marker as the prediction type,
|
||||
* and bigG's dimensions as the model's. */
|
||||
TEST(a_single_file_sdxl_checkpoint_is_read_in_its_adapters_names) {
|
||||
const std::string g = "conditioner.embedders.1.model.";
|
||||
T proj{ g + "text_projection", "F32", { 2, 3 }, {} };
|
||||
proj.bytes.resize(6 * 4);
|
||||
for (int i = 0; i < 6; ++i) rad_store_f32(proj.bytes.data(), RAD_F32, i, (float)i);
|
||||
const std::string dir = fresh_dir();
|
||||
const std::string file = dir + "/sdxl.safetensors";
|
||||
write_shard(file, {
|
||||
bf16("model.diffusion_model.label_emb.0.0.weight", { 2, 4 }, 1.0f),
|
||||
bf16("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight", { 4 }, 2.0f),
|
||||
bf16(g + "transformer.resblocks.3.attn.in_proj_weight", { 6, 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.3.attn.in_proj_bias", { 6 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.3.mlp.c_fc.weight", { 8, 4 }, 3.0f),
|
||||
bf16(g + "transformer.resblocks.3.ln_2.bias", { 4 }, 4.0f),
|
||||
bf16(g + "ln_final.weight", { 4 }, 5.0f),
|
||||
bf16(g + "token_embedding.weight", { 16, 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.0.ln_1.weight", { 4 }, 0.0f),
|
||||
bf16(g + "transformer.resblocks.0.mlp.c_fc.weight", { 8, 4 }, 0.0f),
|
||||
bf16(g + "positional_embedding", { 77, 4 }, 6.0f),
|
||||
proj,
|
||||
bf16("first_stage_model.decoder.up.0.block.2.nin_shortcut.weight", { 4, 8, 1, 1 }, 7.0f),
|
||||
bf16("first_stage_model.decoder.up.3.upsample.conv.bias", { 4 }, 8.0f),
|
||||
bf16("first_stage_model.decoder.mid.attn_1.proj_out.weight", { 4, 4, 1, 1 }, 9.0f),
|
||||
bf16("first_stage_model.encoder.conv_in.weight", { 4, 3, 3, 3 }, 10.0f),
|
||||
T{ "v_pred", "F32", { 0 }, {} },
|
||||
});
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(file), RAD_OK);
|
||||
CHECK_EQ(ck.meta().arch, std::string("sdxl"));
|
||||
REQUIRE(ck.meta().get("sdxl.prediction") != nullptr);
|
||||
CHECK_EQ(std::string(ck.meta().get("sdxl.prediction")), std::string("v"));
|
||||
/* The typed dimensions are bigG's: its width, vocabulary and feed-forward off its tensors,
|
||||
* its layers counted from 0 while they run on. */
|
||||
CHECK_EQ(ck.meta().m.n_embd, (int64_t)4);
|
||||
CHECK_EQ(ck.meta().m.n_vocab, (int64_t)16);
|
||||
CHECK_EQ(ck.meta().m.n_ff, (int64_t)8);
|
||||
CHECK_EQ(ck.meta().m.n_layers, (int64_t)1);
|
||||
CHECK(ck.find("model.diffusion_model.label_emb.0.0.weight") != nullptr);
|
||||
CHECK(ck.find("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight") != nullptr);
|
||||
const std::string t = "conditioner.embedders.1.transformer.";
|
||||
const std::string l = t + "text_model.encoder.layers.3.";
|
||||
const SrcTensor* q = ck.find(l + "self_attn.q_proj.weight");
|
||||
const SrcTensor* v = ck.find(l + "self_attn.v_proj.weight");
|
||||
const SrcTensor* vb = ck.find(l + "self_attn.v_proj.bias");
|
||||
REQUIRE(q && v && vb);
|
||||
CHECK(q->shape == std::vector<int64_t>({ 2, 4 }));
|
||||
/* v is rows 4..5 of in_proj: elements 16..23, each its index (mod 64) in bf16. */
|
||||
CHECK_EQ(rad_load_f32(v->data, RAD_BF16, 0), 16.0f);
|
||||
CHECK_EQ(rad_load_f32(vb->data, RAD_BF16, 1), 5.0f);
|
||||
CHECK(ck.find(g + "transformer.resblocks.3.attn.in_proj_weight") == nullptr);
|
||||
CHECK(ck.find(l + "mlp.fc1.weight") != nullptr);
|
||||
CHECK(ck.find(l + "layer_norm2.bias") != nullptr);
|
||||
CHECK(ck.find(t + "text_model.final_layer_norm.weight") != nullptr);
|
||||
CHECK(ck.find(t + "text_model.embeddings.position_embedding.weight") != nullptr);
|
||||
const SrcTensor* p = ck.find(t + "text_projection.weight");
|
||||
REQUIRE(p != nullptr);
|
||||
CHECK(p->shape == std::vector<int64_t>({ 3, 2 }));
|
||||
/* P^T: element (j, i) is P(i, j) = 3 i + j. */
|
||||
for (int j = 0; j < 3; ++j)
|
||||
for (int i = 0; i < 2; ++i)
|
||||
CHECK_EQ(rad_load_f32(p->data, RAD_F32, j * 2 + i), (float)(3 * i + j));
|
||||
CHECK(ck.find("vae.decoder.up_blocks.3.resnets.2.conv_shortcut.weight") != nullptr);
|
||||
CHECK(ck.find("vae.decoder.up_blocks.0.upsamplers.0.conv.bias") != nullptr);
|
||||
CHECK(ck.find("vae.decoder.mid_block.attentions.0.to_out.0.weight") != nullptr);
|
||||
CHECK(ck.find("first_stage_model.encoder.conv_in.weight") != nullptr);
|
||||
}
|
||||
|
||||
/* Block-scaled FP8 is one weight of two planes; each value is its code times the scale of the
|
||||
* block containing it along both axes. */
|
||||
TEST(block_fp8_is_the_codes_and_their_scale_plane) {
|
||||
@@ -613,6 +699,75 @@ TEST(a_quark_mxfp4_weight_is_its_codes_and_exponents) {
|
||||
CHECK(w.trivial && rad_enc_is(&w.enc, "plain"));
|
||||
}
|
||||
|
||||
/* GLM-5.3-Flash's Quark export keeps excluded attention and MTP weights block-FP8, with F32
|
||||
* `_scale` companions. They multiply the codes; reading the global MXFP4 scheme into these
|
||||
* weights, or overlooking the scale because it is not called `_scale_inv`, corrupts the model. */
|
||||
TEST(quark_refuses_unsupported_or_incomplete_layer_weight_overrides) {
|
||||
for (const char* override_config : {
|
||||
"{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\",\"qscheme\":\"per_block\",\"block_size\":[64,128]}}}",
|
||||
"{\"p\":{\"weight\":{\"dtype\":\"int8\",\"qscheme\":\"per_block\",\"block_size\":[128,128]}}}",
|
||||
"{\"p\":{\"weight\":null}}",
|
||||
"{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\",\"qscheme\":\"per_block\",\"block_size\":[128,128]}},"
|
||||
"\"other\":{\"weight\":{\"qscheme\":\"per_block\"}}}" }) {
|
||||
const std::string config = std::string("{\"quantization_config\":{\"quant_method\":\"quark\","
|
||||
"\"global_quant_config\":{\"weight\":{\"dtype\":\"fp4\",\"qscheme\":\"per_group\","
|
||||
"\"group_size\":32,\"scale_format\":\"e8m0\"}},\"layer_quant_config\":") +
|
||||
override_config + "}}";
|
||||
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, config.c_str());
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
CHECK(ck.imports() != Checkpoint::Import::QuarkMx);
|
||||
CHECK(!ck.import_refusal().empty());
|
||||
}
|
||||
}
|
||||
|
||||
TEST(a_quark_checkpoint_preserves_excluded_block_fp8_weights) {
|
||||
T s{ "p.weight_scale", "F32", { 2, 2 }, std::vector<uint8_t>(4 * sizeof(float)) };
|
||||
for (int i = 0; i < 4; ++i) rad_store_f32(s.bytes.data(), RAD_F32, i, 0.25f * (i + 1));
|
||||
T bad = s;
|
||||
bad.name = "bad.weight_scale";
|
||||
bad.shape = { 1, 4 }; /* same number of scales, wrong block geometry */
|
||||
const std::string dir = write_checkpoint(
|
||||
{ fp8("p.weight", { 256, 256 }), s, fp8("bad.weight", { 256, 256 }), bad,
|
||||
bf16("norm.weight", { 4 }, 1.0f) },
|
||||
"{\"model_type\":\"glm5_next\",\"quantization_config\":{\"quant_method\":\"quark\","
|
||||
"\"global_quant_config\":{\"weight\":{\"dtype\":\"fp4\",\"qscheme\":\"per_group\","
|
||||
"\"group_size\":32,\"scale_format\":\"e8m0\"}},"
|
||||
"\"layer_quant_config\":{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\","
|
||||
"\"qscheme\":\"per_block\",\"block_size\":[128,128]}}}}}");
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
REQUIRE(ck.imports() == Checkpoint::Import::QuarkMx);
|
||||
Program prog;
|
||||
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
|
||||
prog.name_map.push_back(map("bad", RAD_MAP_COPY, { "bad.weight" }));
|
||||
prog.name_map.push_back(map("norm", RAD_MAP_COPY, { "norm.weight" }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
REQUIRE(w.trivial);
|
||||
REQUIRE_EQ(w.enc.n_planes, 2);
|
||||
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_F8E4M3);
|
||||
CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_F32);
|
||||
CHECK_EQ(w.enc.plane[1].block[0], (int64_t)128);
|
||||
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)128);
|
||||
std::vector<float> f(256);
|
||||
for (int64_t r : { (int64_t)0, (int64_t)129 }) {
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, r, 1, f.data(), &why), RAD_OK);
|
||||
for (int64_t c : { (int64_t)0, (int64_t)127, (int64_t)128, (int64_t)255 })
|
||||
CHECK_EQ(f[(size_t)c], ((float)((r * 256 + c) % 7) - 3.0f) *
|
||||
(0.25f * (float)(r / 128 * 2 + c / 128 + 1)));
|
||||
}
|
||||
std::vector<uint8_t> scales(s.bytes.size());
|
||||
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 2, scales.data(), &why), RAD_OK);
|
||||
CHECK_EQ(std::memcmp(scales.data(), s.bytes.data(), scales.size()), 0);
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "bad", false, &w, &why), RAD_OK);
|
||||
CHECK(!w.trivial);
|
||||
CHECK(w.why.find("scale plane") != std::string::npos);
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "norm", false, &w, &why), RAD_OK);
|
||||
CHECK(w.trivial && rad_enc_is(&w.enc, "plain"));
|
||||
}
|
||||
|
||||
/* A directory merging two checkpoints (a finetune's changed tensors beside links to every base
|
||||
* shard) holds some tensors in two shards. The index decides which copy is read; a name in two
|
||||
* shards that the index does not settle is refused, not read from whichever shard sorts first. */
|
||||
@@ -2652,4 +2807,82 @@ TEST(a_companion_folder_is_read_under_its_name) {
|
||||
CHECK_EQ(mget("codec.decoder_config.dim"), std::string("7"));
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A RAD_MAP_ROWS or RAD_MAP_COLS map: source k starts at index[k] and spans rows[k]. */
|
||||
RadNameMap ranged(const char* declared, int mode, std::vector<const char*> src,
|
||||
std::vector<int> index, std::vector<int64_t> rows) {
|
||||
RadNameMap m = map(declared, mode, std::move(src), std::move(index));
|
||||
for (size_t i = 0; i < rows.size(); ++i) m.src_rows[i] = rows[i];
|
||||
return m;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A column range of the last dimension, in every leading slice; a range past the end is
|
||||
* refused. */
|
||||
TEST(a_column_range_is_those_columns_of_every_row) {
|
||||
const std::string dir = write_checkpoint({ bf16("x.weight", { 3, 5 }, 0.0f) }, kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(ranged("xc", RAD_MAP_COLS, { "x.weight" }, { 1 }, { 3 }));
|
||||
prog.name_map.push_back(ranged("far", RAD_MAP_COLS, { "x.weight" }, { 3 }, { 3 }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "xc", false, &w, &why), RAD_OK);
|
||||
CHECK(!w.trivial);
|
||||
REQUIRE_EQ(w.rank, (uint32_t)2);
|
||||
CHECK_EQ(w.shape[0], (int64_t)3);
|
||||
CHECK_EQ(w.shape[1], (int64_t)3);
|
||||
std::vector<float> f(9);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK);
|
||||
for (int r = 0; r < 3; ++r)
|
||||
for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(r * 5 + 1 + c));
|
||||
CHECK_EQ(ckpt_resolve(ck, prog, "far", false, &w, &why), (int)RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* Row pieces declared over several maps of one name join in declaration order, so a permutation
|
||||
* of a weight's rows can be stated one row at a time. */
|
||||
TEST(row_pieces_over_several_maps_join_in_order) {
|
||||
const std::string dir = write_checkpoint({ bf16("w", { 4, 3 }, 0.0f) }, kConfig);
|
||||
Checkpoint ck;
|
||||
REQUIRE_EQ(ck.open(dir), RAD_OK);
|
||||
Program prog;
|
||||
prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w" }, { 2 }, { 1 }));
|
||||
prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w", "w" }, { 0, 3 }, { 1, 1 }));
|
||||
CkptWeight w;
|
||||
std::string why;
|
||||
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
|
||||
CHECK_EQ(w.shape[0], (int64_t)3);
|
||||
CHECK_EQ(w.shape[1], (int64_t)3);
|
||||
std::vector<float> f(9);
|
||||
REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK);
|
||||
const int order[3] = { 2, 0, 3 };
|
||||
for (int r = 0; r < 3; ++r)
|
||||
for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(order[r] * 3 + c));
|
||||
}
|
||||
|
||||
/* A release split into single files merges them under their own names; a name two files share
|
||||
* is refused. The metadata and tokenizer come from the directory set before open(). */
|
||||
TEST(single_files_merge_by_name_and_read_their_metadata_elsewhere) {
|
||||
const std::string dir = fresh_dir();
|
||||
write_shard(dir + "/dit.safetensors", { bf16("net.a", { 2, 2 }, 1.0f) });
|
||||
write_shard(dir + "/te.safetensors", { bf16("model.b", { 2, 2 }, 2.0f) });
|
||||
write_shard(dir + "/dup.safetensors", { bf16("net.a", { 2, 2 }, 3.0f) });
|
||||
const std::string meta = fresh_dir();
|
||||
write_file(meta + "/config.json", "{\"model_type\":\"qwen3\",\"hidden_size\":64}");
|
||||
write_file(meta + "/tokenizer.json", "{}");
|
||||
Checkpoint ck;
|
||||
ck.set_meta_dir(meta);
|
||||
REQUIRE_EQ(ck.open(dir + "/dit.safetensors"), RAD_OK);
|
||||
REQUIRE_EQ(ck.add_file(dir + "/te.safetensors"), RAD_OK);
|
||||
CHECK(ck.find("net.a") != nullptr);
|
||||
CHECK(ck.find("model.b") != nullptr);
|
||||
CHECK(ck.add_file(dir + "/dup.safetensors") < 0);
|
||||
const char* mt = ck.meta().get("model_type");
|
||||
CHECK_EQ(std::string(mt ? mt : ""), std::string("qwen3"));
|
||||
CHECK_EQ(ck.tok_dir(), meta);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+46
-6
@@ -22,6 +22,7 @@
|
||||
#include <sstream>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
@@ -129,7 +130,8 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
|
||||
|
||||
/* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a
|
||||
* combination that would size slots no adapter uses, or name an adapter that is not served, is
|
||||
* refused by name. */
|
||||
* refused by name. A text model's slot count against its adapters, and its targets, are checked
|
||||
* at startup, where the engine knows whether the model generates text. */
|
||||
TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
Config c;
|
||||
CHECK_OK(parse({ "--lora", "b=/ad/b", "--lora", "a=/ad/a", "--max-loras", "3",
|
||||
@@ -144,6 +146,15 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
Config d;
|
||||
CHECK_OK(parse({}, &d));
|
||||
CHECK(!d.lora.enabled());
|
||||
CHECK_EQ(d.lora.rank(false), 16);
|
||||
CHECK_EQ(d.lora.rank(true), 64);
|
||||
Config e;
|
||||
const std::string dir = radtest::tmp_path("loradir");
|
||||
mkdir(dir.c_str(), 0755);
|
||||
CHECK_OK(parse({ "--lora-dir", dir.c_str() }, &e));
|
||||
CHECK(e.lora.enabled());
|
||||
CHECK_EQ(e.lora.slots(), 2);
|
||||
CHECK_EQ(e.lora.rank(true), 64);
|
||||
|
||||
auto refused = [](std::initializer_list<const char*> v, const char* why) {
|
||||
int st = RAD_OK;
|
||||
@@ -157,10 +168,9 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) {
|
||||
refused({ "--lora", "/ad/a" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=" }, "NAME=PATH");
|
||||
refused({ "--lora", "a=/x", "--lora", "a=/y" }, "names the adapter 'a' twice");
|
||||
refused({ "--lora", "a=/x", "--lora", "b=/y", "--max-loras", "1" }, "fewer adapters");
|
||||
refused({ "--max-lora-rank", "32" }, "--max-lora-rank sizes runtime LoRA slots");
|
||||
refused({ "--lora-target-modules", "q_proj" }, "--lora-target-modules sizes");
|
||||
refused({ "--max-loras", "2" }, "names no module an adapter may target");
|
||||
refused({ "--lora-dir", "/no/such/dir" }, "is not a directory");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", "self_attn.q_proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", ".*proj" }, "leaf names");
|
||||
refused({ "--lora", "a=/x", "--lora-target-modules", " , " }, "names no module");
|
||||
@@ -417,7 +427,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--max-num-seqs", { "4" } },
|
||||
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
|
||||
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
|
||||
{ "--host-pool-mib", { "1024" } }, { "--embedding-placement", { "vram" } },
|
||||
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
|
||||
{ "--embedding-placement", { "vram" } },
|
||||
{ "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } },
|
||||
{ "--prefix-cache-mib", { "256" } }, { "--prefix-cache-ttl", { "60" } },
|
||||
{ "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } },
|
||||
@@ -426,6 +437,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } },
|
||||
{ "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } },
|
||||
{ "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } },
|
||||
{ "--control-vector", { "off" } },
|
||||
{ "--generation-config", { "/g.json" } }, { "--override-chat-template", { "/t.jinja" } },
|
||||
{ "--temp", { "0.7" } }, { "--top-k", { "40" } }, { "--top-p", { "0.9" } },
|
||||
{ "--min-p", { "0.05" } }, { "--reasoning-effort", { "low" } },
|
||||
@@ -453,6 +465,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
|
||||
{ "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } },
|
||||
{ "--kld-out", { "/o.json", "--kld-ref", "/r" } },
|
||||
{ "--lora", { "a=/adapters/a" } },
|
||||
{ "--lora-dir", { "/" } },
|
||||
{ "--max-loras", { "2", "--lora-target-modules", "q_proj" } },
|
||||
{ "--max-lora-rank", { "32", "--lora", "a=/adapters/a" } },
|
||||
{ "--lora-target-modules", { "q_proj,v_proj", "--max-loras", "1" } },
|
||||
@@ -591,6 +604,28 @@ TEST(the_placement_is_one_of_the_planners_four) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Three states, and the absent one is the zero-cost default: off and on load the module, disabled --
|
||||
* or no flag -- does not, so no projection op is declared. */
|
||||
TEST(the_control_vector_flag_is_off_on_or_disabled) {
|
||||
for (const char* ok : { "off", "on", "disabled" }) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--control-vector", ok }, &c), RAD_OK);
|
||||
CHECK_EQ(c.control_vector, std::string(ok));
|
||||
}
|
||||
{
|
||||
Config c;
|
||||
CHECK_EQ(parse({}, &c), RAD_OK);
|
||||
CHECK_EQ(c.control_vector, std::string("disabled"));
|
||||
}
|
||||
for (const char* bad : { "auto", "OFF", "", "1", "true" }) {
|
||||
Config c;
|
||||
int st = RAD_OK;
|
||||
const std::string log = stderr_of([&] { st = parse({ "--control-vector", bad }, &c); });
|
||||
CHECK_EQ(st, (int)RAD_E_INVAL);
|
||||
CHECK(has(log, "--control-vector"));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_wire_mode_is_one_of_two_names) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--tp-wire", "exact" }, &c), RAD_OK);
|
||||
@@ -620,16 +655,21 @@ TEST(the_p2p_mode_is_one_of_three_names) {
|
||||
CHECK_EQ(parse({ "--p2p", "OFF" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_kv_cache_dtype_is_one_of_two_names) {
|
||||
TEST(the_kv_cache_dtype_is_one_of_four_names) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("bf16"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp8" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("fp8"));
|
||||
/* Two values only: an "auto" resolving to bf16 would be a second name for the default, and
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp8_v4" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("fp8_v4"));
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "k6_v4" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.kv_cache_dtype, std::string("k6_v4"));
|
||||
/* Four values only: an "auto" resolving to bf16 would be a second name for the default, and
|
||||
* each value should be unambiguous in a log. */
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "auto" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "fp16" }, &c), RAD_E_INVAL);
|
||||
CHECK_EQ(parse({ "--kv-cache-dtype", "v4" }, &c), RAD_E_INVAL);
|
||||
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
/* cvec_test.cpp -- the control vector's loader (core/cvec.h).
|
||||
*
|
||||
* The vector is the published package's format: a GGUF `controlvector` with one unit f32
|
||||
* `direction.<l>` per layer and three metadata keys. These cases write such a file, then check
|
||||
* both what the loader accepts and, just as important, what it refuses: a vector from another
|
||||
* architecture, one of the wrong width, and a layer range with a gap must stop startup rather than
|
||||
* steer a model along a direction that does not describe its residual stream.
|
||||
*
|
||||
* The compatibility question the port turns on is answered here rather than assumed: the file's
|
||||
* directions are 2560 wide and a Flash-Next container's stream is 2560, and the file states
|
||||
* `qwen4exp` as its architecture hint.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "cvec.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
/* A minimal GGUF writer, just enough for a control vector: the header, a string/int KV table, one
|
||||
* F32 one-dimensional tensor per direction, and the data blob at the file's alignment. */
|
||||
struct GgufWriter {
|
||||
struct T { std::string name; std::vector<float> data; };
|
||||
std::vector<std::pair<std::string, std::string>> strs;
|
||||
std::vector<std::pair<std::string, int32_t>> ints;
|
||||
std::vector<T> tensors;
|
||||
|
||||
static void u32(std::string& out, uint32_t v) {
|
||||
for (int i = 0; i < 4; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff));
|
||||
}
|
||||
static void u64(std::string& out, uint64_t v) {
|
||||
for (int i = 0; i < 8; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff));
|
||||
}
|
||||
static void str(std::string& out, const std::string& s) {
|
||||
u64(out, s.size());
|
||||
out += s;
|
||||
}
|
||||
|
||||
void write(const std::string& path, uint64_t alignment = 32) const {
|
||||
std::string h;
|
||||
h += "GGUF";
|
||||
u32(h, 3);
|
||||
u64(h, tensors.size());
|
||||
u64(h, strs.size() + ints.size() + 1); /* + general.alignment */
|
||||
for (const auto& [k, v] : strs) {
|
||||
str(h, k);
|
||||
u32(h, 8); /* GGUF_STR */
|
||||
str(h, v);
|
||||
}
|
||||
for (const auto& [k, v] : ints) {
|
||||
str(h, k);
|
||||
u32(h, 5); /* GGUF_I32 */
|
||||
u32(h, (uint32_t) v);
|
||||
}
|
||||
str(h, "general.alignment");
|
||||
u32(h, 4); /* GGUF_U32 */
|
||||
u32(h, (uint32_t) alignment);
|
||||
|
||||
uint64_t off = 0;
|
||||
std::string dir;
|
||||
for (const T& t : tensors) {
|
||||
str(dir, t.name);
|
||||
u32(dir, 1); /* n_dims */
|
||||
u64(dir, (uint64_t) t.data.size()); /* ne[0] */
|
||||
u32(dir, 0); /* ggml type 0 = F32 */
|
||||
const uint64_t padded = t.data.size() * 4;
|
||||
u64(dir, off);
|
||||
off += (padded + alignment - 1) / alignment * alignment;
|
||||
}
|
||||
h += dir;
|
||||
while (h.size() % alignment) h.push_back('\0');
|
||||
for (const T& t : tensors) {
|
||||
h.append((const char*) t.data.data(), t.data.size() * 4);
|
||||
while (h.size() % alignment) h.push_back('\0');
|
||||
}
|
||||
std::ofstream f(path, std::ios::binary | std::ios::trunc);
|
||||
f.write(h.data(), (std::streamsize) h.size());
|
||||
}
|
||||
};
|
||||
|
||||
/* A vector with the published package's shape: `layers` directions of `n` values, each a unit
|
||||
* vector, plus the metadata its header carries. */
|
||||
GgufWriter make_vector(int64_t n, int layers, const char* arch = "controlvector",
|
||||
const char* hint = "qwen4exp") {
|
||||
GgufWriter w;
|
||||
w.strs.push_back({ "general.architecture", arch });
|
||||
w.strs.push_back({ "controlvector.model_hint", hint });
|
||||
w.ints.push_back({ "controlvector.layer_count", (int32_t) layers });
|
||||
for (int l = 1; l <= layers; ++l) {
|
||||
std::vector<float> d((size_t) n);
|
||||
for (int64_t i = 0; i < n; ++i) d[(size_t) i] = (float) std::sin(0.001 * (double) (l + 1) *
|
||||
(double) i + 0.1 * l);
|
||||
double ss = 0.0;
|
||||
for (float v : d) ss += (double) v * v;
|
||||
const float inv = (float) (1.0 / std::sqrt(ss));
|
||||
for (float& v : d) v *= inv;
|
||||
w.tensors.push_back({ "direction." + std::to_string(l), std::move(d) });
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
struct Loaded {
|
||||
rad::ControlVector cv;
|
||||
std::string err;
|
||||
int rc = 0;
|
||||
};
|
||||
|
||||
/* A vector file, optionally with the package's JSON beside it (which is where the operation's
|
||||
* parameters live: there is no flag for them). */
|
||||
Loaded load(const GgufWriter& w, int64_t n_embd, int64_t model_layers, const std::string& leaf,
|
||||
const std::string& json = std::string()) {
|
||||
const std::string path = radtest::tmp_path(leaf);
|
||||
w.write(path);
|
||||
if (!json.empty()) {
|
||||
const std::string side = path.substr(0, path.find_last_of('.')) + ".json";
|
||||
std::ofstream f(side, std::ios::binary | std::ios::trunc);
|
||||
f << json;
|
||||
}
|
||||
Loaded out;
|
||||
out.rc = rad::control_vector_load(path, "qwen4exp", n_embd, model_layers, &out.cv, &out.err);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(the_published_shape_loads_and_is_normalised) {
|
||||
/* 47 directions of 2560 for a 48-layer model, and no JSON beside it: the loader takes the
|
||||
* published selection, 4..44. */
|
||||
const Loaded f = load(make_vector(2560, 47), 2560, 48, "flash-next.gguf");
|
||||
CHECK_OK(f.rc);
|
||||
CHECK_EQ(f.cv.n_embd, (int64_t) 2560);
|
||||
CHECK_EQ(f.cv.first, 4);
|
||||
CHECK_EQ(f.cv.last, 44);
|
||||
/* Indexed by layer, so row 0 exists (the format has no direction for it) and 47 rows follow. */
|
||||
CHECK_EQ(f.cv.n_layers, (int64_t) 48);
|
||||
CHECK_EQ(f.cv.n_dirs, (int64_t) 47);
|
||||
|
||||
for (int l = 1; l <= 47; ++l) {
|
||||
double ss = 0.0;
|
||||
for (int64_t i = 0; i < 2560; ++i)
|
||||
ss += (double) f.cv.dir[(size_t) (l * 2560 + i)] *
|
||||
(double) f.cv.dir[(size_t) (l * 2560 + i)];
|
||||
CHECK_NEAR(std::sqrt(ss), 1.0, 1e-5);
|
||||
/* Unit rows, so the stored norm -- what llama.cpp keeps as `scales[il]` -- is 1 where the
|
||||
* range steers, and 0 outside it: the plugin declares an op exactly where it is nonzero. */
|
||||
CHECK_NEAR(f.cv.scales[(size_t) l], (l >= 4 && l <= 44) ? 1.0f : 0.0f, 1e-5);
|
||||
}
|
||||
/* Outside the range nothing is steered: no op, and the scale says so too. */
|
||||
CHECK_EQ(f.cv.covers(3), false);
|
||||
CHECK_EQ(f.cv.covers(4), true);
|
||||
CHECK_EQ(f.cv.covers(44), true);
|
||||
CHECK_EQ(f.cv.covers(45), false);
|
||||
|
||||
/* The cache partition: nonzero with a vector loaded, and stable across loads of one file. */
|
||||
const Loaded again = load(make_vector(2560, 47), 2560, 48, "flash-next-2.gguf");
|
||||
CHECK_OK(again.rc);
|
||||
CHECK(rad::control_vector_salt(f.cv) != 0);
|
||||
CHECK_EQ(rad::control_vector_salt(f.cv), rad::control_vector_salt(again.cv));
|
||||
}
|
||||
|
||||
TEST(a_vector_for_another_architecture_is_refused) {
|
||||
/* A direction inferred from another model's residual basis is noise here. The hint is the one
|
||||
* place the file names its architecture, so it is checked when present. */
|
||||
const Loaded l = load(make_vector(2560, 47, "controlvector", "gemma4"), 2560, 48,
|
||||
"wrong-arch.gguf");
|
||||
CHECK(l.rc < 0);
|
||||
CHECK(l.err.find("gemma4") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(a_vector_of_the_wrong_width_is_refused) {
|
||||
/* 2048-wide directions in a 2560-wide model: the kernel would read past the row. */
|
||||
const Loaded l = load(make_vector(2048, 47), 2560, 48, "wrong-width.gguf");
|
||||
CHECK(l.rc < 0);
|
||||
CHECK(l.err.find("2560") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(a_layer_range_with_a_gap_is_refused) {
|
||||
/* A vector with no direction for layer 30 while the range covers it would serve a model that
|
||||
* is silently unsteered on that layer -- a different model from the one the file describes. */
|
||||
GgufWriter w = make_vector(2560, 47);
|
||||
std::vector<GgufWriter::T> kept;
|
||||
for (auto& t : w.tensors)
|
||||
if (t.name != "direction.30") kept.push_back(t);
|
||||
w.tensors = std::move(kept);
|
||||
const Loaded l = load(w, 2560, 48, "gap.gguf");
|
||||
CHECK(l.rc < 0);
|
||||
CHECK(l.err.find("30") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(not_a_control_vector_is_refused) {
|
||||
const Loaded l = load(make_vector(2560, 47, "qwen4exp", "qwen4exp"), 2560, 48,
|
||||
"wrong-kind.gguf");
|
||||
CHECK(l.rc < 0);
|
||||
CHECK(l.err.find("controlvector") != std::string::npos);
|
||||
}
|
||||
|
||||
/* The operation's parameters come from the package's own JSON, not a command line: the published
|
||||
* Flash-Next vector ships {"mode":"project","scale":1.0,"layer_range":[4,44]}. A JSON that states a
|
||||
* different range or scale is honoured; one that says another mode, or is malformed, only means the
|
||||
* defaults (the vector itself is still valid). */
|
||||
TEST(the_packages_json_sets_the_range_and_scale) {
|
||||
const Loaded a = load(make_vector(2560, 47), 2560, 48, "json-range.gguf",
|
||||
R"({"mode":"project","scale":0.5,"layer_range":[8,20]})");
|
||||
CHECK_OK(a.rc);
|
||||
CHECK_EQ(a.cv.first, 8);
|
||||
CHECK_EQ(a.cv.last, 20);
|
||||
CHECK_NEAR(a.cv.scales[(size_t) 8], 0.5f, 1e-5);
|
||||
CHECK_EQ(a.cv.covers(7), false);
|
||||
CHECK_EQ(a.cv.covers(21), false);
|
||||
CHECK_EQ(a.cv.scales[(size_t) 7], 0.0f);
|
||||
CHECK_EQ(a.cv.scales[(size_t) 21], 0.0f);
|
||||
|
||||
/* Another mode is not implemented: the file's directions still load, with the defaults. */
|
||||
const Loaded b = load(make_vector(2560, 47), 2560, 48, "json-add.gguf",
|
||||
R"({"mode":"add","scale":0.1,"layer_range":[16,32]})");
|
||||
CHECK_OK(b.rc);
|
||||
CHECK_EQ(b.cv.first, 4);
|
||||
CHECK_EQ(b.cv.last, 44);
|
||||
CHECK_NEAR(b.cv.user_scale, 1.0f, 1e-6);
|
||||
|
||||
/* Malformed JSON is reported, not fatal. */
|
||||
const Loaded c = load(make_vector(2560, 47), 2560, 48, "json-broken.gguf", "{ not json");
|
||||
CHECK_OK(c.rc);
|
||||
CHECK_EQ(c.cv.first, 4);
|
||||
}
|
||||
|
||||
TEST(a_unit_vector_gives_scale_one_at_every_steered_layer) {
|
||||
const std::string path = radtest::tmp_path("scaled.gguf");
|
||||
make_vector(2560, 47).write(path);
|
||||
rad::ControlVector cv;
|
||||
std::string why;
|
||||
CHECK_OK(rad::control_vector_load(path, "qwen4exp", 2560, 48, &cv, &why));
|
||||
CHECK_NEAR(cv.scales[(size_t) 4], 1.0f, 1e-5);
|
||||
CHECK_NEAR(cv.scales[(size_t) 44], 1.0f, 1e-5);
|
||||
}
|
||||
|
||||
/* Discovery is the branch's policy -- a file beside the model makes the capability available -- so
|
||||
* the order it searches in is part of the contract: the container's sidecar, then its directory,
|
||||
* then each `$RADIANCE_HOME/vectors`, with an empty file skipped rather than reported as found. */
|
||||
TEST(discovery_finds_the_sidecar_then_the_directory_then_the_home) {
|
||||
const std::string dir = radtest::tmpdir();
|
||||
const std::string model = dir + "/model.gguf";
|
||||
const std::string home = dir + "/home";
|
||||
const std::string hvec = home + "/vectors/qwen4exp-control-vector.gguf";
|
||||
std::string found, tried;
|
||||
|
||||
/* Nothing anywhere: no answer, and the candidates are named for the log line. */
|
||||
CHECK_OK(rad::control_vector_discover(model, "qwen4exp", home, &found, &tried));
|
||||
CHECK(found.empty());
|
||||
CHECK(tried.find(dir + "/model.control-vector.gguf") != std::string::npos);
|
||||
|
||||
/* A home's vectors/ entry is the last candidate, and an empty file there is not a vector (the
|
||||
* loader would refuse it), so discovery keeps looking rather than reporting it. */
|
||||
std::filesystem::create_directories(home + "/vectors");
|
||||
std::ofstream(hvec, std::ios::binary).close();
|
||||
CHECK_OK(rad::control_vector_discover(model, "qwen4exp", home, &found, &tried));
|
||||
CHECK(found.empty());
|
||||
make_vector(2560, 47).write(hvec);
|
||||
CHECK_OK(rad::control_vector_discover(model, "qwen4exp", home, &found, &tried));
|
||||
CHECK_EQ(found, hvec);
|
||||
|
||||
/* The container's directory beats every home; the sidecar beats the directory. */
|
||||
make_vector(2560, 47).write(dir + "/control-vector.gguf");
|
||||
CHECK_OK(rad::control_vector_discover(model, "qwen4exp", home, &found, &tried));
|
||||
CHECK_EQ(found, dir + "/control-vector.gguf");
|
||||
make_vector(2560, 47).write(dir + "/model.control-vector.gguf");
|
||||
CHECK_OK(rad::control_vector_discover(model, "qwen4exp", home, &found, &tried));
|
||||
CHECK_EQ(found, dir + "/model.control-vector.gguf");
|
||||
|
||||
/* Homes separated by `:` are searched in order: one without a vector defers to the next. */
|
||||
const std::string dir2 = dir + "/two";
|
||||
std::filesystem::create_directories(dir2 + "/vectors");
|
||||
make_vector(2560, 47).write(dir2 + "/vectors/qwen4exp-control-vector.gguf");
|
||||
CHECK_OK(rad::control_vector_discover(dir2 + "/m.gguf", "qwen4exp", dir + "/none:" + dir2,
|
||||
&found, &tried));
|
||||
CHECK_EQ(found, dir2 + "/vectors/qwen4exp-control-vector.gguf");
|
||||
}
|
||||
|
||||
/* The range is the package's, and it must lie inside the container. Twenty directions fit a
|
||||
* 32-layer model; a JSON naming 4..40 does not. */
|
||||
TEST(a_layer_range_past_the_model_is_refused) {
|
||||
const Loaded l = load(make_vector(2560, 20), 2560, 32, "range-past.gguf",
|
||||
R"({"mode":"project","scale":1.0,"layer_range":[4,40]})");
|
||||
CHECK(l.rc < 0);
|
||||
CHECK(l.err.find("runs past") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A layer index the table cannot hold: a 48-layer model's table is rows 0..47, indexed by layer, so
|
||||
* direction.48 names one row past it -- as does a JSON range ending at 48. Both are refused rather
|
||||
* than writing or reading past the table. */
|
||||
TEST(a_layer_at_the_models_own_count_is_refused) {
|
||||
const Loaded a = load(make_vector(2560, 48), 2560, 48, "layer-48.gguf");
|
||||
CHECK(a.rc < 0);
|
||||
CHECK(a.err.find("outside") != std::string::npos);
|
||||
|
||||
const Loaded b = load(make_vector(2560, 47), 2560, 48, "range-to-48.gguf",
|
||||
R"({"mode":"project","scale":1.0,"layer_range":[4,48]})");
|
||||
CHECK(b.rc < 0);
|
||||
CHECK(b.err.find("runs past") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -8,6 +8,7 @@
|
||||
* groups, where summing or picking the wrong group goes wrong silently.
|
||||
*/
|
||||
#include "server_fakes.h"
|
||||
#include "rad_internal.h" /* rad_mono_ns: a synthetic bringup start */
|
||||
|
||||
#include <set>
|
||||
|
||||
@@ -121,6 +122,8 @@ struct Dash {
|
||||
sched.m.prefix_ckpt_lru = 3;
|
||||
sched.m.hit_cut_no_snapshot = 2;
|
||||
sched.m.hit_cut_tokens = 9000;
|
||||
sched.m.hit_cut_resumed_below = 4;
|
||||
sched.m.prefix_restore_cuts = 1;
|
||||
sched.m.draft_depth_seen = 2;
|
||||
sched.m.draft_pos_reached[0] = 10; sched.m.draft_pos_accepted[0] = 8;
|
||||
sched.m.draft_pos_reached[1] = 8; sched.m.draft_pos_accepted[1] = 2;
|
||||
@@ -238,6 +241,8 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) {
|
||||
CHECK(s.value("enabled", false));
|
||||
CHECK_EQ(s["linear"]["evictions"].value("store_full", (int64_t)0), (int64_t)3);
|
||||
CHECK_EQ(s["linear"]["hit_cuts"].value("no_snapshot", (int64_t)0), (int64_t)2);
|
||||
CHECK_EQ(s["linear"]["hit_cuts"].value("resumed_below", (int64_t)0), (int64_t)4);
|
||||
CHECK_EQ(s["moved"].value("restore_cuts", (int64_t)0), (int64_t)1);
|
||||
CHECK_EQ(s["linear"].value("hit_cut_tokens", (int64_t)0), (int64_t)9000);
|
||||
}
|
||||
|
||||
@@ -246,6 +251,61 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) {
|
||||
/* Every field the page's script reads from /stats (in its update and the request table) and from
|
||||
* /sessions (its loader and the session rows) is one the routes emit for a populated engine. A
|
||||
* rename on either side otherwise blanks a panel and reports nothing. */
|
||||
/* The price of a restart, measured rather than guessed: whatever decides whether a restart is
|
||||
* worth suffering needs this figure, and a guessed cost would decide the answer by itself. The
|
||||
* page stopped consuming it on 2026-10-18, when the payback clause it fed was withdrawn -- the
|
||||
* field stays because it is the missing half of that decision made downstream, by a human or a
|
||||
* tool. A test runs in microseconds, so a real note_ready() would compute 0 -- indistinguishable
|
||||
* from "never called". Passing a synthetic start exercises the arithmetic through the real route. */
|
||||
TEST(stats_reports_how_long_bringup_took_once_the_server_listens) {
|
||||
Dash d(false);
|
||||
/* Before the server has listened, there is no measured cost to report. */
|
||||
CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)0);
|
||||
|
||||
d.srv->note_ready(rad_mono_ns() - 47ull * 1000000000ull);
|
||||
CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47);
|
||||
|
||||
/* A start in the future is not a negative cost: the figure is a duration, and a page that
|
||||
* divided by it would otherwise be handed a sign flip. */
|
||||
d.srv->note_ready(rad_mono_ns() + 10ull * 1000000000ull);
|
||||
CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47);
|
||||
|
||||
/* 0 means "not yet", so it must not overwrite a measured figure. */
|
||||
d.srv->note_ready(0);
|
||||
CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47);
|
||||
}
|
||||
|
||||
/* The pooled ring's element shape is a contract between two functions in the page, and no
|
||||
* browser runs here to notice when they disagree. accWindow pushes {ratio, dr, da}; acceptTriple
|
||||
* iterates the ring as `d` and reads `last`. When a rename left acceptTriple reading accPrev's
|
||||
* {r, a} instead, the pooled figures became NaN and the detail line froze at "recent -" while
|
||||
* every C++ test stayed green (Turnstone judge slices 08 and 11, 2026-10-20). So: scan the page
|
||||
* text and hold the two sides to the same names. */
|
||||
TEST(the_pooled_acceptance_ring_reads_the_names_accWindow_writes) {
|
||||
Dash d(false);
|
||||
const std::string p = d.srv->router().call("GET", "/").body;
|
||||
const std::string aw = function_body(p, "function accWindow(");
|
||||
const std::string at = function_body(p, "function acceptTriple(");
|
||||
REQUIRE(!aw.empty() && !at.empty());
|
||||
/* what goes INTO the ring */
|
||||
CHECK(aw.find("dr: dr") != std::string::npos);
|
||||
CHECK(aw.find("da: da") != std::string::npos);
|
||||
/* what comes OUT of it: every `d.<field>` and `last.<field>` must be a ring name */
|
||||
const std::set<std::string> ring = {"dr", "da"};
|
||||
for (const std::string& n : fields(at, "d")) {
|
||||
CHECK(ring.count(n) == 1);
|
||||
if (!ring.count(n))
|
||||
fprintf(stderr, " acceptTriple reads d.%s, which the ring does not carry\n", n.c_str());
|
||||
}
|
||||
for (const std::string& n : fields(at, "last")) {
|
||||
CHECK(ring.count(n) == 1);
|
||||
if (!ring.count(n))
|
||||
fprintf(stderr, " acceptTriple reads last.%s, which the ring does not carry\n", n.c_str());
|
||||
}
|
||||
/* and the ring must not be empty by construction: the push is gated on dr > 0 */
|
||||
CHECK(aw.find("dr <= 0") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(every_field_the_page_reads_is_one_the_routes_emit) {
|
||||
Dash d(false);
|
||||
HttpResponse page = d.srv->router().call("GET", "/");
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
[gMASK]<sop>
|
||||
{%- set effective_reasoning_effort = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%}
|
||||
{%- if effective_reasoning_effort is not none -%}<|system|>Reasoning Effort: {{ effective_reasoning_effort | capitalize }}{%- endif -%}
|
||||
{%- set clear_thinking = clear_thinking if clear_thinking is defined else false -%}
|
||||
{%- if tools -%}
|
||||
{%- macro tool_to_json(tool) -%}
|
||||
{%- set ns_tool = namespace(first=true) -%}
|
||||
{{ '{' -}}
|
||||
{%- for k, v in tool.items() -%}
|
||||
{%- if k != 'defer_loading' and k != 'strict' -%}
|
||||
{%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%}
|
||||
{%- set ns_tool.first = false -%}
|
||||
"{{ k }}": {{ v | tojson(ensure_ascii=False) }}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{- '}' -}}
|
||||
{%- endmacro -%}
|
||||
{%- macro tool_references_to_response(refs) -%}
|
||||
{{- '<tool_response><tools>\n' -}}
|
||||
{%- for tr in refs -%}
|
||||
{%- for tool in tools -%}
|
||||
{%- if 'function' in tool -%}
|
||||
{%- set tool = tool['function'] -%}
|
||||
{%- endif -%}
|
||||
{%- if tool.name == tr.name -%}
|
||||
{{- tool_to_json(tool) + '\n' -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor -%}
|
||||
{{- '</tools></tool_response>' -}}
|
||||
{%- endmacro -%}
|
||||
<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{% for tool in tools %}
|
||||
{%- if 'function' in tool -%}
|
||||
{%- set tool = tool['function'] -%}
|
||||
{%- endif -%}
|
||||
{% if tool.defer_loading is not defined or not tool.defer_loading %}
|
||||
{{ tool_to_json(tool) }}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call>{%- endif -%}
|
||||
{%- macro emit_image() -%}<|begin_of_image|><|image|><|end_of_image|>{%- endmacro -%}
|
||||
{%- macro emit_video() -%}<|begin_of_video|><|video|><|end_of_video|>{%- endmacro -%}
|
||||
{%- macro emit_audio() -%}<|begin_of_audio|><|end_of_audio|>{%- endmacro -%}
|
||||
{%- macro visible_text(content) -%}
|
||||
{%- if content is string -%}
|
||||
{{- content -}}
|
||||
{%- elif content is iterable and content is not mapping -%}
|
||||
{%- for item in content -%}
|
||||
{%- if item is mapping and item.type == 'text' -%}
|
||||
{{- item.text -}}
|
||||
{%- elif item is string -%}
|
||||
{{- item -}}
|
||||
{%- elif item is mapping and item.type in ['image', 'image_url'] -%}
|
||||
{{- emit_image() -}}
|
||||
{%- elif item is mapping and item.type in ['video', 'video_url'] -%}
|
||||
{{- emit_video() -}}
|
||||
{%- elif item is mapping and item.type in ['audio', 'audio_url', 'input_audio'] -%}
|
||||
{{- emit_audio() -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{{- content }}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro tool_response(text) -%}
|
||||
{{- '<tool_response>' + text + '</tool_response>' -}}
|
||||
{%- endmacro -%}
|
||||
{%- macro render_tool_response(m) -%}
|
||||
{%- if m.content is string -%}
|
||||
{{- tool_response(m.content) -}}
|
||||
{%- elif m.content and m.content is not mapping and m.content.0.type == "tool_reference" -%}
|
||||
{{- tool_references_to_response(m.content) -}}
|
||||
{%- elif is_list_of_outputs(m) -%}
|
||||
{%- for tr in m.content -%}
|
||||
{%- if tr.output is iterable and tr.output is not string and tr.output is not mapping and tr.output and tr.output.0.type == "tool_reference" -%}
|
||||
{{- tool_references_to_response(tr.output) -}}
|
||||
{%- else -%}
|
||||
{{- tool_response(visible_text(tr.output)) -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{{- tool_response(visible_text(m.content)) -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro id_of(obj) -%}
|
||||
{%- if obj.tool_call_id -%}
|
||||
{{- obj.tool_call_id -}}
|
||||
{%- elif obj.id -%}
|
||||
{{- obj.id -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro is_list_of_outputs(m) -%}
|
||||
{%- if m.content and m.content.0.output is defined -%}1{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro has_dup_tool_result_id(lo, hi, target) -%}
|
||||
{%- set ns_cnt = namespace(n=0) -%}
|
||||
{%- for k in range(lo, hi + 1) -%}
|
||||
{%- set m = messages[k] -%}
|
||||
{%- if is_list_of_outputs(m) -%}
|
||||
{%- for entry in m.content -%}
|
||||
{%- if id_of(entry) == target -%}
|
||||
{%- set ns_cnt.n = ns_cnt.n + 1 -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- elif id_of(m) == target -%}
|
||||
{%- set ns_cnt.n = ns_cnt.n + 1 -%}
|
||||
{%- endif -%}
|
||||
{%- if ns_cnt.n > 1 -%}{%- break -%}{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- if ns_cnt.n > 1 -%}1{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- macro tc_id_exists(tcs, target) -%}
|
||||
{%- set ns_f = namespace(found=false) -%}
|
||||
{%- for tc in tcs -%}
|
||||
{%- if id_of(tc) == target -%}
|
||||
{%- set ns_f.found = true -%}
|
||||
{%- break -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- if ns_f.found -%}1{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
{%- set ns = namespace(last_user_index=-1) -%}
|
||||
{%- for m in messages %}
|
||||
{%- if m.role == 'user' %}
|
||||
{%- set ns.last_user_index = loop.index0 -%}
|
||||
{%- endif %}
|
||||
{%- endfor %}
|
||||
{%- for m in messages -%}
|
||||
{%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}
|
||||
{%- elif m.role == 'assistant' -%}
|
||||
<|assistant|>
|
||||
{%- set content = visible_text(m.content) %}
|
||||
{%- if m.reasoning_content is string %}
|
||||
{%- set reasoning_content = m.reasoning_content %}
|
||||
{%- elif '</think>' in content %}
|
||||
{%- set reasoning_content = content.split('</think>')[0].split('<think>')[-1] %}
|
||||
{%- set content = content.split('</think>')[-1] %}
|
||||
{%- endif %}
|
||||
{%- if (not clear_thinking or loop.index0 > ns.last_user_index) and reasoning_content is defined -%}
|
||||
{{ '<think>' + reasoning_content + '</think>'}}
|
||||
{%- else -%}
|
||||
{{ '<think></think>' }}
|
||||
{%- endif -%}
|
||||
{%- if content.strip() -%}
|
||||
{{ content.strip() }}
|
||||
{%- endif -%}
|
||||
{% if m.tool_calls %}
|
||||
{% for tc in m.tool_calls %}
|
||||
{%- if tc.function %}
|
||||
{%- set tc = tc.function %}
|
||||
{%- endif %}
|
||||
{{- '<tool_call>' + tc.name -}}
|
||||
{% set _args = tc.arguments %}{% for k, v in _args.items() %}<arg_key>{{ k }}</arg_key><arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>{% endfor %}</tool_call>{% endfor %}
|
||||
{% endif %}
|
||||
{%- elif m.role == 'tool' -%}
|
||||
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
||||
{{- '<|observation|>' -}}
|
||||
{%- set block_start = loop.index0 -%}
|
||||
{%- set ns_blk = namespace(end=block_start) -%}
|
||||
{%- for j in range(block_start, messages|length) -%}
|
||||
{%- if messages[j].role == 'tool' -%}
|
||||
{%- set ns_blk.end = j -%}
|
||||
{%- else -%}
|
||||
{%- break -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- set ns_a = namespace(tool_calls=none) -%}
|
||||
{%- if block_start > 0 and messages[block_start - 1].role == 'assistant' and messages[block_start - 1].tool_calls -%}
|
||||
{%- set ns_a.tool_calls = messages[block_start - 1].tool_calls -%}
|
||||
{%- endif -%}
|
||||
{%- set ns_chk = namespace(can_sort=true) -%}
|
||||
{%- if not ns_a.tool_calls -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- else -%}
|
||||
{%- for k in range(block_start, ns_blk.end + 1) -%}
|
||||
{%- set m = messages[k] -%}
|
||||
{%- if is_list_of_outputs(m) -%}
|
||||
{%- for entry in m.content -%}
|
||||
{%- set eid = id_of(entry) -%}
|
||||
{%- if not eid -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- elif has_dup_tool_result_id(block_start, ns_blk.end, eid) -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- elif not tc_id_exists(ns_a.tool_calls, eid) -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{%- set tk_id = id_of(m) -%}
|
||||
{%- if not tk_id -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- elif has_dup_tool_result_id(block_start, ns_blk.end, tk_id) -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- elif not tc_id_exists(ns_a.tool_calls, tk_id) -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- for i in range(ns_a.tool_calls | length) -%}
|
||||
{%- set tc_id = id_of(ns_a.tool_calls[i]) -%}
|
||||
{%- if not tc_id -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- endif -%}
|
||||
{%- for j in range(i + 1, ns_a.tool_calls | length) -%}
|
||||
{%- if id_of(ns_a.tool_calls[j]) == tc_id -%}
|
||||
{%- set ns_chk.can_sort = false -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- if ns_chk.can_sort -%}
|
||||
{%- for tc in ns_a.tool_calls -%}
|
||||
{%- set tc_id = id_of(tc) -%}
|
||||
{%- for k in range(block_start, ns_blk.end + 1) -%}
|
||||
{%- set m = messages[k] -%}
|
||||
{%- if is_list_of_outputs(m) -%}
|
||||
{%- for entry in m.content -%}
|
||||
{%- set eid = id_of(entry) -%}
|
||||
{%- if eid == tc_id -%}
|
||||
{%- if entry.output is iterable and entry.output is not string and entry.output is not mapping and entry.output and entry.output.0.type == "tool_reference" -%}
|
||||
{{- tool_references_to_response(entry.output) -}}
|
||||
{%- else -%}
|
||||
{{- tool_response(visible_text(entry.output)) -}}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{%- set tk_id = id_of(m) -%}
|
||||
{%- if tk_id == tc_id -%}
|
||||
{{- render_tool_response(m) -}}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{%- for k in range(block_start, ns_blk.end + 1) -%}
|
||||
{{- render_tool_response(messages[k]) -}}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{% endif -%}
|
||||
{%- elif m.role == 'system' -%}
|
||||
<|system|>{{ visible_text(m.content) }}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- if add_generation_prompt -%}
|
||||
<|assistant|>{{- '<think>' -}}
|
||||
{%- endif -%}
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>Describe<|begin_of_image|><|image|><|end_of_image|>briefly.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Low<|user|>Hi.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: High<|user|>Hi.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>First question.<|assistant|><think>Thinking about the first.</think>First answer.<|user|>Second question.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>First question.<|assistant|><think>Thinking about the first.</think>First answer.<|user|>Second question.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>First question.<|assistant|><think>Thinking about the first.</think>First answer.<|user|>Second question.<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>Hi.<|assistant|><think></think>Hello.
|
||||
@@ -0,0 +1,15 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}}
|
||||
{"name": "edit", "description": "Apply edits — exact text, «quoted» & <tagged>, 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}}
|
||||
{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call><|user|>Edit both files, then ping.<|assistant|><think></think>Doing all three.<tool_call>edit<arg_key>path</arg_key><arg_value>/work/a.py</arg_value><arg_key>edits</arg_key><arg_value>[{"oldText": " return a\n", "newText": " return a < b & c # it's\n"}, {"oldText": "x\ty", "newText": "\\\""}]</arg_value><arg_key>dry_run</arg_key><arg_value>false</arg_value><arg_key>mode</arg_key><arg_value>safe</arg_value></tool_call><tool_call>read<arg_key>path</arg_key><arg_value>/work/über.py</arg_value><arg_key>limit</arg_key><arg_value>3</arg_value></tool_call><tool_call>ping</tool_call><|observation|><tool_response>{"ok": true}</tool_response><tool_response>x = 1
|
||||
</tool_response><tool_response>pong</tool_response><|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>You are terse.<|user|>What is 2+2?<|assistant|><think>
|
||||
@@ -0,0 +1 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|user|>Hi.<|assistant|><think>
|
||||
@@ -0,0 +1,15 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}}
|
||||
{"name": "edit", "description": "Apply edits — exact text, «quoted» & <tagged>, 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}}
|
||||
{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call><|user|>Fix /work/a.py.<|assistant|><think>Read it first.</think><tool_call>read<arg_key>path</arg_key><arg_value>/work/a.py</arg_value></tool_call><|observation|><tool_response>print(1)
|
||||
</tool_response><|user|>Go on.<|assistant|><think>
|
||||
@@ -0,0 +1,14 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}}
|
||||
{"name": "edit", "description": "Apply edits — exact text, «quoted» & <tagged>, 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}}
|
||||
{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call><|user|>Read /work/a.py.<|assistant|><think>
|
||||
@@ -0,0 +1,14 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}}
|
||||
{"name": "edit", "description": "Apply edits — exact text, «quoted» & <tagged>, 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}}
|
||||
{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call><|system|>You are a coding agent.<|user|>Read /work/a.py.<|assistant|><think>
|
||||
@@ -0,0 +1,14 @@
|
||||
[gMASK]<sop><|system|>Reasoning Effort: Max<|system|>
|
||||
# Tools
|
||||
|
||||
You may call one or more functions to assist with the user query.
|
||||
|
||||
You are provided with function signatures within <tools></tools> XML tags:
|
||||
<tools>
|
||||
{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}}
|
||||
{"name": "edit", "description": "Apply edits — exact text, «quoted» & <tagged>, 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}}
|
||||
{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}}
|
||||
</tools>
|
||||
|
||||
For each function call, output the function name and arguments within the following XML format:
|
||||
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call><|user|>Übersetze: 日本語 🙂 "quoted" \ back<|assistant|><think>
|
||||
@@ -4,7 +4,8 @@
|
||||
"qwen3.8": { "bos": "", "eos": "<|im_end|>", "media": "<|vision_start|><|image_pad|><|vision_end|>" },
|
||||
"qwen3.6": { "bos": "", "eos": "<|im_end|>", "media": "<|vision_start|><|image_pad|><|vision_end|>" },
|
||||
"minicpm5": { "bos": "<s>", "eos": "</s>", "media": "" },
|
||||
"gemma4": { "bos": "<bos>", "eos": "<eos>", "media": "<|image|>" }
|
||||
"gemma4": { "bos": "<bos>", "eos": "<eos>", "media": "<|image|>" },
|
||||
"glm53": { "bos": "", "eos": "<|endoftext|>", "media": "<|begin_of_image|><|image|><|end_of_image|>" }
|
||||
},
|
||||
"tools": [
|
||||
{ "type": "function", "function": { "name": "read", "description": "Read a file.",
|
||||
@@ -58,6 +59,7 @@
|
||||
{ "role": "assistant", "reasoning_content": "Thinking about the first.", "content": "First answer." },
|
||||
{ "role": "user", "content": "Second question." } ] },
|
||||
{ "name": "tool_call_then_result",
|
||||
"models": ["qwen3.8", "qwen3.6", "minicpm5", "gemma4"],
|
||||
"tools": true,
|
||||
"messages": [
|
||||
{ "role": "user", "content": "Fix /work/a.py." },
|
||||
@@ -66,6 +68,7 @@
|
||||
"function": { "name": "read", "arguments": "{\"path\": \"/work/a.py\", \"limit\": 40}" } } ] },
|
||||
{ "role": "tool", "tool_call_id": "call_1", "content": "print(1)\n" } ] },
|
||||
{ "name": "tool_call_answered_then_user",
|
||||
"models": ["qwen3.8", "qwen3.6", "minicpm5", "gemma4"],
|
||||
"tools": true,
|
||||
"messages": [
|
||||
{ "role": "user", "content": "Fix /work/a.py." },
|
||||
@@ -114,7 +117,7 @@
|
||||
"kwargs": { "reasoning_effort": "high" },
|
||||
"messages": [ { "role": "user", "content": "Hi." } ] },
|
||||
{ "name": "a_picture_between_text",
|
||||
"models": ["qwen3.8", "qwen3.6", "gemma4"],
|
||||
"models": ["qwen3.8", "qwen3.6", "gemma4", "glm53"],
|
||||
"messages": [
|
||||
{ "role": "user", "content": [
|
||||
{ "type": "text", "text": "Describe" },
|
||||
|
||||
@@ -1694,6 +1694,59 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
|
||||
{ R"({"type":"string","pattern":"^[a-z]{2,5}-[0-9]+$"})",
|
||||
{ R"("ab-1")", R"("abcde-123")" },
|
||||
{ R"("a-1")", R"("ab-")", R"("abcdef-1")", R"("AB-1")", R"("ab1")" } },
|
||||
/* A pattern without ^ or $ searches, as JSON Schema says: the missing side is any text.
|
||||
* Tool schemas send them bare; on array items a tool call's JSON arguments reach this
|
||||
* converter, so one bare pattern there failed the whole request. */
|
||||
{ R"({"type":"string","pattern":"[0-9]+"})",
|
||||
{ R"("7")", R"("ab12c")" }, { R"("abc")", R"("")" } },
|
||||
{ R"({"type":"string","pattern":"^ab"})", { R"("ab")", R"("abz")" }, { R"("zab")" } },
|
||||
{ R"({"type":"string","pattern":"ab$"})", { R"("ab")", R"("zab")" }, { R"("abz")" } },
|
||||
{ R"({"type":"string","pattern":"a\\$"})", { R"("a$")", R"("za$z")" }, { R"("a")" } },
|
||||
{ R"({"type":"string","pattern":"x|yz"})", { R"("x")", R"("ayzb")" }, { R"("y")" } },
|
||||
{ R"({"type":"array","items":{"type":"string","pattern":"[0-9]+"}})",
|
||||
{ R"(["1","x2"])", R"(["x\"1"])", "[]" }, { R"(["x"])", R"(["1","x"])" } },
|
||||
/* \d \w \s and their negations (0018), as tool schemas send them: oh-my-pi's workpool tool
|
||||
* carries "\S" thirteen times. A negated class must not cross the closing quote. */
|
||||
{ R"({"type":"string","pattern":"\\S"})", { R"("a")", R"(" a ")" }, { R"("")", R"(" ")" } },
|
||||
{ R"({"type":"array","items":{"type":"string","pattern":"\\S"}})",
|
||||
{ R"(["a"," b"])" }, { R"([" "])", R"(["a"," "])" } },
|
||||
{ R"({"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"})",
|
||||
{ R"("2026-10-19")" }, { R"("2026-1-19")", R"("20x6-10-19")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\w-]+$"})", { R"("a_b-1")" }, { R"("a b")", R"("")" } },
|
||||
{ R"({"type":"string","pattern":"^-?\\d+(?:\\.\\d+)?$"})",
|
||||
{ R"("3")", R"("-3.14")" }, { R"("3.")", R"("x")" } },
|
||||
{ R"({"type":"string","pattern":"^a\\sb$"})", { R"("a b")", R"("a\tb")" }, { R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\s\\S]{2}$"})", { R"("ab")", R"("a ")" }, { R"("a")" } },
|
||||
{ R"({"type":"string","pattern":"^\\D$"})", { R"("x")" }, { R"("7")" } },
|
||||
/* identity escapes of punctuation (0019): zod's email pattern sends "\-" inside a class, and
|
||||
* JavaScript-written patterns escape "/". An escaped '-' in a class is not a range. */
|
||||
{ R"({"type":"string","pattern":"^a\\/b$"})", { R"("a/b")" }, { R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^a\\-b$"})", { R"("a-b")" }, { R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^[a\\-z]$"})", { R"("a")", R"("-")", R"("z")" }, { R"("b")" } },
|
||||
{ R"({"type":"string","pattern":"^[a\\^]$"})", { R"("^")", R"("a")" }, { R"("b")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\^a]$"})", { R"("^")", R"("a")" }, { R"("b")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\--z]$"})", { R"("-")", R"("a")" }, { R"("+")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\.]$"})", { R"(".")" }, { R"("a")" } },
|
||||
{ R"({"type":"string","pattern":"a\\-b"})", { R"("xa-by")" }, { R"("ab")" } },
|
||||
/* control-character escapes (0020): a JSON string holds a tab or a backspace only as an
|
||||
* escape, so [\t] [\b] [\f] [\v] [\0] and \t outside a class match the escape, and an
|
||||
* escaped space or non-ASCII character is itself. */
|
||||
{ R"({"type":"string","pattern":"^[\\b]$"})", { R"("\b")" }, { R"("b")", R"("\\")" } },
|
||||
{ R"({"type":"string","pattern":"^[a\\t]+$"})", { R"("a\ta")", R"("a")" }, { R"("t")", R"("a b")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\f\\v]$"})", { R"("\f")", R"("\u000b")", R"("\u000B")" }, { R"("f")", R"("v")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\0]$"})", { R"("\u0000")" }, { R"("0")" } },
|
||||
{ R"({"type":"string","pattern":"^a\\tb$"})", { R"("a\tb")" }, { R"("atb")" } },
|
||||
{ R"({"type":"string","pattern":"^[a\\ ]+$"})", { R"("a a")" }, { R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^a\\ b$"})", { R"("a b")" }, { R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\s]$"})", { R"(" ")", R"("\n")" }, { R"("n")" } },
|
||||
{ R"({"type":"string","pattern":"^[^\\t]$"})", { R"("a")" }, { R"("")" } },
|
||||
{ R"({"type":"string","pattern":"^a\\t+b$"})", { R"("a\t\tb")" }, { R"("a\tttb")", R"("ab")" } },
|
||||
{ R"({"type":"string","pattern":"^x\\v{2}$"})", { R"("x\u000b\u000B")" }, { R"("x\u000b")" } },
|
||||
{ R"({"type":"string","pattern":"^[\\t]{2}$"})", { R"("\t\t")" }, { R"("\t")" } },
|
||||
{ R"({"type":"string","pattern":"^[^\\n]+$"})", { R"("ab")", R"("a\tb")" }, { R"("a\nb")" } },
|
||||
{ R"({"type":"string","pattern":"^[^\\s]+$"})", { R"("ab")" }, { R"("\t")", R"("a b")" } },
|
||||
{ R"({"type":"string","pattern":"^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"})",
|
||||
{ R"("a.b@c.io")", R"("x-y@d-e.org")" }, { R"("a@b")", R"("a b@c.io")" } },
|
||||
{ R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})",
|
||||
{ "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } },
|
||||
{ R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)"
|
||||
@@ -1713,6 +1766,18 @@ TEST(json_schema_grammars_admit_exactly_their_instances) {
|
||||
if (schema_admits(bv->v, R"({"type":"number","minimum":0.5})", "-1"))
|
||||
fprintf(stderr, " SKIP number bounds: the converter does not enforce minimum/maximum "
|
||||
"on \"number\"\n");
|
||||
for (const char* schema : { R"({"type":"string","pattern":"^a|b"})",
|
||||
R"({"type":"string","pattern":"a|b$"})",
|
||||
R"({"type":"string","pattern":"^[a\\S]$"})",
|
||||
R"({"type":"string","pattern":"^[\\p{L}]$"})",
|
||||
R"({"type":"string","pattern":"^[\\cA]$"})",
|
||||
R"({"type":"string","pattern":"^[a\\1]$"})",
|
||||
R"({"type":"string","pattern":"^[\\01]$"})",
|
||||
R"({"type":"string","pattern":"^[\\xZ]$"})",
|
||||
R"({"type":"string","pattern":"^[\\u{41}]$"})" }) {
|
||||
std::string gbnf, err;
|
||||
CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0);
|
||||
}
|
||||
for (const Case& c : cases) {
|
||||
for (const char* y : c.yes) {
|
||||
const bool ok = schema_admits(bv->v, c.schema, y);
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
/* gen_lora_test.cpp -- runtime LoRA for generators: adapter files in every spelling and kind
|
||||
* (core/lora/adapter.h), their keys mapped through a generator's declared names, stacked at
|
||||
* strengths, packed per rank; and the request fields that name them (core/server/loras.h).
|
||||
*
|
||||
* Host only, no kernel plugin: the Program is made by the core Builder over an empty Registry, as
|
||||
* lora_test.cpp makes its own, with the generator's names declared through the builder (the calls
|
||||
* rad_lora_root / rad_lora_alias make). The reference is the test's own dense delta of every
|
||||
* checkpoint module, placed by model semantics -- which rows of which tensor a rank's declared
|
||||
* weight holds -- never by anything adapter.cpp or lora.cpp computes.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "build/rad_build.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/lora.h"
|
||||
#include "plugin/registry.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "server/loras.h"
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sys/stat.h>
|
||||
|
||||
using namespace rad;
|
||||
namespace AR = rad::arch;
|
||||
using ojson = nlohmann::ordered_json;
|
||||
|
||||
namespace {
|
||||
|
||||
Registry& empty_registry() {
|
||||
static Registry r;
|
||||
return r;
|
||||
}
|
||||
|
||||
float val(uint32_t seed, uint64_t i) {
|
||||
uint64_t x = (uint64_t)seed * 0x9E3779B97F4A7C15ull + i * 0xBF58476D1CE4E5B9ull + 1;
|
||||
x ^= x >> 31; x *= 0x94D049BB133111EBull; x ^= x >> 29;
|
||||
return (float)((double)(x >> 11) / (double)(1ull << 53) - 0.5) * 0.5f;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ safetensors */
|
||||
struct TW {
|
||||
std::string name, dtype;
|
||||
std::vector<int64_t> shape;
|
||||
std::vector<float> v; /* written as dtype */
|
||||
};
|
||||
void write_st(const std::string& path, const std::vector<TW>& ts) {
|
||||
ojson h = ojson::object();
|
||||
std::vector<std::vector<uint8_t>> bytes;
|
||||
uint64_t off = 0;
|
||||
for (const TW& t : ts) {
|
||||
std::vector<uint8_t> b;
|
||||
if (t.dtype == "I64") { const int64_t v = 4; b.resize(8); std::memcpy(b.data(), &v, 8); }
|
||||
for (float f : t.v) {
|
||||
if (t.dtype == "F32") { uint8_t x[4]; std::memcpy(x, &f, 4); b.insert(b.end(), x, x + 4); }
|
||||
else {
|
||||
const uint16_t u = t.dtype == "F16" ? rad_f32_to_f16(f) : rad_f32_to_bf16(f);
|
||||
uint8_t x[2]; std::memcpy(x, &u, 2); b.insert(b.end(), x, x + 2);
|
||||
}
|
||||
}
|
||||
h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape },
|
||||
{ "data_offsets", { off, off + b.size() } } };
|
||||
off += b.size();
|
||||
bytes.push_back(std::move(b));
|
||||
}
|
||||
h["__metadata__"] = { { "format", "pt" } };
|
||||
std::string s = h.dump();
|
||||
while (s.size() % 8) s += ' ';
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
const uint64_t n = s.size();
|
||||
f.write((const char*)&n, 8);
|
||||
f.write(s.data(), (std::streamsize)s.size());
|
||||
for (const auto& b : bytes) f.write((const char*)b.data(), (std::streamsize)b.size());
|
||||
}
|
||||
/* A tensor of seeded values, and the values as the file holds them. */
|
||||
TW tensor(const std::string& name, const std::string& dt, std::vector<int64_t> shape, uint32_t seed,
|
||||
float mul = 1.0f) {
|
||||
TW t{ name, dt, shape, {} };
|
||||
int64_t n = 1;
|
||||
for (int64_t d : shape) n *= d;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float f = val(seed, (uint64_t)i) * mul;
|
||||
if (dt == "F16") f = rad_f16_to_f32(rad_f32_to_f16(f));
|
||||
else if (dt == "BF16") f = rad_bf16_to_f32(rad_f32_to_bf16(f));
|
||||
t.v.push_back(f);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
TW scalar(const std::string& name, float f) { return TW{ name, "F32", {}, { f } }; }
|
||||
|
||||
/* ------------------------------------------------------------------ dense helpers */
|
||||
struct Dense {
|
||||
int64_t N = 0, K = 0;
|
||||
std::vector<double> d;
|
||||
void add(const Dense& o, double w) {
|
||||
if (d.empty()) { N = o.N; K = o.K; d.assign(o.d.size(), 0.0); }
|
||||
for (size_t i = 0; i < d.size(); ++i) d[i] += w * o.d[i];
|
||||
}
|
||||
};
|
||||
Dense mul(const std::vector<float>& B, const std::vector<float>& A, int64_t N, int64_t r, int64_t K,
|
||||
double s) {
|
||||
Dense o{ N, K, std::vector<double>((size_t)(N * K), 0.0) };
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t j = 0; j < r; ++j)
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
o.d[(size_t)(n * K + k)] += s * (double)B[(size_t)(n * r + j)] * A[(size_t)(j * K + k)];
|
||||
return o;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the generator */
|
||||
/* A two-block DiT under "transformer.", as an image generator's plugin declares one: a fused
|
||||
* [q|k|v] (row parts, ROW), the output (COL), a SwiGLU re-laid from one checkpoint tensor whose
|
||||
* value half comes first (RAD_MAP_ROWS: the gate half moved first), the down projection (COL); a
|
||||
* text encoder's linear outside the root; and a DiT weight a fused GEMM reads. */
|
||||
const int64_t kD = 128, kHD = 32, kNH = 8, kF = 512, kQ = kNH * kHD;
|
||||
|
||||
RadModelMeta gen_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "gentest"; m.name = "lora-test-gen"; m.quant = "fp8_e4m3";
|
||||
m.n_layers = 2; m.n_embd = kD; m.n_head = kNH; m.n_head_kv = kNH; m.head_dim = kHD;
|
||||
m.n_ff = kF; m.n_vocab = 512; m.n_ctx_train = 1024;
|
||||
m.rms_eps = 1e-5f; m.rope_theta = 1e4f; m.rope_scale = 1.0f;
|
||||
return m;
|
||||
}
|
||||
|
||||
OpInfo gemm_op(const char* name, int64_t N, int64_t K, const char* dtype, int64_t hi,
|
||||
std::vector<rad_weight> w, std::vector<int32_t> opd) {
|
||||
OpInfo o;
|
||||
o.op = name;
|
||||
o.base.set_i("N", N);
|
||||
o.base.set_i("K", K);
|
||||
o.base.set_i("group", AR::RAD_FP8_BLOCK);
|
||||
o.base.set_s("dtype", dtype);
|
||||
o.ranged_key = "M";
|
||||
o.range_lo = 1;
|
||||
o.range_hi = hi;
|
||||
o.weights = std::move(w);
|
||||
o.weight_opd = std::move(opd);
|
||||
return o;
|
||||
}
|
||||
void push_op(Builder& b, OpInfo o) {
|
||||
o.index = (int32_t)b.program().ops.size();
|
||||
b.program().ops.push_back(std::move(o));
|
||||
}
|
||||
|
||||
int linear(Builder& b, AR::Names& nm, const AR::Geom& g, const char* base, int64_t N, int64_t K,
|
||||
int shard, int layer, std::initializer_list<const char*> src,
|
||||
std::initializer_list<int64_t> parts = {}, bool mapped = false,
|
||||
const char* op = "gemm_nt_q") {
|
||||
AR::LinearFP8 lin{};
|
||||
AR::ActFP8 act{};
|
||||
lin.mapped = mapped;
|
||||
const int st = lin.declare((RadBuilder*)&b, nm, g, base, N, K, shard, AR::grp_layer(layer), src,
|
||||
act, 0, 0, parts);
|
||||
if (st < 0 || !lin.w || !lin.ws) return st < 0 ? st : RAD_E_INVAL;
|
||||
push_op(b, gemm_op(op, N, K, "fp8a8", g.max_tok, { lin.w, lin.ws }, { 2, 3 }));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RadBuildCtx ctx_for(int rank, int world) {
|
||||
RadBuildCtx c{};
|
||||
c.rank = rank;
|
||||
c.world_size = world;
|
||||
c.max_tok = 256;
|
||||
c.max_seqs = 8;
|
||||
c.max_ctx = 1024;
|
||||
c.scope = "";
|
||||
return c;
|
||||
}
|
||||
|
||||
/* Where a declared weight's rows on one rank come from: (checkpoint module, its full rows) per
|
||||
* row of y, and the full K columns of x. */
|
||||
struct Truth {
|
||||
std::vector<std::pair<std::string, int64_t>> rows;
|
||||
std::vector<int64_t> cols;
|
||||
};
|
||||
|
||||
int build_gen(int rank, int world, Program* out, std::map<std::string, Truth>* truth) {
|
||||
const RadModelMeta meta = gen_meta();
|
||||
const RadBuildCtx ctx = ctx_for(rank, world);
|
||||
AR::Geom g{};
|
||||
RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16));
|
||||
Builder b(empty_registry(), meta, ctx);
|
||||
b.program().generator.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
RAD_ARCH_TRY(AR::lora_names((RadBuilder*)&b, "transformer.", AR::kLoraDiffusionSpellings,
|
||||
{ { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_q", 0, kQ, 0 },
|
||||
{ "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_k", kQ, 2 * kQ, 0 },
|
||||
{ "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_v", 2 * kQ, 3 * kQ, 0 },
|
||||
{ "blocks.#.attn.out_proj", "transformer_blocks.#.attn.to_out.0" },
|
||||
{ "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", 0, kF, kF },
|
||||
{ "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", kF, 2 * kF, 0 },
|
||||
{ "blocks.#.mlp.fc2", "transformer_blocks.#.ff.net.2" } }));
|
||||
AR::Names nm("");
|
||||
const int64_t qr = g.q_dim(), fr = g.n_ff;
|
||||
for (int l = 0; l < 2; ++l) {
|
||||
const std::string P = "transformer.transformer_blocks." + std::to_string(l) + ".";
|
||||
auto ck = [&](const char* leaf) { return nm.ckpt("%s%s.weight", P.c_str(), leaf); };
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.qkv", l), 3 * qr, kD, RAD_SHARD_ROW, l,
|
||||
{ ck("attn.to_q"), ck("attn.to_k"), ck("attn.to_v") }, { qr, qr, qr }));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.o", l), kD, qr, RAD_SHARD_COL, l,
|
||||
{ ck("attn.to_out.0") }));
|
||||
const char* fsrc = ck("ff.net.0.proj");
|
||||
RAD_ARCH_TRY(AR::map_rows((RadBuilder*)&b, nm.f("dit.%d.gate_up.weight", l),
|
||||
{ { fsrc, (int)kF, kF }, { fsrc, 0, kF } }));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.gate_up", l), 2 * fr, kD, RAD_SHARD_ROW, l,
|
||||
{ fsrc }, { fr, fr }, true));
|
||||
RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.down", l), kD, fr, RAD_SHARD_COL, l,
|
||||
{ ck("ff.net.2") }));
|
||||
|
||||
Truth q, o, gu, dn;
|
||||
const char* part[3] = { "attn.to_q", "attn.to_k", "attn.to_v" };
|
||||
for (const char* p : part)
|
||||
for (int64_t i = rank * qr; i < (rank + 1) * qr; ++i) q.rows.push_back({ P + p, i });
|
||||
for (int64_t k = 0; k < kD; ++k) q.cols.push_back(k);
|
||||
for (int64_t i = 0; i < kD; ++i) o.rows.push_back({ P + "attn.to_out.0", i });
|
||||
for (int64_t k = rank * qr; k < (rank + 1) * qr; ++k) o.cols.push_back(k);
|
||||
for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", kF + i });
|
||||
for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", i });
|
||||
for (int64_t k = 0; k < kD; ++k) gu.cols.push_back(k);
|
||||
for (int64_t i = 0; i < kD; ++i) dn.rows.push_back({ P + "ff.net.2", i });
|
||||
for (int64_t k = rank * fr; k < (rank + 1) * fr; ++k) dn.cols.push_back(k);
|
||||
const std::string L = std::to_string(l);
|
||||
(*truth)["dit." + L + ".qkv.weight"] = q;
|
||||
(*truth)["dit." + L + ".o.weight"] = o;
|
||||
(*truth)["dit." + L + ".gate_up.weight"] = gu;
|
||||
(*truth)["dit." + L + ".down.weight"] = dn;
|
||||
}
|
||||
/* Outside the root: a text encoder's projection. */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, "te.0.q", kD, kD, RAD_SHARD_NONE, 0,
|
||||
{ "text_encoder.layers.0.q_proj.weight" }));
|
||||
/* Under the root, read by a fused GEMM: it stays the base. */
|
||||
RAD_ARCH_TRY(linear(b, nm, g, "dit.fused", kD, kD, RAD_SHARD_NONE, 0,
|
||||
{ "transformer.proj_out.weight" }, {}, false, "gemm_nt_q_swiglu"));
|
||||
*out = std::move(b.program());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::string new_dir(const std::string& name) {
|
||||
const std::string d = radtest::tmp_path(name);
|
||||
mkdir(d.c_str(), 0755);
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the adapter files */
|
||||
/* Two files, every spelling and kind, and the dense delta of every checkpoint module they reach
|
||||
* (strength 1). File 1: kohya LoRA on block 0's fused qkv; ComfyUI LoRA on block 0's fc1 (gate
|
||||
* half first); PEFT LoRA on block 1's down projection under the checkpoint's own name; LoHa on
|
||||
* block 1's out_proj; a full delta on block 0's fc2; a module of no model; a bias delta. File 2:
|
||||
* LoKr on block 1's qkv; a bare-keyed LoRA on block 0's qkv, stacking with file 1's. */
|
||||
struct Files {
|
||||
std::string f1, f2;
|
||||
std::map<std::string, Dense> d1, d2; /* by checkpoint module, full rows */
|
||||
};
|
||||
|
||||
void place(std::map<std::string, Dense>* m, const std::string& mod, int64_t N_full, const Dense& d,
|
||||
int64_t from_lo, int64_t n, int64_t to_lo) {
|
||||
Dense& t = (*m)[mod];
|
||||
if (t.d.empty()) { t.N = N_full; t.K = d.K; t.d.assign((size_t)(N_full * d.K), 0.0); }
|
||||
for (int64_t r = 0; r < n; ++r)
|
||||
for (int64_t k = 0; k < d.K; ++k)
|
||||
t.d[(size_t)((to_lo + r) * d.K + k)] += d.d[(size_t)((from_lo + r) * d.K + k)];
|
||||
}
|
||||
|
||||
Files make_files() {
|
||||
Files f;
|
||||
const std::string dir = new_dir("genlora");
|
||||
const std::string B0 = "transformer.transformer_blocks.0.", B1 = "transformer.transformer_blocks.1.";
|
||||
std::vector<TW> ts;
|
||||
{ /* kohya LoRA, rank 8, alpha 4: qkv of block 0 */
|
||||
TW dn = tensor("lora_unet_blocks_0_attn_qkv.lora_down.weight", "F16", { 8, kD }, 1);
|
||||
TW up = tensor("lora_unet_blocks_0_attn_qkv.lora_up.weight", "BF16", { 3 * kQ, 8 }, 2);
|
||||
const Dense d = mul(up.v, dn.v, 3 * kQ, 8, kD, 4.0 / 8.0);
|
||||
place(&f.d1, B0 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d1, B0 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d1, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.push_back(dn); ts.push_back(up);
|
||||
TW al{ "lora_unet_blocks_0_attn_qkv.alpha", "I64", {}, {} }; /* as kohya writes some */
|
||||
ts.push_back(al);
|
||||
}
|
||||
{ /* ComfyUI LoRA, rank 4, no alpha: fc1 of block 0, [gate; up] */
|
||||
TW a = tensor("diffusion_model.blocks.0.mlp.fc1.lora_A.weight", "BF16", { 4, kD }, 3);
|
||||
TW b = tensor("diffusion_model.blocks.0.mlp.fc1.lora_B.weight", "F32", { 2 * kF, 4 }, 4);
|
||||
const Dense d = mul(b.v, a.v, 2 * kF, 4, kD, 1.0);
|
||||
place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, 0, kF, kF);
|
||||
place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, kF, kF, 0);
|
||||
ts.push_back(a); ts.push_back(b);
|
||||
}
|
||||
{ /* PEFT LoRA under the checkpoint's own name, rank 6, alpha 12 */
|
||||
TW a = tensor(B1 + "ff.net.2.lora_A.default.weight", "F32", { 6, kF }, 5);
|
||||
TW b = tensor(B1 + "ff.net.2.lora_B.default.weight", "F32", { kD, 6 }, 6);
|
||||
place(&f.d1, B1 + "ff.net.2", kD, mul(b.v, a.v, kD, 6, kF, 12.0 / 6.0), 0, kD, 0);
|
||||
ts.push_back(a); ts.push_back(b); ts.push_back(scalar(B1 + "ff.net.2.alpha", 12.0f));
|
||||
}
|
||||
{ /* LoHa, ranks 4 and 3, alpha 2: out_proj of block 1 */
|
||||
const std::string k = "diffusion_model.blocks.1.attn.out_proj.";
|
||||
TW w1a = tensor(k + "hada_w1_a", "F32", { kD, 4 }, 7), w1b = tensor(k + "hada_w1_b", "F32", { 4, kQ }, 8);
|
||||
TW w2a = tensor(k + "hada_w2_a", "F32", { kD, 3 }, 9), w2b = tensor(k + "hada_w2_b", "F32", { 3, kQ }, 10);
|
||||
const Dense p1 = mul(w1a.v, w1b.v, kD, 4, kQ, 1.0), p2 = mul(w2a.v, w2b.v, kD, 3, kQ, 1.0);
|
||||
Dense d{ kD, kQ, std::vector<double>(p1.d.size()) };
|
||||
for (size_t i = 0; i < d.d.size(); ++i) d.d[i] = 0.5 * p1.d[i] * p2.d[i];
|
||||
place(&f.d1, B1 + "attn.to_out.0", kD, d, 0, kD, 0);
|
||||
ts.insert(ts.end(), { w1a, w1b, w2a, w2b, scalar(k + "alpha", 2.0f) });
|
||||
}
|
||||
{ /* a full delta: fc2 of block 0 */
|
||||
TW df = tensor("diffusion_model.blocks.0.mlp.fc2.diff", "F32", { kD, kF }, 11, 0.1f);
|
||||
Dense d{ kD, kF, std::vector<double>(df.v.begin(), df.v.end()) };
|
||||
place(&f.d1, B0 + "ff.net.2", kD, d, 0, kD, 0);
|
||||
ts.push_back(df);
|
||||
}
|
||||
ts.push_back(tensor("diffusion_model.nowhere.lora_A.weight", "F32", { 2, 8 }, 12));
|
||||
ts.push_back(tensor("diffusion_model.nowhere.lora_B.weight", "F32", { 8, 2 }, 13));
|
||||
ts.push_back(tensor("diffusion_model.blocks.0.mlp.fc2.diff_b", "F32", { kD }, 14));
|
||||
f.f1 = dir + "/one.safetensors";
|
||||
write_st(f.f1, ts);
|
||||
|
||||
ts.clear();
|
||||
{ /* LoKr: w1 [3, 2] full, w2 = w2_a [kQ, 4] @ w2_b [4, kD / 2], alpha 8 (scale 8 / 4) */
|
||||
const std::string k = "lora_unet_blocks_1_attn_qkv.";
|
||||
TW w1 = tensor(k + "lokr_w1", "F32", { 3, 2 }, 15);
|
||||
TW w2a = tensor(k + "lokr_w2_a", "F32", { kQ, 4 }, 16), w2b = tensor(k + "lokr_w2_b", "F32", { 4, kD / 2 }, 17);
|
||||
const Dense w2 = mul(w2a.v, w2b.v, kQ, 4, kD / 2, 1.0);
|
||||
Dense d{ 3 * kQ, kD, std::vector<double>((size_t)(3 * kQ * kD)) };
|
||||
for (int64_t i1 = 0; i1 < 3; ++i1)
|
||||
for (int64_t j1 = 0; j1 < 2; ++j1)
|
||||
for (int64_t i2 = 0; i2 < kQ; ++i2)
|
||||
for (int64_t j2 = 0; j2 < kD / 2; ++j2)
|
||||
d.d[(size_t)((i1 * kQ + i2) * kD + j1 * (kD / 2) + j2)] =
|
||||
2.0 * w1.v[(size_t)(i1 * 2 + j1)] * w2.d[(size_t)(i2 * (kD / 2) + j2)];
|
||||
place(&f.d2, B1 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d2, B1 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d2, B1 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.insert(ts.end(), { w1, w2a, w2b, scalar(k + "alpha", 8.0f) });
|
||||
}
|
||||
{ /* bare keys, rank 8: qkv of block 0, stacked on file 1's */
|
||||
TW a = tensor("blocks.0.attn.qkv.lora_A.weight", "BF16", { 8, kD }, 18);
|
||||
TW b = tensor("blocks.0.attn.qkv.lora_B.weight", "BF16", { 3 * kQ, 8 }, 19);
|
||||
const Dense d = mul(b.v, a.v, 3 * kQ, 8, kD, 1.0);
|
||||
place(&f.d2, B0 + "attn.to_q", kQ, d, 0, kQ, 0);
|
||||
place(&f.d2, B0 + "attn.to_k", kQ, d, kQ, kQ, 0);
|
||||
place(&f.d2, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0);
|
||||
ts.push_back(a); ts.push_back(b);
|
||||
}
|
||||
f.f2 = dir + "/two.safetensors";
|
||||
write_st(f.f2, ts);
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A packed slot's product, [N_r, K_r]. */
|
||||
std::vector<double> slot_delta(const lora::Site& s, const lora::PackedSite& p) {
|
||||
std::vector<double> d((size_t)(s.N_r * s.K_r), 0.0);
|
||||
for (int64_t y = 0; y < s.N_r; ++y) {
|
||||
for (int64_t j = 0; j < s.R; ++j) {
|
||||
const double b = rad_bf16_to_f32(p.b[(size_t)(y * s.R + j)]);
|
||||
if (b == 0.0) continue;
|
||||
for (int64_t k = 0; k < s.K_r; ++k)
|
||||
d[(size_t)(y * s.K_r + k)] += b * rad_bf16_to_f32(p.a[(size_t)(j * s.K_r + k)]);
|
||||
}
|
||||
for (int64_t k = 0; k < s.K_r; ++k) d[(size_t)(y * s.K_r + k)] *= p.scale[(size_t)y];
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== the files */
|
||||
TEST(adapter_files_group_by_module_and_refuse_what_they_cannot_reproduce) {
|
||||
const Files f = make_files();
|
||||
lora::AdapterFile a;
|
||||
std::string err;
|
||||
REQUIRE_EQ(a.open(f.f1, &err), RAD_OK);
|
||||
CHECK_EQ(a.modules().size(), (size_t)6);
|
||||
CHECK_EQ(a.skipped().size(), (size_t)1);
|
||||
CHECK_EQ(std::string(a.kind_name()), std::string("LoRA"));
|
||||
const std::string dir = new_dir("genlora_bad");
|
||||
write_st(dir + "/dora.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1),
|
||||
tensor("m.lora_B.weight", "F32", { 4, 2 }, 2),
|
||||
tensor("m.dora_scale", "F32", { 4, 1 }, 3) });
|
||||
CHECK_EQ(a.open(dir + "/dora.safetensors", &err), (int)RAD_E_UNSUPPORTED);
|
||||
CHECK(err.find("DoRA") != std::string::npos);
|
||||
write_st(dir + "/half.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1) });
|
||||
CHECK_EQ(a.open(dir + "/half.safetensors", &err), (int)RAD_E_FORMAT);
|
||||
}
|
||||
|
||||
/* A delta given as an operator truncates to its best rank-r form: exact at or above its rank, and
|
||||
* otherwise keeping what the sketch says it keeps. */
|
||||
TEST(truncation_is_exact_within_the_rank_and_honest_past_it) {
|
||||
const int64_t N = 96, K = 80;
|
||||
std::vector<float> D((size_t)(N * K));
|
||||
/* rank 12 */
|
||||
std::vector<float> U((size_t)(N * 12)), V((size_t)(12 * K));
|
||||
for (size_t i = 0; i < U.size(); ++i) U[i] = val(21, i);
|
||||
for (size_t i = 0; i < V.size(); ++i) V[i] = val(22, i);
|
||||
const Dense ref = mul(U, V, N, 12, K, 1.0);
|
||||
for (size_t i = 0; i < D.size(); ++i) D[i] = (float)ref.d[i];
|
||||
lora::Delta d;
|
||||
d.N = N; d.K = K; d.rank_bound = std::min(N, K);
|
||||
d.apply = [&](const float* X, int64_t l, float* Y) {
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
double a = 0;
|
||||
for (int64_t k = 0; k < K; ++k) a += (double)D[(size_t)(n * K + k)] * X[k * l + j];
|
||||
Y[n * l + j] = (float)a;
|
||||
}
|
||||
};
|
||||
d.apply_t = [&](const float* Y, int64_t l, float* X) {
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
for (int64_t j = 0; j < l; ++j) {
|
||||
double a = 0;
|
||||
for (int64_t n = 0; n < N; ++n) a += (double)D[(size_t)(n * K + k)] * Y[n * l + j];
|
||||
X[k * l + j] = (float)a;
|
||||
}
|
||||
};
|
||||
std::vector<float> B, A;
|
||||
double kept = 0;
|
||||
lora::truncate(d, 16, &B, &A, &kept);
|
||||
const Dense got = mul(B, A, N, 16, K, 1.0);
|
||||
double e = 0, t = 0;
|
||||
for (size_t i = 0; i < got.d.size(); ++i) { e += std::pow(got.d[i] - ref.d[i], 2); t += ref.d[i] * ref.d[i]; }
|
||||
CHECK(e / t < 1e-8);
|
||||
CHECK_NEAR(kept, 1.0, 1e-6);
|
||||
/* rank 6 of a rank-12 matrix: what is lost is what the report says is lost */
|
||||
lora::truncate(d, 6, &B, &A, &kept);
|
||||
const Dense g6 = mul(B, A, N, 6, K, 1.0);
|
||||
e = 0;
|
||||
for (size_t i = 0; i < g6.d.size(); ++i) e += std::pow(g6.d[i] - ref.d[i], 2);
|
||||
CHECK(kept < 0.99 && kept > 0.2);
|
||||
CHECK_NEAR(1.0 - e / t, kept, 0.02);
|
||||
}
|
||||
|
||||
/* ================================================================== the names */
|
||||
TEST(keys_resolve_through_spellings_aliases_and_kohya) {
|
||||
Program P;
|
||||
std::map<std::string, Truth> truth;
|
||||
REQUIRE_EQ(build_gen(0, 1, &P, &truth), RAD_OK);
|
||||
std::vector<lora::Site> sites;
|
||||
std::string err;
|
||||
REQUIRE_EQ(lora::build_sites(P, { "*" }, 16, &sites, &err), RAD_OK);
|
||||
/* 2 blocks x 4 weights; the text encoder's and the fused GEMM's are not sites */
|
||||
CHECK_EQ(sites.size(), (size_t)8);
|
||||
for (const lora::Site& s : sites) CHECK(s.weight.rfind("dit.", 0) == 0 && s.weight != "dit.fused.weight");
|
||||
const lora::KeyMap km(P, sites);
|
||||
std::string why;
|
||||
auto one = [&](const std::string& k) { return km.resolve(k, &why); };
|
||||
std::vector<lora::Target> t = one("lora_unet_blocks_1_attn_qkv");
|
||||
REQUIRE_EQ(t.size(), (size_t)3);
|
||||
CHECK_EQ(t[1].module, std::string("transformer.transformer_blocks.1.attn.to_k"));
|
||||
CHECK_EQ(t[1].from_lo, kQ);
|
||||
CHECK_EQ(t[1].from_hi, 2 * kQ);
|
||||
t = one("diffusion_model.blocks.0.mlp.fc2");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.ff.net.2"));
|
||||
t = one("transformer.transformer_blocks.0.attn.to_out.0");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
t = one("lora_unet_transformer_blocks_0_attn_to_out_0");
|
||||
REQUIRE_EQ(t.size(), (size_t)1);
|
||||
CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.attn.to_out.0"));
|
||||
t = one("blocks.1.mlp.fc1");
|
||||
CHECK_EQ(t.size(), (size_t)2);
|
||||
CHECK(one("diffusion_model.proj_out").empty());
|
||||
CHECK(why.find("no adapter path") != std::string::npos);
|
||||
CHECK(one("text_encoder.layers.0.q_proj").empty());
|
||||
CHECK(one("diffusion_model.blocks.7.attn.qkv").empty());
|
||||
}
|
||||
|
||||
/* ================================================================== stacked, packed */
|
||||
/* Packed compact, as the engine packs a generator's slot: every pool's product is the dense delta,
|
||||
* and its ranks are taken from 0. */
|
||||
TEST(stacked_adapters_of_every_kind_pack_to_their_dense_delta_on_every_rank) {
|
||||
const Files f = make_files();
|
||||
auto a1 = std::make_shared<lora::AdapterFile>(), a2 = std::make_shared<lora::AdapterFile>();
|
||||
std::string err;
|
||||
REQUIRE_EQ(a1->open(f.f1, &err), RAD_OK);
|
||||
REQUIRE_EQ(a2->open(f.f2, &err), RAD_OK);
|
||||
const double w1 = 0.8, w2 = -0.5;
|
||||
std::map<std::string, Dense> want;
|
||||
for (const auto& [k, d] : f.d1) want[k].add(d, w1);
|
||||
for (const auto& [k, d] : f.d2) want[k].add(d, w2);
|
||||
const int R = 24;
|
||||
for (int world : { 1, 2 }) {
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
Program P;
|
||||
std::map<std::string, Truth> truth;
|
||||
REQUIRE_EQ(build_gen(rank, world, &P, &truth), RAD_OK);
|
||||
std::vector<lora::Site> sites;
|
||||
std::vector<std::string> pools;
|
||||
REQUIRE_EQ(lora::build_sites(P, { "*" }, R, &sites, &err, &pools), RAD_OK);
|
||||
const lora::KeyMap km(P, sites);
|
||||
std::map<std::string, lora::Composite> comp;
|
||||
lora::ComposeReport rep;
|
||||
const int cs = lora::compose(km, { { "one", a1, w1 }, { "two", a2, w2 } }, R, &comp, &rep, &err);
|
||||
if (cs != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str());
|
||||
REQUIRE_EQ(cs, RAD_OK);
|
||||
CHECK_EQ(rep.unplaced.size(), (size_t)1);
|
||||
CHECK_EQ(rep.skipped.size(), (size_t)1);
|
||||
/* block 0's fc2 (a full delta, rank 128) is the one module past rank 24 */
|
||||
CHECK_EQ(rep.modules - rep.exact, (int64_t)1);
|
||||
CHECK_EQ(rep.worst_module, std::string("transformer.transformer_blocks.0.ff.net.2"));
|
||||
const std::map<std::string, lora::AdModule> mods = lora::as_modules(comp, km);
|
||||
lora::AdapterInfo info;
|
||||
std::vector<lora::PackedSite> packed;
|
||||
const int ps = lora::pack_modules(sites, R, mods, &info, &packed, &err, /*compact=*/true);
|
||||
if (ps != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str());
|
||||
REQUIRE_EQ(ps, RAD_OK);
|
||||
REQUIRE_EQ(packed.size(), pools.size());
|
||||
for (size_t p = 0; p < pools.size(); ++p) {
|
||||
const lora::Site* sp = nullptr;
|
||||
for (const lora::Site& x : sites) if (x.pool == (int32_t)p && !sp) sp = &x;
|
||||
REQUIRE(sp != nullptr);
|
||||
const lora::Site& s = *sp;
|
||||
const Truth& t = truth.at(s.weight);
|
||||
/* compact: the ranks taken from 0, within the pool's R */
|
||||
const lora::PackedSite& pk = packed[(size_t)s.pool];
|
||||
CHECK(pk.empty || (pk.r_used > 0 && pk.r_used <= s.R));
|
||||
for (int64_t y = 0; y < s.N_r && !pk.empty; ++y)
|
||||
for (int64_t j = pk.r_used; j < s.R; ++j)
|
||||
CHECK_EQ(pk.b[(size_t)(y * s.R + j)], (uint16_t)0);
|
||||
REQUIRE_EQ((int64_t)t.rows.size(), s.N_r);
|
||||
REQUIRE_EQ((int64_t)t.cols.size(), s.K_r);
|
||||
const std::vector<double> got = slot_delta(s, packed[(size_t)s.pool]);
|
||||
double e = 0, tot = 0, mx = 0;
|
||||
bool truncated = false;
|
||||
for (int64_t y = 0; y < s.N_r; ++y) {
|
||||
const auto& [mod, row] = t.rows[(size_t)y];
|
||||
truncated = truncated || mod == "transformer.transformer_blocks.0.ff.net.2";
|
||||
auto it = want.find(mod);
|
||||
for (int64_t k = 0; k < s.K_r; ++k) {
|
||||
const double ref = it == want.end() ? 0.0
|
||||
: it->second.d[(size_t)(row * it->second.K + t.cols[(size_t)k])];
|
||||
const double g = got[(size_t)(y * s.K_r + k)];
|
||||
e += (g - ref) * (g - ref);
|
||||
tot += ref * ref;
|
||||
mx = std::max(mx, std::fabs(g - ref) / (std::fabs(ref) + 1e-3));
|
||||
}
|
||||
}
|
||||
const double rel = tot > 0 ? std::sqrt(e / tot) : std::sqrt(e);
|
||||
if (rel > (truncated ? 0.9 : 0.01))
|
||||
fprintf(stderr, " world %d rank %d %s: relative error %.4g\n", world, rank,
|
||||
s.weight.c_str(), rel);
|
||||
/* bf16 factors hold a delta to ~0.5%; the truncated one to what its rank keeps */
|
||||
CHECK(rel <= (truncated ? 0.9 : 0.01));
|
||||
if (truncated && world == 1)
|
||||
CHECK_NEAR(1.0 - rel * rel, rep.worst_kept, 0.03);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the request fields */
|
||||
TEST(requests_name_adapters_in_a_field_or_in_prompt_tags) {
|
||||
std::vector<std::pair<std::string, double>> out;
|
||||
std::string field, why;
|
||||
std::string prompt = "a cat, <lora:pixel art:0.7>, sitting <lora:detail>";
|
||||
nlohmann::json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } };
|
||||
REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK);
|
||||
REQUIRE_EQ(out.size(), (size_t)5);
|
||||
CHECK_EQ(out[0].first, std::string("style"));
|
||||
CHECK_EQ(out[0].second, 1.0);
|
||||
CHECK_EQ(out[1].first, std::string("ink"));
|
||||
CHECK_EQ(out[1].second, 0.5);
|
||||
CHECK_EQ(out[2].first, std::string("x:y"));
|
||||
CHECK_EQ(out[2].second, 2.0);
|
||||
CHECK_EQ(out[3].first, std::string("pixel art"));
|
||||
CHECK_NEAR(out[3].second, 0.7, 1e-12);
|
||||
CHECK_EQ(out[4].first, std::string("detail"));
|
||||
CHECK_EQ(prompt, std::string("a cat, sitting"));
|
||||
body = { { "lora", { { "a", 0.25 }, { "b", 1 } } } };
|
||||
prompt = "p";
|
||||
REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK);
|
||||
CHECK_EQ(out.size(), (size_t)2);
|
||||
body = { { "loras", { 3 } } };
|
||||
CHECK_EQ(server::parse_loras(body, &prompt, &out, &field, &why), (int)RAD_E_INVAL);
|
||||
CHECK_EQ(field, std::string("loras"));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -88,6 +88,29 @@ TEST(the_schedule_is_diffusers_flow_match_euler) {
|
||||
CHECK_EQ(gen::schedule(d, {}, 0, 64).size(), (size_t)d.default_steps + 1);
|
||||
}
|
||||
|
||||
/* A schedule off a table of timesteps is ComfyUI's `simple` scheduler over its discrete flow
|
||||
* sampling (1000 timesteps, shift 3, multiplier 1): the sigmas below are what ComfyUI hands its
|
||||
* sampler, as f32. */
|
||||
TEST(a_sigma_grid_is_comfyui_simple_schedule) {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
d.dyn_shift = 0; d.shift_terminal = 0; d.shift = 3.0;
|
||||
d.sigma_grid = 1000;
|
||||
const double want30[] = { 1, 0.988752544, 0.976987481, 0.964285672, 0.951353252, 0.937781036,
|
||||
0.923076987, 0.908050597, 0.892220497, 0.87499994, 0.857326388,
|
||||
0.838624299, 0.818181813, 0.797094703, 0.774661541, 0.75,
|
||||
0.724405408, 0.697002113, 0.666666687, 0.634948134, 0.600719392,
|
||||
0.5625, 0.522164285, 0.478201658, 0.428571463, 0.375562221,
|
||||
0.317034721, 0.25, 0.177248672, 0.095505625, 0 };
|
||||
const std::vector<float> s = gen::schedule(d, {}, 30, 4096);
|
||||
REQUIRE_EQ(s.size(), (size_t)31);
|
||||
for (size_t i = 0; i < s.size(); ++i) CHECK_NEAR(s[i], want30[i], 1e-8);
|
||||
const double want7[] = { 1, 0.94771713, 0.882716119, 0.800373137, 0.69268024, 0.54580152,
|
||||
0.333592534, 0 };
|
||||
const std::vector<float> s7 = gen::schedule(d, {}, 7, 1024);
|
||||
REQUIRE_EQ(s7.size(), (size_t)8);
|
||||
for (size_t i = 0; i < s7.size(); ++i) CHECK_NEAR(s7[i], want7[i], 1e-8);
|
||||
}
|
||||
|
||||
/* A fixed schedule is taken as declared (with shift 1), then closed with 0. */
|
||||
TEST(a_fixed_schedule_is_used_as_declared) {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
@@ -96,6 +119,146 @@ TEST(a_fixed_schedule_is_used_as_declared) {
|
||||
CHECK_EQ(s[0], 0.9f); CHECK_EQ(s[1], 0.5f); CHECK_EQ(s[2], 0.125f); CHECK_EQ(s[3], 0.0f);
|
||||
}
|
||||
|
||||
/* ================================================================== a discrete-time schedule */
|
||||
/* Stable Diffusion XL's: 1000 timesteps, scaled-linear betas 0.00085..0.012. */
|
||||
RadGeneratorDecl decl_discrete() {
|
||||
RadGeneratorDecl d = decl_base();
|
||||
d.train_steps = 1000;
|
||||
d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR;
|
||||
d.beta_start = 0.00085;
|
||||
d.beta_end = 0.012;
|
||||
d.samplers = (1u << RAD_GEN_SAMPLER_COUNT) - 1;
|
||||
d.default_steps = 5;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* Each scheduler places five sigmas as ComfyUI's ModelSamplingDiscrete does (reference values
|
||||
* from its schedulers over the same table), and each sigma is conditioned at the timestep
|
||||
* ComfyUI picks for it. The table's ends are SDXL's sigma_min and sigma_max. */
|
||||
TEST(a_discrete_schedule_is_comfyuis) {
|
||||
const RadGeneratorDecl d = decl_discrete();
|
||||
gen::DiscreteTable t;
|
||||
std::string why;
|
||||
REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK);
|
||||
CHECK_NEAR(t.sigma_min(), 0.0291671585, 1e-8);
|
||||
CHECK_NEAR(t.sigma_max(), 14.6146412, 2e-5);
|
||||
struct Want { int32_t sched; double s[5]; int32_t ts[5]; };
|
||||
const Want want[] = {
|
||||
{ RAD_GEN_SCHED_NORMAL, { 14.6146402, 4.08608103, 1.61558032, 0.695149541, 0.0291671604 },
|
||||
{ 999, 749, 500, 250, 0 } },
|
||||
{ RAD_GEN_SCHED_KARRAS, { 14.6146431, 4.79653454, 1.27410078, 0.247949973, 0.0291671772 },
|
||||
{ 999, 786, 427, 59, 0 } },
|
||||
{ RAD_GEN_SCHED_EXPONENTIAL,
|
||||
{ 14.6146402, 3.08897638, 0.652891755, 0.137996376, 0.0291671604 },
|
||||
{ 999, 681, 233, 20, 0 } },
|
||||
{ RAD_GEN_SCHED_SGM_UNIFORM,
|
||||
{ 14.6146402, 5.09240818, 2.27973056, 1.16286457, 0.571188867 },
|
||||
{ 999, 799, 599, 400, 200 } },
|
||||
{ RAD_GEN_SCHED_SIMPLE, { 14.6146412, 5.08776331, 2.27646303, 1.16057837, 0.569284916 },
|
||||
{ 999, 799, 599, 399, 199 } },
|
||||
};
|
||||
for (const Want& w : want) {
|
||||
const std::vector<float> s = gen::schedule_discrete(d, t, w.sched, 0);
|
||||
REQUIRE_EQ(s.size(), (size_t)6);
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
CHECK_NEAR(s[(size_t)i], w.s[i], 2e-6 * w.s[i] + 1e-7);
|
||||
CHECK_EQ(t.timestep(s[(size_t)i]), w.ts[i]);
|
||||
}
|
||||
CHECK_EQ(s[5], 0.0f);
|
||||
CHECK_EQ(std::string(gen::scheduler_name(w.sched)).empty(), false);
|
||||
CHECK_EQ(gen::scheduler_id(gen::scheduler_name(w.sched)), w.sched);
|
||||
}
|
||||
/* Zero terminal SNR keeps the smallest sigma and makes the largest ComfyUI's 4518.76. */
|
||||
RadGeneratorDecl z = d;
|
||||
z.zero_snr = 1;
|
||||
gen::DiscreteTable tz;
|
||||
REQUIRE_EQ(gen::discrete_table(z, &tz, &why), (int)RAD_OK);
|
||||
CHECK_NEAR(tz.sigma_min(), 0.0291671585, 1e-8);
|
||||
CHECK_NEAR(tz.sigma_max(), 4518.76367, 0.01);
|
||||
CHECK_EQ(gen::sampler_id("dpmpp_2m"), (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(gen::sampler_id("ddim"), (int32_t)-1);
|
||||
}
|
||||
|
||||
/* A discrete-time model's step carries, per entry, its sigmas (the one before included), the
|
||||
* timestep, the request's sampler, the step, the image's size, and on the host the entry's
|
||||
* conditioning rows, size and branch; the conditioning pass carries its tokens on the host. */
|
||||
TEST(a_discrete_step_carries_its_sampler_and_each_entrys_geometry) {
|
||||
Program prog;
|
||||
prog.generator = decl_discrete();
|
||||
RadGeneratorDecl& d = prog.generator;
|
||||
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
d.latent_scale = 8;
|
||||
d.cond_rows = 2 * 77;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.chunk_tokens = 75;
|
||||
d.chunk_bos = 49406;
|
||||
d.chunk_eos = 49407;
|
||||
d.pad_token = 49407;
|
||||
prog.ctx.max_tok = 4096;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
gen::Driver drv;
|
||||
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto r = std::make_unique<gen::Request>();
|
||||
r->width = 64;
|
||||
r->height = 32;
|
||||
r->steps = 3;
|
||||
r->sampler = RAD_GEN_SAMPLER_DPMPP_2M;
|
||||
r->scheduler = RAD_GEN_SCHED_KARRAS;
|
||||
r->pos.tokens.assign(77, 5);
|
||||
r->has_neg = true;
|
||||
r->neg.tokens.assign(77, 6);
|
||||
r->cfg = 6.0f;
|
||||
r->ticket = std::make_shared<gen::Ticket>();
|
||||
std::string why;
|
||||
REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK);
|
||||
const RadBatch* b = drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
|
||||
REQUIRE(b->gen_b->tokens_h != nullptr);
|
||||
CHECK_EQ(b->gen_b->tokens_h[76], (int32_t)5);
|
||||
CHECK_OK(drv.done());
|
||||
REQUIRE(drv.next(1) != nullptr);
|
||||
CHECK_OK(drv.done());
|
||||
gen::DiscreteTable t;
|
||||
REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK);
|
||||
const std::vector<float> s = gen::schedule_discrete(d, t, RAD_GEN_SCHED_KARRAS, 3);
|
||||
for (int step = 0; step < 3; ++step) {
|
||||
b = drv.next(2 + step);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
|
||||
const RadGenBatch* G = b->gen_b;
|
||||
REQUIRE_EQ(b->n_seq, (int64_t)2);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(2 * (77 + 32)));
|
||||
for (int e = 0; e < 2; ++e) {
|
||||
CHECK_EQ(G->sigma[e], s[(size_t)step]);
|
||||
CHECK_EQ(G->sigma_next[e], s[(size_t)step + 1]);
|
||||
CHECK_EQ(G->sigma_prev[e], step ? s[(size_t)step - 1] : 0.0f);
|
||||
CHECK_EQ(G->timestep[e], (float)t.timestep(s[(size_t)step]));
|
||||
CHECK_EQ(G->sampler[e], (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(G->step[e], (int32_t)step);
|
||||
CHECK_EQ(G->size_px[2 * e], 32.0f);
|
||||
CHECK_EQ(G->size_px[2 * e + 1], 64.0f);
|
||||
CHECK_EQ(G->entry_h[4 * e], (int32_t)77);
|
||||
CHECK_EQ(G->entry_h[4 * e + 1], (int32_t)32);
|
||||
CHECK_EQ(G->entry_h[4 * e + 2], (int32_t)64);
|
||||
CHECK_EQ(G->entry_h[4 * e + 3], (int32_t)e);
|
||||
}
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
/* A sampler the model does not serve is refused at submit. */
|
||||
d.samplers = 1u << RAD_GEN_SAMPLER_EULER;
|
||||
gen::Driver drv2;
|
||||
REQUIRE_EQ(drv2.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto r2 = std::make_unique<gen::Request>();
|
||||
r2->width = 64;
|
||||
r2->height = 32;
|
||||
r2->sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL;
|
||||
r2->pos.tokens.assign(77, 5);
|
||||
r2->ticket = std::make_shared<gen::Ticket>();
|
||||
CHECK_EQ(drv2.submit(std::move(r2), &why), (int)RAD_E_INVAL);
|
||||
}
|
||||
|
||||
/* ================================================================== the sequence */
|
||||
/* An h x w image at frame `pos`: every row at that frame, height and width centred on zero. */
|
||||
TEST(image_rotary_positions_centre_the_grid_on_its_frame) {
|
||||
@@ -327,4 +490,160 @@ TEST(the_generator_admits_in_order_and_shutdown_answers_every_ticket) {
|
||||
CHECK(f.drv.next(1) == nullptr);
|
||||
}
|
||||
|
||||
/* The joint layout (RAD_GEN_LAYOUT_JOINT_STEP): no KV group; the conditioning's prompt padded to
|
||||
* the declared multiple (padding at position 1, valid_cu bounding the prompt), the reference
|
||||
* picture's tokens after it with its own l and scaled positions, and stored for every lane of the
|
||||
* request. A denoising entry is that conditioning, read from its lane and branch's store rows,
|
||||
* then the image, both in the pass order and mode by mode. */
|
||||
TEST(the_joint_layout_carries_the_conditioning_in_every_step) {
|
||||
Program prog;
|
||||
prog.generator = decl_base();
|
||||
RadGeneratorDecl& d = prog.generator;
|
||||
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
d.cond_rows = 64;
|
||||
d.pad_multiple = 8;
|
||||
d.pad_token = 99;
|
||||
d.rope_hw_scale = 0.5;
|
||||
d.rope_text_l = 1;
|
||||
d.ref_area = 32 * 32;
|
||||
prog.ctx.max_tok = 2048;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
gen::Driver drv;
|
||||
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto r = std::make_unique<gen::Request>();
|
||||
r->width = 64;
|
||||
r->height = 32;
|
||||
r->n = 2;
|
||||
r->pos.tokens = { 1, 2, 3, 4, 5 };
|
||||
r->pos.n_drop = 1;
|
||||
r->has_neg = true;
|
||||
r->neg.tokens = { 1, 6 };
|
||||
r->neg.n_drop = 1;
|
||||
r->cfg = 3.0f;
|
||||
gen::Pixels px;
|
||||
px.w = 32;
|
||||
px.h = 32;
|
||||
px.ch = 4;
|
||||
px.bf16.assign(32 * 32 * 4, 0);
|
||||
r->refs.push_back(px);
|
||||
r->ticket = std::make_shared<gen::Ticket>();
|
||||
std::string why;
|
||||
REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK);
|
||||
|
||||
/* The positive conditioning: 4 text rows padded to 8, then the picture's 2 x 2 tokens. */
|
||||
const RadBatch* b = drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
|
||||
const RadGenBatch* G = b->gen_b;
|
||||
CHECK_EQ(b->n_kv_groups, (int32_t)0);
|
||||
CHECK_EQ(b->n_tok, (int64_t)9); /* five tokens and four padding */
|
||||
CHECK_EQ(G->rows, (int64_t)12); /* 8 text rows and 4 picture tokens */
|
||||
CHECK_EQ(G->n_pad, (int32_t)4);
|
||||
CHECK_EQ(G->branch, (int32_t)0);
|
||||
CHECK_EQ(G->valid_cu[1], (int32_t)5);
|
||||
CHECK_EQ(b->token_ids[8], (int32_t)99);
|
||||
CHECK_EQ(b->positions[8], (int32_t)1);
|
||||
CHECK_EQ(G->n_lane, (int64_t)2);
|
||||
CHECK_EQ(G->src[0], (int32_t)1); /* the prompt row after the drop */
|
||||
CHECK_EQ(G->src[8], (int32_t)-1); /* the picture's first latent row */
|
||||
CHECK_EQ(G->rope_f[3 * 12 + 2], 2.0f); /* text row 2: l = 2 */
|
||||
CHECK_EQ(G->rope_f[3 * 12 + 9], -1.0f); /* the picture: l = -1 */
|
||||
CHECK_EQ(G->rope_f[2 * 12 + 9], 0.5f); /* its token (0, 1): w = 0.5 */
|
||||
CHECK_OK(drv.done());
|
||||
b = drv.next(1);
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->gen_b->branch, (int32_t)1);
|
||||
CHECK_EQ(b->gen_b->rows, (int64_t)12); /* one token padded to 8, the picture */
|
||||
CHECK_OK(drv.done());
|
||||
|
||||
/* A step: four entries (two images, each with its negative), 12 + 8 rows each. */
|
||||
b = drv.next(2);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
|
||||
G = b->gen_b;
|
||||
REQUIRE_EQ(b->n_seq, (int64_t)4);
|
||||
CHECK_EQ(b->n_tok, (int64_t)80);
|
||||
CHECK_EQ(G->n_img, (int64_t)32);
|
||||
CHECK_EQ(b->cu_seqlens[1], (int32_t)20);
|
||||
const int32_t lane0 = G->lane_dh[0];
|
||||
CHECK_EQ(G->src[0], (int32_t)(2 * lane0 * 64)); /* lane 0's positive row 0 */
|
||||
CHECK_EQ(G->src[20], (int32_t)((2 * lane0 + 1) * 64)); /* its negative row 0 */
|
||||
CHECK_EQ(G->src[12], (int32_t)-1); /* the first image row */
|
||||
CHECK_EQ(G->img_rows[0], (int32_t)12);
|
||||
CHECK_EQ(G->img_cu[1], (int32_t)8);
|
||||
CHECK_EQ(G->mode_cu[1], (int32_t)8); /* entry 0: text 0..8 */
|
||||
CHECK_EQ(G->mode_cu[2], (int32_t)12); /* pictures 8..12 */
|
||||
CHECK_EQ(G->mode_cu[3], (int32_t)20); /* image to 20 */
|
||||
CHECK_EQ(G->n_mode_h[0], (int64_t)32);
|
||||
CHECK_EQ(G->n_mode_h[1], (int64_t)16);
|
||||
CHECK_EQ(G->n_mode_h[2], (int64_t)32);
|
||||
CHECK_EQ(G->mode_rows[32], (int32_t)8); /* the first picture row */
|
||||
CHECK_EQ(G->mode_ccu[1 * 5 + 1], (int32_t)4); /* pictures: entry 1 from 4 */
|
||||
CHECK_EQ(G->mode_rope_f[4 * 32 + 3 * 16 + 0], -1.0f); /* the pictures' l plane */
|
||||
CHECK_EQ(G->rope_f[1 * 80 + 12 + 4], 0.5f); /* image token (1, 0): h = 0.5 */
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
|
||||
/* A generator that reads its prompt through a second tokenizer (RadGeneratorDecl::aux_tokens):
|
||||
* each branch's COND pass carries that branch's ids and {0, n} on the device, and no other pass
|
||||
* does; a branch with none, or more than declared, is refused at submission. */
|
||||
TEST(a_second_tokenizers_ids_ride_in_each_conditioning) {
|
||||
Program prog;
|
||||
prog.generator = decl_base();
|
||||
RadGeneratorDecl& d = prog.generator;
|
||||
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
|
||||
d.cond_rows = 16;
|
||||
d.pad_multiple = 16;
|
||||
d.pad_token = 99;
|
||||
d.aux_tokens = 1;
|
||||
d.aux_max_tokens = 6;
|
||||
prog.ctx.max_tok = 2048;
|
||||
prog.ctx.max_seqs = 8;
|
||||
prog.kv_groups.emplace_back();
|
||||
gen::Driver drv;
|
||||
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
|
||||
auto mk = [](std::vector<int32_t> aux, std::vector<int32_t> neg_aux) {
|
||||
auto r = std::make_unique<gen::Request>();
|
||||
r->width = 64;
|
||||
r->height = 64;
|
||||
r->pos.tokens = { 1, 2, 3 };
|
||||
r->pos.aux = std::move(aux);
|
||||
r->has_neg = true;
|
||||
r->neg.tokens = { 5 };
|
||||
r->neg.aux = std::move(neg_aux);
|
||||
r->cfg = 4.0f;
|
||||
r->ticket = std::make_shared<gen::Ticket>();
|
||||
return r;
|
||||
};
|
||||
std::string why;
|
||||
CHECK_EQ(drv.submit(mk({ 7, 8 }, {}), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "second tokenizer"));
|
||||
CHECK_EQ(drv.submit(mk({ 1, 2, 3, 4, 5, 6, 7 }, { 1 }), &why), (int)RAD_E_INVAL);
|
||||
REQUIRE_EQ(drv.submit(mk({ 7, 8, 1 }, { 1 }), &why), (int)RAD_OK);
|
||||
|
||||
const RadBatch* b = drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
|
||||
const RadGenBatch* G = b->gen_b;
|
||||
REQUIRE_EQ(G->n_aux, (int64_t)3);
|
||||
CHECK_EQ(G->aux_ids[0], (int32_t)7);
|
||||
CHECK_EQ(G->aux_ids[2], (int32_t)1);
|
||||
CHECK_EQ(G->aux_cu[0], (int32_t)0);
|
||||
CHECK_EQ(G->aux_cu[1], (int32_t)3);
|
||||
CHECK_OK(drv.done());
|
||||
b = drv.next(1);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen_b->n_aux, (int64_t)1);
|
||||
CHECK_EQ(b->gen_b->aux_ids[0], (int32_t)1);
|
||||
CHECK_EQ(b->gen_b->aux_cu[1], (int32_t)1);
|
||||
CHECK_OK(drv.done());
|
||||
b = drv.next(2);
|
||||
REQUIRE(b != nullptr);
|
||||
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
|
||||
CHECK_EQ(b->gen_b->n_aux, (int64_t)0);
|
||||
CHECK(b->gen_b->aux_ids == nullptr);
|
||||
CHECK_OK(drv.done());
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,73 @@
|
||||
/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers 5.21.0.dev0; do not edit. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
static const int32_t kGlm5Patch = 14, kGlm5Merge = 2, kGlm5Temporal = 2, kGlm5MinTok = 16, kGlm5MaxTok = 8000;
|
||||
static const int32_t kGlm5Image = 154854, kGlm5Start = 154830, kGlm5End = 154831;
|
||||
static const float kGlm5Mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f }, kGlm5Std[3] = { 0.26862954f, 0.26130258f, 0.27577711f };
|
||||
|
||||
struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; };
|
||||
static const GoldGlm5Size kGoldGlm5Size[] = {
|
||||
{ 1, 1, 8000, 112, 112, 64 },
|
||||
{ 1, 1, 4096, 112, 112, 64 },
|
||||
{ 100, 100, 8000, 112, 112, 64 },
|
||||
{ 100, 100, 4096, 112, 112, 64 },
|
||||
{ 61, 97, 8000, 112, 168, 96 },
|
||||
{ 61, 97, 4096, 112, 168, 96 },
|
||||
{ 3, 4000, 8000, 28, 4004, 572 },
|
||||
{ 3, 4000, 4096, 28, 4004, 572 },
|
||||
{ 448, 448, 8000, 448, 448, 1024 },
|
||||
{ 448, 448, 4096, 448, 448, 1024 },
|
||||
{ 300, 500, 8000, 308, 504, 792 },
|
||||
{ 300, 500, 4096, 308, 504, 792 },
|
||||
{ 768, 1024, 8000, 784, 1036, 4144 },
|
||||
{ 768, 1024, 4096, 784, 1036, 4144 },
|
||||
{ 1080, 1920, 8000, 1092, 1932, 10764 },
|
||||
{ 1080, 1920, 4096, 1092, 1932, 10764 },
|
||||
{ 2048, 2048, 8000, 2072, 2072, 21904 },
|
||||
{ 2048, 2048, 4096, 1792, 1792, 16384 },
|
||||
{ 3000, 4000, 8000, 2156, 2884, 31724 },
|
||||
{ 3000, 4000, 4096, 1540, 2072, 16280 },
|
||||
{ 4000, 3000, 8000, 2884, 2156, 31724 },
|
||||
{ 4000, 3000, 4096, 2072, 1540, 16280 },
|
||||
{ 20, 1500, 8000, 28, 1512, 216 },
|
||||
{ 20, 1500, 4096, 28, 1512, 216 },
|
||||
{ 1500, 20, 8000, 1512, 28, 216 },
|
||||
{ 1500, 20, 4096, 1512, 28, 216 },
|
||||
{ 111, 113, 8000, 112, 140, 80 },
|
||||
{ 111, 113, 4096, 112, 140, 80 },
|
||||
{ 112, 112, 8000, 112, 112, 64 },
|
||||
{ 112, 112, 4096, 112, 112, 64 },
|
||||
{ 113, 111, 8000, 140, 112, 80 },
|
||||
{ 113, 111, 4096, 140, 112, 80 },
|
||||
{ 2300, 2900, 8000, 2240, 2800, 32000 },
|
||||
{ 2300, 2900, 4096, 1596, 1988, 16188 },
|
||||
{ 7000, 120, 8000, 7000, 140, 5000 },
|
||||
{ 7000, 120, 4096, 7000, 140, 5000 },
|
||||
{ 120, 7000, 8000, 140, 7000, 5000 },
|
||||
{ 120, 7000, 4096, 140, 7000, 5000 },
|
||||
{ 5000, 5000, 8000, 2492, 2492, 31684 },
|
||||
{ 5000, 5000, 4096, 1792, 1792, 16384 },
|
||||
{ 12000, 9000, 8000, 2884, 2156, 31724 },
|
||||
{ 12000, 9000, 4096, 2072, 1540, 16280 },
|
||||
{ 2160, 3840, 8000, 1876, 3332, 31892 },
|
||||
{ 2160, 3840, 4096, 1344, 2380, 16320 },
|
||||
{ 1, 30000, 8000, 28, 30016, 4288 },
|
||||
{ 1, 30000, 4096, 28, 30016, 4288 },
|
||||
{ 900, 1400, 8000, 924, 1400, 6600 },
|
||||
{ 900, 1400, 4096, 924, 1400, 6600 },
|
||||
};
|
||||
|
||||
struct GoldGlm5Pic { int32_t f, h, w, budget, grid_h, grid_w; uint64_t fnv; int32_t n_ids; uint64_t ids_fnv; uint16_t head[8]; };
|
||||
static const GoldGlm5Pic kGoldGlm5Pics[] = {
|
||||
{ 0, 448, 448, 8000, 32, 32, 0xd1a1afd8f20ac789ull, 258, 0x72139e1c3f39bf1cull, { 0xbf1c, 0xbfc0, 0x3e0a, 0x3fc6, 0xbf7d, 0x3e64, 0x3f8e, 0x3f87 } },
|
||||
{ 1, 300, 500, 8000, 22, 36, 0x7be72496cfec045dull, 200, 0x255584700075589cull, { 0x3f0b, 0xbe30, 0xbf91, 0x3fdb, 0xbfe2, 0xbe6c, 0x3f4b, 0x3fa7 } },
|
||||
{ 2, 61, 97, 8000, 8, 12, 0xfedf63278fd84bf1ull, 26, 0x257747e49c4ee91cull, { 0x3ff1, 0x3fce, 0x3f96, 0x3fa9, 0x3fb2, 0x3f4e, 0x3f13, 0x3f47 } },
|
||||
{ 3, 3, 400, 8000, 2, 94, 0x26cc3ab47053bc9dull, 49, 0xfbf168ec084616acull, { 0xbfe5, 0xbfda, 0xbf5f, 0x3ef8, 0x3fe3, 0x3ff7, 0x3fdf, 0x3f96 } },
|
||||
{ 4, 20, 1500, 8000, 2, 108, 0x2fd52c52ec4a00a9ull, 56, 0x47537633a0505c9cull, { 0x3f94, 0xbeb2, 0xbf3e, 0x3e64, 0xbfc9, 0xbed0, 0x3f5a, 0xbf41 } },
|
||||
{ 5, 900, 1400, 256, 26, 38, 0x398290b8912d19d9ull, 249, 0x355dfb37a793d4acull, { 0x3f34, 0xbec1, 0xbf11, 0xbe12, 0xbe85, 0x3d9c, 0x3c93, 0x3f29 } },
|
||||
{ 6, 1200, 1700, 4096, 86, 122, 0x5fd09cd1af13ba41ull, 2625, 0xf9b8b842d63572acull, { 0xbf8f, 0x3fa5, 0xbf6b, 0x3f61, 0x3fac, 0xbf67, 0xbf18, 0x3df6 } },
|
||||
{ 7, 2300, 2900, 8000, 160, 200, 0x267b44f24a266119ull, 8002, 0x41e705bec95caf1cull, { 0xbf3a, 0x3fc1, 0xbe94, 0xbfc0, 0xbfa0, 0xbe94, 0xbf7a, 0xbf9b } },
|
||||
{ 8, 1, 1, 8000, 8, 8, 0xb8835c50fee76f25ull, 18, 0xb05a4c2103cd9b1cull, { 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1 } },
|
||||
{ 9, 113, 111, 8000, 10, 8, 0x4ae29fe59e7b4e15ull, 22, 0xd734c8e25ac1621cull, { 0xbfba, 0x3fe4, 0xbf11, 0xbf33, 0x3ed3, 0x3f43, 0xbfc9, 0xbfbc } },
|
||||
};
|
||||
@@ -0,0 +1,183 @@
|
||||
"""glm5_vision_reference.py MODEL_DIR OUT_DIR IMAGE [IMAGE ...] [--dtype bfloat16|float32] [--taps]
|
||||
[--max-image-tokens N] [--compare DUMP_DIR]
|
||||
|
||||
Transformers' own GLM-5.3 vision tower, run on the CPU, as the reference arch/glm5next's tower is
|
||||
checked against. Only `model.visual.*` is loaded (the checkpoint keeps the whole tower, bf16, in its
|
||||
last shard), so this needs about 3 GB of memory, not the model's 180.
|
||||
|
||||
All the pictures go through the tower in one call, as one encoder pass carries them: one attention
|
||||
segment each. For each picture it writes, under OUT_DIR/<picture's file name>/:
|
||||
|
||||
pix.bf16 the patches Glm5NextProcessor makes [P, 1176], merge-block order, bf16 -- the
|
||||
layout core/mm stages and RADIANCE_DEBUG_MM_DUMP writes as .pix.bf16
|
||||
out.f32 the merger's rows [P / 4, 4096], the rows that replace the picture's placeholders
|
||||
meta.json the grid, the patch and token counts, the dtype, and the prompt ids the processor
|
||||
makes of <|begin_of_image|><|image|><|end_of_image|>
|
||||
|
||||
and with --taps the tensors on the way, each as f32 in the tower's own order:
|
||||
|
||||
patch.f32 the patch embedding [P, 1024]
|
||||
q0.f32 k0.f32 block 0's q and k after the per-head norm and the rotary [P, 16 * 64]
|
||||
blk0.f32 blk11.f32 blk23.f32 the residual stream after those blocks [P, 1024]
|
||||
post.f32 post_layernorm [P, 1024]
|
||||
down.f32 the 2 x 2 downsample [P / 4, 4096]
|
||||
|
||||
--max-image-tokens is the processor's budget, the checkpoint's 8000 by default: a server whose
|
||||
encoder pass holds fewer (--mm-max-patches auto is 4096 tokens) sizes a large picture smaller, and
|
||||
the reference must be asked for the same budget.
|
||||
|
||||
The tower's input is the processor's patches rounded to bf16 in both dtypes, which is what the
|
||||
engine stages: --dtype float32 then measures the tower's arithmetic alone. Every number here comes
|
||||
from transformers, not from this script.
|
||||
|
||||
--compare DUMP_DIR reads what an engine serving the same pictures wrote with
|
||||
RADIANCE_DEBUG_MM_DUMP=DUMP_DIR (mm_<key>_1xHxW.pix.bf16 and .bf16, matched to the pictures by
|
||||
grid) and checks it against the reference: the staged patches bit for bit, and the encoder rows to
|
||||
the tolerance of two bf16 computations of the same tower -- a cosine of at least 0.99 over the
|
||||
picture and a median per-row relative error of at most 0.08 against the bfloat16 reference.
|
||||
Measured against it on the CPU (libref, libavx) and one R9700 (libr4d): cosine 0.996 to 0.998 and
|
||||
a median per-row error of 0.03 to 0.045 at up to 4144 patches, 0.993 and 0.049 at 16384, the same
|
||||
order as the bfloat16 reference's own against float32; a handful of rows with a small norm differ
|
||||
more in both (docs/ARCHITECTURES.md). Exits 1 past either bound."""
|
||||
import argparse, json, os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
from safetensors import safe_open
|
||||
from transformers import AutoConfig, AutoProcessor
|
||||
from transformers.models.glm5_next import modeling_glm5_next as M
|
||||
|
||||
|
||||
def load_tower(model_dir, dtype):
|
||||
cfg = AutoConfig.from_pretrained(model_dir).vision_config
|
||||
cfg._attn_implementation = "sdpa"
|
||||
tower = M.Glm5NextVisionModel(cfg)
|
||||
index = json.load(open(os.path.join(model_dir, "model.safetensors.index.json")))
|
||||
want = {k: v for k, v in index["weight_map"].items() if k.startswith("model.visual.")}
|
||||
state = {}
|
||||
for shard in sorted(set(want.values())):
|
||||
with safe_open(os.path.join(model_dir, shard), "pt") as f:
|
||||
for k in f.keys():
|
||||
if k in want:
|
||||
state[k[len("model.visual."):]] = f.get_tensor(k)
|
||||
missing, unexpected = tower.load_state_dict(state, strict=False)
|
||||
if unexpected or [k for k in missing if "inv_freq" not in k]:
|
||||
raise SystemExit(f"tower weights: missing {missing}, unexpected {unexpected}")
|
||||
return tower.to(dtype).eval()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("model")
|
||||
ap.add_argument("out")
|
||||
ap.add_argument("images", nargs="+")
|
||||
ap.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"])
|
||||
ap.add_argument("--taps", action="store_true")
|
||||
ap.add_argument("--threads", type=int, default=0)
|
||||
ap.add_argument("--max-image-tokens", type=int, default=0)
|
||||
ap.add_argument("--compare", default=None, metavar="DUMP_DIR")
|
||||
a = ap.parse_args()
|
||||
if a.threads:
|
||||
torch.set_num_threads(a.threads)
|
||||
dtype = getattr(torch, a.dtype)
|
||||
proc = AutoProcessor.from_pretrained(a.model)
|
||||
tower = load_tower(a.model, dtype)
|
||||
|
||||
pics = [Image.open(p).convert("RGB") for p in a.images]
|
||||
budget = {"max_image_tokens": a.max_image_tokens} if a.max_image_tokens else {}
|
||||
enc = proc.image_processor(images=pics, return_tensors="pt", **budget)
|
||||
pv, thw = enc["pixel_values"], enc["image_grid_thw"]
|
||||
counts = [int(t.prod()) for t in thw]
|
||||
pv16 = pv.to(torch.bfloat16)
|
||||
|
||||
taps = {}
|
||||
hooks = []
|
||||
if a.taps:
|
||||
def keep(name, fn=lambda o: o):
|
||||
return lambda mod, inp, out: taps.__setitem__(name, fn(out).detach().float())
|
||||
hooks.append(tower.patch_embed.register_forward_hook(keep("patch")))
|
||||
for i in (0, 11, len(tower.blocks) - 1):
|
||||
hooks.append(tower.blocks[i].register_forward_hook(keep(f"blk{i}")))
|
||||
hooks.append(tower.post_layernorm.register_forward_hook(keep("post")))
|
||||
hooks.append(tower.downsample.register_forward_hook(
|
||||
keep("down", lambda o: o.reshape(-1, o.shape[1]))))
|
||||
rope = M.apply_rotary_pos_emb_vision
|
||||
|
||||
def rope_tap(q, k, cos, sin):
|
||||
qe, ke = rope(q, k, cos, sin)
|
||||
if "q0" not in taps:
|
||||
taps["q0"] = qe.detach().float().reshape(qe.shape[0], -1)
|
||||
taps["k0"] = ke.detach().float().reshape(ke.shape[0], -1)
|
||||
return qe, ke
|
||||
M.apply_rotary_pos_emb_vision = rope_tap
|
||||
with torch.no_grad():
|
||||
out = tower(pv16.to(dtype), grid_thw=thw).pooler_output.float()
|
||||
if a.taps:
|
||||
M.apply_rotary_pos_emb_vision = rope
|
||||
for h in hooks:
|
||||
h.remove()
|
||||
|
||||
p0 = r0 = 0
|
||||
for path, im, t, n in zip(a.images, pics, thw.tolist(), counts):
|
||||
d = os.path.join(a.out, os.path.basename(path))
|
||||
os.makedirs(d, exist_ok=True)
|
||||
r = n // 4
|
||||
pv16[p0:p0 + n].view(torch.int16).numpy().astype("<i2").tofile(os.path.join(d, "pix.bf16"))
|
||||
out[r0:r0 + r].numpy().astype("<f4").tofile(os.path.join(d, "out.f32"))
|
||||
for name, v in taps.items():
|
||||
lo, hi = (r0, r0 + r) if name == "down" else (p0, p0 + n)
|
||||
v[lo:hi].numpy().astype("<f4").tofile(os.path.join(d, name + ".f32"))
|
||||
ids = proc(text=["<|begin_of_image|><|image|><|end_of_image|>"], images=[im],
|
||||
return_tensors="pt", **budget)["input_ids"][0].tolist()
|
||||
json.dump({"grid_thw": t, "patches": n, "tokens": r, "dtype": a.dtype,
|
||||
"prompt_ids_len": len(ids), "prompt_ids_head": ids[:3], "prompt_ids_tail": ids[-2:],
|
||||
"taps": sorted(taps)}, open(os.path.join(d, "meta.json"), "w"), indent=1)
|
||||
p0 += n
|
||||
r0 += r
|
||||
print(f"wrote {len(a.images)} picture(s) to {a.out}: {counts} patches, dtype {a.dtype}")
|
||||
if a.compare:
|
||||
raise SystemExit(compare(a.compare, a.images, thw.tolist(), pv16, out, counts))
|
||||
|
||||
|
||||
def compare(dump, images, grids, pv16, out, counts):
|
||||
"""The engine's patches and rows against the reference's; 0 when every picture is within."""
|
||||
def bf16(path):
|
||||
return (np.fromfile(path, dtype="<u2").astype(np.uint32) << 16).view(np.float32)
|
||||
bad = 0
|
||||
p0 = r0 = 0
|
||||
for path, (t, h, w), n in zip(images, grids, counts):
|
||||
r = n // 4
|
||||
name = os.path.basename(path)
|
||||
rows = [f for f in os.listdir(dump) if f.endswith(f"_{t}x{h}x{w}.bf16")]
|
||||
pix = [f for f in os.listdir(dump) if f.endswith(f"_{t}x{h}x{w}.pix.bf16")]
|
||||
if len(rows) != 1 or len(pix) != 1:
|
||||
print(f" {name}: {len(rows)} row dump(s) and {len(pix)} patch dump(s) for a "
|
||||
f"{t}x{h}x{w} grid in {dump}; expected one each")
|
||||
bad += 1
|
||||
p0 += n
|
||||
r0 += r
|
||||
continue
|
||||
same = np.array_equal(np.fromfile(os.path.join(dump, pix[0]), dtype="<u2"),
|
||||
pv16[p0:p0 + n].view(torch.int16).numpy().astype("<u2").ravel())
|
||||
e = bf16(os.path.join(dump, rows[0])).reshape(-1, 4096).astype(np.float64)
|
||||
ref = out[r0:r0 + r].numpy().astype(np.float64)
|
||||
if e.shape != ref.shape:
|
||||
print(f" {name}: {e.shape[0]} rows, the reference {ref.shape[0]}")
|
||||
bad += 1
|
||||
else:
|
||||
cos = float((e * ref).sum() / np.sqrt((e * e).sum() * (ref * ref).sum()))
|
||||
row = np.linalg.norm(e - ref, axis=1) / np.linalg.norm(ref, axis=1)
|
||||
med, worst = float(np.median(row)), float(row.max())
|
||||
ok = same and cos >= 0.99 and med <= 0.08
|
||||
bad += not ok
|
||||
print(f" {name}: patches {'identical' if same else 'DIFFER'}; rows: cosine {cos:.5f}, "
|
||||
f"per-row relative error median {med:.4f}, largest {worst:.4f} -- "
|
||||
f"{'within' if ok else 'OUTSIDE'}")
|
||||
p0 += n
|
||||
r0 += r
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,7 +23,7 @@ struct Run {
|
||||
* inherited from ctest. */
|
||||
Run fixture(const std::string& args, const std::string& env = "") {
|
||||
const std::string cmd = "env -u RAD_TEST_FILTER -u RAD_TEST_STRICT -u RAD_TEST_LEVEL "
|
||||
"-u RAD_TEST_CPU_BUDGET " + env + " '" RAD_HARNESS_FIXTURE "' " +
|
||||
"-u RAD_TEST_CPU_BUDGET -u RAD_TEST_CPU_BUDGET_SCALE " + env + " '" RAD_HARNESS_FIXTURE "' " +
|
||||
args + " 2>&1";
|
||||
Run r;
|
||||
FILE* p = popen(cmd.c_str(), "r");
|
||||
@@ -194,6 +194,12 @@ TEST(a_binary_over_its_cpu_budget_fails) {
|
||||
CHECK(has(r.out, "slowest: burns_cpu "));
|
||||
r = fixture("passes_one", "RAD_TEST_CPU_BUDGET=60");
|
||||
CHECK_EQ(r.status, 0);
|
||||
/* A slower host scales every budget by one factor. */
|
||||
r = fixture("burns_cpu passes_one", "RAD_TEST_CPU_BUDGET=0.05 RAD_TEST_CPU_BUDGET_SCALE=2");
|
||||
CHECK_EQ(r.status, 1);
|
||||
CHECK(has(r.out, "over its budget of 0.1 s"));
|
||||
r = fixture("burns_cpu passes_one", "RAD_TEST_CPU_BUDGET=0.05 RAD_TEST_CPU_BUDGET_SCALE=100");
|
||||
CHECK_EQ(r.status, 0);
|
||||
}
|
||||
|
||||
/* A command line the harness does not understand is refused rather than read as a filter. */
|
||||
|
||||
@@ -169,8 +169,107 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) {
|
||||
CHECK(s.last().has_neg);
|
||||
}
|
||||
|
||||
/* A model that reads its prompt through a second tokenizer gets the user's prompt as that tokenizer
|
||||
* encodes it, in each branch, and a prompt longer than it reads is refused under `prompt`. A
|
||||
* prompt shorter than the model's minimum after the fixed prefix is padded with its padding token
|
||||
* (an empty prompt is one, and is not turned into " " first). */
|
||||
TEST(a_second_tokenizer_and_a_minimum_prompt_reach_the_generator) {
|
||||
Images s;
|
||||
s.img.inf.aux_tokens = true;
|
||||
s.img.inf.aux_max_tokens = 4;
|
||||
s.img.inf.min_tokens = 2;
|
||||
s.img.inf.pad_token = 9;
|
||||
s.gen({ { "prompt", "ab" }, { "negative_prompt", "c" }, { "true_cfg_scale", 4.0 } });
|
||||
REQUIRE(!s.img.got.empty());
|
||||
CHECK(s.last().pos.aux == std::vector<int32_t>({ 100 + 'a', 100 + 'b', 1 }));
|
||||
CHECK(s.last().neg.aux == std::vector<int32_t>({ 100 + 'c', 1 }));
|
||||
/* "c" is one token after the prefix, padded to two. */
|
||||
const gen::Branch& n = s.last().neg;
|
||||
REQUIRE((int64_t)n.tokens.size() - n.n_drop == 2);
|
||||
CHECK_EQ(n.tokens[(size_t)n.n_drop], (int32_t)'c');
|
||||
CHECK_EQ(n.tokens.back(), (int32_t)9);
|
||||
s.gen({ { "prompt", "" } });
|
||||
const gen::Branch& p = s.last().pos;
|
||||
REQUIRE((int64_t)p.tokens.size() - p.n_drop == 2);
|
||||
CHECK_EQ(p.tokens[(size_t)p.n_drop], (int32_t)9);
|
||||
CHECK(p.aux == std::vector<int32_t>({ 1 }));
|
||||
/* An empty negative prompt stays empty for such a model: all padding. */
|
||||
s.gen({ { "prompt", "x" }, { "negative_prompt", "" }, { "true_cfg_scale", 4.0 } });
|
||||
const gen::Branch& e = s.last().neg;
|
||||
REQUIRE((int64_t)e.tokens.size() - e.n_drop == 2);
|
||||
CHECK_EQ(e.tokens[(size_t)e.n_drop], (int32_t)9);
|
||||
CHECK(e.aux == std::vector<int32_t>({ 1 }));
|
||||
const json longp = s.gen({ { "prompt", "abcd" } }, 400);
|
||||
CHECK_EQ(str_at(longp["error"], "param"), std::string("prompt"));
|
||||
}
|
||||
|
||||
/* A discrete-time model takes `sampler` and `scheduler` by ComfyUI's names, defaulting to its
|
||||
* own, and refuses one it does not serve; a flow-matching model refuses both. A prompt read in
|
||||
* windows reaches the generator cut into runs between their markers, each padded to the window,
|
||||
* after the template's fixed prefix, and a prompt that fills its last window exactly takes no
|
||||
* empty one after it. */
|
||||
TEST(a_discrete_model_takes_its_sampler_and_reads_the_prompt_in_windows) {
|
||||
Images s;
|
||||
const json flow = s.gen({ { "prompt", "x" }, { "sampler", "euler" } }, 400);
|
||||
CHECK_EQ(str_at(flow["error"], "param"), std::string("sampler"));
|
||||
s.img.inf.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
s.img.inf.default_sampler = RAD_GEN_SAMPLER_EULER;
|
||||
s.img.inf.default_scheduler = RAD_GEN_SCHED_NORMAL;
|
||||
s.img.inf.chunk_tokens = 4;
|
||||
s.img.inf.chunk_bos = 2;
|
||||
s.img.inf.chunk_eos = 3;
|
||||
s.img.inf.chunk_pad = 9;
|
||||
s.gen({ { "prompt", "abcdefghij" } });
|
||||
REQUIRE(!s.img.got.empty());
|
||||
CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_EULER);
|
||||
CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_NORMAL);
|
||||
const std::vector<int32_t> want = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3,
|
||||
2, 'e', 'f', 'g', 'h', 3, 2, 'i', 'j', 3, 9, 9 };
|
||||
CHECK(s.last().pos.tokens == want);
|
||||
CHECK_EQ(s.last().pos.n_drop, (int32_t)3);
|
||||
s.gen({ { "prompt", "x" }, { "sampler", "dpmpp_2m" }, { "scheduler", "karras" } });
|
||||
CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_DPMPP_2M);
|
||||
CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_KARRAS);
|
||||
/* A prompt that fills a window takes no second one. */
|
||||
s.gen({ { "prompt", "abcd" } });
|
||||
const std::vector<int32_t> one = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3 };
|
||||
CHECK(s.last().pos.tokens == one);
|
||||
const json bad = s.gen({ { "prompt", "x" }, { "sampler", "euler_ancestral" } }, 400);
|
||||
CHECK_EQ(str_at(bad["error"], "param"), std::string("sampler"));
|
||||
CHECK(bad["error"]["supported"] == json::array({ "euler", "dpmpp_2m" }));
|
||||
const json badk = s.gen({ { "prompt", "x" }, { "scheduler", "ddim_uniform" } }, 400);
|
||||
CHECK_EQ(str_at(badk["error"], "param"), std::string("scheduler"));
|
||||
}
|
||||
|
||||
/* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must
|
||||
* be the first picture's size. */
|
||||
/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2):
|
||||
* a request naming nothing is guided at the card's scale with the model's own empty negative
|
||||
* prompt, handed on as s + 1; `guidance_scale` is the same field as `true_cfg_scale`, 0 turns it
|
||||
* off, and naming both is refused. An RGB model refuses a transparent background. */
|
||||
TEST(guidance_follows_the_model_cards_terms_and_its_default_negative) {
|
||||
Images s;
|
||||
s.img.inf.cfg_original = true;
|
||||
s.img.inf.default_cfg = 4.5;
|
||||
s.img.inf.has_default_negative = true;
|
||||
s.img.inf.default_negative = "";
|
||||
s.img.inf.pixel_channels = 3;
|
||||
s.gen({ { "prompt", "a fox" } });
|
||||
REQUIRE(!s.img.got.empty());
|
||||
CHECK(s.last().has_neg);
|
||||
CHECK_EQ(s.last().cfg, 5.5f);
|
||||
s.gen({ { "prompt", "a fox" }, { "guidance_scale", 2.0 } });
|
||||
CHECK(s.last().has_neg);
|
||||
CHECK_EQ(s.last().cfg, 3.0f);
|
||||
s.gen({ { "prompt", "a fox" }, { "guidance_scale", 0.0 } });
|
||||
CHECK(!s.last().has_neg);
|
||||
const json both = s.gen({ { "prompt", "x" }, { "guidance_scale", 2.0 }, { "true_cfg_scale", 2.0 } },
|
||||
400);
|
||||
CHECK_EQ(str_at(both["error"], "param"), std::string("guidance_scale"));
|
||||
const json alpha = s.gen({ { "prompt", "x" }, { "background", "transparent" } }, 400);
|
||||
CHECK_EQ(str_at(alpha["error"], "param"), std::string("background"));
|
||||
}
|
||||
|
||||
TEST(an_auto_background_follows_the_pictures_alpha) {
|
||||
if (!mm::decoder_available()) return;
|
||||
Images s;
|
||||
|
||||
+4
-3
@@ -1032,8 +1032,9 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) {
|
||||
CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm"));
|
||||
}
|
||||
|
||||
/* Adapters serve the token steps of a model that writes logits: declare refuses a generator, an
|
||||
* embedding model and a program with no logits by name, and lets a text model through. */
|
||||
/* Adapters serve the token steps of a model that writes logits, or a generator that names its
|
||||
* adapter keys: declare refuses a generator that names none, an embedding model and a program with
|
||||
* no logits by name, and lets a text model through. */
|
||||
TEST(declare_refuses_a_model_that_does_not_generate_text) {
|
||||
const RadModelMeta meta = llama_meta();
|
||||
const RadBuildCtx ctx = ctx_for(0, 1);
|
||||
@@ -1044,7 +1045,7 @@ TEST(declare_refuses_a_model_that_does_not_generate_text) {
|
||||
d.cfg = &cfg;
|
||||
d.targets = { "q_proj" };
|
||||
const struct { const char* what; void (*set)(Program&); } kinds[] = {
|
||||
{ "is an image, audio or video generator",
|
||||
{ "declares no adapter key names",
|
||||
[](Program& p) { p.logits_buf = 1; p.generator.layout = 1; } },
|
||||
{ "makes embeddings", [](Program& p) { p.pooled_buf = 1; } },
|
||||
{ "declares no logits", [](Program&) {} },
|
||||
|
||||
+458
-28
@@ -385,6 +385,77 @@ TEST(the_cache_keeps_one_full_length_sequence_even_against_the_expert_floor) {
|
||||
CHECK_EQ(b2.experts, b2.elastic - g.kv_ceiling);
|
||||
}
|
||||
|
||||
/* With a lending cache at its floor, the prefill staging region is paid by expert residency
|
||||
* above the host pool's floor, and never by an expert that has no other home. */
|
||||
TEST(prefill_staging_can_borrow_expert_slack_when_the_cache_is_small) {
|
||||
VramFacts f = big_moe_facts();
|
||||
f.lends = true;
|
||||
f.kv_one = f.kv_ceiling = 64LL << 20;
|
||||
f.expert_floor = 16LL << 30;
|
||||
f.expert_layer_max = 2LL << 30;
|
||||
Config c = derive_config();
|
||||
VramBudget b;
|
||||
CHECK_OK(vram_budget_resolve(c, { f }, &b));
|
||||
CHECK(b.stage > 0);
|
||||
CHECK(b.report.find("out of the experts") != std::string::npos);
|
||||
CHECK_EQ(b.kv, f.kv_one);
|
||||
CHECK(b.experts >= f.expert_floor);
|
||||
CHECK_EQ(b.weights, b.statics + b.experts);
|
||||
CHECK_EQ(b.experts + b.kv + b.stage, b.elastic);
|
||||
|
||||
// With no host-pool slack, staging must not evict an expert that has no other home.
|
||||
f.expert_floor = b.elastic - f.kv_one;
|
||||
Config tight = derive_config();
|
||||
VramBudget no_ring;
|
||||
CHECK_OK(vram_budget_resolve(tight, { f }, &no_ring));
|
||||
CHECK_EQ(no_ring.stage, 0ll);
|
||||
CHECK_EQ(no_ring.kv, f.kv_one);
|
||||
CHECK_EQ(no_ring.experts, f.expert_floor);
|
||||
}
|
||||
|
||||
/* When experts can pay, the staging region leaves the cache at its full coverage. */
|
||||
TEST(prefill_staging_preserves_cache_coverage_when_experts_can_pay) {
|
||||
VramFacts f = big_moe_facts();
|
||||
f.lends = true;
|
||||
f.kv_ceiling = 2LL << 30;
|
||||
f.kv_one = 768LL << 20;
|
||||
f.expert_floor = 16LL << 30;
|
||||
f.expert_layer_max = 2LL << 30;
|
||||
Config c = derive_config();
|
||||
VramBudget b;
|
||||
CHECK_OK(vram_budget_resolve(c, { f }, &b));
|
||||
CHECK(b.stage > 0);
|
||||
CHECK_EQ(b.kv, f.kv_ceiling);
|
||||
CHECK(b.experts >= f.expert_floor);
|
||||
CHECK(b.report.find("out of the experts") != std::string::npos);
|
||||
CHECK_EQ(b.experts + b.kv + b.stage, b.elastic);
|
||||
}
|
||||
|
||||
/* A hybrid model's recurrent and conv slots stay allocated with one request active, so the
|
||||
* one-sequence floor is the inverse of the live plan, not a separate one-sequence plan: that plan
|
||||
* drops the fixed state and falls short of max_ctx. */
|
||||
TEST(hybrid_context_floor_accounts_for_all_configured_state_slots) {
|
||||
Config c = small_config();
|
||||
c.max_seqs = 4;
|
||||
c.max_ctx = 32768;
|
||||
c.checkpoint_slots = 0;
|
||||
auto groups = hybrid_groups();
|
||||
KVManager actual, single;
|
||||
CHECK_OK(actual.plan_groups(groups, c));
|
||||
Config one = c;
|
||||
one.max_seqs = 1;
|
||||
CHECK_OK(single.plan_groups(groups, one));
|
||||
// A one-sequence declaration drops fixed state that the live four-slot plan owns.
|
||||
CHECK(actual.paged_tokens(single.ceiling(c.max_ctx)) < c.max_ctx);
|
||||
constexpr int64_t MiB = 1ll << 20;
|
||||
const int64_t ceiling_mib = (actual.ceiling(c.max_ctx) + MiB - 1) / MiB;
|
||||
const int64_t floor_mib = actual.pool_mib_for_tokens(c.max_ctx, ceiling_mib);
|
||||
CHECK(floor_mib > 0);
|
||||
CHECK(actual.paged_tokens(floor_mib * MiB) >= c.max_ctx);
|
||||
CHECK((floor_mib - 1) * MiB < actual.fixed_bytes() ||
|
||||
actual.paged_tokens((floor_mib - 1) * MiB) < c.max_ctx);
|
||||
}
|
||||
|
||||
TEST(neither_side_is_given_more_than_it_could_use) {
|
||||
/* A model that fits: 4 GiB of experts and a cache that can address 1.2 GiB cannot use a
|
||||
* 32 GiB card, so the remainder is reported unusable rather than allocated to an idle pool. */
|
||||
@@ -1611,8 +1682,9 @@ TEST(checkpoint_retention_is_budgeted_and_keeps_the_tip) {
|
||||
|
||||
auto prompt = tok_run(4242, 16 * 64);
|
||||
const std::vector<BlockHash> hs = chain_of(prompt);
|
||||
/* Eight checkpoints at 64, 128, ... 512 fill the pool exactly. */
|
||||
/* Eight checkpoints at 64, 128, ... 512 fill the pool exactly, one step each. */
|
||||
for (int i = 1; i <= 8; ++i) {
|
||||
f.pc.begin_step();
|
||||
int32_t s = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(1, i * 64, hs[i * 4 - 1], &s));
|
||||
}
|
||||
@@ -1621,6 +1693,7 @@ TEST(checkpoint_retention_is_budgeted_and_keeps_the_tip) {
|
||||
|
||||
/* The ninth forces retention. Geometric backoff over {64..512} keeps 512, 448, 384, 256 and
|
||||
* 64 and releases the rest; the tip survives, as an appending agent transcript needs. */
|
||||
f.pc.begin_step();
|
||||
int32_t s9 = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(1, 9 * 64, hs[9 * 4 - 1], &s9));
|
||||
auto held = f.pc.checkpoints(1);
|
||||
@@ -1768,6 +1841,89 @@ TEST(a_snapshot_handed_out_this_step_is_not_evicted) {
|
||||
CHECK_OK(f.pc.reserve_checkpoint(1, 128, hs[7], &s2));
|
||||
}
|
||||
|
||||
/* A reservation made this step is a save target: the engine copies the state into its slot
|
||||
* after the step, and nothing checks the slot again before that copy. A later reservation in the
|
||||
* same step that finds the store full runs retention over every session, and the policy, placing
|
||||
* its ladder from each session's tip, may release the very slot just handed out -- a second
|
||||
* request's reservation lands on a snapshot a first session already holds (the same prefix, so
|
||||
* the same key), and that snapshot is below the first session's tip. Geometric backoff over
|
||||
* {64..512} releases 192, so the shared reservation is made to land there. The save then faults
|
||||
* ("the store does not hold that slot") and the step loop stops the engine. A reservation keeps
|
||||
* its slot until its commit, or until the next step begins, as a handed-out snapshot does. */
|
||||
TEST(a_reservation_this_step_survives_retention) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8));
|
||||
|
||||
const auto a = tok_run(4242, 16 * 33);
|
||||
publish(f, 1, a, 16 * 32);
|
||||
const std::vector<BlockHash> hs = chain_of(a);
|
||||
std::vector<int32_t> slot_at(9, -1);
|
||||
for (int i = 1; i <= 8; ++i) slot_at[(size_t)i] = ckpt_at(f, 1, hs, i * 64);
|
||||
CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll);
|
||||
|
||||
/* Session 2 prefilling the same prompt reserves at 192: the same key, so session 1's slot. */
|
||||
f.pc.begin_step();
|
||||
int32_t s2 = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(2, 192, hs[11], &s2));
|
||||
CHECK_EQ(s2, slot_at[3]);
|
||||
|
||||
/* The same step's next reservation finds the store full: retention runs over session 1,
|
||||
* whose ladder does not keep 192. */
|
||||
BlockHash other = hs[3];
|
||||
other.lo ^= 0x5eedull;
|
||||
int32_t s3 = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(3, 64, other, &s3));
|
||||
CHECK(s3 >= 0);
|
||||
CHECK(s3 != s2);
|
||||
CHECK(f.kv.checkpoint_held(s2));
|
||||
bool kept_192 = false;
|
||||
for (int64_t p : f.pc.checkpoints(1)) if (p == 192) kept_192 = true;
|
||||
CHECK(kept_192);
|
||||
CHECK(f.pc.stats().ckpt_retired >= 1ll);
|
||||
|
||||
/* The next step may release it again: an uncommitted reservation whose save was skipped (its
|
||||
* request gone) must not hold a slot for good. (A committed one is a snapshot like any other
|
||||
* from the commit on, tested below.) */
|
||||
f.pc.begin_step();
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
BlockHash fresh = hs[3];
|
||||
fresh.lo ^= 0x1000ull + (uint64_t)i;
|
||||
int32_t s = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(10 + (uint64_t)i, 64, fresh, &s));
|
||||
}
|
||||
bool still_192 = false;
|
||||
for (int64_t p : f.pc.checkpoints(1)) if (p == 192) still_192 = true;
|
||||
CHECK(!still_192);
|
||||
}
|
||||
|
||||
/* Eviction after retention skips it too. With one slot, the reservation is the only candidate,
|
||||
* so a second reservation in the same step is refused instead of taking it; once committed, it
|
||||
* is a snapshot like any other and the next step's reservation may take the slot. */
|
||||
TEST(a_reservation_this_step_is_not_evicted) {
|
||||
Fixture f;
|
||||
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/1));
|
||||
const auto a = tok_run(5151, 16 * 9);
|
||||
const std::vector<BlockHash> hs = chain_of(a);
|
||||
|
||||
f.pc.begin_step();
|
||||
int32_t s1 = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(1, 64, hs[3], &s1));
|
||||
CHECK(s1 >= 0);
|
||||
|
||||
BlockHash other = hs[3];
|
||||
other.lo ^= 0x5eedull;
|
||||
int32_t s2 = -1;
|
||||
CHECK_EQ(f.pc.reserve_checkpoint(2, 64, other, &s2), RAD_E_FULL);
|
||||
CHECK(f.kv.checkpoint_held(s1));
|
||||
CHECK_EQ(f.pc.stats().ckpt_evictions, 0ll);
|
||||
CHECK_EQ(f.pc.stats().ckpt_refused, 1ll);
|
||||
|
||||
f.pc.commit_checkpoint(hs[3]);
|
||||
f.pc.begin_step();
|
||||
CHECK_OK(f.pc.reserve_checkpoint(2, 64, other, &s2));
|
||||
CHECK_EQ(s2, s1);
|
||||
}
|
||||
|
||||
TEST(a_dead_sessions_tip_is_evictable_so_the_slot_pool_cannot_wedge) {
|
||||
/* One checkpoint each from more distinct sessions than slots, each its session's tip. If tips
|
||||
* were unevictable the pool would wedge and every later request get RAD_E_FULL. A session is a
|
||||
@@ -1790,7 +1946,8 @@ TEST(a_dead_sessions_tip_is_evictable_so_the_slot_pool_cannot_wedge) {
|
||||
}
|
||||
CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll);
|
||||
|
||||
/* The ninth session is served by retiring the least recently used tip. */
|
||||
/* The ninth session, a step later, is served by retiring the least recently used tip. */
|
||||
f.pc.begin_step();
|
||||
BlockHash fresh = hs[3];
|
||||
fresh.lo ^= 0x5eedull;
|
||||
int32_t s9 = -1;
|
||||
@@ -1813,6 +1970,7 @@ TEST(a_sessions_index_entry_does_not_outlive_its_last_snapshot) {
|
||||
auto prompt = tok_run(313, 16 * 32);
|
||||
const std::vector<BlockHash> hs = chain_of(prompt);
|
||||
for (int i = 1; i <= 5; ++i) {
|
||||
f.pc.begin_step();
|
||||
int32_t s = -1;
|
||||
CHECK_OK(f.pc.reserve_checkpoint(7, i * 64, hs[i * 4 - 1], &s));
|
||||
}
|
||||
@@ -1821,8 +1979,10 @@ TEST(a_sessions_index_entry_does_not_outlive_its_last_snapshot) {
|
||||
CHECK_EQ((long long)f.pc.checkpoints(7).size(), 2ll);
|
||||
CHECK_EQ(f.pc.sessions_tracked(), 1ll);
|
||||
|
||||
/* Four more sessions, one snapshot each: session 7's tip is the LRU and is evicted. */
|
||||
/* Four more sessions, one snapshot each, a step apart: session 7's tip is the LRU and is
|
||||
* evicted. */
|
||||
for (uint64_t sess = 20; sess < 24; ++sess) {
|
||||
f.pc.begin_step();
|
||||
BlockHash h = hs[9];
|
||||
h.lo ^= sess;
|
||||
int32_t s = -1;
|
||||
@@ -3143,8 +3303,8 @@ struct TierFixture {
|
||||
Fixture f;
|
||||
IdleTiers t;
|
||||
int64_t per = 0;
|
||||
int build() {
|
||||
int s = f.build(/*with_linear=*/false, /*ckpt_slots=*/0);
|
||||
int build(bool with_linear = false, int64_t ckpt_slots = 0) {
|
||||
int s = f.build(with_linear, ckpt_slots);
|
||||
if (s < 0) return s;
|
||||
s = t.configure(tier_config(1 << 20, 1024));
|
||||
if (s < 0) return s;
|
||||
@@ -3770,15 +3930,19 @@ static unsigned char pat(int rank, int64_t layer, int32_t block, int64_t i) {
|
||||
return (unsigned char)(z ^ (z >> 31));
|
||||
}
|
||||
|
||||
static void fill(Fixture& f, int rank) {
|
||||
/* `alike`: a replicated group holds rank 0's bytes on every rank, as rad_kv_group_replicated
|
||||
* promises. Without it the ranks differ there on purpose, so a follower restored from its own
|
||||
* gather rather than the leader's window would show. */
|
||||
static void fill(Fixture& f, int rank, bool alike = false) {
|
||||
for (int32_t g : f.pc.cached_groups()) {
|
||||
const KVGroupPlan* p = f.kv.plan(g);
|
||||
if (p->zero) continue;
|
||||
const int r = alike && p->replicated ? 0 : rank;
|
||||
const int64_t frag = p->layer_bytes_per_block();
|
||||
for (int64_t l = 0; l < p->n_layers; ++l)
|
||||
for (int32_t b = 0; b < (int32_t)p->n_blocks; ++b) {
|
||||
unsigned char* row = (unsigned char*)p->base + l * p->layer_stride() + b * frag;
|
||||
for (int64_t i = 0; i < frag; ++i) row[i] = pat(rank, g * 16 + l, b, i);
|
||||
for (int64_t i = 0; i < frag; ++i) row[i] = pat(r, g * 16 + l, b, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3793,7 +3957,8 @@ static void scribble(Fixture& f) {
|
||||
}
|
||||
|
||||
/* The number of entries whose blocks in `now` hold, in every cached group and layer, exactly what
|
||||
* their blocks in `was` held before the move. */
|
||||
* their blocks in `was` held before the move: this rank's own bytes, and for a replicated group
|
||||
* rank 0's, the one copy the slot holds. */
|
||||
static int64_t same_bytes(Fixture& f, int rank, const std::vector<std::vector<int32_t>>& was,
|
||||
const std::vector<std::vector<int32_t>>& now) {
|
||||
const std::vector<int32_t>& cg = f.pc.cached_groups();
|
||||
@@ -3803,12 +3968,13 @@ static int64_t same_bytes(Fixture& f, int rank, const std::vector<std::vector<in
|
||||
for (size_t gi = 0; gi < cg.size() && ok; ++gi) {
|
||||
const KVGroupPlan* p = f.kv.plan(cg[gi]);
|
||||
if (p->zero) continue;
|
||||
const int r = p->replicated ? 0 : rank;
|
||||
const int64_t frag = p->layer_bytes_per_block();
|
||||
for (int64_t l = 0; l < p->n_layers && ok; ++l) {
|
||||
const unsigned char* row =
|
||||
(const unsigned char*)p->base + l * p->layer_stride() + now[gi][k] * frag;
|
||||
for (int64_t i = 0; i < frag && ok; ++i)
|
||||
ok = row[i] == pat(rank, cg[gi] * 16 + l, was[gi][k], i);
|
||||
ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][k], i);
|
||||
}
|
||||
}
|
||||
good += ok;
|
||||
@@ -3845,8 +4011,24 @@ static std::vector<KVGroupInfo> two_paged_groups() {
|
||||
|
||||
/* `zero_last`: the last rank keeps no attention cache (rad_kv_group_zero), so its window of a slot
|
||||
* is the narrower group alone and the windows are unequal; every rank still takes part in every
|
||||
* job. */
|
||||
static void run_transfer(int world, bool fragment, bool zero_last = false) {
|
||||
* job. `replicated`: the attention group is the same on every rank (rad_kv_group_replicated), so
|
||||
* the slot holds it once at its front, written by rank 0 and read back by all. `verify`: under
|
||||
* RADIANCE_DEBUG_TIER_VERIFY each follower's gather of the replicated group is compared with the
|
||||
* leader's window; `alike` fills the replicated group the same on every rank, as the flag
|
||||
* promises, so the comparison passes, and without it every entry is caught. */
|
||||
struct TransferCase {
|
||||
int world = 1;
|
||||
bool fragment = false;
|
||||
bool zero_last = false;
|
||||
bool replicated = false;
|
||||
bool alike = false;
|
||||
bool verify = false;
|
||||
};
|
||||
static void run_transfer(const TransferCase& tc) {
|
||||
const int world = tc.world;
|
||||
const bool fragment = tc.fragment, zero_last = tc.zero_last;
|
||||
if (tc.verify) setenv("RADIANCE_DEBUG_TIER_VERIFY", "1", 1);
|
||||
else unsetenv("RADIANCE_DEBUG_TIER_VERIFY");
|
||||
/* Host backend only: the stand-in kernels copy rows on the CPU, where host-backend "device"
|
||||
* memory lives; on a card the staging buffer is VRAM and production kernels apply. */
|
||||
if (!device_is_host()) {
|
||||
@@ -3863,20 +4045,33 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) {
|
||||
fx.push_back(std::make_unique<Fixture>());
|
||||
fx.back()->cfg.checkpoint_slots = 0;
|
||||
std::vector<KVGroupInfo> groups = two_paged_groups();
|
||||
if (zero_last && r == world - 1) groups[1].zero = true;
|
||||
/* The zero group is the one not replicated: attention, or the key cache beside a
|
||||
* replicated attention group, which leaves that rank's own window empty. */
|
||||
if (zero_last && r == world - 1) groups[tc.replicated ? 2 : 1].zero = true;
|
||||
if (tc.replicated) groups[1].replicated = true;
|
||||
REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK);
|
||||
}
|
||||
Fixture& f = *fx[0];
|
||||
const std::vector<int32_t>& cg = f.pc.cached_groups();
|
||||
REQUIRE_EQ(cg.size(), 2u);
|
||||
/* A slot is the sum of the ranks' entries, each rank's window following the previous ones
|
||||
* (Engine::configure_kv). */
|
||||
std::vector<int64_t> win_off((size_t)world, 0);
|
||||
int64_t slot = 0;
|
||||
for (int r = 0; r < world; ++r) {
|
||||
win_off[(size_t)r] = slot;
|
||||
for (int32_t g : cg) slot += fx[(size_t)r]->kv.plan(g)->bytes_per_block;
|
||||
}
|
||||
/* The slot as bringup lays it out: a replicated group once at the front, then each rank's own
|
||||
* window following the previous ones. Checked against the plain sums here. */
|
||||
std::vector<const KVManager*> kvs;
|
||||
for (auto& fp : fx) kvs.push_back(&fp->kv);
|
||||
TierExec::SlotLayout L;
|
||||
REQUIRE_EQ(TierExec::slot_layout(kvs, cg, &L), RAD_OK);
|
||||
const int64_t attn = f.kv.plan(cg[0])->bytes_per_block;
|
||||
int64_t sum = 0;
|
||||
for (int r = 0; r < world; ++r)
|
||||
for (int32_t g : cg) sum += fx[(size_t)r]->kv.plan(g)->bytes_per_block;
|
||||
CHECK_EQ(L.rep_bytes, tc.replicated ? attn : 0);
|
||||
CHECK_EQ(L.slot_bytes, tc.replicated ? sum - (world - 1) * attn : sum);
|
||||
CHECK_EQ(L.own_off[0], L.rep_bytes);
|
||||
for (int r = 1; r < world; ++r)
|
||||
CHECK_EQ(L.own_off[(size_t)r], L.own_off[(size_t)r - 1] + L.own_bytes[(size_t)r - 1]);
|
||||
CHECK_EQ(L.own_off[(size_t)world - 1] + L.own_bytes[(size_t)world - 1], L.slot_bytes);
|
||||
const std::vector<int64_t>& win_off = L.own_off;
|
||||
const int64_t slot = L.slot_bytes;
|
||||
|
||||
/* Forty slots. Fragmented, every other one is taken and the copy goes out as twenty runs of
|
||||
* one; whole, as one run of twenty, where a rank's pitch through the shared slots decides where
|
||||
@@ -3915,7 +4110,7 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) {
|
||||
REQUIRE_EQ(f.pc.lookup(prompt, {}, &hit).n_attn_tokens, 320);
|
||||
const std::vector<std::vector<int32_t>> was = hit;
|
||||
CHECK(was[0][0] != was[1][0]);
|
||||
for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r);
|
||||
for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r, tc.alike);
|
||||
|
||||
/* ---- out ---- */
|
||||
std::vector<TierJob> jobs;
|
||||
@@ -3929,6 +4124,22 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) {
|
||||
usleep(100);
|
||||
CHECK_EQ(st, 1);
|
||||
}
|
||||
/* Every rank landed: the follower's hash of the replicated group against the leader's window
|
||||
* (Engine::tier_tick's order). Bytes out: a follower writes only its own window. */
|
||||
if (tc.verify && tc.replicated) {
|
||||
for (int r = 1; r < world; ++r)
|
||||
for (const TierJob& j : jobs) {
|
||||
uint64_t sum = 0;
|
||||
REQUIRE(x[(size_t)r]->take_replicated_sum(j.key, &sum));
|
||||
x[0]->verify_replicated(j, r, sum);
|
||||
CHECK(!x[(size_t)r]->take_replicated_sum(j.key, &sum));
|
||||
}
|
||||
CHECK_EQ(x[0]->stats().rep_checked, 20ll * (world - 1));
|
||||
CHECK_EQ(x[0]->stats().rep_mismatch, tc.alike ? 0ll : 20ll * (world - 1));
|
||||
}
|
||||
for (int r = 0; r < world; ++r)
|
||||
CHECK_EQ(x[(size_t)r]->stats().bytes_out,
|
||||
20 * (r == 0 ? L.rep_bytes + L.own_bytes[0] : L.own_bytes[(size_t)r]));
|
||||
x[0]->report_pass(jobs, std::vector<char>(jobs.size(), 1), 0);
|
||||
CHECK_EQ(t.stats().to_host, 20);
|
||||
|
||||
@@ -3975,19 +4186,67 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) {
|
||||
for (auto& xp : x) xp->close();
|
||||
for (RadStream s : compute) rad_stream_destroy(s);
|
||||
f.pc.set_tiers(nullptr);
|
||||
unsetenv("RADIANCE_DEBUG_TIER_VERIFY");
|
||||
}
|
||||
|
||||
TEST(a_conversation_restored_from_host_is_byte_identical_in_new_blocks) {
|
||||
run_transfer(1, /*fragment=*/false);
|
||||
run_transfer(1, /*fragment=*/true);
|
||||
run_transfer({ 1, /*fragment=*/false });
|
||||
run_transfer({ 1, /*fragment=*/true });
|
||||
}
|
||||
TEST(each_rank_restores_its_own_window_of_a_shared_slot) {
|
||||
run_transfer(2, /*fragment=*/false);
|
||||
run_transfer(2, /*fragment=*/true);
|
||||
run_transfer({ 2, /*fragment=*/false });
|
||||
run_transfer({ 2, /*fragment=*/true });
|
||||
}
|
||||
TEST(a_rank_with_a_zero_group_moves_only_its_own_groups) {
|
||||
run_transfer(3, /*fragment=*/false, /*zero_last=*/true);
|
||||
run_transfer(3, /*fragment=*/true, /*zero_last=*/true);
|
||||
run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true });
|
||||
run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true });
|
||||
}
|
||||
/* The replicated group is in the slot once: the leader writes it, every rank reads it back
|
||||
* beside its own shard of the other group, and the slot is smaller by (world - 1) copies. At one
|
||||
* rank nothing changes but the layout's bookkeeping. The ranks' copies differ on purpose, so the
|
||||
* bytes a follower gets back are provably the leader's. */
|
||||
TEST(a_replicated_group_is_held_once_a_slot_and_restored_on_every_rank) {
|
||||
for (int world : { 1, 2, 8 }) {
|
||||
run_transfer({ world, /*fragment=*/false, false, /*replicated=*/true });
|
||||
run_transfer({ world, /*fragment=*/true, false, /*replicated=*/true });
|
||||
}
|
||||
}
|
||||
/* A replicated group beside a zero one: the last rank's own window is empty, so it writes nothing
|
||||
* on a copy out and reads the replicated window alone on a restore. */
|
||||
TEST(a_replicated_group_beside_a_zero_rank_keeps_the_windows_apart) {
|
||||
run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true, /*replicated=*/true });
|
||||
run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true, /*replicated=*/true });
|
||||
}
|
||||
/* RADIANCE_DEBUG_TIER_VERIFY: a follower hashes the replicated bytes it would have written and
|
||||
* the leader compares them with its window. Alike, nothing is reported (seven followers at eight
|
||||
* ranks); differing, every entry, which the two-rank arm logs twenty times. */
|
||||
TEST(tier_verify_catches_a_follower_whose_replicated_group_differs) {
|
||||
run_transfer({ 2, /*fragment=*/false, false, /*replicated=*/true, /*alike=*/true, /*verify=*/true });
|
||||
run_transfer({ 8, /*fragment=*/true, false, /*replicated=*/true, /*alike=*/true, /*verify=*/true });
|
||||
run_transfer({ 2, /*fragment=*/true, false, /*replicated=*/true, /*alike=*/false, /*verify=*/true });
|
||||
}
|
||||
/* The flag must agree across the ranks: one rank's replicated group that another rank declared
|
||||
* zero or did not declare replicated has no one window every rank can read, so bringup stops. */
|
||||
TEST(a_group_replicated_on_one_rank_only_is_refused_by_the_slot_layout) {
|
||||
if (!device_is_host()) {
|
||||
std::printf(" SKIP the tier layout fixture needs the host backend\n");
|
||||
return;
|
||||
}
|
||||
for (int bad : { 0, 1 }) {
|
||||
std::vector<std::unique_ptr<Fixture>> fx;
|
||||
for (int r = 0; r < 2; ++r) {
|
||||
fx.push_back(std::make_unique<Fixture>());
|
||||
fx.back()->cfg.checkpoint_slots = 0;
|
||||
std::vector<KVGroupInfo> groups = two_paged_groups();
|
||||
groups[1].replicated = r == 0 || bad == 1;
|
||||
if (bad == 1 && r == 1) groups[1].zero = true;
|
||||
REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK);
|
||||
}
|
||||
std::vector<const KVManager*> kvs;
|
||||
for (auto& fp : fx) kvs.push_back(&fp->kv);
|
||||
TierExec::SlotLayout L;
|
||||
CHECK_EQ(TierExec::slot_layout(kvs, fx[0]->pc.cached_groups(), &L), RAD_E_STATE);
|
||||
}
|
||||
}
|
||||
|
||||
/* With speculation each sequence has two physical state slots while the free list counts logical
|
||||
@@ -5929,6 +6188,177 @@ TEST(the_cache_tiers_and_pool_agree_over_random_interleavings) {
|
||||
CHECK_EQ(run.x.t.arena().used_slots(), 0ll);
|
||||
}
|
||||
|
||||
/* ================================================================== a restore makes room
|
||||
*
|
||||
* A conversation whose blocks went to the host tier comes back whole on its next turn, when the
|
||||
* pool can be made to hold it. The reserve's trim leaves a quarter of the pool free after every
|
||||
* publish; a restore larger than that gives up VRAM copies other idle conversations keep on the
|
||||
* host as well, the same way pressure does, rather than stopping where the free list ends. These
|
||||
* drive the engine's restore against the real cache, tiers and manager, with no bytes moving.
|
||||
*/
|
||||
|
||||
/* The engine's restore (the binding's restore_fn) without the transfer: which entries come back,
|
||||
* into which blocks, and what the tiers and the cache are told. Returns how many came back. */
|
||||
static int64_t engine_restore(TierFixture& x, PCBinding<PrefixCache>& b, const Request& r) {
|
||||
const std::vector<BlockHash> want = b.restore_plan(r, 0);
|
||||
std::vector<TierJob> jobs;
|
||||
for (const BlockHash& h : want) {
|
||||
TierJob j;
|
||||
if (!x.t.plan_promote(h, &j)) break;
|
||||
jobs.push_back(std::move(j));
|
||||
}
|
||||
std::vector<int32_t> ids;
|
||||
const int64_t m = x.f.kv.reserve_blocks(G_FULL, (int64_t)jobs.size(), &ids);
|
||||
int64_t back = 0;
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
const bool ok = (int64_t)i < m;
|
||||
j.started = ok;
|
||||
j.blocks.clear();
|
||||
if (ok) j.blocks.push_back(ids[i]);
|
||||
x.t.report(j, ok, rad_mono_ns());
|
||||
if (ok) { CHECK_OK(x.f.pc.rebind(j.key, j.blocks)); ++back; }
|
||||
}
|
||||
return back;
|
||||
}
|
||||
|
||||
/* Two conversations of 0.6 of the pool each, as the scheduler leaves them: A published and copied
|
||||
* to the host, B admitted by giving up A's VRAM under pressure, published, and the reserve's trim
|
||||
* run while B's sequence still holds its blocks (Scheduler::close_request publishes before it
|
||||
* frees). A ends up mostly on the host with its first blocks still in VRAM. `b_live` keeps B's
|
||||
* sequence running; otherwise it ends with no host copy yet. */
|
||||
struct TwoSessions {
|
||||
int64_t n = 0; /* blocks each conversation published */
|
||||
std::vector<int32_t> a, b; /* prompts that hit the whole of each */
|
||||
std::vector<BlockHash> ha;
|
||||
};
|
||||
static TwoSessions two_sessions(TierFixture& x, bool b_live, bool a_snapshots) {
|
||||
TwoSessions s;
|
||||
const int64_t total = x.f.kv.total_blocks(G_FULL);
|
||||
s.n = (total * 3 / 5) & ~(int64_t)3; /* on the 64-token checkpoint interval */
|
||||
CHECK(2 * s.n <= x.t.arena().capacity());
|
||||
s.a = tok_run(100000, (int)(s.n * 16 + 16));
|
||||
s.b = tok_run(900000, (int)(s.n * 16 + 16));
|
||||
s.ha = chain_of(s.a);
|
||||
|
||||
publish(x.f, 1, s.a, s.n * 16);
|
||||
if (a_snapshots) {
|
||||
/* A snapshot on every interval, retention after each, as a long prefill leaves them. */
|
||||
for (int64_t pos = 64; pos <= s.n * 16; pos += 64) {
|
||||
x.f.pc.begin_step();
|
||||
ckpt_at(x.f, 1, s.ha, pos);
|
||||
x.f.pc.retain(1);
|
||||
}
|
||||
x.f.pc.begin_step();
|
||||
}
|
||||
x.f.kv.free_sequence(1);
|
||||
copy_now(x.t);
|
||||
|
||||
const int64_t room = total - x.f.kv.held_blocks(G_FULL);
|
||||
CHECK_EQ(x.f.pc.trim(s.n + 1 - room), s.n + 1 - room);
|
||||
publish(x.f, 2, s.b, s.n * 16);
|
||||
const int64_t short_by = total / 4 - (total - x.f.kv.held_blocks(G_FULL));
|
||||
if (short_by > 0) (void)x.f.pc.trim(short_by);
|
||||
if (!b_live) x.f.kv.free_sequence(2);
|
||||
return s;
|
||||
}
|
||||
|
||||
TEST(a_restore_gives_up_other_clean_copies_to_bring_the_whole_chain_back) {
|
||||
TierFixture x;
|
||||
CHECK_OK(x.build());
|
||||
const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/false);
|
||||
const int64_t off = (int64_t)x.f.pc.restorable_from(s.a, {}).size();
|
||||
const int64_t free_now = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL);
|
||||
REQUIRE(off > free_now); /* the free list alone cannot hold it */
|
||||
const int64_t evictions = x.f.pc.stats().evictions;
|
||||
|
||||
PCBinding<PrefixCache> b(&x.f.pc);
|
||||
int flushes = 0;
|
||||
b.flush_fn = [&]() { ++flushes; return !copy_now(x.t).empty(); };
|
||||
CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), off);
|
||||
CHECK_EQ(x.f.pc.lookup(s.a, {}).n_attn_tokens, (int32_t)(s.n * 16));
|
||||
/* B had no host copy yet: its copies were landed first, then its VRAM went. Nothing lost. */
|
||||
CHECK_EQ(flushes, 1);
|
||||
CHECK_EQ(x.f.pc.stats().evictions, evictions);
|
||||
CHECK_EQ(x.f.pc.size(), 2 * s.n);
|
||||
CHECK_EQ((int64_t)x.f.pc.restorable_from(s.b, {}).size(), 2 * s.n - x.f.pc.resident());
|
||||
CHECK_EQ(x.f.pc.stats().restore_cuts, 0ll);
|
||||
}
|
||||
|
||||
/* With recurrent state the hit resumes at the deepest snapshot the restored prefix reaches. Cut
|
||||
* at the free list, that is somewhere down the retention ladder, far below the tip. */
|
||||
TEST(a_restored_hybrid_conversation_resumes_at_its_tip_snapshot) {
|
||||
TierFixture x;
|
||||
CHECK_OK(x.build(/*with_linear=*/true, /*ckpt_slots=*/32));
|
||||
x.f.pc.set_policy(std::make_unique<GeometricBackoff>(64));
|
||||
const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/true);
|
||||
REQUIRE_EQ(x.f.pc.checkpoints(1).back(), s.n * 16);
|
||||
|
||||
PCBinding<PrefixCache> b(&x.f.pc);
|
||||
b.flush_fn = [&]() { return !copy_now(x.t).empty(); };
|
||||
(void)engine_restore(x, b, turn(3, s.a, {}));
|
||||
const CacheHit hit = x.f.pc.lookup(s.a, {});
|
||||
CHECK_EQ(hit.n_attn_tokens, (int32_t)(s.n * 16));
|
||||
CHECK_EQ(hit.n_linear_tokens, (int32_t)(s.n * 16));
|
||||
CHECK_EQ(x.f.pc.stats().restore_cuts, 0ll);
|
||||
}
|
||||
|
||||
/* When the pool cannot be made to hold the chain, what comes back ends at a snapshot: blocks past
|
||||
* the deepest snapshot the shorter prefix reaches would be restored for nothing. Making room
|
||||
* never takes the conversation's own blocks, which would only have to come back too, nor a chain
|
||||
* a running sequence reads, which frees nothing. */
|
||||
TEST(a_restore_the_pool_cannot_hold_stops_at_a_snapshot_and_spares_its_own_chain) {
|
||||
TierFixture x;
|
||||
CHECK_OK(x.build(/*with_linear=*/true, /*ckpt_slots=*/32));
|
||||
x.f.pc.set_policy(std::make_unique<GeometricBackoff>(64));
|
||||
const TwoSessions s = two_sessions(x, /*b_live=*/true, /*a_snapshots=*/true);
|
||||
const int64_t off = (int64_t)x.f.pc.restorable_from(s.a, {}).size();
|
||||
const int64_t resident = s.n - off; /* A's first blocks, still in VRAM */
|
||||
const int64_t room = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL);
|
||||
REQUIRE(resident > 0);
|
||||
REQUIRE(room < off);
|
||||
/* The deepest snapshot the prefix reaches with `room` more blocks. */
|
||||
int64_t snap = 0;
|
||||
for (int64_t p : x.f.pc.checkpoints(1))
|
||||
if (p <= (resident + room) * 16) snap = p;
|
||||
REQUIRE(snap > 0);
|
||||
const int64_t drops = x.f.pc.stats().drops;
|
||||
|
||||
PCBinding<PrefixCache> b(&x.f.pc);
|
||||
b.flush_fn = [&]() { return !copy_now(x.t).empty(); };
|
||||
const int64_t back = engine_restore(x, b, turn(3, s.a, {}));
|
||||
CHECK_EQ(back, std::max<int64_t>(0, snap / 16 - resident));
|
||||
CHECK_EQ(x.f.pc.stats().drops, drops); /* no VRAM copy given up: A's own, or B's */
|
||||
const CacheHit hit = x.f.pc.lookup(s.a, {});
|
||||
CHECK_EQ(hit.n_linear_tokens, (int32_t)snap);
|
||||
CHECK_EQ(hit.n_attn_tokens, (int32_t)std::max<int64_t>(snap, resident * 16));
|
||||
CHECK_EQ(x.f.pc.lookup(s.b, {}).n_attn_tokens, (int32_t)(s.n * 16));
|
||||
CHECK_EQ(x.f.pc.stats().restore_cuts, 1ll);
|
||||
}
|
||||
|
||||
/* A chain another waiting request holds is kept too: that request restored it and was refused,
|
||||
* and taking it would only have its next attempt restore it again. */
|
||||
TEST(a_restore_does_not_take_a_chain_a_waiting_request_holds) {
|
||||
TierFixture x;
|
||||
CHECK_OK(x.build());
|
||||
const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/false);
|
||||
copy_now(x.t); /* B is clean, so a trim could take it */
|
||||
x.f.pc.hold(9, s.b, {});
|
||||
const int64_t room = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL);
|
||||
const int64_t drops = x.f.pc.stats().drops;
|
||||
|
||||
PCBinding<PrefixCache> b(&x.f.pc);
|
||||
CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), room);
|
||||
CHECK_EQ(x.f.pc.stats().drops, drops);
|
||||
CHECK_EQ(x.f.pc.lookup(s.b, {}).n_attn_tokens, (int32_t)(s.n * 16));
|
||||
CHECK_EQ(x.f.pc.stats().restore_cuts, 1ll);
|
||||
|
||||
x.f.pc.release(9);
|
||||
const int64_t rest = (int64_t)x.f.pc.restorable_from(s.a, {}).size();
|
||||
CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), rest);
|
||||
CHECK_EQ(x.f.pc.lookup(s.a, {}).n_attn_tokens, (int32_t)(s.n * 16));
|
||||
}
|
||||
|
||||
/* Tools and tests build and tear down the tier executors and pools repeatedly, and on a card every
|
||||
* event is a hardware resource and every committed byte VRAM. A two-rank transfer pass gives back
|
||||
* every event and device byte it took. */
|
||||
@@ -5937,7 +6367,7 @@ TEST(a_tier_transfer_gives_back_every_event_and_device_byte) {
|
||||
const int64_t events0 = rad_dev_live_events();
|
||||
int64_t vram0 = 0, vram1 = 0;
|
||||
CHECK_OK(dev_vram_used(0, &vram0));
|
||||
run_transfer(2, /*fragment=*/true);
|
||||
run_transfer({ 2, /*fragment=*/true });
|
||||
CHECK_EQ(rad_dev_live_events(), events0);
|
||||
CHECK_OK(dev_vram_used(0, &vram1));
|
||||
CHECK_EQ(vram1, vram0);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Writes tests/precompiled_golden.h: expected outputs for precompiled_test.cpp.
|
||||
|
||||
- Unicode 16.0.0's GraphemeBreakTest.txt cases, each a codepoint sequence and the boundaries
|
||||
UAX #29 puts in it (core/text/tokenizer_grapheme.h's grapheme_end);
|
||||
- a small SentencePiece character map and what HuggingFace `tokenizers`' Precompiled normaliser
|
||||
makes of a set of strings through it, clusters that map whole and clusters that do not among
|
||||
them (PrecompiledMap::normalize).
|
||||
|
||||
The map below was built with sentencepiece 0.2 from the rules
|
||||
A -> a, U+FF21 -> A, U+FF41 -> a, e U+0301 -> U+00E9, LF -> space, U+2160 -> I
|
||||
and is kept as base64 so regenerating needs only `tokenizers` (0.23.3 produced the current file):
|
||||
|
||||
python3 tests/mk_precompiled_goldens.py GraphemeBreakTest.txt > tests/precompiled_golden.h
|
||||
"""
|
||||
import base64
|
||||
import sys
|
||||
|
||||
import tokenizers
|
||||
from tokenizers import normalizers
|
||||
|
||||
CHARSMAP = (
|
||||
"AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAA"
|
||||
"AAEAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAj"
|
||||
"AAAAIgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAA"
|
||||
"A1AAAANAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQA"
|
||||
"AABHAAAARgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAF"
|
||||
"YAAABZAAAAWAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAA"
|
||||
"AGgAAABrAAAAagAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAew"
|
||||
"AAAHoAAAB9AAAAfAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAA"
|
||||
"jQAAAIwAAACPAAAAjgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAA"
|
||||
"AAnwAAAJ4AAAChAAAAoAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACu"
|
||||
"AAAAsQAAALAAAACzAAAAsgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAA"
|
||||
"DAAAAAwwAAAMIAAADFAAAAxAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMA"
|
||||
"AADSAAAA1QAAANQAAADXAAAA1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO"
|
||||
"9IAQDkAAAA5wAAAOYAAADpAAAA4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAA"
|
||||
"APcAAAD2AAAA+QAAAPgAAAD7AAAA+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA=="
|
||||
)
|
||||
|
||||
INPUTS = [
|
||||
"", "plain ascii", "A big Apple", "Abc a", "line one\nline two\n",
|
||||
"café", "éé", "Áx", "Á", "Ⅰ Ⅰ́",
|
||||
"é vs é", "1️⃣ keycap", "\U0001F469\U0001F4BB",
|
||||
"\U0001F1EF\U0001F1F5\U0001F1FA", "각 jamo", "\r\nCRLF\r\n",
|
||||
"क्ष conjunct", "ab", "tab\there", "กำ thai",
|
||||
"ẍ̈̈̈", "Ä̈",
|
||||
]
|
||||
|
||||
|
||||
def cstr(s):
|
||||
out = '"'
|
||||
prev_hex = False
|
||||
for b in s.encode("utf-8"):
|
||||
c = chr(b)
|
||||
if c == '"':
|
||||
out += '\\"'; prev_hex = False
|
||||
elif c == "\\":
|
||||
out += "\\\\"; prev_hex = False
|
||||
elif 0x20 <= b < 0x7F:
|
||||
if prev_hex and c in "0123456789abcdefABCDEF":
|
||||
out += '" "'
|
||||
out += c; prev_hex = False
|
||||
else:
|
||||
out += "\\x%02x" % b; prev_hex = True
|
||||
return out + '"'
|
||||
|
||||
|
||||
def grapheme_cases(path):
|
||||
"""(codepoints, bitmask of the positions a cluster starts at, beyond the first)."""
|
||||
cases = []
|
||||
for line in open(path, encoding="utf-8"):
|
||||
line = line.split("#", 1)[0].strip()
|
||||
if not line:
|
||||
continue
|
||||
toks = line.split()
|
||||
cps, mask = [], 0
|
||||
for t in toks[1:-1]:
|
||||
if t in ("÷", "×"):
|
||||
if t == "÷":
|
||||
mask |= 1 << len(cps)
|
||||
continue
|
||||
cps.append(int(t, 16))
|
||||
cases.append((cps, mask))
|
||||
return cases
|
||||
|
||||
|
||||
def main():
|
||||
pc = normalizers.Precompiled(base64.b64decode(CHARSMAP))
|
||||
w = sys.stdout.write
|
||||
w("/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers %s and "
|
||||
"the\n * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */\n" % tokenizers.__version__)
|
||||
w("#pragma once\n#include <cstdint>\n\n")
|
||||
w("static const char* kPcCharsmap =\n")
|
||||
for i in range(0, len(CHARSMAP), 96):
|
||||
w(" \"%s\"\n" % CHARSMAP[i:i + 96])
|
||||
w(" ;\n\n")
|
||||
w("struct PcCase { const char* in; const char* out; };\n")
|
||||
w("static const PcCase kPcCases[] = {\n")
|
||||
for s in INPUTS:
|
||||
w(" { %s, %s },\n" % (cstr(s), cstr(pc.normalize_str(s))))
|
||||
w("};\n\n")
|
||||
cases = grapheme_cases(sys.argv[1])
|
||||
w("/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */\n")
|
||||
w("struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; };\n")
|
||||
w("static const GbCase kGbCases[] = {\n")
|
||||
for cps, mask in cases:
|
||||
if len(cps) > 8:
|
||||
continue
|
||||
w(" { { %s }, %d, 0x%x },\n" % (", ".join("0x%X" % c for c in cps), len(cps),
|
||||
mask & ~1))
|
||||
w("};\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -246,6 +246,104 @@ def metaspace_specials(scheme):
|
||||
"vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------- CLIP-shaped
|
||||
|
||||
CLIP_SPLIT = r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+"""
|
||||
|
||||
|
||||
def gpt2_alphabet():
|
||||
"""GPT-2's byte -> character map, in CLIP's vocabulary order."""
|
||||
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\xa1"), ord("\xac") + 1)) + \
|
||||
list(range(ord("\xae"), ord("\xff") + 1))
|
||||
cs = bs[:]
|
||||
n = 0
|
||||
for b in range(256):
|
||||
if b not in bs:
|
||||
bs.append(b)
|
||||
cs.append(256 + n)
|
||||
n += 1
|
||||
return [chr(c) for c in cs]
|
||||
|
||||
|
||||
CLIP_TRAIN = ("a photo of a cat, a painting of a dog, best quality, masterpiece, 1girl, solo, "
|
||||
"looking at viewer, it's a photograph of the mountains at sunset, don't stop, "
|
||||
"highly detailed digital art, portrait of an astronaut riding a horse, ") * 3
|
||||
|
||||
|
||||
def clip_like():
|
||||
"""CLIP ViT-L/14's tokenizer.json with its vocabulary cut down: the real normaliser, Split,
|
||||
ByteLevel, RobertaProcessing and decoder, the 512 byte tokens with and without the "</w>"
|
||||
end-of-word suffix in CLIP's order, and merges trained here (most frequent pair, then the
|
||||
smallest) over a few prompts, each merged token's id 512 + its rank as in CLIP's own file."""
|
||||
from tokenizers import normalizers, pre_tokenizers, Regex
|
||||
norm = normalizers.Sequence([normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "),
|
||||
normalizers.Lowercase()])
|
||||
pre = pre_tokenizers.Sequence([
|
||||
pre_tokenizers.Split(Regex(CLIP_SPLIT), behavior="removed", invert=True),
|
||||
pre_tokenizers.ByteLevel(add_prefix_space=False)])
|
||||
alpha = gpt2_alphabet()
|
||||
vocab = alpha + [c + "</w>" for c in alpha]
|
||||
words = {}
|
||||
for w, _ in pre.pre_tokenize_str(norm.normalize_str(CLIP_TRAIN)):
|
||||
sym = tuple(list(w[:-1]) + [w[-1] + "</w>"])
|
||||
words[sym] = words.get(sym, 0) + 1
|
||||
merges = []
|
||||
for _ in range(160):
|
||||
pairs = {}
|
||||
for sym, n in words.items():
|
||||
for a, b in zip(sym, sym[1:]):
|
||||
pairs[(a, b)] = pairs.get((a, b), 0) + n
|
||||
if not pairs:
|
||||
break
|
||||
best = min(pairs, key=lambda k: (-pairs[k], k))
|
||||
merges.append(best)
|
||||
vocab.append(best[0] + best[1])
|
||||
nw = {}
|
||||
for sym, n in words.items():
|
||||
out, i = [], 0
|
||||
while i < len(sym):
|
||||
if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best:
|
||||
out.append(sym[i] + sym[i + 1])
|
||||
i += 2
|
||||
else:
|
||||
out.append(sym[i])
|
||||
i += 1
|
||||
nw[tuple(out)] = nw.get(tuple(out), 0) + n
|
||||
words = nw
|
||||
bos, eos = len(vocab), len(vocab) + 1
|
||||
vocab += ["<|startoftext|>", "<|endoftext|>"]
|
||||
return {
|
||||
"added_tokens": [
|
||||
{"id": bos, "content": "<|startoftext|>", "single_word": False, "lstrip": False,
|
||||
"rstrip": False, "normalized": True, "special": True},
|
||||
{"id": eos, "content": "<|endoftext|>", "single_word": False, "lstrip": False,
|
||||
"rstrip": False, "normalized": False, "special": True}],
|
||||
"normalizer": {"type": "Sequence", "normalizers": [
|
||||
{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": r"\s+"}, "content": " "},
|
||||
{"type": "Lowercase"}]},
|
||||
"pre_tokenizer": {"type": "Sequence", "pretokenizers": [
|
||||
{"type": "Split", "pattern": {"Regex": CLIP_SPLIT}, "behavior": "Removed",
|
||||
"invert": True},
|
||||
{"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True}]},
|
||||
"post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", eos],
|
||||
"cls": ["<|startoftext|>", bos], "trim_offsets": False,
|
||||
"add_prefix_space": False},
|
||||
"decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True},
|
||||
"model": {"type": "BPE", "dropout": None, "unk_token": "<|endoftext|>",
|
||||
"continuing_subword_prefix": "", "end_of_word_suffix": "</w>",
|
||||
"fuse_unk": False, "vocab": {t: i for i, t in enumerate(vocab)},
|
||||
"merges": [a + " " + b for a, b in merges]},
|
||||
}
|
||||
|
||||
|
||||
CLIP_TEXTS = ["a photo of a cat", "1girl, solo, masterpiece, best quality, (absurdres:1.2), "
|
||||
"looking_at_viewer, hatsune_miku", "A Photograph of the Mountains, it's DON'T stop",
|
||||
"1024x1024 2.5 v1.0", "Café naïve 東京タワー 서울 🍣👩👩👧 İstanbul ΣΊΣΥΦΟΣ",
|
||||
" many spaces\t\ttabs\n\nnewlines ", "...!!!??? ((()))[[]]", "", "a",
|
||||
"<|startoftext|>a cat<|endoftext|>", "x<|StartOfText|>y", "a</w>b catcat",
|
||||
"photographphotograph", "it'sit's'll"]
|
||||
|
||||
|
||||
SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "<s>Hi", "Hi Hi[INST]Hi"]
|
||||
|
||||
GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat",
|
||||
@@ -341,6 +439,30 @@ def main():
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
c = clip_like()
|
||||
tok = Tokenizer.from_str(json.dumps(c))
|
||||
print("const char* const kClipLike = R\"JSON(%s)JSON\";" % json.dumps(c, ensure_ascii=False))
|
||||
print()
|
||||
print("const std::vector<EncodeGolden>& clip_goldens() {")
|
||||
print(" static const std::vector<EncodeGolden> v = {")
|
||||
for t in CLIP_TEXTS:
|
||||
a = tok.encode(t, add_special_tokens=False).ids
|
||||
b = tok.encode(t, add_special_tokens=True).ids
|
||||
print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b)))
|
||||
print(" };")
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
print("/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */")
|
||||
print("const std::vector<const char*>& clip_decoded() {")
|
||||
print(" static const std::vector<const char*> v = {")
|
||||
for t in CLIP_TEXTS:
|
||||
print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids,
|
||||
skip_special_tokens=True)))
|
||||
print(" };")
|
||||
print(" return v;")
|
||||
print("}")
|
||||
print()
|
||||
print("/* END generated by mk_tokenizer_goldens.py */")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""mkglm5golden.py MODELDIR OUT.h -- goldens for tests/mm_test.cpp's GLM-5.3 vision cases, every number
|
||||
from transformers' own Glm5NextProcessor as MODELDIR's processor_config.json sets it up (run in a
|
||||
venv with a transformers that has glm5_next, torch, torchvision, numpy and Pillow).
|
||||
|
||||
The reference is the processor AutoProcessor loads: Glm5NextImageProcessor, transformers' torchvision
|
||||
backend, which resizes the uint8 picture with torchvision's antialiased bicubic (ATen's fixed-point
|
||||
kernel), pads it right and bottom with zero bytes, and normalises in float32 with the rescale fused
|
||||
into the mean and deviation.
|
||||
|
||||
* smart_resize over a grid of picture sizes and two token budgets (the checkpoint's 8000, and
|
||||
the 4096 an encoder pass of 16384 patches holds): the canvas and the patch count, the latter
|
||||
from get_number_of_image_patches;
|
||||
* whole pictures, some only padded, some grown under the token floor, some shrunk to a budget:
|
||||
the patch grid and the FNV-1a of every patch as the tower reads it (float32, then bfloat16),
|
||||
in the reference's own order, which is merge-block order; and the token ids Glm5NextProcessor
|
||||
makes of <|begin_of_image|><|image|><|end_of_image|>.
|
||||
|
||||
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 transformers import AutoProcessor
|
||||
from transformers.models.glm5_next.image_processing_glm5_next import smart_resize
|
||||
|
||||
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 fnv(data):
|
||||
h = 0xcbf29ce484222325
|
||||
for b in np.frombuffer(data, dtype=np.uint8).tolist():
|
||||
h = ((h ^ b) * 0x100000001b3) & ((1 << 64) - 1)
|
||||
return h
|
||||
|
||||
|
||||
def main():
|
||||
model_dir, out = sys.argv[1], sys.argv[2]
|
||||
P = AutoProcessor.from_pretrained(model_dir)
|
||||
IP = P.image_processor
|
||||
tok = P.tokenizer
|
||||
T, F = IP.temporal_patch_size, IP.patch_size * IP.merge_size * IP.patch_expand_factor
|
||||
L = ["/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers %s; do not edit. */"
|
||||
% transformers.__version__, "#pragma once", "#include <cstdint>", ""]
|
||||
L.append(f"static const int32_t kGlm5Patch = {IP.patch_size}, kGlm5Merge = {IP.merge_size}, "
|
||||
f"kGlm5Temporal = {T}, kGlm5MinTok = {IP.min_image_tokens}, "
|
||||
f"kGlm5MaxTok = {IP.max_image_tokens};")
|
||||
ids = [tok.convert_tokens_to_ids(t) for t in ("<|image|>", "<|begin_of_image|>", "<|end_of_image|>")]
|
||||
L.append(f"static const int32_t kGlm5Image = {ids[0]}, kGlm5Start = {ids[1]}, kGlm5End = {ids[2]};")
|
||||
L.append("static const float kGlm5Mean[3] = { %s }, kGlm5Std[3] = { %s };" %
|
||||
(", ".join(f"{v!r}f" for v in IP.image_mean), ", ".join(f"{v!r}f" for v in IP.image_std)))
|
||||
L.append("")
|
||||
|
||||
# ---- smart_resize: the canvas, and the patch count the processor reports for it
|
||||
sizes = [(1, 1), (100, 100), (61, 97), (3, 4000), (448, 448), (300, 500), (768, 1024),
|
||||
(1080, 1920), (2048, 2048), (3000, 4000), (4000, 3000), (20, 1500), (1500, 20),
|
||||
(111, 113), (112, 112), (113, 111), (2300, 2900), (7000, 120), (120, 7000),
|
||||
(5000, 5000), (12000, 9000), (2160, 3840), (1, 30000), (900, 1400)]
|
||||
L.append("struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; };")
|
||||
L.append("static const GoldGlm5Size kGoldGlm5Size[] = {")
|
||||
for h, w in sizes:
|
||||
for budget in (IP.max_image_tokens, 4096):
|
||||
oh, ow = smart_resize(num_frames=T, height=h, width=w, temporal_factor=T, factor=F,
|
||||
min_pixels=IP.min_image_tokens, max_pixels=budget)
|
||||
n = IP.get_number_of_image_patches(h, w, {"max_image_tokens": budget})
|
||||
assert n == (oh // IP.patch_size) * (ow // IP.patch_size)
|
||||
L.append(f" {{ {h}, {w}, {budget}, {oh}, {ow}, {n} }},")
|
||||
L.append("};")
|
||||
L.append("")
|
||||
|
||||
# ---- whole pictures: padded only, grown under the floor, shrunk to a budget
|
||||
pics = [(0, 448, 448, IP.max_image_tokens), (1, 300, 500, IP.max_image_tokens),
|
||||
(2, 61, 97, IP.max_image_tokens), (3, 3, 400, IP.max_image_tokens),
|
||||
(4, 20, 1500, IP.max_image_tokens), (5, 900, 1400, 256), (6, 1200, 1700, 4096),
|
||||
(7, 2300, 2900, IP.max_image_tokens), (8, 1, 1, IP.max_image_tokens),
|
||||
(9, 113, 111, IP.max_image_tokens)]
|
||||
L.append("struct GoldGlm5Pic { int32_t f, h, w, budget, grid_h, grid_w; uint64_t fnv; "
|
||||
"int32_t n_ids; uint64_t ids_fnv; uint16_t head[8]; };")
|
||||
L.append("static const GoldGlm5Pic kGoldGlm5Pics[] = {")
|
||||
for f, h, w, budget in pics:
|
||||
im = picture(f, h, w)
|
||||
o = IP(images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget,
|
||||
return_tensors="pt")
|
||||
thw = o["image_grid_thw"][0].tolist()
|
||||
assert thw[0] == 1
|
||||
pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16)
|
||||
assert pv.shape == (thw[1] * thw[2], 3 * T * IP.patch_size ** 2)
|
||||
po = P(text=["<|begin_of_image|><|image|><|end_of_image|>"],
|
||||
images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget,
|
||||
return_tensors="pt")
|
||||
tid = po["input_ids"][0].to(torch.int32).numpy().astype("<i4")
|
||||
assert np.array_equal(po["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy()
|
||||
.astype(np.uint16), pv)
|
||||
head = ", ".join(f"0x{v:04x}" for v in pv.ravel()[:8].tolist())
|
||||
L.append(f" {{ {f}, {h}, {w}, {budget}, {thw[1]}, {thw[2]}, "
|
||||
f"0x{fnv(pv.astype('<u2').tobytes()):016x}ull, {len(tid)}, "
|
||||
f"0x{fnv(tid.tobytes()):016x}ull, {{ {head} }} }},")
|
||||
L.append("};")
|
||||
open(out, "w").write("\n".join(L) + "\n")
|
||||
print("wrote", out, len(L), "lines")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+164
-2
@@ -2,8 +2,9 @@
|
||||
*
|
||||
* Every expected value in mm_golden.h comes from transformers' own code (tests/mkgolden.py names
|
||||
* the function behind each table), in lfm2_golden.h from its LFM2-VL processor
|
||||
* (tests/mklfm2golden.py) and in gemma4_golden.h from its Gemma 4 processors
|
||||
* (tests/mkgemma4golden.py): smart_resize in both forms, the frames a video keeps, the patches of a
|
||||
* (tests/mklfm2golden.py), in gemma4_golden.h from its Gemma 4 processors
|
||||
* (tests/mkgemma4golden.py) and in glm5_golden.h from its GLM-5.3 processor
|
||||
* (tests/mkglm5golden.py): smart_resize in both forms, the frames a video keeps, the patches of a
|
||||
* picture and a clip, the timestamps between a clip's groups, and get_rope_index's positions over
|
||||
* a prompt carrying both. A mistake in any of these still yields a model that answers, about a
|
||||
* slightly different picture or with positions a row off, so only this file can catch it.
|
||||
@@ -21,10 +22,12 @@
|
||||
#include "mm/media.h"
|
||||
#include "mm/processor.h"
|
||||
#include "gemma4_golden.h"
|
||||
#include "glm5_golden.h"
|
||||
#include "imaging_golden.h"
|
||||
#include "lfm2_golden.h"
|
||||
#include "mm/resample.h"
|
||||
#include "mm_golden.h"
|
||||
#include "rad_builder.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -726,6 +729,165 @@ TEST(gemma4_frames_are_sampled_as_the_reference_does) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== GLM-5.3's processor
|
||||
*
|
||||
* glm5_golden.h: Glm5NextProcessor as the checkpoint's processor_config.json sets it up
|
||||
* (Glm5NextImageProcessor, torchvision backend): canvases, patch counts, patches as the tower reads
|
||||
* them, and the token ids around a picture. The reference's patches are in merge-block order, as
|
||||
* this processor's are, so they compare without reordering. */
|
||||
namespace {
|
||||
|
||||
VisionConfig glm5_cfg(int32_t max_tok, int64_t max_patches) {
|
||||
VisionConfig c;
|
||||
c.family = Family::Glm5Next;
|
||||
c.patch = kGlm5Patch;
|
||||
c.merge = kGlm5Merge;
|
||||
c.temporal = kGlm5Temporal;
|
||||
c.min_image_tokens = kGlm5MinTok;
|
||||
c.max_image_tokens = max_tok;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
c.mean[i] = kGlm5Mean[i];
|
||||
c.stdv[i] = kGlm5Std[i];
|
||||
}
|
||||
const int64_t f2 = (int64_t)c.factor() * c.factor();
|
||||
c.image_min_pixels = c.video_min_pixels = kGlm5MinTok * f2;
|
||||
c.image_max_pixels = c.video_max_pixels = (int64_t)max_tok * f2;
|
||||
c.tok_image = kGlm5Image;
|
||||
c.tok_video = 154855;
|
||||
c.tok_start = kGlm5Start;
|
||||
c.tok_end = kGlm5End;
|
||||
c.max_patches = max_patches;
|
||||
return c;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* Canvases: sides rounded up to 28, grown under 16 tokens, the budget's binary search over 8000
|
||||
* and over the 4096 a pass of 16384 patches holds, aspect ratios to 30000:1. */
|
||||
TEST(glm5_canvases_are_the_references) {
|
||||
for (const GoldGlm5Size& g : kGoldGlm5Size) {
|
||||
int64_t oh = 0, ow = 0, ch = 0, cw = 0;
|
||||
std::string why;
|
||||
CHECK_OK(glm5next_size(g.h, g.w, kGlm5Temporal, kGlm5Patch * kGlm5Merge, kGlm5MinTok,
|
||||
g.budget, &oh, &ow, &ch, &cw, &why));
|
||||
if (oh != g.oh || ow != g.ow)
|
||||
std::fprintf(stderr, " %lld x %lld at %d tokens: %lld x %lld, reference %lld x "
|
||||
"%lld\n", (long long)g.h, (long long)g.w, g.budget, (long long)oh,
|
||||
(long long)ow, (long long)g.oh, (long long)g.ow);
|
||||
CHECK_EQ(oh, g.oh);
|
||||
CHECK_EQ(ow, g.ow);
|
||||
CHECK_EQ((oh / kGlm5Patch) * (ow / kGlm5Patch), g.patches);
|
||||
CHECK(ch <= oh && cw <= ow);
|
||||
}
|
||||
}
|
||||
|
||||
/* Whole pictures: padded only (448 x 448 is the one with no padding), grown under the floor (the
|
||||
* 1 x 1, 61 x 97 and 3 x 400 ones), shrunk to a budget (900 x 1400 at 256 tokens, 2300 x 2900 at
|
||||
* 8000), every patch value exactly, and <|begin_of_image|>, one <|image|> a token,
|
||||
* <|end_of_image|>, as the reference processor expands the template's triple. */
|
||||
TEST(glm5_pictures_are_the_references) {
|
||||
for (const GoldGlm5Pic& g : kGoldGlm5Pics) {
|
||||
Processor p;
|
||||
REQUIRE_EQ(p.init(glm5_cfg(g.budget, 32768), [](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_t, 1);
|
||||
CHECK_EQ(it->grid_h, g.grid_h);
|
||||
CHECK_EQ(it->grid_w, g.grid_w);
|
||||
CHECK(it->rope_1d);
|
||||
REQUIRE_EQ(it->patch_dim, (int64_t)3 * kGlm5Temporal * kGlm5Patch * kGlm5Patch);
|
||||
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * (size_t)it->patch_dim);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]);
|
||||
if (fnv(it->pixels) != g.fnv)
|
||||
std::fprintf(stderr, " picture %d x %d at %d tokens: patches differ\n", g.h, g.w,
|
||||
g.budget);
|
||||
CHECK_EQ(fnv(it->pixels), g.fnv);
|
||||
const int64_t rows = (int64_t)g.grid_h * g.grid_w / (kGlm5Merge * kGlm5Merge);
|
||||
CHECK_EQ(it->n_rows(), rows);
|
||||
CHECK_EQ((int32_t)it->expand.size(), g.n_ids);
|
||||
CHECK_EQ(fnv(it->expand), g.ids_fnv);
|
||||
REQUIRE_EQ(it->expand.size(), (size_t)rows + 2);
|
||||
CHECK_EQ(it->expand.front(), kGlm5Start);
|
||||
CHECK_EQ(it->expand.back(), kGlm5End);
|
||||
CHECK_EQ((int64_t)std::count(it->expand.begin(), it->expand.end(), kGlm5Image), rows);
|
||||
REQUIRE_EQ(it->seg_at.size(), (size_t)1);
|
||||
CHECK_EQ(it->seg_at[0], 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* The checkpoint's budget is lowered to what one encoder pass holds (a token is four patches),
|
||||
* as a pixel band is; a pass that holds less than the floor is refused. Video and a request's own
|
||||
* budget are refused by name. */
|
||||
TEST(glm5_budget_is_one_pass_and_pictures_only) {
|
||||
Processor p;
|
||||
REQUIRE_EQ(p.init(glm5_cfg(kGlm5MaxTok, 16384), [](const std::string&) {
|
||||
return std::vector<int32_t>{};
|
||||
}), RAD_OK);
|
||||
CHECK_EQ(p.config().max_image_tokens, 4096);
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.image_from(frame(0, 2048, 2048), &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
CHECK_EQ(it->grid_h, 128);
|
||||
CHECK_EQ(it->grid_w, 128);
|
||||
CHECK_EQ(it->n_rows(), (int64_t)4096);
|
||||
Processor q;
|
||||
CHECK_EQ(q.init(glm5_cfg(kGlm5MaxTok, 60), [](const std::string&) {
|
||||
return std::vector<int32_t>{};
|
||||
}), RAD_E_INVAL);
|
||||
Video v;
|
||||
v.frames.push_back(frame(0, 64, 64));
|
||||
v.frames.push_back(frame(1, 64, 64));
|
||||
CHECK_EQ(p.video_from(v, &it, &why), RAD_E_UNSUPPORTED);
|
||||
CHECK(why.find("pictures, not video") != std::string::npos);
|
||||
const uint8_t png_magic[8] = { 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a };
|
||||
CHECK_EQ(p.image(png_magic, sizeof png_magic, 280, &it, &why), RAD_E_UNSUPPORTED);
|
||||
CHECK(why.find("--image-tokens") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A converted GLM-5.3 container states the processor under `processor.image_processor.*` and
|
||||
* the media ids under their own names, not Qwen's vision_start / vision_end. */
|
||||
TEST(glm5_reads_its_processor_from_the_container) {
|
||||
const char* keys[] = {
|
||||
"vision_config.model_type", "vision_config.patch_size", "vision_config.temporal_patch_size",
|
||||
"vision_config.spatial_merge_size", "image_token_id", "video_token_id",
|
||||
"image_start_token_id", "image_end_token_id", "processor.image_processor.min_image_tokens",
|
||||
"processor.image_processor.max_image_tokens", "processor.image_processor.image_mean",
|
||||
"processor.image_processor.image_std", "processor.image_processor.patch_expand_factor",
|
||||
};
|
||||
const char* vals[] = {
|
||||
"glm5_next_vision", "14", "2", "2", "154854", "154855", "154830", "154831", "16", "8000",
|
||||
"0.48145465999999998 0.4578275 0.40821073000000002",
|
||||
"0.26862954 0.26130258000000001 0.27577710999999999", "1",
|
||||
};
|
||||
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::Glm5Next);
|
||||
CHECK_EQ(c.patch_dim(), (int64_t)1176);
|
||||
CHECK_EQ(c.factor(), 28);
|
||||
CHECK_EQ(c.min_image_tokens, 16);
|
||||
CHECK_EQ(c.max_image_tokens, 8000);
|
||||
CHECK_EQ(c.tok_image, kGlm5Image);
|
||||
CHECK_EQ(c.tok_start, kGlm5Start);
|
||||
CHECK_EQ(c.tok_end, kGlm5End);
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
CHECK_EQ(c.mean[i], kGlm5Mean[i]);
|
||||
CHECK_EQ(c.stdv[i], kGlm5Std[i]);
|
||||
}
|
||||
vals[12] = "2";
|
||||
CHECK_EQ(c.from_meta(m, &why), RAD_E_UNSUPPORTED);
|
||||
CHECK(why.find("patch_expand_factor") != std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== Pillow's arithmetic
|
||||
*
|
||||
* imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow,
|
||||
|
||||
+15
-8
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS]
|
||||
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE]]
|
||||
#
|
||||
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
|
||||
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
|
||||
@@ -19,13 +19,14 @@
|
||||
# every host library implements (a norm, the fp8 activation quantiser, a gated activation)
|
||||
# are enough;
|
||||
# 5. with HIP_COMPILER given, the device library the tree built (libr4d) is built out of tree
|
||||
# too, for HIP_TARGETS, and compiles to the tree's device code. A replay of a device library
|
||||
# needs a card, and this test must not touch one a server is using; the same instructions mean
|
||||
# the tree's own GPU suite (ctest -L gpu) has already checked what the out-of-tree build
|
||||
# produced.
|
||||
# too, for HIP_TARGETS and at the tree's RAD_HIP_VOPD_REPEATABLE (VOPD_REPEATABLE, default
|
||||
# OFF; on LLVM 24 it decides whether VOPD pairs, so it changes the code), and compiles to the
|
||||
# tree's device code. A replay of a device library needs a card, and this test must not touch
|
||||
# one a server is using; the same instructions mean the tree's own GPU suite (ctest -L gpu)
|
||||
# has already checked what the out-of-tree build produced.
|
||||
set -eu
|
||||
B=$1; S=$2; W=$3
|
||||
HIPC=${4:-}; HIPT=${5:-}
|
||||
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}
|
||||
GEN=${CMAKE_GENERATOR:-Ninja}
|
||||
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
|
||||
|
||||
@@ -62,12 +63,18 @@ for d in $dirs; do
|
||||
n=$(basename "$d")
|
||||
say "building $d against the installed package"
|
||||
extra=""
|
||||
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT"
|
||||
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
|
||||
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
|
||||
# shellcheck disable=SC2086
|
||||
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
|
||||
-DCMAKE_PREFIX_PATH="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
|
||||
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J"
|
||||
run "$W/logs/$n.install.log" cmake --install "$W/b/$n"
|
||||
# --prefix for the same reason as the tree install above: a plugin's own CMakeLists may install
|
||||
# companions (libr4d ships r4d_selftest) to relative destinations under CMAKE_INSTALL_PREFIX, and
|
||||
# the test must not need root. The plugins themselves ignore the prefix -- rad_add_plugin installs
|
||||
# them under the absolute RAD_PLUGIN_INSTALL_HOME given at configure time -- so the checks below,
|
||||
# which look in $H, are unaffected.
|
||||
run "$W/logs/$n.install.log" cmake --install "$W/b/$n" --prefix "$W/i"
|
||||
done
|
||||
|
||||
# 1. The same plugins, file for file.
|
||||
|
||||
+70
-40
@@ -26,6 +26,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
@@ -3829,53 +3830,82 @@ int process_vram(int64_t* out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* process_vram once it holds still. A stream is a hardware queue, and KFD gives each queue a
|
||||
* context save area (the topology's cwsr_size + ctl_stack_size: 29.3 MiB on a 64-CU RDNA4 card)
|
||||
* that can be released a few milliseconds after the queue is destroyed, so a reading straight
|
||||
* after a stream's destruction may still include it (#124). Reads every 10 ms until 100 ms pass
|
||||
* without a change, for at most 2 s. */
|
||||
int settled_vram(int64_t* out) {
|
||||
int64_t v = 0;
|
||||
RAD_TRY(process_vram(&v));
|
||||
const auto end = std::chrono::steady_clock::now() + std::chrono::seconds(2);
|
||||
for (int still = 0; still < 10 && std::chrono::steady_clock::now() < end;) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
int64_t w = 0;
|
||||
RAD_TRY(process_vram(&w));
|
||||
still = w == v ? still + 1 : 0;
|
||||
v = w;
|
||||
}
|
||||
*out = v;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* Tools and tests build and tear down movers repeatedly, and on a card every event or stream is
|
||||
* a hardware queue and VRAM. A mover that staged, promoted and filled a loan gives back every
|
||||
* event and every byte of device memory it took. */
|
||||
/* The runtime and the driver keep some memory for the life of the process once a path is first
|
||||
* used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory). So
|
||||
* the work runs once before the count is taken, and the count after a second run may differ by a
|
||||
* page and a directory, never by a buffer. Both counts are taken once the figure holds still: a
|
||||
* destroyed stream's queue save area can outlive it by a few milliseconds (settled_vram, #124). */
|
||||
TEST(a_mover_gives_back_every_event_and_device_byte) {
|
||||
const int64_t events0 = rad_dev_live_events();
|
||||
int64_t vram0 = 0, vram1 = 0;
|
||||
CHECK_OK(process_vram(&vram0));
|
||||
{
|
||||
Fixture f;
|
||||
build_dense(f, 8, 1 * MiB, /*host_kernel=*/false);
|
||||
Config c = base_config();
|
||||
c.placement = "layer_offload";
|
||||
c.vram_weights_mib = 5;
|
||||
c.host_pool_mib = 64;
|
||||
PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0};
|
||||
Plan p;
|
||||
REQUIRE_EQ(Planner(in).plan(&p), RAD_OK);
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK);
|
||||
RadStream compute = nullptr;
|
||||
REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK);
|
||||
CHECK_OK(m.bind_compute_stream(compute));
|
||||
CHECK(rad_dev_live_events() > events0);
|
||||
ComputeWork work;
|
||||
for (int d = 0; d < 20; ++d) {
|
||||
CHECK_OK(m.begin_dispatch(d, nullptr));
|
||||
work.run(compute);
|
||||
CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op));
|
||||
auto run = [&]() {
|
||||
const int64_t events0 = rad_dev_live_events();
|
||||
{
|
||||
Fixture f;
|
||||
build_dense(f, 8, 1 * MiB, /*host_kernel=*/false);
|
||||
Config c = base_config();
|
||||
c.placement = "layer_offload";
|
||||
c.vram_weights_mib = 5;
|
||||
c.host_pool_mib = 64;
|
||||
PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0};
|
||||
Plan p;
|
||||
REQUIRE_EQ(Planner(in).plan(&p), RAD_OK);
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK);
|
||||
RadStream compute = nullptr;
|
||||
REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK);
|
||||
CHECK_OK(m.bind_compute_stream(compute));
|
||||
CHECK(rad_dev_live_events() > events0);
|
||||
ComputeWork work;
|
||||
for (int d = 0; d < 20; ++d) {
|
||||
CHECK_OK(m.begin_dispatch(d, nullptr));
|
||||
work.run(compute);
|
||||
CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op));
|
||||
}
|
||||
CHECK(m.stats().prefetched > 0);
|
||||
CHECK_OK(rad_stream_sync(compute));
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
CHECK(m.stats().prefetched > 0);
|
||||
CHECK_OK(rad_stream_sync(compute));
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
{
|
||||
LoanRig r;
|
||||
REQUIRE_EQ(r.build(), RAD_OK);
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
|
||||
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
CHECK(r.m.stats().promotions > 0);
|
||||
}
|
||||
CHECK_EQ(rad_dev_live_events(), events0);
|
||||
CHECK_OK(process_vram(&vram1));
|
||||
CHECK_EQ(vram1, vram0);
|
||||
{
|
||||
LoanRig r;
|
||||
REQUIRE_EQ(r.build(), RAD_OK);
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
|
||||
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
CHECK(r.m.stats().promotions > 0);
|
||||
}
|
||||
CHECK_EQ(rad_dev_live_events(), events0);
|
||||
};
|
||||
run();
|
||||
int64_t vram0 = 0, vram1 = 0;
|
||||
CHECK_OK(settled_vram(&vram0));
|
||||
run();
|
||||
CHECK_OK(settled_vram(&vram1));
|
||||
CHECK(vram1 - vram0 <= 2 * MiB + 4096);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+50
-20
@@ -843,11 +843,14 @@ TEST(an_engine_with_no_card_leaves_a_gpu_librarys_device_rows_out) {
|
||||
for (const KernelRow& row : r.rows()) CHECK(row.info->domain != RAD_DOMAIN_DEVICE);
|
||||
}
|
||||
|
||||
/* The shipped libr4d picks the all-reduce by message size. At 3, 4 and 8 ranks the exact sum is a
|
||||
* one-shot for decode-sized messages and a two-shot for prefill chunks; the two-shot rows start one
|
||||
* element above the one-shot bound, which is a band edge of the ranged `numel`. The band under it
|
||||
* must stay resolvable for every row with a DIV on `numel` (two-rank wht6 (64), three- and
|
||||
* four-rank ti8 (32, 128)), or a lossy serve loses its decode band. Only the real plugin can show
|
||||
/* The shipped libr4d picks the all-reduce by message size. At 3 and 4 ranks the exact sum is a
|
||||
* one-shot for decode-sized messages and a two-shot for prefill chunks, at 8 ranks a one-shot only
|
||||
* up to 8192 elements (its seven-fold send loses early); the two-shot rows start one element above
|
||||
* the one-shot bound, which is a band edge of the ranged `numel`. Edges are the union over every
|
||||
* candidate row, so the eight-rank edge at 8192 also splits the other widths' bands, each half
|
||||
* resolving the same row. The band under the one-shot bound must stay resolvable for every row
|
||||
* with a DIV on `numel` (two-rank wht6 (64), three- and four-rank ti8 (32, 128)), or a lossy
|
||||
* serve loses its decode band. Only the real plugin can show
|
||||
* resolution above two ranks on a two-card machine. Geometry: Qwen3.8-Flash-Next, 2560 wide,
|
||||
* 2048-token chunk. */
|
||||
TEST(libr4d_resolves_the_all_reduce_by_message_size) {
|
||||
@@ -868,35 +871,44 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
|
||||
};
|
||||
|
||||
CHECK_EQ(band_names(bands(3, 1, chunk)),
|
||||
"524288:ar_oneshot_3rank_exact 5242880:ar_twoshot_3rank_exact ");
|
||||
"8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact "
|
||||
"5242880:ar_twoshot_3rank_exact ");
|
||||
CHECK_EQ(band_names(bands(4, 1, chunk)),
|
||||
"524288:ar_oneshot_4rank_exact 5242880:ar_twoshot_4rank_exact ");
|
||||
"8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact "
|
||||
"5242880:ar_twoshot_4rank_exact ");
|
||||
CHECK_EQ(band_names(bands(8, 1, chunk)),
|
||||
"524288:ar_oneshot_8rank_exact 5242880:ar_twoshot_8rank_exact ");
|
||||
"8192:ar_oneshot_8rank_exact 524288:ar_twoshot_8rank_exact "
|
||||
"5242880:ar_twoshot_8rank_exact ");
|
||||
CHECK_EQ(band_names(bands(3, 0, chunk)),
|
||||
"524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 ");
|
||||
"8192:ar_twoshot_3rank_ti8 524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 ");
|
||||
CHECK_EQ(band_names(bands(4, 0, chunk)),
|
||||
"524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 ");
|
||||
"8192:ar_twoshot_4rank_ti8 524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 ");
|
||||
CHECK_EQ(band_names(bands(2, 0, chunk)),
|
||||
"524288:ar_oneshot_2rank_wht6 5242880:ar_oneshot_2rank_wht6 ");
|
||||
"8192:ar_oneshot_2rank_wht6 524288:ar_oneshot_2rank_wht6 "
|
||||
"5242880:ar_oneshot_2rank_wht6 ");
|
||||
CHECK_EQ(band_names(bands(2, 1, chunk)),
|
||||
"524288:ar_oneshot_2rank_exact 5242880:ar_oneshot_2rank_exact ");
|
||||
"8192:ar_oneshot_2rank_exact 524288:ar_oneshot_2rank_exact "
|
||||
"5242880:ar_oneshot_2rank_exact ");
|
||||
|
||||
/* A 16384-token chunk is two-shot to its end: the two-shot's bound guards its word offsets,
|
||||
* it is not a prefill size, and a chunk past 20971520 elements would otherwise fall back to
|
||||
* the one-shot's twice-as-heavy send. */
|
||||
CHECK_EQ(band_names(bands(4, 1, 16384)),
|
||||
"524288:ar_oneshot_4rank_exact 41943040:ar_twoshot_4rank_exact ");
|
||||
"8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact "
|
||||
"41943040:ar_twoshot_4rank_exact ");
|
||||
CHECK_EQ(band_names(bands(3, 1, 16384)),
|
||||
"524288:ar_oneshot_3rank_exact 41943040:ar_twoshot_3rank_exact ");
|
||||
"8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact "
|
||||
"41943040:ar_twoshot_3rank_exact ");
|
||||
|
||||
/* Above the two-shot's bound the one-shot takes the message back. */
|
||||
CHECK_EQ(band_names(bands(4, 1, 131072)),
|
||||
"524288:ar_oneshot_4rank_exact 268435456:ar_twoshot_4rank_exact "
|
||||
"335544320:ar_oneshot_4rank_exact ");
|
||||
"8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact "
|
||||
"268435456:ar_twoshot_4rank_exact 335544320:ar_oneshot_4rank_exact ");
|
||||
|
||||
/* A step that never exceeds the bound has one band, and it is the one-shot's. */
|
||||
CHECK_EQ(band_names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact ");
|
||||
/* A step that never exceeds the bound stays on the one-shot, split only at the eight-rank
|
||||
* edge. */
|
||||
CHECK_EQ(band_names(bands(4, 1, 128)),
|
||||
"8192:ar_oneshot_4rank_exact 327680:ar_oneshot_4rank_exact ");
|
||||
|
||||
/* Eight ranks have no lossy wire: every band is a miss that names the request. */
|
||||
const std::vector<Band> none = bands(8, 0, chunk);
|
||||
@@ -912,9 +924,10 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
|
||||
for (const Band& b : bands(3, 0, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 32ll);
|
||||
for (const Band& b : bands(4, 0, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 128ll);
|
||||
const std::vector<Band> exact4 = bands(4, 1, chunk);
|
||||
REQUIRE_EQ(exact4.size(), 2u);
|
||||
REQUIRE_EQ(exact4.size(), 3u);
|
||||
CHECK_EQ(exact4[0].dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll);
|
||||
CHECK_EQ(exact4[1].dom[RAD_DOMAIN_DEVICE].ranged_div, 64ll);
|
||||
CHECK_EQ(exact4[1].dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll);
|
||||
CHECK_EQ(exact4[2].dom[RAD_DOMAIN_DEVICE].ranged_div, 64ll);
|
||||
for (const Band& b : bands(3, 1, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll);
|
||||
}
|
||||
|
||||
@@ -982,6 +995,23 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) {
|
||||
for (const Band& x : b) CHECK_EQ(picked(x.dom[RAD_DOMAIN_DEVICE].row), "attn_vit_h72_bf16");
|
||||
}
|
||||
|
||||
/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves
|
||||
* every M up to its bound, a decode step's rows and a prefill chunk alike. */
|
||||
TEST(libr4d_resolves_the_mla_attention_by_rows) {
|
||||
const std::string so = libr4d();
|
||||
if (so.empty()) return;
|
||||
Registry r;
|
||||
CHECK(r.load_plugin(so, 0) >= 0);
|
||||
Geometry g;
|
||||
g.set_i("latent_dim", 512);
|
||||
g.set_i("heads", 8);
|
||||
g.set_i("blocks", 513);
|
||||
g.set_i("block_size", 4);
|
||||
g.set_s("dtype", "bf16");
|
||||
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 ");
|
||||
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 ");
|
||||
}
|
||||
|
||||
/* ================================================================== constraints that are not intervals */
|
||||
namespace {
|
||||
std::string extra_dir() { return home() + "/testkernels/extra"; }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,103 @@
|
||||
/* precompiled_test.cpp -- extended grapheme clusters and SentencePiece's precompiled normaliser
|
||||
* (core/text/tokenizer_grapheme.h) against Unicode's own test file and HuggingFace tokenizers'
|
||||
* Precompiled normaliser (goldens: mk_precompiled_goldens.py). */
|
||||
#include "rad_test.h"
|
||||
#include "text/tokenizer.h"
|
||||
#include "text/tokenizer_grapheme.h"
|
||||
|
||||
#include "precompiled_golden.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
/* Every case of Unicode 16.0.0's GraphemeBreakTest.txt: the clusters grapheme_end walks out of the
|
||||
* sequence start where the file breaks it. */
|
||||
TEST(grapheme_clusters_follow_uax29) {
|
||||
int bad = 0;
|
||||
for (const GbCase& g : kGbCases) {
|
||||
uint32_t starts = 0;
|
||||
for (size_t i = 0; i < g.n;) {
|
||||
if (i) starts |= 1u << i;
|
||||
const size_t e = grapheme_end(g.cp, g.n, i);
|
||||
if (e <= i || e > g.n) { ++bad; break; }
|
||||
i = e;
|
||||
}
|
||||
if (starts != g.starts) {
|
||||
if (++bad <= 5) {
|
||||
std::string s;
|
||||
for (uint32_t k = 0; k < g.n; ++k) s += fmt(" %04X", g.cp[k]);
|
||||
fprintf(stderr, " [%s ] starts 0x%x, want 0x%x\n", s.c_str(), starts, g.starts);
|
||||
}
|
||||
}
|
||||
}
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK(sizeof kGbCases / sizeof kGbCases[0] > 1000);
|
||||
}
|
||||
|
||||
/* A cluster under six bytes goes whole to its shortest mapped prefix's replacement (a combining
|
||||
* accent after a mapped letter is dropped); otherwise each character goes to its own. */
|
||||
TEST(precompiled_normaliser_matches_tokenizers) {
|
||||
PrecompiledMap pm;
|
||||
std::string why;
|
||||
REQUIRE_EQ(pm.load(kPcCharsmap, &why), (int)RAD_OK);
|
||||
for (const PcCase& c : kPcCases) {
|
||||
const std::string got = pm.normalize(c.in);
|
||||
if (got != c.out) fprintf(stderr, " '%s' -> '%s', want '%s'\n", c.in, got.c_str(), c.out);
|
||||
CHECK(got == c.out);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(precompiled_map_refuses_what_does_not_decode) {
|
||||
PrecompiledMap pm;
|
||||
std::string why;
|
||||
CHECK_EQ(pm.load("not base64!", &why), RAD_E_FORMAT);
|
||||
CHECK_EQ(pm.load("AAA=", &why), RAD_E_FORMAT);
|
||||
/* A trie byte count past the map's end. */
|
||||
CHECK_EQ(pm.load("AAEAAA==", &why), RAD_E_FORMAT);
|
||||
CHECK(!pm.ready());
|
||||
}
|
||||
|
||||
/* The normaliser inside a Unigram vocabulary, as T5's tokenizer.json declares it: Precompiled,
|
||||
* a right Strip and a Replace of space runs, then Metaspace. With no tokenizer_config.json beside
|
||||
* it the end token's id is unset, so encoding adds none (HuggingFace's ids: the same pieces, then
|
||||
* </s>). */
|
||||
TEST(precompiled_runs_in_a_tokenizer_json_chain) {
|
||||
const std::string json = std::string(R"({
|
||||
"version": "1.0", "added_tokens": [
|
||||
{"id": 0, "content": "<pad>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
|
||||
{"id": 1, "content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true},
|
||||
{"id": 2, "content": "<unk>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}],
|
||||
"normalizer": {"type": "Sequence", "normalizers": [
|
||||
{"type": "Precompiled", "precompiled_charsmap": ")") + kPcCharsmap + R"("},
|
||||
{"type": "Strip", "strip_left": false, "strip_right": true},
|
||||
{"type": "Replace", "pattern": {"Regex": " {2,}"}, "content": "▁"}]},
|
||||
"pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "first", "split": true},
|
||||
"post_processor": {"type": "TemplateProcessing",
|
||||
"single": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "</s>", "type_id": 0}}],
|
||||
"pair": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "</s>", "type_id": 0}}],
|
||||
"special_tokens": {"</s>": {"id": "</s>", "ids": [1], "tokens": ["</s>"]}}},
|
||||
"decoder": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true},
|
||||
"model": {"type": "Unigram", "unk_id": 2, "vocab": [
|
||||
["<pad>", 0.0], ["</s>", 0.0], ["<unk>", 0.0], ["▁", -2.0], ["▁a", -3.0], ["a", -4.0],
|
||||
["▁big", -3.0], ["b", -5.0], ["i", -5.0], ["g", -5.0], ["▁apple", -3.0], ["p", -5.0],
|
||||
["l", -5.0], ["e", -5.0], ["é", -5.0], ["▁café", -3.0], ["c", -5.0], ["f", -5.0]]}
|
||||
})";
|
||||
VocabBuild vb;
|
||||
REQUIRE_EQ(parse_tokenizer_json_buf(json, "t5-like", vb), (int)RAD_OK);
|
||||
auto v = std::make_shared<Vocab>();
|
||||
REQUIRE_EQ(v->load(std::move(vb)), (int)RAD_OK);
|
||||
Tokenizer tok;
|
||||
REQUIRE_EQ(tok.init(v), (int)RAD_OK);
|
||||
std::vector<int32_t> ids;
|
||||
REQUIRE_EQ(tok.encode("A big Apple", ids, true, true), (int)RAD_OK);
|
||||
CHECK(ids == std::vector<int32_t>({ 4, 6, 10 }));
|
||||
ids.clear();
|
||||
/* The fullwidth A normalises to an A the vocabulary lacks, and the decomposed accent to the
|
||||
* piece it holds. */
|
||||
REQUIRE_EQ(tok.encode("\xef\xbc\xa1 cafe\xcc\x81", ids, true, true), (int)RAD_OK);
|
||||
CHECK(ids == std::vector<int32_t>({ 3, 2, 15 }));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,198 @@
|
||||
/* projection_test.cpp -- the per-request switch that feeds the control vector.
|
||||
*
|
||||
* Two halves, both host-side:
|
||||
*
|
||||
* 1. the derivation (core/sched/derive.cpp, `projection_on_rows`) that turns the step's requests
|
||||
* into the int32 row mask the projection op reads. Getting this wrong is silent in both
|
||||
* directions: a mask that is never set serves the stock model to a client that asked for the
|
||||
* vector, and one that is always set applies it to every request, including those that
|
||||
* explicitly turned it off. Mixed steps are the case that matters (two conversations in one
|
||||
* step, one projected), and that is what these cases build.
|
||||
*
|
||||
* 2. the reference operation's arithmetic (libref/ref_hc.cpp, `hc_project`), called through the
|
||||
* plugin the way the engine calls it, checked against the operation the vector's package
|
||||
* documents: h -= scale * (h . v) v per hyper-connection stream, and an untouched row where
|
||||
* the mask is 0.
|
||||
*
|
||||
* The kernel parity check (libavx against libref) is libavx/avx_cases.cpp, fed to rad-avx-check;
|
||||
* libr4d's device kernel has no in-tree parity case yet (the rad-kbench fixture is still missing).
|
||||
* This file pins the meaning.
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_core.h"
|
||||
#include "sched/derive.h"
|
||||
|
||||
#include "../arch/common/rad_arch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
/* A step of `n_seq` sequences of `tokens_each` tokens, each with its own request, and the two
|
||||
* arrays a derivation reads. */
|
||||
struct Step {
|
||||
std::vector<rad::Request> reqs;
|
||||
std::vector<rad::StepEntry> entries;
|
||||
std::vector<int32_t> cu;
|
||||
rad::StepPlan plan;
|
||||
|
||||
Step(int n_seq, int tokens_each) {
|
||||
reqs.resize((size_t) n_seq);
|
||||
entries.resize((size_t) n_seq);
|
||||
cu.push_back(0);
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
entries[(size_t) i].req = &reqs[(size_t) i];
|
||||
entries[(size_t) i].n_tokens = tokens_each;
|
||||
cu.push_back(cu.back() + tokens_each);
|
||||
}
|
||||
plan.e = entries;
|
||||
plan.n_tok = cu.back();
|
||||
}
|
||||
};
|
||||
|
||||
int run_derive(const Step& s, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
const int idx = rad::derive_index("projection_on_rows");
|
||||
if (idx < 0) return -999;
|
||||
rad::DeriveInput in;
|
||||
in.plan = &s.plan;
|
||||
in.cu_seqlens = s.cu.data();
|
||||
in.n_tok = s.plan.n_tok;
|
||||
in.n_seq = (int64_t) s.plan.e.size();
|
||||
return rad::derive_row(idx)->fn(in, out, cap, n_out);
|
||||
}
|
||||
|
||||
/* libref's kernel table, dlopen'd from the build's radiance home (ctest sets RADIANCE_HOME), the
|
||||
* same way ref_test reaches it. */
|
||||
const RadKernelInfo* libref_kernel(const char* op) {
|
||||
static int (*count)(void) = nullptr;
|
||||
static const RadKernelInfo* (*at)(int) = nullptr;
|
||||
if (!count) {
|
||||
std::vector<std::string> paths;
|
||||
const std::string home = ::home();
|
||||
paths.push_back(home + "/kernels/libref.so");
|
||||
paths.push_back("build/radiance_home/kernels/libref.so");
|
||||
paths.push_back("./libref.so");
|
||||
for (const std::string& p : paths) {
|
||||
void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) continue;
|
||||
count = (int (*)(void)) dlsym(h, "rad_kernel_count");
|
||||
at = (const RadKernelInfo* (*)(int)) dlsym(h, "rad_kernel_at");
|
||||
if (count && at) break;
|
||||
count = nullptr;
|
||||
at = nullptr;
|
||||
}
|
||||
if (!count) return nullptr;
|
||||
}
|
||||
for (int i = 0; i < count(); ++i) {
|
||||
const RadKernelInfo* k = at(i);
|
||||
if (k && k->op && std::strcmp(k->op, op) == 0) return k;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(the_mask_follows_each_requests_own_choice) {
|
||||
Step s(2, 3);
|
||||
s.reqs[0].sp.use_control_vector = true; /* this conversation asked for the vector */
|
||||
s.reqs[1].sp.use_control_vector = false; /* this one did not */
|
||||
|
||||
int32_t mask[8] = { -1, -1, -1, -1, -1, -1, -1, -1 };
|
||||
int64_t n = 0;
|
||||
CHECK_OK(run_derive(s, mask, 8, &n));
|
||||
CHECK_EQ(n, (int64_t) 6);
|
||||
CHECK_EQ(mask[0], 1);
|
||||
CHECK_EQ(mask[2], 1);
|
||||
/* The second sequence's rows: untouched. A mixed step is what a naive "any request in the
|
||||
* step asked for it" would get wrong. */
|
||||
CHECK_EQ(mask[3], 0);
|
||||
CHECK_EQ(mask[5], 0);
|
||||
}
|
||||
|
||||
TEST(the_mask_is_all_zero_when_no_request_asked) {
|
||||
Step s(3, 2);
|
||||
int32_t mask[8] = { 9, 9, 9, 9, 9, 9, 9, 9 };
|
||||
int64_t n = 0;
|
||||
CHECK_OK(run_derive(s, mask, 8, &n));
|
||||
CHECK_EQ(n, (int64_t) 6);
|
||||
for (int i = 0; i < 6; ++i) CHECK_EQ(mask[i], 0);
|
||||
}
|
||||
|
||||
TEST(the_derivation_refuses_a_buffer_too_small) {
|
||||
Step s(2, 4);
|
||||
int32_t mask[4] = {};
|
||||
int64_t n = 0;
|
||||
CHECK(run_derive(s, mask, 4, &n) < 0); /* 8 rows in 4 slots */
|
||||
}
|
||||
|
||||
TEST(the_reference_projection_removes_the_direction_per_stream) {
|
||||
/* Directly the operation the package's README states, on a synthetic stream: after one
|
||||
* application every stream's component along v is (1 - scale) times what it was, and with a
|
||||
* unit direction at the stored scale 1 it is exactly zero, i.e. h -= (h.v) v. */
|
||||
const int64_t n = 8, hc = 2, rows = 2;
|
||||
std::vector<float> h((size_t) (rows * hc * n));
|
||||
std::vector<float> v((size_t) n);
|
||||
std::vector<int32_t> on{ 1, 0 };
|
||||
for (int64_t i = 0; i < n; ++i) v[(size_t) i] = (i % 2) ? 0.6f : 0.8f;
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < hc; ++c)
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
h[(size_t) ((r * hc + c) * n + i)] = (float) (0.1 * (r + 1) + 0.05 * (double) c +
|
||||
0.01 * (double) i);
|
||||
|
||||
/* The expected result, computed here independently of the kernel. */
|
||||
std::vector<float> want = h;
|
||||
for (int64_t c = 0; c < hc; ++c) {
|
||||
double dot = 0.0;
|
||||
for (int64_t i = 0; i < n; ++i) dot += (double) h[(size_t) ((0 * hc + c) * n + i)] * v[(size_t) i];
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
want[(size_t) ((0 * hc + c) * n + i)] =
|
||||
(float) ((double) h[(size_t) ((0 * hc + c) * n + i)] - dot * (double) v[(size_t) i]);
|
||||
}
|
||||
|
||||
/* Call libref's own launch, the way the engine does: through the plugin's kernel table. */
|
||||
const RadKernelInfo* k = libref_kernel("hc_project");
|
||||
if (!k || !k->launch) {
|
||||
ARTIFACT_MISSING("libref.so with an hc_project kernel");
|
||||
}
|
||||
|
||||
RadTensor t[3]{};
|
||||
t[0].data = h.data(); t[0].dtype = RAD_F32; t[0].rank = 2;
|
||||
t[0].shape[0] = rows; t[0].shape[1] = hc * n;
|
||||
t[0].stride[0] = hc * n; t[0].stride[1] = 1;
|
||||
t[1].data = v.data(); t[1].dtype = RAD_F32; t[1].rank = 1;
|
||||
t[1].shape[0] = n; t[1].stride[0] = 1;
|
||||
t[2].data = on.data(); t[2].dtype = RAD_I32; t[2].rank = 1;
|
||||
t[2].shape[0] = rows; t[2].stride[0] = 1;
|
||||
|
||||
const RadParam ps[] = {
|
||||
RAD_RANGE("M", 1, (int64_t) rows),
|
||||
RAD_INT("n", n),
|
||||
RAD_INT("hc", hc),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_STR("dtype", "f32"),
|
||||
};
|
||||
RadArgs a{};
|
||||
a.t = t; a.n_t = 3;
|
||||
a.p = ps; a.n_p = (int)(sizeof(ps) / sizeof(ps[0]));
|
||||
|
||||
const int rc = k->launch(&a, nullptr);
|
||||
CHECK_OK(rc);
|
||||
|
||||
for (size_t i = 0; i < h.size(); ++i) CHECK_NEAR(h[i], want[i], 1e-5);
|
||||
|
||||
/* The row with a zero mask is untouched, bit for bit: that is what makes an unprojected
|
||||
* request identical to a deployment with no vector loaded. */
|
||||
for (int64_t c = 0; c < hc; ++c)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const size_t k = (size_t) ((1 * hc + c) * n + i);
|
||||
CHECK_EQ(std::memcmp(&h[k], &want[k], sizeof(float)), 0);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -272,6 +272,72 @@ TEST(an_expert_reads_its_own_hessian_before_its_layers) {
|
||||
CHECK(same_planes(run(both, e11), run(only_pool, e11)));
|
||||
}
|
||||
|
||||
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
|
||||
* keyed by directory), one run each way: the output error agrees to rounding. Codes may
|
||||
* differ where error feedback lands on a rounding boundary. Without OpenBLAS both runs take
|
||||
* the loops and agree trivially. */
|
||||
NEED_LIBQUANT();
|
||||
const TempDir fast_dir("rad_quant_lapack"), loop_dir("rad_quant_loops");
|
||||
REQUIRE(!fast_dir.path.empty() && !loop_dir.path.empty());
|
||||
REQUIRE(write_gram(fast_dir.path + "/gram.r0.blk.2.attn_q.bin", kC, kT, H()));
|
||||
REQUIRE(write_gram(loop_dir.path + "/gram.r0.blk.2.attn_q.bin", kC, kT, H()));
|
||||
auto run = [&](const std::string& dir) {
|
||||
Opts o;
|
||||
o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str());
|
||||
return quantise(quantizer("gptq"), o, kName, kR, kC, weight());
|
||||
};
|
||||
const Quantised fast = run(fast_dir.path);
|
||||
setenv("RAD_LQ_LAPACK", "0", 1);
|
||||
const Quantised loops = run(loop_dir.path);
|
||||
unsetenv("RAD_LQ_LAPACK");
|
||||
REQUIRE_EQ(fast.status, RAD_OK);
|
||||
REQUIRE_EQ(loops.status, RAD_OK);
|
||||
const double ef = out_err(weight(), decode(fast, kR, kC));
|
||||
const double el = out_err(weight(), decode(loops, kR, kC));
|
||||
std::fprintf(stderr, " LAPACK %.9g, loops %.9g\n", ef, el);
|
||||
CHECK(std::fabs(ef - el) <= 1e-6 * el);
|
||||
}
|
||||
|
||||
TEST(a_column_split_hessian_is_assembled_from_its_rank_parts) {
|
||||
/* Under tensor parallelism a down projection's tap sees one rank's K / 2 input columns, and each
|
||||
* rank writes the Gram of its own as `<stem>.part`. GPTQ against the two parts must quantise
|
||||
* exactly as against one whole file holding them block diagonally (the cross-rank products
|
||||
* zero, never formed). Parts that do not cover K are reported and the weight is rounded to
|
||||
* nearest, as with no calibration at all. */
|
||||
NEED_LIBQUANT();
|
||||
const std::vector<float>& h = H();
|
||||
const int64_t k2 = kC / 2;
|
||||
std::vector<float> p0((size_t)(k2 * k2)), p1((size_t)(k2 * k2)), whole((size_t)(kC * kC), 0.0f);
|
||||
for (int64_t i = 0; i < k2; ++i)
|
||||
for (int64_t j = 0; j < k2; ++j) {
|
||||
p0[(size_t)(i * k2 + j)] = h[(size_t)(i * kC + j)];
|
||||
p1[(size_t)(i * k2 + j)] = h[(size_t)((k2 + i) * kC + k2 + j)];
|
||||
whole[(size_t)(i * kC + j)] = p0[(size_t)(i * k2 + j)];
|
||||
whole[(size_t)((k2 + i) * kC + k2 + j)] = p1[(size_t)(i * k2 + j)];
|
||||
}
|
||||
const TempDir tp("rad_quant_parts"), tw("rad_quant_whole"), ts("rad_quant_short"),
|
||||
tn("rad_quant_none");
|
||||
REQUIRE(!tp.path.empty() && !tw.path.empty() && !ts.path.empty() && !tn.path.empty());
|
||||
REQUIRE(write_gram(tp.path + "/gram.r0.blk.2.ffn_down.part.bin", k2, kT, p0));
|
||||
REQUIRE(write_gram(tp.path + "/gram.r1.blk.2.ffn_down.part.bin", k2, kT, p1));
|
||||
REQUIRE(write_gram(tw.path + "/gram.r0.blk.2.ffn_down.bin", kC, kT, whole));
|
||||
REQUIRE(write_gram(ts.path + "/gram.r0.blk.2.ffn_down.part.bin", k2, kT, p0));
|
||||
|
||||
auto run = [&](const std::string& dir) -> Quantised {
|
||||
Opts o;
|
||||
o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str());
|
||||
Quantised q = quantise(quantizer("gptq"), o, "blk.2.ffn_down.weight", kR, kC, weight());
|
||||
CHECK_EQ(q.status, RAD_OK);
|
||||
return q;
|
||||
};
|
||||
const Quantised parts = run(tp.path), one = run(tw.path), short_ = run(ts.path), none = run(tn.path);
|
||||
CHECK(same_planes(parts, one));
|
||||
CHECK(!same_planes(parts, none));
|
||||
CHECK(same_planes(short_, none));
|
||||
}
|
||||
|
||||
TEST(awq_scales_the_columns_the_input_says_matter) {
|
||||
NEED_LIBQUANT();
|
||||
Opts g, x;
|
||||
|
||||
@@ -81,6 +81,30 @@ TEST(a_rotated_int4_group_decodes_back_through_the_hadamard) {
|
||||
CHECK(eb < ea);
|
||||
}
|
||||
|
||||
TEST(a_rotated_int8_group_decodes_back_through_the_hadamard) {
|
||||
NEED_LIBQUANT();
|
||||
/* What gemm_nt_q reads at dtype i8a8h: i8 codes with a bf16 scale a (row, 128), each group
|
||||
* rotated by the unnormalised Hadamard and the 1/128 in the stored scale. A scale that kept
|
||||
* the factor, or lost it twice, decodes 128 times off, and a skipped rotation to noise. */
|
||||
const int64_t R = 32, C = 512;
|
||||
const std::vector<float> w = draw(R * C, 2, 30.0f);
|
||||
Opts plain, rot;
|
||||
plain.s("codes", "i8").i("group", 128).s("scale", "bf16");
|
||||
rot.s("codes", "i8").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
|
||||
Quantised a = quantise(quantizer("rtn"), plain, "x", R, C, w);
|
||||
Quantised b = quantise(quantizer("rtn"), rot, "x", R, C, w);
|
||||
REQUIRE_EQ(a.status, RAD_OK);
|
||||
REQUIRE_EQ(b.status, RAD_OK);
|
||||
CHECK_EQ(enc_name(b.enc), std::string("i8*bf16[1x128]/fwht128"));
|
||||
const double ea = rel_err(w, decode(a, R, C)), eb = rel_err(w, decode(b, R, C));
|
||||
std::fprintf(stderr, " int8 g128: plain %.5f, rotated %.5f\n", ea, eb);
|
||||
/* An int8 grid's error is a few parts in a thousand; with outliers the rotation is again the
|
||||
* better grid. */
|
||||
CHECK(ea < 0.03);
|
||||
CHECK(eb < 0.01);
|
||||
CHECK(eb < ea);
|
||||
}
|
||||
|
||||
TEST(the_w4nl_table_is_exact_in_e4m3_and_beats_minus_8_to_7_after_the_rotation) {
|
||||
NEED_LIBQUANT();
|
||||
/* The sixteen levels libr4d's w4nla8h kernel decodes, in its code order, as a container
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
/* r4d_ar_links_test.cpp -- the eight-rank two-shot's shard weights from the PCIe links
|
||||
* (libr4d/r4d_ar_links.h).
|
||||
*
|
||||
* Each case builds sysfs under a root directory, laid out like the eight-R9700 box the weights
|
||||
* were measured on: each card behind its on-card switch (upstream and downstream port at Gen5
|
||||
* x16, endpoint at Gen5 x16) under a root port whose link is the real slot. The slot shows only
|
||||
* at the root port, so a reader that stops at the card's own link sees eight equal cards.
|
||||
*
|
||||
* Bottleneck the slowest hop of a card's path, root port included
|
||||
* Weights round(4 * (rate / max)^2): two Gen4 x8 links give 4,1,0,4,0,1,4,4, the
|
||||
* repaired ones 4 and 1; a card whose path says nothing leaves the weights unknown
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "r4d_ar_links.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Root {
|
||||
std::string dir;
|
||||
Root() {
|
||||
std::string tmpl = radtest::tmp_path("root.XXXXXX");
|
||||
dir = mkdtemp(tmpl.data()) ? tmpl : "";
|
||||
}
|
||||
void put(const std::string& rel, const std::string& text) const {
|
||||
const fs::path p = fs::path(dir) / rel.substr(1);
|
||||
fs::create_directories(p.parent_path());
|
||||
std::ofstream(p) << text;
|
||||
}
|
||||
void link(const std::string& rel, const std::string& target) const {
|
||||
const fs::path p = fs::path(dir) / rel.substr(1);
|
||||
fs::create_directories(p.parent_path());
|
||||
fs::create_symlink(target, p);
|
||||
}
|
||||
};
|
||||
|
||||
/* A device under /sys/devices at `path` with its /sys/bus/pci/devices link; `speed` "" writes no
|
||||
* link files, as some bridges inside a switch do. */
|
||||
void pci(const Root& r, const std::string& path, const std::string& speed, int width) {
|
||||
const std::string bdf = path.substr(path.rfind('/') + 1);
|
||||
const std::string d = "/sys/devices/" + path;
|
||||
r.put(d + "/class", "0x060400\n");
|
||||
if (!speed.empty()) {
|
||||
r.put(d + "/current_link_speed", speed + "\n");
|
||||
r.put(d + "/current_link_width", std::to_string(width) + "\n");
|
||||
}
|
||||
r.link("/sys/bus/pci/devices/" + bdf, "../../../devices/" + path);
|
||||
}
|
||||
|
||||
std::string bdf_on(int bus) {
|
||||
char b[16];
|
||||
std::snprintf(b, sizeof b, "0000:%02x:00.0", bus);
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Card `i` behind root port 0000:00:0i.1 running `speed` x`width`; returns the card's BDF. */
|
||||
std::string card(const Root& r, int i, const std::string& speed, int width) {
|
||||
const std::string rp = "pci0000:00/0000:00:0" + std::to_string(i) + ".1";
|
||||
const std::string up = rp + "/" + bdf_on(0x10 + 3 * i);
|
||||
const std::string down = up + "/" + bdf_on(0x11 + 3 * i);
|
||||
const std::string ep = down + "/" + bdf_on(0x12 + 3 * i);
|
||||
pci(r, rp, speed, width);
|
||||
pci(r, up, "32.0 GT/s PCIe", 16);
|
||||
pci(r, down, "32.0 GT/s PCIe", 16);
|
||||
pci(r, ep, "32.0 GT/s PCIe", 16);
|
||||
return bdf_on(0x12 + 3 * i);
|
||||
}
|
||||
|
||||
struct Slot { const char* speed; int width; };
|
||||
|
||||
/* The weights the eight cards give, or "unknown", by the quadratic rule or the duplex model. */
|
||||
std::string weights(const Root& r, const Slot* slots, bool duplex = false) {
|
||||
std::string bdf[8];
|
||||
for (int i = 0; i < 8; ++i) bdf[i] = card(r, i, slots[i].speed, slots[i].width);
|
||||
double gbs[8] = { 0 };
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
R4DArLink l;
|
||||
if (r4d_ar_link_bottleneck(r.dir, bdf[i], &l)) gbs[i] = r4d_ar_link_gbs(l);
|
||||
}
|
||||
int w[8];
|
||||
if (!(duplex ? r4d_ar_weights_duplex(gbs, 8, w) : r4d_ar_weights_from_rates(gbs, 8, w)))
|
||||
return "unknown";
|
||||
std::string s;
|
||||
for (int i = 0; i < 8; ++i) s += (i ? "," : "") + std::to_string(w[i]);
|
||||
return s;
|
||||
}
|
||||
|
||||
const char* G5 = "32.0 GT/s PCIe";
|
||||
const char* G4 = "16.0 GT/s PCIe";
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(the_slowest_hop_is_the_root_port_behind_an_on_card_switch) {
|
||||
Root r;
|
||||
const std::string bdf = card(r, 2, G4, 8);
|
||||
R4DArLink l;
|
||||
REQUIRE(r4d_ar_link_bottleneck(r.dir, bdf, &l));
|
||||
CHECK_EQ(l.bdf, std::string("0000:00:02.1"));
|
||||
CHECK(l.gts == 16.0);
|
||||
CHECK_EQ(l.width, 8);
|
||||
CHECK(std::fabs(r4d_ar_link_gbs(l) - 16.0 * 8 * 128.0 / 130.0 / 8.0) < 1e-9);
|
||||
}
|
||||
|
||||
TEST(two_degraded_links_give_the_measured_weights) {
|
||||
Root r;
|
||||
const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 },
|
||||
{ G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } };
|
||||
CHECK_EQ(weights(r, s), std::string("4,1,0,4,0,1,4,4"));
|
||||
}
|
||||
|
||||
TEST(repaired_links_give_four_and_one) {
|
||||
Root r;
|
||||
const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G5, 16 }, { G5, 16 },
|
||||
{ G5, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } };
|
||||
CHECK_EQ(weights(r, s), std::string("4,1,4,4,1,1,4,4"));
|
||||
}
|
||||
|
||||
/* The duplex model on the board after the repair: x16 holds 2/9 of the message and x8 1/36, so
|
||||
* each direction of every link carries the same time's bytes; on the earlier board the Gen4 x8
|
||||
* cards hold nothing (they would need T B > N) and Gen5 x8 one seventh of x16. */
|
||||
TEST(the_duplex_model_balances_both_directions_of_every_link) {
|
||||
Root r;
|
||||
const Slot fixed[8] = { { G5, 16 }, { G5, 8 }, { G5, 8 }, { G5, 16 },
|
||||
{ G5, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } };
|
||||
CHECK_EQ(weights(r, fixed, true), std::string("64,8,8,64,8,8,64,64"));
|
||||
Root r2;
|
||||
const Slot older[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 },
|
||||
{ G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } };
|
||||
CHECK_EQ(weights(r2, older, true), std::string("64,9,0,64,0,9,64,64"));
|
||||
Root r3;
|
||||
Slot even[8];
|
||||
for (Slot& x : even) x = { G5, 16 };
|
||||
CHECK_EQ(weights(r3, even, true), std::string("64,64,64,64,64,64,64,64"));
|
||||
/* The time each rank's bytes take, (1 + 6 x) / B, is the same for every rank with a shard. */
|
||||
const double gbs[8] = { 63, 31.5, 31.5, 63, 31.5, 31.5, 63, 63 };
|
||||
int w[8];
|
||||
REQUIRE(r4d_ar_weights_duplex(gbs, 8, w));
|
||||
double sum = 0;
|
||||
for (int i = 0; i < 8; ++i) sum += w[i];
|
||||
const double tf = (1 + 6 * w[0] / sum) / gbs[0], ts = (1 + 6 * w[1] / sum) / gbs[1];
|
||||
CHECK(std::fabs(tf - ts) / tf < 1e-9);
|
||||
}
|
||||
|
||||
TEST(equal_links_give_equal_weights) {
|
||||
Root r;
|
||||
Slot s[8];
|
||||
for (Slot& x : s) x = { G5, 16 };
|
||||
CHECK_EQ(weights(r, s), std::string("4,4,4,4,4,4,4,4"));
|
||||
}
|
||||
|
||||
/* A Gen2 link moves 8 of every 10 bits, Gen3 on 128 of 130: 5.0 GT/s x16 is 8.0 GB/s, an eighth
|
||||
* of Gen5 x16 at 63.0, so its weight rounds to 0. */
|
||||
TEST(the_line_code_is_counted) {
|
||||
R4DArLink l;
|
||||
l.gts = 5.0; l.width = 16;
|
||||
CHECK(std::fabs(r4d_ar_link_gbs(l) - 8.0) < 1e-9);
|
||||
l.gts = 8.0; l.width = 16;
|
||||
CHECK(std::fabs(r4d_ar_link_gbs(l) - 8.0 * 16 * 128.0 / 130.0 / 8.0) < 1e-9);
|
||||
}
|
||||
|
||||
/* A hop without link files (a bridge inside a switch) is skipped; a path where no hop says
|
||||
* anything has no rate, and one such card leaves all weights unknown, not guessed. */
|
||||
TEST(a_silent_path_has_no_rate_and_no_weights) {
|
||||
Root r;
|
||||
const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 },
|
||||
{ G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } };
|
||||
std::string bdf[8];
|
||||
for (int i = 0; i < 8; ++i) bdf[i] = card(r, i, s[i].speed, s[i].width);
|
||||
pci(r, "pci0000:00/0000:00:09.1", "", 0);
|
||||
pci(r, "pci0000:00/0000:00:09.1/0000:40:00.0", "", 0);
|
||||
R4DArLink l;
|
||||
CHECK(!r4d_ar_link_bottleneck(r.dir, "0000:40:00.0", &l));
|
||||
CHECK(!r4d_ar_link_bottleneck(r.dir, "0000:41:00.0", &l));
|
||||
double gbs[8] = { 0 };
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
R4DArLink x;
|
||||
if (r4d_ar_link_bottleneck(r.dir, bdf[i], &x)) gbs[i] = r4d_ar_link_gbs(x);
|
||||
}
|
||||
int w[8];
|
||||
CHECK(!r4d_ar_weights_from_rates(gbs, 8, w));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "rad_plugin.h"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
@@ -47,11 +48,12 @@ struct Sched {
|
||||
std::vector<Fiber> f;
|
||||
void* main_sp = nullptr;
|
||||
int cur = -1, nthreads = 0;
|
||||
EmuIdx bid{};
|
||||
EmuIdx bid{}, bdim{}, gdim{};
|
||||
void (*body)(void*) = nullptr;
|
||||
void* ctx = nullptr;
|
||||
/* block barrier */
|
||||
/* block barrier; or_acc[g % 3] collects __syncthreads_or's predicates at generation g */
|
||||
int arrive = 0; unsigned gen = 0;
|
||||
int or_acc[3] = {};
|
||||
/* wave barriers and exchange slots, double-buffered by parity */
|
||||
int warrive[64] = {}; unsigned wgen[64] = {};
|
||||
int slot[64][2][32] = {};
|
||||
@@ -82,15 +84,26 @@ extern "C" void emu_entry();
|
||||
|
||||
EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; }
|
||||
EmuIdx& emu_block_idx() { return S.bid; }
|
||||
EmuIdx& emu_block_dim() { return S.bdim; }
|
||||
EmuIdx& emu_grid_dim() { return S.gdim; }
|
||||
|
||||
void __syncthreads() {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.gen;
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; }
|
||||
/* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every
|
||||
* write to it (threads arrive at g + 1 only after g completes) and behind every read of the
|
||||
* slot it shares a residue with (g - 2's, read before arriving at g - 1). */
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; }
|
||||
me.waiting = 1;
|
||||
while (S.gen == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
int __syncthreads_or(int p) {
|
||||
const unsigned g = S.gen;
|
||||
if (p) S.or_acc[g % 3] = 1;
|
||||
__syncthreads();
|
||||
return S.or_acc[g % 3];
|
||||
}
|
||||
|
||||
static void wave_barrier(int w) {
|
||||
Fiber& me = S.f[S.cur];
|
||||
@@ -165,6 +178,23 @@ static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
|
||||
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; });
|
||||
}
|
||||
namespace {
|
||||
struct Bytes8 {
|
||||
uint8_t v[8];
|
||||
uint8_t operator[](int e) const { return v[e]; }
|
||||
};
|
||||
}
|
||||
static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8];
|
||||
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) {
|
||||
Bytes8 pa, pb;
|
||||
std::memcpy(pa.v, &a, 8);
|
||||
std::memcpy(pb.v, &b, 8);
|
||||
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); });
|
||||
}
|
||||
emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) {
|
||||
std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n");
|
||||
std::abort();
|
||||
}
|
||||
unsigned emu_ballot(bool p) {
|
||||
int l;
|
||||
const int* s = exchange(p ? 1 : 0, &l, kOpBallot);
|
||||
@@ -236,6 +266,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
}
|
||||
lds_reserve(dyn_lds);
|
||||
S.body = body; S.ctx = ctx; S.nthreads = n;
|
||||
S.bdim = EmuIdx{block.x, block.y, block.z};
|
||||
S.gdim = EmuIdx{grid.x, grid.y, grid.z};
|
||||
S.f.resize(n);
|
||||
for (auto& f : S.f) if (!f.stack) f.stack.reset(new char[kStack]);
|
||||
for (unsigned bz = 0; bz < grid.z; ++bz)
|
||||
@@ -244,6 +276,7 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
S.bid = EmuIdx{bx, by, bz};
|
||||
std::memset(g_lds, 0xA5, dyn_lds);
|
||||
S.arrive = 0; S.gen = 0;
|
||||
for (int& a : S.or_acc) a = 0;
|
||||
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; }
|
||||
for (int t = 0; t < n; ++t) {
|
||||
Fiber& f = S.f[t];
|
||||
|
||||
@@ -15,8 +15,12 @@
|
||||
#define __device__
|
||||
#define __host__
|
||||
#define __shared__ static
|
||||
#define __constant__
|
||||
#define __forceinline__ inline
|
||||
#define __launch_bounds__(n)
|
||||
/* R4D_WAVES (r4d_common.h) names a kernel attribute; on the host it becomes an empty attribute */
|
||||
#define amdgpu_waves_per_eu(lo, hi)
|
||||
#define __align__(n) __attribute__((aligned(n)))
|
||||
|
||||
struct dim3 {
|
||||
unsigned x, y, z;
|
||||
@@ -29,6 +33,25 @@ inline hipError_t hipGetLastError() { return 0; }
|
||||
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
|
||||
struct hipDeviceProp_t { size_t sharedMemPerBlock; };
|
||||
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
|
||||
/* no graphs: a stream never captures */
|
||||
enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 };
|
||||
inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) {
|
||||
*s = hipStreamCaptureStatusNone;
|
||||
return hipSuccess;
|
||||
}
|
||||
/* every launch runs to completion before it returns */
|
||||
inline hipError_t hipDeviceSynchronize() { return hipSuccess; }
|
||||
/* __device__ variables are host globals, so a symbol copy is a memcpy */
|
||||
enum hipMemcpyKind { hipMemcpyHostToDevice = 1, hipMemcpyDeviceToHost = 2 };
|
||||
#define HIP_SYMBOL(s) (&(s))
|
||||
inline hipError_t hipMemcpyFromSymbol(void* dst, const void* sym, size_t n, size_t off, hipMemcpyKind) {
|
||||
std::memcpy(dst, (const char*)sym + off, n);
|
||||
return hipSuccess;
|
||||
}
|
||||
inline hipError_t hipMemcpyToSymbol(const void* sym, const void* src, size_t n, size_t off, hipMemcpyKind) {
|
||||
std::memcpy((char*)sym + off, src, n);
|
||||
return hipSuccess;
|
||||
}
|
||||
inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
|
||||
*p = hipDeviceProp_t{};
|
||||
p->sharedMemPerBlock = 64 * 1024;
|
||||
@@ -38,9 +61,15 @@ inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
|
||||
struct EmuIdx { unsigned x, y, z; };
|
||||
EmuIdx& emu_thread_idx();
|
||||
EmuIdx& emu_block_idx();
|
||||
EmuIdx& emu_block_dim();
|
||||
EmuIdx& emu_grid_dim();
|
||||
#define threadIdx (emu_thread_idx())
|
||||
#define blockIdx (emu_block_idx())
|
||||
#define blockDim (emu_block_dim())
|
||||
#define gridDim (emu_grid_dim())
|
||||
void __syncthreads();
|
||||
/* the block barrier, returning whether any thread passed a nonzero predicate */
|
||||
int __syncthreads_or(int p);
|
||||
int emu_bpermute(int addr, int v);
|
||||
int emu_readlane(int v, int lane);
|
||||
#define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v))
|
||||
@@ -73,6 +102,14 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
|
||||
return r;
|
||||
}
|
||||
#define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s))
|
||||
/* HIP's __byte_perm: result byte i is the byte of {y, x} (x low) that the low three bits of
|
||||
* nibble i of s name; only the low four nibbles are read */
|
||||
inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) {
|
||||
const unsigned long long d = ((unsigned long long)y << 32) | x;
|
||||
unsigned r = 0;
|
||||
for (int i = 0; i < 4; ++i) r |= (unsigned)((d >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i);
|
||||
return r;
|
||||
}
|
||||
/* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a
|
||||
* fence or a scheduling barrier orders nothing more. */
|
||||
#define __builtin_amdgcn_s_barrier() __syncthreads()
|
||||
@@ -81,15 +118,38 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
|
||||
/* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */
|
||||
template <class T>
|
||||
inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; }
|
||||
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
|
||||
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
|
||||
typedef short emu_v8s __attribute__((ext_vector_type(8)));
|
||||
typedef float emu_v8f __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
|
||||
/* the __bf16 fragments of r4d_gdn_wmma.h, the same bits */
|
||||
typedef __bf16 emu_v8bf __attribute__((ext_vector_type(8)));
|
||||
inline emu_v8f emu_wmma_bf16(emu_v8bf a, emu_v8bf b, emu_v8f c) {
|
||||
return emu_wmma_bf16(__builtin_bit_cast(emu_v8s, a), __builtin_bit_cast(emu_v8s, b), c);
|
||||
}
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c))
|
||||
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
|
||||
/* v_wmma_f32_16x16x16_fp8_fp8 (gfx12, wave32): the bf16 form's layout with eight E4M3 bytes a
|
||||
* lane, element e in byte e. Each output is c plus its 16 products in k order: not the hardware's
|
||||
* internal order, but a function of the output's own row, column and c alone, as the hardware's
|
||||
* is, which is what a comparison of two kernels over the same fragments relies on. */
|
||||
typedef int emu_v2i __attribute__((ext_vector_type(2)));
|
||||
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c) emu_wmma_fp8((a), (b), (c))
|
||||
/* v_wmma_i32_16x16x16_iu8: not emulated; reported when reached */
|
||||
typedef int emu_v8i __attribute__((ext_vector_type(8)));
|
||||
emu_v8i emu_wmma_iu8(bool sa, emu_v2i a, bool sb, emu_v2i b, emu_v8i c, bool clamp);
|
||||
#define __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(sa, a, sb, b, c, cl) \
|
||||
emu_wmma_iu8((sa), (a), (sb), (b), (c), (cl))
|
||||
/* global_load_tr_b128: not emulated; reported when reached */
|
||||
emu_v8s emu_load_tr_b128(const void* p);
|
||||
#define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p))
|
||||
@@ -120,9 +180,34 @@ inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; }
|
||||
inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; }
|
||||
inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */
|
||||
/* The device's fast exponential is not bit-exact to expf; here it is expf, so a test compares two
|
||||
* kernels that both take it, never a kernel against a host value of it. */
|
||||
inline float __expf(float x) { return std::exp(x); }
|
||||
inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; }
|
||||
inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; }
|
||||
/* The float shuffles over ds_bpermute, for one-dimensional blocks, within groups of `width`
|
||||
* lanes: __shfl_xor reads lane L ^ mask, __shfl lane `src`, __shfl_down lane L + delta (its own
|
||||
* value past the group's end) */
|
||||
inline float emu_shfl_from(float v, int src) {
|
||||
return __int_as_float(emu_bpermute(src << 2, __float_as_int(v)));
|
||||
}
|
||||
inline float __shfl_xor(float v, int mask, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31;
|
||||
return emu_shfl_from(v, (lane & ~(width - 1)) | ((lane ^ mask) & (width - 1)));
|
||||
}
|
||||
inline float __shfl(float v, int src, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31;
|
||||
return emu_shfl_from(v, (lane & ~(width - 1)) | (src & (width - 1)));
|
||||
}
|
||||
inline float __shfl_down(float v, unsigned delta, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31, in_group = lane & (width - 1);
|
||||
return emu_shfl_from(v, in_group + (int)delta < width ? lane + (int)delta : lane);
|
||||
}
|
||||
/* HIP declares the classification functions in the global namespace */
|
||||
using std::isfinite;
|
||||
inline int min(int a, int b) { return a < b ? a : b; }
|
||||
inline int max(int a, int b) { return a > b ? a : b; }
|
||||
|
||||
/* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0);
|
||||
@@ -154,6 +239,9 @@ int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, cons
|
||||
}
|
||||
#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \
|
||||
emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)
|
||||
/* hipLaunchKernelGGL, for units that launch with it directly: the same call as R4D_EMIT. */
|
||||
#define hipLaunchKernelGGL(kernel, grid, block, lds, stream, ...) \
|
||||
((void)(stream), (void)emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__))
|
||||
/* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending
|
||||
* at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one
|
||||
* past the end faults */
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
/* tests/r4d_emu: GLM's DSA scoring and selection split over the tensor-parallel ranks by query
|
||||
* rows (r4d_dsa.hip, then r4d_qsa_select_bf16.hip) on the host SIMT emulator.
|
||||
*
|
||||
* Each rank scores its run of R = 4 * ceil(M / (4 * world)) rows with `row_part`, selects over
|
||||
* the rows of that run that exist with the rebased bounds the scorer wrote (`cu_part`), and the
|
||||
* runs are laid end to end as the all_gather concatenates them. The joined table, nsel and
|
||||
* seqused must equal the unsplit scorer and selection byte for byte on every row of the step; a
|
||||
* run's scores must equal the unsplit scores' rows, and its rows past the step score -inf. The
|
||||
* fixtures mix decode rows with a prefill chunk, a missing page, duplicated keys (exact ties) and
|
||||
* signed gates, at world sizes where every rank has rows and where the last ranks have none. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kHeads = 32, kN = 128, kRatio = 4, kPitch = 136;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
struct Fix {
|
||||
int S = 0, M = 0, nb = 0, pages = 0, topk = 0;
|
||||
std::vector<int32_t> cu, nc, pos, bt;
|
||||
std::vector<uint8_t> q, cache; /* [M*32, 128] codes; [pages, 1, 4, 34] packed keys */
|
||||
std::vector<float> qs, gate; /* [M*32, 1], [M, 32] */
|
||||
};
|
||||
|
||||
/* `decode` one-row sequences, then one prefill chunk of `chunk` rows at `start`. */
|
||||
Fix make(uint32_t seed, int decode, int chunk, int start, int topk) {
|
||||
std::mt19937 rng(seed);
|
||||
std::uniform_int_distribution<int> byte(0, 255), coin(0, 99);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
Fix f;
|
||||
f.S = decode + 1;
|
||||
f.M = decode + chunk;
|
||||
f.topk = topk;
|
||||
f.cu.push_back(0);
|
||||
for (int s = 0; s < decode; ++s) {
|
||||
const int p = 40 + 37 * s + byte(rng) % 50;
|
||||
f.pos.push_back(p);
|
||||
f.cu.push_back(f.cu.back() + 1);
|
||||
f.nc.push_back((p + 1) / kRatio);
|
||||
}
|
||||
for (int i = 0; i < chunk; ++i) f.pos.push_back(start + i);
|
||||
f.cu.push_back(f.M);
|
||||
f.nc.push_back((start + chunk) / kRatio);
|
||||
for (int c : f.nc) f.nb = std::max(f.nb, c + 2);
|
||||
f.pages = f.S * f.nb + 3;
|
||||
f.bt.assign((size_t)f.S * f.nb, -1);
|
||||
for (int s = 0; s < f.S; ++s)
|
||||
for (int b = 0; b <= f.nc[s] && b < f.nb; ++b)
|
||||
f.bt[(size_t)s * f.nb + b] = (s * f.nb + b * 7) % f.pages;
|
||||
f.bt[(size_t)(f.S - 1) * f.nb + 3] = -1;
|
||||
auto code = [&] {
|
||||
int v;
|
||||
do v = byte(rng);
|
||||
while ((v & 0x7f) == 0x7f);
|
||||
return (uint8_t)v;
|
||||
};
|
||||
f.cache.assign((size_t)f.pages * kPitch, 0);
|
||||
for (int p = 0; p < f.pages; ++p) {
|
||||
uint8_t* page = &f.cache[(size_t)p * kPitch];
|
||||
/* Every fifth page repeats its predecessor's key: equal scores on one row. */
|
||||
if (p % 5 == 4)
|
||||
std::memcpy(page, page - kPitch, kPitch);
|
||||
else {
|
||||
for (int d = 0; d < kN; ++d) page[d] = code();
|
||||
const float scale = std::ldexp(1.0f, -6 - p % 3);
|
||||
std::memcpy(page + kN, &scale, 4);
|
||||
}
|
||||
}
|
||||
f.q.resize((size_t)f.M * kHeads * kN);
|
||||
for (auto& v : f.q) v = code();
|
||||
f.qs.resize((size_t)f.M * kHeads);
|
||||
for (size_t i = 0; i < f.qs.size(); ++i) f.qs[i] = std::ldexp(1.0f, -5 - (int)(i % 3));
|
||||
f.gate.resize((size_t)f.M * kHeads);
|
||||
for (auto& v : f.gate) v = nd(rng) * (coin(rng) < 10 ? 0.0f : 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
RadParam pint(const char* k, long long v) { return { k, RAD_P_INT, v, 0, nullptr }; }
|
||||
|
||||
/* Scores `rows` score rows from step row `part * rows` (part < 0: the whole step, no row_part). */
|
||||
int score(const Fix& f, const uint8_t* q, const float* qs, const float* gate, int64_t qrows,
|
||||
int part, int rows, float* out, int32_t* cu_part) {
|
||||
RadTensor t[10] = {
|
||||
tens((void*)q, RAD_F8E4M3, { qrows * kHeads, kN }),
|
||||
tens((void*)qs, RAD_F32, { qrows * kHeads, 1 }),
|
||||
tens((void*)gate, RAD_F32, { qrows, kHeads }),
|
||||
tens((void*)f.cache.data(), RAD_U8, { f.pages, 1, 4, 34 }),
|
||||
RadTensor{},
|
||||
tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }),
|
||||
tens((void*)f.cu.data(), RAD_I32, { f.S + 1 }),
|
||||
tens((void*)f.nc.data(), RAD_I32, { f.S }),
|
||||
tens(out, RAD_F32, { rows, f.nb }),
|
||||
cu_part ? tens(cu_part, RAD_I32, { f.S + 1 }) : RadTensor{},
|
||||
};
|
||||
t[3].stride[0] = kPitch;
|
||||
RadParam p[7] = { pint("M", rows), pint("n", kN), pint("heads", kHeads), pint("blocks", f.nb),
|
||||
pint("seqs", f.S), { "dtype", RAD_P_STR, 0, 0, "fp8_e4m3" },
|
||||
pint("row_part", part) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 10;
|
||||
a.p = p;
|
||||
a.n_p = part < 0 ? 6 : 7;
|
||||
return r4d_rad_dsa_score(&a, nullptr);
|
||||
}
|
||||
|
||||
int select(const Fix& f, const float* sc, int rows, const int32_t* pos, const int32_t* cu,
|
||||
int32_t* sel, int32_t* nsel, int32_t* seqused) {
|
||||
RadTensor t[8] = {
|
||||
tens((void*)sc, RAD_F32, { rows, f.nb }),
|
||||
tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }),
|
||||
tens((void*)f.nc.data(), RAD_I32, { f.S }),
|
||||
tens((void*)pos, RAD_I32, { rows }),
|
||||
tens((void*)cu, RAD_I32, { f.S + 1 }),
|
||||
tens(sel, RAD_I32, { rows, f.topk + 1 }),
|
||||
tens(nsel, RAD_I32, { rows }),
|
||||
tens(seqused, RAD_I32, { rows }),
|
||||
};
|
||||
RadParam p[6] = { pint("M", rows), pint("blocks", f.nb), pint("topk", f.topk),
|
||||
pint("ratio", kRatio), pint("seqs", f.S), pint("signed", 1) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 8;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
const int64_t need = r4d_rad_qsa_select_scratch(&a);
|
||||
std::vector<uint32_t> scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u);
|
||||
a.scratch = scratch.data();
|
||||
a.scratch_bytes = need;
|
||||
return r4d_rad_qsa_select(&a, nullptr);
|
||||
}
|
||||
|
||||
int check(const char* name, const Fix& f) {
|
||||
const int M = f.M, K = f.topk + 1;
|
||||
std::vector<float> want_sc((size_t)M * f.nb);
|
||||
std::vector<int32_t> want_sel((size_t)M * K, 0x55555555), want_n(M), want_su(M);
|
||||
if (score(f, f.q.data(), f.qs.data(), f.gate.data(), M, -1, M, want_sc.data(), nullptr) ||
|
||||
select(f, want_sc.data(), M, f.pos.data(), f.cu.data(), want_sel.data(), want_n.data(),
|
||||
want_su.data())) {
|
||||
std::printf("FAIL %s: the unsplit launch\n", name);
|
||||
return 1;
|
||||
}
|
||||
int fails = 0;
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
const int R = 4 * ((M + 4 * world - 1) / (4 * world));
|
||||
const int64_t padded = (int64_t)world * R;
|
||||
/* The step's query rows, then rows past the step that a last run reads no further than. */
|
||||
std::vector<uint8_t> q((size_t)padded * kHeads * kN, 0x38);
|
||||
std::vector<float> qs((size_t)padded * kHeads, 1.0f), gate((size_t)padded * kHeads, 3.0f);
|
||||
std::memcpy(q.data(), f.q.data(), f.q.size());
|
||||
std::memcpy(qs.data(), f.qs.data(), f.qs.size() * 4);
|
||||
std::memcpy(gate.data(), f.gate.data(), f.gate.size() * 4);
|
||||
std::vector<int32_t> sel((size_t)padded * K, 0x55555555), ns(padded, 0x55555555),
|
||||
su(padded, 0x55555555);
|
||||
bool ok = true;
|
||||
const char* why = "";
|
||||
for (int part = 0; part < world && ok; ++part) {
|
||||
const int r0 = part * R, have = std::min(R, M - r0);
|
||||
std::vector<float> sc((size_t)R * f.nb, 7.0f);
|
||||
std::vector<int32_t> cu_part(f.S + 1, 0x55555555);
|
||||
if (score(f, q.data(), qs.data(), gate.data(), padded, part, R, sc.data(),
|
||||
cu_part.data())) {
|
||||
ok = false, why = "score launch";
|
||||
break;
|
||||
}
|
||||
for (int s = 0; s <= f.S; ++s) ok = ok && cu_part[s] == f.cu[s] - r0;
|
||||
if (!ok) {
|
||||
why = "cu_part";
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < R && ok; ++i)
|
||||
for (int b = 0; b < f.nb && ok; ++b) {
|
||||
const float v = sc[(size_t)i * f.nb + b];
|
||||
ok = i < have ? std::memcmp(&v, &want_sc[(size_t)(r0 + i) * f.nb + b], 4) == 0
|
||||
: v == -INFINITY;
|
||||
}
|
||||
if (!ok) {
|
||||
why = "scores";
|
||||
break;
|
||||
}
|
||||
if (have <= 0) continue;
|
||||
if (select(f, sc.data(), have, f.pos.data() + r0, cu_part.data(), &sel[(size_t)r0 * K],
|
||||
&ns[r0], &su[r0])) {
|
||||
ok = false, why = "select launch";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok) {
|
||||
ok = std::memcmp(sel.data(), want_sel.data(), want_sel.size() * 4) == 0;
|
||||
why = "selection";
|
||||
}
|
||||
if (ok) {
|
||||
ok = std::memcmp(ns.data(), want_n.data(), (size_t)M * 4) == 0 &&
|
||||
std::memcmp(su.data(), want_su.data(), (size_t)M * 4) == 0;
|
||||
why = "nsel or seqused";
|
||||
}
|
||||
if (!ok) {
|
||||
std::printf("FAIL %s world %d (R %d): %s differs\n", name, world, R, why);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int fails = 0, cases = 0;
|
||||
struct Case {
|
||||
const char* name;
|
||||
uint32_t seed;
|
||||
int decode, chunk, start, topk;
|
||||
} cases_[] = {
|
||||
{ "prefill chunk alone", 1, 0, 64, 300, 16 },
|
||||
{ "decode rows beside a chunk", 2, 6, 61, 517, 32 },
|
||||
{ "chunk from position 0, short history", 3, 2, 37, 0, 8 },
|
||||
{ "rows below topk blocks", 4, 3, 29, 20, 64 },
|
||||
};
|
||||
for (const auto& c : cases_) {
|
||||
fails += check(c.name, make(c.seed, c.decode, c.chunk, c.start, c.topk));
|
||||
++cases;
|
||||
}
|
||||
std::printf("dsa split: %d fixture(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. The form the launcher picks
|
||||
* at each shape (a tile of rows x columns a wave with its steps of k in flight, by M and N; the
|
||||
* shapes reach every one, with K past and short of whole groups of steps) must match the
|
||||
* arithmetic written out here bit for bit: lane l folds k = l, l+32, ... with fmaf, then the xor
|
||||
* butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding stay untouched.
|
||||
*
|
||||
* router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written
|
||||
* out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
static float gemm_model(const uint16_t* x, const float* w, int k) {
|
||||
float lane[32];
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
float s = 0;
|
||||
for (int j = l; j < k; j += 32) s = std::fmaf(b2f(x[j]), w[j], s);
|
||||
lane[l] = s;
|
||||
}
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
float next[32];
|
||||
for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask];
|
||||
std::memcpy(lane, next, sizeof lane);
|
||||
}
|
||||
return lane[0];
|
||||
}
|
||||
|
||||
static void router_model(const float* lg, const float* bias, int bp, int ne, int k, int norm,
|
||||
float factor, int* ids, float* w) {
|
||||
float prob[512], rank[512], chosen[32], total = 0;
|
||||
int index[32];
|
||||
for (int e = 0; e < ne; ++e) {
|
||||
prob[e] = 1.0f / (1.0f + expf(-lg[e]));
|
||||
rank[e] = prob[e] + bias[(size_t)e * bp];
|
||||
}
|
||||
for (int j = 0; j < k; ++j) {
|
||||
int best = 0;
|
||||
for (int e = 1; e < ne; ++e)
|
||||
if (rank[e] > rank[best]) best = e;
|
||||
index[j] = best;
|
||||
chosen[j] = prob[best];
|
||||
total += chosen[j];
|
||||
rank[best] = -INFINITY;
|
||||
}
|
||||
const float mult = norm ? factor / (total + 1e-20f) : factor;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
ids[j] = index[j];
|
||||
w[j] = chosen[j] * mult;
|
||||
}
|
||||
}
|
||||
|
||||
static void router_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
struct Shape {
|
||||
int M, ne, k, norm;
|
||||
bool ties;
|
||||
};
|
||||
const Shape shapes[] = { { 1, 288, 8, 1, false }, { 6, 288, 8, 1, false },
|
||||
{ 20, 288, 8, 1, true }, { 48, 288, 8, 1, false },
|
||||
{ 6, 288, 8, 1, true }, { 5, 8, 8, 0, true },
|
||||
{ 5, 32, 32, 0, true }, { 7, 300, 8, 1, false },
|
||||
{ 3, 512, 32, 1, true } };
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.ties ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias) v = sh.ties ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
RadTensor t[4]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 4;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
std::vector<int> ids((size_t)M * ip, -77);
|
||||
std::vector<float> w((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids.data();
|
||||
t[3].data = w.data();
|
||||
++cases;
|
||||
const int rc = r4d_rad_router_sigmoid_topk(&a, nullptr);
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M && rc == RAD_OK; ++r) {
|
||||
int mi[32];
|
||||
float mw[32];
|
||||
router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw);
|
||||
bad += std::memcmp(mi, &ids[(size_t)r * ip], (size_t)k * 4) != 0;
|
||||
bad += std::memcmp(mw, &w[(size_t)r * wp], (size_t)k * 4) != 0;
|
||||
for (int c = k; c < ip; ++c) bad += ids[(size_t)r * ip + c] != -77;
|
||||
for (int c = k; c < wp; ++c) bad += w[(size_t)r * wp + c] != -7.25f;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL router wave select against the scan at M=%d ne=%d k=%d%s (rc %d): "
|
||||
"%d\n",
|
||||
M, ne, k, sh.ties ? " tied" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(17);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
};
|
||||
// One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles.
|
||||
const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 },
|
||||
{ 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 },
|
||||
{ 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 },
|
||||
{ 16, 288, 1056 }, { 24, 288, 1040 }, { 40, 36, 1024 } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3;
|
||||
std::vector<uint16_t> x((size_t)M * xp);
|
||||
std::vector<float> w((size_t)N * K);
|
||||
for (auto& v : x) v = f2b(nd(rng));
|
||||
for (auto& v : w) v = nd(rng) * 0.03f;
|
||||
RadTensor t[3]{};
|
||||
t[0].data = x.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = K;
|
||||
t[0].stride[0] = xp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = w.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 2;
|
||||
t[1].shape[0] = N;
|
||||
t[1].shape[1] = K;
|
||||
t[1].stride[0] = K;
|
||||
t[1].stride[1] = 1;
|
||||
t[2].dtype = RAD_F32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = N;
|
||||
t[2].stride[0] = yp;
|
||||
t[2].stride[1] = 1;
|
||||
RadParam p[4]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3].key = "dtype";
|
||||
p[3].kind = RAD_P_STR;
|
||||
p[3].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 3;
|
||||
a.p = p;
|
||||
a.n_p = 4;
|
||||
std::vector<float> y((size_t)M * yp, -7.25f);
|
||||
t[2].data = y.data();
|
||||
++cases;
|
||||
const int rc = r4d_rad_gemm_nt_f32(&a, nullptr);
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M && rc == RAD_OK; ++r) {
|
||||
for (int c = 0; c < N; ++c) {
|
||||
const float e = gemm_model(&x[(size_t)r * xp], &w[(size_t)c * K], K);
|
||||
bad += std::memcmp(&e, &y[(size_t)r * yp + c], 4) != 0;
|
||||
}
|
||||
for (int c = N; c < yp; ++c) bad += y[(size_t)r * yp + c] != -7.25f;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL %s at M=%d N=%d K=%d against its model (rc %d): %d words\n",
|
||||
emu_last_kernel, M, N, K, rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
router_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT
|
||||
* emulator. The form the rule picks at each shape (the decode form at one and two column tiles a
|
||||
* wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile,
|
||||
* which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma
|
||||
* chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that
|
||||
* leaves the decode form's last wave group partly idle are covered; the output's pitch padding
|
||||
* stays untouched. The grouped row at GLM's MTP slices is held to a host restatement
|
||||
* (grouped_cases). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
/* The grouped row at GLM's MTP slices (288 experts, top 8) below 384 routed rows -- the small-M
|
||||
* form at gate_up, the expert-major form at down -- against a host restatement of the
|
||||
* per-element sequence: per 128 of K in order, the
|
||||
* 128-product sum of the emulated WMMA chain from zero, folded as raw * (activation scale *
|
||||
* weight scale) and added. Dropped slots inside runs and past the routed rows, runs longer than an
|
||||
* A tile, token and sorted rows, pointer tables over three slices a class. */
|
||||
static int grouped_cases(int& cases) {
|
||||
struct G {
|
||||
const char* name;
|
||||
int N, K;
|
||||
bool sorted_a;
|
||||
std::vector<int> live;
|
||||
int tail;
|
||||
const char* kernel;
|
||||
};
|
||||
const G all[] = {
|
||||
{ "MTP gate_up, one token", 512, 4096, false, { 1, 1, 1, 1, 1, 1, 1, 1 }, 0,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP gate_up, runs past one tile", 512, 4096, false, { 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }, 2,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP down, six tokens", 4096, 256, true, { 3, 1, 10, 2, 1, 5, 1, 1, 17, 4 },
|
||||
3, "(fp8_f32scale_experts<128, 4>)" },
|
||||
};
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
int fails = 0;
|
||||
std::mt19937 rng(77);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (const G& g : all) {
|
||||
const int E = 288, top = 8, N = g.N, K = g.K, kb = K / 128;
|
||||
std::vector<int> runs(E, 0);
|
||||
for (size_t i = 0; i < g.live.size(); ++i) runs[at[i]] = g.live[i];
|
||||
int routed = 0;
|
||||
for (int r : runs) routed += r;
|
||||
const int T = (routed + g.tail + top - 1) / top * top;
|
||||
const int Arows = g.sorted_a ? T : T / top, ap = K + 16, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
std::vector<float> as((size_t)Arows * kb);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
std::vector<uint8_t> w[2];
|
||||
std::vector<float> s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
w[q].resize((size_t)3 * N * K);
|
||||
s[q].resize((size_t)3 * (N / 128) * kb);
|
||||
for (auto& v : w[q]) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
for (auto& v : s[q]) v = std::exp2(oct(rng)) * 0.01f;
|
||||
for (int x = 0; x < E / 2; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % 3) * N * K);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % 3) * (N / 128) * kb);
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777), got((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int n = 0; n < N; ++n) {
|
||||
uint16_t& out = ref[(size_t)r * yp + n];
|
||||
out = 0;
|
||||
if (owner[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1;
|
||||
const bool rv = sorted[r] >= 0;
|
||||
const int ar = !rv ? -1 : g.sorted_a ? r : sorted[r] / top;
|
||||
const uint8_t* wr = (const uint8_t*)wt[q][(size_t)(e / 2)] + (size_t)n * K;
|
||||
const float* sr = (const float*)st[q][(size_t)(e / 2)] + (size_t)(n / 128) * kb;
|
||||
float acc = 0.f;
|
||||
for (int b = 0; b < kb; ++b) {
|
||||
float raw = 0.f;
|
||||
if (rv)
|
||||
for (int k = b * 128; k < b * 128 + 128; ++k)
|
||||
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + k]) *
|
||||
rad_fp8e4m3_to_f32(wr[k]);
|
||||
const float scale = rv ? as[(size_t)ar * kb + b] * sr[b] : 0.f;
|
||||
const float t = raw * scale;
|
||||
acc = acc + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &acc, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
auto ten3 = [](const void* const* tab, uint32_t dt, int64_t n0, int64_t n1, int64_t n2) {
|
||||
RadTensor t{};
|
||||
t.data = (void*)tab;
|
||||
t.dtype = dt;
|
||||
t.rank = 3;
|
||||
t.shape[0] = n0;
|
||||
t.shape[1] = n1;
|
||||
t.shape[2] = n2;
|
||||
t.stride[0] = 0;
|
||||
t.stride[1] = n2;
|
||||
t.stride[2] = 1;
|
||||
return t;
|
||||
};
|
||||
RadTensor t[9] = { mat(a.data(), RAD_F8E4M3, Arows, K, ap),
|
||||
mat(as.data(), RAD_F32, Arows, kb, kb),
|
||||
ten3(wt[0].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[0].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
ten3(wt[1].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[1].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
mat(got.data(), RAD_BF16, T, N, yp) };
|
||||
t[4].data = sorted.data();
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].data = offsets.data();
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = E + 1;
|
||||
t[5].stride[0] = 1;
|
||||
RadParam p[10]{};
|
||||
p[0] = { "M", RAD_P_INT, T / top };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "N_odd", RAD_P_INT, N };
|
||||
p[4] = { "K_odd", RAD_P_INT, K };
|
||||
p[5] = { "n_expert", RAD_P_INT, E };
|
||||
p[6] = { "top_k", RAD_P_INT, top };
|
||||
p[7] = { "group", RAD_P_INT, 128 };
|
||||
p[8].key = "a_order";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = g.sorted_a ? "sorted" : "token";
|
||||
p[9].key = "dtype";
|
||||
p[9].kind = RAD_P_STR;
|
||||
p[9].sval = "fp8a8f32";
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 10;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = r4d_rad_moe_fp8_f32scale(&ar, nullptr);
|
||||
size_t i = 0;
|
||||
while (i < got.size() && got[i] == ref[i]) ++i;
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, g.kernel) || i != got.size() ||
|
||||
live < routed * N / 2) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu of %zu, %d live\n",
|
||||
g.name, T, emu_last_kernel, g.kernel, rc, i, got.size(), live);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(31);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
const char* kernel;
|
||||
};
|
||||
const char* const dec1 = "(fp8_f32scale_decode<1, 1>)";
|
||||
const char* const dec2 = "(fp8_f32scale_decode<1, 2>)";
|
||||
const char* const rows = "fp8_f32scale_rows<R>";
|
||||
// Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column
|
||||
// tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096.
|
||||
const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 },
|
||||
{ 17, 256, 512, dec1 }, { 48, 128, 512, dec1 },
|
||||
{ 2, 128, 256, dec1 }, { 5, 256, 128, dec1 },
|
||||
{ 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 },
|
||||
{ 20, 640, 256, dec2 }, { 70, 128, 384, rows },
|
||||
{ 130, 128, 256, rows }, { 33, 4096, 512, rows },
|
||||
{ 70, 4096, 128, rows } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K);
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
|
||||
// summation order shows through the bf16 output.
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap),
|
||||
mat(as.data(), RAD_F32, M, kb, kb),
|
||||
mat(w.data(), RAD_F8E4M3, N, K, K),
|
||||
mat(ws.data(), RAD_F32, N / 128, kb, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
// The pitch off 16 bytes takes the legacy tile.
|
||||
auto run = [&](bool legacy, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * yp, 0x7777);
|
||||
t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp)
|
||||
: mat(a.data(), RAD_F8E4M3, M, K, ap);
|
||||
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return r4d_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> legacy, got;
|
||||
++cases;
|
||||
if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) {
|
||||
std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int nonzero = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0;
|
||||
if (nonzero < M * N / 2) {
|
||||
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
|
||||
++fails;
|
||||
}
|
||||
++cases;
|
||||
const int rc = run(false, got);
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) {
|
||||
size_t i = 0;
|
||||
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
|
||||
std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n",
|
||||
emu_last_kernel, sh.kernel, M, N, K, rc, i);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
fails += grouped_cases(cases);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator, held to libref's kda_update
|
||||
* (from $RADIANCE_HOME, which ctest sets) over the output and the whole state buffer, in all four
|
||||
* modes: prefill per candidate and anchored, verify per candidate and anchored (after the replay
|
||||
* of the accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten
|
||||
* slot are mixed in, so a byte the reference leaves alone must stay as it was. The kernel's lane
|
||||
* reductions sum in another order than libref's loops: f32 state within 2e-5 + 2e-5 |x|, bf16
|
||||
* output within one rounding step. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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 uint16_t f2b(float f) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
/* libref's kda_update, through the plugin's own exports, or null. */
|
||||
static RadLaunchFn load_libref() {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
if (!home || !*home) return nullptr;
|
||||
const std::string p = std::string(home) + "/kernels/libref.so";
|
||||
void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) return nullptr;
|
||||
auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */
|
||||
if (open && open() < 0) return nullptr;
|
||||
auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
if (!cnt || !at) return nullptr;
|
||||
for (int i = 0; i < cnt(); ++i) {
|
||||
const RadKernelInfo* k = at(i);
|
||||
if (k && k->op && !std::strcmp(k->op, "kda_update")) return k->launch;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static float bf16_value(uint16_t b) {
|
||||
const uint32_t u = (uint32_t)b << 16;
|
||||
float f;
|
||||
std::memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
const char* mode;
|
||||
bool anchor;
|
||||
int64_t width;
|
||||
std::vector<int> cu, idx, accepted, init;
|
||||
std::vector<std::pair<int64_t, float>> counts;
|
||||
};
|
||||
|
||||
int main() {
|
||||
const RadLaunchFn reference = load_libref();
|
||||
if (!reference) {
|
||||
std::printf("FAIL libref's kda_update not loadable (set RADIANCE_HOME)\n");
|
||||
return 1;
|
||||
}
|
||||
std::mt19937 rng(41);
|
||||
std::uniform_real_distribution<float> u(-1.f, 1.f);
|
||||
const int64_t H = 2, D = 128, slots = 16, tokens = 9;
|
||||
std::vector<float> state0((size_t)(slots * H * D * D)), alog((size_t)H), bias((size_t)(H * D));
|
||||
for (auto& v : state0) v = u(rng);
|
||||
for (auto& v : alog) v = 0.5f * u(rng);
|
||||
for (auto& v : bias) v = u(rng);
|
||||
std::vector<uint16_t> in[5];
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D)));
|
||||
for (auto& v : in[i]) v = f2b((i >= 3 ? 2.f : 1.f) * u(rng));
|
||||
}
|
||||
const std::vector<Case> cases = {
|
||||
{ "prefill, per candidate",
|
||||
"prefill",
|
||||
false,
|
||||
1,
|
||||
{ 0, 4, 4, 9 },
|
||||
{ 3, 4, -1 },
|
||||
{ 1, 1, 1 },
|
||||
{ 0, 1, 1 },
|
||||
{} },
|
||||
{ "prefill, anchored",
|
||||
"prefill",
|
||||
true,
|
||||
2,
|
||||
{ 0, 5, 9 },
|
||||
{ 1, 2, 3, 4 },
|
||||
{ 1, 1 },
|
||||
{ 1, 0 },
|
||||
{} },
|
||||
{ "verify, per candidate",
|
||||
"verify",
|
||||
false,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 0, 1 },
|
||||
{} },
|
||||
{ "verify, anchored",
|
||||
"verify",
|
||||
true,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 1, 9, 5, 9, 2, 9, 6, 9, 3, 9, 7, 9 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 1, 0 },
|
||||
{ { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } },
|
||||
};
|
||||
int fails = 0, checks = 0;
|
||||
for (const Case& c : cases) {
|
||||
std::vector<float> start = state0;
|
||||
for (const auto& sc : c.counts)
|
||||
for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second;
|
||||
const int64_t seqs = (int64_t)c.cu.size() - 1;
|
||||
std::vector<int> idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init;
|
||||
auto run = [&](RadLaunchFn launch, std::vector<uint16_t>& out, std::vector<float>& state) {
|
||||
out.assign((size_t)(tokens * H * D), 0x7777);
|
||||
state = start;
|
||||
RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[1].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[2].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[3].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[4].data(), RAD_BF16, { tokens, H }),
|
||||
tens(alog.data(), RAD_F32, { H }),
|
||||
tens(bias.data(), RAD_F32, { H * D }),
|
||||
tens(state.data(), RAD_F32, { slots, H, D, D }),
|
||||
tens(idx.data(), RAD_I32, { seqs, c.width }),
|
||||
tens(cu.data(), RAD_I32, { seqs + 1 }),
|
||||
tens(acc.data(), RAD_I32, { seqs }),
|
||||
tens(init.data(), RAD_I32, { seqs }),
|
||||
tens(out.data(), RAD_BF16, { tokens, H, D }) };
|
||||
RadParam p[10]{};
|
||||
p[0] = { "heads", RAD_P_INT, H };
|
||||
p[1] = { "head_k", RAD_P_INT, D };
|
||||
p[2] = { "head_v", RAD_P_INT, D };
|
||||
p[3].key = "lower_bound";
|
||||
p[3].kind = RAD_P_F64;
|
||||
p[3].dval = -5;
|
||||
p[4].key = "scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 1.0 / std::sqrt(128.0);
|
||||
p[5].key = "l2_eps";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 1e-6;
|
||||
p[6].key = "mode";
|
||||
p[6].kind = RAD_P_STR;
|
||||
p[6].sval = c.mode;
|
||||
p[7].key = "state_form";
|
||||
p[7].kind = RAD_P_STR;
|
||||
p[7].sval = c.anchor ? "anchor" : "per_candidate";
|
||||
p[8].key = "dtype";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 13;
|
||||
a.p = p;
|
||||
a.n_p = 9;
|
||||
return launch(&a, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> ref_out, out;
|
||||
std::vector<float> ref_state, state;
|
||||
++checks;
|
||||
if (run(reference, ref_out, ref_state) != RAD_OK ||
|
||||
run(r4d_rad_kda_update, out, state) != RAD_OK) {
|
||||
std::printf("FAIL %s: refused\n", c.name);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
bool written = false;
|
||||
for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777;
|
||||
size_t bad = 0;
|
||||
double out_err = 0, state_err = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
if (out[i] == ref_out[i]) continue;
|
||||
const float x = bf16_value(out[i]), y = bf16_value(ref_out[i]);
|
||||
const double e = std::fabs((double)x - y);
|
||||
out_err = std::max(out_err, e);
|
||||
if (!std::isfinite(x) || ref_out[i] == 0x7777 || out[i] == 0x7777 ||
|
||||
e > 1e-6 + 0.008 * std::fabs(y))
|
||||
++bad;
|
||||
}
|
||||
for (size_t i = 0; i < state.size(); ++i) {
|
||||
if (state[i] == ref_state[i]) continue;
|
||||
const double e = std::fabs((double)state[i] - ref_state[i]);
|
||||
state_err = std::max(state_err, e);
|
||||
if (!std::isfinite(state[i]) || e > 2e-5 + 2e-5 * std::fabs(ref_state[i])) ++bad;
|
||||
}
|
||||
std::printf("%-24s output max %.3g, state max %.3g%s\n", c.name, out_err, state_err,
|
||||
!written ? " NO OUTPUT" : bad ? " FAIL" : "");
|
||||
if (!written || bad) ++fails;
|
||||
}
|
||||
std::printf("kda_update against libref: %d of %d within bounds\n", checks - fails, checks);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -511,6 +511,74 @@ static void test_codes() {
|
||||
checked);
|
||||
}
|
||||
|
||||
/* lora_expand_mm (the generators' expand): t rounded to bf16 and summed on the WMMA in its own
|
||||
* order, so each output is held to the double sum over bf16(t) within one rounding of y plus the
|
||||
* f32 sum's bound; base rows and everything outside the slice untouched, bit for bit. Mixed slots
|
||||
* in a tile, an odd M and N, R not a multiple of 32, every y dtype, aligned and not. */
|
||||
static void test_expand_mm() {
|
||||
std::mt19937 rng(41);
|
||||
struct Sh { int M, N, R, S; uint32_t ydt; bool al; int base_pct; };
|
||||
const Sh shapes[] = {
|
||||
{ 1, 20, 16, 1, RAD_BF16, true, 0 },
|
||||
{ 64, 64, 32, 1, RAD_BF16, true, 0 },
|
||||
{ 130, 300, 48, 2, RAD_BF16, false, 20 },
|
||||
{ 77, 9216, 192, 1, RAD_BF16, true, 0 }, /* a fused qkv, one adapter */
|
||||
{ 200, 1000, 64, 3, RAD_F32, false, 30 },
|
||||
{ 65, 257, 24, 2, RAD_F16, true, 10 },
|
||||
{ 512, 2048, 128, 1, RAD_BF16, true, 0 },
|
||||
};
|
||||
int64_t worst_n = 0;
|
||||
double worst = 0;
|
||||
for (const Sh& sh : shapes) {
|
||||
const std::vector<int32_t> slot = rand_slots(rng, sh.M, sh.S, sh.base_pct);
|
||||
Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al);
|
||||
std::vector<uint8_t> got;
|
||||
if (run_expand(E, r4d_rad_lora_expand_mm, &got) != RAD_OK) {
|
||||
fail("expand_mm", fmt("rc (M %d N %d R %d)", sh.M, sh.N, sh.R));
|
||||
continue;
|
||||
}
|
||||
const size_t e = esz(sh.ydt), ny = (size_t)E.yoff + (size_t)sh.M * E.ldy;
|
||||
int64_t bad_base = 0, bad_val = 0;
|
||||
for (size_t i = 0; i < ny; ++i) {
|
||||
const long long q = (long long)i - E.yoff;
|
||||
const int m = q < 0 ? -1 : (int)(q / E.ldy), n = q < 0 ? -1 : (int)(q % E.ldy);
|
||||
const int sl = m >= 0 && m < sh.M ? slot[(size_t)m] : -1;
|
||||
if (m < 0 || m >= sh.M || n >= sh.N || sl < 0 || sl >= sh.S) {
|
||||
bad_base += std::memcmp(&got[i * e], &E.y0[i * e], e) != 0;
|
||||
continue;
|
||||
}
|
||||
double acc = 0, terms = 0;
|
||||
for (int j = 0; j < sh.R; ++j) {
|
||||
const double tv = rad_bf16_to_f32(rad_f32_to_bf16(E.t[(size_t)m * sh.R + j]));
|
||||
const double bv = rad_bf16_to_f32(E.lb[((size_t)sl * sh.N + n) * sh.R + j]);
|
||||
acc += tv * bv;
|
||||
terms += std::fabs(tv * bv);
|
||||
}
|
||||
const double sc = E.sc[(size_t)sl * sh.N + n];
|
||||
const double y0 = lora_cases::get(sh.ydt, E.y0.data(), i);
|
||||
const double want = y0 + sc * acc;
|
||||
const double g = lora_cases::get(sh.ydt, got.data(), i);
|
||||
if (std::isnan(y0)) { bad_val += !std::isnan(g); continue; }
|
||||
const double ulp = sh.ydt == RAD_BF16 ? std::ldexp(1.0, -8)
|
||||
: sh.ydt == RAD_F16 ? std::ldexp(1.0, -10) : std::ldexp(1.0, -23);
|
||||
const double tol = std::fabs(want) * ulp + sc * terms * (sh.R + 2) * std::ldexp(1.0, -24) +
|
||||
1e-30;
|
||||
const double r = std::fabs(g - want) / tol;
|
||||
worst = std::max(worst, r);
|
||||
if (r > 1.0) ++bad_val;
|
||||
++worst_n;
|
||||
}
|
||||
if (bad_base)
|
||||
fail("expand_mm", fmt("touched %lld base-row / outside bytes (M %d N %d R %d %s)",
|
||||
(long long)bad_base, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
if (bad_val)
|
||||
fail("expand_mm", fmt("%lld outputs outside the bound (M %d N %d R %d %s)",
|
||||
(long long)bad_val, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
}
|
||||
std::printf("lora expand_mm: %zu shapes, %lld outputs, worst |err|/bound %.3f\n",
|
||||
sizeof(shapes) / sizeof(shapes[0]), (long long)worst_n, worst);
|
||||
}
|
||||
|
||||
int main() {
|
||||
LaunchFn rs = nullptr, re = nullptr;
|
||||
load_libref(&rs, &re);
|
||||
@@ -532,6 +600,7 @@ int main() {
|
||||
test_invariance();
|
||||
test_all_base();
|
||||
test_codes();
|
||||
test_expand_mm();
|
||||
std::printf("lora tiled rows: %d failure(s)\n", g_fails);
|
||||
return (T.fails != 0 || g_fails != 0) ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator.
|
||||
* Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the
|
||||
* row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and
|
||||
* comb bit for bit; the partial matrix's padding slots are zero. On 16-byte rows the vector forms
|
||||
* run, and they are held bit for bit to the same operands on pitched rows, where the scalar forms
|
||||
* run. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, int64_t n) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = RAD_F32;
|
||||
t.rank = 1;
|
||||
t.shape[0] = n;
|
||||
t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8;
|
||||
std::vector<float> fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix);
|
||||
for (auto& v : fn) v = nd(rng) * 0.01f;
|
||||
for (auto& v : base) v = nd(rng) * 0.5f;
|
||||
int fails = 0, cases = 0;
|
||||
for (int64_t rows : { 1, 5, 37 }) {
|
||||
const int64_t hp = W + 6, xp = n + 2;
|
||||
std::vector<uint16_t> h((size_t)(rows * hp));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
RadParam coef[8]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-5;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
std::vector<uint16_t> x((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc));
|
||||
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(x.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL mhc_pre M=%lld\n", (long long)rows);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
++cases;
|
||||
const int64_t mine = total / world;
|
||||
std::vector<float> gathered((size_t)(rows * total * S));
|
||||
bool padded = true, launched = true;
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
std::vector<float> part((size_t)(rows * mine * S), 7.0f);
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(part.data(), RAD_F32, rows, mine * S, mine * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, rank * mine };
|
||||
pp[5] = { "chunks", RAD_P_INT, mine };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t c = 0; c < mine; ++c)
|
||||
for (int64_t j = mix + 1; j < S; ++j)
|
||||
padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f;
|
||||
std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)],
|
||||
&part[(size_t)(r * mine * S)], (size_t)(mine * S * 4));
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> x2((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post2(post.size()), comb2(comb.size());
|
||||
RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S),
|
||||
t[0],
|
||||
t[2],
|
||||
t[3],
|
||||
mat(x2.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post2.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadParam fp[8];
|
||||
std::memcpy(fp, coef, sizeof coef);
|
||||
fp[6] = { "chunk", RAD_P_INT, 2048 };
|
||||
fp[7].key = "dtype";
|
||||
fp[7].kind = RAD_P_STR;
|
||||
fp[7].sval = "bf16";
|
||||
RadArgs fa{};
|
||||
fa.t = ft;
|
||||
fa.n_t = 7;
|
||||
fa.p = fp;
|
||||
fa.n_p = 8;
|
||||
launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK;
|
||||
const bool same = launched && x2 == x &&
|
||||
std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 &&
|
||||
std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0;
|
||||
if (!same || !padded) {
|
||||
std::printf("FAIL M=%lld world %d: %s\n", (long long)rows, world,
|
||||
!launched ? "launch"
|
||||
: !padded ? "padding"
|
||||
: "differs");
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The vector forms (four-slot partials, the finish's 16-byte collapse, the eight-column
|
||||
* mhc_post) on 16-byte rows against the scalar forms (one slot a thread, four rows and four
|
||||
* coefficients a block from 32 rows, the per-output mhc_post) on the same operands with the
|
||||
* residual pitched by two elements: mhc_pre's x, post and comb, mhc_pre_partial's matrix and
|
||||
* mhc_post's output, bit for bit. */
|
||||
for (int64_t rows : { 1, 5, 16, 37, 64 }) {
|
||||
std::vector<uint16_t> h((size_t)(rows * W)), y((size_t)(rows * n));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
for (auto& v : y) v = f2b(nd(rng));
|
||||
const int64_t pitched = W + 2;
|
||||
std::vector<uint16_t> hp((size_t)(rows * pitched), 0x7777);
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
std::memcpy(&hp[(size_t)(r * pitched)], &h[(size_t)(r * W)], (size_t)W * 2);
|
||||
RadParam coef[7]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-6;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
struct Out {
|
||||
std::vector<uint16_t> x, o;
|
||||
std::vector<float> p, c, part;
|
||||
};
|
||||
auto run = [&](Out* r, const uint16_t* hd, int64_t ld) {
|
||||
r->x.assign((size_t)(rows * n), 0x7777);
|
||||
r->o.assign((size_t)(rows * W), 0x7777);
|
||||
r->p.assign((size_t)(rows * hc), 0);
|
||||
r->c.assign((size_t)(rows * hc * hc), 0);
|
||||
r->part.assign((size_t)(rows * total * S), 7.0f);
|
||||
RadTensor t[7] = { mat((void*)hd, RAD_BF16, rows, W, ld),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(r->x.data(), RAD_BF16, rows, n, n),
|
||||
mat(r->p.data(), RAD_F32, rows, hc, hc),
|
||||
mat(r->c.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
bool okay = r4d_rad_mhc_pre(&a, nullptr) == RAD_OK;
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(r->part.data(), RAD_F32, rows, total * S, total * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, 0 };
|
||||
pp[5] = { "chunks", RAD_P_INT, total };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
okay = okay && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
RadTensor ot[5] = { mat(y.data(), RAD_BF16, rows, n, n), t[0], t[5], t[6],
|
||||
mat(r->o.data(), RAD_BF16, rows, W, W) };
|
||||
RadArgs oa{};
|
||||
oa.t = ot;
|
||||
oa.n_t = 5;
|
||||
oa.p = coef;
|
||||
oa.n_p = 7;
|
||||
return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK;
|
||||
};
|
||||
Out ref, got;
|
||||
++cases;
|
||||
const bool launched = run(&ref, hp.data(), pitched) && run(&got, h.data(), W);
|
||||
const char* bad = !launched ? "launch"
|
||||
: got.x != ref.x ? "x"
|
||||
: std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post"
|
||||
: std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb"
|
||||
: std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4)
|
||||
? "partials"
|
||||
: got.o != ref.o ? "mhc_post"
|
||||
: nullptr;
|
||||
if (bad) {
|
||||
std::printf("FAIL M=%lld 16-byte rows against pitched rows: %s differs\n",
|
||||
(long long)rows, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
/* Drives libr4d's MLA matrix row (r4d_mla.hip, attend_matrix) through the SIMT emulator and checks
|
||||
* every output element against an f64 softmax over each row's own table. The cases put the paired
|
||||
* tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk
|
||||
* whose rows share one table, and rows past the DSA budget, where each row selects its own top
|
||||
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
|
||||
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the
|
||||
* same operands: the union at the case's table width, the positional pairing on the table
|
||||
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" void r4d_mla_matrix_pin_form(int form);
|
||||
extern "C" void r4d_mla_matrix_stats(unsigned long long* out);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int D = 512, BS = 4, kUnionBlocks = 520;
|
||||
|
||||
enum class Fill { prefill, topk, ragged, repeat };
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
int rows, heads, blocks;
|
||||
Fill fill;
|
||||
int swaps = 0; /* topk: blocks exchanged between neighbouring rows */
|
||||
int context = 0; /* topk: tokens of the sequence the rows end */
|
||||
bool scratch = false; /* lets the launcher split the history */
|
||||
int form = 0; /* r4d_mla_matrix_pin_form */
|
||||
int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */
|
||||
/* Unsplit only: with scratch the widened table gives the positional run more splits. */
|
||||
bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */
|
||||
bool bitwise_all = false; /* both requests do (the tables agree position by position) */
|
||||
bool union_falls_back = false; /* the table is wider than the union's lists */
|
||||
};
|
||||
|
||||
/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows ..
|
||||
* context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher
|
||||
* ones in block order and a short tie run after them, then the partial page. Row r's choice is row
|
||||
* r-1's with `swaps` members exchanged for non-members. Pages are a fixed shuffle of the blocks. */
|
||||
void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng,
|
||||
std::vector<int>& bt, std::vector<int>& len, int& pages) {
|
||||
const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk);
|
||||
pages = universe;
|
||||
std::vector<int> page(universe);
|
||||
for (int i = 0; i < universe; ++i) page[i] = i;
|
||||
std::shuffle(page.begin(), page.end(), rng);
|
||||
std::vector<char> in(universe, 0);
|
||||
std::vector<int> members;
|
||||
auto tie_rank = [](int b) { return (uint32_t)b * 2654435761u ^ 0x9e3779b9u; };
|
||||
bt.assign((size_t)rows * blocks, -1);
|
||||
len.assign(rows, 0);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const int p = context - rows + r, n = (p + 1) / BS;
|
||||
if (n <= topk) {
|
||||
for (int b = 0; b < n; ++b)
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
} else {
|
||||
while ((int)members.size() < topk) {
|
||||
const int b = (int)(rng() % (unsigned)n);
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
}
|
||||
for (int s = 0; s < swaps; ++s) {
|
||||
int add;
|
||||
do add = (int)(rng() % (unsigned)n);
|
||||
while (in[add]);
|
||||
const size_t drop = rng() % members.size();
|
||||
in[members[drop]] = 0;
|
||||
members[drop] = add;
|
||||
in[add] = 1;
|
||||
}
|
||||
}
|
||||
std::vector<int> order(members);
|
||||
std::sort(order.begin(), order.end());
|
||||
if (n > topk) {
|
||||
std::vector<int> tied(order);
|
||||
std::sort(tied.begin(), tied.end(),
|
||||
[&](int a, int b) { return tie_rank(a) < tie_rank(b); });
|
||||
tied.resize(ties);
|
||||
std::sort(tied.begin(), tied.end());
|
||||
order.erase(std::remove_if(
|
||||
order.begin(), order.end(),
|
||||
[&](int b) { return std::binary_search(tied.begin(), tied.end(), b); }),
|
||||
order.end());
|
||||
order.insert(order.end(), tied.begin(), tied.end());
|
||||
}
|
||||
int out = 0;
|
||||
for (int b : order) bt[(size_t)r * blocks + out++] = page[b];
|
||||
if ((p + 1) % BS) bt[(size_t)r * blocks + out++] = page[n];
|
||||
len[r] = out ? (out - 1) * BS + p % BS + 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
int run(const Case& c, std::mt19937& rng) {
|
||||
const int M = c.rows, H = c.heads, B = c.blocks;
|
||||
std::vector<int> bt, len;
|
||||
int pages = 0;
|
||||
if (c.fill == Fill::topk) {
|
||||
topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages);
|
||||
} else if (c.fill == Fill::prefill) {
|
||||
/* one sequence, its rows the last M positions of the capacity, one table */
|
||||
pages = B + 1;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = (b * 7 + 3) % pages;
|
||||
len[r] = B * BS - M + r + 1;
|
||||
}
|
||||
} else if (c.fill == Fill::repeat) {
|
||||
/* every page twice in a row's table and shifted by one entry from row to row, so a page
|
||||
* repeats within a table and between the pair */
|
||||
pages = M + B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = ((b + r) / 2 * 5) % pages;
|
||||
len[r] = B * BS - r % 3;
|
||||
}
|
||||
} else {
|
||||
/* every row its own scattered table, with holes and out-of-range pages */
|
||||
pages = M * B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b)
|
||||
bt[(size_t)r * B + b] = b % 17 == 3 ? -1
|
||||
: b % 19 == 5 ? pages + 3
|
||||
: (b * 7 + r * 11) % pages;
|
||||
len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7;
|
||||
}
|
||||
}
|
||||
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);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
|
||||
auto 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;
|
||||
};
|
||||
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, 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 }) };
|
||||
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 pf = [&](const char* k, double v) {
|
||||
RadParam x{};
|
||||
x.key = k;
|
||||
x.kind = RAD_P_F64;
|
||||
x.dval = v;
|
||||
p.push_back(x);
|
||||
};
|
||||
pi("M", M);
|
||||
pi("latent_dim", D);
|
||||
pi("heads", H);
|
||||
pi("blocks", B);
|
||||
pi("block_size", BS);
|
||||
const double scale = 0.0625;
|
||||
pf("scale", scale);
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p.data();
|
||||
a.n_p = (int)p.size();
|
||||
std::vector<char> scratch;
|
||||
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;
|
||||
}
|
||||
|
||||
/* the f64 reference */
|
||||
std::vector<double> want((size_t)M * H * D);
|
||||
std::vector<double> sc;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int h = 0; h < H; ++h) {
|
||||
const int live = std::min(std::max(len[r], 0), B * BS);
|
||||
sc.assign(live, -INFINITY);
|
||||
double mx = -INFINITY;
|
||||
auto row_of = [&](int j) -> const uint16_t* {
|
||||
const int pg = bt[(size_t)r * B + j / BS];
|
||||
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
|
||||
};
|
||||
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
|
||||
for (int j = 0; j < live; ++j) {
|
||||
const uint16_t* k = row_of(j);
|
||||
if (!k) continue;
|
||||
double dot = 0;
|
||||
for (int d = 0; d < D; ++d)
|
||||
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
|
||||
sc[j] = dot * scale;
|
||||
mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(D, 0.0);
|
||||
double sum = 0;
|
||||
for (int j = 0; j < live; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx);
|
||||
sum += w;
|
||||
const uint16_t* k = row_of(j);
|
||||
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
|
||||
}
|
||||
for (int d = 0; d < D; ++d)
|
||||
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
|
||||
}
|
||||
|
||||
/* Both pairings on the same operands: the positional one, on the table widened past the
|
||||
* union's lists, and at the case's own width the launcher's choice, the union, which must
|
||||
* never take a second pass. A tile of 16 heads has no pairing and runs once. */
|
||||
const bool paired = H % 16 == 8;
|
||||
const int wide = std::max(B, kUnionBlocks + 1);
|
||||
std::vector<int> bt_wide((size_t)M * wide, -1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
std::copy(bt.begin() + (size_t)r * B, bt.begin() + (size_t)(r + 1) * B,
|
||||
bt_wide.begin() + (size_t)r * wide);
|
||||
std::vector<uint16_t> by_pos;
|
||||
int fails = 0;
|
||||
for (const char* pairing : { "pos", "union" }) {
|
||||
const bool by_page = !std::strcmp(pairing, "union");
|
||||
if (!paired && by_page) break;
|
||||
const bool widened = paired && !by_page;
|
||||
t[2] = widened ? tens(bt_wide.data(), RAD_I32, { M, wide })
|
||||
: tens(bt.data(), RAD_I32, { M, B });
|
||||
p[3].ival = widened ? wide : B;
|
||||
std::fill(out.begin(), out.end(), 0xffff);
|
||||
unsigned long long stats[3];
|
||||
r4d_mla_matrix_stats(stats);
|
||||
r4d_mla_matrix_pin_form(c.form);
|
||||
const int rc = r4d_rad_mla_attn_matrix(&a, nullptr);
|
||||
r4d_mla_matrix_pin_form(0);
|
||||
r4d_mla_matrix_stats(stats);
|
||||
if (rc != RAD_OK) {
|
||||
std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
double max_err = 0;
|
||||
long bad = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
const float got = rad_bf16_to_f32(out[i]);
|
||||
const double e = std::fabs(got - want[i]);
|
||||
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
|
||||
if (std::isfinite(got)) max_err = std::max(max_err, e);
|
||||
}
|
||||
bool ok = bad == 0;
|
||||
std::string note;
|
||||
if (!by_page) {
|
||||
by_pos = out;
|
||||
if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) {
|
||||
note +=
|
||||
c.expect_second ? " (expected a second pass)" : " (expected no second pass)";
|
||||
ok = false;
|
||||
}
|
||||
} else {
|
||||
if ((stats[1] > 0) != c.union_falls_back) {
|
||||
note += c.union_falls_back ? " (expected the positional fallback)"
|
||||
: " (the union took a second pass)";
|
||||
ok = false;
|
||||
}
|
||||
/* Request r of each pair walks its own table in its own order, as the positional
|
||||
* pairing does, so at one split it must agree to the bit; r+1 sums in another order. */
|
||||
size_t first_diff_a = 0, diff_b = 0;
|
||||
double max_ab = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
|
||||
if (out[i] == by_pos[i]) continue;
|
||||
if (r % 2 == 0)
|
||||
++first_diff_a;
|
||||
else
|
||||
++diff_b;
|
||||
max_ab = std::max(max_ab, (double)std::fabs(rad_bf16_to_f32(out[i]) -
|
||||
rad_bf16_to_f32(by_pos[i])));
|
||||
}
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e",
|
||||
first_diff_a, diff_b, max_ab);
|
||||
note += buf;
|
||||
if (c.bitwise_a && !c.scratch && first_diff_a) {
|
||||
note += " (request r differs)";
|
||||
ok = false;
|
||||
}
|
||||
if (c.bitwise_all && !c.scratch && diff_b) {
|
||||
note += " (request r+1 differs)";
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
std::printf("%-40s %-5s M %3d H %2d blocks %3d passes %5llu raster %5llu second %5llu "
|
||||
"max_abs %.2e bad %ld%s %s\n",
|
||||
c.name.c_str(), pairing, M, H, B, stats[0], stats[2], stats[1], max_err, bad,
|
||||
note.c_str(), ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The launcher prints the running totals every 1024th counted launch and must leave them
|
||||
* standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */
|
||||
int periodic_report() {
|
||||
std::vector<uint16_t> q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D);
|
||||
std::vector<int> bt = { 0, 1 }, len = { 4, 3 };
|
||||
RadTensor t[5]{};
|
||||
auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
x.data = p;
|
||||
x.dtype = dt;
|
||||
x.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
x.shape[i] = shape[i];
|
||||
x.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
};
|
||||
set(t[0], q.data(), RAD_BF16, { 2, 8, D });
|
||||
set(t[1], kv.data(), RAD_BF16, { 4, 1, BS, D });
|
||||
set(t[2], bt.data(), RAD_I32, { 2, 1 });
|
||||
set(t[3], len.data(), RAD_I32, { 2 });
|
||||
set(t[4], out.data(), RAD_BF16, { 2, 8, D });
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { 2, D, 8, 1, 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;
|
||||
unsigned long long stats[3];
|
||||
r4d_mla_matrix_stats(stats);
|
||||
for (int i = 0; i < 1024; ++i)
|
||||
if (r4d_rad_mla_attn_matrix(&a, nullptr) != RAD_OK) {
|
||||
std::printf("periodic report: launch failed\n");
|
||||
return 1;
|
||||
}
|
||||
r4d_mla_matrix_stats(stats);
|
||||
const bool ok = stats[0] == 1024 && stats[2] == 1024 && stats[1] == 0;
|
||||
std::printf("periodic report: %llu passes over %llu raster chunks after 1024 launches %s\n",
|
||||
stats[0], stats[2], ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setenv("RADIANCE_MLA_CONFLICT_STATS", "1", 1);
|
||||
/* name, rows, heads, blocks, fill, swaps, context, scratch, form, expect_second, bitwise_a,
|
||||
* bitwise_all, union_falls_back */
|
||||
std::vector<Case> cases = {
|
||||
{ "prefill, one table", 8, 8, 65, Fill::prefill, 0, 0, false, 0, 0, true, true },
|
||||
{ "prefill, odd rows, split", 7, 8, 33, Fill::prefill, 0, 0, true, 0, 0, true, true },
|
||||
{ "prefill, 16 heads", 4, 16, 33, Fill::prefill, 0, 0, false, 0, 0 },
|
||||
{ "prefill, 24 heads (three pairs)", 5, 24, 17, Fill::prefill, 0, 0, false, 0, 0, true,
|
||||
true },
|
||||
{ "topk d=0", 8, 8, 65, Fill::topk, 0, 600, false, 0, 0, true, true },
|
||||
{ "topk d=4", 8, 8, 65, Fill::topk, 4, 600, false, 0, 1 },
|
||||
{ "topk d=16", 8, 8, 65, Fill::topk, 16, 600, false, 0, 1 },
|
||||
{ "topk d=64 (disjoint neighbours)", 6, 8, 65, Fill::topk, 64, 600, false, 0, 1 },
|
||||
{ "topk d=16, 513 blocks", 4, 8, 513, Fill::topk, 16, 8192, false, 0, 1 },
|
||||
/* a split cuts the union's walk elsewhere than the positional raster */
|
||||
{ "topk d=4, odd rows, split", 5, 8, 33, Fill::topk, 4, 400, true, 0, 1, false },
|
||||
{ "topk d=4, element load", 4, 8, 33, Fill::topk, 4, 400, false, 1, 1 },
|
||||
{ "topk d=4, 16 heads", 4, 16, 33, Fill::topk, 4, 400, false, 0, 0 },
|
||||
{ "topk, table past the union's lists", 4, 8, 600, Fill::topk, 16, 4000, false, 0, 1, true,
|
||||
true, true },
|
||||
{ "repeated pages", 6, 8, 33, Fill::repeat, 0, 0, false, 0, -1 },
|
||||
{ "repeated pages, split", 3, 8, 33, Fill::repeat, 0, 0, true, 0, -1, false },
|
||||
{ "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 },
|
||||
{ "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false },
|
||||
};
|
||||
const char* filter = argc > 1 ? argv[1] : nullptr;
|
||||
int fails = 0;
|
||||
for (size_t i = 0; i < cases.size(); ++i) {
|
||||
if (filter && cases[i].name.find(filter) == std::string::npos) continue;
|
||||
std::mt19937 rng(20261018u + (unsigned)i);
|
||||
fails += run(cases[i], rng);
|
||||
}
|
||||
if (!filter) fails += periodic_report();
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
/* tests/r4d_emu: GLM's decode fusions of the MoE block (r4d_glm.hip) on the host SIMT emulator,
|
||||
* each byte for byte against the separate launches it replaces.
|
||||
*
|
||||
* router_sigmoid_topk_scatter against router_sigmoid_topk (the emulated kernel), then moe_scatter's
|
||||
* stable counting sort over its ids written out here, then the `fill` of the shared gate with 1:
|
||||
* random, tied and NaN ranks (a row with fewer finite ranks than top_k selects expert 0 for its
|
||||
* empty slots, and the sort takes those as written), slices and protected experts, rows past 64
|
||||
* wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past
|
||||
* every output and the gate's untouched rows show an overrun.
|
||||
*
|
||||
* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes,
|
||||
* scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the
|
||||
* clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the
|
||||
* sigmoid underflows, and NaN and infinite inputs.
|
||||
*
|
||||
* moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself
|
||||
* without, and the inverse against the table the gather builds from `sorted`; then moe_gather's
|
||||
* kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at
|
||||
* GLM's f32 routing weights and bf16 ones, with the ungated shared arm, a sigmoid-gated one and
|
||||
* none, and slices that drop slots. moe_scatter's three-pass form (T > 1024) is not here: its
|
||||
* kernels take dynamic LDS through `extern __shared__`, which the emulator cannot give; the card
|
||||
* checks it (r4d_selftest --case moe_scatter_inv_i32). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include "r4d_moe_sort.h"
|
||||
#include "r4d_moe_gather.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int32_t kPoison = -77;
|
||||
constexpr uint16_t kGatePoison = 0x7e57;
|
||||
|
||||
/* moe_scatter's contract: slot i = token * top_k + slot goes to its expert's run in ascending i;
|
||||
* an expert outside the slice drops the slot; protected experts are placed last in list order;
|
||||
* sorted rows past the live count are -1. */
|
||||
struct SortModel {
|
||||
std::vector<int32_t> sorted, off, cnt;
|
||||
};
|
||||
int32_t place_of(int32_t e, int nl, const std::vector<int>& prot) {
|
||||
int32_t below = 0;
|
||||
for (size_t j = 0; j < prot.size(); ++j) {
|
||||
if (prot[j] == e) return nl - (int32_t)prot.size() + (int32_t)j;
|
||||
below += prot[j] < e;
|
||||
}
|
||||
return e - below;
|
||||
}
|
||||
SortModel sort_model(const std::vector<int32_t>& ids, int M, int k, int ip, int nl, int base,
|
||||
const std::vector<int>& prot) {
|
||||
const int T = M * k;
|
||||
std::vector<int32_t> place((size_t)T);
|
||||
SortModel s;
|
||||
s.cnt.assign((size_t)nl, 0);
|
||||
s.off.assign((size_t)nl + 1, 0);
|
||||
s.sorted.assign((size_t)T, -1);
|
||||
for (int i = 0; i < T; ++i) {
|
||||
const int32_t e = ids[(size_t)(i / k) * ip + i % k] - base;
|
||||
place[(size_t)i] = e >= 0 && e < nl ? place_of(e, nl, prot) : -1;
|
||||
if (place[(size_t)i] >= 0) ++s.cnt[(size_t)place[(size_t)i]];
|
||||
}
|
||||
for (int e = 0; e < nl; ++e) s.off[(size_t)e + 1] = s.off[(size_t)e] + s.cnt[(size_t)e];
|
||||
std::vector<int32_t> seen((size_t)nl, 0);
|
||||
for (int i = 0; i < T; ++i)
|
||||
if (place[(size_t)i] >= 0) {
|
||||
const int32_t e = place[(size_t)i];
|
||||
s.sorted[(size_t)(s.off[(size_t)e] + seen[(size_t)e]++)] = i;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The table the gather builds from `sorted` (gather_kernel's self-scan, or its prepass): slot
|
||||
* sorted[p] at row p, every other slot -1. */
|
||||
std::vector<int32_t> inverse_of(const std::vector<int32_t>& sorted) {
|
||||
std::vector<int32_t> inv(sorted.size(), -1);
|
||||
for (size_t p = 0; p < sorted.size(); ++p)
|
||||
if (sorted[p] >= 0) inv[(size_t)sorted[p]] = (int32_t)p;
|
||||
return inv;
|
||||
}
|
||||
|
||||
/* moe_scatter's small-form kernel (r4d_moe_sort.h) over contiguous ids, with or without the
|
||||
* inverse. */
|
||||
struct Scatter {
|
||||
int rc = RAD_OK;
|
||||
std::vector<int32_t> sorted, off, cnt, inv;
|
||||
};
|
||||
Scatter scatter_kernel(const std::vector<int32_t>& ids, int nl, int base, const char* protect,
|
||||
bool with_inv) {
|
||||
const int T = (int)ids.size();
|
||||
Scatter s;
|
||||
s.sorted.assign((size_t)T, kPoison);
|
||||
s.off.assign((size_t)nl + 1, kPoison);
|
||||
s.cnt.assign((size_t)nl, kPoison);
|
||||
s.inv.assign((size_t)T, kPoison);
|
||||
RadParam pp{};
|
||||
pp.key = "protect";
|
||||
pp.kind = RAD_P_STR;
|
||||
pp.sval = protect;
|
||||
RadArgs pa{};
|
||||
pa.p = &pp;
|
||||
pa.n_p = protect ? 1 : 0;
|
||||
r4d_moesort::Protect prot;
|
||||
s.rc = r4d_moesort::protect_of(&pa, nl, &prot);
|
||||
if (s.rc != RAD_OK) return s;
|
||||
if (with_inv)
|
||||
R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel<true>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, s.inv.data());
|
||||
else
|
||||
R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel<false>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, (int32_t*)nullptr);
|
||||
return s;
|
||||
}
|
||||
|
||||
struct RouterShape {
|
||||
int M, ne, k, norm;
|
||||
int mode; /* 0 random, 1 tied ranks, 2 NaN rows */
|
||||
int nl, base; /* the slice: nl 0 is the whole router */
|
||||
const char* protect;
|
||||
bool gate;
|
||||
};
|
||||
|
||||
void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const RouterShape shapes[] = {
|
||||
{ 1, 288, 8, 1, 0, 0, 0, nullptr, true }, { 2, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 6, 288, 8, 1, 0, 0, 0, nullptr, true }, { 8, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 9, 288, 8, 1, 0, 0, 0, nullptr, false }, { 16, 288, 8, 1, 2, 0, 0, nullptr, true },
|
||||
{ 17, 288, 8, 1, 0, 0, 0, nullptr, true }, { 24, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 33, 288, 8, 1, 0, 0, 0, nullptr, true }, { 48, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 48, 288, 8, 1, 2, 0, 0, nullptr, true }, { 65, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 100, 288, 8, 0, 0, 0, 0, nullptr, true }, { 128, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 24, 288, 8, 1, 0, 144, 144, nullptr, true }, { 24, 288, 8, 1, 1, 96, 32, "3,7,90", true },
|
||||
{ 48, 512, 8, 1, 0, 0, 0, nullptr, true }, { 32, 32, 32, 0, 1, 0, 0, nullptr, true },
|
||||
{ 5, 300, 10, 1, 2, 0, 0, "0,299", true },
|
||||
};
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const RouterShape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, T = M * k;
|
||||
const int nl = sh.nl ? sh.nl : ne, base = sh.base;
|
||||
const int lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1, gp = 3;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.mode == 1 ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias)
|
||||
v = sh.mode == 1 ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
if (sh.mode == 2)
|
||||
for (int r = 0; r < M; r += 2) {
|
||||
/* every other row keeps (r % 5) finite ranks, fewer than top_k */
|
||||
for (int e = 0; e < ne; ++e) lg[(size_t)r * lp + e] = NAN;
|
||||
for (int j = 0; j < r % 5; ++j)
|
||||
lg[(size_t)r * lp + (size_t)(ud(rng) + 1000) % ne] = 0.25f * (float)j;
|
||||
}
|
||||
std::vector<int> prot;
|
||||
if (sh.protect)
|
||||
for (const char* p = sh.protect; *p;) {
|
||||
char* end = nullptr;
|
||||
prot.push_back((int)std::strtol(p, &end, 10));
|
||||
p = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
|
||||
RadTensor t[8]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = nl + 1;
|
||||
t[5].stride[0] = 1;
|
||||
t[6].dtype = RAD_I32;
|
||||
t[6].rank = 1;
|
||||
t[6].shape[0] = nl;
|
||||
t[6].stride[0] = 1;
|
||||
t[7].dtype = RAD_BF16;
|
||||
t[7].rank = 2;
|
||||
t[7].shape[0] = M;
|
||||
t[7].shape[1] = 1;
|
||||
t[7].stride[0] = gp;
|
||||
t[7].stride[1] = 1;
|
||||
std::vector<RadParam> p(9);
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
p[6] = { "n_local", RAD_P_INT, nl };
|
||||
p[7] = { "expert_base", RAD_P_INT, base };
|
||||
p[8].key = "protect";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = sh.protect;
|
||||
const int n_p = sh.protect ? 9 : 8;
|
||||
|
||||
/* the separate launches: the selection, then the sort and fill modelled */
|
||||
std::vector<int32_t> ids_ref((size_t)M * ip, kPoison);
|
||||
std::vector<float> w_ref((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids_ref.data();
|
||||
t[3].data = w_ref.data();
|
||||
RadArgs sel{};
|
||||
sel.t = t;
|
||||
sel.n_t = 4;
|
||||
sel.p = p.data();
|
||||
sel.n_p = 6;
|
||||
++cases;
|
||||
if (r4d_rad_router_sigmoid_topk(&sel, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL router_sigmoid_topk launch M=%d ne=%d\n", M, ne);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const SortModel ref = sort_model(ids_ref, M, k, ip, nl, base, prot);
|
||||
/* moe_scatter's own kernel over the ids, contiguous as it reads them, held to the model;
|
||||
* with the inverse, which must be the table the gather builds from `sorted`. */
|
||||
std::vector<int32_t> flat((size_t)T);
|
||||
for (int i = 0; i < T; ++i) flat[(size_t)i] = ids_ref[(size_t)(i / k) * ip + i % k];
|
||||
Scatter ks = scatter_kernel(flat, nl, base, sh.protect, true);
|
||||
++cases;
|
||||
if (ks.rc != RAD_OK || ks.sorted != ref.sorted || ks.off != ref.off || ks.cnt != ref.cnt ||
|
||||
ks.inv != inverse_of(ref.sorted)) {
|
||||
std::printf("FAIL moe_scatter kernel against its model at M=%d ne=%d slice %d+%d\n", M,
|
||||
ne, base, nl);
|
||||
++fails;
|
||||
}
|
||||
|
||||
for (int with_inv = 0; with_inv < 2; ++with_inv) {
|
||||
std::vector<int32_t> ids((size_t)M * ip, kPoison), sorted((size_t)T + 4, kPoison),
|
||||
off((size_t)nl + 5, kPoison), cnt((size_t)nl + 4, kPoison),
|
||||
inv((size_t)T + 4, kPoison);
|
||||
std::vector<float> w((size_t)M * wp, -7.25f);
|
||||
std::vector<uint16_t> gate((size_t)(M + 2) * gp, kGatePoison);
|
||||
RadTensor tf[9];
|
||||
std::memcpy(tf, t, sizeof t);
|
||||
tf[2].data = ids.data();
|
||||
tf[3].data = w.data();
|
||||
tf[4].data = sorted.data();
|
||||
tf[5].data = off.data();
|
||||
tf[6].data = cnt.data();
|
||||
tf[7].data = sh.gate ? gate.data() : nullptr;
|
||||
tf[8] = tf[4];
|
||||
tf[8].data = inv.data();
|
||||
RadArgs a{};
|
||||
a.t = tf;
|
||||
a.n_t = with_inv ? 9 : 8;
|
||||
a.p = p.data();
|
||||
a.n_p = n_p;
|
||||
++cases;
|
||||
const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
int bad = 0;
|
||||
bad += ids != ids_ref;
|
||||
bad += std::memcmp(w.data(), w_ref.data(), w.size() * 4) != 0;
|
||||
bad += std::memcmp(sorted.data(), ks.sorted.data(), (size_t)T * 4) != 0;
|
||||
bad += std::memcmp(off.data(), ks.off.data(), (size_t)(nl + 1) * 4) != 0;
|
||||
bad += std::memcmp(cnt.data(), ks.cnt.data(), (size_t)nl * 4) != 0;
|
||||
if (with_inv) bad += std::memcmp(inv.data(), ks.inv.data(), (size_t)T * 4) != 0;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
bad += sorted[(size_t)T + i] != kPoison || off[(size_t)nl + 1 + i] != kPoison ||
|
||||
cnt[(size_t)nl + i] != kPoison || inv[(size_t)T + i] != kPoison;
|
||||
if (!with_inv)
|
||||
for (int i = 0; i < T; ++i) bad += inv[(size_t)i] != kPoison;
|
||||
for (int r = 0; r < M + 2; ++r)
|
||||
for (int c = 0; c < gp; ++c) {
|
||||
const uint16_t want = sh.gate && r < M && c == 0 ? 0x3f80 : kGatePoison;
|
||||
bad += gate[(size_t)r * gp + c] != want;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf(
|
||||
"FAIL router_sigmoid_topk_scatter at M=%d ne=%d k=%d mode %d slice %d+%d%s%s%s "
|
||||
"(rc %d, %d mismatching outputs)\n",
|
||||
M, ne, k, sh.mode, base, nl, sh.protect ? " protect " : "",
|
||||
sh.protect ? sh.protect : "", with_inv ? " with inverse" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Past the sort's one workgroup: refused, nothing written. */
|
||||
{
|
||||
const int M = 129, ne = 288, k = 8;
|
||||
std::vector<float> lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f),
|
||||
w((size_t)M * k, -7.25f);
|
||||
std::vector<int32_t> ids((size_t)M * k, kPoison), sorted((size_t)M * k, kPoison),
|
||||
off((size_t)ne + 1, kPoison), cnt((size_t)ne, kPoison);
|
||||
RadTensor t[7]{};
|
||||
auto mat = [](RadTensor& x, void* d, uint32_t dt, int r, int c) {
|
||||
x.data = d;
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = c;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
auto vec = [](RadTensor& x, void* d, int n) {
|
||||
x.data = d;
|
||||
x.dtype = RAD_I32;
|
||||
x.rank = 1;
|
||||
x.shape[0] = n;
|
||||
x.stride[0] = 1;
|
||||
};
|
||||
mat(t[0], lg.data(), RAD_F32, M, ne);
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = 1;
|
||||
mat(t[2], ids.data(), RAD_I32, M, k);
|
||||
mat(t[3], w.data(), RAD_F32, M, k);
|
||||
vec(t[4], sorted.data(), M * k);
|
||||
vec(t[5], off.data(), ne + 1);
|
||||
vec(t[6], cnt.data(), ne);
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, 1 };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 2.5;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
++cases;
|
||||
const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
if (rc == RAD_OK || ids[0] != kPoison || sorted[0] != kPoison) {
|
||||
std::printf("FAIL router_sigmoid_topk_scatter served M*top_k=%d past the sort's bound "
|
||||
"(rc %d)\n",
|
||||
M * k, rc);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QuantShape {
|
||||
int M, n;
|
||||
float limit;
|
||||
int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */
|
||||
bool y; /* the fused op also writes the bf16 product */
|
||||
};
|
||||
|
||||
void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const QuantShape shapes[] = {
|
||||
{ 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false },
|
||||
{ 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true },
|
||||
{ 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true },
|
||||
{ 2, 260, 0.5f, 2, false },
|
||||
};
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> ud(0, 15);
|
||||
for (const QuantShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, nkb = (n + 127) / 128;
|
||||
const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3;
|
||||
std::vector<uint16_t> gu((size_t)M * gp, f2b(-3.f));
|
||||
const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < 2 * n; ++c) {
|
||||
float v = nd(rng) * 6.f;
|
||||
uint16_t h = f2b(v);
|
||||
if (sh.mode == 1) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = lim;
|
||||
else if (pick == 1)
|
||||
h = past;
|
||||
else if (pick == 2)
|
||||
h = (uint16_t)(lim | 0x8000u);
|
||||
else if (pick == 3)
|
||||
h = (uint16_t)(past | 0x8000u);
|
||||
else if (pick == 4)
|
||||
h = f2b(-200.f);
|
||||
/* rows divisible by 3 hold an all-zero first group */
|
||||
if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0;
|
||||
} else if (sh.mode == 2) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = 0x7fc0; /* NaN */
|
||||
else if (pick == 1)
|
||||
h = 0x7f80; /* +inf */
|
||||
else if (pick == 2)
|
||||
h = 0xff80; /* -inf */
|
||||
}
|
||||
gu[(size_t)r * gp + c] = h;
|
||||
}
|
||||
RadTensor t[4]{};
|
||||
t[0].data = gu.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = 2 * n;
|
||||
t[0].stride[0] = gp;
|
||||
t[0].stride[1] = 1;
|
||||
auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) {
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = pitch;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
RadParam pc[4]{};
|
||||
pc[0] = { "M", RAD_P_INT, M };
|
||||
pc[1] = { "n", RAD_P_INT, n };
|
||||
pc[2].key = "limit";
|
||||
pc[2].kind = RAD_P_F64;
|
||||
pc[2].dval = sh.limit;
|
||||
pc[3].key = "dtype";
|
||||
pc[3].kind = RAD_P_STR;
|
||||
pc[3].sval = "bf16";
|
||||
RadParam pq[4]{};
|
||||
pq[0] = { "M", RAD_P_INT, M };
|
||||
pq[1] = { "n", RAD_P_INT, n };
|
||||
pq[2] = { "group", RAD_P_INT, 128 };
|
||||
pq[3].key = "dtype";
|
||||
pq[3].kind = RAD_P_STR;
|
||||
pq[3].sval = "bf16";
|
||||
RadParam pf[5]{};
|
||||
pf[0] = pc[0];
|
||||
pf[1] = pc[1];
|
||||
pf[2] = pc[2];
|
||||
pf[3] = pq[2];
|
||||
pf[4] = pc[3];
|
||||
|
||||
std::vector<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
|
||||
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
|
||||
std::vector<float> s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f);
|
||||
RadTensor tc[2] = { t[0], {} };
|
||||
mat(tc[1], RAD_BF16, M, n, yp);
|
||||
tc[1].data = y_ref.data();
|
||||
RadArgs ac{};
|
||||
ac.t = tc;
|
||||
ac.n_t = 2;
|
||||
ac.p = pc;
|
||||
ac.n_p = 4;
|
||||
RadTensor tq[3] = { tc[1], {}, {} };
|
||||
mat(tq[1], RAD_F8E4M3, M, n, qp);
|
||||
tq[1].data = q_ref.data();
|
||||
mat(tq[2], RAD_F32, M, nkb, sp);
|
||||
tq[2].data = s_ref.data();
|
||||
RadArgs aq{};
|
||||
aq.t = tq;
|
||||
aq.n_t = 3;
|
||||
aq.p = pq;
|
||||
aq.n_p = 4;
|
||||
++cases;
|
||||
if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK ||
|
||||
r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
RadTensor tf[4] = { t[0], {}, {}, {} };
|
||||
mat(tf[1], RAD_F8E4M3, M, n, qp);
|
||||
tf[1].data = q.data();
|
||||
mat(tf[2], RAD_F32, M, nkb, sp);
|
||||
tf[2].data = s.data();
|
||||
mat(tf[3], RAD_BF16, M, n, yp);
|
||||
tf[3].data = sh.y ? y.data() : nullptr;
|
||||
RadArgs af{};
|
||||
af.t = tf;
|
||||
af.n_t = 4;
|
||||
af.p = pf;
|
||||
af.n_p = 5;
|
||||
const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr);
|
||||
int bad = 0;
|
||||
bad += q != q_ref;
|
||||
bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0;
|
||||
if (sh.y)
|
||||
bad += y != y_ref;
|
||||
else
|
||||
for (uint16_t v : y) bad += v != 0x7e57;
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d "
|
||||
"mismatching outputs)\n",
|
||||
M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GatherShape {
|
||||
int M, n, nl, base;
|
||||
bool f32w; /* GLM's f32 routing weights, else bf16 */
|
||||
int shared; /* 0 none, 1 the ungated arm (gate 1, act none), 2 a sigmoid gate */
|
||||
};
|
||||
|
||||
/* moe_gather's kernel (r4d_moe_gather.h) as its launcher runs it, reading the table moe_scatter_inv
|
||||
* wrote, against the same kernel building the table itself from `sorted` (T <= 512) or reading the
|
||||
* prepass's table (above). Ids are distinct per row from 288 experts, a slice drops slots. */
|
||||
void gather_inverse_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const GatherShape shapes[] = {
|
||||
{ 1, 4096, 288, 0, true, 1 }, { 6, 4096, 288, 0, true, 1 }, { 8, 512, 288, 0, true, 1 },
|
||||
{ 24, 512, 144, 72, true, 1 }, { 48, 256, 288, 0, true, 1 }, { 64, 256, 288, 0, true, 0 },
|
||||
{ 100, 256, 96, 0, true, 1 }, { 6, 300, 288, 0, false, 2 }, { 33, 256, 288, 0, false, 0 },
|
||||
};
|
||||
const int k = 8, ne = 288;
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
for (const GatherShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, T = M * k, nl = sh.nl;
|
||||
std::vector<int32_t> ids((size_t)T);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
std::vector<int32_t> pool(ne);
|
||||
for (int e = 0; e < ne; ++e) pool[(size_t)e] = e;
|
||||
std::shuffle(pool.begin(), pool.end(), rng);
|
||||
for (int j = 0; j < k; ++j) ids[(size_t)(r * k + j)] = pool[(size_t)j];
|
||||
}
|
||||
Scatter plain = scatter_kernel(ids, nl, sh.base, nullptr, false);
|
||||
Scatter inv = scatter_kernel(ids, nl, sh.base, nullptr, true);
|
||||
++cases;
|
||||
if (plain.rc != RAD_OK || inv.rc != RAD_OK || inv.sorted != plain.sorted ||
|
||||
inv.off != plain.off || inv.cnt != plain.cnt || inv.inv != inverse_of(plain.sorted)) {
|
||||
std::printf("FAIL moe_scatter with the inverse at M=%d slice %d+%d\n", M, sh.base, nl);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const int ye_ld = n + 3, ew_ld = k + 2, y_ld = n + 5, sh_ld = n + 1, sg_ld = 2;
|
||||
std::vector<uint16_t> ye((size_t)T * ye_ld), shp((size_t)M * sh_ld), sg((size_t)M * sg_ld);
|
||||
for (auto& v : ye) v = f2b(nd(rng));
|
||||
for (auto& v : shp) v = f2b(nd(rng));
|
||||
for (size_t i = 0; i < sg.size(); ++i) sg[i] = sh.shared == 1 ? f2b(1.f) : f2b(nd(rng));
|
||||
std::vector<float> ewf((size_t)M * ew_ld);
|
||||
std::vector<uint16_t> ewb((size_t)M * ew_ld);
|
||||
for (size_t i = 0; i < ewf.size(); ++i) {
|
||||
ewf[i] = std::fabs(nd(rng)) * 0.3f;
|
||||
ewb[i] = f2b(ewf[i]);
|
||||
}
|
||||
const void* ew = sh.f32w ? (const void*)ewf.data() : (const void*)ewb.data();
|
||||
const uint16_t* shv = sh.shared ? shp.data() : nullptr;
|
||||
const uint16_t* sgv = sh.shared ? sg.data() : nullptr;
|
||||
const int sig = sh.shared == 2;
|
||||
const bool small = T <= (int)r4d_moegather::kGatherSelfT;
|
||||
/* the launcher's rule: the self-scan up to 512 slots, the prepass's table above */
|
||||
const std::vector<int32_t> table = inverse_of(plain.sorted);
|
||||
const unsigned gy = (unsigned)((n + 255) / 256);
|
||||
auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * y_ld, 0x7e57);
|
||||
if (sh.f32w)
|
||||
R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, true>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
else
|
||||
R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, false>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
};
|
||||
std::vector<uint16_t> y_old, y_new;
|
||||
if (small)
|
||||
gather(nullptr, plain.sorted.data(), y_old);
|
||||
else
|
||||
gather(table.data(), nullptr, y_old);
|
||||
gather(inv.inv.data(), nullptr, y_new);
|
||||
++cases;
|
||||
if (y_new != y_old) {
|
||||
size_t first = 0;
|
||||
while (first < y_new.size() && y_new[first] == y_old[first]) ++first;
|
||||
std::printf("FAIL moe_gather from the inverse at M=%d n=%d slice %d+%d %s weights, "
|
||||
"shared %d: first difference at %zu\n",
|
||||
M, n, sh.base, nl, sh.f32w ? "f32" : "bf16", sh.shared, first);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
int fails = 0, cases = 0;
|
||||
router_scatter_cases(rng, cases, fails);
|
||||
swiglu_quant_cases(rng, cases, fails);
|
||||
gather_inverse_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the
|
||||
* rule picks at each case (named per case, so a moved bound shows) must match a host restatement
|
||||
* of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh
|
||||
* 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0
|
||||
* scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a
|
||||
* longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up
|
||||
* slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped
|
||||
* slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for
|
||||
* odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer
|
||||
* tables. At GLM's TP8 slices below P64 the small-M form, with runs longer than one tile. The
|
||||
* table decode is also held to the arithmetic one over every code. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes
|
||||
* from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high
|
||||
* nibbles' bytes interleave in k order. */
|
||||
static uint32_t fp4x4_ref(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4);
|
||||
}
|
||||
static int check_decode() {
|
||||
int fails = 0;
|
||||
auto one = [&](uint32_t w) {
|
||||
const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu);
|
||||
const uint32_t lo_ref = __byte_perm(low, high, 0x5140),
|
||||
hi_ref = __byte_perm(low, high, 0x7362);
|
||||
uint32_t lo, hi, tlo, thi;
|
||||
r4d_mxfp4_unpack8_exact(w, &lo, &hi);
|
||||
r4d_mxfp4_unpack8(w, 0, &tlo, &thi);
|
||||
if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) {
|
||||
if (fails < 4)
|
||||
std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi,
|
||||
lo, hi_ref, lo_ref);
|
||||
++fails;
|
||||
}
|
||||
/* each byte against the e2m1 value it encodes */
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const uint32_t c = (w >> (4 * e)) & 15u;
|
||||
static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f };
|
||||
const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u];
|
||||
const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu);
|
||||
if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) {
|
||||
if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
};
|
||||
/* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves
|
||||
* of the word, and random words over all four */
|
||||
for (uint32_t v = 0; v < 65536; ++v) {
|
||||
one(v);
|
||||
one(v << 16);
|
||||
one(v << 8);
|
||||
}
|
||||
std::mt19937 rng(7);
|
||||
for (int i = 0; i < 200000; ++i) one((uint32_t)rng());
|
||||
return fails;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
int N, K, N_odd, K_odd, parts, top;
|
||||
bool sorted_a, tables, exceptional;
|
||||
std::vector<int> runs;
|
||||
int tail; // dropped slots past the routed rows
|
||||
const char* kernel; // the form the rule picks
|
||||
};
|
||||
|
||||
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
|
||||
* default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap;
|
||||
* the card generates the positive quiet NaN, so a NaN's sign carries no information here. */
|
||||
static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); }
|
||||
static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
for (size_t i = 0; i < a.size() && i < b.size(); ++i)
|
||||
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
|
||||
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
|
||||
}
|
||||
|
||||
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
|
||||
std::vector<int64_t> stride) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
for (size_t i = 0; i < shape.size(); ++i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = stride[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */
|
||||
static std::vector<int> glm_runs(std::vector<int> live) {
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
std::vector<int> runs(288, 0);
|
||||
for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i];
|
||||
return runs;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_decode(), cases = 1;
|
||||
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
|
||||
|
||||
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
|
||||
const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)";
|
||||
const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)";
|
||||
const char* const groups = "moe_mxfp4_fp8_kernel";
|
||||
const Case all[] = {
|
||||
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6,
|
||||
groups },
|
||||
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
|
||||
2, groups },
|
||||
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups },
|
||||
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups },
|
||||
{ "expert-major, K 384",
|
||||
64,
|
||||
384,
|
||||
64,
|
||||
384,
|
||||
2,
|
||||
2,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
{ 0, 1, 15, 16, 17, 30 },
|
||||
3,
|
||||
expert },
|
||||
{ "expert-major, K 256, exceptional codes",
|
||||
64,
|
||||
256,
|
||||
32,
|
||||
256,
|
||||
1,
|
||||
2,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
{ 1, 0, 3, 15, 1 },
|
||||
2,
|
||||
staged },
|
||||
{ "expert-major, K 512:384, runs past 64 rows, N under a block",
|
||||
96,
|
||||
512,
|
||||
96,
|
||||
384,
|
||||
1,
|
||||
2,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
{ 32, 33, 31, 96, 128, 129, 0, 2 },
|
||||
9,
|
||||
expert },
|
||||
{ "expert-major, K 256:128, column tiles cut",
|
||||
192,
|
||||
256,
|
||||
128,
|
||||
128,
|
||||
2,
|
||||
4,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
{ 64, 63, 65, 1, 0, 127, 17 },
|
||||
5,
|
||||
staged },
|
||||
{ "GLM TP4 down, the GLM prefill form",
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }),
|
||||
13,
|
||||
"moe_mxfp4_prefill_kernel" },
|
||||
{ "GLM TP8 gate_up, P64 BM32 BN64 K256",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 200, 33, 300, 31, 200 }),
|
||||
20,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, four tokens",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 1, 2, 1, 3, 1, 6, 1, 2, 9, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, runs past one tile",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }),
|
||||
2,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 down, small-M form, a run past one tile",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 3, 1, 17, 2, 1, 1, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<256, 4>)" },
|
||||
{ "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }),
|
||||
40,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" },
|
||||
};
|
||||
|
||||
for (const Case& c : all) {
|
||||
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
|
||||
int routed = 0;
|
||||
for (int r : c.runs) routed += r;
|
||||
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
|
||||
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
|
||||
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
|
||||
yp = OUT + ((&c - all) % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1000 + cases);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
|
||||
std::vector<float> as((size_t)Arows * asp);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
// A dropped slot about every eleventh row, the first rows of some runs included.
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
/* Stacked planes hold every expert; a pointer table names one of at most three slices a
|
||||
* class, so GLM's 288 experts stay small. */
|
||||
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
|
||||
nexp[2] = { (E + 1) / 2, E / 2 };
|
||||
std::vector<uint8_t> w[2], s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
std::vector<std::vector<float>> wf[2];
|
||||
int slices[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q];
|
||||
w[q].resize((size_t)slices[q] * n[q] * k[q] / 2);
|
||||
s[q].resize((size_t)slices[q] * n[q] * k[q] / 32);
|
||||
for (auto& v : w[q]) v = (uint8_t)rng();
|
||||
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
|
||||
for (size_t i = 0; i < s[q].size(); ++i)
|
||||
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
|
||||
: (uint8_t)(118 + rng() % 16);
|
||||
for (int x = 0; x < nexp[q]; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32);
|
||||
}
|
||||
/* each slice's codes as the E4M3 values the table decode gives */
|
||||
for (int x = 0; x < slices[q]; ++x) {
|
||||
std::vector<float> f((size_t)n[q] * k[q]);
|
||||
const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2;
|
||||
for (size_t i = 0; i < f.size(); ++i) {
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi);
|
||||
f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
|
||||
}
|
||||
wf[q].push_back(std::move(f));
|
||||
}
|
||||
}
|
||||
auto plane = [&](int q, bool scale) {
|
||||
const int64_t cols = scale ? k[q] / 32 : k[q];
|
||||
void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data())
|
||||
: (void*)(scale ? s[q].data() : w[q].data());
|
||||
RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols },
|
||||
{ c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 });
|
||||
return t;
|
||||
};
|
||||
|
||||
/* the per-element sequence, on the host */
|
||||
std::vector<float> af(a.size());
|
||||
for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]);
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int col = 0; col < OUT; ++col) {
|
||||
uint16_t& out = ref[(size_t)r * yp + col];
|
||||
out = 0;
|
||||
if (owner[r] < 0 || sorted[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top;
|
||||
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
|
||||
const bool valid = within < cw;
|
||||
const int wn = (col / pw) * cw + within;
|
||||
const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q];
|
||||
const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32;
|
||||
const float* arow = af.data() + (size_t)ar * ap;
|
||||
float total = 0.f;
|
||||
for (int kb = 0; kb < k[q]; kb += 128)
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
float raw = 0.f;
|
||||
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk)
|
||||
raw += arow[kk] * (valid ? wr[kk] : 0.f);
|
||||
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
|
||||
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
|
||||
float scale;
|
||||
std::memcpy(&scale, &bits, 4);
|
||||
float t = raw * as[(size_t)ar * asp + kb / 128];
|
||||
t = t * scale;
|
||||
total = total + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &total, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
|
||||
16); // f32_to_bf16, r4d_common.h
|
||||
}
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (live < T * OUT / 3) {
|
||||
std::printf("FAIL %s: output mostly zero\n", c.name);
|
||||
++fails;
|
||||
}
|
||||
|
||||
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
|
||||
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
|
||||
plane(0, false),
|
||||
plane(0, true),
|
||||
ten(sorted.data(), RAD_I32, { T }, { 1 }),
|
||||
ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }),
|
||||
plane(1, false),
|
||||
plane(1, true),
|
||||
RadTensor{} };
|
||||
RadParam p[11]{};
|
||||
auto pi = [](const char* key, long long v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
return x;
|
||||
};
|
||||
auto ps = [](const char* key, const char* v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_STR;
|
||||
x.sval = v;
|
||||
return x;
|
||||
};
|
||||
p[0] = pi("M", T / c.top);
|
||||
p[1] = pi("N", c.N);
|
||||
p[2] = pi("K", c.K);
|
||||
p[3] = pi("N_odd", c.N_odd);
|
||||
p[4] = pi("K_odd", c.K_odd);
|
||||
p[5] = pi("n_expert", E);
|
||||
p[6] = pi("top_k", c.top);
|
||||
p[7] = pi("parts", c.parts);
|
||||
p[8] = pi("group", 128);
|
||||
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
|
||||
p[10] = ps("dtype", "mxfp4a8");
|
||||
std::vector<uint16_t> got((size_t)T * yp, 0x7777);
|
||||
t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 });
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 11;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = r4d_rad_moe_mxfp4(&ar, nullptr);
|
||||
const size_t i = first_diff(got, ref);
|
||||
if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: "
|
||||
"%04x, want %04x)\n",
|
||||
c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp,
|
||||
i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
+67
-12
@@ -12,7 +12,11 @@
|
||||
* seeded sweep of small odd shapes (NaN, +-inf, -0.0, denormal and -1e30 scores, pitches, a table
|
||||
* narrower than the scores, rows no sequence holds, topk 1, ratio 1). Which branch a row takes
|
||||
* inside the kernels is predicted from their constants, restated in `Path`; the run fails when the
|
||||
* fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead. */
|
||||
* fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead.
|
||||
*
|
||||
* Fixtures marked signed run with the op's `signed` parameter: the kernels' signed key order,
|
||||
* against the port's signed ranking, over negative, mixed and the sweep's odd scores. The unsigned
|
||||
* fixtures are the same as without the parameter. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
@@ -42,6 +46,7 @@ struct Fix {
|
||||
int S = 1, M = 1, nb_s = 1, nb_t = 1; /* sequences, query rows, score and table widths */
|
||||
int s_ld = 0, t_ld = 0, o_ld = 0; /* row pitches; 0 = tight */
|
||||
int topk = 1, ratio = 1;
|
||||
bool sgn = false; /* the op's `signed` parameter */
|
||||
std::vector<float> sc; /* [M][s_ld] */
|
||||
std::vector<int32_t> bt; /* [S][t_ld] */
|
||||
std::vector<int32_t> nc, pos, cu; /* [S], [M], [S + 1] */
|
||||
@@ -66,7 +71,7 @@ struct Fix {
|
||||
};
|
||||
|
||||
/* ---- libref's ref_qsa_select (libref/ref_qsa.cpp), restated over the fixture's arrays: the same
|
||||
* steps in the same order. */
|
||||
* steps in the same order, both rankings. */
|
||||
void ref_select(const Fix& f, std::vector<int32_t>& se, std::vector<int32_t>& ns, std::vector<int32_t>& su) {
|
||||
const int64_t topk = f.topk, ratio = f.ratio;
|
||||
se.assign((size_t)f.M * (topk + 1), 0); ns.assign((size_t)f.M, 0); su.assign((size_t)f.M, 0);
|
||||
@@ -77,8 +82,9 @@ void ref_select(const Fix& f, std::vector<int32_t>& se, std::vector<int32_t>& ns
|
||||
std::vector<int64_t> live;
|
||||
for (int64_t b = 0; b < n; ++b) {
|
||||
const float v = f.sc[(size_t)(m * f.s_ld + b)];
|
||||
if (f.bt[(size_t)(s * f.t_ld + b)] < 0 || !(v > -1e30f)) continue;
|
||||
val[(size_t)b] = v > 0.0f ? v : 0.0f;
|
||||
if (f.bt[(size_t)(s * f.t_ld + b)] < 0) continue;
|
||||
if (f.sgn ? !std::isfinite(v) : !(v > -1e30f)) continue;
|
||||
val[(size_t)b] = f.sgn ? v : v > 0.0f ? v : 0.0f;
|
||||
live.push_back(b);
|
||||
}
|
||||
std::vector<int64_t> take;
|
||||
@@ -114,6 +120,8 @@ namespace Path {
|
||||
constexpr int kCacheCap = 8192, kCacheMaxM = 64; /* the key cache */
|
||||
constexpr int kSamp = 2048, kSampRun = 32, kSampRuns = 64, kSampMinN = 3 * kSamp, kSampCap = 1920;
|
||||
constexpr int kWideShift = 19, kWideCand = 3840, kMergeAbove = 512, kMergeCand = 1664;
|
||||
constexpr int kWideShiftSigned = 20; /* the signed key's 32 bits */
|
||||
int wide_shift(bool sgn) { return sgn ? kWideShiftSigned : kWideShift; }
|
||||
constexpr int kParM = 32, kParWMax = 16, kParCap = 8192; /* the split path */
|
||||
int par_chunks(int nb) { return std::max(1, std::min(kParWMax, (nb + 4095) / 4096)); }
|
||||
}
|
||||
@@ -126,6 +134,14 @@ uint32_t keyof(float v, int32_t page) {
|
||||
return u + 1u;
|
||||
}
|
||||
|
||||
/* The signed order: the float's total order over 32 bits, -0 keyed as +0, nonfinite dead. */
|
||||
uint32_t keyof_signed(float v, int32_t page) {
|
||||
if (page < 0 || !std::isfinite(v)) return 0u;
|
||||
uint32_t u = 0;
|
||||
if (v != 0.0f) std::memcpy(&u, &v, 4);
|
||||
return (u & 0x80000000u) ? ~u : (u ^ 0x80000000u);
|
||||
}
|
||||
|
||||
enum Form { kSingle, kWide, kAuto };
|
||||
const char* const kFormName[] = { "single", "wide", "auto" };
|
||||
|
||||
@@ -140,7 +156,11 @@ std::map<std::string, int> g_paths;
|
||||
void note_paths(const Fix& f, int m, Form form, bool split) {
|
||||
const int s = f.seq_of(m), n = f.n_of(m), topk = f.topk;
|
||||
std::vector<uint32_t> k((size_t)std::max(n, 0));
|
||||
for (int b = 0; b < n; ++b) k[(size_t)b] = keyof(f.sc[(size_t)m * f.s_ld + b], f.bt[(size_t)s * f.t_ld + b]);
|
||||
for (int b = 0; b < n; ++b) {
|
||||
const float v = f.sc[(size_t)m * f.s_ld + b];
|
||||
const int32_t pg = f.bt[(size_t)s * f.t_ld + b];
|
||||
k[(size_t)b] = f.sgn ? keyof_signed(v, pg) : keyof(v, pg);
|
||||
}
|
||||
std::vector<uint32_t> live;
|
||||
for (uint32_t x : k) if (x) live.push_back(x);
|
||||
std::sort(live.begin(), live.end(), std::greater<uint32_t>());
|
||||
@@ -155,6 +175,7 @@ void note_paths(const Fix& f, int m, Form form, bool split) {
|
||||
int above = 0, eq = 0;
|
||||
for (uint32_t x : live) { above += x > T; eq += x == T; }
|
||||
if (eq > topk - above) hit("a threshold whose ties are cut short");
|
||||
if (f.sgn && T < 0x80000000u) hit("signed: a negative threshold");
|
||||
}
|
||||
if (split) {
|
||||
const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch;
|
||||
@@ -200,9 +221,10 @@ void note_paths(const Fix& f, int m, Form form, bool split) {
|
||||
hit("wide: a sample that fell back");
|
||||
}
|
||||
if (L <= topk) return;
|
||||
const uint32_t B = live[(size_t)topk - 1] >> Path::kWideShift;
|
||||
const int shift = Path::wide_shift(f.sgn);
|
||||
const uint32_t B = live[(size_t)topk - 1] >> shift;
|
||||
int in = 0;
|
||||
for (uint32_t x : live) in += (x >> Path::kWideShift) == B;
|
||||
for (uint32_t x : live) in += (x >> shift) == B;
|
||||
hit(in <= Path::kMergeCand && topk <= Path::kMergeAbove ? "wide: merged lists"
|
||||
: in <= Path::kWideCand ? "wide: the threshold's bin in LDS" : "wide: the threshold's bin over global memory");
|
||||
}
|
||||
@@ -227,10 +249,10 @@ int run(Fix& f, Form form) {
|
||||
tens(f.cu.data(), RAD_I32, {f.S + 1}), tens(se.data(), RAD_I32, {M, W}, f.o_ld),
|
||||
tens(ns.data(), RAD_I32, {M}), tens(su.data(), RAD_I32, {M}),
|
||||
};
|
||||
RadParam p[5]{};
|
||||
RadParam p[6]{};
|
||||
p[0] = {"M", RAD_P_INT, M}; p[1] = {"blocks", RAD_P_INT, f.nb()}; p[2] = {"topk", RAD_P_INT, f.topk};
|
||||
p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S};
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = 5;
|
||||
p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S}; p[5] = {"signed", RAD_P_INT, 1};
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = f.sgn ? 6 : 5;
|
||||
const int64_t need = r4d_rad_qsa_select_scratch(&a);
|
||||
std::vector<uint32_t> scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u);
|
||||
if (form == kAuto) { a.scratch = scratch.data(); a.scratch_bytes = need; }
|
||||
@@ -245,7 +267,9 @@ int run(Fix& f, Form form) {
|
||||
: "qsa_select_kernel";
|
||||
const char* fn = kFormName[form];
|
||||
if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; }
|
||||
if (std::strcmp(emu_last_kernel, expect) != 0 || grids != (split ? 2 : 1)) {
|
||||
/* The launch site names the template, `kernel<Signed>`: the name is what precedes it. */
|
||||
const std::string ran(emu_last_kernel, std::strcspn(emu_last_kernel, "<"));
|
||||
if (ran != expect || grids != (split ? 2 : 1)) {
|
||||
std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn,
|
||||
emu_last_kernel, grids, expect, split ? 2 : 1);
|
||||
return 1;
|
||||
@@ -324,8 +348,11 @@ Fix fix_prefill() {
|
||||
* score distributions. Over 4096 blocks at six rows, the automatic choice is the split path. */
|
||||
Fix fix_wide(int dist) {
|
||||
static const char* const kDist[] = { "continuous", "coarse, heavy ties", "an eighth in one first-digit bin",
|
||||
"all in one first-digit bin", "fine ties at the threshold" };
|
||||
"all in one first-digit bin", "fine ties at the threshold",
|
||||
"signed, heavy ties", "signed, all negative, heavy ties",
|
||||
"signed, continuous across zero" };
|
||||
Fix f; f.name = std::string("wide: ") + kDist[dist];
|
||||
f.sgn = dist >= 5;
|
||||
const int S = 2, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20;
|
||||
f.shape(S, 6, nb, nb, topk, ratio);
|
||||
f.cu = { 0, 4, 6 };
|
||||
@@ -341,6 +368,9 @@ Fix fix_wide(int dist) {
|
||||
case 1: v = (float)(u % 23) * 0.25f; break;
|
||||
case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break;
|
||||
case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break;
|
||||
case 5: v = (float)(u % 23) * 0.25f - 3.0f; break;
|
||||
case 6: v = -(float)(u % 23) * 0.25f - 1.0f; break;
|
||||
case 7: v = (float)(u % 1000003) / 1000.0f - 500.0f; break;
|
||||
default: v = (float)(u % 4999) * 0.01f; break;
|
||||
}
|
||||
}
|
||||
@@ -551,6 +581,22 @@ Fix fix_random(int it) {
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A fixture under the signed order, its finite scores negated on odd rows when `flip` and moved
|
||||
* by `shift`, so live scores straddle zero or fall below it. */
|
||||
Fix as_signed(Fix f, float shift, bool flip = false) {
|
||||
f.sgn = true;
|
||||
f.name = "signed " + f.name;
|
||||
if (shift == 0.0f && !flip) return f; /* as built: keeps -0 apart from +0 */
|
||||
for (int m = 0; m < f.M; ++m)
|
||||
for (int b = 0; b < f.nb_s; ++b) {
|
||||
float& v = f.score(m, b);
|
||||
if (!std::isfinite(v)) continue;
|
||||
if (flip && m % 2) v = -v;
|
||||
v += shift;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* No argument: the fixtures above and the branch check. `sweep N`: N fix_random fixtures, about
|
||||
@@ -562,12 +608,20 @@ int main(int argc, char** argv) {
|
||||
if (sweep) {
|
||||
const int n = argc > 2 ? std::atoi(argv[2]) : 100;
|
||||
for (int i = 0; i < n; ++i) fixtures.push_back([i] { return fix_random(i); });
|
||||
for (int i = 0; i < n; ++i) fixtures.push_back([i] { return as_signed(fix_random(i), -1.0f, true); });
|
||||
} else {
|
||||
fixtures = { fix_decode, fix_prefill, fix_few_live, fix_wide_launch,
|
||||
[] { return fix_split(1, 4); }, [] { return fix_split(2, 4); }, fix_split_sparse, fix_big_topk,
|
||||
[] { return fix_no_split(true); }, [] { return fix_no_split(false); } };
|
||||
for (int d = 0; d < 5; ++d) fixtures.push_back([d] { return fix_wide(d); });
|
||||
for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return fix_sweep(i); });
|
||||
fixtures.push_back([] { return as_signed(fix_decode(), -5.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_decode(), -20.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_few_live(), 0.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_split(2, 4), -6.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_wide_launch(), -1.0f, true); });
|
||||
for (int d = 5; d < 8; ++d) fixtures.push_back([d] { return fix_wide(d); });
|
||||
for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return as_signed(fix_sweep(i), 0.0f); });
|
||||
}
|
||||
int fails = 0, launches = 0;
|
||||
for (auto& make : fixtures) {
|
||||
@@ -592,6 +646,7 @@ int main(int argc, char** argv) {
|
||||
"wide: the threshold's bin in LDS", "wide: the threshold's bin over global memory",
|
||||
"split: topk or fewer live, every one taken", "split: no chunk over topk, more than topk live",
|
||||
"split: a chunk over topk", "split: exactly topk candidates, from a chunk over topk",
|
||||
"signed: a negative threshold",
|
||||
};
|
||||
int missing = 0;
|
||||
for (const char* p : kRequired)
|
||||
|
||||
+5
-1
@@ -14,6 +14,8 @@
|
||||
* RAD_TEST_TMPDIR where tmpdir() is made, before $TMPDIR and /tmp
|
||||
* RAD_TEST_CPU_BUDGET seconds of process CPU time the binary may spend; over it, it fails
|
||||
* tests/CMakeLists.txt sets the last three for every ctest entry.
|
||||
* RAD_TEST_CPU_BUDGET_SCALE a factor on that budget, for a host slower per thread than the
|
||||
* one the budgets were set on; unset or 0 is 1
|
||||
*
|
||||
* Exit status: 1 when a check failed (an exception escaping a case is a failed check), 77 when
|
||||
* nothing failed and no check ran, 2 for a command line it does not understand, else 0. 77 is
|
||||
@@ -288,7 +290,9 @@ inline int run_all(int argc, char** argv) {
|
||||
* so a slow case or a spinning thread pool is caught when it lands. CPU time rather than wall
|
||||
* time, so a loaded machine does not fail a correct binary. */
|
||||
if (const char* b = std::getenv("RAD_TEST_CPU_BUDGET")) {
|
||||
const double budget = std::atof(b);
|
||||
double budget = std::atof(b);
|
||||
if (const char* s = std::getenv("RAD_TEST_CPU_BUDGET_SCALE"); s && std::atof(s) > 0)
|
||||
budget *= std::atof(s);
|
||||
if (budget > 0 && cpu > budget && rc != 1) {
|
||||
fprintf(stderr, " FAIL the binary spent %.2f s of CPU, over its budget of %g s "
|
||||
"(RAD_TEST_CPU_BUDGET)\n", cpu, budget);
|
||||
|
||||
@@ -175,4 +175,57 @@ TEST(the_nvfp4_recipe_decides_the_model_it_was_written_for) {
|
||||
CHECK(has_opt(dh, "codes", "u2"));
|
||||
}
|
||||
|
||||
/* The Sage-A1.5 recipe as it ships: every trunk linear -- attention, the delta net's in- and
|
||||
* out-projections, the routed and shared experts of all 40 blocks and the MTP layer at its own
|
||||
* index 40 -- goes to block fp8, the head likewise, and the routers, the shared-expert gates,
|
||||
* the delta net's parameters, the norms, the embedding and the vision tower keep the
|
||||
* checkpoint's form. */
|
||||
TEST(the_sage_recipe_decides_the_model_it_was_written_for) {
|
||||
std::string dir = __FILE__;
|
||||
dir = dir.substr(0, dir.find_last_of('/')) + "/../data/recipes";
|
||||
std::ifstream in(dir + "/sage-a1.5-fp8.recipe");
|
||||
REQUIRE(in.good());
|
||||
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
Recipe r;
|
||||
std::string why;
|
||||
REQUIRE_EQ(r.add_text(text, "sage-a1.5-fp8.recipe", &why), RAD_OK);
|
||||
CHECK_EQ(r.rules().size(), (size_t)12);
|
||||
|
||||
const char* linears[] = { "blk.0.attn_qg.weight", "blk.3.attn_qg.weight", "blk.39.attn_qg.weight",
|
||||
"blk.40.attn_qg.weight", "blk.3.attn_k.weight", "blk.3.attn_v.weight",
|
||||
"blk.39.attn_output.weight", "blk.0.ssm_inz.weight", "blk.39.ssm_out.weight",
|
||||
"blk.0.ffn_gate_up_exps.0.weight", "blk.19.ffn_down_exps.255.weight",
|
||||
"blk.40.ffn_gate_up_exps.0.weight", "blk.40.ffn_down_exps.255.weight",
|
||||
"blk.0.ffn_gate_up_shexp.weight", "blk.40.ffn_down_shexp.weight" };
|
||||
for (const char* n : linears) {
|
||||
const RecipeRule* m = r.match(n);
|
||||
REQUIRE(m != nullptr);
|
||||
CHECK_EQ(m->quantizer, std::string("rtn"));
|
||||
CHECK(has_opt(m, "codes", "fp8_e4m3"));
|
||||
CHECK(has_opt(m, "block", "128x128"));
|
||||
CHECK(has_opt(m, "scale", "bf16"));
|
||||
}
|
||||
const RecipeRule* head = r.match("output.weight");
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK(has_opt(head, "codes", "fp8_e4m3"));
|
||||
CHECK(has_opt(head, "block", "128x128"));
|
||||
const RecipeRule* dh = r.match("mtp.draft_head.weight");
|
||||
REQUIRE(dh != nullptr);
|
||||
CHECK(has_opt(dh, "codes", "u2"));
|
||||
CHECK(has_opt(dh, "zero", "u8"));
|
||||
CHECK(has_opt(dh, "group", "128"));
|
||||
CHECK(has_opt(dh, "scale", "f16"));
|
||||
|
||||
/* kept as the checkpoint ships them: the routers, the gates, the delta net's parameters,
|
||||
* the norms, the embedding and the whole vision tower */
|
||||
const char* kept[] = { "blk.0.ffn_norm.weight", "blk.0.attn_norm.weight", "blk.0.ssm_ab.weight",
|
||||
"blk.0.ssm_conv1d.weight", "blk.0.ssm_a_log", "blk.0.ssm_dt.bias",
|
||||
"blk.0.ssm_norm.weight", "blk.0.ffn_gate_inp.weight",
|
||||
"blk.0.ffn_gate_shexp.weight", "blk.40.ffn_gate_inp.weight",
|
||||
"token_embd.weight", "output_norm.weight", "mtp.fc.weight",
|
||||
"mtp.norm.weight", "v.blk.0.qkv.weight", "v.merger.fc1.weight" };
|
||||
for (const char* n : kept)
|
||||
CHECK(r.match(n) == nullptr);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+1194
-8
File diff suppressed because it is too large.
Load diff
+57
-5
@@ -229,7 +229,7 @@ struct Fixture {
|
||||
return (rad_op)(P.ops.size() - 1);
|
||||
}
|
||||
|
||||
int start(rad::ResidencyTable* res = nullptr, bool profile = false) {
|
||||
int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false) {
|
||||
CtxDesc d;
|
||||
d.program = &P;
|
||||
d.rank = 1;
|
||||
@@ -241,8 +241,8 @@ struct Fixture {
|
||||
d.registry = registry;
|
||||
/* The arch bodies here issue whatever a case asks, which the batch does not describe, so
|
||||
* no pass may be recorded and replayed under the batch's key (a card records passes; the
|
||||
* host backend cannot). */
|
||||
d.record_passes = false;
|
||||
* host backend cannot). A case about the recording decision itself asks for it. */
|
||||
d.record_passes = record;
|
||||
return ctx.init(d);
|
||||
}
|
||||
|
||||
@@ -918,7 +918,7 @@ TEST(raw_operand_carries_the_pointer_and_refuses_an_offset) {
|
||||
* lora_shrink and lora_expand over its own activation, output and rows, but only on a step that
|
||||
* has an adapter row (RadBatch::lora_slot non-null). A step without one, or a draft pass, issues
|
||||
* the gemm alone, the pass an engine without adapters runs; an encoder pass reaching a site is
|
||||
* refused by name. */
|
||||
* refused by name; a generator pass runs its one slot in every row. */
|
||||
static int k_gemm (const RadArgs* a, RadStream s) { return record("gemm", a, s); }
|
||||
static int k_shrink(const RadArgs* a, RadStream s) { return record("shrink", a, s); }
|
||||
static int k_expand(const RadArgs* a, RadStream s) { return record("expand", a, s); }
|
||||
@@ -933,6 +933,7 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
const rad_buf ps = f.add_buffer("lora.scale", RAD_F32, 2, 8, 1536);
|
||||
const rad_buf t0 = f.add_buffer("lora.t0", RAD_F32, 16, 4, 2048);
|
||||
const rad_buf t1 = f.add_buffer("lora.t1", RAD_F32, 16, 4, 2304);
|
||||
const rad_buf rows = f.add_buffer("lora.rows", RAD_I32, 32, 1, 2560); /* [S * 16] */
|
||||
const rad_op g = f.add_op("gemm_nt", "M", { 64 }, { k_gemm }, { "gemm" }, &g_gemm_schema, { w });
|
||||
const rad_op sh = f.add_op("lora_shrink", "M", { 64 }, { k_shrink }, { "shrink" }, nullptr, {});
|
||||
const rad_op ex = f.add_op("lora_expand", "M", { 64 }, { k_expand }, { "expand" }, nullptr, {});
|
||||
@@ -955,6 +956,8 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
scr.R = 4;
|
||||
scr.lane[0] = t0; scr.lane[1] = t1;
|
||||
f.P.lora_t.push_back(scr);
|
||||
f.P.lora_rows = rows;
|
||||
f.P.lora_rows_n = 16;
|
||||
CHECK_OK(f.start());
|
||||
|
||||
auto body = [&](Ctx& c) {
|
||||
@@ -1002,8 +1005,38 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) {
|
||||
c.issue(g, opd, 3, RAD_N_BATCH);
|
||||
});
|
||||
CHECK_EQ(s, RAD_E_UNSUPPORTED);
|
||||
CHECK(std::strstr(f.ctx.step_error(), "encoder or generator pass") != nullptr);
|
||||
CHECK(std::strstr(f.ctx.step_error(), "encoder pass") != nullptr);
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
|
||||
/* A generator pass runs one slot in every row, whatever the gemm's rows are: its slot operand
|
||||
* is that slot's run of the slot-row table; with no slot, the gemm alone. */
|
||||
f.batch.enc = 0;
|
||||
f.batch.gen = RAD_GEN_PASS_DENOISE;
|
||||
f.batch.lora_slot = nullptr;
|
||||
f.ctx.set_gen_lora_slot(-1);
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 4, body));
|
||||
CHECK_EQ(names(), std::string("gemm"));
|
||||
f.ctx.set_gen_lora_slot(1);
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 5, body));
|
||||
REQUIRE_EQ(names(), std::string("gemm shrink expand"));
|
||||
CHECK(g_rec[1].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 16 * 4));
|
||||
CHECK_EQ(g_rec[1].t[2].shape[0], (int64_t)4);
|
||||
CHECK(g_rec[2].t[1].data == g_rec[1].t[2].data);
|
||||
/* Rows past the slot table's run are issued in chunks of it, each over its own rows. */
|
||||
f.P.lora_rows_n = 3;
|
||||
g_rec.clear();
|
||||
CHECK_OK(f.step(4, 6, body));
|
||||
REQUIRE_EQ(names(), std::string("gemm shrink expand shrink expand"));
|
||||
CHECK_EQ(g_rec[1].t[0].shape[0], (int64_t)3);
|
||||
CHECK_EQ(g_rec[3].t[0].shape[0], (int64_t)1);
|
||||
CHECK(g_rec[3].t[0].data == (void*)((char*)g_rec[1].t[0].data + 3 * 4 * 2)); /* x row 3 */
|
||||
CHECK(g_rec[4].t[4].data == (void*)((char*)g_rec[2].t[4].data + 3 * 8 * 2)); /* y row 3 */
|
||||
CHECK(g_rec[3].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 3 * 4));
|
||||
f.P.lora_rows_n = 16;
|
||||
f.ctx.set_gen_lora_slot(-1);
|
||||
f.batch.gen = 0;
|
||||
}
|
||||
|
||||
/* Site is a property of the weights (spec §5.1). A domain with no kernel in some band is refused,
|
||||
@@ -1869,6 +1902,25 @@ TEST(a_lane_built_mid_step_starts_behind_lane_zero) {
|
||||
CHECK_EQ(dev_get(f, f.ctx.buf_ptr(y)), 4242);
|
||||
}
|
||||
|
||||
/* A calibration tap's gram_accum sums across passes while its plugin counts the summed rows in
|
||||
* step; a played pass reissues the sum without calling step (#122). A program holding one records
|
||||
* no passes; one without records them wherever the backend can. */
|
||||
TEST(a_program_with_a_calibration_tap_records_no_passes) {
|
||||
{
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
loose_op(f);
|
||||
CHECK_OK(f.start(nullptr, false, /*record=*/true));
|
||||
CHECK_EQ(f.ctx.records_passes(), rad::tape_supported());
|
||||
}
|
||||
Fixture f;
|
||||
f.add_buffer("x", RAD_BF16, 64, 4, 0);
|
||||
loose_op(f);
|
||||
loose_op(f, "gram_accum");
|
||||
CHECK_OK(f.start(nullptr, false, /*record=*/true));
|
||||
CHECK(!f.ctx.records_passes());
|
||||
}
|
||||
|
||||
/* ================================================================== the pass key */
|
||||
/* A recorded pass is replayed while its key holds, so the key must change with every batch field
|
||||
* and runtime state a pass's shape or arguments read, and must not change with the step number
|
||||
|
||||
+48
-6
@@ -1108,11 +1108,12 @@ TEST(json_schema_refuses_what_it_cannot_actually_enforce) {
|
||||
"{\"$ref\":\"https://example.com/s.json#/x\"}", "root", &gbnf, &err) < 0);
|
||||
CHECK(!err.empty());
|
||||
|
||||
/* GBNF cannot spell \d. Copying it through would succeed here and produce a grammar that
|
||||
* fails to load, an internal error on a schema we accepted. */
|
||||
/* GBNF cannot spell \b. Copying it through would succeed here and produce a grammar that
|
||||
* fails to load, an internal error on a schema we accepted. (\d and its kin are written out
|
||||
* as classes since vendor patch 0018.) */
|
||||
err.clear();
|
||||
CHECK(grammar_from_json_schema(
|
||||
"{\"type\":\"string\",\"pattern\":\"^\\\\d+$\"}", "root", &gbnf, &err) < 0);
|
||||
"{\"type\":\"string\",\"pattern\":\"^a\\\\bb$\"}", "root", &gbnf, &err) < 0);
|
||||
CHECK(!err.empty());
|
||||
|
||||
/* A stray ']' is in NON_LITERAL_SET but claimed by no arm of the pattern scanner, so the
|
||||
@@ -1123,10 +1124,11 @@ TEST(json_schema_refuses_what_it_cannot_actually_enforce) {
|
||||
"{\"type\":\"string\",\"pattern\":\"^a]$\"}", "root", &gbnf, &err) < 0);
|
||||
CHECK(!err.empty());
|
||||
|
||||
/* An empty pattern would run front()/back() on an empty string. */
|
||||
/* An empty pattern would run front()/back() on an empty string. Unanchored, as JSON Schema
|
||||
* reads it, it now matches every string and never reaches them (vendor patch 0017). */
|
||||
err.clear();
|
||||
CHECK(grammar_from_json_schema(
|
||||
"{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err) < 0);
|
||||
CHECK_OK(grammar_from_json_schema(
|
||||
"{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err));
|
||||
|
||||
/* A leading quantifier would run back() on an empty vector. */
|
||||
err.clear();
|
||||
@@ -2098,6 +2100,46 @@ TEST(a_greedy_row_over_a_split_vocabulary_is_staged_as_a_chain_row) {
|
||||
CHECK_EQ(p[1].top_k, 1);
|
||||
}
|
||||
|
||||
/* Over a split vocabulary the merge holds every rank's candidates in one workgroup, 4096 pairs at
|
||||
* most (kSampleMergeCandidates, libr4d's sample_merge_topk). At two and four ranks the default
|
||||
* width of 1024 a rank fits; at eight it would ask 8192 and the step's merge would find no kernel,
|
||||
* so declare narrows it to 512 and admission refuses a wider top_k instead. */
|
||||
TEST(the_candidate_width_over_a_split_vocabulary_is_what_the_merge_holds) {
|
||||
Registry reg;
|
||||
(void)reg.load_plugin(home() + "/kernels/libref.so", 0);
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
RadModelMeta meta{};
|
||||
meta.arch_id = "sampler_split";
|
||||
meta.name = "sampler_split";
|
||||
RadBuildCtx bc{};
|
||||
bc.world_size = world;
|
||||
bc.max_seqs = 2;
|
||||
bc.max_tok = 2;
|
||||
bc.max_ctx = 64;
|
||||
bc.scope = "";
|
||||
Builder b(reg, meta, bc);
|
||||
Sampler s;
|
||||
SamplerConfig cfg;
|
||||
cfg.n_vocab = 2048 * (int64_t)world;
|
||||
cfg.n_vocab_local = 2048;
|
||||
cfg.max_seqs = 2;
|
||||
cfg.world_size = world;
|
||||
cfg.rank = world - 1;
|
||||
cfg.vocab_off = 2048 * (int64_t)(world - 1);
|
||||
cfg.max_hist = 16;
|
||||
CHECK_OK(s.declare(&b, cfg));
|
||||
|
||||
const int64_t width = world == 8 ? 512 : kSampleCandidates;
|
||||
SamplingParams sp = greedy_params();
|
||||
std::string why;
|
||||
sp.top_k = (int)width;
|
||||
CHECK_OK(s.check_request(sp, &why));
|
||||
sp.top_k = (int)width + 1;
|
||||
CHECK_EQ(s.check_request(sp, &why), RAD_E_INVAL);
|
||||
CHECK(why.find("candidate width of " + std::to_string(width)) != std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
/* Triggers are resolved at admission, with special tokens recognised: a one-token word becomes an
|
||||
* id, a longer word is scanned for as bytes, a token trigger that is not one token is a bad
|
||||
* request, and a regular expression is refused by name (it would be matched over the reply once
|
||||
|
||||
@@ -824,6 +824,7 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
|
||||
/* The checkpoint shortfall: the 48 cached tokens above the snapshot are computed again. */
|
||||
CHECK_EQ(m.hit_cut_tokens, 48);
|
||||
CHECK_EQ(m.hit_cut_no_snapshot, 0);
|
||||
CHECK_EQ(m.hit_cut_resumed_below, 0); /* within an interval: a turn's ordinary tail */
|
||||
|
||||
/* The snapshot this step takes is not offered to anyone until the step has run: the
|
||||
* reservation happens when the chunk is planned, the state exists only afterwards. */
|
||||
@@ -833,6 +834,26 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
|
||||
CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */
|
||||
}
|
||||
|
||||
/* A hit that resumes more than an interval below the attention blocks is counted with its own
|
||||
* reason: the snapshots in between are gone, or a restore brought back only part of the chain,
|
||||
* and hit_cut_tokens alone would not say how many admissions it was. */
|
||||
TEST(a_hit_resuming_far_below_its_blocks_is_counted_as_cut) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
f.pc.seed(784); /* 49 blocks */
|
||||
f.pc.lin = 256; /* 528 tokens below, past the 256-token interval */
|
||||
f.pc.src = 3;
|
||||
|
||||
uint64_t a = f.submit(1000, 8);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
CHECK_EQ(f.sch.find(a)->n_computed, 256);
|
||||
const SchedMetrics m = f.sch.metrics();
|
||||
CHECK_EQ(m.hit_cut_resumed_below, 1);
|
||||
CHECK_EQ(m.hit_cut_no_snapshot, 0);
|
||||
CHECK_EQ(m.hit_cut_tokens, 528);
|
||||
}
|
||||
|
||||
/* A hit that skipped tokens with no snapshot to resume from would corrupt the linear state, so it
|
||||
* is refused outright rather than served with a zeroed state. */
|
||||
TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) {
|
||||
@@ -1746,6 +1767,23 @@ static Interleaved interleave_run(int64_t n, bool decoder, int steps) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Between a commit and the next step (where an encoder pass is prepared) the committed step's
|
||||
* plan names a request the scheduler may already have released: a client cancelled it and the
|
||||
* server reaped it. prefill_continues() reads only an open step's plan (#127). */
|
||||
TEST(prefill_continues_reads_no_committed_plan) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
f.sch.set_stage_rows(64);
|
||||
const uint64_t p = f.submit(2000, 4);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
CHECK(f.sch.prefill_continues());
|
||||
f.commit_plain(12);
|
||||
CHECK_OK(f.sch.cancel(p));
|
||||
CHECK_OK(f.sch.reap(p));
|
||||
CHECK(!f.sch.prefill_continues());
|
||||
}
|
||||
|
||||
TEST(interleave_off_puts_a_chunk_in_every_step) {
|
||||
const Interleaved r = interleave_run(0, /*decoder=*/true, 8);
|
||||
CHECK_EQ(r.shape, std::string("CCCCCCCC"));
|
||||
@@ -2546,6 +2584,309 @@ TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) {
|
||||
}
|
||||
|
||||
/* ================================================================== the step path */
|
||||
/* The single-sequence decode floor the dashboard reads instead of a typed ruler. Timing is real
|
||||
* wall clock, so the assertions are the ones that hold whatever the machine measured: a step of a
|
||||
* shape that must not sample leaves the floor at zero (a min only ever goes down, so a wrongly
|
||||
* sampled step could never be told apart later -- it has to be caught while the floor is still
|
||||
* unset), and a single-sequence step sets it. */
|
||||
TEST(the_decode_floor_estimator_does_not_latch_a_degenerate_bracket) {
|
||||
/* The estimator is tested on a SYNTHETIC stream because the defect is a property of the
|
||||
* estimator, not of the scheduler's ability to produce a degenerate bracket: the fixture runs
|
||||
* steps in microseconds and cannot manufacture a 1.34 ms bracket behind a 15 ms one. What the
|
||||
* live lane showed -- floor 1.34 ms against a 15.70 ms mean -- is reproduced here directly. */
|
||||
using Est = rad::DecodeFloor;
|
||||
|
||||
/* First, the OLD construction, shown to fail. A min over raw brackets latches the single
|
||||
* degenerate sample and never recovers, no matter how many honest steps follow. This is the
|
||||
* defect, encoded as a test so the fix is measured against it rather than asserted. */
|
||||
{
|
||||
int64_t best = 0;
|
||||
const int64_t real = 15'000'000, degenerate = 1'340'000;
|
||||
auto old_min = [&](int64_t ns) { if (best == 0 || ns < best) best = ns; };
|
||||
old_min(degenerate); /* one degenerate, early */
|
||||
for (int i = 0; i < 500; ++i) old_min(real);
|
||||
CHECK_EQ(best, degenerate); /* latched -- this is the bug */
|
||||
}
|
||||
|
||||
/* The NEW construction: a min over WINDOW MEANS. The same single degenerate is diluted by
|
||||
* the honest steps sharing its window, so the floor tracks the real floor instead. */
|
||||
{
|
||||
Est est;
|
||||
const int64_t real = 15'000'000, degenerate = 1'340'000;
|
||||
est.update(degenerate); /* same degenerate, same position */
|
||||
for (int i = 0; i < 500; ++i) est.update(real);
|
||||
const int64_t floor = est.best();
|
||||
CHECK(floor > 0);
|
||||
CHECK(floor > degenerate); /* did NOT latch the degenerate */
|
||||
/* Within 25% of the real floor: the window mean is a faithful estimator. */
|
||||
CHECK(floor >= real * 3 / 4 && floor <= real);
|
||||
}
|
||||
|
||||
/* Robust to a HIGH rate of degenerates: the live lane's checkpoint interval (256 tokens)
|
||||
* implies they recur. One in four here. The assertion is that the floor tracks the REAL step
|
||||
* time, not merely that it beats the degenerate -- with the rejection gate in place the latter
|
||||
* would be trivially true and prove nothing. */
|
||||
{
|
||||
Est est;
|
||||
const int64_t real = 15'000'000, degenerate = 1'340'000;
|
||||
for (int i = 0; i < 400; ++i) est.update((i % 4 == 0) ? degenerate : real);
|
||||
const int64_t floor = est.best();
|
||||
CHECK(floor >= real * 90 / 100); /* tracks the real step, not the poison */
|
||||
CHECK(floor <= real);
|
||||
}
|
||||
|
||||
/* A steady stream with no degenerates: the floor equals the true floor. */
|
||||
{
|
||||
Est est;
|
||||
const int64_t real = 14'500'000;
|
||||
for (int i = 0; i < 200; ++i) est.update(real);
|
||||
CHECK_EQ(est.best(), real);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_rejects_degenerate_brackets_so_the_floor_is_the_true_floor) {
|
||||
/* Window-averaging dilutes a LONE degenerate but not a RECURRENT one. At the live lane's
|
||||
* observed ~1.4% degenerate rate (a decode step issued ahead behind a long host commit --
|
||||
* prefill, or a KV checkpoint every 256 tokens), a min over hundreds of windows reliably
|
||||
* catches a window holding two or three degenerates, and the floor lands ~10% below the true
|
||||
* floor. That residual is phantom drift: a healthy engine reads "restart pays back" against a
|
||||
* floor it can no longer reach because the floor was never reachable -- it was an artifact.
|
||||
* So a candidate far below the running mean of accepted steps is rejected outright: the
|
||||
* degenerates sit at ~9% of the mean, real single-sequence steps at ~96%, so the two
|
||||
* populations are ~10x apart and any threshold between them separates them. 0.5 is the
|
||||
* midpoint of that gap, not a value tuned to a single distribution. */
|
||||
using Est = rad::DecodeFloor;
|
||||
const int64_t true_floor = 14'400'000, typical = 15'000'000, degen = 1'340'000;
|
||||
|
||||
/* A realistic stream: ~1.4% degenerates, the rest jittered around the typical step, with the
|
||||
* true floor occasionally reached. The floor must land near the TRUE floor, not near the
|
||||
* degenerate-contaminated window mean. */
|
||||
Est est;
|
||||
uint32_t rng = 12345;
|
||||
for (int i = 0; i < 400 * Est::kWindow; ++i) {
|
||||
rng = rng * 1664525u + 1013904223u;
|
||||
const bool d = ((rng >> 16) % 1000u) < 14u; /* ~1.4% */
|
||||
int64_t ns;
|
||||
if (d) ns = degen;
|
||||
else {
|
||||
rng = rng * 1664525u + 1013904223u;
|
||||
ns = true_floor + (int64_t)((rng >> 8) % (typical - true_floor + 1)); /* floor..typical */
|
||||
}
|
||||
est.update(ns);
|
||||
}
|
||||
const int64_t floor = est.best();
|
||||
/* Within 5% of the true floor. The un-rejected estimator lands ~10% low here, so this fails
|
||||
* without the rejection gate. */
|
||||
CHECK(floor >= true_floor * 95 / 100);
|
||||
CHECK(floor <= true_floor * 115 / 100);
|
||||
|
||||
/* The bootstrap hole: the gate needs a window of accepted samples before it can judge one, so
|
||||
* the first window is un-gated. A degenerate-heavy FIRST window must therefore be recorded by
|
||||
* neither side, or the floor latches an unreachable value forever. */
|
||||
{
|
||||
Est est;
|
||||
for (int i = 0; i < Est::kWindow; ++i) est.update(degen); /* whole first window poisoned */
|
||||
CHECK_EQ(est.best(), (int64_t)0);
|
||||
CHECK_EQ(est.recent(), (int64_t)0);
|
||||
for (int i = 0; i < 40 * Est::kWindow; ++i) est.update(typical);
|
||||
CHECK(est.best() >= typical * 95 / 100); /* floor came from a gated window, not bootstrap */
|
||||
}
|
||||
|
||||
/* And the rejection must NOT eat real steps: a stream of only real steps (no degenerates)
|
||||
* still records a floor equal to the true floor. */
|
||||
Est clean;
|
||||
for (int i = 0; i < 100 * Est::kWindow; ++i) clean.update(true_floor);
|
||||
CHECK_EQ(clean.best(), true_floor);
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_reports_a_recent_window_for_like_for_like_drift) {
|
||||
/* The advisory compares "how fast is it now" against "how fast has it ever been". If those two
|
||||
* numbers come from different instruments -- the engine's floor versus the browser's per-poll
|
||||
* mean -- they disagree by pure order statistics: a min over hundreds of windows sits below a
|
||||
* min over the last sixty samples even on a perfectly flat engine. Measured live 2026-10-18:
|
||||
* a 7.7% phantom gap on a lane that had not changed. So the engine reports BOTH sides of the
|
||||
* comparison, from the same stream and the same window size. */
|
||||
using Est = rad::DecodeFloor;
|
||||
const int64_t base = 15'000'000;
|
||||
|
||||
/* A steady engine with realistic run-to-run jitter: the recent window and the floor are both
|
||||
* window means of the same population, so they must agree closely. */
|
||||
{
|
||||
Est est;
|
||||
for (int i = 0; i < 400 * Est::kWindow; ++i) {
|
||||
const int64_t jitter = ((i % 7) - 3) * 200'000; /* +/- 0.6 ms, deterministic */
|
||||
est.update(base + jitter);
|
||||
}
|
||||
const int64_t floor = est.best(), recent = est.recent();
|
||||
CHECK(floor > 0);
|
||||
CHECK(recent > 0);
|
||||
/* The phantom gap must be small: this is the number the deadband is sized against. */
|
||||
const int64_t gap_pct = 100 * (recent - floor) / floor;
|
||||
CHECK(gap_pct < 3);
|
||||
}
|
||||
|
||||
/* A degraded engine: the recent window rises, the floor remembers the old best. The verdict
|
||||
* must separate -- that is the whole point of the advisory. */
|
||||
{
|
||||
Est est;
|
||||
for (int i = 0; i < 200 * Est::kWindow; ++i) est.update(base);
|
||||
const int64_t floor = est.best();
|
||||
for (int i = 0; i < 20 * Est::kWindow; ++i) est.update(base * 6 / 5); /* 20% slower */
|
||||
const int64_t recent = est.recent();
|
||||
CHECK(recent > floor * 115 / 100);
|
||||
/* The floor does not chase the degradation: a restart is exactly what would restore it. */
|
||||
CHECK_EQ(est.best(), floor);
|
||||
}
|
||||
|
||||
/* Before any window completes there is no recent reading -- the page must not divide by it. */
|
||||
{
|
||||
Est est;
|
||||
for (int i = 0; i < Est::kWindow - 1; ++i) est.update(base);
|
||||
CHECK_EQ(est.recent(), (int64_t)0);
|
||||
est.update(base); /* completes window 1: the un-gated warmup */
|
||||
CHECK_EQ(est.recent(), (int64_t)0); /* warmup is recorded by neither side */
|
||||
for (int i = 0; i < Est::kWindow; ++i) est.update(base);
|
||||
CHECK(est.recent() > 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_records_only_single_sequence_decode_steps) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
/* A prefill step samples nothing. Budget 320 tokens: this test walks 1 prefill + one window,
|
||||
* at most six windows until the floor is set and one more, 257 steps. */
|
||||
uint64_t a = f.submit(160, 320, /*priority=*/0, /*ignore_eos=*/true);
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
f.sch.step_finished();
|
||||
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0);
|
||||
|
||||
/* The floor is a min over WINDOW MEANS of single-sequence decode steps, so it stays 0 until a
|
||||
* full window (DecodeFloor::kWindow) has run -- unlike the old raw min, which latched the very
|
||||
* first bracket. One short of a window and the floor is still unset. */
|
||||
for (int i = 1; i < rad::DecodeFloor::kWindow; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_EQ(f.sch.plan().n_seq_decode, 1);
|
||||
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE);
|
||||
f.commit_plain(12);
|
||||
f.sch.step_finished();
|
||||
}
|
||||
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0);
|
||||
|
||||
/* The step that completes the FIRST window leaves the floor unset: window 1 is the un-gated
|
||||
* warmup (the rejection gate needs a window of accepted samples before it can judge one), so
|
||||
* it is recorded by neither side. */
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain(13);
|
||||
f.sch.step_finished();
|
||||
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0);
|
||||
|
||||
/* The first gated window sets the floor: positive, and no larger than the cumulative decode
|
||||
* time it was drawn from. The fixture's steps take microseconds and vary widely, so the gate
|
||||
* may reject some and the window take more than kWindow steps to fill. */
|
||||
for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best;
|
||||
++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain(14);
|
||||
f.sch.step_finished();
|
||||
}
|
||||
const int64_t floor1 = f.sch.metrics().step_ns_decode_best;
|
||||
CHECK(floor1 > 0);
|
||||
CHECK(floor1 <= f.sch.metrics().step_ns_decode);
|
||||
|
||||
/* A further full window can only lower the floor or leave it: it is a min over windows. */
|
||||
for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain(15);
|
||||
f.sch.step_finished();
|
||||
}
|
||||
const int64_t floor2 = f.sch.metrics().step_ns_decode_best;
|
||||
CHECK(floor2 > 0);
|
||||
CHECK(floor2 <= floor1);
|
||||
(void)a;
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_ignores_a_decode_step_issued_behind_a_prefill) {
|
||||
/* The decode step issued behind the prefill's host-side staging is a real single-sequence
|
||||
* decode step: it is eligible, and the window mean dilutes its short bracket. Decode steps
|
||||
* that begin with it produce a floor. The fixture's steps take microseconds and vary widely,
|
||||
* so the gate may reject some and a window take more than kWindow steps to fill. */
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
uint64_t a = f.submit(160, 256, /*priority=*/0, /*ignore_eos=*/true);
|
||||
REQUIRE(f.sch.step() != nullptr); /* prefill */
|
||||
f.commit_plain(21);
|
||||
f.sch.step_finished();
|
||||
|
||||
/* Window 1 (holding the prefill-following step) is the un-gated warmup, so the floor only
|
||||
* appears once a gated window completes. */
|
||||
for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best;
|
||||
++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE);
|
||||
CHECK_EQ(f.sch.plan().n_seq_decode, 1);
|
||||
CHECK(f.sch.plan().n_tok_decode >= 1); /* a token DID advance; token count is not the guard */
|
||||
f.commit_plain(22);
|
||||
f.sch.step_finished();
|
||||
}
|
||||
/* The window filled, counting the prefill-following step: the floor is set. */
|
||||
CHECK(f.sch.metrics().step_ns_decode_best > 0);
|
||||
(void)a;
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_ignores_batched_and_mixed_steps) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
/* Two requests prefilled, then decoding TOGETHER: every decode step here carries two rows, so
|
||||
* the floor must still be unset at the end -- a batched step is a different measurement and
|
||||
* keying the floor to it would report the batch arriving as drift. */
|
||||
uint64_t a = f.submit(160, 64);
|
||||
uint64_t b = f.submit(160, 64);
|
||||
REQUIRE(f.sch.step() != nullptr); /* both prompts */
|
||||
f.commit_plain(11);
|
||||
f.sch.step_finished();
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
CHECK_EQ(f.sch.plan().n_seq_decode, 2);
|
||||
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE);
|
||||
f.commit_plain(12);
|
||||
f.sch.step_finished();
|
||||
}
|
||||
CHECK(f.sch.metrics().steps_decode > 0); /* decode steps really ran ... */
|
||||
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); /* ... and none of them sampled */
|
||||
(void)a; (void)b;
|
||||
}
|
||||
|
||||
TEST(the_decode_floor_ignores_a_lone_decode_row_inside_a_mixed_step) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
|
||||
/* The subtle case: a mixed step carrying exactly ONE decode row alongside a prefill chunk.
|
||||
* n_seq_decode is 1, so a check on the row count alone would sample it -- but that row shared
|
||||
* the step with a chunk an order of magnitude dearer, and its time is not the mechanical floor.
|
||||
* The phase gate is what excludes it. */
|
||||
uint64_t b = f.submit(1000, 64, /*priority=*/1); /* several chunks */
|
||||
uint64_t a = f.submit(160, 64, /*priority=*/0); /* one chunk, then decodes */
|
||||
REQUIRE(f.sch.step() != nullptr); /* both prompts */
|
||||
f.commit_plain(11);
|
||||
f.sch.step_finished();
|
||||
|
||||
REQUIRE(f.sch.step() != nullptr); /* a decodes, b still chunking */
|
||||
CHECK_EQ(f.sch.plan().n_seq_decode, 1);
|
||||
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
|
||||
f.commit_plain(12);
|
||||
f.sch.step_finished();
|
||||
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0);
|
||||
(void)a; (void)b;
|
||||
}
|
||||
|
||||
TEST(the_step_path_does_not_allocate) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/4096, /*states=*/64);
|
||||
@@ -3617,6 +3958,179 @@ TEST(a_step_issued_ahead_equals_the_step_built_after_the_commit) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== a block drafter on the card */
|
||||
namespace {
|
||||
/* Every pass of a block drafter's run: each step's trunk batch, then its context and query
|
||||
* passes, as the card holds them once its advances have run. */
|
||||
struct BlockRun {
|
||||
std::vector<BatchRows> trunk, context, query;
|
||||
std::vector<std::vector<int32_t>> out;
|
||||
int ahead = 0;
|
||||
int card_host_disagree = 0;
|
||||
};
|
||||
constexpr int kBlk = 8, kBlkDepth = 7;
|
||||
constexpr int32_t kBlkMask = 99;
|
||||
|
||||
/* The host's driver: both passes built after the commit, from the committed sequence. */
|
||||
BlockRun block_reference(int steps) {
|
||||
Fixture f;
|
||||
std::vector<uint64_t> ids;
|
||||
ahead_setup(f, kBlkDepth, ids);
|
||||
BlockRun run;
|
||||
const RadBatch* b = f.sch.step();
|
||||
if (!b) return run;
|
||||
run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv));
|
||||
Scheduler::BlockRow rows[4];
|
||||
for (int t = 0; t < steps; ++t) {
|
||||
CHECK_OK(ahead_commit(f, t));
|
||||
CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4), 3);
|
||||
const RadBatch* cb = f.sch.block_context(t + 1);
|
||||
if (!cb) { CHECK(cb != nullptr); return run; }
|
||||
run.context.push_back(read_rows(cb, f.sch.plan(), f.kv));
|
||||
const RadBatch* qb = f.sch.block_query(t + 1);
|
||||
if (!qb) { CHECK(qb != nullptr); return run; }
|
||||
/* The query plan is the scheduler's own; its rows are the drafting sequences in order. */
|
||||
StepPlan qp;
|
||||
for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); }
|
||||
run.query.push_back(read_rows(qb, qp, f.kv));
|
||||
f.sch.block_end();
|
||||
ahead_publish(f, ids, kBlkDepth, t + 1);
|
||||
b = f.sch.step();
|
||||
if (!b) break;
|
||||
run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv));
|
||||
}
|
||||
for (uint64_t id : ids) run.out.push_back(f.sch.find(id)->output);
|
||||
return run;
|
||||
}
|
||||
|
||||
/* The card's driver (Engine::issue_block_drafter): the step's acceptance into the StepSlots, both
|
||||
* passes built before the commit with the query rows placed by ADV_BLOCK, the proposals into the
|
||||
* slots (ADV_BTAKE), expect_draft and step_next with ADV_TRUNK, then the commit, block_end, the
|
||||
* drafts published and promote_next. */
|
||||
BlockRun block_pipelined(int steps) {
|
||||
Fixture f;
|
||||
std::vector<uint64_t> ids;
|
||||
ahead_setup(f, kBlkDepth, ids);
|
||||
BlockRun run;
|
||||
std::vector<StepSlot> slots((size_t)f.cfg.max_seqs);
|
||||
const RadBatch* b = f.sch.step();
|
||||
if (!b) return run;
|
||||
run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv));
|
||||
Scheduler::BlockRow rows[4];
|
||||
for (int t = 0; t < steps; ++t) {
|
||||
const StepPlan& p = f.sch.plan();
|
||||
std::vector<int32_t> y((size_t)b->n_out + 1, -1);
|
||||
for (const StepEntry& e : p.e) {
|
||||
if (e.dev_out < 0) continue;
|
||||
const int32_t a = ahead_acc(e.seq, t, e.n_spec);
|
||||
for (int j = 0; j <= e.n_spec; ++j)
|
||||
y[(size_t)(e.dev_out + j)] = j < a ? ahead_draft(e.seq, t, j) : ahead_tok(e.seq, t);
|
||||
}
|
||||
AdvanceArgs acc = f.sch.advance_args(0);
|
||||
acc.mode = ADV_ACCEPT;
|
||||
acc.st = slots.data();
|
||||
acc.src = y.data();
|
||||
for (int i = 0; i < acc.n_seq; ++i) adv_row(acc, i);
|
||||
for (const StepEntry& e : p.e) {
|
||||
const StepSlot& S = slots[(size_t)e.card];
|
||||
if (S.acc != ahead_acc(e.seq, t, e.n_spec) || S.tok[0] != ahead_tok(e.seq, t))
|
||||
++run.card_host_disagree;
|
||||
}
|
||||
|
||||
CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4, /*on_card=*/true), 3);
|
||||
const RadBatch* cb = f.sch.block_context(t + 1);
|
||||
if (!cb) { CHECK(cb != nullptr); return run; }
|
||||
run.context.push_back(read_rows(cb, f.sch.plan(), f.kv));
|
||||
const RadBatch* qb = f.sch.block_query(t + 1);
|
||||
if (!qb) { CHECK(qb != nullptr); return run; }
|
||||
AdvanceArgs q = f.sch.advance_args(0);
|
||||
q.mode = ADV_BLOCK;
|
||||
q.st = slots.data();
|
||||
for (int i = 0; i < q.n_seq; ++i) adv_row(q, i);
|
||||
StepPlan qp;
|
||||
for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); }
|
||||
run.query.push_back(read_rows(qb, qp, f.kv));
|
||||
/* The block's proposals for step t + 1, taken behind the anchor. */
|
||||
std::vector<int32_t> prop((size_t)3 * kBlkDepth);
|
||||
for (int i = 0; i < 3; ++i)
|
||||
for (int j = 0; j < kBlkDepth; ++j)
|
||||
prop[(size_t)(i * kBlkDepth + j)] = ahead_draft(rows[i].seq, t + 1, j);
|
||||
AdvanceArgs tk = f.sch.advance_args(0);
|
||||
tk.mode = ADV_BTAKE;
|
||||
tk.round = kBlkDepth;
|
||||
tk.src = prop.data();
|
||||
tk.src_pitch = kBlkDepth;
|
||||
tk.st = slots.data();
|
||||
for (int i = 0; i < tk.n_seq; ++i) adv_row(tk, i);
|
||||
for (int i = 0; i < 3; ++i) f.sch.expect_draft(rows[i].seq, kBlkDepth);
|
||||
|
||||
const RadBatch* nb = f.sch.step_next();
|
||||
if (nb) {
|
||||
AdvanceArgs tr = f.sch.advance_args(0);
|
||||
tr.mode = ADV_TRUNK;
|
||||
tr.st = slots.data();
|
||||
for (int i = 0; i < tr.n_seq; ++i) adv_row(tr, i);
|
||||
}
|
||||
CHECK_OK(ahead_commit(f, t));
|
||||
f.sch.block_end();
|
||||
ahead_publish(f, ids, kBlkDepth, t + 1);
|
||||
if (nb) {
|
||||
f.sch.promote_next();
|
||||
b = nb;
|
||||
++run.ahead;
|
||||
} else {
|
||||
b = f.sch.step();
|
||||
if (!b) break;
|
||||
}
|
||||
run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv));
|
||||
}
|
||||
for (uint64_t id : ids) run.out.push_back(f.sch.find(id)->output);
|
||||
return run;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* A block drafter on the card runs the passes the host's driver runs after the commit: the same
|
||||
* trunk steps, and context and query passes with the same positions, lengths and slots once the
|
||||
* card's advances have filled in what the host only bounded, and the same query tokens. Its query
|
||||
* block is staged before the step's acceptance is known, at the furthest anchor; a wrong position
|
||||
* drafts from the wrong place (acceptance collapses, no error) and a wrong slot writes the
|
||||
* drafter's K/V into another block. Every step after the first runs issued ahead.
|
||||
*
|
||||
* The context pass's token ids are not compared: that pass reads hidden states and no ids
|
||||
* (Scheduler::block_context), and staged before the commit, its accepted positions are not in the
|
||||
* sequence yet. */
|
||||
TEST(a_block_drafter_on_the_card_runs_the_passes_the_hosts_driver_runs) {
|
||||
const int T = 24;
|
||||
const BlockRun a = block_reference(T);
|
||||
const BlockRun b = block_pipelined(T);
|
||||
CHECK_EQ(b.ahead, T);
|
||||
CHECK_EQ(b.card_host_disagree, 0);
|
||||
REQUIRE_EQ(a.trunk.size(), (size_t)T + 1);
|
||||
REQUIRE_EQ(a.trunk.size(), b.trunk.size());
|
||||
REQUIRE_EQ(a.context.size(), b.context.size());
|
||||
REQUIRE_EQ(a.query.size(), b.query.size());
|
||||
for (size_t t = 0; t < a.trunk.size(); ++t) {
|
||||
CHECK(a.trunk[t] == b.trunk[t]);
|
||||
CHECK_EQ(b.trunk[t].bad_slots, 0);
|
||||
}
|
||||
for (size_t t = 0; t < a.context.size(); ++t) {
|
||||
BatchRows ca = a.context[t], cb = b.context[t];
|
||||
ca.tok.clear();
|
||||
cb.tok.clear();
|
||||
const bool same_c = ca == cb, same_q = a.query[t] == b.query[t];
|
||||
CHECK(same_c);
|
||||
CHECK(same_q);
|
||||
if (!same_c || !same_q)
|
||||
std::fprintf(stderr, " step %zu: context %s, query %s\n", t,
|
||||
same_c ? "same" : "differs", same_q ? "same" : "differs");
|
||||
CHECK_EQ(a.context[t].bad_slots, 0);
|
||||
CHECK_EQ(b.context[t].bad_slots, 0);
|
||||
CHECK_EQ(a.query[t].bad_slots, 0);
|
||||
CHECK_EQ(b.query[t].bad_slots, 0);
|
||||
}
|
||||
CHECK(a.out == b.out);
|
||||
}
|
||||
|
||||
/* ================================================================== the token budget per token */
|
||||
/* A verify step emits up to 1 + n_spec tokens at once. The budget (max_tokens, and the context)
|
||||
* is applied token by token before each reaches the sink: trimming `output` afterwards would leave
|
||||
|
||||
@@ -144,6 +144,8 @@ struct FakeChatTemplate : IChatTemplate {
|
||||
if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]";
|
||||
if (!opt.enable_thinking) s += "[nothink]";
|
||||
for (const auto& kv : opt.template_kwargs) s += "[" + kv.first + "=" + kv.second + "]";
|
||||
if (!default_effort.empty() && !opt.template_kwargs.count("reasoning_effort"))
|
||||
s += "[reasoning_effort=" + default_effort + "]";
|
||||
size_t n_msg = 0;
|
||||
int tool_msgs = 0;
|
||||
for (const auto& m : messages) {
|
||||
@@ -203,6 +205,8 @@ struct FakeChatTemplate : IChatTemplate {
|
||||
std::string refusal;
|
||||
std::string refuse_kwarg;
|
||||
std::vector<std::string> efforts; /* JSON text, as the template context carries them */
|
||||
/* The effort a render naming none is written as, as Qwen3.8's template writes xhigh. */
|
||||
std::string default_effort;
|
||||
/* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */
|
||||
std::string think_open, think_close;
|
||||
bool think_starts_open = false;
|
||||
@@ -632,6 +636,14 @@ struct FakeImageGen : IImageGen {
|
||||
}
|
||||
int64_t queued() const override { return 0; }
|
||||
int64_t running() const override { return 0; }
|
||||
/* The second tokenizer: one id a byte, then 1 (an end token). */
|
||||
int encode_aux(const std::string& text, std::vector<int32_t>* out) const override {
|
||||
if (!inf.aux_tokens) return RAD_E_UNSUPPORTED;
|
||||
out->clear();
|
||||
for (unsigned char c : text) out->push_back(100 + c);
|
||||
out->push_back(1);
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/* An audio generator that finishes every request on submit: `windows` windows of `per_window`
|
||||
|
||||
@@ -946,6 +946,14 @@ TEST(an_effort_the_template_refuses_is_answered_with_the_set_it_takes) {
|
||||
CHECK_EQ(set[0], std::string("low"));
|
||||
CHECK_EQ(set[1], std::string("medium"));
|
||||
CHECK_EQ(set[2], std::string("xhigh"));
|
||||
CHECK(f.srv->template_default_effort().empty()); /* no level renders as no level */
|
||||
/* A template that writes one level when a request names none, as Qwen3.8's writes xhigh
|
||||
* (#113): the probe names it. */
|
||||
f.tmpl.default_effort = "\"xhigh\"";
|
||||
f.srv->probe_reasoning_efforts();
|
||||
CHECK_EQ(f.srv->template_default_effort(), std::string("xhigh"));
|
||||
f.tmpl.default_effort.clear();
|
||||
f.srv->probe_reasoning_efforts();
|
||||
|
||||
OaiLimits lim = f.limits();
|
||||
lim.reasoning_efforts = set;
|
||||
@@ -2276,6 +2284,12 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
|
||||
CHECK_NEAR(find_one("radiance:draft_acceptance_ratio{"), 0.61, 1e-9);
|
||||
CHECK_NEAR(find_one("vllm:generation_tokens_total{"), 5.0, 1e-9);
|
||||
|
||||
/* An unmeasured decode floor is ABSENT, not 0: a floor of 0 seconds per token is an
|
||||
* infinitely fast one, and a scrape would plot it as a record. This fixture never completes a
|
||||
* window of 32 single-stream steps, so neither series may appear. */
|
||||
CHECK(r.body.find("radiance:decode_step_seconds_best") == std::string::npos);
|
||||
CHECK(r.body.find("radiance:decode_step_seconds_recent") == std::string::npos);
|
||||
|
||||
/* Every sample carries the model_name label vLLM's dashboards group by. */
|
||||
for (auto& kv : d.samples)
|
||||
CHECK(kv.first.find("model_name=\"test-model\"") != std::string::npos);
|
||||
@@ -2298,6 +2312,48 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
|
||||
CHECK(r.body.find("le=\"2560\"") != std::string::npos);
|
||||
}
|
||||
|
||||
/* The decode floor reaches /metrics, in seconds. The scheduler keeps nanoseconds and the page
|
||||
* divides for display; the wire uses the base unit Prometheus expects, the same choice
|
||||
* radiance:engine_step_seconds_* already makes. */
|
||||
TEST(metrics_carries_the_decode_floor_in_seconds) {
|
||||
Fixture f;
|
||||
f.sched.m.step_ns_decode_best = 14708911; /* 14.71 ms/token: a measured floor */
|
||||
f.sched.m.step_ns_decode_recent = 16428860; /* 16.43 ms/token: the recent window */
|
||||
|
||||
HttpResponse r = f.get("/metrics");
|
||||
CHECK_EQ(r.status, 200);
|
||||
PromDoc d = parse_prom(r.body);
|
||||
CHECK_EQ((int)d.errors.size(), 0);
|
||||
CHECK_EQ(d.type["radiance:decode_step_seconds_best"], std::string("gauge"));
|
||||
CHECK_EQ(d.type["radiance:decode_step_seconds_recent"], std::string("gauge"));
|
||||
|
||||
auto find_one = [&](const std::string& prefix) -> double {
|
||||
for (auto& kv : d.samples)
|
||||
if (kv.first.rfind(prefix, 0) == 0) return kv.second;
|
||||
return -12345.0;
|
||||
};
|
||||
CHECK_NEAR(find_one("radiance:decode_step_seconds_best{"), 0.014708911, 1e-12);
|
||||
CHECK_NEAR(find_one("radiance:decode_step_seconds_recent{"), 0.016428860, 1e-12);
|
||||
|
||||
/* A floor is a duration, so it must survive the number formatter: 0.0147 s rendered as an
|
||||
* integer would read as infinitely fast. Checked on a prefix rather than the whole literal
|
||||
* because num() prints 17 significant digits and the last ones are the double's own noise. */
|
||||
CHECK(r.body.find("radiance:decode_step_seconds_best{model_name=\"test-model\",engine=\"0\"} 0.01470891")
|
||||
!= std::string::npos);
|
||||
}
|
||||
|
||||
/* Half a window: a floor exists but the recent window has not completed since. Each series is
|
||||
* gated on its own value, so one may appear while the other is absent. */
|
||||
TEST(metrics_omits_only_the_floor_half_that_is_unmeasured) {
|
||||
Fixture f;
|
||||
f.sched.m.step_ns_decode_best = 15000000;
|
||||
f.sched.m.step_ns_decode_recent = 0;
|
||||
|
||||
HttpResponse r = f.get("/metrics");
|
||||
CHECK(r.body.find("radiance:decode_step_seconds_best{") != std::string::npos);
|
||||
CHECK(r.body.find("radiance:decode_step_seconds_recent") == std::string::npos);
|
||||
}
|
||||
|
||||
/* The scheduler's totals are cumulative, and a scrape turns them into counter increments by adding
|
||||
* the difference from the counter's current value. Concurrent scrapes must still count each total
|
||||
* once: however many run, the counter ends at the total. */
|
||||
@@ -2335,6 +2391,7 @@ TEST(snapshot_evictions_and_cut_hits_are_counted_by_reason) {
|
||||
server::SchedMetrics s;
|
||||
s.prefix_ckpt_retired = 5; s.prefix_ckpt_lru = 3; s.prefix_ckpt_refused = 1;
|
||||
s.hit_cut_no_snapshot = 2; s.hit_cut_window = 0; s.hit_cut_adopt = 4;
|
||||
s.hit_cut_resumed_below = 6; s.prefix_restore_cuts = 7;
|
||||
s.hit_cut_tokens = 76092;
|
||||
m.sample(s);
|
||||
PromDoc d = parse_prom(m.render());
|
||||
@@ -2355,6 +2412,8 @@ TEST(snapshot_evictions_and_cut_hits_are_counted_by_reason) {
|
||||
CHECK_NEAR(value(C + ",reason=\"no_snapshot\"}"), 2.0, 1e-9);
|
||||
CHECK_NEAR(value(C + ",reason=\"windowed_group\"}"), 0.0, 1e-9);
|
||||
CHECK_NEAR(value(C + ",reason=\"adopt_failed\"}"), 4.0, 1e-9);
|
||||
CHECK_NEAR(value(C + ",reason=\"resumed_below\"}"), 6.0, 1e-9);
|
||||
CHECK_NEAR(value("radiance:prefix_restore_cuts_total" + L + "}"), 7.0, 1e-9);
|
||||
CHECK_NEAR(value("radiance:prefix_hit_cut_tokens_total" + L + "}"), 76092.0, 1e-9);
|
||||
}
|
||||
|
||||
@@ -4016,6 +4075,56 @@ TEST(a_responses_request_becomes_the_chat_request_it_means) {
|
||||
&echo, &e) < 0);
|
||||
}
|
||||
|
||||
/* A namespace groups function tools (Codex sends every MCP server's tools that way). They reach
|
||||
* the model flattened to <namespace>__<name>, the reply's function_call item reports the two apart,
|
||||
* streamed and not, and the next turn's call and tool_choice come back joined (#119). */
|
||||
TEST(a_namespaces_tools_are_offered_flat_and_answered_apart) {
|
||||
OaiLimits lim;
|
||||
std::string chat, echo;
|
||||
ApiError e;
|
||||
std::map<std::string, std::pair<std::string, std::string>> ns;
|
||||
CHECK_OK(responses_to_chat(R"({
|
||||
"tools":[{"type":"function","name":"plain","parameters":{"type":"object"}},
|
||||
{"type":"namespace","name":"crm","description":"d","tools":[
|
||||
{"type":"function","name":"find","parameters":{"type":"object"}},
|
||||
{"type":"custom","name":"raw"}]}],
|
||||
"tool_choice":{"type":"function","namespace":"crm","name":"find"},
|
||||
"input":[{"role":"user","content":"x"},
|
||||
{"type":"function_call","call_id":"c1","namespace":"crm","name":"find","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"c1","output":"y"}]})",
|
||||
lim, &chat, &echo, &e, &ns));
|
||||
const json c = json::parse(chat);
|
||||
CHECK_EQ(c["tools"].size(), (size_t)2); /* the custom tool left out */
|
||||
CHECK_EQ(c["tools"][1]["function"].value("name", ""), std::string("crm__find"));
|
||||
CHECK_EQ(c["messages"][1]["tool_calls"][0]["function"].value("name", ""), std::string("crm__find"));
|
||||
CHECK_EQ(c["tool_choice"]["function"].value("name", ""), std::string("crm__find"));
|
||||
CHECK_EQ(ns.size(), (size_t)1);
|
||||
CHECK_EQ(ns["crm__find"].first, std::string("crm"));
|
||||
CHECK_EQ(json::parse(echo)["tools"].size(), (size_t)2); /* echoed as sent */
|
||||
|
||||
/* A flattened name may not shadow a top-level tool's. */
|
||||
CHECK(responses_to_chat(R"({"input":"x","tools":[{"type":"function","name":"crm__find"},
|
||||
{"type":"namespace","name":"crm","tools":[{"type":"function","name":"find"}]}]})",
|
||||
lim, &chat, &echo, &e, &ns) < 0);
|
||||
|
||||
Fixture f;
|
||||
f.sched.reply = R"(TOOL:crm__find:{"q":"P"})";
|
||||
const std::string tools = R"("tools":[{"type":"namespace","name":"crm","tools":[)"
|
||||
R"({"type":"function","name":"find","parameters":{"type":"object"}}]}],)";
|
||||
HttpResponse r = f.post("/v1/responses", "{" + tools + R"("input":"find P"})");
|
||||
CHECK_EQ(r.status, 200);
|
||||
const json o = json::parse(r.body);
|
||||
CHECK_EQ(o["output"][0].value("type", ""), std::string("function_call"));
|
||||
CHECK_EQ(o["output"][0].value("namespace", ""), std::string("crm"));
|
||||
CHECK_EQ(o["output"][0].value("name", ""), std::string("find"));
|
||||
f.sched.join_all();
|
||||
HttpResponse st = f.post("/v1/responses", "{" + tools + R"("stream":true,"input":"find P"})");
|
||||
const std::string body = drain(st);
|
||||
CHECK(has(body, R"("namespace":"crm")"));
|
||||
CHECK(!has(body, "crm__find"));
|
||||
f.sched.join_all();
|
||||
}
|
||||
|
||||
TEST(the_responses_api_answers_with_a_response_object_and_its_events) {
|
||||
Fixture f;
|
||||
HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})");
|
||||
@@ -4465,6 +4574,90 @@ int status_with(Fixture& f, const std::string& ep, const std::string& key, const
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The control vector: absent, the deployment's default applies; an explicit `true` on a
|
||||
* deployment with no vector is refused by name (serving the stock model while the client believes
|
||||
* otherwise would be a silent lie), and on one with a vector it reaches the engine's request. */
|
||||
TEST(the_control_vector_field_overrides_the_default_or_is_refused) {
|
||||
const json body = json::parse(R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4,
|
||||
"control_vector":true})");
|
||||
{
|
||||
/* No vector loaded: refused, naming the field. */
|
||||
Fixture f;
|
||||
HttpResponse r = f.post("/v1/chat/completions", body.dump());
|
||||
if (r.streaming()) drain(r);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r.status, 400);
|
||||
CHECK(r.body.find("control_vector") != std::string::npos);
|
||||
/* The route itself is present and answers 404 on both methods: that is what the page tests
|
||||
* for before it hides the panel, and what distinguishes "no vector here" from "not signed
|
||||
* in". */
|
||||
const HttpResponse g0 = f.get("/admin/control-vector");
|
||||
CHECK_EQ(g0.status, 404);
|
||||
CHECK(g0.body.find("not_found_error") != std::string::npos);
|
||||
CHECK_EQ(f.post("/admin/control-vector", R"({"enabled":true})").status, 404);
|
||||
}
|
||||
{
|
||||
/* A vector loaded, default off: the request's own choice wins and reaches the engine. */
|
||||
bool def = false;
|
||||
Fixture f(Fixture::Tweak{ [&](ServerOptions&, Deps& d) {
|
||||
d.control_vector.available = [] { return true; };
|
||||
d.control_vector.get_default = [&def] { return def; };
|
||||
d.control_vector.set_default = [&def](bool on) { def = on; };
|
||||
d.control_vector.json = [&def] {
|
||||
return std::string("{\"available\":true,\"default\":") +
|
||||
(def ? "true" : "false") + "}";
|
||||
};
|
||||
} });
|
||||
HttpResponse r = f.post("/v1/chat/completions", body.dump());
|
||||
if (r.streaming()) drain(r);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* The same request naming nothing runs the default, which the admin route flips. */
|
||||
def = true;
|
||||
HttpResponse r2 = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4})");
|
||||
if (r2.streaming()) drain(r2);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r2.status, 200);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* Both spellings in one body: the field's own name wins over Strata's alias, whichever
|
||||
* order the parser happens to read them in. */
|
||||
HttpResponse r3 = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4,
|
||||
"experimental_speed_projection":true,
|
||||
"control_vector":false})");
|
||||
if (r3.streaming()) drain(r3);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r3.status, 200);
|
||||
CHECK(!f.sched.last_sp.use_control_vector);
|
||||
|
||||
/* A JSON null is "not sent", not "false": the deployment's default (on, here) applies. */
|
||||
HttpResponse r4 = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}],
|
||||
"max_tokens":4,
|
||||
"control_vector":null})");
|
||||
if (r4.streaming()) drain(r4);
|
||||
f.sched.join_all();
|
||||
CHECK_EQ(r4.status, 200);
|
||||
CHECK(f.sched.last_sp.use_control_vector);
|
||||
|
||||
const HttpResponse g = f.get("/admin/control-vector");
|
||||
CHECK_EQ(g.status, 200);
|
||||
CHECK(g.body.find("\"default\":true") != std::string::npos);
|
||||
const HttpResponse p = f.post("/admin/control-vector", R"({"enabled":false})");
|
||||
CHECK_EQ(p.status, 200);
|
||||
CHECK(!def);
|
||||
/* Refuses a body that names no boolean rather than guessing. */
|
||||
CHECK_EQ(f.post("/admin/control-vector", R"({"enabled":"yes"})").status, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/* The policy oai.cpp's lists state, key by key, on every endpoint: a guarded key is served at its
|
||||
* neutral value and refused by name at any other (a 200 means every answer-changing field was
|
||||
* honoured); an inert key and an unknown one are accepted and ignored; an accepted key with a
|
||||
@@ -4476,6 +4669,12 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
Fixture f(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) {
|
||||
d.embed = &emb;
|
||||
o.supports_logprobs = true;
|
||||
/* This deployment has a control vector, so `control_vector: true` is served rather
|
||||
* than refused; the refusal on a deployment without one is its own case below. */
|
||||
d.control_vector.available = [] { return true; };
|
||||
d.control_vector.get_default = [] { return false; };
|
||||
d.control_vector.set_default = [](bool) {};
|
||||
d.control_vector.json = [] { return std::string("{\"available\":true}"); };
|
||||
} });
|
||||
emb.tpl = &f.tmpl;
|
||||
f.sched.embedding = { 1.0f, 2.0f, 3.0f, 4.0f };
|
||||
@@ -4581,6 +4780,11 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
|
||||
{ "input", { "yo", none } }, { "encoding_format", { "base64", none } },
|
||||
{ "dimensions", { 2, none } }, { "image_tokens", { 70, none } },
|
||||
{ "prompt_name", { "query", none } },
|
||||
/* The control vector is accepted by every text endpoint under its own name and under
|
||||
* Strata's spelling; its semantic refusal (a deployment with no vector) happens at
|
||||
* submission, not parsing, so a parse test sees 200 here. */
|
||||
{ "control_vector", { true, none } },
|
||||
{ "experimental_speed_projection", { true, none } },
|
||||
};
|
||||
/* logprobs is spelled per endpoint: true on chat, a count on completions. */
|
||||
auto value_for = [&](const std::string& key, const std::string& ep) -> Valid {
|
||||
|
||||
@@ -300,4 +300,20 @@ TEST(a_unit_inner_dimension_is_sharded_as_the_matrix_it_leaves) {
|
||||
CHECK_EQ(weight_share(w, e, 3, stack, 2, 0, s, &why), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(glm_kda_tp4_takes_each_head_shard_from_all_three_convolution_parts) {
|
||||
const auto e = rad_enc_plain(RAD_BF16);
|
||||
const auto w = decl(e, { 0 }, 3 * 8192, 4, RAD_SHARD_ROW, 4, { 2048, 2048, 2048 });
|
||||
const int64_t shape[] = { 3 * 8192, 1, 4 };
|
||||
for (int rank = 0; rank < 4; ++rank) {
|
||||
PlaneShare s[RAD_ENC_MAX_PLANES];
|
||||
REQUIRE_EQ(weight_share(w, e, 3, shape, 4, rank, s, nullptr), RAD_OK);
|
||||
REQUIRE_EQ(s[0].rects.size(), (size_t)3);
|
||||
for (int part = 0; part < 3; ++part) {
|
||||
CHECK_EQ(s[0].rects[part].row0, (int64_t)(part * 8192 + rank * 2048));
|
||||
CHECK_EQ(s[0].rects[part].rows, (int64_t)2048);
|
||||
CHECK_EQ(s[0].rects[part].bytes, (int64_t)8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
|
||||
@@ -87,11 +88,14 @@ 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 = {
|
||||
{ "breeze", "" }, { "embeddinggemma2", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" },
|
||||
{ "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" },
|
||||
{ "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };
|
||||
{ "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" },
|
||||
{ "flux3distilled", "" },
|
||||
{ "gemma3", "" }, { "gemma4", "" },
|
||||
{ "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" },
|
||||
{ "llama", "fp8_e4m3" }, { "qwen35", "" },
|
||||
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
|
||||
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
|
||||
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "sdxl", "" } };
|
||||
std::set<std::pair<std::string, std::string>> got;
|
||||
for (const auto& [k, name] : keys) got.insert(k);
|
||||
if (got != want)
|
||||
@@ -101,4 +105,32 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
|
||||
CHECK(got == want);
|
||||
}
|
||||
|
||||
/* A checkpoint whose quantisation was imported weight by weight (Quark, ParoQuant, GPTQ, NVFP4)
|
||||
* names a tool no plugin claims, so the family's one quantised plugin serves it, and two are
|
||||
* refused (startup.h). So each family has at most one quantised plugin that takes imports:
|
||||
* qwen35_w8a8 declines them (rad_arch_serves_imports), leaving Qwen3.8 imports to qwen35_fp8. */
|
||||
TEST(every_shipped_family_has_at_most_one_plugin_for_an_imported_checkpoint) {
|
||||
Registry r;
|
||||
const int st = r.load_dir(dir_of("architectures"), {});
|
||||
if (st == RAD_E_IO && r.plugins().empty())
|
||||
ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures"));
|
||||
CHECK_OK(st);
|
||||
std::map<std::string, std::vector<std::string>> takers;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && !p.arch_quant.empty() && p.arch_serves_imports)
|
||||
takers[p.arch_id].push_back(p.name);
|
||||
for (const auto& [id, names] : takers) {
|
||||
if (names.size() > 1)
|
||||
for (const auto& n : names)
|
||||
fprintf(stderr, " '%s' would take an imported %s checkpoint\n", n.c_str(),
|
||||
id.c_str());
|
||||
CHECK_EQ(names.size(), 1u);
|
||||
}
|
||||
REQUIRE(takers.count("qwen35"));
|
||||
CHECK_EQ(takers["qwen35"][0], std::string("qwen35_fp8"));
|
||||
const Plugin* w8 = r.plugin("qwen35_w8a8");
|
||||
REQUIRE(w8 != nullptr);
|
||||
CHECK(!w8->arch_serves_imports);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+138
-32
@@ -869,6 +869,40 @@ struct TestStrings : StringSink {
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
|
||||
/* `in` through the .rad's vocab section and back into `out`. */
|
||||
int round_trip(const VocabBuild& in, VocabBuild* out) {
|
||||
TestStrings strings;
|
||||
std::vector<uint8_t> section;
|
||||
/* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser
|
||||
* writes absolute offsets, so the section must know where it lands before it is written, and
|
||||
* it lands 8-aligned, as the writer places it, because the reader takes the header as a typed
|
||||
* pointer into the file. */
|
||||
const uint64_t str_off = sizeof(RadFileHeader);
|
||||
RAD_TRY(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */
|
||||
const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7;
|
||||
|
||||
TestStrings strings2;
|
||||
section.clear();
|
||||
RAD_TRY(vocab_serialize(in, strings2, sec_off, section));
|
||||
|
||||
std::vector<uint8_t> file(sec_off + section.size(), 0);
|
||||
RadFileHeader* fh = reinterpret_cast<RadFileHeader*>(file.data());
|
||||
fh->magic = RAD_MAGIC;
|
||||
fh->version = RAD_FORMAT_VER;
|
||||
fh->str_off = str_off;
|
||||
fh->str_bytes = strings2.blob.size();
|
||||
fh->vocab_off = sec_off;
|
||||
fh->vocab_bytes = section.size();
|
||||
std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size());
|
||||
std::memcpy(file.data() + sec_off, section.data(), section.size());
|
||||
return vocab_deserialize(file.data(), file.size(),
|
||||
reinterpret_cast<const RadVocabHeader*>(file.data() + sec_off), *out);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(vocab_section_round_trip) {
|
||||
VocabBuild in;
|
||||
in.kind = RAD_TOK_BPE;
|
||||
@@ -885,35 +919,8 @@ TEST(vocab_section_round_trip) {
|
||||
VocabStep s2; s2.kind = RAD_PRE_BYTELEVEL; s2.flags = 2; in.steps.push_back(s2);
|
||||
VocabStep s3; s3.kind = RAD_DEC_BYTELEVEL; in.steps.push_back(s3);
|
||||
|
||||
TestStrings strings;
|
||||
std::vector<uint8_t> section;
|
||||
/* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser
|
||||
* writes absolute offsets, so the section must know where it lands before it is written, and
|
||||
* it lands 8-aligned, as the writer places it, because the reader takes the header as a typed
|
||||
* pointer into the file. */
|
||||
const uint64_t str_off = sizeof(RadFileHeader);
|
||||
CHECK_OK(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */
|
||||
const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7;
|
||||
|
||||
TestStrings strings2;
|
||||
section.clear();
|
||||
CHECK_OK(vocab_serialize(in, strings2, sec_off, section));
|
||||
|
||||
std::vector<uint8_t> file(sec_off + section.size(), 0);
|
||||
RadFileHeader* fh = reinterpret_cast<RadFileHeader*>(file.data());
|
||||
fh->magic = RAD_MAGIC;
|
||||
fh->version = RAD_FORMAT_VER;
|
||||
fh->str_off = str_off;
|
||||
fh->str_bytes = strings2.blob.size();
|
||||
fh->vocab_off = sec_off;
|
||||
fh->vocab_bytes = section.size();
|
||||
std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size());
|
||||
std::memcpy(file.data() + sec_off, section.data(), section.size());
|
||||
|
||||
VocabBuild out;
|
||||
CHECK_OK(vocab_deserialize(file.data(), file.size(),
|
||||
reinterpret_cast<const RadVocabHeader*>(file.data() + sec_off),
|
||||
out));
|
||||
CHECK_OK(round_trip(in, &out));
|
||||
|
||||
CHECK_EQ(out.kind, in.kind);
|
||||
CHECK(out.tokens == in.tokens);
|
||||
@@ -985,7 +992,7 @@ TEST(parse_tokenizer_json_chain) {
|
||||
* interpreted rather than hashed. */
|
||||
TEST(parse_tokenizer_json_refuses_unknown_components) {
|
||||
const char* js = R"JSON({
|
||||
"normalizer": { "type": "Precompiled", "precompiled_charsmap": "AAAA" },
|
||||
"normalizer": { "type": "StripAccents" },
|
||||
"pre_tokenizer": { "type": "ByteLevel" },
|
||||
"model": { "type": "BPE", "vocab": {"a": 0}, "merges": [] }
|
||||
})JSON";
|
||||
@@ -995,7 +1002,7 @@ TEST(parse_tokenizer_json_refuses_unknown_components) {
|
||||
|
||||
/* A step the tokenizer does not run is refused at load, not passed over on every encode. */
|
||||
TEST(a_vocab_with_an_unknown_step_does_not_load) {
|
||||
for (uint32_t kind : { 9u, 39u, 70u, 200u }) {
|
||||
for (uint32_t kind : { 10u, 41u, 70u, 200u }) {
|
||||
VocabBuild vb;
|
||||
vb.kind = RAD_TOK_BPE;
|
||||
vb.tokens = { "a" };
|
||||
@@ -1498,7 +1505,7 @@ TEST(decompose_and_compose_are_inverses_over_the_canonical_forms) {
|
||||
|
||||
namespace {
|
||||
|
||||
/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.2) */
|
||||
/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.3) */
|
||||
|
||||
struct DecodeGolden { const char* fixture; std::vector<int32_t> ids; const char* text; };
|
||||
struct PretokGolden { const char* name; const char* json; std::vector<int32_t> ids; };
|
||||
@@ -1676,6 +1683,49 @@ const std::vector<std::pair<const char*, EncodeGolden>>& metaspace_special_golde
|
||||
return v;
|
||||
}
|
||||
|
||||
const char* const kClipLike = R"JSON({"added_tokens": [{"id": 620, "content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": true}, {"id": 621, "content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], "normalizer": {"type": "Sequence", "normalizers": [{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": "\\s+"}, "content": " "}, {"type": "Lowercase"}]}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [{"type": "Split", "pattern": {"Regex": "'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+"}, "behavior": "Removed", "invert": true}, {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true}]}, "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", 621], "cls": ["<|startoftext|>", 620], "trim_offsets": false, "add_prefix_space": false}, "decoder": {"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true}, "model": {"type": "BPE", "dropout": null, "unk_token": "<|endoftext|>", "continuing_subword_prefix": "", "end_of_word_suffix": "</w>", "fuse_unk": false, "vocab": {"!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "&": 5, "'": 6, "(": 7, ")": 8, "*": 9, "+": 10, ",": 11, "-": 12, ".": 13, "/": 14, "0": 15, "1": 16, "2": 17, "3": 18, "4": 19, "5": 20, "6": 21, "7": 22, "8": 23, "9": 24, ":": 25, ";": 26, "<": 27, "=": 28, ">": 29, "?": 30, "@": 31, "A": 32, "B": 33, "C": 34, "D": 35, "E": 36, "F": 37, "G": 38, "H": 39, "I": 40, "J": 41, "K": 42, "L": 43, "M": 44, "N": 45, "O": 46, "P": 47, "Q": 48, "R": 49, "S": 50, "T": 51, "U": 52, "V": 53, "W": 54, "X": 55, "Y": 56, "Z": 57, "[": 58, "\\": 59, "]": 60, "^": 61, "_": 62, "`": 63, "a": 64, "b": 65, "c": 66, "d": 67, "e": 68, "f": 69, "g": 70, "h": 71, "i": 72, "j": 73, "k": 74, "l": 75, "m": 76, "n": 77, "o": 78, "p": 79, "q": 80, "r": 81, "s": 82, "t": 83, "u": 84, "v": 85, "w": 86, "x": 87, "y": 88, "z": 89, "{": 90, "|": 91, "}": 92, "~": 93, "¡": 94, "¢": 95, "£": 96, "¤": 97, "¥": 98, "¦": 99, "§": 100, "¨": 101, "©": 102, "ª": 103, "«": 104, "¬": 105, "®": 106, "¯": 107, "°": 108, "±": 109, "²": 110, "³": 111, "´": 112, "µ": 113, "¶": 114, "·": 115, "¸": 116, "¹": 117, "º": 118, "»": 119, "¼": 120, "½": 121, "¾": 122, "¿": 123, "À": 124, "Á": 125, "Â": 126, "Ã": 127, "Ä": 128, "Å": 129, "Æ": 130, "Ç": 131, "È": 132, "É": 133, "Ê": 134, "Ë": 135, "Ì": 136, "Í": 137, "Î": 138, "Ï": 139, "Ð": 140, "Ñ": 141, "Ò": 142, "Ó": 143, "Ô": 144, "Õ": 145, "Ö": 146, "×": 147, "Ø": 148, "Ù": 149, "Ú": 150, "Û": 151, "Ü": 152, "Ý": 153, "Þ": 154, "ß": 155, "à": 156, "á": 157, "â": 158, "ã": 159, "ä": 160, "å": 161, "æ": 162, "ç": 163, "è": 164, "é": 165, "ê": 166, "ë": 167, "ì": 168, "í": 169, "î": 170, "ï": 171, "ð": 172, "ñ": 173, "ò": 174, "ó": 175, "ô": 176, "õ": 177, "ö": 178, "÷": 179, "ø": 180, "ù": 181, "ú": 182, "û": 183, "ü": 184, "ý": 185, "þ": 186, "ÿ": 187, "Ā": 188, "ā": 189, "Ă": 190, "ă": 191, "Ą": 192, "ą": 193, "Ć": 194, "ć": 195, "Ĉ": 196, "ĉ": 197, "Ċ": 198, "ċ": 199, "Č": 200, "č": 201, "Ď": 202, "ď": 203, "Đ": 204, "đ": 205, "Ē": 206, "ē": 207, "Ĕ": 208, "ĕ": 209, "Ė": 210, "ė": 211, "Ę": 212, "ę": 213, "Ě": 214, "ě": 215, "Ĝ": 216, "ĝ": 217, "Ğ": 218, "ğ": 219, "Ġ": 220, "ġ": 221, "Ģ": 222, "ģ": 223, "Ĥ": 224, "ĥ": 225, "Ħ": 226, "ħ": 227, "Ĩ": 228, "ĩ": 229, "Ī": 230, "ī": 231, "Ĭ": 232, "ĭ": 233, "Į": 234, "į": 235, "İ": 236, "ı": 237, "IJ": 238, "ij": 239, "Ĵ": 240, "ĵ": 241, "Ķ": 242, "ķ": 243, "ĸ": 244, "Ĺ": 245, "ĺ": 246, "Ļ": 247, "ļ": 248, "Ľ": 249, "ľ": 250, "Ŀ": 251, "ŀ": 252, "Ł": 253, "ł": 254, "Ń": 255, "!</w>": 256, "\"</w>": 257, "#</w>": 258, "$</w>": 259, "%</w>": 260, "&</w>": 261, "'</w>": 262, "(</w>": 263, ")</w>": 264, "*</w>": 265, "+</w>": 266, ",</w>": 267, "-</w>": 268, ".</w>": 269, "/</w>": 270, "0</w>": 271, "1</w>": 272, "2</w>": 273, "3</w>": 274, "4</w>": 275, "5</w>": 276, "6</w>": 277, "7</w>": 278, "8</w>": 279, "9</w>": 280, ":</w>": 281, ";</w>": 282, "<</w>": 283, "=</w>": 284, "></w>": 285, "?</w>": 286, "@</w>": 287, "A</w>": 288, "B</w>": 289, "C</w>": 290, "D</w>": 291, "E</w>": 292, "F</w>": 293, "G</w>": 294, "H</w>": 295, "I</w>": 296, "J</w>": 297, "K</w>": 298, "L</w>": 299, "M</w>": 300, "N</w>": 301, "O</w>": 302, "P</w>": 303, "Q</w>": 304, "R</w>": 305, "S</w>": 306, "T</w>": 307, "U</w>": 308, "V</w>": 309, "W</w>": 310, "X</w>": 311, "Y</w>": 312, "Z</w>": 313, "[</w>": 314, "\\</w>": 315, "]</w>": 316, "^</w>": 317, "_</w>": 318, "`</w>": 319, "a</w>": 320, "b</w>": 321, "c</w>": 322, "d</w>": 323, "e</w>": 324, "f</w>": 325, "g</w>": 326, "h</w>": 327, "i</w>": 328, "j</w>": 329, "k</w>": 330, "l</w>": 331, "m</w>": 332, "n</w>": 333, "o</w>": 334, "p</w>": 335, "q</w>": 336, "r</w>": 337, "s</w>": 338, "t</w>": 339, "u</w>": 340, "v</w>": 341, "w</w>"Line truncated
|
||||
|
||||
const std::vector<EncodeGolden>& clip_goldens() {
|
||||
static const std::vector<EncodeGolden> v = {
|
||||
{ "a photo of a cat", { 320, 608, 513, 320, 555 }, { 620, 320, 608, 513, 320, 555, 621 } },
|
||||
{ "1girl, solo, masterpiece, best quality, (absurdres:1.2), looking_at_viewer, hatsune_miku", { 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340 }, { 620, 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340, 621 } },
|
||||
{ "A Photograph of the Mountains, it's DON'T stop", { 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616 }, { 620, 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616, 621 } },
|
||||
{ "1024x1024 2.5 v1.0", { 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271 }, { 620, 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271, 621 } },
|
||||
{ "Caf\xc3\xa9 na\xc3\xafve \xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc \xec\x84\x9c\xec\x9a\xb8 \xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7 \xc4\xb0stanbul \xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3", { 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481 }, { 620, 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481, 621 } },
|
||||
{ " many spaces\t\ttabs\n\nnewlines ", { 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338 }, { 620, 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338, 621 } },
|
||||
{ "...!!!??? ((()))[[]]", { 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316 }, { 620, 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316, 621 } },
|
||||
{ "", { }, { 620, 621 } },
|
||||
{ "a", { 320 }, { 620, 320, 621 } },
|
||||
{ "<|startoftext|>a cat<|endoftext|>", { 620, 320, 555, 621 }, { 620, 620, 320, 555, 621, 621 } },
|
||||
{ "x<|StartOfText|>y", { 343, 620, 344 }, { 620, 343, 620, 344, 621 } },
|
||||
{ "a</w>b catcat", { 320, 27, 270, 342, 285, 321, 66, 64, 83, 555 }, { 620, 320, 27, 270, 342, 285, 321, 66, 64, 83, 555, 621 } },
|
||||
{ "photographphotograph", { 525, 78, 577, 71, 609 }, { 620, 525, 78, 577, 71, 609, 621 } },
|
||||
{ "it'sit's'll", { 524, 528, 524, 528, 6, 75, 331 }, { 620, 524, 528, 524, 528, 6, 75, 331, 621 } },
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */
|
||||
const std::vector<const char*>& clip_decoded() {
|
||||
static const std::vector<const char*> v = {
|
||||
"a</w>photo</w>of</w>a</w>cat</w>",
|
||||
"1</w>girl</w>,</w>solo</w>,</w>masterpiece</w>,</w>best</w>quality</w>,</w>(</w>absurdres</w>:</w>1</w>.</w>2</w>),</w>looking</w>_</w>at</w>_</w>viewer</w>,</w>hatsune</w>_</w>miku</w>",
|
||||
"a</w>photograph</w>of</w>the</w>mountains</w>,</w>it</w>'s</w>don</w>'t</w>stop</w>",
|
||||
"1</w>0</w>2</w>4</w>x</w>1</w>0</w>2</w>4</w>2</w>.</w>5</w>v</w>1</w>.</w>0</w>",
|
||||
"caf\xc3\xa9</w>na\xc3\xafve</w>\xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc</w>\xec\x84\x9c\xec\x9a\xb8</w>\xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7</w>i</w>\xcc\x87</w>stanbul</w>\xcf\x83\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x83</w>",
|
||||
"many</w>spaces</w>tabs</w>newlines</w>",
|
||||
"...!!!???</w>((()))[[]]</w>",
|
||||
"",
|
||||
"a</w>",
|
||||
"a</w>cat</w>",
|
||||
"x</w>y</w>",
|
||||
"a</w></</w>w</w>></w>b</w>catcat</w>",
|
||||
"photographphotograph</w>",
|
||||
"it</w>'s</w>it</w>'s</w>'ll</w>",
|
||||
};
|
||||
return v;
|
||||
}
|
||||
|
||||
/* END generated by mk_tokenizer_goldens.py */
|
||||
|
||||
} /* namespace */
|
||||
@@ -1794,6 +1844,58 @@ TEST(the_gemma_shaped_tokenizer_encodes_as_huggingface) {
|
||||
CHECK_EQ(k, gemma_decoded().size());
|
||||
}
|
||||
|
||||
/* CLIP's shape (Stable Diffusion's text encoders): an NFC / whitespace-collapse / Lowercase
|
||||
* normaliser, a Split that keeps letter runs, single digits and punctuation runs, ByteLevel, BPE
|
||||
* whose word-final symbols carry the "</w>" suffix, RobertaProcessing `<|startoftext|> $A
|
||||
* <|endoftext|>`, and `<|startoftext|>` matched in the normalised text (so `<|StartOfText|>` is it
|
||||
* too). Encoded with and without the framing and decoded, against HuggingFace. */
|
||||
TEST(the_clip_shaped_tokenizer_encodes_as_huggingface) {
|
||||
VocabBuild vb;
|
||||
REQUIRE(parse_tokenizer_json_buf(kClipLike, "clip_like", vb) >= 0);
|
||||
CHECK(vb.add_bos);
|
||||
CHECK(vb.add_eos);
|
||||
CHECK_EQ(vb.bos, 620);
|
||||
CHECK_EQ(vb.eos, 621);
|
||||
/* Served as a container holds it: the suffix and the normalised added token are steps. */
|
||||
VocabBuild baked;
|
||||
REQUIRE(round_trip(vb, &baked) == RAD_OK);
|
||||
auto v = std::make_shared<Vocab>();
|
||||
REQUIRE(v->load(std::move(baked)) >= 0);
|
||||
Tokenizer t;
|
||||
CHECK_OK(t.init(v));
|
||||
size_t k = 0;
|
||||
for (const EncodeGolden& g : clip_goldens()) {
|
||||
std::vector<int32_t> plain, special;
|
||||
CHECK_OK(t.encode(g.text, plain, /*add_special=*/false, /*parse_special=*/true));
|
||||
CHECK_OK(t.encode(g.text, special, /*add_special=*/true, /*parse_special=*/true));
|
||||
CHECK(plain == g.ids);
|
||||
/* A text opening with the BOS token gets a second one, as in HuggingFace: CLIP's BOS
|
||||
* is matched in the normalised text, after Tokenizer::encode decides on adding one. */
|
||||
CHECK(special == g.with_special);
|
||||
if (plain != g.ids) {
|
||||
std::string got;
|
||||
for (int32_t id : plain) got += std::to_string(id) + ",";
|
||||
fprintf(stderr, " \"%s\": %s\n", g.text, got.c_str());
|
||||
}
|
||||
CHECK_EQ(t.decode(g.with_special), std::string(clip_decoded()[k]));
|
||||
CHECK_EQ(streamed(v, g.with_special), std::string(clip_decoded()[k]));
|
||||
++k;
|
||||
}
|
||||
CHECK_EQ(k, clip_decoded().size());
|
||||
|
||||
/* A token matched in the normalised text follows parse_special as the raw ones do, through
|
||||
* the segment cache as well: the same long text with it off and then on. */
|
||||
std::string text;
|
||||
for (int i = 0; i < 30; ++i) text += "a photo of a cat <|StartOfText|> ";
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
std::vector<int32_t> off, on;
|
||||
CHECK_OK(t.encode(text, off, false, /*parse_special=*/false));
|
||||
CHECK_OK(t.encode(text, on, false, /*parse_special=*/true));
|
||||
CHECK_EQ(std::count(off.begin(), off.end(), 620), (ptrdiff_t)0);
|
||||
CHECK_EQ(std::count(on.begin(), on.end(), 620), (ptrdiff_t)30);
|
||||
}
|
||||
}
|
||||
|
||||
/* Metaspace's "first" scheme prepends the replacement only where the text starts: a segment after
|
||||
* a special token ("[INST]Hi", "<s>Hi") has a non-zero original offset in HuggingFace and gets
|
||||
* none, where "always" gives every segment one. Encoded through the segment cache both cold and
|
||||
@@ -1851,7 +1953,6 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) {
|
||||
bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"),
|
||||
bpe(ws, "", R"(, "end_of_word_suffix": "</w>")"),
|
||||
bpe(ws, "", R"(, "continuing_subword_prefix": "##")"),
|
||||
bpe(ws, "", R"(, "dropout": 0.1)"),
|
||||
bpe(ws, added(R"("single_word": true, "lstrip": false, "rstrip": false, "normalized": false)")),
|
||||
@@ -1878,6 +1979,11 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) {
|
||||
bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)"
|
||||
R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"),
|
||||
bpe(ws, "", R"(, "dropout": null, "continuing_subword_prefix": null, "end_of_word_suffix": null)"),
|
||||
bpe(ws, "", R"(, "continuing_subword_prefix": "", "end_of_word_suffix": "</w>")"),
|
||||
/* Lower case already, so the Lowercase normaliser leaves its spelling alone. */
|
||||
bpe(ws, R"(, "normalizer": {"type": "Lowercase"}, "added_tokens": [{"id": 3, "content": "x",)"
|
||||
R"( "special": true, "single_word": false, "lstrip": false, "rstrip": false,)"
|
||||
R"( "normalized": true}])"),
|
||||
};
|
||||
for (const std::string& js : accepted) {
|
||||
VocabBuild vb;
|
||||
|
||||
@@ -1020,4 +1020,35 @@ TEST(the_token_view_gives_grammars_the_decoded_bytes) {
|
||||
CHECK_EQ(tv.token_piece(world[0])[0], ' ');
|
||||
}
|
||||
|
||||
/* Gemma's tokenizer.json: whitespace runs are added tokens, not special, spelled in U+2581, and
|
||||
* the decoder replaces U+2581 with a space. HuggingFace decodes them to spaces; returned literally,
|
||||
* an indented line came out as "▁▁- web-a" (TranslateGemma, 18. 10. 2026). */
|
||||
TEST(an_added_whitespace_run_decodes_to_spaces_as_huggingface_does) {
|
||||
auto v = from_json(R"JSON({
|
||||
"normalizer": { "type": "Replace", "pattern": { "String": " " }, "content": "▁" },
|
||||
"decoder": { "type": "Sequence", "decoders": [
|
||||
{ "type": "Replace", "pattern": { "String": "▁" }, "content": " " },
|
||||
{ "type": "ByteFallback" }, { "type": "Fuse" } ] },
|
||||
"model": { "type": "BPE", "byte_fallback": true,
|
||||
"vocab": {"<unk>": 0, "▁": 1, "-": 2, "▁▁": 3, "<eot>": 4, "▁▁▁▁": 5},
|
||||
"merges": ["▁ ▁", "▁▁ ▁▁"] },
|
||||
"added_tokens": [
|
||||
{"id": 3, "content": "▁▁", "special": false, "normalized": false},
|
||||
{"id": 5, "content": "▁▁▁▁", "special": false, "normalized": false},
|
||||
{"id": 4, "content": "<eot>", "special": true} ]
|
||||
})JSON");
|
||||
REQUIRE(v != nullptr);
|
||||
Tokenizer t;
|
||||
CHECK_OK(t.init(v));
|
||||
CHECK_EQ(t.piece(3, false), std::string(" "));
|
||||
CHECK_EQ(t.piece(5, false), std::string(" "));
|
||||
CHECK_EQ(t.decode({ 3, 2, 5, 2 }, false), std::string(" - -"));
|
||||
/* A control token still renders as written. */
|
||||
CHECK_EQ(t.piece(4, true), std::string("<eot>"));
|
||||
|
||||
TokenView tv;
|
||||
CHECK_OK(tv.init(v));
|
||||
CHECK_EQ(tv.token_piece(3), std::string(" "));
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+396
-4
@@ -8,8 +8,10 @@
|
||||
using namespace sched_fake;
|
||||
|
||||
#include "gen/video_driver.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -55,9 +57,13 @@ RadVideoGenDecl decl_small() {
|
||||
return d;
|
||||
}
|
||||
|
||||
/* The soundtrack's rows a latent in fake_positions' layout: the declaration's audio_streams, or its
|
||||
* two channels. */
|
||||
int g_audio_streams = 2;
|
||||
|
||||
/* The packed layout's rows, each position the row's index; a decode pass, ten rows a frame. */
|
||||
int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) {
|
||||
const int64_t rows = g->n_text + 2 * (int64_t)g->n_audio +
|
||||
const int64_t rows = g->n_text + g_audio_streams * (int64_t)g->n_audio +
|
||||
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
|
||||
if (which == RAD_VPOS_DECODE) return 10 * (int64_t)g->frames;
|
||||
if (pos) {
|
||||
@@ -339,7 +345,7 @@ TEST(the_schedule_counts_grid_points_and_shifts_each_modality) {
|
||||
TEST(a_request_shift_overrides_the_declaration_per_stream) {
|
||||
const RadVideoGenDecl d = decl_small();
|
||||
const gen::VideoSchedule base = gen::video_schedule(d, 50);
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 50, 6.0, 0.0); /* video -> 6, audio keep 3 */
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 50, 0, false, 6.0, 0.0); /* video -> 6, audio keep 3 */
|
||||
REQUIRE_EQ(s.sig_v.size(), base.sig_v.size());
|
||||
REQUIRE_EQ(s.sig_a.size(), base.sig_a.size());
|
||||
const double b = 1.0 - 30.0 / 49.0;
|
||||
@@ -661,7 +667,7 @@ TEST(an_upscale_that_cannot_run_is_refused_at_submit) {
|
||||
|
||||
/* What can never run is refused at submit: an empty or long prompt, a size off the multiple,
|
||||
* below the least side, over the area or the aspect, a length outside the chunks, steps outside
|
||||
* 2..max. */
|
||||
* 2..max. A length of 0 chunks is none named. */
|
||||
TEST(a_request_that_cannot_run_is_refused_at_submit) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
@@ -690,9 +696,395 @@ TEST(a_request_that_cannot_run_is_refused_at_submit) {
|
||||
r->height = 96;
|
||||
refused(std::move(r), "size");
|
||||
refused(f.req(4), "chunks");
|
||||
refused(f.req(0), "chunks");
|
||||
refused(f.req(1, 6), "num_inference_steps");
|
||||
refused(f.req(1, 1), "num_inference_steps");
|
||||
/* No length named is the model's default. */
|
||||
auto none = f.req(0);
|
||||
gen::VideoTicket* t = none->ticket.get();
|
||||
CHECK_OK(f.drv.submit(std::move(none), &why));
|
||||
CHECK_EQ(t->frames, 3);
|
||||
}
|
||||
|
||||
/* Decoders (RadVideoGenDecl::decoders): a request's index reaches every VDECODE pass; an index past
|
||||
* the list, or a frame over the decoder's area, is refused at submit. */
|
||||
TEST(the_decoder_a_request_names_reaches_its_decode_passes) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.vgen_str.decoders = { "vae", "diffusion" };
|
||||
f.prog.vgen_str.decoder_max_area = { 64 * 64, 32 * 32 };
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(1);
|
||||
r->decoder = 1;
|
||||
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); /* 64 x 32 over 32 x 32 */
|
||||
CHECK(why.find("diffusion") != std::string::npos);
|
||||
r = f.req(1);
|
||||
r->decoder = 2;
|
||||
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
|
||||
r = f.req(1);
|
||||
r->decoder = 1;
|
||||
r->width = 32;
|
||||
r->height = 32;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
int decodes = 0;
|
||||
for (int i = 0; i < 20; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
if (b->gen == RAD_GEN_PASS_VDECODE) {
|
||||
CHECK_EQ(b->vgen_b->decoder, 1);
|
||||
++decodes;
|
||||
}
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK(decodes > 0);
|
||||
}
|
||||
|
||||
/* A length head (RadVideoGenDecl::duration_out): a request that names no length is shaped at the
|
||||
* default until its VCOND pass, whose prediction (ln seconds, read back) the driver turns into
|
||||
* chunks -- clamped to the declared seconds, rounded half to even to frames, floored to the chunk
|
||||
* grid and lifted a chunk under the minimum -- then held to the chunks the model makes. */
|
||||
TEST(a_length_head_sets_the_length_after_the_prompt_pass) {
|
||||
struct Case { double sec; int32_t frames; };
|
||||
/* 4 fps, 2 frames a chunk + 1, 1..3 chunks, 0.5..2 s (2..8 frames): 1.3 s is 5.2 frames, 5;
|
||||
* 1.125 s is 4.5, which rounds to 4 (half to even) and floors to 3; 0.1 s is held to 2
|
||||
* frames, which floor to 1 and are lifted to 3; 9 s is held to 8 frames, 7 on the grid. */
|
||||
const Case cases[] = { { 1.3, 5 }, { 1.125, 3 }, { 0.1, 3 }, { 9.0, 7 } };
|
||||
for (const Case& k : cases) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.video_gen.duration_out = 3;
|
||||
f.prog.video_gen.duration_min = 0.5;
|
||||
f.prog.video_gen.duration_max = 2.0;
|
||||
f.prog.video_gen.duration_dtype = RAD_F32;
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(0);
|
||||
std::shared_ptr<gen::VideoTicket> t = r->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
CHECK_EQ(t->frames, 3); /* the default, one chunk */
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VCOND);
|
||||
REQUIRE_EQ(f.drv.readbacks().size(), (size_t)1);
|
||||
CHECK_EQ(f.drv.readbacks()[0].buf, (rad_buf)3);
|
||||
*static_cast<float*>(f.drv.readbacks()[0].host) = (float)std::log(k.sec);
|
||||
CHECK_OK(f.drv.done());
|
||||
CHECK_EQ(t->frames, k.frames);
|
||||
gen::VideoEvent e;
|
||||
bool to = false;
|
||||
REQUIRE(t->next(&e, 0, &to));
|
||||
CHECK_EQ(e.kind, (int)gen::VideoEvent::LENGTH);
|
||||
CHECK_EQ(e.n, k.frames);
|
||||
/* The steps run at that length. */
|
||||
b = f.drv.next(1);
|
||||
REQUIRE(b != nullptr);
|
||||
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VSTEP);
|
||||
CHECK_EQ(b->vgen_b->geom.frames, k.frames);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- form 1 (LTX-2's FlowMatchEulerDiscrete): evaluations, not grid points */
|
||||
|
||||
static uint32_t bits(float v) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &v, 4);
|
||||
return u;
|
||||
}
|
||||
|
||||
/* The dev schedule bit for bit against diffusers' scheduler (numpy 2.5): 30 evaluations of a
|
||||
* 6144-token video shift by mu 2.7833 and stretch to end at 0.1; and 7 of a 1500-token one. */
|
||||
TEST(form_one_is_ltx2s_dynamically_shifted_schedule_bit_for_bit) {
|
||||
RadVideoGenDecl d = decl_small();
|
||||
d.sched_kind = 1;
|
||||
d.dyn_shift = 1;
|
||||
d.base_shift = 0.95;
|
||||
d.max_shift = 2.05;
|
||||
d.base_seq = 1024;
|
||||
d.max_seq = 4096;
|
||||
d.shift_terminal = 0.1;
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 30, 6144);
|
||||
REQUIRE_EQ(s.sig_v.size(), (size_t)31);
|
||||
CHECK_EQ(s.steps, 30);
|
||||
const std::pair<int, uint32_t> want[] = {
|
||||
{ 0, 0x3f800000u }, { 1, 0x3f7f3c87u }, { 2, 0x3f7e6c02u }, { 15, 0x3f6b19eeu },
|
||||
{ 27, 0x3eff5f82u }, { 28, 0x3eb2f452u }, { 29, 0x3dccccd0u }, { 30, 0u },
|
||||
};
|
||||
for (const auto& w : want) CHECK_EQ(bits(s.sig_v[(size_t)w.first]), w.second);
|
||||
CHECK(s.sig_a == s.sig_v);
|
||||
const gen::VideoSchedule s7 = gen::video_schedule(d, 7, 1500);
|
||||
const uint32_t want7[] = { 0x3f800000u, 0x3f6e0d50u, 0x3f57d30eu, 0x3f3b945eu, 0x3f167dc8u,
|
||||
0x3ec74586u, 0x3dccccd0u, 0u };
|
||||
REQUIRE_EQ(s7.sig_v.size(), (size_t)8);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(bits(s7.sig_v[(size_t)i]), want7[i]);
|
||||
/* One evaluation is a schedule of form 1. */
|
||||
CHECK_EQ(gen::video_schedule(d, 1, 6144).steps, 1);
|
||||
}
|
||||
|
||||
static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725,
|
||||
0.421875 };
|
||||
static const double kStage2[] = { 0.909375, 0.725, 0.421875 };
|
||||
|
||||
RadVideoGenDecl decl_distilled() {
|
||||
RadVideoGenDecl d = decl_small();
|
||||
d.sched_kind = 1;
|
||||
d.n_rungs = 8;
|
||||
d.rungs = kDistilled;
|
||||
d.default_steps = d.max_steps = 8;
|
||||
d.upscale_max = 2.0;
|
||||
d.n_refine_rungs = 3;
|
||||
d.refine_rungs = kStage2;
|
||||
d.upscale_refine = 3;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* A trained schedule of form 1 is its rungs as given, and with refinement the second stage's rungs
|
||||
* follow the first's in place of the 0. */
|
||||
TEST(form_one_rungs_are_used_as_given_and_the_refinement_follows_them) {
|
||||
const RadVideoGenDecl d = decl_distilled();
|
||||
const gen::VideoSchedule s = gen::video_schedule(d, 8);
|
||||
REQUIRE_EQ(s.sig_v.size(), (size_t)9);
|
||||
CHECK_EQ(s.steps, 8);
|
||||
for (int i = 0; i < 8; ++i) CHECK_EQ(s.sig_v[(size_t)i], (float)kDistilled[i]);
|
||||
CHECK_EQ(s.sig_v[8], 0.0f);
|
||||
CHECK_EQ(gen::video_schedule(d, 9).steps, 0);
|
||||
const gen::VideoSchedule r = gen::video_schedule(d, 8, 0, true);
|
||||
REQUIRE_EQ(r.sig_v.size(), (size_t)12);
|
||||
CHECK_EQ(r.steps, 11);
|
||||
CHECK_EQ(r.sig_v[8], (float)kStage2[0]);
|
||||
CHECK_EQ(r.sig_v[10], (float)kStage2[2]);
|
||||
CHECK_EQ(r.sig_v[11], 0.0f);
|
||||
}
|
||||
|
||||
/* Two stages: every first-stage rung at the small size, the last to the clean estimate; the
|
||||
* upscale re-noises to the second stage's first sigma; the second stage's rungs at the full size.
|
||||
* The request's refinement is the second stage's length or nothing. */
|
||||
TEST(a_two_stage_request_runs_the_second_stages_own_rungs_after_the_upscale) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.video_gen = decl_distilled();
|
||||
f.prog.video_gen.rungs = nullptr;
|
||||
f.prog.video_gen.refine_rungs = nullptr;
|
||||
f.prog.vgen_str.rungs.assign(kDistilled, kDistilled + 8);
|
||||
f.prog.vgen_str.refine_rungs.assign(kStage2, kStage2 + 3);
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto bad = f.req(1, 0);
|
||||
bad->width = bad->height = 64;
|
||||
bad->upscale = 2.0;
|
||||
bad->refine = 2;
|
||||
CHECK_EQ(f.drv.submit(std::move(bad), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "upscale_refine_steps must be 3"));
|
||||
auto r = f.req(1, 0);
|
||||
r->width = r->height = 64;
|
||||
r->upscale = 2.0;
|
||||
auto t = r->ticket;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
CHECK_EQ(t->steps, 11);
|
||||
CHECK_EQ(t->refine, 3);
|
||||
std::string kinds;
|
||||
int n = 0;
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
const RadBatch* b = f.drv.next(i);
|
||||
if (!b) break;
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
kinds += kind_of(b->gen);
|
||||
if (b->gen == RAD_GEN_PASS_VSTEP) {
|
||||
const float cur = n < 8 ? (float)kDistilled[n] : (float)kStage2[n - 8];
|
||||
const float nxt = n == 7 || n == 10 ? 0.0f
|
||||
: n < 7 ? (float)kDistilled[n + 1] : (float)kStage2[n - 7];
|
||||
CHECK_EQ(V->sched[1], cur);
|
||||
CHECK_EQ(V->sched[2], nxt);
|
||||
CHECK_EQ(V->geom.lat_h, n < 8 ? 2 : 4);
|
||||
++n;
|
||||
} else if (b->gen == RAD_GEN_PASS_VUPSCALE) {
|
||||
CHECK_EQ(V->sched[1], (float)kStage2[0]);
|
||||
CHECK_EQ(V->sched[4], (float)kStage2[0]);
|
||||
}
|
||||
f.answer(0);
|
||||
CHECK_OK(f.drv.done());
|
||||
}
|
||||
CHECK_EQ(kinds, std::string("CSSSSSSSSUSSSAD"));
|
||||
CHECK_EQ(t->status(), (int)RAD_OK);
|
||||
}
|
||||
|
||||
/* A guided model: the request's terms over the model's defaults reach every pass; the negative
|
||||
* prompt rides in the VCOND pass after the prompt, each from position 0, only while a scale asks
|
||||
* for the unconditional branch; the text rows of a step are the model's fixed count. */
|
||||
TEST(guidance_and_the_negative_prompt_reach_the_passes) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
RadVideoGenDecl& d = f.prog.video_gen;
|
||||
d.guidance = 1;
|
||||
const double defaults[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 };
|
||||
std::memcpy(d.guidance_default, defaults, sizeof defaults);
|
||||
d.step_text_rows = 6;
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(1, 3);
|
||||
r->neg_tokens = { 9, 8 };
|
||||
r->guidance[1] = 0.0;
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
CHECK_EQ(b->n_tok, (int64_t)5);
|
||||
CHECK_EQ(b->n_seq, 2);
|
||||
CHECK_EQ(V->n_neg, 2);
|
||||
CHECK(std::vector<int32_t>(b->cu_seqlens, b->cu_seqlens + 3) == std::vector<int32_t>({ 0, 3, 5 }));
|
||||
CHECK(std::vector<int32_t>(b->token_ids, b->token_ids + 5) ==
|
||||
std::vector<int32_t>({ 1, 2, 3, 9, 8 }));
|
||||
CHECK(std::vector<int32_t>(b->positions, b->positions + 5) ==
|
||||
std::vector<int32_t>({ 0, 1, 2, 0, 1 }));
|
||||
CHECK_EQ(V->geom.n_text, 6);
|
||||
REQUIRE(V->guidance_h != nullptr);
|
||||
CHECK_EQ(V->guidance_h[0], 3.0f);
|
||||
CHECK_EQ(V->guidance_h[1], 0.0f);
|
||||
CHECK_EQ(V->guidance_h[3], 0.7f);
|
||||
CHECK_OK(f.drv.done());
|
||||
b = f.drv.next(1);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
|
||||
CHECK_EQ(b->n_tok, (int64_t)(6 + 60 + 2 * 2));
|
||||
CHECK_EQ(b->vgen_b->guidance_h[4], 7.0f);
|
||||
/* The device copy the ops read. */
|
||||
REQUIRE(b->vgen_b->guidance != nullptr);
|
||||
CHECK_EQ(b->vgen_b->guidance[0], 3.0f);
|
||||
CHECK_EQ(b->vgen_b->guidance[4], 7.0f);
|
||||
CHECK_OK(f.drv.done());
|
||||
|
||||
/* Both scales 1: no unconditional branch, so no negative prompt. */
|
||||
VideoFixture g;
|
||||
g.build();
|
||||
g.prog.video_gen = d;
|
||||
CHECK_OK(g.start());
|
||||
auto u = g.req(1, 3);
|
||||
u->neg_tokens = { 9 };
|
||||
u->guidance[0] = 1.0;
|
||||
u->guidance[4] = 1.0;
|
||||
CHECK_OK(g.drv.submit(std::move(u), &why));
|
||||
b = g.drv.next(0);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
|
||||
CHECK_EQ(b->n_tok, (int64_t)3);
|
||||
CHECK_EQ(b->n_seq, 1);
|
||||
CHECK_EQ(b->vgen_b->n_neg, 0);
|
||||
|
||||
/* A guided request with no negative prompt cannot run; an unguided model takes no terms. */
|
||||
auto m = g.req(1, 3);
|
||||
why.clear();
|
||||
CHECK_EQ(g.drv.submit(std::move(m), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "negative prompt"));
|
||||
VideoFixture h;
|
||||
h.build();
|
||||
CHECK_OK(h.start());
|
||||
auto q = h.req(1, 3);
|
||||
q->guidance[2] = 2.0;
|
||||
why.clear();
|
||||
CHECK_EQ(h.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "no guidance"));
|
||||
}
|
||||
|
||||
/* A first frame reaches the VCOND pass as bf16 x / 255 * 2 - 1 at the size the first steps run
|
||||
* at, and every pass of the request says it has one; a model without image conditioning, or a
|
||||
* frame of another size, is refused. */
|
||||
TEST(a_first_frame_reaches_the_prompt_pass_at_the_first_steps_size) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
f.prog.video_gen.image_cond = 1;
|
||||
f.prog.video_gen.upscale_max = 2.0;
|
||||
f.prog.video_gen.upscale_refine = 1;
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(1, 3);
|
||||
r->width = r->height = 64;
|
||||
r->upscale = 2.0;
|
||||
r->image.assign(32 * 32 * 3, 0);
|
||||
r->image[0] = 255;
|
||||
r->image[1] = 128;
|
||||
auto wrong = f.req(1, 3);
|
||||
wrong->image.assign(64 * 32 * 3, 0);
|
||||
wrong->width = wrong->height = 64;
|
||||
wrong->upscale = 2.0;
|
||||
CHECK_EQ(f.drv.submit(std::move(wrong), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "32x32"));
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
|
||||
const RadVideoGenBatch* V = b->vgen_b;
|
||||
REQUIRE(V->image != nullptr);
|
||||
CHECK_EQ(V->has_image, 1);
|
||||
CHECK_EQ(V->image[0], rad_f32_to_bf16(1.0f));
|
||||
CHECK_EQ(V->image[1], rad_f32_to_bf16(2.0f * (128.0f / 255.0f) - 1.0f));
|
||||
CHECK_EQ(V->image[2], rad_f32_to_bf16(-1.0f));
|
||||
CHECK_OK(f.drv.done());
|
||||
b = f.drv.next(1);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
|
||||
CHECK(b->vgen_b->image == nullptr);
|
||||
CHECK_EQ(b->vgen_b->has_image, 1);
|
||||
|
||||
VideoFixture g;
|
||||
g.build();
|
||||
CHECK_OK(g.start());
|
||||
auto q = g.req(1, 3);
|
||||
q->image.assign(64 * 32 * 3, 0);
|
||||
why.clear();
|
||||
CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "picture"));
|
||||
}
|
||||
|
||||
/* A left-padded encoder's prompt ends at text_left_pad - 1, the negative prompt too; one stream of
|
||||
* soundtrack rows a latent; an exact upscaler takes its factor only, over sides it divides. */
|
||||
TEST(left_padded_prompts_one_audio_stream_and_an_exact_upscaler) {
|
||||
VideoFixture f;
|
||||
f.build();
|
||||
RadVideoGenDecl& d = f.prog.video_gen;
|
||||
d.guidance = 1;
|
||||
d.guidance_default[0] = 3.0;
|
||||
d.guidance_default[4] = 1.0;
|
||||
d.text_left_pad = 8;
|
||||
d.audio_streams = 1;
|
||||
d.upscale_max = 2.0;
|
||||
d.upscale_refine = 1;
|
||||
d.upscale_exact = 1;
|
||||
g_audio_streams = 1;
|
||||
CHECK_OK(f.start());
|
||||
std::string why;
|
||||
auto r = f.req(1, 3);
|
||||
r->neg_tokens = { 9, 8 };
|
||||
CHECK_OK(f.drv.submit(std::move(r), &why));
|
||||
const RadBatch* b = f.drv.next(0);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
|
||||
CHECK(std::vector<int32_t>(b->positions, b->positions + 5) ==
|
||||
std::vector<int32_t>({ 5, 6, 7, 6, 7 }));
|
||||
CHECK_OK(f.drv.done());
|
||||
b = f.drv.next(1);
|
||||
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
|
||||
/* 3 text rows, 30 soundtrack latents in one stream, 2 x 2 video patches. */
|
||||
CHECK_EQ(b->n_tok, (int64_t)(3 + 30 + 2 * 2));
|
||||
/* The soundtrack as a (30, 1, 1) volume; the video's rows cut at its first latent frame. */
|
||||
const int32_t* gd = b->vgen_b->geom_d;
|
||||
CHECK(std::vector<int32_t>(gd + RAD_VGEOM_AUDIO_VOL, gd + RAD_VGEOM_AUDIO_VOL + 3) ==
|
||||
std::vector<int32_t>({ 30, 1, 1 }));
|
||||
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU], 0);
|
||||
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 2], 4);
|
||||
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 1] * gd[RAD_VGEOM_LAT_FRAMES], 4);
|
||||
CHECK_OK(f.drv.done());
|
||||
|
||||
auto u = f.req(1, 3);
|
||||
u->width = 64;
|
||||
u->height = 32;
|
||||
u->upscale = 2.0;
|
||||
u->neg_tokens = { 9 };
|
||||
why.clear();
|
||||
CHECK_EQ(f.drv.submit(std::move(u), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "multiples of 64"));
|
||||
auto v = f.req(1, 3);
|
||||
v->width = v->height = 64;
|
||||
v->upscale = 1.5;
|
||||
v->neg_tokens = { 9 };
|
||||
why.clear();
|
||||
CHECK_EQ(f.drv.submit(std::move(v), &why), (int)RAD_E_INVAL);
|
||||
CHECK(has(why, "exactly 2"));
|
||||
g_audio_streams = 2;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
+222
-3
@@ -10,6 +10,7 @@
|
||||
#include "server_fakes.h"
|
||||
|
||||
#include "gen/video.h"
|
||||
#include "mm/media.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
@@ -70,6 +71,13 @@ struct FakeVideoGen : IVideoGen {
|
||||
t.refine = r->refine > 0 ? r->refine : (int32_t)inf.upscale_refine;
|
||||
}
|
||||
if (finish_status == RAD_OK) {
|
||||
/* A request that named no length learns the one the model chose first. */
|
||||
if (r->chunks == 0) {
|
||||
gen::VideoEvent l;
|
||||
l.kind = gen::VideoEvent::LENGTH;
|
||||
l.n = 3;
|
||||
t.push(std::move(l));
|
||||
}
|
||||
for (int s = 1; s <= 2; ++s) {
|
||||
gen::VideoEvent e;
|
||||
e.kind = gen::VideoEvent::STEP;
|
||||
@@ -158,9 +166,10 @@ TEST(a_video_request_that_cannot_be_served_names_its_field) {
|
||||
std::string("input_reference"));
|
||||
/* `format` is a known field; a container it does not write names the field. */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "format", "avi" } })), std::string("format"));
|
||||
/* fl2va is a valid task, but one that promises a first frame -- refused naming the missing
|
||||
* part, not the task. */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "task", "fl2va" } })), std::string("first_frame"));
|
||||
/* The keyframe tasks belong to a model with a video encoder; this one has none, so the name
|
||||
* is refused as a task. A model that encodes accepts it and is refused naming the missing
|
||||
* part instead (a_keyframe_task_refuses_a_missing_frame). */
|
||||
CHECK_EQ(v.refused(Videos::body({ { "task", "fl2va" } })), std::string("task"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "conditions", json::array({ json::object() }) } })),
|
||||
std::string("conditions"));
|
||||
/* The shift: (0, 100], a number; 0 / negative / over the cap / non-numeric are refused. */
|
||||
@@ -248,6 +257,57 @@ TEST(the_shift_threads_to_the_request_and_echoes) {
|
||||
v.wait(str_at(o, "id"));
|
||||
}
|
||||
|
||||
/* A model with a length head chooses the length of a request that names none or says "auto": the
|
||||
* generator gets 0 chunks, the video object says "auto" until the model has chosen and then the
|
||||
* length chosen. A length named is as for any model; without a head, none named is the default. */
|
||||
TEST(a_length_head_chooses_the_length_of_a_request_that_names_none) {
|
||||
Videos v;
|
||||
HttpResponse r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().chunks, 7);
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
|
||||
v.gen.inf.length_head = true;
|
||||
for (const json& b : { Videos::body(), Videos::body({ { "seconds", "auto" } }) }) {
|
||||
r = v.create(b);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().chunks, 0);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(str_at(o, "seconds"), std::string("auto"));
|
||||
o = v.wait(str_at(o, "id"));
|
||||
CHECK_EQ(str_at(o, "status"), std::string("completed"));
|
||||
CHECK_EQ(str_at(o, "seconds"), std::string("0.12")); /* 3 frames at 24 a second */
|
||||
}
|
||||
r = v.create(Videos::body({ { "seconds", "8" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().chunks, 11);
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
}
|
||||
|
||||
/* A model with more than one decoder takes `decoder` by name, the default first: the generator gets
|
||||
* its index, the video object names a decoder other than the default, an unknown name or a frame
|
||||
* over the decoder's area is a 400 naming the field. A model with one decoder takes no name. */
|
||||
TEST(a_decoder_is_named_and_held_to_its_area) {
|
||||
Videos v;
|
||||
CHECK_EQ(v.refused(Videos::body({ { "decoder", "vae" } })), std::string("decoder"));
|
||||
v.gen.inf.decoders = { "vae", "diffusion" };
|
||||
v.gen.inf.decoder_max_area = { 1344 * 768, 512 * 256 };
|
||||
HttpResponse r = v.create(Videos::body({ { "decoder", "diffusion" }, { "size", "512x256" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().decoder, 1);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(str_at(o, "decoder"), std::string("diffusion"));
|
||||
v.wait(str_at(o, "id"));
|
||||
r = v.create(Videos::body({ { "decoder", "vae" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().decoder, 0);
|
||||
CHECK(!json::parse(r.body, nullptr, false).contains("decoder"));
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "decoder", "magic" } })), std::string("decoder"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "decoder", "diffusion" }, { "size", "768x512" } })),
|
||||
std::string("decoder"));
|
||||
}
|
||||
|
||||
/* Latent upscaling: refused by a model without an upscaler; with one, the factor and the refine
|
||||
* steps reach the generator, a factor of 1 is none, and the refine steps need a factor. */
|
||||
TEST(latent_upscale_reaches_the_generator_where_the_model_has_an_upscaler) {
|
||||
@@ -792,4 +852,163 @@ TEST(ref2va_requests_are_refused_naming_the_part) {
|
||||
CHECK_EQ(c["video_max_text"], 64);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* A PNG of w x h, every pixel (r, g, b). */
|
||||
std::string png_rgb(int32_t w, int32_t h, uint8_t r, uint8_t g, uint8_t b) {
|
||||
std::vector<uint8_t> px;
|
||||
for (int64_t i = 0; i < (int64_t)w * h; ++i) px.insert(px.end(), { r, g, b });
|
||||
std::vector<uint8_t> file;
|
||||
std::string why;
|
||||
if (mm::encode_image(px.data(), w, h, 3, "png", 0, &file, &why) < 0) return std::string();
|
||||
return std::string(file.begin(), file.end());
|
||||
}
|
||||
|
||||
std::string png_url(const std::string& bytes) {
|
||||
return "data:image/png;base64," + base64_encode(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
/* A guided model that starts from a picture, as LTX-2.5's dev weights. */
|
||||
void guided(Videos& v, int32_t crf) {
|
||||
VideoGenInfo& in = v.gen.inf;
|
||||
in.guidance = true;
|
||||
const double d[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 };
|
||||
std::copy(d, d + 8, in.guidance_default);
|
||||
in.default_negative = "ugly";
|
||||
in.image_cond = true;
|
||||
in.image_crf = crf;
|
||||
in.step_evals = true;
|
||||
in.upscale_max = 2.0;
|
||||
in.upscale_refine = 3;
|
||||
}
|
||||
|
||||
std::string text_of(const std::vector<int32_t>& ids) {
|
||||
std::string s;
|
||||
for (int32_t c : ids) s += (char)c;
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* Guidance terms and the negative prompt: refused by a model without guidance; on a guided one the
|
||||
* named terms reach the generator (the rest NaN, the model's default), the negative prompt is
|
||||
* rendered in the template (the model's own when none is named), and the video object reports the
|
||||
* resolved terms. Steps count evaluations there, from 1. */
|
||||
TEST(guidance_and_the_negative_prompt_reach_a_guided_model) {
|
||||
{
|
||||
Videos v;
|
||||
CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", "x" } })),
|
||||
std::string("negative_prompt"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "stg_scale", 1 } })), std::string("stg_scale"));
|
||||
}
|
||||
Videos v;
|
||||
guided(v, 0);
|
||||
CHECK_EQ(v.refused(Videos::body({ { "guidance_rescale", 1.5 } })),
|
||||
std::string("guidance_rescale"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "audio_guidance_scale", -1 } })),
|
||||
std::string("audio_guidance_scale"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", 3 } })), std::string("negative_prompt"));
|
||||
HttpResponse r = v.create(Videos::body({ { "guidance_scale", 5 }, { "audio_stg_scale", "0" },
|
||||
{ "negative_prompt", "blurry" },
|
||||
{ "num_inference_steps", 1 } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& q = v.gen.last();
|
||||
CHECK_EQ(q.guidance[0], 5.0);
|
||||
CHECK_EQ(q.guidance[5], 0.0);
|
||||
CHECK(std::isnan(q.guidance[1]) && std::isnan(q.guidance[4]));
|
||||
CHECK(q.has_neg);
|
||||
CHECK_EQ(text_of(q.neg_tokens), std::string("<v>blurry"));
|
||||
CHECK_EQ(q.steps, 1);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK_EQ(o["guidance_scale"].get<double>(), 5.0);
|
||||
CHECK_EQ(o["guidance_rescale"].get<double>(), 0.7);
|
||||
CHECK_EQ(o["audio_guidance_scale"].get<double>(), 7.0);
|
||||
CHECK_EQ(str_at(o, "negative_prompt"), std::string("blurry"));
|
||||
v.wait(str_at(o, "id"));
|
||||
|
||||
r = v.create(Videos::body());
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK(!v.gen.last().has_neg);
|
||||
CHECK_EQ(text_of(v.gen.last().neg_tokens), std::string("<v>ugly"));
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
|
||||
/* Both scales 1: unguided, so the object names no negative prompt. */
|
||||
r = v.create(Videos::body({ { "guidance_scale", 1 }, { "audio_guidance_scale", 1 } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
o = json::parse(r.body, nullptr, false);
|
||||
CHECK(!o.contains("negative_prompt"));
|
||||
v.wait(str_at(o, "id"));
|
||||
}
|
||||
|
||||
/* input_reference: refused by a text-only model; on a model that starts from a picture, a data URL
|
||||
* in JSON or a file in a form becomes the first frame at the size the first steps run at (the
|
||||
* small size under latent upscaling), an even colour staying that colour; task i2va goes with it. */
|
||||
TEST(input_reference_becomes_the_first_frame_at_the_first_steps_size) {
|
||||
const std::string pic = png_rgb(300, 170, 200, 40, 90);
|
||||
{
|
||||
Videos v;
|
||||
CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) } })),
|
||||
std::string("input_reference"));
|
||||
}
|
||||
Videos v;
|
||||
guided(v, 0);
|
||||
CHECK_EQ(v.refused(Videos::body({ { "input_reference", "data:image/png;base64,AAAA" } })),
|
||||
std::string("input_reference"));
|
||||
CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) }, { "task", "t2va" } })),
|
||||
std::string("task"));
|
||||
HttpResponse r = v.create(Videos::body({ { "input_reference", { { "image_url", png_url(pic) } } },
|
||||
{ "task", "i2va" } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& q = v.gen.last();
|
||||
REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3);
|
||||
CHECK_EQ((int)q.image[0], 200);
|
||||
CHECK_EQ((int)q.image[1], 40);
|
||||
CHECK_EQ((int)q.image[q.image.size() - 1], 90);
|
||||
json o = json::parse(r.body, nullptr, false);
|
||||
CHECK(o.value("input_reference", false));
|
||||
v.wait(str_at(o, "id"));
|
||||
|
||||
r = v.create(Videos::body({ { "input_reference", png_url(pic) }, { "size", "512x512" },
|
||||
{ "latent_upscale", 2 } }));
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().image.size(), (size_t)256 * 256 * 3);
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
|
||||
HttpRequest f;
|
||||
f.method = "POST";
|
||||
f.path = "/v1/videos";
|
||||
f.form = { FormPart{ "prompt", "", "", "a boat" }, FormPart{ "size", "", "", "512x256" },
|
||||
FormPart{ "input_reference", "boat.png", "image/png", pic } };
|
||||
r = v.f->srv->router().dispatch(f);
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
CHECK_EQ(v.gen.last().image.size(), (size_t)512 * 256 * 3);
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
}
|
||||
|
||||
/* With the model's H.264 quality the picture goes through the round trip first: an even colour
|
||||
* comes back within a few levels (yuv420p's rounding), an odd size losing its last column. */
|
||||
TEST(input_reference_takes_the_models_h264_round_trip) {
|
||||
Videos v;
|
||||
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 */
|
||||
REQUIRE_EQ(r.status, 200);
|
||||
const gen::VideoRequest& q = v.gen.last();
|
||||
REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3);
|
||||
const int want[3] = { 200, 40, 90 };
|
||||
for (size_t i = 0; i < q.image.size(); i += 997)
|
||||
CHECK(std::abs((int)q.image[i] - want[i % 3]) <= 3);
|
||||
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
|
||||
|
||||
mm::Frame in, out;
|
||||
in.w = 7;
|
||||
in.h = 5;
|
||||
in.rgb.assign(7 * 5 * 3, 128);
|
||||
std::string why;
|
||||
REQUIRE_EQ(mm::h264_roundtrip(in, 18, &out, &why), (int)RAD_OK);
|
||||
CHECK_EQ(out.w, 6);
|
||||
CHECK_EQ(out.h, 4);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
Reference in new issue
Block a user