radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
# One executable per *_test.cpp, globbed, so adding a test is adding a file.
#
# arch_test is the exception and says why in its own header: "No GPU, no model file, no core." It
# supplies its OWN implementation of the declare-phase C ABI -- a recording fake -- so that a
# plugin cannot pass only against core/build/'s builder, which would be an undeclared dependency.
# Linking rad_core would put a second definition of every rad_decl_* symbol in the link, so it
# gets the two utility translation units it actually needs and nothing else.
#
# The failure mode this avoids is worth naming, because it is not obvious from the error: a static
# archive only yields an object file that resolves an undefined symbol, so the clash appears the
# moment the ABI grows a call the fake has not implemented yet. The linker pulls rad_builder.cpp.o
# to satisfy that one symbol and every other rad_decl_* in it collides. Adding the call to the fake
# is the real fix; not linking the archive is what stops the next one presenting as a wall of
# duplicate-definition errors instead of one honest "undefined reference".
set(RAD_TESTS_NO_CORE arch_test)
# fixture_test is about tools/kfixture.cpp and tools/opshapes.cpp -- the seeded draw, the
# reduction and the on-disk recording that every kernel correctness number in the project is
# relative to. Those two are compiled into each tool rather than made a library (tools/
# CMakeLists.txt says why), so a test of them compiles them too. The alternative is a test that
# shells out to rad-kbench, which can only observe the harness through whatever a kernel run says
# about it -- and the properties worth pinning here are ones a passing run is equally consistent
# with.
set(RAD_TESTS_WITH_TOOLS fixture_test)
# The tokenizer tests compare the encoder against tools/tokref, the reference encoder, which is a
# library of its own for exactly that (tools/CMakeLists.txt).
set(RAD_TESTS_WITH_TOKREF tokenizer_test tokenizer_perf_test)
# The GBNF oracle is upstream's candidate walk, which the mask engine is held to bit for bit. It is
# test code and is compiled into the tests that compare against it -- and into rad-gbnf-check,
# which runs the same comparison on a real vocabulary -- so that no serving binary contains it.
set(RAD_TESTS_WITH_GBNF_ORACLE sample_test gbnf_test)
# THE LEGACY REPLY PARSER, AS AN ORACLE. The engine reads replies with core/text/chatparse.h; a
# whole-reply path built on llama.cpp's PEG parser and a by-hand call lifter is kept in legacy/ so
# that the tests can compare the two on every input. Built as its own archive and linked into the
# tests that compare -- nothing in core/ can reach it. tools/ links it for the acceptance tool's
# side-by-side numbers.
add_library(rad_legacy_toolparse STATIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy/toolparse_legacy.cpp
${CMAKE_CURRENT_SOURCE_DIR}/legacy/chatdiff.cpp)
target_link_libraries(rad_legacy_toolparse PUBLIC rad_core)
target_include_directories(rad_legacy_toolparse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy)
set(RAD_TESTS_WITH_LEGACY chatparse_test)
# relayout_parity_test holds each kernel library's relayout of libquant's planes to the recorded
# hash of the bytes that library stores. libr4d needs a HIP toolchain to build and its layouts do
# not, so the test compiles their host sources in -- -ffp-contract=off, as libr4d compiles every
# unit, so a scale converted on the way through rounds here as it does in the plugin.
set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test)
# The chat templates the reply-format tests render through, copied from the model repositories,
# and the media samples the decoder is held to. Passed by path so a test binary run from anywhere
# finds them.
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
set(RAD_MEDIA_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/media)
file(GLOB RAD_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*_test.cpp)
foreach(t ${RAD_TESTS})
get_filename_component(n ${t} NAME_WE)
if(n IN_LIST RAD_TESTS_NO_CORE)
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/core/util/rad_util.cpp)
elseif(n IN_LIST RAD_TESTS_WITH_TOKREF)
add_executable(${n} ${t})
target_link_libraries(${n} PRIVATE rad_tokref rad_core)
elseif(n IN_LIST RAD_TESTS_WITH_TOOLS)
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/tools/kfixture.cpp
${CMAKE_SOURCE_DIR}/tools/opshapes.cpp)
target_link_libraries(${n} PRIVATE rad_core)
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
elseif(n IN_LIST RAD_TESTS_WITH_R4D_HOST)
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/libr4d/r4d_layout.cpp
${CMAKE_SOURCE_DIR}/libr4d/r4d_fp8_layout.cpp)
target_link_libraries(${n} PRIVATE rad_core ${CMAKE_DL_LIBS})
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d)
target_compile_options(${n} PRIVATE -ffp-contract=off)
elseif(n IN_LIST RAD_TESTS_WITH_GBNF_ORACLE)
add_executable(${n} ${t} ${CMAKE_CURRENT_SOURCE_DIR}/gbnf_oracle.cpp)
target_link_libraries(${n} PRIVATE rad_core)
# The chat templates whose tool-call grammars the engine is held to the oracle on. Checked
# in, because a template is a few kilobytes and the tokenizer beside it is not.
target_compile_definitions(${n} PRIVATE
RAD_GBNF_TEST_DATA="${CMAKE_CURRENT_SOURCE_DIR}/data/gbnf")
else()
add_executable(${n} ${t})
target_link_libraries(${n} PRIVATE rad_core)
endif()
if(n IN_LIST RAD_TESTS_WITH_LEGACY)
target_link_libraries(${n} PRIVATE rad_legacy_toolparse)
endif()
target_compile_definitions(${n} PRIVATE RAD_CHAT_FIXTURES="${RAD_CHAT_FIXTURES}"
RAD_MEDIA_FIXTURES="${RAD_MEDIA_FIXTURES}")
# include/ normally arrives through rad_core's PUBLIC interface; a test that does not link it
# still needs the ABI headers, since that is the whole surface it is testing against.
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi
${CMAKE_BINARY_DIR}/rad_include)
set_target_properties(${n} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
# The tier transfer test loads a kernel plugin that waits on a stream through the device API, so
# the executable exports it the way the engine binary does for its plugins.
if(n STREQUAL "mem_test")
set_target_properties(${n} PROPERTIES ENABLE_EXPORTS ON)
endif()
add_test(NAME ${n} COMMAND ${n})
# AND mem_test NEEDS THE CARD TO ITSELF, which nothing about its name says. The KV pool is
# elastic on every run, so Pools::configure reserves and commits through the driver whatever
# allocators the fixture injects -- the host-allocator seam is real for the weight pool and
# dead for this one. Beside a server holding the card the pool cannot be backed and the whole
# file fails with "the card would not back it", which reads as a regression and is contention.
# The `gpu` label is how the rest of the tree already says that, and `ctest -LE gpu` still runs
# everything else on a machine that is busy.
if(${n} STREQUAL "mem_test")
set_tests_properties(${n} PROPERTIES LABELS "gpu")
endif()
# A TEST THAT SKIPPED IS NOT A TEST THAT PASSED, and a test that FAILED must not read as one
# either. Several files here guard cases on a model file, a vocabulary or a backend and print a
# " SKIP " line when it is absent; ctest swallows output on success, so without a skip signal
# those cases report Passed having asserted nothing.
#
# SKIP_REGULAR_EXPRESSION cannot be that signal. CMake evaluates it BEFORE the return code, so a
# binary that prints one skip line and then fails is reported Skipped and counted toward "100%
# tests passed" -- and a partly-skipped binary is exactly the one that prints skip lines.
#
# So the skip signal is the RETURN CODE, and rad_test.h derives it rather than declaring it:
# every CHECK increments a counter and main returns 77 only when nothing failed and nothing was
# checked at all. A file where some cases ran and others skipped passes on the ones that ran,
# which is the honest answer, and a failure anywhere is a failure.
set_tests_properties(${n} PROPERTIES SKIP_RETURN_CODE 77)
set_tests_properties(${n} PROPERTIES ENVIRONMENT
"RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
endforeach()
# ================================================================== the device selftest
#
# r4d_selftest IS THE ONLY THING THAT CHECKS THE FUSION CLAIMS, so it is a registered test.
#
# Sixteen rows in libr4d's registry say things like "byte-identical to the two ops it replaces",
# and that claim is what makes a fused kernel SUBSTITUTABLE rather than a second numerical path --
# it is the difference between a fusion and a fork. Six of those claims are verified, by memcmp,
# against the unfused kernels run on the same inputs. Every one of those verifications lives in
# r4d_selftest.cpp, which libr4d/CMakeLists.txt builds; a binary built and registered with nothing
# leaves `ctest` green without executing a single one of them.
#
# It needs a card, so it is guarded on the HIP backend; it forks a child per row and takes about
# two minutes, against 1.2 seconds for everything else, so it carries a `slow` label and
# `ctest -LE slow` is the fast inner loop. The default `ctest` runs it.
if(RAD_HIP_FOUND AND TARGET r4d_selftest)
add_test(NAME r4d_selftest
COMMAND r4d_selftest ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
set_tests_properties(r4d_selftest PROPERTIES
LABELS "slow;gpu"
TIMEOUT 900
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
endif()
# ================================================================== the host kernels
#
# rad-avx-check holds libavx to libref, op for op and at every ISA level the machine executes, and
# runs embed_lookup_q over a file-backed table with two ranks and the read-ahead racing: the path a
# model's host gather takes and that no geometry reaches. It writes its table beside itself, since
# the gather reads with O_DIRECT and a tmpfs refuses it.
if(TARGET libavx AND TARGET rad-avx-check)
add_test(NAME avx_check
COMMAND rad-avx-check --ref ${RAD_PLUGIN_OUT}/kernels/libref.so
--avx ${RAD_PLUGIN_OUT}/kernels/libavx.so)
set_tests_properties(avx_check PROPERTIES TIMEOUT 600)
endif()
# ================================================================== the document as a test
#
# docs/OPS.md calls its resolved table "THE AUTHORITY FOR THE OPS IN IT" and says of itself that
# ref's op list is the conventional vocabulary and this file is that list. A hand-maintained table
# drifts from the registries -- dropped optional operands, a missing `:inout`, parameters that
# have moved into the `params` operand, a parameter no plugin declares -- so this test holds the
# document to what the plugins dump.
#
# The cost is named in OPS.md itself: a header written against a GUESS at a schema the document
# omits gets the schema wrong. A document that is WRONG is worse than one that is missing, because
# it is read instead of the source.
#
# It is cheap (a dlopen and an awk pass) so it carries no label and runs in the default ctest.
# libref alone would catch most of it; libr4d.so is added when there is a card to load it, and
# the script reports " SKIP " rather than green when a plugin will not dump.
set(RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libref.so)
if(RAD_HIP_FOUND AND TARGET libr4d)
list(APPEND RAD_OPSDOC_PLUGINS ${RAD_PLUGIN_OUT}/kernels/libr4d.so)
endif()
add_test(NAME ops_doc
COMMAND ${CMAKE_SOURCE_DIR}/tools/ops_doc_check.sh
${CMAKE_SOURCE_DIR}/docs/OPS.md $<TARGET_FILE:rad-schemas>
${RAD_OPSDOC_PLUGINS})
set_tests_properties(ops_doc PROPERTIES SKIP_RETURN_CODE 77)
# ================================================================== the shipped plugins, out of tree
#
# Every plugin radiance ships is a plugin like any other, and this is what holds that to be true:
# the build is installed into a prefix, every plugin directory is configured ON ITS OWN against it
# with find_package(radiance), built and installed into a home of its own, and the result has to
# hold the same plugins, declare the same vocabulary and register the same way as the tree's build
# -- then serve rad-kbench's fixture from that home through the installed tools
# (tests/oot_plugins.sh). A first-party plugin that quietly depended on being built in the tree
# fails here; so does an installed package a third party could not build against.
#
# libr4d is included where the tree built it: the same HIP compiler, its own targets. Labelled
# `oot` because it rebuilds every plugin, which is minutes, not seconds.
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}")
endif()
add_test(NAME oot_plugins
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP})
set_tests_properties(oot_plugins PROPERTIES LABELS "oot" TIMEOUT 3600
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR}")
# ================================================================== the kernel library, as a test
#
# rad-kbench replaying data/kernels.rkb: every kernel every loaded library supplies, run against
# libref's recorded answers on seeded inputs, inside guarded allocations. No model, no oracle at
# run time, no network -- the fixture is checked in.
#
# r4d_selftest checks what its author wrote down and is compiled by the plugin; rad-kbench checks
# every row in every registry against an independent implementation, and the checked-in fixture
# lets it run without a model container.
#
# NOT GATED ON A CARD, because the reference library is under test in a replay too. The answers
# in the fixture were recorded by libref and checked in, so libref against them is a real
# comparison and the only regression test the oracle has -- which matters more than it sounds,
# since every correctness number this project reports about any kernel is defined relative to
# libref. It also means a build machine with no card still checks something, and a host
# implementation is exactly what regresses there.
#
# SLOW: libref is a straight-loop host implementation, so a full replay is minutes rather than the
# seconds the device libraries take. `ctest -LE slow` is the fast inner loop, as it is for
# r4d_selftest. `gpu` is added only where there is one, so `ctest -LE gpu` on a build machine
# still runs this.
#
# `--max-cases 1` because a fixture recorded at max-cases 1 has one case per point already and
# the cap is then only a guard against a future fixture that does not.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels.rkb)
add_test(NAME kbench
COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --max-cases 1)
set(RAD_KBENCH_LABELS "slow")
if(RAD_HIP_FOUND AND TARGET libr4d)
set(RAD_KBENCH_LABELS "slow;gpu")
endif()
# RESOURCE_LOCK, because the case budget each of these takes is a fraction of what the machine
# has FREE at the moment it starts. Two replays launched together both read the same number and
# both take their share of it, so the pair arrives at the total the budget exists to stay under.
# They also thrash a shared last-level cache against each other, which makes --bench meaningless.
set_tests_properties(kbench PROPERTIES
LABELS "${RAD_KBENCH_LABELS}"
TIMEOUT 1800
RESOURCE_LOCK kbench_memory
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT}")
endif()
# The same replay over the ROUTED fixture. A recording is of one container and no container in
# scope declares the whole vocabulary, so the MoE ops, the gqa 8 attention dispatch and the MTP
# head have no coverage in data/kernels.rkb at all -- see the note beside it in the root
# CMakeLists. Two tests rather than one merged fixture because a fixture names the container it
# was recorded from, and merging two would make that field a lie.
if(TARGET rad-kbench AND EXISTS ${CMAKE_SOURCE_DIR}/data/kernels_moe.rkb)
add_test(NAME kbench_moe
COMMAND rad-kbench --home ${RAD_PLUGIN_OUT} --max-cases 1
--fixture ${RAD_PLUGIN_OUT}/kernels_moe.rkb)
set_tests_properties(kbench_moe PROPERTIES
LABELS "${RAD_KBENCH_LABELS}"
TIMEOUT 1800
RESOURCE_LOCK kbench_memory
ENVIRONMENT "RADIANCE_HOME=${RAD_PLUGIN_OUT}")
endif()
+2208
View File
File diff suppressed because it is too large. Load diff
+1270
View File
File diff suppressed because it is too large. Load diff
+1029
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+305
View File
@@ -0,0 +1,305 @@
/* checkpoint_test.cpp -- a checkpoint as a source of logical weights (core/format/checkpoint.h).
*
* rad-convert writes a container from a checkpoint and the loader serves a trivial one directly,
* and both go through ckpt_resolve: which tensors make a declared weight, what encoding they
* already are, and the rows of it. A wrong answer there is a model that loads and is wrong -- an
* expert that is every expert, a scale applied to the next piece's rows -- so each case below is
* one of the ways a checkpoint is laid out in practice, built small and read back.
*/
#include "rad_test.h"
#include "format/checkpoint.h"
#include "rad_plugin.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
using namespace rad;
namespace {
struct T {
std::string name, dtype; /* safetensors spelling: BF16, F32, F8_E4M3 */
std::vector<int64_t> shape;
std::vector<uint8_t> bytes;
};
std::string dir_path() {
const char* d = std::getenv("TMPDIR");
return std::string(d && *d ? d : "/tmp") + "/radiance_checkpoint_test_" +
std::to_string((long long)getpid());
}
/* One model.safetensors and a config.json in a fresh directory. */
std::string write_checkpoint(const std::vector<T>& ts, const std::string& config) {
const std::string dir = dir_path();
::mkdir(dir.c_str(), 0755);
std::string hdr = "{";
uint64_t off = 0;
for (size_t i = 0; i < ts.size(); ++i) {
std::string shape;
for (size_t k = 0; k < ts[i].shape.size(); ++k)
shape += (k ? "," : "") + std::to_string(ts[i].shape[k]);
hdr += (i ? "," : "") + std::string("\"") + ts[i].name + "\":{\"dtype\":\"" + ts[i].dtype +
"\",\"shape\":[" + shape + "],\"data_offsets\":[" + std::to_string(off) + "," +
std::to_string(off + ts[i].bytes.size()) + "]}";
off += ts[i].bytes.size();
}
hdr += "}";
while (hdr.size() % 8) hdr += ' ';
FILE* f = std::fopen((dir + "/model.safetensors").c_str(), "wb");
const uint64_t n = hdr.size();
std::fwrite(&n, 8, 1, f);
std::fwrite(hdr.data(), 1, hdr.size(), f);
for (const T& t : ts) std::fwrite(t.bytes.data(), 1, t.bytes.size(), f);
std::fclose(f);
f = std::fopen((dir + "/config.json").c_str(), "wb");
std::fwrite(config.data(), 1, config.size(), f);
std::fclose(f);
return dir;
}
void remove_checkpoint(const std::string& dir) {
std::remove((dir + "/model.safetensors").c_str());
std::remove((dir + "/config.json").c_str());
::rmdir(dir.c_str());
}
/* Element i of a tensor is a value that names it: tensor tag + i/1000, exact in bf16 for small i. */
T bf16(const std::string& name, std::vector<int64_t> shape, float tag) {
T t{ name, "BF16", shape, {} };
int64_t n = 1;
for (int64_t s : shape) n *= s;
t.bytes.resize((size_t)n * 2);
for (int64_t i = 0; i < n; ++i) rad_store_f32(t.bytes.data(), RAD_BF16, i, tag + (float)(i % 64));
return t;
}
T fp8(const std::string& name, std::vector<int64_t> shape) {
T t{ name, "F8_E4M3", shape, {} };
int64_t n = 1;
for (int64_t s : shape) n *= s;
t.bytes.resize((size_t)n);
for (int64_t i = 0; i < n; ++i) rad_store_f32(t.bytes.data(), RAD_F8E4M3, i, (float)(i % 7) - 3.0f);
return t;
}
RadNameMap map(const char* declared, int mode, std::vector<const char*> src,
std::vector<int> index = {}, int concat_dim = 0) {
RadNameMap m{};
m.declared = declared;
m.mode = mode;
m.n_src = (int)src.size();
m.concat_dim = concat_dim;
for (int i = 0; i < 8; ++i) m.src_index[i] = -1;
for (size_t i = 0; i < src.size(); ++i) m.src[i] = src[i];
for (size_t i = 0; i < index.size(); ++i) m.src_index[i] = index[i];
return m;
}
const char* kConfig =
"{\"model_type\":\"qwen3_5\",\"hidden_size\":256,\"num_hidden_layers\":2,"
"\"quantization_config\":{\"quant_method\":\"fp8\",\"fmt\":\"e4m3\","
"\"weight_block_size\":[128,128]}}";
} /* namespace */
TEST(the_metadata_names_the_architecture_and_the_quantisation) {
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
CHECK_EQ(ck.meta().arch, std::string("qwen35"));
CHECK_EQ(ck.meta().quant, std::string("fp8_e4m3"));
CHECK_EQ(ck.meta().m.n_embd, (int64_t)256);
CHECK_EQ(ck.fp8_block_rows(), (int64_t)128);
CHECK_EQ(ck.dir(), dir);
remove_checkpoint(dir);
}
TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) {
const std::string dir = write_checkpoint({ bf16("a.weight", { 4, 8 }, 1.0f) }, "{}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("a", RAD_MAP_COPY, { "a.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "a", false, &w, &why), RAD_OK);
CHECK(w.trivial);
CHECK(rad_enc_is(&w.enc, "plain"));
CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_BF16);
CHECK_EQ(w.rows, (int64_t)4);
CHECK_EQ(w.cols, (int64_t)8);
std::vector<float> f(8);
REQUIRE_EQ(ckpt_rows_f32(w, 2, 1, f.data(), &why), RAD_OK);
for (int j = 0; j < 8; ++j) CHECK_EQ(f[(size_t)j], 1.0f + (float)((16 + j) % 64));
std::vector<uint8_t> raw(8 * 2);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 2, 1, raw.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(raw.data(), (const uint8_t*)ck.find("a.weight")->data + 32, 16), 0);
remove_checkpoint(dir);
}
/* BLOCK-SCALED FP8 IS ONE WEIGHT OF TWO PLANES, and its value is the code times its block's
* scale -- the scale of the block the element is in, along both axes. */
TEST(block_fp8_is_the_codes_and_their_scale_plane) {
const int64_t N = 256, K = 384;
T s = bf16("p.weight_scale_inv", { 2, 3 }, 0.0f);
for (int i = 0; i < 6; ++i) rad_store_f32(s.bytes.data(), RAD_BF16, i, 0.5f * (float)(i + 1));
const std::string dir = write_checkpoint({ fp8("p.weight", { N, K }), s }, kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK);
REQUIRE(w.trivial);
CHECK(rad_enc_is(&w.enc, "affine"));
REQUIRE_EQ(w.enc.n_planes, 2);
CHECK_EQ(w.enc.plane[1].block[0], (int64_t)128);
CHECK_EQ(w.enc.plane[1].block[1], (int64_t)128);
CHECK(rad_enc_valid(&w.enc));
std::vector<float> f((size_t)(2 * K));
REQUIRE_EQ(ckpt_rows_f32(w, 129, 2, f.data(), &why), RAD_OK);
for (int64_t r = 0; r < 2; ++r)
for (int64_t c : { (int64_t)0, (int64_t)130, (int64_t)383 }) {
const int64_t i = (129 + r) * K + c;
const float code = (float)(i % 7) - 3.0f;
const float scale = 0.5f * (float)(3 + c / 128 + 1); /* block row 1 */
CHECK_EQ(f[(size_t)(r * K + c)], code * scale);
}
std::vector<uint8_t> sp(3 * 2);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 1, 1, sp.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(sp.data(), s.bytes.data() + 6, 6), 0);
remove_checkpoint(dir);
}
/* A FUSION JOINS THE PIECES -- and their scale planes -- along dim 0, and refuses a piece that ends
* inside a scale block, whose scales could not follow it. */
TEST(a_fusion_joins_pieces_and_their_scales) {
const std::string dir = write_checkpoint(
{ fp8("g.weight", { 256, 128 }), bf16("g.weight_scale_inv", { 2, 1 }, 10.0f),
fp8("u.weight", { 128, 128 }), bf16("u.weight_scale_inv", { 1, 1 }, 20.0f),
fp8("odd.weight", { 100, 128 }), bf16("odd.weight_scale_inv", { 1, 1 }, 30.0f) },
kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g.weight", "u.weight" }));
prog.name_map.push_back(map("bad", RAD_MAP_CONCAT, { "odd.weight", "u.weight" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
CHECK(w.trivial);
CHECK_EQ(w.shape[0], (int64_t)384);
std::vector<uint8_t> sp(3 * 2);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 3, sp.data(), &why), RAD_OK);
CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 0), 10.0f);
CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 1), 11.0f);
CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 2), 20.0f);
std::vector<float> f(128);
REQUIRE_EQ(ckpt_rows_f32(w, 300, 1, f.data(), &why), RAD_OK); /* u's row 44, u's scale */
CHECK_EQ(f[5], ((float)((44 * 128 + 5) % 7) - 3.0f) * 20.0f);
REQUIRE_EQ(ckpt_resolve(ck, prog, "bad", false, &w, &why), RAD_OK);
CHECK(!w.trivial);
CHECK(w.why.find("inside a scale block") != std::string::npos);
remove_checkpoint(dir);
}
/* A join along dim 1 interleaves the pieces row by row. */
TEST(a_join_along_columns_interleaves_rows) {
const std::string dir = write_checkpoint({ bf16("l", { 3, 2 }, 0.0f),
bf16("r", { 3, 4 }, 100.0f) }, "{}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("lr", RAD_MAP_CONCAT, { "l", "r" }, {}, 1));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "lr", false, &w, &why), RAD_OK);
CHECK_EQ(w.shape[1], (int64_t)6);
std::vector<float> f(6);
REQUIRE_EQ(ckpt_rows_f32(w, 1, 1, f.data(), &why), RAD_OK);
const float want[6] = { 2, 3, 104, 105, 106, 107 };
for (int j = 0; j < 6; ++j) CHECK_EQ(f[(size_t)j], want[j]);
std::vector<uint8_t> raw(6 * 2);
REQUIRE_EQ(ckpt_plane_rows(w, 0, 2, 1, raw.data(), &why), RAD_OK);
CHECK_EQ(rad_load_f32(raw.data(), RAD_BF16, 0), 4.0f);
CHECK_EQ(rad_load_f32(raw.data(), RAD_BF16, 2), 108.0f);
remove_checkpoint(dir);
}
/* AN EXPERT IS ITS OWN SLICE OF A STACKED TENSOR -- never the whole stack -- and a stacked FP8
* tensor's scales are sliced at the same index. */
TEST(an_expert_is_its_slice_of_a_stack) {
const std::string dir = write_checkpoint(
{ bf16("exps", { 4, 2, 3 }, 0.0f), fp8("q.weight", { 2, 128, 128 }),
bf16("q.weight_scale_inv", { 2, 1, 1 }, 7.0f) }, kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("e2", RAD_MAP_COPY, { "exps" }, { 2 }));
prog.name_map.push_back(map("q1", RAD_MAP_COPY, { "q.weight" }, { 1 }));
prog.name_map.push_back(map("e9", RAD_MAP_COPY, { "exps" }, { 9 }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "e2", false, &w, &why), RAD_OK);
CHECK_EQ(w.rank, 2u);
std::vector<float> f(3);
REQUIRE_EQ(ckpt_rows_f32(w, 1, 1, f.data(), &why), RAD_OK);
CHECK_EQ(f[0], (float)(2 * 6 + 3)); /* stack index 2, row 1, col 0 */
REQUIRE_EQ(ckpt_resolve(ck, prog, "q1", false, &w, &why), RAD_OK);
CHECK(w.trivial);
std::vector<uint8_t> sp(2);
REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 1, sp.data(), &why), RAD_OK);
CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 0), 8.0f); /* the second expert's scale */
CHECK(ckpt_resolve(ck, prog, "e9", false, &w, &why) < 0);
remove_checkpoint(dir);
}
/* A COPY's sources are alternatives, first present wins: a tied head reads the embedding where
* the checkpoint ships no head of its own. */
TEST(alternatives_take_the_first_tensor_present) {
const std::string dir = write_checkpoint({ bf16("embed", { 2, 2 }, 5.0f) }, "{}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("out", RAD_MAP_COPY, { "lm_head", "embed" }));
prog.name_map.push_back(map("need", RAD_MAP_COPY, { "missing" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "out", false, &w, &why), RAD_OK);
REQUIRE_EQ(w.pieces.size(), (size_t)1);
CHECK_EQ(w.pieces[0]->name, std::string("embed"));
CHECK_EQ(ckpt_resolve(ck, prog, "need", false, &w, &why), RAD_E_NOTFOUND);
CHECK(why.find("missing") != std::string::npos);
CHECK_EQ(ckpt_resolve(ck, prog, "need", true, &w, &why), RAD_E_NOTFOUND);
CHECK_EQ(ckpt_resolve(ck, prog, "unmapped", false, &w, &why), RAD_E_NOTFOUND);
remove_checkpoint(dir);
}
/* NOT TRIVIAL, AND SAID WHY: FP8 with no scale beside it, and pieces of different dtypes. */
TEST(what_is_not_served_as_it_is_says_why) {
const std::string dir = write_checkpoint({ fp8("bare", { 128, 128 }),
bf16("b16", { 128, 128 }, 0.0f) }, kConfig);
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
Program prog;
prog.name_map.push_back(map("bare", RAD_MAP_COPY, { "bare" }));
prog.name_map.push_back(map("mixed", RAD_MAP_CONCAT, { "bare", "b16" }));
CkptWeight w;
std::string why;
REQUIRE_EQ(ckpt_resolve(ck, prog, "bare", false, &w, &why), RAD_OK);
CHECK(!w.trivial);
CHECK(w.why.find("no scale plane") != std::string::npos);
REQUIRE_EQ(ckpt_resolve(ck, prog, "mixed", false, &w, &why), RAD_OK);
CHECK(!w.trivial);
remove_checkpoint(dir);
}
RAD_TEST_MAIN()
+539
View File
@@ -0,0 +1,539 @@
/* config_test.cpp -- the command line.
*
* WHAT THIS IS HOLDING DOWN. Every pool in this engine is budgeted explicitly (spec §6), and a
* budget flag is the one kind of input where a typo and a decision look identical downstream:
* nothing after this function can tell "the operator asked for 0.82" from "the operator asked for
* 0.87 and it did not parse". The parser's whole job is to make that distinction at the door --
* to refuse by name rather than to fall through to a default -- and a refusal that stops
* refusing is silent everywhere else.
*
* Three groups of property here, and they fail differently:
*
* TAKEN the value reaches the field an operator thinks it reaches
* REFUSED a value outside the legal set stops the server rather than being rounded into it
* RESOLVED what is left unsaid comes from the environment or from a stated default
*
* No device, no model, no container: argc/argv in, a Config out.
*/
#include "rad_test.h"
#include "rad_core.h"
#include <cstdlib>
#include <cstdio>
#include <string>
#include <unistd.h>
#include <vector>
using namespace rad;
namespace {
/* config_parse takes `char**`, so the argument strings have to be writable. Held by the caller
* for the life of the call, which is what argv is. */
struct Args {
std::vector<std::string> store;
std::vector<char*> argv;
explicit Args(std::initializer_list<const char*> v) {
store.emplace_back("radiance"); /* argv[0], which the parser skips */
for (const char* s : v) store.emplace_back(s);
for (std::string& s : store) argv.push_back(s.data());
}
int argc() const { return (int)argv.size(); }
};
/* Parse, with a model so that the required-argument check is not what every case trips over. */
int parse(std::initializer_list<const char*> v, Config* c) {
std::vector<std::string> store{ "radiance", "--model", "/m/x.rad" };
for (const char* s : v) store.emplace_back(s);
std::vector<char*> argv;
for (std::string& s : store) argv.push_back(s.data());
return config_parse((int)argv.size(), argv.data(), c);
}
/* The level `-v` moves and every other test in this binary reads. */
struct LogGuard {
Log saved = log_level();
~LogGuard() { log_set_level(saved); }
};
} /* namespace */
/* ================================================================== the shape of the call */
TEST(help_is_reported_separately_from_an_error) {
/* 1 rather than a negative: the caller prints usage and exits ZERO. Folding it into the error
* path would make `--help` a failed run in anything scripting the binary. */
Config c;
Args a{ "--help" };
CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), 1);
Args b{ "-h" };
CHECK_EQ(config_parse(b.argc(), b.argv.data(), &c), 1);
/* And it wins from anywhere on the line, including ahead of an otherwise fatal argument. */
Args d{ "--tp", "0", "--help" };
CHECK_EQ(config_parse(d.argc(), d.argv.data(), &c), 1);
}
/* AN UNKNOWN FLAG IS AN ERROR NAMING IT, NOT A WARNING. A typo in a budget flag is the difference
* between the plan you asked for and one the planner invented. */
TEST(an_unknown_option_is_refused) {
Config c;
CHECK_EQ(parse({ "--not-a-flag" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--max-num-seq", "8" }, &c), RAD_E_INVAL); /* near-miss on a real flag */
CHECK_EQ(parse({ "-x" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "positional" }, &c), RAD_E_INVAL);
}
/* A RETIRED FLAG IS REFUSED, NOT ACCEPTED AND IGNORED. Each of these names a decision the engine
* does not take from the operator: the KV cache is elastic on every run and derives its own
* buffer, the activation arena is computed from the buffer plan and charged by name, and a
* finished conversation is copied to host memory and on to disk as soon as it can be rather than
* after an idle time. A command line carrying one expects behaviour the engine does not have, and
* starting it anyway gives an operator a server that is not the one they asked for and no way to
* tell. Refusing names the flag and stops; accepting and warning puts the
* answer in a log nobody reads. */
TEST(a_retired_flag_is_refused) {
Config c;
CHECK_EQ(parse({ "--kv-flex-mib", "512" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--vram-headroom-mib", "2000" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-idle-to-host", "30" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-idle-to-disk", "1800" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-host-cache-mib", "4096" }, &c), RAD_E_INVAL);
}
/* A FLAG WHOSE ARGUMENT IS OFF THE END OF THE LINE. Reading past argv is the failure this
* prevents, and the one shape that reaches it is the flag written last. */
TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) {
Config c;
CHECK_EQ(parse({ "--tp" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--port" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-cache-dtype" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio" }, &c), RAD_E_INVAL);
Args a{ "--model" };
CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), RAD_E_INVAL);
}
/* THE KL MODE TAKES ONE DIRECTION AND WHAT THAT DIRECTION READS. Recording into a directory and
* scoring against one in the same run would leave the engine to guess which the operator meant,
* and guessing wrong makes a quantised model the yardstick. */
TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
Config c;
CHECK_EQ(parse({ "--kld-record", "/r", "--kld-corpus", "/c.jsonl" }, &c), RAD_OK);
CHECK_EQ(c.kld_record, std::string("/r"));
CHECK_EQ(c.kld_corpus, std::string("/c.jsonl"));
CHECK(c.kld());
Config d;
CHECK_EQ(parse({ "--kld-ref", "/r", "--kld-out", "/o.json" }, &d), RAD_OK);
CHECK_EQ(d.kld_ref, std::string("/r"));
CHECK_EQ(d.kld_out, std::string("/o.json"));
CHECK(d.kld());
Config e;
CHECK_EQ(parse({}, &e), RAD_OK);
CHECK(!e.kld());
Config f;
CHECK_EQ(parse({ "--kld-record", "/r", "--kld-ref", "/s" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--kld-record", "/r" }, &f), RAD_E_INVAL); /* no corpus */
CHECK_EQ(parse({ "--kld-ref", "/r", "--kld-corpus", "/c" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--kld-out", "/o.json" }, &f), RAD_E_INVAL); /* nothing to report */
CHECK_EQ(parse({ "--kld-ref" }, &f), RAD_E_INVAL);
}
TEST(the_model_is_required_and_nothing_else_is) {
Config c;
Args none{};
CHECK_EQ(config_parse(none.argc(), none.argv.data(), &c), RAD_E_INVAL);
Config ok;
CHECK_EQ(parse({}, &ok), RAD_OK);
CHECK_EQ(ok.model, std::string("/m/x.rad"));
}
/* ================================================================== taken */
TEST(the_sizes_and_counts_reach_the_fields_they_name) {
Config c;
CHECK_EQ(parse({ "--tp", "2",
"--max-num-batched-tokens", "512",
"--max-num-seqs", "8",
"--max-model-len", "200000",
"--vram-weights-mib", "20480",
"--vram-kv-mib", "6144",
"--host-pool-mib", "12288",
"--prefix-cache-host-mib", "4096",
"--prefix-cache-disk-mib", "65536",
"--checkpoint-interval", "2048",
"--checkpoint-slots", "8",
"--tp-wire-min-kb", "64",
"--port", "8100" }, &c), RAD_OK);
CHECK_EQ(c.tp, 2);
CHECK_EQ(c.max_tok, 512ll);
CHECK_EQ(c.max_seqs, 8ll);
CHECK_EQ(c.max_ctx, 200000ll);
CHECK_EQ(c.vram_weights_mib, 20480ll);
CHECK_EQ(c.vram_kv_mib, 6144ll);
CHECK_EQ(c.host_pool_mib, 12288ll);
CHECK_EQ(c.prefix_cache_host_mib, 4096ll);
CHECK_EQ(c.prefix_cache_disk_mib, 65536ll);
CHECK_EQ(c.checkpoint_interval, 2048ll);
CHECK_EQ(c.checkpoint_slots, 8ll);
CHECK_EQ(c.tp_wire_min_kb, 64ll);
CHECK_EQ(c.port, 8100);
/* A CONTEXT BOUND THAT DOES NOT FIT IN AN int. --max-model-len is the flag most likely to
* carry a number past two billion, and atoi would wrap it. */
Config big;
CHECK_EQ(parse({ "--max-model-len", "4294967296" }, &big), RAD_OK);
CHECK_EQ(big.max_ctx, 4294967296ll);
}
TEST(the_paths_and_names_reach_their_fields) {
Config c;
CHECK_EQ(parse({ "--radiance-home", "/rh",
"--weights-disk-tier",
"--prefix-cache-dir", "/kvdir",
"--placement", "expert_tiered",
"--host", "0.0.0.0",
"--generation-config", "/g.json",
"--reasoning-effort", "medium" }, &c), RAD_OK);
CHECK_EQ(c.radiance_home, std::string("/rh"));
CHECK(c.weights_disk_tier);
CHECK_EQ(c.prefix_cache_dir, std::string("/kvdir"));
CHECK_EQ(c.placement, std::string("expert_tiered"));
CHECK_EQ(c.host, std::string("0.0.0.0"));
CHECK_EQ(c.generation_config, std::string("/g.json"));
CHECK_EQ(c.reasoning_effort, std::string("medium"));
}
TEST(the_boolean_flags_are_off_until_they_are_given) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(!d.deterministic);
CHECK(d.prefix_cache); /* on by default; the flag only turns it off */
CHECK(!d.debug_graph);
CHECK(!d.debug_selection);
CHECK(!d.debug_placement);
CHECK(!d.accept_reference_kernels);
CHECK(!d.profile_ops);
CHECK(!d.live_view);
Config c;
CHECK_EQ(parse({ "--deterministic", "--no-prefix-cache", "--debug-placement",
"--debug-accept-reference-kernels", "--profile-ops", "--live" }, &c), RAD_OK);
CHECK(c.deterministic);
CHECK(!c.prefix_cache);
CHECK(c.debug_placement);
CHECK(c.accept_reference_kernels);
CHECK(c.profile_ops);
CHECK(c.live_view);
}
/* THE GRAPH DUMP IMPLIES THE SELECTION TABLE, because a graph without the kernel that resolved
* each node is a picture of a program nobody can tell is the one that will run. */
TEST(debug_graph_turns_the_selection_table_on_too) {
Config c;
CHECK_EQ(parse({ "--debug-graph" }, &c), RAD_OK);
CHECK(c.debug_graph);
CHECK(c.debug_selection);
Config s;
CHECK_EQ(parse({ "--debug-selection" }, &s), RAD_OK);
CHECK(!s.debug_graph); /* and not the other way round */
CHECK(s.debug_selection);
}
TEST(the_verbosity_flags_move_the_log_level) {
LogGuard guard;
Config c;
log_set_level(Log::Info);
CHECK_EQ(parse({ "-v" }, &c), RAD_OK);
CHECK((int)log_level() == (int)Log::Debug);
CHECK_EQ(parse({ "-vv" }, &c), RAD_OK);
CHECK((int)log_level() == (int)Log::Trace);
}
/* ================================================================== refused */
TEST(tp_below_one_is_refused) {
Config c;
CHECK_EQ(parse({ "--tp", "0" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp", "-1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp", "notanumber" }, &c), RAD_E_INVAL); /* atoi gives 0 */
CHECK_EQ(parse({ "--tp", "1" }, &c), RAD_OK);
}
TEST(the_wire_mode_is_one_of_two_names) {
Config c;
CHECK_EQ(parse({ "--tp-wire", "exact" }, &c), RAD_OK);
CHECK_EQ(c.tp_wire_exact, 1);
CHECK_EQ(parse({ "--tp-wire", "wht6" }, &c), RAD_OK);
CHECK_EQ(c.tp_wire_exact, 0);
/* A LOSSY WIRE IS A DEPLOYMENT CHOICE AND NOTHING DOWNSTREAM CAN DETECT IT: the sum a rank
* receives is not the sum it would have received. So a name this build does not know has to
* stop the server rather than fall through to whichever mode happens to be the default. */
CHECK_EQ(parse({ "--tp-wire", "wht8" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp-wire", "" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--tp-wire", "EXACT" }, &c), RAD_E_INVAL);
}
TEST(the_kv_cache_dtype_is_one_of_two_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 and not three: an "auto" resolving to bf16 would be a second name for the
* default, and a flag whose values are not all distinct cannot be read back out of a log. */
CHECK_EQ(parse({ "--kv-cache-dtype", "auto" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--kv-cache-dtype", "fp16" }, &c), RAD_E_INVAL);
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.kv_cache_dtype, std::string("bf16"));
}
/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS. It is the WEIGHTS share, strictly inside
* (0, 1): either endpoint gives one side of the split nothing at all, and the server would come
* up and then fail to place either the experts or the cache. */
TEST(the_expert_cache_ratio_is_strictly_between_zero_and_one) {
Config c;
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.82" }, &c), RAD_OK);
CHECK_NEAR(c.expert_cache_ratio, 0.82, 1e-9);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.5" }, &c), RAD_OK);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "-0.5" }, &c), RAD_E_INVAL);
/* A PERCENTAGE IS THE OBVIOUS MISREADING of a flag documented as a ratio, and 82 is outside
* the range rather than clamped to it -- which is the difference between a server that says
* what is wrong and one that quietly serves a different split. */
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "82" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--expert-vs-cache-ratio", "high" }, &c), RAD_E_INVAL);
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_NEAR(d.expert_cache_ratio, 0.75, 1e-9);
}
/* A POLICY NAME THIS BUILD DOES NOT KNOW WOULD FALL THROUGH TO THE DEFAULT, and a measurement
* comparing the default against itself is the failure that costs the most to notice. */
TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) {
Config c;
for (const char* p : { "geometric-backoff", "tip-only", "keep-all" }) {
CHECK_EQ(parse({ "--checkpoint-policy", p }, &c), RAD_OK);
CHECK_EQ(c.checkpoint_policy, std::string(p));
}
CHECK_EQ(parse({ "--checkpoint-policy", "lru" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--checkpoint-policy", "geometric_backoff" }, &c), RAD_E_INVAL);
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.checkpoint_policy, std::string("geometric-backoff"));
}
/* THE SAME RANGES THE REQUEST PARSER ENFORCES, refused here rather than at the first request: a
* default outside them is a 400 on every request that omits the field, which is a server that
* starts, reports healthy and answers nothing. */
TEST(the_sampler_defaults_are_range_checked_at_startup) {
Config c;
CHECK_EQ(parse({ "--temp", "0.7", "--top-k", "20", "--top-p", "0.95",
"--min-p", "0.05" }, &c), RAD_OK);
CHECK_NEAR(c.sample_temp, 0.7f, 1e-6);
CHECK_EQ(c.sample_top_k, 20);
CHECK_NEAR(c.sample_top_p, 0.95f, 1e-6);
CHECK_NEAR(c.sample_min_p, 0.05f, 1e-6);
/* The legal endpoints. Temperature 0 is greedy and top_k 0 is off: both are real settings. */
CHECK_EQ(parse({ "--temp", "0" }, &c), RAD_OK);
CHECK_EQ(parse({ "--temp", "2" }, &c), RAD_OK);
CHECK_EQ(parse({ "--top-k", "0" }, &c), RAD_OK);
CHECK_EQ(parse({ "--top-p", "1" }, &c), RAD_OK);
CHECK_EQ(parse({ "--min-p", "0" }, &c), RAD_OK);
CHECK_EQ(parse({ "--min-p", "1" }, &c), RAD_OK);
CHECK_EQ(parse({ "--temp", "2.1" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--top-p", "0" }, &c), RAD_E_INVAL); /* a nucleus of nothing */
CHECK_EQ(parse({ "--top-p", "1.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--min-p", "1.5" }, &c), RAD_E_INVAL);
/* A negative value is refused rather than read as "unset", which is what a negative field
* means below the parser -- the container's default would be served in its place. */
CHECK_EQ(parse({ "--temp", "-0.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--top-k", "-5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--top-p", "-0.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--min-p", "-0.5" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--temp", "nan" }, &c), RAD_E_INVAL);
/* UNSET IS NEGATIVE AND NOT ZERO, which is what lets the container's own generation config be
* resolved underneath: zero is a real temperature and a real top_k, so a default of zero
* would be indistinguishable from an operator asking for greedy. */
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.sample_temp < 0.0f);
CHECK(d.sample_top_k < 0);
CHECK(d.sample_top_p < 0.0f);
CHECK(d.sample_min_p < 0.0f);
}
/* REFUSED, NOT QUIETLY IGNORED. Accepting it and then serving the container's own drafter -- or
* none -- hands the caller a server that is not the one they asked for, with nothing in the
* output to say so. A caller coming from vLLM will reach for this flag. */
TEST(draft_model_is_refused_by_name_rather_than_ignored) {
Config c;
CHECK_EQ(parse({ "--draft-model", "/d.rad" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--draft-model" }, &c), RAD_E_INVAL);
}
/* ================================================================== resolved */
TEST(auto_speculation_is_negative_one_and_not_zero) {
/* The depth is a property of the DRAFTER, which the architecture plugin states once the
* container is open -- so "auto" has to survive as a distinct value here. Zero is off. */
Config c;
CHECK_EQ(parse({ "--num-speculative-tokens", "auto" }, &c), RAD_OK);
CHECK_EQ(c.n_spec, -1);
CHECK_EQ(parse({ "--num-speculative-tokens", "0" }, &c), RAD_OK);
CHECK_EQ(c.n_spec, 0);
CHECK_EQ(parse({ "--num-speculative-tokens", "3" }, &c), RAD_OK);
CHECK_EQ(c.n_spec, 3);
/* Only the word says auto: a negative depth would read as it downstream. */
CHECK_EQ(parse({ "--num-speculative-tokens", "-3" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--num-speculative-tokens", "-1" }, &c), RAD_E_INVAL);
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.n_spec, -1); /* auto is also the default */
}
/* IT TAKES THE SHORT NAME TOO: "-mib" is the unit, and this is the flag an operator reaches for.
* Both spellings parse to the same field, so a line written either way means one thing. */
TEST(gpu_headroom_parses_under_both_spellings) {
Config a, b, d;
CHECK_EQ(parse({ "--gpu-headroom-mib", "256" }, &a), RAD_OK);
CHECK_EQ(parse({ "--gpu-headroom", "256" }, &b), RAD_OK);
CHECK_EQ(a.gpu_headroom_mib, 256ll);
CHECK_EQ(b.gpu_headroom_mib, 256ll);
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.gpu_headroom_mib, 96ll);
}
TEST(the_kernel_hierarchy_is_comma_separated_and_ordered) {
Config c;
CHECK_EQ(parse({ "--kernels", "libr4d.so,libref.so" }, &c), RAD_OK);
CHECK_EQ(c.kernel_hierarchy.size(), 2u);
CHECK_EQ(c.kernel_hierarchy[0], std::string("libr4d.so")); /* first wins, so order is data */
CHECK_EQ(c.kernel_hierarchy[1], std::string("libref.so"));
/* Empty segments are dropped rather than kept as empty names: a trailing comma is a typing
* artefact, and a plugin path of "" matches nothing and would warn on every start. */
Config t;
CHECK_EQ(parse({ "--kernels", ",a,,b," }, &t), RAD_OK);
CHECK_EQ(t.kernel_hierarchy.size(), 2u);
CHECK_EQ(t.kernel_hierarchy[0], std::string("a"));
CHECK_EQ(t.kernel_hierarchy[1], std::string("b"));
Config one;
CHECK_EQ(parse({ "--kernels", "solo" }, &one), RAD_OK);
CHECK_EQ(one.kernel_hierarchy.size(), 1u);
}
/* AND THERE IS NO BUILT-IN DEFAULT HIERARCHY, deliberately: naming one card's kernel library in
* the core would, on every other machine, rank the library that IS installed behind the reference
* implementation. An empty hierarchy is not "no order" -- the loader supplies one. */
TEST(an_unnamed_hierarchy_stays_empty_for_the_loader_to_order) {
Config c;
CHECK_EQ(parse({}, &c), RAD_OK);
CHECK_EQ(c.kernel_hierarchy.size(), 0u);
}
/* THE ENGINE HONOURS THE SAME VARIABLE THE TOOLS DO. Otherwise an operator who validated a
* third-party plugin with rad-kbench or rad-tune has no way to serve with it short of editing
* every launcher's command line. */
TEST(the_environment_supplies_what_the_line_left_unsaid) {
const char* old_home = getenv("RADIANCE_HOME");
const char* old_kern = getenv("RADIANCE_KERNELS");
const std::string save_home = old_home ? old_home : "";
const std::string save_kern = old_kern ? old_kern : "";
setenv("RADIANCE_HOME", "/env/home", 1);
setenv("RADIANCE_KERNELS", "env_a,env_b", 1);
Config c;
CHECK_EQ(parse({}, &c), RAD_OK);
CHECK_EQ(c.radiance_home, std::string("/env/home"));
CHECK_EQ(c.kernel_hierarchy.size(), 2u);
CHECK_EQ(c.kernel_hierarchy[0], std::string("env_a"));
/* The command line wins over the environment, in both cases. */
Config f;
CHECK_EQ(parse({ "--radiance-home", "/flag/home", "--kernels", "flag_only" }, &f), RAD_OK);
CHECK_EQ(f.radiance_home, std::string("/flag/home"));
CHECK_EQ(f.kernel_hierarchy.size(), 1u);
CHECK_EQ(f.kernel_hierarchy[0], std::string("flag_only"));
/* An empty variable says nothing rather than saying "the empty hierarchy". */
setenv("RADIANCE_KERNELS", "", 1);
Config e;
CHECK_EQ(parse({}, &e), RAD_OK);
CHECK_EQ(e.kernel_hierarchy.size(), 0u);
unsetenv("RADIANCE_HOME");
Config h;
CHECK_EQ(parse({}, &h), RAD_OK);
CHECK(!h.radiance_home.empty()); /* the compiled-in default, whatever it is */
if (old_home) setenv("RADIANCE_HOME", save_home.c_str(), 1); else unsetenv("RADIANCE_HOME");
if (old_kern) setenv("RADIANCE_KERNELS", save_kern.c_str(), 1); else unsetenv("RADIANCE_KERNELS");
}
/* LATER WINS, for every flag that takes a value. Scripts build these lines by appending, and a
* parser that kept the first occurrence would make an override a no-op. */
TEST(a_repeated_flag_takes_the_last_one) {
Config c;
CHECK_EQ(parse({ "--port", "1", "--port", "8100" }, &c), RAD_OK);
CHECK_EQ(c.port, 8100);
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16", "--kv-cache-dtype", "fp8" }, &c), RAD_OK);
CHECK_EQ(c.kv_cache_dtype, std::string("fp8"));
/* And a bad value refuses even when a good one preceded it. */
CHECK_EQ(parse({ "--tp-wire", "exact", "--tp-wire", "nope" }, &c), RAD_E_INVAL);
}
TEST(usage_names_every_flag_it_documents) {
/* config_usage writes to stderr; the property worth holding is that it mentions the flags an
* operator is most likely to be looking for, so a flag added without a help line is caught. */
FILE* f = tmpfile();
CHECK(f != nullptr);
if (!f) return;
const int saved = dup(2);
CHECK(saved >= 0);
fflush(stderr);
dup2(fileno(f), 2);
config_usage("radiance");
fflush(stderr);
dup2(saved, 2);
close(saved);
std::string text;
rewind(f);
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) text.append(buf, n);
fclose(f);
CHECK(text.find("--model") != std::string::npos);
CHECK(text.find("--expert-vs-cache-ratio") != std::string::npos);
CHECK(text.find("--kv-cache-dtype") != std::string::npos);
CHECK(text.find("--num-speculative-tokens") != std::string::npos);
CHECK(text.find("--checkpoint-policy") != std::string::npos);
CHECK(text.find("--prefix-cache-host-mib") != std::string::npos);
CHECK(text.find("--tp-wire") != std::string::npos);
CHECK(text.find("--kld-record") != std::string::npos);
CHECK(text.find("--kld-ref") != std::string::npos);
CHECK(text.size() > 1000);
}
RAD_TEST_MAIN()
@@ -0,0 +1,177 @@
{{- bos_token }}{%- if tools %}
{%- set tool_definitions %}
{{- "# Tools\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson(ensure_ascii=False) }}
{%- endfor %}
{{- '\n</tools>\n\nTool usage guidelines:\n- You may call zero or more functions. If no function calls are needed, just answer normally and do not include any <function ... </function>.\n- When calling a function, return an XML object within <function ... </function> using:\n<function name="function-name"><param name="param-name">param-value</param></function>\n- param-value may be multi-line. If it contains <, & or newline characters, wrap it in a CDATA block: <param name="param-name"><![CDATA[...multi-line value...]]></param>' }}
{%- endset %}
{{- '<|im_start|>system\n' }}
{%- if messages[0].role == 'system' %}
{%- if '<tool_def_sep>' in messages[0].content %}
{{- messages[0].content.replace('<tool_def_sep>', tool_definitions) }}
{%- else %}
{{- messages[0].content + '\n\n' + tool_definitions }}
{%- endif %}
{%- else %}
{{- tool_definitions.lstrip() }}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endfor %}
{%- for message in messages %}
{%- if message.content is string %}
{%- set content = message.content %}
{%- else %}
{%- set content = '' %}
{%- endif %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- else %}
{%- if '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- if message.tool_calls %}
{%- set content_parts = content.split('<tool_sep>') %}
{%- set processed_content = content_parts[0] %}
{%- set tool_calls_count = message.tool_calls|length %}
{%- set tool_sep_count = content_parts|length - 1 %}
{%- set min_count = [tool_calls_count, tool_sep_count]|min %}
{%- for i in range(1, content_parts|length) %}
{%- set tool_index = i - 1 %}
{%- if tool_index < tool_calls_count %}
{%- set tool_call = message.tool_calls[tool_index] %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- set single_tool_xml %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endset %}
{%- set processed_content = processed_content + single_tool_xml + content_parts[i] %}
{%- else %}
{%- set processed_content = processed_content + content_parts[i] %}
{%- endif %}
{%- endfor %}
{%- if tool_calls_count > tool_sep_count %}
{%- for remaining_index in range(tool_sep_count, tool_calls_count) %}
{%- set tool_call = message.tool_calls[remaining_index] %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- set remaining_tool_xml %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endset %}
{%- set processed_content = processed_content + remaining_tool_xml %}
{%- endfor %}
{%- endif %}
{%- set content = processed_content %}
{%- endif %}
{%- if reasoning_content %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
{%- elif '<think>' not in content and '</think>' not in content %}
{{- '<|im_start|>' + message.role + '\n<think>\n\n</think>\n\n' + content.lstrip('\n') }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and not has_tool_sep %}
{%- for tool_call in message.tool_calls %}
{%- if (loop.first and content) or (not loop.first) %}
{{- '\n' }}
{%- endif %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{%- if message.content is string %}
{{- content }}
{%- else %}
{{- message.content | tojson(ensure_ascii=False) }}
{%- endif %}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined %}
{%- if enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- elif enable_thinking is true %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
{%- endif %}
+154
View File
@@ -0,0 +1,154 @@
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
{%- if content is string %}
{{- content }}
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain images.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set image_count.value = image_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Picture ' ~ image_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
{%- elif 'video' in item or item.type == 'video' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain videos.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set video_count.value = video_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Video ' ~ video_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
{%- elif 'text' in item %}
{{- item.text }}
{%- else %}
{{- raise_exception('Unexpected item type in content.') }}
{%- endif %}
{%- endfor %}
{%- elif content is none or content is undefined %}
{{- '' }}
{%- else %}
{{- raise_exception('Unexpected content type.') }}
{%- endif %}
{%- endmacro %}
{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system\n' }}
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '\n\n' + content }}
{%- endif %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" %}
{%- set content = render_content(message.content, false)|trim %}
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if ns.multi_step_tool %}
{{- raise_exception('No user query found in messages.') }}
{%- endif %}
{%- for message in messages %}
{%- set content = render_content(message.content, true)|trim %}
{%- if message.role == "system" %}
{%- if not loop.first %}
{{- raise_exception('System message must be at the beginning.') }}
{%- endif %}
{%- elif message.role == "user" %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- else %}
{%- if '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- set reasoning_content = reasoning_content|trim %}
{%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- if loop.first %}
{%- if content|trim %}
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- else %}
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- else %}
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- if tool_call.arguments is defined %}
{%- for args_name, args_value in tool_call.arguments|items %}
{{- '<parameter=' + args_name + '>\n' }}
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
{{- args_value }}
{{- '\n</parameter>\n' }}
{%- endfor %}
{%- endif %}
{{- '</function>\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if not loop.last and loop.nextitem.role != "tool" %}
{{- '<|im_end|>\n' }}
{%- elif loop.last %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{{- raise_exception('Unexpected message role.') }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- else %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
+170
View File
@@ -0,0 +1,170 @@
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
{%- if content is string %}
{{- content }}
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain images.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set image_count.value = image_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Picture ' ~ image_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
{%- elif 'video' in item or item.type == 'video' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain videos.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set video_count.value = video_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Video ' ~ video_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
{%- elif 'text' in item %}
{{- item.text }}
{%- else %}
{{- raise_exception('Unexpected item type in content.') }}
{%- endif %}
{%- endfor %}
{%- elif content is none or content is undefined %}
{{- '' }}
{%- else %}
{{- raise_exception('Unexpected content type.') }}
{%- endif %}
{%- endmacro %}
{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- set reasoning_instructions = '' %}
{%- if enable_thinking is undefined or enable_thinking is true %}
{%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
{%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
{%- endif %}
{%- if resolved_reasoning_effort == 'xhigh' %}
{%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
{%- elif resolved_reasoning_effort == 'low' %}
{%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
{%- endif %}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system\n' }}
{%- if reasoning_instructions %}
{{- reasoning_instructions + '\n\n' }}
{%- endif %}
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '\n\n' + content }}
{%- endif %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
{%- elif reasoning_instructions %}
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
{%- endif %}
{%- elif reasoning_instructions %}
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" %}
{%- set content = render_content(message.content, false)|trim %}
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if ns.multi_step_tool %}
{{- raise_exception('No user query found in messages.') }}
{%- endif %}
{%- for message in messages %}
{%- set content = render_content(message.content, true)|trim %}
{%- if message.role == "system" %}
{%- if not loop.first %}
{{- raise_exception('System message must be at the beginning.') }}
{%- endif %}
{%- elif message.role == "user" %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- endif %}
{%- set reasoning_content = reasoning_content|trim %}
{%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- if loop.first %}
{%- if content|trim %}
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- else %}
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- else %}
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- if tool_call.arguments is defined and tool_call.arguments != '' %}
{%- for args_name, args_value in tool_call.arguments|items %}
{{- '<parameter=' + args_name + '>\n' }}
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
{{- args_value }}
{{- '\n</parameter>\n' }}
{%- endfor %}
{%- endif %}
{{- '</function>\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if not loop.last and loop.nextitem.role != "tool" %}
{{- '<|im_end|>\n' }}
{%- elif loop.last %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{{- raise_exception('Unexpected message role.') }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- else %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
+177
View File
@@ -0,0 +1,177 @@
{{- bos_token }}{%- if tools %}
{%- set tool_definitions %}
{{- "# Tools\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson(ensure_ascii=False) }}
{%- endfor %}
{{- '\n</tools>\n\nTool usage guidelines:\n- You may call zero or more functions. If no function calls are needed, just answer normally and do not include any <function ... </function>.\n- When calling a function, return an XML object within <function ... </function> using:\n<function name="function-name"><param name="param-name">param-value</param></function>\n- param-value may be multi-line. If it contains <, & or newline characters, wrap it in a CDATA block: <param name="param-name"><![CDATA[...multi-line value...]]></param>' }}
{%- endset %}
{{- '<|im_start|>system\n' }}
{%- if messages[0].role == 'system' %}
{%- if '<tool_def_sep>' in messages[0].content %}
{{- messages[0].content.replace('<tool_def_sep>', tool_definitions) }}
{%- else %}
{{- messages[0].content + '\n\n' + tool_definitions }}
{%- endif %}
{%- else %}
{{- tool_definitions.lstrip() }}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endfor %}
{%- for message in messages %}
{%- if message.content is string %}
{%- set content = message.content %}
{%- else %}
{%- set content = '' %}
{%- endif %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- else %}
{%- if '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- if message.tool_calls %}
{%- set content_parts = content.split('<tool_sep>') %}
{%- set processed_content = content_parts[0] %}
{%- set tool_calls_count = message.tool_calls|length %}
{%- set tool_sep_count = content_parts|length - 1 %}
{%- set min_count = [tool_calls_count, tool_sep_count]|min %}
{%- for i in range(1, content_parts|length) %}
{%- set tool_index = i - 1 %}
{%- if tool_index < tool_calls_count %}
{%- set tool_call = message.tool_calls[tool_index] %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- set single_tool_xml %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endset %}
{%- set processed_content = processed_content + single_tool_xml + content_parts[i] %}
{%- else %}
{%- set processed_content = processed_content + content_parts[i] %}
{%- endif %}
{%- endfor %}
{%- if tool_calls_count > tool_sep_count %}
{%- for remaining_index in range(tool_sep_count, tool_calls_count) %}
{%- set tool_call = message.tool_calls[remaining_index] %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- set remaining_tool_xml %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endset %}
{%- set processed_content = processed_content + remaining_tool_xml %}
{%- endfor %}
{%- endif %}
{%- set content = processed_content %}
{%- endif %}
{%- if reasoning_content %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
{%- elif '<think>' not in content and '</think>' not in content %}
{{- '<|im_start|>' + message.role + '\n<think>\n\n</think>\n\n' + content.lstrip('\n') }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and not has_tool_sep %}
{%- for tool_call in message.tool_calls %}
{%- if (loop.first and content) or (not loop.first) %}
{{- '\n' }}
{%- endif %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '<function name="' ~ tool_call.name ~ '">' }}
{%- if tool_call.arguments %}
{%- set args_dict = tool_call.arguments %}
{%- for param_name, param_value in args_dict.items() %}
{{- '<param name="' ~ param_name ~ '">' }}
{%- if param_value is string and ('<' in param_value or '&' in param_value or '\n' in param_value) %}
{{- '<![CDATA[' + param_value + ']]>' }}
{%- else %}
{{- param_value }}
{%- endif %}
{{- '</param>' }}
{%- endfor %}
{%- endif %}
{{- '</function>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{%- if message.content is string %}
{{- content }}
{%- else %}
{{- message.content | tojson(ensure_ascii=False) }}
{%- endif %}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined %}
{%- if enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- elif enable_thinking is true %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
{%- endif %}
+154
View File
@@ -0,0 +1,154 @@
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
{%- if content is string %}
{{- content }}
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain images.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set image_count.value = image_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Picture ' ~ image_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
{%- elif 'video' in item or item.type == 'video' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain videos.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set video_count.value = video_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Video ' ~ video_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
{%- elif 'text' in item %}
{{- item.text }}
{%- else %}
{{- raise_exception('Unexpected item type in content.') }}
{%- endif %}
{%- endfor %}
{%- elif content is none or content is undefined %}
{{- '' }}
{%- else %}
{{- raise_exception('Unexpected content type.') }}
{%- endif %}
{%- endmacro %}
{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system\n' }}
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '\n\n' + content }}
{%- endif %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" %}
{%- set content = render_content(message.content, false)|trim %}
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if ns.multi_step_tool %}
{{- raise_exception('No user query found in messages.') }}
{%- endif %}
{%- for message in messages %}
{%- set content = render_content(message.content, true)|trim %}
{%- if message.role == "system" %}
{%- if not loop.first %}
{{- raise_exception('System message must be at the beginning.') }}
{%- endif %}
{%- elif message.role == "user" %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- else %}
{%- if '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- set reasoning_content = reasoning_content|trim %}
{%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- if loop.first %}
{%- if content|trim %}
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- else %}
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- else %}
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- if tool_call.arguments is defined %}
{%- for args_name, args_value in tool_call.arguments|items %}
{{- '<parameter=' + args_name + '>\n' }}
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
{{- args_value }}
{{- '\n</parameter>\n' }}
{%- endfor %}
{%- endif %}
{{- '</function>\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if not loop.last and loop.nextitem.role != "tool" %}
{{- '<|im_end|>\n' }}
{%- elif loop.last %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{{- raise_exception('Unexpected message role.') }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- else %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
+170
View File
@@ -0,0 +1,170 @@
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
{%- if content is string %}
{{- content }}
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain images.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set image_count.value = image_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Picture ' ~ image_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
{%- elif 'video' in item or item.type == 'video' %}
{%- if is_system_content %}
{{- raise_exception('System message cannot contain videos.') }}
{%- endif %}
{%- if do_vision_count %}
{%- set video_count.value = video_count.value + 1 %}
{%- endif %}
{%- if add_vision_id %}
{{- 'Video ' ~ video_count.value ~ ': ' }}
{%- endif %}
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
{%- elif 'text' in item %}
{{- item.text }}
{%- else %}
{{- raise_exception('Unexpected item type in content.') }}
{%- endif %}
{%- endfor %}
{%- elif content is none or content is undefined %}
{{- '' }}
{%- else %}
{{- raise_exception('Unexpected content type.') }}
{%- endif %}
{%- endmacro %}
{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- set reasoning_instructions = '' %}
{%- if enable_thinking is undefined or enable_thinking is true %}
{%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
{%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
{%- endif %}
{%- if resolved_reasoning_effort == 'xhigh' %}
{%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
{%- elif resolved_reasoning_effort == 'low' %}
{%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
{%- endif %}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system\n' }}
{%- if reasoning_instructions %}
{{- reasoning_instructions + '\n\n' }}
{%- endif %}
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '\n\n' + content }}
{%- endif %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- else %}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, false, true)|trim %}
{%- if content %}
{{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
{%- elif reasoning_instructions %}
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
{%- endif %}
{%- elif reasoning_instructions %}
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == "user" %}
{%- set content = render_content(message.content, false)|trim %}
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if ns.multi_step_tool %}
{{- raise_exception('No user query found in messages.') }}
{%- endif %}
{%- for message in messages %}
{%- set content = render_content(message.content, true)|trim %}
{%- if message.role == "system" %}
{%- if not loop.first %}
{{- raise_exception('System message must be at the beginning.') }}
{%- endif %}
{%- elif message.role == "user" %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- endif %}
{%- set reasoning_content = reasoning_content|trim %}
{%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- if loop.first %}
{%- if content|trim %}
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- else %}
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- else %}
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- if tool_call.arguments is defined and tool_call.arguments != '' %}
{%- for args_name, args_value in tool_call.arguments|items %}
{{- '<parameter=' + args_name + '>\n' }}
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
{{- args_value }}
{{- '\n</parameter>\n' }}
{%- endfor %}
{%- endif %}
{{- '</function>\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if not loop.last and loop.nextitem.role != "tool" %}
{{- '<|im_end|>\n' }}
{%- elif loop.last %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{{- raise_exception('Unexpected message role.') }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- else %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
+34
View File
@@ -0,0 +1,34 @@
# tests/data/media
One solid red picture in every still format `core/mm/media.cpp` admits, and one short solid red
clip in each container and codec it admits; `mm_test` decodes every one and checks it is red at
its size. They were made with FFmpeg 8.1 (libx264, libx265, libvpx, libsvtav1, libaom, libtheora,
libwebp):
```sh
I="-f lavfi -i color=c=red:s=32x32:d=1:r=1"
V="-f lavfi -i color=c=red:s=64x64:d=1:r=4"
ffmpeg $I -frames:v 1 red.png
ffmpeg $I -frames:v 2 -f apng red.apng
ffmpeg $I -frames:v 1 red.jpg
ffmpeg $I -frames:v 1 -c:v libwebp red.webp
ffmpeg $I -frames:v 1 red.gif
ffmpeg $I -frames:v 1 red.bmp
ffmpeg $I -frames:v 1 red.tiff
ffmpeg $I -frames:v 1 -c:v qoi red.qoi
ffmpeg $I -frames:v 1 -pix_fmt rgb24 red.ppm
ffmpeg $I -frames:v 1 -c:v jpegls red.jls
ffmpeg $V -frames:v 1 -c:v libaom-av1 -cpu-used 8 -f avif red.avif
ffmpeg $V -c:v libx264 -pix_fmt yuv420p red-h264.mp4
ffmpeg $V -c:v libx265 -pix_fmt yuv420p -tag:v hvc1 red-hevc.mp4
ffmpeg $V -c:v libsvtav1 -pix_fmt yuv420p red-av1.mp4
ffmpeg $V -c:v libvpx red-vp8.webm
ffmpeg $V -c:v libvpx-vp9 red-vp9.webm
ffmpeg $V -c:v libx264 -pix_fmt yuv420p red-h264.mkv
ffmpeg $V -c:v libx264 -pix_fmt yuv420p -f mpegts red-h264.ts
ffmpeg $V -c:v mpeg4 red-mpeg4.avi
ffmpeg $V -c:v libtheora red-theora.ogv
```
The Theora clip repeats its first frame with empty packets, which is how Ogg Theora encodes a frame
that does not change.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 120 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 B

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 84 B

+790
View File
@@ -0,0 +1,790 @@
/* device_test.cpp -- the device layer against its own contract.
*
* The interesting tests here are the ordering ones. Allocation and memcpy are hard to get wrong;
* what is easy to get wrong is a backend whose "async" calls quietly execute inline, because then
* every ordering bug above it -- a missing rad_event_wait, a staging buffer reused before the
* mover's copy landed -- passes on the host backend and corrupts weights on a card. So the event tests
* are built so that an out-of-order execution produces wrong BYTES, not merely a suspicious
* timestamp, and they run the race several times.
*/
#include "rad_test.h"
#include "rad_internal.h"
#include "device/device.h"
#include "device/directio.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
using rad::DirectFile;
using rad::RAD_DIO_READ;
using rad::RAD_DIO_WRITE;
using rad::RAD_DIO_CREATE;
using rad::RAD_DIO_TRUNC;
using rad::RAD_DIO_ALLOW_BUFFERED;
namespace {
struct Stream {
RadStream s = nullptr;
explicit Stream(int hi = 0) { rad_stream_create(&s, hi); }
~Stream() { if (s) rad_stream_destroy(s); }
};
struct Event {
RadEvent e = nullptr;
Event() { rad_event_create(&e); }
~Event() { if (e) rad_event_destroy(e); }
};
/* Deterministic filler, so a torn copy shows up as a mismatch at a known index. */
void fill(uint8_t* p, int64_t n, uint32_t seed) {
uint32_t x = seed | 1u;
for (int64_t i = 0; i < n; ++i) {
x = x * 1664525u + 1013904223u;
p[i] = (uint8_t)(x >> 24);
}
}
std::string temp_path(const char* tag) {
/* The working directory, not /tmp: /tmp is tmpfs on most systems and tmpfs refuses
* O_DIRECT outright, so the test would only ever exercise the buffered fallback. ctest runs
* from the build directory, which is on whatever the repository is on. */
return rad::fmt("./rad_%s_test_%d.bin", tag, (int)getpid());
}
} /* namespace */
/* ------------------------------------------------------------------ identity */
TEST(backend_reports_itself) {
const char* name = rad::device_backend_name();
CHECK(name && *name);
CHECK_EQ(rad::device_is_host(), std::strcmp(name, "host") == 0);
const int n = rad_dev_count();
CHECK(n >= 1);
RadDeviceProps p{};
CHECK_OK(rad_dev_props(0, &p));
CHECK(p.name[0] != '\0');
CHECK(p.arch[0] != '\0');
CHECK(p.vram_bytes > 0);
CHECK(p.vram_free >= 0);
CHECK(p.n_cu >= 1);
CHECK(p.warp_size >= 1);
CHECK_EQ(p.device_id, 0);
if (rad::device_is_host()) {
CHECK_EQ(p.is_host_backend, 1);
CHECK_EQ(std::string(p.arch), std::string("host"));
}
/* Out of range is refused, not clamped: a rank index that came from a bad --tp is a
* configuration bug and silently serving device 0 twice is how two ranks share one card. */
CHECK(rad_dev_props(n, &p) < 0);
CHECK(rad_dev_set(-1) < 0);
CHECK_OK(rad_dev_set(0));
}
TEST(host_vram_budget_comes_from_the_environment) {
/* A real card reports its own VRAM. Print the marker the other suites use so ctest scores
* this Skipped rather than Passed: a bare return leaves no trace of the case at all. */
if (!rad::device_is_host()) {
std::fprintf(stderr, " SKIP host_vram_budget_comes_from_the_environment: host backend only\n");
return;
}
const char* old = std::getenv("RADIANCE_HOST_VRAM_MIB");
const std::string saved = old ? old : "";
setenv("RADIANCE_HOST_VRAM_MIB", "777", 1);
RadDeviceProps p{};
CHECK_OK(rad_dev_props(0, &p));
CHECK_EQ(p.vram_bytes, (int64_t)777 << 20);
unsetenv("RADIANCE_HOST_VRAM_MIB");
CHECK_OK(rad_dev_props(0, &p));
/* The default is derived from physical RAM, so all that can be asserted is that it is a real
* budget the planner can plan against rather than a placeholder. */
CHECK(p.vram_bytes > (int64_t)64 << 20);
if (!saved.empty()) setenv("RADIANCE_HOST_VRAM_MIB", saved.c_str(), 1);
}
/* ------------------------------------------------------------------ allocation */
TEST(alloc_free_roundtrip) {
const int kinds[] = { RAD_MEM_DEVICE, RAD_MEM_HOST_PINNED, RAD_MEM_HOST, RAD_MEM_HOST_MAPPED };
const int64_t n = 64 * 1024 + 17; /* deliberately not a page multiple */
for (int k : kinds) {
void* p = rad_dev_alloc(n, k);
CHECK(p != nullptr);
if (!p) continue;
/* Host-visible kinds are writable from here; a DEVICE allocation is not, on a real card. */
if (rad::device_is_host() || k != RAD_MEM_DEVICE) {
auto* b = (uint8_t*)p;
fill(b, n, (uint32_t)k + 5u);
uint8_t expect[64];
fill(expect, 64, (uint32_t)k + 5u);
CHECK_EQ(std::memcmp(b, expect, 64), 0);
}
if (k == RAD_MEM_HOST_MAPPED) {
/* The zero-copy site of spec §5.1: one allocation, addressable from both sides. */
CHECK(rad_dev_host_ptr(p) != nullptr);
CHECK(rad_dev_device_ptr(p) != nullptr);
/* AND THE TWO VIEWS ARE THE SAME ADDRESS, ON EVERY BACKEND, because the runtime
* depends on it: Ctx::bind_buffers stores ONE base pointer per buffer, and the host
* activation arena is RAD_MEM_HOST_MAPPED precisely so a host-site op and a device
* kernel can be handed the same buffer. Under HIP's unified addressing they coincide;
* where they would not, host-site execution cannot work and Ctx refuses to start.
* This is the cheaper place to find that out than a model that will not load. */
CHECK_EQ(rad_dev_host_ptr(p), rad_dev_device_ptr(p));
CHECK_EQ(rad_dev_host_ptr(p), p);
}
/* Every host-visible pool this layer hands out is page-aligned, which is what lets a
* pinned buffer be an O_DIRECT landing zone with no bounce (directio.h). A device
* allocation only has to clear RAD_ALIGN_SUB, the container's sub-block. */
CHECK_EQ((uintptr_t)p % (k == RAD_MEM_DEVICE && !rad::device_is_host() ? 256u : 4096u), 0u);
rad_dev_free(p, k);
}
CHECK(rad_dev_alloc(0, RAD_MEM_HOST) == nullptr);
CHECK(rad_dev_alloc(-1, RAD_MEM_HOST) == nullptr);
CHECK(rad_dev_alloc(16, 99) == nullptr);
rad_dev_free(nullptr, RAD_MEM_HOST); /* must not fault */
CHECK(rad_dev_host_ptr(nullptr) == nullptr);
}
TEST(device_allocation_moves_vram_free) {
/* On a card, other processes move it too. */
if (!rad::device_is_host()) {
std::fprintf(stderr, " SKIP device_allocation_moves_vram_free: host backend only\n");
return;
}
RadDeviceProps before{}, during{};
CHECK_OK(rad_dev_props(0, &before));
const int64_t n = 32 << 20;
void* p = rad_dev_alloc(n, RAD_MEM_DEVICE);
CHECK(p != nullptr);
CHECK_OK(rad_dev_props(0, &during));
/* The planner's "did it fit" path is one of the things the host backend exists to falsify, and
* a constant vram_free would let a plan that overcommits a real card pass here. */
CHECK_EQ(before.vram_free - during.vram_free, n);
rad_dev_free(p, RAD_MEM_DEVICE);
CHECK_OK(rad_dev_props(0, &during));
CHECK_EQ(before.vram_free, during.vram_free);
}
/* ------------------------------------------------------------------ transfers */
TEST(memcpy_async_then_stream_sync) {
const int64_t n = 4 << 20;
Stream st;
CHECK(st.s != nullptr);
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST);
CHECK(src && dst);
if (!src || !dst) return;
fill(src, n, 0xC0FFEEu);
std::memset(dst, 0, (size_t)n);
CHECK_OK(rad_memcpy_async(dst, src, n, st.s));
CHECK_OK(rad_stream_sync(st.s));
CHECK_EQ(std::memcmp(dst, src, (size_t)n), 0);
/* Zero bytes is a no-op, not an error: a batch with an empty span should not need a branch. */
CHECK_OK(rad_memcpy_async(dst, src, 0, st.s));
rad_dev_free(src, RAD_MEM_HOST_PINNED);
rad_dev_free(dst, RAD_MEM_HOST);
}
TEST(memset_async) {
const int64_t n = 1 << 20;
Stream st;
/* Pinned, not RAD_MEM_HOST. rad_memset_async needs a device-ACCESSIBLE destination: pageable
* host memory is memory the GPU has never been shown, and hipMemsetAsync refuses it. The host
* backend cannot reproduce that refusal, so testing it against pageable memory here would
* green-light code that fails on a card -- which is exactly the divergence the shared vtable
* exists to prevent. See core/device/device.h. */
auto* p = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
CHECK(p != nullptr);
if (!p) return;
std::memset(p, 0, (size_t)n);
CHECK_OK(rad_memset_async(p, 0x5A, n, st.s));
CHECK_OK(rad_stream_sync(st.s));
bool all = true;
for (int64_t i = 0; i < n; ++i) if (p[i] != 0x5A) { all = false; break; }
CHECK(all);
/* Only the low byte of `value` is written, matching hipMemsetAsync and memset. */
CHECK_OK(rad_memset_async(p, 0x1FF, n, st.s));
CHECK_OK(rad_stream_sync(st.s));
CHECK_EQ((int)p[0], 0xFF);
CHECK_EQ((int)p[n - 1], 0xFF);
rad_dev_free(p, RAD_MEM_HOST_PINNED);
}
TEST(memset_of_pageable_host_memory_is_refused_on_a_card) {
/* The one asymmetry between the backends, pinned here so it is a documented contract rather
* than something rediscovered on a card. On a card the destination must be
* device-accessible and RAD_MEM_HOST is not; on the host backend every kind is the same
* memory and there is nothing to refuse. Either way the message names the rule. */
Stream st;
auto* p = (uint8_t*)rad_dev_alloc(4096, RAD_MEM_HOST);
CHECK(p != nullptr);
if (!p) return;
int s = rad_memset_async(p, 0, 4096, st.s);
if (rad::device_is_host()) {
CHECK_OK(s);
CHECK_OK(rad_stream_sync(st.s));
} else {
CHECK_EQ(s, RAD_E_UNSUPPORTED);
CHECK(std::strstr(rad_dev_last_error(), "device-accessible") != nullptr);
}
rad_dev_free(p, RAD_MEM_HOST);
}
TEST(memcpy_2d_respects_the_pitch) {
/* A KV block's rows are strided by the pool's row pitch, not packed, so the padding between
* rows is somebody else's data and must survive the copy untouched. */
const int64_t W = 48, H = 7, DP = 64, SP = 55;
Stream st;
auto* s = (uint8_t*)rad_dev_alloc(SP * H, RAD_MEM_HOST_PINNED);
auto* d = (uint8_t*)rad_dev_alloc(DP * H, RAD_MEM_HOST_PINNED);
CHECK(s && d);
if (!s || !d) return;
fill(s, SP * H, 0xBEEF);
CHECK_OK(rad_memset_async(d, 0xCC, DP * H, st.s));
CHECK_OK(rad_memcpy_2d_async(d, DP, s, SP, W, H, st.s));
CHECK_OK(rad_stream_sync(st.s));
bool rows_ok = true, pad_ok = true;
for (int64_t r = 0; r < H; ++r) {
if (std::memcmp(d + r * DP, s + r * SP, (size_t)W) != 0) rows_ok = false;
for (int64_t c = W; c < DP; ++c) if (d[r * DP + c] != 0xCC) pad_ok = false;
}
CHECK(rows_ok);
CHECK(pad_ok);
/* A pitch shorter than the row is a caller bug and is refused rather than clamped. */
CHECK(rad_memcpy_2d_async(d, W - 1, s, SP, W, H, st.s) < 0);
rad_dev_free(s, RAD_MEM_HOST_PINNED);
rad_dev_free(d, RAD_MEM_HOST_PINNED);
}
/* THREE LAPS OF THE KERNEL ARGUMENT RING WITH NO HOST WAIT BETWEEN THEM. A device backend that
* keeps kernel arguments in memory the host rewrites has to make each slot's new contents visible
* to the kernel that reads them; a stale slot does not fail, it runs the previous lap's kernel
* again. Every copy here moves a different 64-byte piece to a different place, so a stale
* argument lands a piece where another belonged and the comparison names it. */
TEST(twelve_thousand_copies_each_land_where_their_own_arguments_say) {
const int64_t piece = 64, n = 12000, bytes = piece * n;
Stream st;
auto* host = (uint8_t*)rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
auto* back = (uint8_t*)rad_dev_alloc(bytes, RAD_MEM_HOST_PINNED);
auto* src = (uint8_t*)rad_dev_alloc(bytes, RAD_MEM_DEVICE);
auto* dst = (uint8_t*)rad_dev_alloc(bytes, RAD_MEM_DEVICE);
CHECK(host && back && src && dst);
if (!host || !back || !src || !dst) return;
fill(host, bytes, 0xA11CE);
CHECK_OK(rad_memcpy_async(src, host, bytes, st.s));
/* Piece i of dst comes from piece (i * 7919) mod n of src: a permutation, since 7919 is prime
* and does not divide n, so no two copies share an argument. */
for (int64_t i = 0; i < n; ++i)
CHECK_OK(rad_memcpy_async(dst + i * piece, src + ((i * 7919) % n) * piece, piece, st.s));
CHECK_OK(rad_memcpy_async(back, dst, bytes, st.s));
CHECK_OK(rad_stream_sync(st.s));
int64_t wrong = 0, first = -1;
for (int64_t i = 0; i < n; ++i)
if (std::memcmp(back + i * piece, host + ((i * 7919) % n) * piece, (size_t)piece) != 0) {
if (first < 0) first = i;
++wrong;
}
CHECK_EQ(wrong, (int64_t)0);
if (wrong) std::fprintf(stderr, " first misplaced piece: %lld\n", (long long)first);
rad_dev_free(host, RAD_MEM_HOST_PINNED);
rad_dev_free(back, RAD_MEM_HOST_PINNED);
rad_dev_free(src, RAD_MEM_DEVICE);
rad_dev_free(dst, RAD_MEM_DEVICE);
}
/* ------------------------------------------------------------------ ordering */
TEST(event_on_one_stream_orders_work_on_another) {
const int64_t n = 4 << 20;
const int chain = 8; /* copies stream A does before it records */
const int rounds = 3; /* the race, run more than once */
Stream a, b;
CHECK(a.s && b.s);
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
auto* mid = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST);
CHECK(src && mid && dst);
if (!src || !mid || !dst) return;
for (int round = 0; round < rounds; ++round) {
Event e_a, e_b;
CHECK(e_a.e && e_b.e);
fill(src, n, 0x51ED0000u + (uint32_t)round);
/* Poison the intermediate from a *synchronised* point, so a read that jumps the queue sees
* 0xEE and not a stale copy of the right answer. */
CHECK_OK(rad_memset_async(mid, 0xEE, n, b.s));
CHECK_OK(rad_stream_sync(b.s));
/* Stream A: enough work that an unordered reader on B lands in the middle of it. */
CHECK_OK(rad_memset_async(mid, 0x00, n, a.s));
for (int i = 0; i < chain; ++i) CHECK_OK(rad_memcpy_async(mid, src, n, a.s));
CHECK_OK(rad_event_record(e_a.e, a.s));
/* Stream B waits on the event, not on the host: no rad_stream_sync(a) here, which is the
* property spec §5.4 needs -- a transfer that involves no host synchronisation. */
CHECK_OK(rad_event_wait(b.s, e_a.e));
CHECK_OK(rad_memcpy_async(dst, mid, n, b.s));
CHECK_OK(rad_event_record(e_b.e, b.s));
CHECK_OK(rad_stream_sync(b.s));
CHECK_EQ(std::memcmp(dst, src, (size_t)n), 0);
/* The timestamps are taken when each stream reaches its record, so B's cannot precede A's
* unless the wait did nothing. */
float ms = -1.0f;
CHECK_OK(rad_event_elapsed_ms(e_a.e, e_b.e, &ms));
CHECK(ms >= 0.0f);
CHECK_OK(rad_stream_sync(a.s));
CHECK_EQ(rad_event_query(e_a.e), 1);
CHECK_EQ(rad_event_query(e_b.e), 1);
}
rad_dev_free(src, RAD_MEM_HOST_PINNED);
rad_dev_free(mid, RAD_MEM_DEVICE);
rad_dev_free(dst, RAD_MEM_HOST);
}
/* TWO STREAMS THAT JOIN EACH OTHER HUNDREDS OF TIMES, with the host far ahead of both and one of
* them lagging -- the shape of a model's two compute lanes, which meet every layer. A backend that
* reuses an event's completion object while a wait enqueued against its previous record has not yet
* been reached turns that wait into a wait on a LATER record, which sits behind a join the lagging
* stream has not reached: a deadlock, not a wrong answer. Here it would hang; the bytes are checked
* as well, because the joins are also what orders the copies. */
TEST(two_streams_joining_each_other_hundreds_of_times_neither_deadlock_nor_reorder) {
const int64_t big = 1 << 20, small = 4096;
const int joins = 400;
Stream a, b;
Event ea, eb;
auto* d0 = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE);
auto* d1 = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE);
auto* h = (uint8_t*)rad_dev_alloc(big, RAD_MEM_HOST_PINNED);
auto* r = (uint8_t*)rad_dev_alloc(small, RAD_MEM_HOST_PINNED);
CHECK(d0 && d1 && h && r);
if (!d0 || !d1 || !h || !r) return;
fill(h, big, 0x5EED);
CHECK_OK(rad_memcpy_async(d0, h, big, a.s));
for (int i = 0; i < joins; ++i) {
/* b lags: a whole megabyte each round against a's four kilobytes. */
CHECK_OK(rad_event_record(ea.e, a.s));
CHECK_OK(rad_event_wait(b.s, ea.e));
CHECK_OK(rad_memcpy_async(d1, d0, big, b.s));
CHECK_OK(rad_event_record(eb.e, b.s));
CHECK_OK(rad_event_wait(a.s, eb.e));
CHECK_OK(rad_memcpy_async(d0, d1, small, a.s));
}
CHECK_OK(rad_memcpy_async(r, d0, small, a.s));
CHECK_OK(rad_stream_sync(a.s));
CHECK_OK(rad_stream_sync(b.s));
CHECK_EQ(std::memcmp(r, h, (size_t)small), 0);
rad_dev_free(d0, RAD_MEM_DEVICE);
rad_dev_free(d1, RAD_MEM_DEVICE);
rad_dev_free(h, RAD_MEM_HOST_PINNED);
rad_dev_free(r, RAD_MEM_HOST_PINNED);
}
TEST(an_event_destroyed_while_queued_work_names_it_still_orders_that_work) {
/* Teardown written against a card destroys events whose record or wait has not run yet --
* the mover's own does -- and HIP allows it. The work already queued has to behave as if the
* handle were still alive: the wait still waits, the copy behind it still sees the bytes, and
* neither stream wedges. The events are recreated and destroyed again between rounds so that
* memory freed too early is handed straight back out and overwritten. */
const int64_t n = 4 << 20;
Stream a, b;
CHECK(a.s && b.s);
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
auto* mid = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST);
CHECK(src && mid && dst);
if (!src || !mid || !dst) return;
for (int round = 0; round < 4; ++round) {
fill(src, n, 0xDE570000u + (uint32_t)round);
CHECK_OK(rad_memset_async(mid, 0xEE, n, b.s));
CHECK_OK(rad_stream_sync(b.s));
RadEvent ga = nullptr, eb = nullptr;
CHECK_OK(rad_event_create(&ga));
CHECK_OK(rad_event_create(&eb));
for (int i = 0; i < 8; ++i) CHECK_OK(rad_memcpy_async(mid, src, n, a.s));
CHECK_OK(rad_event_record(ga, a.s));
CHECK_OK(rad_event_wait(b.s, ga));
CHECK_OK(rad_memcpy_async(dst, mid, n, b.s));
CHECK_OK(rad_event_record(eb, b.s));
rad_event_destroy(eb);
rad_event_destroy(ga);
for (int k = 0; k < 4; ++k) {
Event churn;
CHECK_OK(rad_event_record(churn.e, b.s));
}
CHECK_OK(rad_stream_sync(b.s));
CHECK_OK(rad_stream_sync(a.s));
CHECK_EQ(std::memcmp(dst, src, (size_t)n), 0);
}
rad_dev_free(src, RAD_MEM_HOST_PINNED);
rad_dev_free(mid, RAD_MEM_DEVICE);
rad_dev_free(dst, RAD_MEM_HOST);
}
TEST(waiting_on_an_unrecorded_event_is_a_no_op) {
/* The mover relies on this: a weight with no transfer in flight has an event nobody recorded,
* and making that an error would put a branch on the issue path for nothing. */
Stream st;
Event e;
CHECK_EQ(rad_event_query(e.e), 1);
CHECK_OK(rad_event_wait(st.s, e.e));
CHECK_OK(rad_stream_sync(st.s));
}
TEST(the_null_stream_is_refused) {
/* HIP's stream 0 serialises against every other blocking stream in the process, which is the
* opposite of what a transfer is for here. Refusing it on both backends means a caller cannot
* pick it up by accident on the host backend and discover it on a card. */
uint8_t a[16] = {}, b[16] = {};
CHECK(rad_memcpy_async(a, b, sizeof a, nullptr) < 0);
CHECK(std::strlen(rad_dev_last_error()) > 0);
/* Drained by reading, per the header. */
CHECK_EQ(std::strlen(rad_dev_last_error()), 0u);
CHECK(rad_memset_async(a, 0, sizeof a, nullptr) < 0);
CHECK(rad_stream_sync(nullptr) < 0);
}
/* ------------------------------------------------------------------ the file tier */
TEST(directfile_write_then_read_roundtrip) {
const std::string path = temp_path("dio");
const int64_t A = DirectFile::alignment();
const int64_t body = 3 * A, tail = 123;
DirectFile f;
CHECK_OK(f.open(path.c_str(), RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE | RAD_DIO_TRUNC |
RAD_DIO_ALLOW_BUFFERED));
if (!f.is_open()) return;
if (!f.direct())
fprintf(stderr, " (note: %s has no O_DIRECT; the buffered fallback is under test)\n",
path.c_str());
CHECK_EQ(f.size(), (int64_t)0);
/* A pinned buffer is what the mover reads into, so that is what the aligned path is tested
* with: page-aligned address, aligned offset, aligned length, and therefore one pread with no
* copy anywhere in between. */
auto* w = (uint8_t*)rad_dev_alloc(body, RAD_MEM_HOST_PINNED);
auto* r = (uint8_t*)rad_dev_alloc(body, RAD_MEM_HOST_PINNED);
CHECK(w && r);
if (!w || !r) { f.close(); ::unlink(path.c_str()); return; }
fill(w, body, 0xD1EC7);
CHECK_OK(f.write_at(w, 0, body));
CHECK_EQ(f.size(), body);
/* The misaligned tail: an unaligned length, from an unaligned stack buffer. This is the only
* bounce in the read path and it exists because O_DIRECT will EINVAL the alternative. */
uint8_t t[tail];
fill(t, tail, 0x7A11);
CHECK_OK(f.write_at(t, body, tail));
CHECK_EQ(f.size(), body + tail);
std::memset(r, 0, (size_t)body);
CHECK_OK(f.read_at(r, 0, body));
CHECK_EQ(std::memcmp(r, w, (size_t)body), 0);
uint8_t t2[tail];
std::memset(t2, 0, sizeof t2);
CHECK_OK(f.read_at(t2, body, tail));
CHECK_EQ(std::memcmp(t2, t, sizeof t2), 0);
/* A slice that is aligned at neither end and straddles two blocks. */
uint8_t slice[2000];
CHECK_OK(f.read_at(slice, 1000, sizeof slice));
CHECK_EQ(std::memcmp(slice, w + 1000, sizeof slice), 0);
/* One byte past the end is RAD_E_IO, not a short read: read_at fills exactly what was asked
* for or fails, so no caller has to check a byte count on the step path. */
CHECK(f.read_at(t2, body, tail + 1) < 0);
CHECK(f.read_at(r, body + tail + A, A) < 0);
/* Reopen without O_TRUNC: the bytes are on disk, not in this handle. */
f.close();
CHECK_OK(f.open(path.c_str(), RAD_DIO_READ | RAD_DIO_ALLOW_BUFFERED));
CHECK_EQ(f.size(), body + tail);
std::memset(r, 0, (size_t)body);
CHECK_OK(f.read_at(r, 0, body));
CHECK_EQ(std::memcmp(r, w, (size_t)body), 0);
f.close();
CHECK(f.read_at(r, 0, A) < 0); /* closed is RAD_E_STATE, not a crash */
CHECK_EQ(f.size(), (int64_t)-1);
rad_dev_free(w, RAD_MEM_HOST_PINNED);
rad_dev_free(r, RAD_MEM_HOST_PINNED);
::unlink(path.c_str());
}
TEST(directfile_refuses_a_missing_file) {
DirectFile f;
CHECK(f.open("/nonexistent/rad/dio/path.bin", RAD_DIO_READ | RAD_DIO_ALLOW_BUFFERED) < 0);
CHECK(!f.is_open());
CHECK(f.open(nullptr, RAD_DIO_READ) < 0);
}
/* ------------------------------------------------------------------ elastic memory
*
* WHAT THESE ARE HOLDING DOWN. An elastic pool exists so two pools can trade VRAM -- the KV cache
* gives back what no session is holding and the expert slab takes it -- and the trade is only safe
* if three things are exactly true: an address never moves, a granule the caller still wants is
* never unmapped, and a range that comes back is backed by real pages rather than merely listed as
* backed. Each of the three fails silently in its own way. A moved address is a kernel reading
* another group's blocks; a granule unmapped under live data is a fault at an address that was
* valid a moment ago; a range that is listed but not mapped is a fault the first time a sequence
* writes past the old boundary, under load, long after the commit that was supposed to back it.
*
* The interval arithmetic is the whole of the risk and none of it needs a card, so it is held down
* here against the host backend, where a decommitted page can also be PROVEN gone by reading it
* back as zero.
*/
TEST(elastic_memory_takes_address_space_and_no_pages) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP elastic_memory_takes_address_space_and_no_pages: "
"no virtual memory management on this backend\n");
return;
}
const int64_t g = rad::VMem::granularity();
CHECK(g > 0);
CHECK_EQ(g % 4096, 0); /* a granule is whole pages, whatever else it is */
rad::VMem v;
CHECK_OK(v.reserve(8 * g));
CHECK(v.base() != nullptr);
CHECK_EQ(v.size(), 8 * g);
CHECK_EQ(v.committed(), 0); /* reserved is not allocated: this is the whole point */
CHECK_EQ((int64_t)((uintptr_t)v.base() % (uintptr_t)g), 0);
/* A SIZE THAT IS NOT A WHOLE NUMBER OF GRANULES ROUNDS UP. The last partial granule can never
* be committed, so leaving it out of the range would reserve bytes nothing could ever back. */
rad::VMem odd;
CHECK_OK(odd.reserve(g + 1));
CHECK_EQ(odd.size(), 2 * g);
CHECK_EQ(v.reserve(0), RAD_E_INVAL);
CHECK_EQ(v.size(), 0); /* and a refused reserve released what it held */
}
TEST(a_committed_range_is_backed_and_keeps_its_address) {
if (!rad::VMem::supported() || !rad::device_is_host()) {
std::fprintf(stderr, " SKIP a_committed_range_is_backed_and_keeps_its_address: "
"needs host-visible elastic memory\n");
return;
}
const int64_t g = rad::VMem::granularity();
rad::VMem v;
CHECK_OK(v.reserve(8 * g));
void* const addr = v.base();
CHECK_OK(v.commit(0, 2 * g));
CHECK_EQ(v.committed(), 2 * g);
CHECK(v.is_committed(0, 2 * g));
CHECK(!v.is_committed(0, 3 * g));
fill((uint8_t*)v.base(), 2 * g, 0x5eedu);
uint8_t expect[128];
fill(expect, sizeof expect, 0x5eedu);
CHECK_EQ(std::memcmp(v.base(), expect, sizeof expect), 0);
/* Growing at the far end must not disturb what is already there, and must not move the base:
* every block index the pool has handed out is an offset from it. */
CHECK_OK(v.commit(6 * g, 2 * g));
CHECK_EQ(v.committed(), 4 * g);
CHECK_EQ(v.base(), addr);
CHECK_EQ(std::memcmp(v.base(), expect, sizeof expect), 0);
}
TEST(commit_rounds_outward_and_decommit_rounds_inward) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP commit_rounds_outward_and_decommit_rounds_inward: "
"no virtual memory management on this backend\n");
return;
}
const int64_t g = rad::VMem::granularity();
rad::VMem v;
CHECK_OK(v.reserve(4 * g));
/* One byte in the middle of a granule needs the whole granule, or the byte is not backed. */
CHECK_OK(v.commit(g / 2, 1));
CHECK_EQ(v.committed(), g);
CHECK(v.is_committed(0, g));
/* And a decommit that does not cover a whole granule takes nothing, because the rest of that
* granule is data somebody still owns. */
CHECK_OK(v.decommit(g / 2, 1));
CHECK_EQ(v.committed(), g);
CHECK_OK(v.decommit(0, g - 1));
CHECK_EQ(v.committed(), g);
CHECK_OK(v.decommit(0, g));
CHECK_EQ(v.committed(), 0);
}
TEST(the_commit_quantum_is_the_pool_alignment_on_every_backend) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP the_commit_quantum_is_the_pool_alignment_on_every_backend: "
"no virtual memory management on this backend\n");
return;
}
/* WHAT A TEST PINS HERE HAS TO BE WHAT THE CARD RUNS, and the granule is what decides that.
* A driver's own answer is a floor -- one reports a single host page -- and a backend that
* took it would grow in pieces the host suite never exercises and pay a driver call for each
* of them. Both backends take RAD_ALIGN_POOL instead, which every pool is already aligned to,
* so a commit arithmetic checked on a machine with no card is the commit arithmetic a card
* performs. */
const int64_t g = rad::VMem::granularity();
CHECK(g >= (int64_t)RAD_ALIGN_POOL);
CHECK_EQ(g % (int64_t)RAD_ALIGN_POOL, 0);
}
TEST(committing_over_a_commit_maps_only_the_gap) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP committing_over_a_commit_maps_only_the_gap: "
"no virtual memory management on this backend\n");
return;
}
const int64_t g = rad::VMem::granularity();
rad::VMem v;
CHECK_OK(v.reserve(8 * g));
/* A pool that grows a granule at a time asks for [0,n) every time it changes n. The driver
* refuses a map that overlaps a map, so the overlap has to be subtracted here -- and this is
* the case that would otherwise work in every test that grows from nothing and fail the first
* time a live pool grew twice. */
CHECK_OK(v.commit(0, 2 * g));
CHECK_OK(v.commit(0, 5 * g));
CHECK_EQ(v.committed(), 5 * g);
CHECK_OK(v.commit(0, 5 * g));
CHECK_EQ(v.committed(), 5 * g);
/* Two islands and then the bridge between them. */
rad::VMem w;
CHECK_OK(w.reserve(8 * g));
CHECK_OK(w.commit(0, g));
CHECK_OK(w.commit(4 * g, g));
CHECK_EQ(w.committed(), 2 * g);
CHECK_OK(w.commit(0, 5 * g));
CHECK_EQ(w.committed(), 5 * g);
CHECK(w.is_committed(0, 5 * g));
/* Past the end clamps rather than failing: the range is the maximum by construction and a
* caller asking for all of it is asking for what is left. */
CHECK_OK(w.commit(7 * g, 4 * g));
CHECK_EQ(w.committed(), 6 * g);
}
TEST(decommitting_the_middle_leaves_the_ends) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP decommitting_the_middle_leaves_the_ends: "
"no virtual memory management on this backend\n");
return;
}
const int64_t g = rad::VMem::granularity();
rad::VMem v;
CHECK_OK(v.reserve(8 * g));
CHECK_OK(v.commit(0, 4 * g));
CHECK_OK(v.decommit(g, g));
CHECK_EQ(v.committed(), 3 * g);
CHECK(v.is_committed(0, g));
CHECK(!v.is_committed(g, g));
CHECK(v.is_committed(2 * g, 2 * g));
/* And the span across the hole is not committed, which is the question a caller actually asks
* before handing a range to a kernel. */
CHECK(!v.is_committed(0, 4 * g));
/* The hole fills back in and the extents merge, so the next question is answered by one
* comparison rather than by a list that grows for the life of the process. */
CHECK_OK(v.commit(g, g));
CHECK_EQ(v.committed(), 4 * g);
CHECK(v.is_committed(0, 4 * g));
}
TEST(a_recommitted_range_comes_back_zeroed) {
if (!rad::VMem::supported() || !rad::device_is_host()) {
std::fprintf(stderr, " SKIP a_recommitted_range_comes_back_zeroed: "
"needs host-visible elastic memory\n");
return;
}
const int64_t g = rad::VMem::granularity();
rad::VMem v;
CHECK_OK(v.reserve(4 * g));
CHECK_OK(v.commit(0, 2 * g));
fill((uint8_t*)v.base(), 2 * g, 0xabcdu);
CHECK((( uint8_t*)v.base())[g] != 0);
/* THE PAGES REALLY WENT BACK. A decommit that merely forgot the range would leave the old
* bytes in place and the VRAM spent, and every test above would still pass -- so the proof
* that the memory was returned is that what comes back is not what was there. */
CHECK_OK(v.decommit(0, 2 * g));
CHECK_EQ(v.committed(), 0);
CHECK_OK(v.commit(0, 2 * g));
const uint8_t* b = (const uint8_t*)v.base();
for (int64_t i = 0; i < 2 * g; i += 4093) CHECK_EQ((int)b[i], 0);
}
TEST(elastic_memory_is_accounted_and_released_whole) {
if (!rad::VMem::supported()) {
std::fprintf(stderr, " SKIP elastic_memory_is_accounted_and_released_whole: "
"no virtual memory management on this backend\n");
return;
}
const int64_t g = rad::VMem::granularity();
const int64_t before = rad::rad_dev_vmem_committed();
{
rad::VMem v;
CHECK_OK(v.reserve(8 * g));
CHECK_OK(v.commit(0, 3 * g));
CHECK_EQ(rad::rad_dev_vmem_committed() - before, 3 * g);
CHECK_OK(v.decommit(0, g));
CHECK_EQ(rad::rad_dev_vmem_committed() - before, 2 * g);
/* Destruction releases what is still committed. A range freed with pages in it leaks the
* pages, and on some drivers refuses the address free as well -- which is why the order is
* fixed inside release() rather than asked of every caller. */
}
CHECK_EQ(rad::rad_dev_vmem_committed(), before);
}
RAD_TEST_MAIN()
+494
View File
@@ -0,0 +1,494 @@
/* encoding_test.cpp -- weight encodings: the struct, its spelling, its geometry, the core's decoder
* and the plane cuts tensor parallelism takes. spec.md §4.1.
*
* The decoder is checked against values worked by hand rather than against a second
* implementation of itself: a scale that lands on the wrong block, a zero point subtracted after
* the multiply instead of before, a nibble read from the wrong half of a byte -- each gives a
* plausible number, and only an expected value that did not come from the code can tell.
*/
#include "rad_test.h"
#include "rad_types.h"
#include "rad_plugin.h"
#include "format/encoding.h"
#include <cstring>
#include <string>
#include <vector>
using namespace rad;
TEST(encodings_spell_themselves_canonically) {
CHECK_EQ(enc_name(rad_enc_plain(RAD_BF16)), std::string("bf16"));
RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
CHECK_EQ(enc_name(fp8), std::string("fp8_e4m3*bf16[128x128]"));
RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
rad_enc_copy_str(w4.transform, "fwht128");
CHECK_EQ(enc_name(w4), std::string("i4*bf16[1x128]/fwht128"));
RadEncoding w2 = rad_enc_affine(RAD_U2, RAD_F16, 1, 128);
rad_enc_add_plane(&w2, "zero", RAD_U8, 1, 128);
CHECK_EQ(enc_name(w2), std::string("u2*f16[1x128]-u8[1x128]"));
RadEncoding tensor = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 0, 0);
CHECK_EQ(enc_name(tensor), std::string("fp8_e4m3*bf16[*x*]"));
RadEncoding own;
rad_enc_clear(&own);
rad_enc_copy_str(own.scheme, "lattice");
rad_enc_add_plane(&own, "codes", RAD_U8, 1, 1);
rad_enc_add_plane(&own, "book", RAD_F16, 0, 0);
CHECK_EQ(enc_name(own), std::string("lattice:codes=u8[1x1],book=f16[*x*]"));
/* NVFP4: an e4m3 scale a 16 and an f32 a tensor, read in the order they multiply */
RadEncoding nv = rad_enc_affine(RAD_FP4E2M1, RAD_F8E4M3, 1, 16);
rad_enc_add_plane(&nv, "scale.1", RAD_F32, 0, 0);
CHECK(rad_enc_valid(&nv));
CHECK_EQ(enc_name(nv), std::string("fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]"));
/* Q4_K's min chain has no short form */
RadEncoding qk = rad_enc_affine(RAD_U4, RAD_U6, 1, 32);
rad_enc_add_plane(&qk, "scale.1", RAD_F16, 1, 256);
rad_enc_add_plane(&qk, "min", RAD_U6, 1, 32);
rad_enc_add_plane(&qk, "min.1", RAD_F16, 1, 256);
CHECK(rad_enc_valid(&qk));
CHECK_EQ(enc_name(qk), std::string("affine:codes=u4[1x1],scale=u6[1x32],scale.1=f16[1x256],"
"min=u6[1x32],min.1=f16[1x256]"));
/* a TABLE plane is written with its own extents */
RadEncoding nl = rad_enc_affine(RAD_U4, RAD_F16, 1, 32);
rad_enc_add_table(&nl, "table", RAD_I8, 1, 16);
CHECK(rad_enc_valid(&nl));
CHECK_EQ(enc_name(nl), std::string("affine:codes=u4[1x1],scale=f16[1x32],table=i8{1x16}"));
}
TEST(only_well_formed_encodings_are_valid) {
RadEncoding e = rad_enc_plain(RAD_BF16);
CHECK(rad_enc_valid(&e));
e = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
CHECK(rad_enc_valid(&e));
/* a rotation on a plain weight says nothing a reader could undo */
e = rad_enc_plain(RAD_BF16);
rad_enc_copy_str(e.transform, "fwht128");
CHECK(!rad_enc_valid(&e));
/* not a power of two */
e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 96);
rad_enc_copy_str(e.transform, "fwht96");
CHECK(!rad_enc_valid(&e));
/* affine with nothing beyond the codes is plain, and a weight has one spelling */
e = rad_enc_plain(RAD_I4);
rad_enc_copy_str(e.scheme, "affine");
CHECK(!rad_enc_valid(&e));
/* a plugin-private dtype in a container would be unreadable without that plugin */
e = rad_enc_plain(RAD_DT_PLUGIN_BASE + 3);
CHECK(!rad_enc_valid(&e));
/* the codes come first and cover one value each -- unless a grid expands them */
e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
e.plane[0].block[1] = 2;
CHECK(!rad_enc_valid(&e));
rad_enc_add_table(&e, "grid", RAD_I8, 16, 2);
CHECK(rad_enc_valid(&e));
e.plane[2].extent[1] = 4; /* a grid of 4-vectors for 2-wide codes */
CHECK(!rad_enc_valid(&e));
/* a scale.2 needs a scale.1 under it */
e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 32);
rad_enc_add_plane(&e, "scale.2", RAD_F32, 0, 0);
CHECK(!rad_enc_valid(&e));
/* a role the scheme does not read is a mistake, not an extension */
e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 32);
rad_enc_add_plane(&e, "scales", RAD_F32, 0, 0);
CHECK(!rad_enc_valid(&e));
/* a transform needs its tables */
e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 32);
rad_enc_copy_str(e.transform, "givens");
CHECK(!rad_enc_valid(&e));
/* signs are one bit a value */
e = rad_enc_affine(RAD_U4, RAD_BF16, 1, 32);
rad_enc_add_plane(&e, "signs", RAD_U2, 1, 1);
CHECK(!rad_enc_valid(&e));
}
TEST(plane_geometry_rounds_blocks_up_and_rows_to_a_byte) {
const RadEncoding e = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&e.plane[0], 10, 300, &pr, &pc);
CHECK_EQ(pr, 10);
CHECK_EQ(pc, 300);
CHECK_EQ(rad_enc_plane_bytes(&e.plane[0], 10, 300), 10 * 150);
rad_enc_plane_dims(&e.plane[1], 10, 300, &pr, &pc);
CHECK_EQ(pr, 10);
CHECK_EQ(pc, 3); /* 128 + 128 + a short last block */
CHECK_EQ(rad_enc_plane_bytes(&e.plane[1], 10, 300), 10 * 3 * 2);
/* 2-bit codes, 7 a row: two bytes a row, not seven quarter-bytes run together */
const RadEncoding u2 = rad_enc_plain(RAD_U2);
CHECK_EQ(rad_enc_plane_bytes(&u2.plane[0], 3, 7), 3 * 2);
const RadEncoding t = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 0, 0);
rad_enc_plane_dims(&t.plane[1], 320001536, 160, &pr, &pc);
CHECK_EQ(pr, 1);
CHECK_EQ(pc, 1);
int64_t rows = 0, cols = 0;
const int64_t shape3[3] = { 4, 5, 6 };
rad_enc_view(3, shape3, &rows, &cols);
CHECK_EQ(rows, 20);
CHECK_EQ(cols, 6);
const int64_t shape1[1] = { 9 };
rad_enc_view(1, shape1, &rows, &cols);
CHECK_EQ(rows, 1);
CHECK_EQ(cols, 9);
}
TEST(sub_byte_codes_pack_low_bits_first) {
uint8_t b[4] = { 0, 0, 0, 0 };
CHECK(rad_store_code(b, RAD_I4, 0, -3)); /* 0xd */
CHECK(rad_store_code(b, RAD_I4, 1, 7)); /* 0x7 */
CHECK_EQ((int)b[0], 0x7d);
CHECK_EQ(rad_load_f32(b, RAD_I4, 0), -3.0f);
CHECK_EQ(rad_load_f32(b, RAD_I4, 1), 7.0f);
CHECK_EQ(rad_load_f32(b, RAD_U4, 0), 13.0f);
std::memset(b, 0, sizeof b);
for (int i = 0; i < 4; ++i) CHECK(rad_store_code(b, RAD_U2, i, i));
CHECK_EQ((int)b[0], 0xe4); /* 3 2 1 0 */
for (int i = 0; i < 4; ++i) CHECK_EQ(rad_load_f32(b, RAD_U2, i), (float)i);
CHECK_EQ(rad_load_f32(b, RAD_I2, 3), -1.0f);
CHECK_EQ(rad_load_f32(b, RAD_I2, 2), -2.0f);
/* fp4 e2m1: 0x7 is 6, 0x9 is -0.5 */
b[1] = 0x97;
CHECK_EQ(rad_load_f32(b + 1, RAD_FP4E2M1, 0), 6.0f);
CHECK_EQ(rad_load_f32(b + 1, RAD_FP4E2M1, 1), -0.5f);
b[2] = 127;
CHECK_EQ(rad_load_f32(b + 2, RAD_E8M0, 0), 1.0f);
b[2] = 130;
CHECK_EQ(rad_load_f32(b + 2, RAD_E8M0, 0), 8.0f);
b[2] = 0xff;
CHECK(std::isnan(rad_load_f32(b + 2, RAD_E8M0, 0)));
CHECK(!rad_store_code(b, RAD_F32, 0, 1)); /* wider than 16 bits is not a code */
}
TEST(odd_widths_are_a_bit_stream_that_straddles_bytes) {
/* 3-bit codes 0..7 in a row: 24 bits, element 2 straddling bytes 0 and 1 */
uint8_t b[8] = {};
for (int i = 0; i < 8; ++i) CHECK(rad_store_code(b, RAD_U3, i, i));
CHECK_EQ((int)b[0], 0x88); /* 0b10 001 000: elements 0, 1, low of 2 */
for (int i = 0; i < 8; ++i) CHECK_EQ(rad_load_f32(b, RAD_U3, i), (float)i);
CHECK_EQ(rad_load_f32(b, RAD_I3, 7), -1.0f);
CHECK_EQ(rad_load_f32(b, RAD_I3, 4), -4.0f);
/* every width, a pattern that cannot pass by accident */
const uint32_t widths[] = { RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6, RAD_U7,
RAD_U9, RAD_U10, RAD_U11, RAD_U12 };
for (uint32_t dt : widths) {
const int bits = rad_dtype_bits(dt);
std::vector<uint8_t> row((size_t)(37 * bits + 7) / 8 + 2, 0xa5);
for (int i = 0; i < 37; ++i)
rad_store_code(row.data(), dt, i, (int)((i * 2654435761u) & ((1u << bits) - 1)));
int off = 0;
for (int i = 0; i < 37; ++i)
off += rad_load_f32(row.data(), dt, i) !=
(float)((i * 2654435761u) & ((1u << bits) - 1));
CHECK_EQ(off, 0);
}
/* signed widths: the extremes */
for (uint32_t dt : { RAD_I3, RAD_I5, RAD_I6, RAD_I7 }) {
const int bits = rad_dtype_bits(dt), lo = -(1 << (bits - 1)), hi = (1 << (bits - 1)) - 1;
uint8_t r[4] = {};
rad_store_code(r, dt, 0, lo);
rad_store_code(r, dt, 1, hi);
CHECK_EQ(rad_load_f32(r, dt, 0), (float)lo);
CHECK_EQ(rad_load_f32(r, dt, 1), (float)hi);
}
}
TEST(fp6_decodes_both_forms) {
uint8_t b[4] = {};
rad_store_code(b, RAD_FP6E2M3, 0, 0x1f); /* e=3 m=7: 1.875 * 4 */
rad_store_code(b, RAD_FP6E2M3, 1, 0x21); /* negative subnormal: -1/8 */
CHECK_EQ(rad_load_f32(b, RAD_FP6E2M3, 0), 7.5f);
CHECK_EQ(rad_load_f32(b, RAD_FP6E2M3, 1), -0.125f);
std::memset(b, 0, sizeof b);
rad_store_code(b, RAD_FP6E3M2, 0, 0x1f); /* e=7 m=3: 1.75 * 16 */
rad_store_code(b, RAD_FP6E3M2, 1, 0x0c); /* e=3 m=0: 1 */
CHECK_EQ(rad_load_f32(b, RAD_FP6E3M2, 0), 28.0f);
CHECK_EQ(rad_load_f32(b, RAD_FP6E3M2, 1), 1.0f);
}
TEST(affine_decodes_through_the_right_block_and_subtracts_the_zero_first) {
/* A 2 x 4 weight, u4 codes, a scale per [1 x 2] and a zero per [2 x 4]. */
RadEncoding e = rad_enc_affine(RAD_U4, RAD_F32, 1, 2);
rad_enc_add_plane(&e, "zero", RAD_U8, 2, 4);
CHECK(rad_enc_valid(&e));
uint8_t codes[4] = { 0, 0, 0, 0 };
const int q[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
for (int r = 0; r < 2; ++r)
for (int c = 0; c < 4; ++c) rad_store_code(codes + r * 2, RAD_U4, c, q[r * 4 + c]);
const float scale[4] = { 1.0f, 10.0f, 100.0f, 1000.0f }; /* [2][2] */
const uint8_t zero[1] = { 3 };
const void* planes[3] = { codes, scale, zero };
EncodedView v;
enc_view(e, 2, 4, planes, &v);
std::vector<float> out(8);
CHECK_EQ(enc_decode_rows(v, 0, 2, out.data()), RAD_OK);
const float want[8] = { -2, -1, 0, 10, 200, 300, 4000, 5000 };
for (int i = 0; i < 8; ++i) CHECK_EQ(out[(size_t)i], want[i]);
/* one row alone decodes the same */
std::vector<float> one(4);
CHECK_EQ(enc_decode_rows(v, 1, 1, one.data()), RAD_OK);
for (int i = 0; i < 4; ++i) CHECK_EQ(one[(size_t)i], want[4 + i]);
}
TEST(a_rotation_decodes_back_to_the_weight) {
/* Store v = H w / 4 for a 4-wide group; decoding applies H once more, H H = 4 I, so the
* weight comes back exactly -- the convention docs/MOE-W4.md folds into the stored scale. */
const float w[8] = { 1, -2, 3, 0.5f, 0, 0, 2, -1 };
float v[8];
std::memcpy(v, w, sizeof v);
fwht_inplace(v, 4);
fwht_inplace(v + 4, 4);
for (float& x : v) x /= 4.0f;
RadEncoding e = rad_enc_plain(RAD_F32);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "scale", RAD_F32, 0, 0);
rad_enc_copy_str(e.transform, "fwht4");
CHECK(rad_enc_valid(&e));
const float one = 1.0f;
const void* planes[2] = { v, &one };
EncodedView ev;
enc_view(e, 1, 8, planes, &ev);
float out[8];
CHECK_EQ(enc_decode_rows(ev, 0, 1, out), RAD_OK);
for (int i = 0; i < 8; ++i) CHECK_EQ(out[i], w[i]);
/* the Sylvester order: H_4 e_1 is the second column, (1, -1, 1, -1) */
float e1[4] = { 0, 1, 0, 0 };
fwht_inplace(e1, 4);
CHECK_EQ(e1[0], 1.0f);
CHECK_EQ(e1[1], -1.0f);
CHECK_EQ(e1[2], 1.0f);
CHECK_EQ(e1[3], -1.0f);
/* a group that does not divide the row is refused, not decoded short */
enc_view(e, 1, 6, planes, &ev);
std::string why;
CHECK_EQ(enc_decode_rows(ev, 0, 1, out, &why), RAD_E_SHAPE);
}
TEST(multilevel_scales_and_minimums_decode_as_the_k_quants_do) {
/* One row of 8: u4 codes, u6 scale and min per [1 x 4], f16 super-scale and super-min per row.
* w = d * sc * q - dmin * m, Q4_K's formula. */
RadEncoding e = rad_enc_affine(RAD_U4, RAD_U6, 1, 4);
rad_enc_add_plane(&e, "scale.1", RAD_F16, 1, 0);
rad_enc_add_plane(&e, "min", RAD_U6, 1, 4);
rad_enc_add_plane(&e, "min.1", RAD_F16, 1, 0);
REQUIRE(rad_enc_valid(&e));
uint8_t q[4] = {}, sc[2] = {}, mn[2] = {};
for (int i = 0; i < 8; ++i) rad_store_code(q, RAD_U4, i, i + 1);
rad_store_code(sc, RAD_U6, 0, 3);
rad_store_code(sc, RAD_U6, 1, 5);
rad_store_code(mn, RAD_U6, 0, 2);
rad_store_code(mn, RAD_U6, 1, 7);
const uint16_t d = rad_f32_to_f16(0.5f), dm = rad_f32_to_f16(0.25f);
const void* planes[5] = { q, sc, &d, mn, &dm };
EncodedView v;
enc_view(e, 1, 8, planes, &v);
float out[8];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int i = 0; i < 8; ++i) {
const float want = 0.5f * (i < 4 ? 3 : 5) * (float)(i + 1) - 0.25f * (i < 4 ? 2 : 7);
CHECK_EQ(out[i], want);
}
}
TEST(nvfp4_multiplies_both_scale_levels) {
RadEncoding e = rad_enc_affine(RAD_FP4E2M1, RAD_F8E4M3, 1, 16);
rad_enc_add_plane(&e, "scale.1", RAD_F32, 0, 0);
uint8_t q[16] = {};
for (int i = 0; i < 32; ++i) rad_store_code(q, RAD_FP4E2M1, i, i & 15);
const uint8_t s[2] = { rad_f32_to_fp8e4m3(2.0f), rad_f32_to_fp8e4m3(0.5f) };
const float t = 3.0f;
const void* planes[3] = { q, s, &t };
EncodedView v;
enc_view(e, 1, 32, planes, &v);
float out[32];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int i = 0; i < 32; ++i)
CHECK_EQ(out[i], rad_fp4e2m1_to_f32((uint8_t)(i & 15)) * (i < 16 ? 2.0f : 0.5f) * 3.0f);
}
TEST(a_scalar_codebook_maps_each_code_before_the_scale) {
/* IQ4_NL: the code indexes sixteen non-linear levels */
static const int8_t kvalues[16] = { -127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113 };
RadEncoding e = rad_enc_affine(RAD_U4, RAD_F16, 1, 4);
rad_enc_add_table(&e, "table", RAD_I8, 1, 16);
REQUIRE(rad_enc_valid(&e));
uint8_t q[2] = {};
const int codes[4] = { 0, 7, 8, 15 };
for (int i = 0; i < 4; ++i) rad_store_code(q, RAD_U4, i, codes[i]);
const uint16_t d = rad_f32_to_f16(0.25f);
const void* planes[3] = { q, &d, kvalues };
EncodedView v;
enc_view(e, 1, 4, planes, &v);
float out[4];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int i = 0; i < 4; ++i) CHECK_EQ(out[i], 0.25f * kvalues[codes[i]]);
}
TEST(a_vector_codebook_expands_a_code_into_its_grid_row_and_signs) {
/* IQ2-shaped: a u8 code per 4 values into a grid of 4-vectors, a sign bit a value, a u4
* scale per [1 x 8] and an f16 per row. */
static const uint8_t grid[3][4] = { { 8, 8, 8, 8 }, { 8, 25, 43, 8 }, { 43, 43, 25, 8 } };
RadEncoding e = rad_enc_affine(RAD_U8, RAD_U4, 1, 8);
e.plane[0].block[1] = 4;
rad_enc_add_plane(&e, "scale.1", RAD_F16, 1, 0);
rad_enc_add_table(&e, "grid", RAD_U8, 3, 4);
rad_enc_add_plane(&e, "signs", RAD_U1, 1, 1);
REQUIRE(rad_enc_valid(&e));
const uint8_t codes[2] = { 1, 2 };
uint8_t sc[1] = {};
rad_store_code(sc, RAD_U4, 0, 3);
const uint16_t d = rad_f32_to_f16(0.125f);
const uint8_t signs[1] = { 0x81 }; /* values 0 and 7 negative */
const void* planes[5] = { codes, sc, &d, grid, signs };
EncodedView v;
enc_view(e, 1, 8, planes, &v);
float out[8];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int i = 0; i < 8; ++i) {
float g = (float)grid[codes[i / 4]][i % 4];
if (i == 0 || i == 7) g = -g;
CHECK_EQ(out[i], g * 3.0f * 0.125f);
}
/* a code past the grid's end is a corrupt file, said so */
const uint8_t bad[2] = { 1, 9 };
const void* bp[5] = { bad, sc, &d, grid, signs };
enc_view(e, 1, 8, bp, &v);
std::string why;
CHECK_EQ(enc_decode_rows(v, 0, 1, out, &why), RAD_E_FORMAT);
}
TEST(an_act_order_permutation_puts_columns_back) {
RadEncoding e = rad_enc_plain(RAD_F32);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "scale", RAD_F32, 0, 0);
rad_enc_add_table(&e, "t.perm", RAD_I32, 1, 4);
rad_enc_copy_str(e.transform, "perm");
REQUIRE(rad_enc_valid(&e));
const float w[4] = { 10, 20, 30, 40 };
const int32_t perm[4] = { 2, 0, 3, 1 };
float vq[4];
for (int j = 0; j < 4; ++j) vq[j] = w[perm[j]]; /* stored in the order it was quantised */
const float one = 1.0f;
const void* planes[3] = { vq, &one, perm };
EncodedView v;
enc_view(e, 1, 4, planes, &v);
float out[4];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int j = 0; j < 4; ++j) CHECK_EQ(out[j], w[j]);
}
TEST(a_givens_transform_with_channel_scales_inverts) {
/* Two stages over 4 columns and a channel scale: build v = w . D . G1 . G2 the way a
* quantiser would, store v exactly, and decode back to w. */
const int K = 4;
const float w[4] = { 1.0f, -2.0f, 0.5f, 3.0f };
const float dsc[4] = { 2.0f, 0.5f, 1.0f, 4.0f };
const int32_t pairs[2][4] = { { 0, 1, 2, 3 }, { 0, 2, 1, 3 } };
const float ang[2][2] = { { 0.3f, -1.1f }, { 0.7f, 2.0f } };
double x[4];
for (int k = 0; k < K; ++k) x[k] = (double)w[k] * dsc[k];
for (int s = 0; s < 2; ++s)
for (int p = 0; p < 2; ++p) {
const int a = pairs[s][2 * p], b = pairs[s][2 * p + 1];
const double c = std::cos((double)ang[s][p]), sn = std::sin((double)ang[s][p]);
const double xa = x[a], xb = x[b];
x[a] = xa * c + xb * sn;
x[b] = xb * c - xa * sn;
}
float vq[4];
for (int k = 0; k < K; ++k) vq[k] = (float)x[k];
RadEncoding e = rad_enc_plain(RAD_F32);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "scale", RAD_F32, 0, 0);
rad_enc_add_table(&e, "t.pairs", RAD_I32, 2, 4);
rad_enc_add_table(&e, "t.angle", RAD_F32, 2, 2);
rad_enc_add_table(&e, "t.scale", RAD_F32, 1, 4);
rad_enc_copy_str(e.transform, "givens");
REQUIRE(rad_enc_valid(&e));
const float one = 1.0f;
const void* planes[5] = { vq, &one, pairs, ang, dsc };
EncodedView v;
enc_view(e, 1, 4, planes, &v);
float out[4];
REQUIRE_EQ(enc_decode_rows(v, 0, 1, out), RAD_OK);
for (int k = 0; k < K; ++k) CHECK(std::fabs(out[k] - w[k]) < 1e-5f);
}
TEST(the_core_declines_a_scheme_it_did_not_define) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "lattice");
rad_enc_add_plane(&e, "codes", RAD_U8, 1, 1);
uint8_t c = 0;
const void* planes[1] = { &c };
EncodedView v;
enc_view(e, 1, 1, planes, &v);
float out = 0;
std::string why;
CHECK_EQ(enc_decode_rows(v, 0, 1, &out, &why), RAD_E_UNSUPPORTED);
CHECK(why.find("lattice") != std::string::npos);
}
TEST(a_plane_is_cut_on_its_own_blocks) {
const RadEncoding e = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
PlaneRect r;
std::string why;
/* a row shard of a [5120, 17408] weight at tp 2 */
CHECK_EQ(enc_plane_rect(e.plane[0], 5120, 17408, 2560, 5120, 0, 17408, &r, &why), RAD_OK);
CHECK_EQ(r.row0, 2560);
CHECK_EQ(r.rows, 2560);
CHECK_EQ(enc_plane_rect(e.plane[1], 5120, 17408, 2560, 5120, 0, 17408, &r, &why), RAD_OK);
CHECK_EQ(r.row0, 20);
CHECK_EQ(r.rows, 20);
CHECK_EQ(r.cols, 136);
/* a 640-wide weight split 3:2 in 128-column blocks */
CHECK_EQ(enc_plane_rect(e.plane[1], 2560, 640, 0, 2560, 384, 640, &r, &why), RAD_OK);
CHECK_EQ(r.col0, 3);
CHECK_EQ(r.cols, 2);
/* half of 640 splits a block */
CHECK_EQ(enc_plane_rect(e.plane[1], 2560, 640, 0, 2560, 320, 640, &r, &why), RAD_E_SHAPE);
CHECK(why.find("splits") != std::string::npos);
/* the weight's own end is not a split: 300 columns end inside a block */
CHECK_EQ(enc_plane_rect(e.plane[1], 4, 300, 0, 4, 256, 300, &r, &why), RAD_OK);
CHECK_EQ(r.col0, 2);
CHECK_EQ(r.cols, 1);
/* a whole-extent scale belongs to every slice */
const RadEncoding t = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 0, 0);
CHECK_EQ(enc_plane_rect(t.plane[1], 1000, 160, 500, 1000, 0, 160, &r, &why), RAD_OK);
CHECK_EQ(r.row0, 0);
CHECK_EQ(r.rows, 1);
/* a table goes whole into every slice */
RadEncoding nl = rad_enc_affine(RAD_U4, RAD_F16, 1, 32);
rad_enc_add_table(&nl, "table", RAD_I8, 1, 16);
CHECK_EQ(enc_plane_rect(nl.plane[2], 64, 256, 32, 64, 128, 256, &r, &why), RAD_OK);
CHECK_EQ(r.rows, 1);
CHECK_EQ(r.cols, 16);
/* a 4-bit column cut must land on a byte */
const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 1);
CHECK_EQ(enc_plane_rect(w4.plane[0], 2, 10, 0, 2, 3, 10, &r, &why), RAD_E_SHAPE);
CHECK_EQ(enc_plane_rect(w4.plane[0], 2, 10, 0, 2, 4, 10, &r, &why), RAD_OK);
}
RAD_TEST_MAIN()
+997
View File
@@ -0,0 +1,997 @@
/* fixture_test.cpp -- the recorded reference itself: the draw, the reduction and the file.
*
* EVERY CORRECTNESS NUMBER THIS PROJECT REPORTS ABOUT A KERNEL IS RELATIVE TO THIS CODE.
* rad-kbench compares a kernel against an answer libref recorded at another time, possibly on
* another machine, and the only reason that comparison means anything is that both sides drew
* byte-identical inputs from a stored seed and reduced their outputs the same way. A drift in
* either half does not report as a harness fault: it reports as a page of kernel failures, or --
* much worse -- as agreement, because two sides that both produce zeros agree perfectly.
*
* So the cases here are about the properties the comparison RESTS on rather than about the
* arithmetic:
*
* - a weight's bytes depend on the operand's identity and not on the case, which is what lets
* an M sweep draw one weight once and is what makes two libraries comparable at all;
* - the blocked draw and the whole draw are one stream, because a large operand takes the first
* path and a small one the second and nothing else would notice they had parted;
* - the reduction is the same however many threads ran, or a recorded norm is machine-specific;
* - an input lands inside the domain its op is ever handed, or the comparison measures the
* condition number of the test;
* - every dtype a recorded case uses is one the harness can actually draw AND read back;
* - a weight's planes are drawn inside what each plane can hold, the reference reads what they
* decode to, and a kernel is handed what its own layout hooks make of them.
*/
#include "rad_test.h"
#include "kfixture.h"
#include "opshapes.h"
#include "rad_plugin.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <set>
#include <string>
#include <vector>
#include <unistd.h>
using namespace rad;
namespace {
std::string scratch_path(const char* leaf) {
const char* dir = std::getenv("TMPDIR");
return std::string(dir && *dir ? dir : "/tmp") + "/radiance_fixture_test_" + leaf;
}
/* An operand of `n` f32 elements laid out as `shape`, with the draw law the case is about. */
KfOperand opd_f32(std::vector<int64_t> shape, int role = RAD_OPD_IN, int fill = KF_FILL_NORMAL) {
KfOperand d;
d.role = role;
d.dtype = RAD_F32;
d.shape = std::move(shape);
d.fill = fill;
return d;
}
/* A weight operand of a block-fp8 [rows, cols] weight taking `roles`: one plane at its own
* extents, several at the codes' dtype and the logical extents -- as a declaration records it. */
KfOperand fp8_weight(int64_t rows, int64_t cols, std::vector<const char*> roles) {
KfOperand d;
d.role = RAD_OPD_WEIGHT;
d.has_enc = true;
rad_enc_clear(&d.enc);
rad_enc_copy_str(d.enc.scheme, "affine");
rad_enc_add_plane(&d.enc, "codes", RAD_F8E4M3, 1, 1);
rad_enc_add_plane(&d.enc, "scale", RAD_BF16, 128, 128);
for (const char* r : roles) {
const int i = rad_enc_find(&d.enc, r);
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&d.enc.plane[i], rows, cols, &pr, &pc);
d.sel.push_back(i);
d.sel_rows.push_back(pr);
d.sel_cols.push_back(pc);
}
if (roles.size() == 1) {
d.dtype = d.enc.plane[d.sel[0]].dtype;
d.shape = { d.sel_rows[0], d.sel_cols[0] };
} else {
d.dtype = RAD_F32;
d.shape = { rows, cols };
}
return d;
}
int64_t numel(const KfOperand& d) {
int64_t n = 1;
for (int64_t x : d.shape) n *= x;
return n;
}
std::vector<float> draw_f32(const std::vector<KfOperand>& opd, size_t k, int64_t M, uint64_t seed) {
std::vector<uint8_t> bytes;
kf_draw(opd, k, M, kf_vocab_rows(opd), seed, &bytes);
std::vector<float> out;
rad_widen(bytes.data(), opd[k].dtype, numel(opd[k]), &out);
return out;
}
} /* namespace */
/* ================================================================== the draw's block contract */
/* RAD_FILL_BLOCK is documented as part of the contract rather than an implementation detail, and
* this is what makes that true. kf_draw streams any operand past one block through
* rad_fill_normal_block so the float intermediate never gets as big as the tensor; everything
* smaller goes through rad_fill_normal in one pass. If those two ever stopped producing the same
* stream, a weight would be drawn differently depending only on its size, silently. */
TEST(a_blocked_draw_and_a_whole_one_are_the_same_stream) {
const int64_t n = RAD_FILL_BLOCK * 3 + 517; /* three full blocks and a partial one */
std::vector<float> whole((size_t)n, 0.0f);
rad_fill_normal(whole.data(), n, 0xC0FFEEull, 0.02f);
std::vector<float> piecewise((size_t)n, 0.0f);
for (int64_t lo = 0; lo < n; lo += RAD_FILL_BLOCK) {
const int64_t len = (n - lo) < RAD_FILL_BLOCK ? (n - lo) : RAD_FILL_BLOCK;
rad_fill_normal_block(piecewise.data() + lo, len, 0xC0FFEEull, lo / RAD_FILL_BLOCK, 0.02f);
}
CHECK_EQ(std::memcmp(whole.data(), piecewise.data(), (size_t)n * sizeof(float)), 0);
}
/* The threaded path is taken whenever the operand spans more than one block, and the work is
* handed out round-robin over however many cores the machine has. A draw that moved with the core
* count would make every recorded reference machine-specific. */
TEST(a_draw_does_not_change_between_runs) {
const int64_t n = RAD_FILL_BLOCK * 5;
std::vector<float> a((size_t)n, 0.0f), b((size_t)n, 0.0f);
rad_fill_normal(a.data(), n, 12345ull, 1.0f);
rad_fill_normal(b.data(), n, 12345ull, 1.0f);
CHECK_EQ(std::memcmp(a.data(), b.data(), (size_t)n * sizeof(float)), 0);
/* And that the fill is actually a unit-variance normal rather than, say, zeros -- a draw that
* silently produced nothing would satisfy every equality above. */
double ss = 0;
for (int64_t i = 0; i < n; ++i) ss += (double)a[(size_t)i] * (double)a[(size_t)i];
CHECK_NEAR(std::sqrt(ss / (double)n), 1.0, 0.02);
}
TEST(a_case_seed_separates_the_op_the_band_the_domain_and_the_operand) {
const uint64_t base = 7;
const uint64_t s = rad_case_seed(base, "rmsnorm", 0, 0, 0);
CHECK(s != rad_case_seed(base, "softmax", 0, 0, 0));
CHECK(s != rad_case_seed(base, "rmsnorm", 1, 0, 0));
CHECK(s != rad_case_seed(base, "rmsnorm", 0, 1, 0));
CHECK(s != rad_case_seed(base, "rmsnorm", 0, 0, 1));
CHECK_EQ(s, rad_case_seed(base, "rmsnorm", 0, 0, 0));
CHECK(rad_case_seed(base, "rmsnorm", 0, 0, 0) != 0);
}
/* ================================================================== narrow and widen */
/* THE PAIR HAS TO BE COMPLETE AT BOTH ENDS. rad_narrow writes the operand a kernel reads and
* rad_widen reads the operand a kernel wrote, so a dtype handled by one and not the other is a
* case that draws zeros or compares zeros -- and two zeroed sides agree, which reports as a
* pass. Held to the integer and float types the core's vocabulary names; the packed weight
* formats (W4, W2, MXFP4) are deliberately absent from both, since only the kernel's layout hook
* knows what their bytes mean.
*
* This is completeness and not identity, because the two halves are not inverses for every type:
* a drawn i8 is a QUANTISED unit normal and carries a scale, so writing 5.0 and reading 127 back
* is the pair working. Identity is asserted separately below, for the types where a value is its
* own meaning. */
TEST(every_plain_dtype_the_harness_writes_it_can_read_back) {
struct Row { uint32_t dt; const char* name; };
const Row rows[] = {
{ RAD_F32, "f32" }, { RAD_BF16, "bf16" }, { RAD_F16, "f16" },
{ RAD_F8E4M3, "f8e4m3" }, { RAD_F8E5M2, "f8e5m2" },
{ RAD_I8, "i8" }, { RAD_U8, "u8" }, { RAD_I16, "i16" },
{ RAD_I32, "i32" }, { RAD_I64, "i64" }, { RAD_U32, "u32" }, { RAD_BOOL, "bool" },
};
const float src[] = { 1.0f, 2.0f, 3.0f, 4.0f };
const int64_t n = (int64_t)(sizeof src / sizeof src[0]);
for (const Row& r : rows) {
std::vector<uint8_t> packed((size_t)rad_dtype_bytes(r.dt, n), 0);
rad_narrow(src, r.dt, n, packed.data());
bool wrote = false;
for (uint8_t b : packed) if (b) { wrote = true; break; }
std::vector<float> back;
rad_widen(packed.data(), r.dt, n, &back);
CHECK_EQ((int64_t)back.size(), n);
bool read = false;
for (float x : back) if (x != 0.0f) { read = true; break; }
if (!wrote || !read)
std::fprintf(stderr, " %s: narrow wrote %s, widen read %s\n", r.name,
wrote ? "bytes" : "NOTHING", read ? "values" : "NOTHING");
CHECK(wrote);
CHECK(read);
}
}
/* AN INTEGER OPERAND'S VALUE IS ITS MEANING, so these round trip exactly. They carry token ids,
* slot numbers, sequence lengths and table sizes -- a scale or a rounding rule on any of them is
* not a loss of precision, it is a different index. (i8 and u8 are absent on purpose: an i8
* operand in this vocabulary is a quantised activation, not an index.) */
TEST(an_integer_operand_round_trips_exactly) {
const uint32_t dts[] = { RAD_I16, RAD_I32, RAD_I64, RAD_U32 };
const float src[] = { 0.0f, 1.0f, 17.0f, 4095.0f, 65535.0f, 7.0f, 250.0f, 3.0f };
const int64_t n = (int64_t)(sizeof src / sizeof src[0]);
for (uint32_t dt : dts) {
std::vector<uint8_t> packed((size_t)rad_dtype_bytes(dt, n), 0);
rad_narrow(src, dt, n, packed.data());
std::vector<float> back;
rad_widen(packed.data(), dt, n, &back);
if ((int64_t)back.size() != n) { CHECK_EQ((int64_t)back.size(), n); continue; }
for (int64_t i = 0; i < n; ++i) {
/* i16 tops out below the largest probe and is expected to; everything else is exact. */
if (dt == RAD_I16 && src[i] > 32767.0f) continue;
if (back[(size_t)i] != src[i])
std::fprintf(stderr, " %s: %g came back %g\n", rad_dtype_name(dt), src[i],
back[(size_t)i]);
CHECK_EQ(back[(size_t)i], src[i]);
}
}
/* bool carries one bit of each value and is expected to. */
const float flags[] = { 0.0f, 1.0f, 0.0f, 9.0f };
std::vector<uint8_t> packed(4, 0xEE);
rad_narrow(flags, RAD_BOOL, 4, packed.data());
std::vector<float> back;
rad_widen(packed.data(), RAD_BOOL, 4, &back);
CHECK_EQ((int64_t)back.size(), (int64_t)4);
for (int i = 0; i < 4 && i < (int)back.size(); ++i)
CHECK_EQ(back[(size_t)i], flags[i] != 0.0f ? 1.0f : 0.0f);
}
/* The float formats round trip to their own precision, which is what makes a recorded bf16
* reference comparable against a bf16 output at all. */
TEST(a_float_dtype_round_trips_to_its_own_precision) {
struct Row { uint32_t dt; double tol; };
const Row rows[] = { { RAD_F32, 0.0 }, { RAD_BF16, 0.05 }, { RAD_F16, 0.005 },
{ RAD_F8E4M3, 0.0 }, { RAD_F8E5M2, 1.0 } };
const float src[] = { 0.0f, 1.0f, 2.0f, 5.0f, 9.0f, -3.0f, 7.0f, -4.0f };
const int64_t n = (int64_t)(sizeof src / sizeof src[0]);
for (const Row& r : rows) {
std::vector<uint8_t> packed((size_t)rad_dtype_bytes(r.dt, n), 0);
rad_narrow(src, r.dt, n, packed.data());
std::vector<float> back;
rad_widen(packed.data(), r.dt, n, &back);
if ((int64_t)back.size() != n) { CHECK_EQ((int64_t)back.size(), n); continue; }
for (int64_t i = 0; i < n; ++i)
CHECK_NEAR(back[(size_t)i], src[i], r.tol);
}
}
TEST(an_operand_seed_is_distinct_per_operand_and_stable) {
const uint64_t c = 0xABCDEF01ull;
std::set<uint64_t> seen;
for (int k = 0; k < 32; ++k) {
const uint64_t s = kf_operand_seed(c, k);
CHECK(seen.insert(s).second);
CHECK_EQ(s, kf_operand_seed(c, k));
}
CHECK(kf_operand_seed(c, 0) != kf_operand_seed(c + 1, 0));
}
/* A WEIGHT'S SEED IS ITS IDENTITY, NOT ITS CASE, and that is load-bearing twice over: it is what
* lets an M sweep of ten query lengths draw one 178-million-element weight once, and it is the
* key the caller caches the drawn bytes under. Keyed on the case instead, the cache would never
* hit and the same weight would be a different weight at every point of the sweep. */
TEST(a_weight_is_drawn_from_its_own_identity_and_not_the_case) {
std::vector<KfOperand> opd = { opd_f32({ 64, 32 }, RAD_OPD_WEIGHT) };
std::vector<uint8_t> a, b;
kf_draw(opd, 0, /*M=*/1, kf_vocab_rows(opd), kf_operand_seed(111, 0), &a);
kf_draw(opd, 0, /*M=*/512, kf_vocab_rows(opd), kf_operand_seed(999, 0), &b);
CHECK_EQ(a.size(), b.size());
CHECK_EQ(std::memcmp(a.data(), b.data(), a.size()), 0);
/* And the identity is position, dtype and extents -- a change in any of them is a different
* weight, or two unrelated operands would share a cache entry. */
const uint64_t s = kf_weight_seed(opd[0], 0);
CHECK_EQ(s, kf_weight_seed(opd[0], 0));
CHECK(s != kf_weight_seed(opd[0], 1));
KfOperand other = opd[0];
other.dtype = RAD_BF16;
CHECK(s != kf_weight_seed(other, 0));
other = opd[0];
other.shape = { 32, 64 };
CHECK(s != kf_weight_seed(other, 0));
}
/* A weight is drawn at a checkpoint's scale rather than at unit variance. Drawn unit, an fp8
* quantiser's amax sits three orders of magnitude off where a real one does, so the case would
* measure the quantiser on data no model produces. */
TEST(a_weight_is_drawn_at_the_scale_a_checkpoint_holds) {
std::vector<KfOperand> opd = { opd_f32({ 256, 256 }, RAD_OPD_WEIGHT) };
const std::vector<float> w = draw_f32(opd, 0, 1, 0);
double ss = 0;
for (float x : w) ss += (double)x * (double)x;
CHECK_NEAR(std::sqrt(ss / (double)w.size()), 0.02, 0.002);
}
/* ================================================================== sampling positions */
TEST(a_small_operand_is_sampled_exhaustively) {
std::vector<int64_t> pos;
kf_sample_positions(42, 300, &pos);
CHECK_EQ((int64_t)pos.size(), 300);
for (int64_t i = 0; i < 300; ++i) CHECK_EQ(pos[(size_t)i], i);
/* Below the sample count the seed cannot matter, because nothing is drawn. */
std::vector<int64_t> other;
kf_sample_positions(43, 300, &other);
CHECK(pos == other);
}
TEST(a_large_operand_is_sampled_at_positions_both_sides_can_derive) {
const int64_t n = 1 << 20;
std::vector<int64_t> a, b;
kf_sample_positions(0x5EEDull, n, &a);
kf_sample_positions(0x5EEDull, n, &b);
CHECK_EQ((int64_t)a.size(), (int64_t)KF_SAMPLES);
CHECK(a == b);
for (int64_t p : a) CHECK(p >= 0 && p < n);
std::vector<int64_t> c;
kf_sample_positions(0x5EEEull, n, &c);
CHECK(a != c);
}
TEST(an_empty_operand_is_sampled_at_no_position) {
std::vector<int64_t> pos = { 9 };
kf_sample_positions(1, 0, &pos);
CHECK(pos.empty());
kf_sample_positions(1, -4, &pos);
CHECK(pos.empty());
}
/* ================================================================== the reduction */
/* The reduction is threaded over blocks and the partials are added back in BLOCK order, so the
* sum does not move with the core count. Checked against a serial sum taken the same way rather
* than against a naive left-to-right one, which is a different number in floating point and
* would make this a test of associativity. */
TEST(the_reduction_adds_its_blocks_back_in_order) {
const int64_t n = KF_REDUCE_BLOCK * 3 + 1000; /* past the threaded threshold */
std::vector<float> v((size_t)n, 0.0f);
rad_fill_normal(v.data(), n, 0xBEEFull, 1.0f);
double got_ss = 0;
int64_t got_nf = 0;
std::vector<float> sample;
kf_reduce(v.data(), n, 7, &got_ss, &got_nf, &sample);
double want = 0;
for (int64_t lo = 0; lo < n; lo += KF_REDUCE_BLOCK) {
const int64_t hi = std::min<int64_t>(lo + KF_REDUCE_BLOCK, n);
double part = 0;
for (int64_t i = lo; i < hi; ++i) part += (double)v[(size_t)i] * (double)v[(size_t)i];
want += part;
}
CHECK_EQ(got_ss, want);
CHECK_EQ(got_nf, (int64_t)0);
double again_ss = 0;
int64_t again_nf = 0;
std::vector<float> again;
kf_reduce(v.data(), n, 7, &again_ss, &again_nf, &again);
CHECK_EQ(again_ss, got_ss);
CHECK(again == sample);
}
/* A NaN on one side and a number on the other is a failure and is checked before any tolerance,
* so the count has to be exact -- and a non-finite element must not enter the norm, or one NaN
* makes the whole sum NaN and every comparison against it meaningless. */
TEST(a_non_finite_element_is_counted_and_kept_out_of_the_norm) {
std::vector<float> v(10, 2.0f);
v[3] = std::nanf("");
v[7] = INFINITY;
double ss = 0;
int64_t nf = 0;
std::vector<float> sample;
kf_reduce(v.data(), (int64_t)v.size(), 1, &ss, &nf, &sample);
CHECK_EQ(nf, (int64_t)2);
CHECK_EQ(ss, 8.0 * 4.0); /* the eight finite 2.0s */
CHECK_EQ((int64_t)sample.size(), (int64_t)v.size());
CHECK(std::isnan(sample[3]));
CHECK(std::isinf(sample[7]));
}
TEST(the_reduction_samples_the_positions_a_reader_will_ask_for) {
const int64_t n = (int64_t)KF_SAMPLES * 4;
std::vector<float> v((size_t)n, 0.0f);
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = (float)i;
double ss = 0;
int64_t nf = 0;
std::vector<float> sample;
kf_reduce(v.data(), n, 0x1234ull, &ss, &nf, &sample);
std::vector<int64_t> pos;
kf_sample_positions(0x1234ull, n, &pos);
CHECK_EQ(sample.size(), pos.size());
for (size_t i = 0; i < pos.size() && i < sample.size(); ++i)
CHECK_EQ(sample[i], (float)pos[i]);
}
/* ================================================================== the input-domain laws
*
* Each of these puts an operand inside the domain its op is only ever handed. Drawn outside it,
* the two implementations disagree by however ill-conditioned the input is and the report blames
* the kernel for the condition number of the test.
*/
/* Cumulative sequence lengths are the batch's shape, not a draw: every gated-delta-net kernel
* opens by reading cu[n] before any null test, so a wrong one faults rather than answering. */
TEST(a_cumulative_length_operand_is_the_batch_shape_not_a_draw) {
KfOperand d = opd_f32({ 5 });
d.dtype = RAD_I32;
d.is_index = true;
d.idx_cu = true;
const std::vector<float> v = draw_f32({ d }, 0, /*M=*/100, 0xAAAA);
CHECK_EQ((int64_t)v.size(), (int64_t)5);
CHECK_EQ(v[0], 0.0f);
CHECK_EQ(v[4], 100.0f);
for (size_t i = 1; i < v.size(); ++i) CHECK(v[i] >= v[i - 1]);
}
/* A length is a length. A random context shorter than the query makes causal attention read a
* prefix that does not exist, and both implementations then agree about the garbage. */
TEST(a_length_operand_is_the_constant_it_was_recorded_with) {
KfOperand d = opd_f32({ 6 });
d.dtype = RAD_I32;
d.is_index = true;
d.idx_const = 4096;
const std::vector<float> v = draw_f32({ d }, 0, 8, 0xBBBB);
for (float x : v) CHECK_EQ(x, 4096.0f);
}
/* A scatter's destinations must be distinct: two tokens on one slot is a race the two
* implementations resolve differently, so the comparison would measure the scheduler. */
TEST(a_scatter_destination_is_drawn_without_repeats) {
KfOperand d = opd_f32({ 8 });
d.dtype = RAD_I32;
d.is_index = true;
d.idx_unique = true;
d.idx_max = 16;
const std::vector<float> v = draw_f32({ d }, 0, 8, 0xCCCC);
std::set<int> seen;
for (float x : v) {
CHECK(x >= 0.0f && x < 16.0f);
CHECK(seen.insert((int)x).second);
}
/* Asked for more destinations than the range holds, the surplus is marked rather than
* repeated: a duplicate would be the very race the law exists to keep out. */
d.idx_max = 4;
const std::vector<float> w = draw_f32({ d }, 0, 8, 0xCCCC);
std::set<int> first;
for (size_t i = 0; i < 4; ++i) CHECK(first.insert((int)w[i]).second);
for (size_t i = 4; i < w.size(); ++i) CHECK_EQ(w[i], -1.0f);
}
/* An index indexes the operand before it, and its leading extent is the only legal range. */
TEST(an_index_operand_stays_inside_the_operand_it_indexes) {
std::vector<KfOperand> opd = { opd_f32({ 7, 3 }, RAD_OPD_WEIGHT), opd_f32({ 32 }) };
opd[1].dtype = RAD_I32;
opd[1].is_index = true;
const std::vector<float> v = draw_f32(opd, 1, 32, 0xDDDD);
bool any_past_zero = false;
for (float x : v) {
CHECK(x >= 0.0f && x < 7.0f);
if (x > 0.0f) any_past_zero = true;
}
CHECK(any_past_zero); /* drawn, not zeroed */
/* Where the range is not any operand's leading extent -- a KV slot indexes
* n_blocks * block_size -- the recipe names it and the named range wins. */
opd[1].idx_max = 200;
const std::vector<float> w = draw_f32(opd, 1, 32, 0xDDDD);
bool past_seven = false;
for (float x : w) {
CHECK(x >= 0.0f && x < 200.0f);
if (x >= 7.0f) past_seven = true;
}
CHECK(past_seven);
}
TEST(a_sigmoid_gate_is_drawn_inside_zero_to_one) {
const std::vector<float> v = draw_f32({ opd_f32({ 64 }, RAD_OPD_IN, KF_FILL_SIGMOID) },
0, 64, 0xEEEE);
bool spread = false;
for (float x : v) {
CHECK(x > 0.0f && x < 1.0f);
if (x > 0.6f || x < 0.4f) spread = true;
}
CHECK(spread);
}
/* The chunked delta rule's intra-chunk matrix is I + tril(diag(beta) K K^T, -1) -- unit lower
* triangular by construction, with a bounded inverse. Drawn with a normal on the diagonal it is
* not: an element near zero makes the inverse enormous and gdn_kkt_solve then returns values of
* order 1e20 with a rel_l2 that grows with the chunk count. */
TEST(an_intra_chunk_matrix_is_drawn_unit_lower_triangular) {
KfOperand d = opd_f32({ 8, 2, 4 }, RAD_OPD_IN, KF_FILL_TRI_LOWER);
d.fill_chunk = 4;
const std::vector<float> v = draw_f32({ d }, 0, 8, 0xF00D);
const int64_t heads = 2, ch = 4, rows = 8;
for (int64_t t = 0; t < rows; ++t)
for (int64_t h = 0; h < heads; ++h)
for (int64_t j = 0; j < ch; ++j) {
const float x = v[(size_t)((t * heads + h) * ch + j)];
const int64_t diag = t % ch;
if (j > diag) CHECK_EQ(x, 0.0f);
else if (j == diag) CHECK_EQ(x, 1.0f);
else CHECK(std::fabs(x) < 4.0f);
}
}
/* The gated-delta-net key arrives from the model's own qk_norm with unit rows. Drawn as plain
* normals over a 128-wide head it has norm ~11, the solve's off-diagonals are then two orders of
* magnitude too large and its inverse is astronomical. */
TEST(a_qk_normed_key_is_drawn_with_unit_rows) {
const int64_t r = 6, w = 128;
const std::vector<float> v = draw_f32({ opd_f32({ r, w }, RAD_OPD_IN, KF_FILL_UNIT_ROW) },
0, r, 0x1010);
for (int64_t i = 0; i < r; ++i) {
double ss = 0;
for (int64_t j = 0; j < w; ++j) {
const double x = (double)v[(size_t)(i * w + j)];
ss += x * x;
}
CHECK_NEAR(std::sqrt(ss), 1.0, 1e-5);
}
}
/* The decay plane is an intra-chunk cumulative sum of log-decays that RESETS at every chunk
* boundary, which is what chunk_local_cumsum produces and what the scan assumes. Fed plain
* normals the reference overflows to 2e38 and the comparison measures the overflow. */
TEST(a_gate_cumsum_runs_down_a_chunk_and_resets_at_its_boundary) {
const int64_t rows = 8, heads = 2;
KfOperand d = opd_f32({ rows, heads }, RAD_OPD_IN, KF_FILL_GATE_CUMSUM);
KfOperand plain = d;
plain.fill_chunk = 0; /* one chunk over the whole plane: no reset */
d.fill_chunk = 4;
const std::vector<float> chunked = draw_f32({ d }, 0, rows, 0x2020);
const std::vector<float> whole = draw_f32({ plain }, 0, rows, 0x2020);
for (int64_t h = 0; h < heads; ++h) {
/* Strictly decreasing within a chunk: each step subtracts log1p(exp(x)), always positive,
* and the accumulator starts at zero so every value is negative. */
for (int64_t t = 0; t < rows; ++t) {
const float x = chunked[(size_t)(t * heads + h)];
CHECK(x < 0.0f);
if (t % 4 != 0) CHECK(x < chunked[(size_t)((t - 1) * heads + h)]);
}
/* The first chunk is the same either way, because there is nothing to reset yet. */
for (int64_t t = 0; t < 4; ++t)
CHECK_EQ(chunked[(size_t)(t * heads + h)], whole[(size_t)(t * heads + h)]);
/* And at the boundary the accumulator restarts: the chunked value is exactly the step the
* unchunked one took, rather than that step added to everything before it. */
const double step = (double)whole[(size_t)(4 * heads + h)] -
(double)whole[(size_t)(3 * heads + h)];
CHECK_NEAR(chunked[(size_t)(4 * heads + h)], step, 1e-5);
}
}
TEST(an_output_operand_is_sized_and_left_alone) {
const std::vector<float> v = draw_f32({ opd_f32({ 16, 4 }, RAD_OPD_OUT) }, 0, 16, 0x3030);
CHECK_EQ((int64_t)v.size(), (int64_t)64);
for (float x : v) CHECK_EQ(x, 0.0f);
}
TEST(an_absent_operand_draws_nothing) {
KfOperand d = opd_f32({ 16 });
d.absent = true;
std::vector<uint8_t> bytes;
kf_draw({ d }, 0, 16, 16, 1, &bytes);
for (uint8_t b : bytes) CHECK_EQ((int)b, 0);
}
/* The fallback range for an index operand with nothing to index. Derived from the case on both
* sides rather than read off the model on one of them, or the recorder and the reader would draw
* different token ids from the same seed. */
TEST(the_fallback_index_range_is_the_widest_leading_extent) {
CHECK_EQ(kf_vocab_rows({ opd_f32({ 4, 9 }), opd_f32({ 128, 2 }), opd_f32({ 7 }) }),
(int64_t)128);
CHECK_EQ(kf_vocab_rows({}), (int64_t)0);
}
/* ================================================================== the file */
TEST(a_fixture_survives_a_save_and_a_load) {
Kfixture fx;
fx.source = "/models/thing.rad";
fx.oracle = "libref@0.1.0";
fx.recorded = "2026-01-02";
KfCase c;
c.op = "rmsnorm";
c.seed = 0xFEEDFACEDEADBEEFull;
c.m = 517;
c.band = "M in (64, 512]";
c.speed_only = true;
c.params.push_back(KfParam{ "M", RAD_P_INT, 517, 0, "" });
c.params.push_back(KfParam{ "eps", RAD_P_F64, 0, 1e-6, "" });
c.params.push_back(KfParam{ "dtype", RAD_P_STR, 0, 0, "bf16" });
KfOperand in = opd_f32({ 517, 4096 }, RAD_OPD_IN, KF_FILL_GATE_CUMSUM);
in.fill_chunk = 64;
in.is_index = true;
in.idx_unique = true;
in.idx_cu = true;
in.idx_max = 99;
in.idx_const = 12;
c.opd.push_back(in);
KfOperand out = opd_f32({ 517, 4096 }, RAD_OPD_OUT);
out.dtype = RAD_BF16;
out.have_ref = true;
out.ref_n = 517 * 4096;
out.ref_sumsq = 1234.5;
out.ref_nonfinite = 3;
out.sample.assign(KF_SAMPLES, 0.0f);
for (int i = 0; i < KF_SAMPLES; ++i) out.sample[(size_t)i] = (float)i * 0.5f;
c.opd.push_back(out);
KfOperand gone = opd_f32({ 1 });
gone.absent = true;
c.opd.push_back(gone);
c.opd.push_back(fp8_weight(256, 384, { "codes", "scale" }));
fx.cases.push_back(c);
const std::string path = scratch_path("roundtrip.rkb");
CHECK_OK(fx.save(path));
Kfixture rd;
CHECK_OK(rd.load(path));
CHECK_EQ(rd.version, fx.version);
CHECK_EQ(rd.source, fx.source);
CHECK_EQ(rd.oracle, fx.oracle);
CHECK_EQ(rd.recorded, fx.recorded);
CHECK_EQ(rd.cases.size(), (size_t)1);
if (rd.cases.size() != 1) { std::remove(path.c_str()); return; }
const KfCase& g = rd.cases[0];
CHECK_EQ(g.op, c.op);
CHECK_EQ(g.seed, c.seed);
CHECK_EQ(g.m, c.m);
CHECK_EQ(g.band, c.band);
CHECK_EQ(g.speed_only, c.speed_only);
CHECK_EQ(g.params.size(), c.params.size());
for (size_t i = 0; i < g.params.size() && i < c.params.size(); ++i) {
CHECK_EQ(g.params[i].key, c.params[i].key);
CHECK_EQ(g.params[i].kind, c.params[i].kind);
CHECK_EQ(g.params[i].i, c.params[i].i);
CHECK_EQ(g.params[i].d, c.params[i].d);
CHECK_EQ(g.params[i].s, c.params[i].s);
}
CHECK_EQ(g.opd.size(), c.opd.size());
for (size_t i = 0; i < g.opd.size() && i < c.opd.size(); ++i) {
const KfOperand& a = g.opd[i];
const KfOperand& b = c.opd[i];
CHECK_EQ(a.role, b.role);
CHECK_EQ(a.dtype, b.dtype);
CHECK(a.shape == b.shape);
CHECK_EQ(a.absent, b.absent);
CHECK_EQ(a.fill, b.fill);
CHECK_EQ(a.is_index, b.is_index);
CHECK_EQ(a.idx_unique, b.idx_unique);
CHECK_EQ(a.idx_cu, b.idx_cu);
CHECK_EQ(a.idx_max, b.idx_max);
CHECK_EQ(a.idx_const, b.idx_const);
CHECK_EQ(a.fill_chunk, b.fill_chunk);
CHECK_EQ(a.have_ref, b.have_ref);
CHECK_EQ(a.ref_n, b.ref_n);
CHECK_EQ(a.ref_sumsq, b.ref_sumsq);
CHECK_EQ(a.ref_nonfinite, b.ref_nonfinite);
CHECK(a.sample == b.sample);
CHECK_EQ(a.has_enc, b.has_enc);
CHECK(rad_enc_equal(&a.enc, &b.enc));
CHECK(a.sel == b.sel);
CHECK(a.sel_rows == b.sel_rows);
CHECK(a.sel_cols == b.sel_cols);
}
std::remove(path.c_str());
}
TEST(a_fixture_that_is_not_there_is_not_found) {
Kfixture fx;
CHECK_EQ(fx.load(scratch_path("no_such_file.rkb")), RAD_E_NOTFOUND);
}
/* A reader that does not refuse a file it does not understand reads a struct that has moved, and
* the failure mode is a report full of confident wrong numbers rather than an error. */
TEST(a_fixture_the_reader_does_not_understand_is_refused) {
Kfixture fx;
fx.source = "x";
fx.cases.push_back(KfCase{});
const std::string path = scratch_path("bad.rkb");
CHECK_OK(fx.save(path));
auto poke = [&](long off, const void* bytes, size_t n) {
FILE* f = std::fopen(path.c_str(), "r+b");
if (!f) { CHECK(false); return; }
std::fseek(f, off, SEEK_SET);
std::fwrite(bytes, 1, n, f);
std::fclose(f);
};
const char wrong_magic[4] = { 'R', 'K', 'B', '9' };
poke(0, wrong_magic, 4);
Kfixture rd;
CHECK_EQ(rd.load(path), RAD_E_FORMAT);
const char good_magic[4] = { 'R', 'K', 'B', '1' };
poke(0, good_magic, 4);
const uint32_t wrong_version = 99;
poke(4, &wrong_version, 4);
CHECK_EQ(rd.load(path), RAD_E_FORMAT);
/* The sample count is derived, not stored per value, so a file recorded at another count
* would have every sample compared against the wrong element. */
const uint32_t version = 4;
poke(4, &version, 4);
const uint32_t wrong_samples = 512;
poke(8, &wrong_samples, 4);
CHECK_EQ(rd.load(path), RAD_E_FORMAT);
std::remove(path.c_str());
}
/* A FILE WHOSE WEIGHTS DO NOT CARRY THEIR ENCODING IS REFUSED, not read. Its weight operands are
* tensors a kernel's layout hooks cannot take, and replaying it would hand every relayout a plain
* plane in place of the encoding the reference was computed through. */
TEST(a_fixture_without_encodings_is_refused) {
Kfixture fx;
fx.source = "x";
fx.cases.push_back(KfCase{});
const std::string path = scratch_path("v3.rkb");
CHECK_OK(fx.save(path));
FILE* f = std::fopen(path.c_str(), "r+b");
REQUIRE(f != nullptr);
const uint32_t v3 = 3;
std::fseek(f, 4, SEEK_SET);
std::fwrite(&v3, 1, 4, f);
std::fclose(f);
Kfixture rd;
CHECK_EQ(rd.load(path), RAD_E_FORMAT);
std::remove(path.c_str());
}
TEST(a_truncated_fixture_is_refused) {
Kfixture fx;
fx.source = "x";
KfCase c;
c.op = "rmsnorm";
c.opd.push_back(opd_f32({ 4 }));
fx.cases.push_back(c);
const std::string path = scratch_path("short.rkb");
CHECK_OK(fx.save(path));
FILE* f = std::fopen(path.c_str(), "rb");
CHECK(f != nullptr);
if (!f) return;
std::fseek(f, 0, SEEK_END);
const long n = std::ftell(f);
std::fclose(f);
CHECK(n > 24);
CHECK_EQ(truncate(path.c_str(), n - 8), 0);
Kfixture rd;
CHECK_EQ(rd.load(path), RAD_E_FORMAT);
std::remove(path.c_str());
}
/* ================================================================== a weight's planes */
namespace {
/* Select every plane of `e` over a [rows, cols] weight, as a declaration taking all of them. */
KfOperand all_planes(const RadEncoding& e, int64_t rows, int64_t cols) {
KfOperand d;
d.role = RAD_OPD_WEIGHT;
d.has_enc = true;
d.enc = e;
d.dtype = RAD_F32;
d.shape = { rows, cols };
for (int i = 0; i < e.n_planes; ++i) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&e.plane[i], rows, cols, &pr, &pc);
d.sel.push_back(i);
d.sel_rows.push_back(pr);
d.sel_cols.push_back(pc);
}
return d;
}
} /* namespace */
/* A DRAWN PLANE HOLDS ONLY WHAT ITS ROLE CAN. A code past its codebook is a read past a table; a
* permutation that repeats a column is a different weight on every reader; an exponent scale
* drawn over every exponent overflows the reference. Any of them turns a replay into a
* comparison of two ways of handling garbage. */
TEST(a_weights_planes_are_drawn_inside_what_each_can_hold) {
const int64_t R = 8, C = 64;
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_copy_str(e.transform, "perm");
rad_enc_add_plane(&e, "codes", RAD_U8, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_E8M0, 1, 32);
rad_enc_add_table(&e, "table", RAD_F32, 1, 10);
rad_enc_add_table(&e, "t.perm", RAD_I32, 1, C);
REQUIRE(rad_enc_valid(&e));
const KfOperand d = all_planes(e, R, C);
std::vector<std::vector<uint8_t>> a, b, x;
kf_draw_planes(d, 7, &a);
kf_draw_planes(d, 7, &b);
kf_draw_planes(d, 8, &x);
REQUIRE_EQ(a.size(), (size_t)4);
CHECK(a == b); /* a seed is the planes */
CHECK(a[0] != x[0]);
for (int64_t i = 0; i < R * C; ++i) CHECK(a[0][(size_t)i] < 10);
for (uint8_t s8 : a[1]) CHECK(s8 >= 123 && s8 <= 131);
std::vector<int32_t> perm((size_t)C);
std::memcpy(perm.data(), a[3].data(), (size_t)C * 4);
std::sort(perm.begin(), perm.end());
for (int64_t j = 0; j < C; ++j) CHECK_EQ(perm[(size_t)j], (int32_t)j);
}
/* THE REFERENCE READS WHAT THE PLANES DECODE TO: the codes times their block's scale for the whole
* encoding, and one plane as its own values -- widened where the operand is wider. */
TEST(the_reference_reads_what_the_planes_decode_to) {
const int64_t R = 256, C = 384;
KfOperand both = fp8_weight(R, C, { "codes", "scale" });
std::vector<std::vector<uint8_t>> pl;
kf_draw_planes(both, 3, &pl);
std::vector<uint8_t> out;
std::string why;
REQUIRE_EQ(kf_planes_logical(both, pl, &out, &why), RAD_OK);
REQUIRE_EQ(out.size(), (size_t)(R * C * 4));
const float* f = (const float*)out.data();
for (int64_t r : { (int64_t)0, (int64_t)130, R - 1 })
for (int64_t c : { (int64_t)0, (int64_t)200, C - 1 }) {
const float code = rad_load_f32(pl[0].data(), RAD_F8E4M3, r * C + c);
const float scale = rad_load_f32(pl[1].data(), RAD_BF16, (r / 128) * 3 + c / 128);
CHECK_EQ(f[r * C + c], code * scale);
}
KfOperand sc = fp8_weight(R, C, { "scale" });
sc.dtype = RAD_F32; /* a reference reading the scales in f32 */
std::vector<std::vector<uint8_t>> sp;
kf_draw_planes(sc, 3, &sp);
REQUIRE_EQ(kf_planes_logical(sc, sp, &out, &why), RAD_OK);
REQUIRE_EQ(out.size(), (size_t)(2 * 3 * 4));
for (int i = 0; i < 6; ++i)
CHECK_EQ(((const float*)out.data())[i], rad_load_f32(sp[0].data(), RAD_BF16, i));
}
namespace {
int lay_identity(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int,
RadLayout*) { return RAD_E_UNSUPPORTED; }
int lay_refuse(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int,
RadLayout*) { return RAD_E_DTYPE; }
int lay_reverse(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor* pl,
int n, RadLayout* out) {
if (n != 1) return RAD_E_SHAPE;
out->dtype = pl[0].dtype;
out->bytes = rad_dtype_bytes(pl[0].dtype, pl[0].shape[0] * pl[0].shape[1]);
return RAD_OK;
}
int relay_reverse(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor* pl,
int, void* dst, int64_t bytes) {
const uint8_t* s = (const uint8_t*)pl[0].data;
for (int64_t i = 0; i < bytes; ++i) ((uint8_t*)dst)[i] = s[bytes - 1 - i];
return RAD_OK;
}
} /* namespace */
/* A KERNEL IS HANDED WHAT ITS OWN LAYOUT HOOKS MAKE OF THE PLANES, and the three answers a hook
* gives are three different things: read as stored, not this encoding, or these bytes. */
TEST(a_kernel_is_handed_what_its_own_layout_makes) {
const KfOperand d = fp8_weight(128, 256, { "codes" });
std::vector<std::vector<uint8_t>> pl;
kf_draw_planes(d, 5, &pl);
RadKernelInfo ki{};
RadLayout lay{};
std::vector<uint8_t> out;
CHECK_EQ(kf_lay_weight(&ki, nullptr, 0, 0, d, pl, &lay, &out), RAD_E_UNSUPPORTED);
ki.layout = lay_identity;
CHECK_EQ(kf_lay_weight(&ki, nullptr, 0, 0, d, pl, &lay, &out), RAD_E_UNSUPPORTED);
ki.layout = lay_refuse;
CHECK_EQ(kf_lay_weight(&ki, nullptr, 0, 0, d, pl, &lay, &out), RAD_E_DTYPE);
ki.layout = lay_reverse;
CHECK_EQ(kf_lay_weight(&ki, nullptr, 0, 0, d, pl, &lay, &out), RAD_E_STATE); /* no relayout */
ki.relayout = relay_reverse;
REQUIRE_EQ(kf_lay_weight(&ki, nullptr, 0, 0, d, pl, &lay, &out), RAD_OK);
REQUIRE_EQ(out.size(), pl[0].size());
CHECK(std::equal(out.begin(), out.end(), pl[0].rbegin()));
CHECK_EQ(lay.dtype, (uint32_t)RAD_F8E4M3);
}
/* ================================================================== the artifact in the tree
*
* data/kernels.rkb is checked in and is the whole of the replay's coverage, so it is a thing the
* tests have an opinion about rather than an input they trust. A fixture that became unreadable,
* lost its cases or gained an operand dtype the harness cannot draw would otherwise present as a
* rad-kbench run that quietly checks less than the fixture records.
*/
namespace {
/* False when the file is not there, which is a skip, or does not load, which is a failure: a stale
* recording is the replay checking nothing. */
bool load_checked_in(const char* leaf, Kfixture* fx) {
const char* home = std::getenv("RADIANCE_HOME");
if (!home || !*home) return false;
const std::string path = std::string(home) + "/" + leaf;
const int rc = fx->load(path);
if (rc == RAD_E_NOTFOUND) {
std::fprintf(stderr, " SKIP %s is not in $RADIANCE_HOME\n", leaf);
return false;
}
if (rc != RAD_OK)
std::fprintf(stderr, " %s does not load (%s) -- record it again with rad-kbench -m "
"<model.rad> --max-cases 1 --record\n", path.c_str(),
rad_strerror(rc));
CHECK_OK(rc);
return rc == RAD_OK;
}
} /* namespace */
TEST(the_checked_in_fixtures_load_and_describe_real_cases) {
for (const char* leaf : { "kernels.rkb", "kernels_moe.rkb" }) {
Kfixture fx;
if (!load_checked_in(leaf, &fx)) continue;
/* THE VERSION THE RECORDINGS ARE HELD AT, pinned so that a fixture re-recorded by an
* older tool is caught here rather than as a page of confident kernel failures. */
CHECK_EQ(fx.version, (uint32_t)4);
CHECK(!fx.cases.empty());
CHECK(!fx.source.empty());
CHECK(!fx.oracle.empty());
int with_ref = 0, with_enc = 0;
for (const KfCase& c : fx.cases) {
CHECK(!c.op.empty());
CHECK(!c.opd.empty());
for (const KfOperand& d : c.opd) {
if (d.absent) continue;
if (d.role == RAD_OPD_WEIGHT) {
/* every weight a recording draws carries its encoding */
CHECK(d.has_enc);
if (d.has_enc) ++with_enc;
}
CHECK(!d.shape.empty());
if (d.have_ref) {
++with_ref;
CHECK(d.ref_n > 0);
CHECK((int64_t)d.sample.size() ==
(d.ref_n < KF_SAMPLES ? d.ref_n : (int64_t)KF_SAMPLES));
}
}
}
CHECK(with_ref > 0);
CHECK(with_enc > 0);
}
}
/* EVERY DTYPE A RECORDED CASE USES MUST BE ONE THE HARNESS CAN BOTH WRITE AND READ. An operand
* whose dtype rad_narrow does not handle is handed to the kernel as zeros; one rad_widen does not
* handle is compared as zeros on both sides, which agrees perfectly and reports a pass. Neither
* shows up as an error anywhere, so the fixtures are swept for it here. */
TEST(the_checked_in_fixtures_use_no_dtype_the_harness_cannot_draw_or_read) {
const float probe[4] = { 1.0f, 2.0f, 3.0f, 4.0f };
for (const char* leaf : { "kernels.rkb", "kernels_moe.rkb" }) {
Kfixture fx;
if (!load_checked_in(leaf, &fx)) continue;
std::set<uint32_t> seen;
for (const KfCase& c : fx.cases)
for (const KfOperand& d : c.opd)
if (!d.absent) seen.insert(d.dtype);
for (uint32_t dt : seen) {
/* A plugin-private dtype is nobody else's to interpret and is excluded by design. */
if (dt >= RAD_DT_PLUGIN_BASE) continue;
std::vector<uint8_t> packed((size_t)rad_dtype_bytes(dt, 4), 0);
rad_narrow(probe, dt, 4, packed.data());
bool wrote = false;
for (uint8_t b : packed) if (b) { wrote = true; break; }
std::vector<float> back;
rad_widen(packed.data(), dt, 4, &back);
bool read = false;
for (float x : back) if (x != 0.0f) { read = true; break; }
if (!wrote || !read)
std::fprintf(stderr, " %s: dtype %s (%u) narrow=%s widen=%s\n", leaf,
rad_dtype_name(dt), dt, wrote ? "yes" : "NO", read ? "yes" : "NO");
CHECK(wrote);
CHECK(read);
}
}
}
RAD_TEST_MAIN()
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
/* gbnf_oracle.cpp -- upstream's candidate walk (llama.cpp `llama_grammar_reject_candidates` and
* `llama_grammar_apply_impl`, at the commit gbnf.h names), over the engine's own stack machinery.
* See gbnf_oracle.h for why it exists and where it may be used.
*
* The closure, the character tests and the UTF-8 decoding are the engine's (gbnf_internal.h),
* because they are the PARSE and this is a second implementation of the MASK: the thing under
* test is how a mask is assembled from a stack set, and sharing everything below that is what
* makes a disagreement mean a defect in the assembly.
*/
#include "gbnf_oracle.h"
#include "sample/gbnf_internal.h"
#include <algorithm>
#include <new>
namespace rad {
namespace {
using namespace gbnf;
struct Candidate {
size_t index;
const uint32_t* code_points;
PartialUtf8 partial_utf8;
int32_t id;
};
using Candidates = std::vector<Candidate>;
/* What carrying one candidate through one element of a character range costs, against the same
* per-operation bound the engine is held to. */
constexpr uint64_t kCandidateCost = 4;
Candidates reject_for_stack(const GbnfRuleSet& rules, const GbnfStack& stack,
const Candidates& candidates, OpWork& work);
Candidates reject_candidates(const GbnfRuleSet& rules, const GbnfStacks& stacks,
const Candidates& candidates, OpWork& work) {
if (candidates.empty() || stacks.empty()) return {};
Candidates rejects = reject_for_stack(rules, stacks.front(), candidates, work);
for (size_t i = 1; i < stacks.size(); ++i)
rejects = reject_for_stack(rules, stacks[i], rejects, work);
return rejects;
}
Candidates reject_for_stack(const GbnfRuleSet& rules, const GbnfStack& stack,
const Candidates& candidates, OpWork& work) {
{
const GbnfElement* t = stack.empty() ? nullptr : stack.back();
const bool range = t && !is_token_elem(t);
work.add(candidates.size() * kCandidateCost * (range ? char_range_len(t) : 1) +
kStackCost);
}
Candidates rejects;
rejects.reserve(candidates.size());
if (stack.empty()) {
/* A completed stack accepts nothing further, so anything with content left is rejected. */
for (const auto& t : candidates)
if (*t.code_points != 0 || t.partial_utf8.n_remain != 0) rejects.push_back(t);
return rejects;
}
const GbnfElement* top = stack.back();
if (is_token_elem(top)) {
for (const auto& t : candidates) {
if (*t.code_points == 0) {
if (t.partial_utf8.n_remain != 0) rejects.push_back(t);
} else if (!match_token(top, t.id)) {
rejects.push_back(t);
}
}
return rejects;
}
Candidates next;
next.reserve(candidates.size());
for (const auto& t : candidates) {
if (*t.code_points == 0) {
if (t.partial_utf8.n_remain != 0 && !match_partial_char(top, t.partial_utf8))
rejects.push_back(t);
} else if (match_char(top, *t.code_points).first) {
next.push_back({ t.index, t.code_points + 1, t.partial_utf8, t.id });
} else {
rejects.push_back(t);
}
}
const GbnfElement* after = match_char(top, 0).second;
GbnfStack stack_after(stack.begin(), stack.end() - 1);
if (!is_end_of_sequence(after)) stack_after.push_back(after);
GbnfStacks next_stacks;
SetBuild next_set(work);
advance_stack(rules, stack_after, next_stacks, next_set);
for (const auto& t : reject_candidates(rules, next_stacks, next, work))
rejects.push_back({ t.index, t.code_points - 1, t.partial_utf8, t.id });
return rejects;
}
int oracle_impl(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words, uint64_t work_limit) {
const VocabView& vocab = *g.vocab();
const GbnfRuleSet& rules = program_rules(g.program());
const int32_t n_tok = vocab.n_tokens();
const bool allow_eog = g.complete();
/* Decode every piece against the carried partial, then run the whole vocabulary through the
* reject walk in one pass: every candidate admitted, then the rejects cleared. */
std::vector<std::pair<std::vector<uint32_t>, PartialUtf8>> decoded;
decoded.reserve((size_t)n_tok);
Candidates cands;
cands.reserve((size_t)n_tok);
std::vector<int32_t> index_to_id;
index_to_id.reserve((size_t)n_tok);
for (int32_t id = 0; id < n_tok; ++id) {
if (vocab.is_eog(id)) {
if (allow_eog) bitmask[id >> 5] |= 1u << ((uint32_t)id & 31u);
continue;
}
const std::string& piece = vocab.token_piece(id);
if (piece.empty() || piece[0] == 0) continue;
decoded.push_back(decode_utf8(piece, g.partial()));
}
size_t k = 0;
for (int32_t id = 0; id < n_tok; ++id) {
if (vocab.is_eog(id)) continue;
const std::string& piece = vocab.token_piece(id);
if (piece.empty() || piece[0] == 0) continue;
cands.push_back({ index_to_id.size(), decoded[k].first.data(), decoded[k].second, id });
index_to_id.push_back(id);
++k;
}
for (int32_t id : index_to_id) bitmask[id >> 5] |= 1u << ((uint32_t)id & 31u);
OpWork work;
if (work_limit) work.limit = work_limit;
for (const auto& r : reject_candidates(rules, g.stacks(), cands, work)) {
const int32_t id = index_to_id[r.index];
bitmask[id >> 5] &= ~(1u << ((uint32_t)id & 31u));
}
for (int64_t w = 0; w < n_words; ++w)
if (bitmask[w]) return RAD_OK;
return RAD_E_STATE;
}
} /* namespace */
int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words,
uint64_t work_limit) {
if (!bitmask || !g.vocab()) return RAD_E_INVAL;
if (n_words < bitmask_words(g.vocab()->n_tokens())) return RAD_E_SHAPE;
if (g.awaiting_trigger()) {
std::fill(bitmask, bitmask + n_words, 0xFFFFFFFFu);
return RAD_OK;
}
std::fill(bitmask, bitmask + n_words, 0u);
if (g.stacks().empty()) return RAD_E_STATE;
try {
return oracle_impl(g, bitmask, n_words, work_limit);
} catch (const gbnf::GbnfLimit&) {
return RAD_E_FULL;
} catch (const std::bad_alloc&) {
return RAD_E_NOMEM;
}
}
} /* namespace rad */
+29
View File
@@ -0,0 +1,29 @@
/* gbnf_oracle.h -- upstream's candidate walk, kept as the oracle the GBNF mask engine is tested
* against.
*
* fill_mask serves a mask from a plan precomputed at compile time (core/sample/gbnf_mask.cpp).
* This computes the same mask the way llama.cpp's llama_grammar_apply_impl does: every piece in
* the vocabulary decoded against the carried partial character and rescanned per stack, per code
* point. The two are implementations of one pure function of the grammar's state, so the test is
* equality, bit for bit and status for status, and any difference is a defect in the engine.
*
* It is linked into the tests and the acceptance tool only. It costs a full rescan of the
* vocabulary per stack per mask, which is what the engine exists to avoid, and it must never be
* reachable from a serving path.
*/
#pragma once
#include "sample/gbnf.h"
#include <cstdint>
namespace rad {
/* The mask for `g`'s current state. Returns what fill_mask must return for it: RAD_OK, RAD_E_STATE
* when the grammar has no live parse or admits no token, RAD_E_SHAPE when `n_words` is short --
* or RAD_E_FULL when the rescan outgrows `work_limit` (the engine's per-operation bound when 0),
* which is a comparison the caller could not make rather than a disagreement. A lazy grammar
* still waiting for its trigger admits everything. */
int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words,
uint64_t work_limit = 0);
} /* namespace rad */
+1145
View File
File diff suppressed because it is too large. Load diff
+199
View File
@@ -0,0 +1,199 @@
/* gen_config_test.cpp -- the sampling a checkpoint states for itself.
*
* WHAT THIS IS HOLDING DOWN. SamplingParams' defaults are an untruncated sampler, and a model
* tuned against a truncated tail served that way draws, now and then, a token from far down its
* distribution. End-of-turn is one of those tokens, so the symptom is not prose that reads badly
* -- it is a reply that ends early, which from outside the server is indistinguishable from a
* dropped request. Nothing about a wrong sampler default announces itself, which is exactly why
* the reading of it is a component with a test rather than a helper inside the engine.
*
* No model and no container: the three sources are a string, a file and a key lookup, and all
* three are reachable directly.
*/
#include "rad_test.h"
#include "gen_config.h"
#include <cstdio>
#include <map>
#include <string>
using namespace rad;
namespace {
/* The container's metadata table as gen_sampling_from_kv sees it: bare field names, and every
* value a string, which is how rad-convert writes free-form metadata. */
std::function<const char*(const char*)> kv_of(const std::map<std::string, std::string>& m) {
return [&m](const char* k) -> const char* {
auto it = m.find(k);
return it == m.end() ? nullptr : it->second.c_str();
};
}
std::string write_temp(const char* name, const std::string& body) {
std::string path = std::string("/tmp/radiance_gen_config_test_") + name + ".json";
FILE* f = std::fopen(path.c_str(), "w");
if (!f) return std::string();
std::fwrite(body.data(), 1, body.size(), f);
std::fclose(f);
return path;
}
/* Qwen3.8-Flash-Next's, verbatim -- the shape this was built for. */
const char* const kQwenGenConfig = R"({
"bos_token_id": 248044,
"do_sample": true,
"eos_token_id": [248046, 248044],
"pad_token_id": 248044,
"temperature": 1.0,
"top_k": 20,
"top_p": 0.95
})";
} /* namespace */
TEST(gen_config_reads_a_real_generation_config) {
GenSampling g;
CHECK(gen_sampling_parse(kQwenGenConfig, "test", &g));
CHECK_NEAR(g.temp, 1.0f, 1e-6);
CHECK_EQ(g.top_k, 20);
CHECK_NEAR(g.top_p, 0.95f, 1e-6);
CHECK_NEAR(g.min_p, -1.0f, 1e-6); /* the file does not say, so nothing is claimed */
/* Overlaid on the built-in defaults it truncates the tail, which is the whole point: the
* untruncated sampler is what lets an early end-of-turn be drawn at all. */
const SamplingParams sp = g.onto(SamplingParams{});
CHECK_NEAR(sp.temp, 1.0f, 1e-6);
CHECK_EQ(sp.top_k, 20);
CHECK_NEAR(sp.top_p, 0.95f, 1e-6);
CHECK_NEAR(sp.min_p, 0.0f, 1e-6); /* untouched, so still the struct's own */
CHECK(!sp.greedy());
}
/* A FIELD A SOURCE DID NOT STATE MUST NOT BE CLAIMED, or the sources cannot stack: a sidecar that
* sets only top_k would otherwise wipe the temperature underneath it. */
TEST(gen_config_claims_only_what_a_source_states) {
GenSampling g;
CHECK(gen_sampling_parse(R"({"top_k": 40})", "test", &g));
CHECK_EQ(g.top_k, 40);
CHECK(g.temp < 0.0f);
CHECK(g.top_p < 0.0f);
SamplingParams base;
base.temp = 0.6f;
base.top_p = 0.8f;
const SamplingParams sp = g.onto(base);
CHECK_NEAR(sp.temp, 0.6f, 1e-6);
CHECK_NEAR(sp.top_p, 0.8f, 1e-6);
CHECK_EQ(sp.top_k, 40);
GenSampling none;
CHECK(!gen_sampling_parse(R"({"bos_token_id": 1})", "test", &none));
CHECK(!none.any());
}
/* `do_sample: false` is greedy and transformers ignores every other sampler field under it. */
TEST(gen_config_reads_do_sample_false_as_greedy) {
GenSampling g;
CHECK(gen_sampling_parse(R"({"do_sample": false, "temperature": 0.7, "top_k": 20})",
"test", &g));
CHECK_NEAR(g.temp, 0.0f, 1e-6);
CHECK_EQ(g.top_k, -1); /* not taken: greedy does not have one */
CHECK(g.onto(SamplingParams{}).greedy());
/* do_sample true is the ordinary case and says nothing by itself. */
GenSampling t;
CHECK(gen_sampling_parse(R"({"do_sample": true, "temperature": 0.7})", "test", &t));
CHECK_NEAR(t.temp, 0.7f, 1e-6);
}
/* transformers spells "no top_k" as -1 and this sampler spells it 0. */
TEST(gen_config_translates_top_k_minus_one_to_off) {
GenSampling g;
CHECK(gen_sampling_parse(R"({"top_k": -1})", "test", &g));
CHECK_EQ(g.top_k, 0);
}
/* A VALUE OUT OF RANGE IS DROPPED, NOT REFUSED, and it drops alone: these arrive with the model,
* and one implausible entry is not a reason to serve the rest wrongly or not at all. */
TEST(gen_config_drops_an_out_of_range_field_and_keeps_the_rest) {
GenSampling g;
CHECK(gen_sampling_parse(R"({"temperature": 9.0, "top_p": 0.95, "top_k": 20})", "test", &g));
CHECK(g.temp < 0.0f); /* 9.0 is not a temperature; nothing was claimed */
CHECK_NEAR(g.top_p, 0.95f, 1e-6);
CHECK_EQ(g.top_k, 20);
/* top_p is a half-open range: 0 is not a nucleus, 1 is. */
GenSampling z;
CHECK(!gen_sampling_parse(R"({"top_p": 0.0})", "test", &z));
GenSampling one;
CHECK(gen_sampling_parse(R"({"top_p": 1.0})", "test", &one));
CHECK_NEAR(one.top_p, 1.0f, 1e-6);
}
TEST(gen_config_survives_text_that_is_not_a_config) {
GenSampling g;
CHECK(!gen_sampling_parse("{not json", "test", &g));
CHECK(!gen_sampling_parse("[1, 2, 3]", "test", &g));
CHECK(!gen_sampling_parse("", "test", &g));
CHECK(!g.any());
}
/* The container's copy and the original file must resolve to the same sampler: rad-convert
* flattens every value to a string, and two readings of one schema is how the two come to
* disagree about a checkpoint. */
TEST(gen_config_reads_the_container_table_as_the_file) {
GenSampling from_file;
CHECK(gen_sampling_parse(kQwenGenConfig, "test", &from_file));
const std::map<std::string, std::string> table = {
{ "do_sample", "1" },
{ "temperature", "1" },
{ "top_k", "20" },
{ "top_p", "0.95" },
};
GenSampling from_kv;
CHECK(gen_sampling_from_kv(kv_of(table), &from_kv));
CHECK_NEAR(from_kv.temp, from_file.temp, 1e-6);
CHECK_EQ(from_kv.top_k, from_file.top_k);
CHECK_NEAR(from_kv.top_p, from_file.top_p, 1e-6);
/* An empty table states nothing rather than stating zeros. */
GenSampling empty;
CHECK(!gen_sampling_from_kv(kv_of({}), &empty));
CHECK(!empty.any());
/* A value that is not a number is dropped, and the rest of the table still reads. */
GenSampling junk;
CHECK(gen_sampling_from_kv(kv_of({ { "temperature", "warm" }, { "top_k", "20" } }), &junk));
CHECK(junk.temp < 0.0f);
CHECK_EQ(junk.top_k, 20);
}
TEST(gen_config_reads_a_file_and_treats_absence_as_silence) {
const std::string path = write_temp("sidecar", kQwenGenConfig);
CHECK(!path.empty());
GenSampling g;
CHECK(gen_sampling_from_file(path, /*required=*/false, &g));
CHECK_EQ(g.top_k, 20);
std::remove(path.c_str());
/* A checkpoint that ships no generation config is served from whatever lies underneath, not
* refused -- so a missing file takes nothing and reports nothing taken. */
GenSampling missing;
CHECK(!gen_sampling_from_file("/nonexistent/generation_config.json", false, &missing));
CHECK(!missing.any());
}
/* The sidecar is the container's path with its extension replaced, and the extension is the LAST
* dot in the basename -- a directory with a dot in its name must not eat it. */
TEST(gen_config_derives_the_sidecar_path) {
CHECK_EQ(gen_sidecar_path("/m/q38-flashnext-unc-w4-mtp.rad"),
std::string("/m/q38-flashnext-unc-w4-mtp.generation.json"));
CHECK_EQ(gen_sidecar_path("model.rad"), std::string("model.generation.json"));
CHECK_EQ(gen_sidecar_path("/a.b/model"), std::string("/a.b/model.generation.json"));
CHECK_EQ(gen_sidecar_path("/a.b/model.rad"), std::string("/a.b/model.generation.json"));
}
RAD_TEST_MAIN()
+235
View File
@@ -0,0 +1,235 @@
/* kld_test.cpp -- the KL scorer (core/kld.h): its arithmetic and its reference files.
*
* No device and no model. A reference is recorded from synthetic logits split over two vocabulary
* shards, the way two ranks hand them over; a candidate is scored against it; and every position's
* KL, argmax agreement and NLL is held to a direct computation in double from the two sets of f32
* logits. The f16 the reference keeps is the only approximation, so the tolerance is what that
* costs -- and a candidate identical to the reference has to score zero.
*/
#include "rad_test.h"
#include "kld.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <random>
#include <string>
#include <vector>
using namespace rad;
namespace {
constexpr int64_t V = 1000; /* two shards of 500 */
constexpr int64_t W = V / 2;
struct TmpDir {
std::string path;
TmpDir() {
char t[] = "/tmp/kld_test.XXXXXX";
path = mkdtemp(t) ? t : "";
}
~TmpDir() { std::error_code ec; std::filesystem::remove_all(path, ec); }
};
/* Logits with a confident head and a long tail: one token a few nats clear of a normal spread,
* which is the shape where an f16 head would cost the most and the exact one has to cover it. */
std::vector<float> make_logits(int64_t rows, uint32_t seed) {
std::mt19937 g(seed);
std::normal_distribution<float> n(0.0f, 2.5f);
std::uniform_int_distribution<int> pick(0, (int)V - 1);
std::vector<float> l((size_t)(rows * V));
for (int64_t r = 0; r < rows; ++r) {
for (int64_t i = 0; i < V; ++i) l[(size_t)(r * V + i)] = n(g);
l[(size_t)(r * V + pick(g))] += (r % 3 == 0) ? 2.0f : 9.0f;
}
return l;
}
/* The two shards a step hands over, from full rows. */
struct Shards {
std::vector<float> a, b;
std::vector<KldShard> s;
Shards(const std::vector<float>& full, int64_t rows) : a((size_t)(rows * W)), b((size_t)(rows * W)) {
for (int64_t r = 0; r < rows; ++r)
for (int64_t i = 0; i < W; ++i) {
a[(size_t)(r * W + i)] = full[(size_t)(r * V + i)];
b[(size_t)(r * W + i)] = full[(size_t)(r * V + W + i)];
}
s = { { a.data(), 0, W }, { b.data(), W, W } };
}
};
double lse(const float* l) {
double m = l[0];
for (int64_t i = 1; i < V; ++i) m = std::max(m, (double)l[i]);
double s = 0;
for (int64_t i = 0; i < V; ++i) s += std::exp((double)l[i] - m);
return m + std::log(s);
}
double kl_direct(const float* p, const float* q) {
const double zp = lse(p), zq = lse(q);
double kl = 0;
for (int64_t i = 0; i < V; ++i) {
const double lp = (double)p[i] - zp;
kl += std::exp(lp) * (lp - ((double)q[i] - zq));
}
return kl;
}
int64_t argmax(const float* l) {
int64_t a = 0;
for (int64_t i = 1; i < V; ++i) if (l[i] > l[a]) a = i;
return a;
}
/* Two documents: 40 tokens scored from 8, and 25 scored from 0 -- so 31 + 24 rows. */
const std::vector<int32_t> kDocA = [] { std::vector<int32_t> t(40); for (int i = 0; i < 40; ++i) t[i] = (i * 37) % V; return t; }();
const std::vector<int32_t> kDocB = [] { std::vector<int32_t> t(25); for (int i = 0; i < 25; ++i) t[i] = (i * 91 + 5) % V; return t; }();
/* Positions [0, n) of a document, one logits row each, handed over in two steps the way a
* chunked prefill would: the first chunk ends mid-document. */
void feed(Kld& k, uint64_t id, int64_t n, const std::vector<float>& full) {
const int64_t cut = n / 2;
{
std::vector<float> part(full.begin(), full.begin() + cut * V);
Shards sh(part, cut);
CHECK_OK(k.score({ { id, 0, cut, 0 } }, sh.s));
}
{
std::vector<float> part(full.begin() + cut * V, full.begin() + n * V);
Shards sh(part, n - cut);
CHECK_OK(k.score({ { id, cut, n - cut, 0 } }, sh.s));
}
}
std::vector<float> read_rows(const std::string& path) {
std::ifstream in(path, std::ios::binary);
in.seekg(0, std::ios::end);
std::vector<float> v((size_t)in.tellg() / sizeof(float));
in.seekg(0);
in.read(reinterpret_cast<char*>(v.data()), (std::streamsize)(v.size() * sizeof(float)));
return v;
}
void record(const std::string& dir, const std::vector<float>& la, const std::vector<float>& lb) {
Kld rec;
CHECK_OK(rec.add_doc("a", kDocA, 8));
CHECK_OK(rec.add_doc("b", kDocB, 0));
CHECK_OK(rec.record_into(dir, V, "reference"));
CHECK_EQ(rec.n_rows(), (int64_t)(31 + 24));
feed(rec, 1, 40, la);
feed(rec, 2, 25, lb);
CHECK_OK(rec.finish());
}
} /* namespace */
/* THE NUMBERS THEMSELVES. Every scored position of a perturbed candidate against a direct double
* computation from both sets of logits, and the rows outside each document's range left out. */
TEST(a_candidate_scores_what_a_direct_computation_gives) {
TmpDir t;
REQUIRE(!t.path.empty());
const std::vector<float> ra = make_logits(40, 1), rb = make_logits(25, 2);
record(t.path + "/ref", ra, rb);
/* The candidate: the reference plus noise, enough to flip some argmaxes. */
std::vector<float> ca = ra, cb = rb;
std::mt19937 g(7);
std::normal_distribution<float> n(0.0f, 0.6f);
for (float& v : ca) v += n(g);
for (float& v : cb) v += n(g);
Kld k;
CHECK_OK(k.score_against(t.path + "/ref", t.path + "/rep.json", V, "candidate"));
feed(k, 1, 40, ca);
feed(k, 2, 25, cb);
CHECK_OK(k.finish());
const std::vector<float> rows = read_rows(t.path + "/rep.json.rows");
REQUIRE_EQ(rows.size(), (size_t)(55 * 4));
int64_t r = 0, flips = 0;
auto check_doc = [&](const std::vector<float>& ref, const std::vector<float>& cand,
const std::vector<int32_t>& tok, int64_t from) {
for (int64_t p = from; p + 1 < (int64_t)tok.size(); ++p, ++r) {
const float* lp = ref.data() + p * V;
const float* lq = cand.data() + p * V;
const double want = kl_direct(lp, lq);
CHECK_NEAR(rows[(size_t)(r * 4 + 0)], want, 2e-5 + 1e-3 * want);
CHECK_NEAR(rows[(size_t)(r * 4 + 1)], lse(lq) - lq[tok[(size_t)p + 1]], 1e-4);
CHECK_NEAR(rows[(size_t)(r * 4 + 2)], lse(lp) - lp[tok[(size_t)p + 1]], 1e-4);
const bool same = argmax(lp) == argmax(lq);
CHECK_EQ(rows[(size_t)(r * 4 + 3)], same ? 1.0f : 0.0f);
flips += !same;
}
};
check_doc(ra, ca, kDocA, 8);
check_doc(rb, cb, kDocB, 0);
CHECK_EQ(r, (int64_t)55);
CHECK(flips > 0); /* the noise has to have moved something for the check to mean it */
}
/* THE CONTROL. A candidate identical to the reference: every KL is the f16 storage's second-order
* residue, and every argmax agrees. */
TEST(the_reference_against_itself_scores_zero) {
TmpDir t;
REQUIRE(!t.path.empty());
const std::vector<float> ra = make_logits(40, 3), rb = make_logits(25, 4);
record(t.path + "/ref", ra, rb);
Kld k;
CHECK_OK(k.score_against(t.path + "/ref", t.path + "/rep.json", V, "same"));
feed(k, 1, 40, ra);
feed(k, 2, 25, rb);
CHECK_OK(k.finish());
const std::vector<float> rows = read_rows(t.path + "/rep.json.rows");
REQUIRE_EQ(rows.size(), (size_t)(55 * 4));
for (size_t r = 0; r < 55; ++r) {
CHECK(std::fabs(rows[r * 4 + 0]) < 1e-6f);
CHECK_EQ(rows[r * 4 + 3], 1.0f);
CHECK_NEAR(rows[r * 4 + 1], rows[r * 4 + 2], 1e-5);
}
}
/* A REFERENCE IS NEVER WRITTEN OVER, and one whose recording did not finish is never read. */
TEST(a_reference_is_written_once_and_read_only_when_complete) {
TmpDir t;
REQUIRE(!t.path.empty());
const std::vector<float> ra = make_logits(40, 5), rb = make_logits(25, 6);
record(t.path + "/ref", ra, rb);
{
Kld again;
CHECK_OK(again.add_doc("a", kDocA, 8));
CHECK_EQ(again.record_into(t.path + "/ref", V, "x"), RAD_E_INVAL);
}
/* A recording that stops short: the manifest is never written, finish() says what is missing,
* and the directory is not a reference. */
{
Kld half;
CHECK_OK(half.add_doc("a", kDocA, 8));
CHECK_OK(half.add_doc("b", kDocB, 0));
CHECK_OK(half.record_into(t.path + "/half", V, "x"));
feed(half, 1, 40, ra);
CHECK_EQ(half.finish(), RAD_E_STATE);
}
Kld k;
CHECK(k.score_against(t.path + "/half", "", V, "x") < 0);
/* And a vocabulary that is not the reference's. */
Kld v;
CHECK_EQ(v.score_against(t.path + "/ref", "", V + 1, "x"), RAD_E_INVAL);
}
/* A DOCUMENT WITH NOTHING TO SCORE is refused when it is added, not discovered as a missing row. */
TEST(a_document_must_leave_a_position_to_score) {
Kld k;
CHECK_EQ(k.add_doc("x", { 1 }, 0), RAD_E_INVAL);
CHECK_EQ(k.add_doc("x", { 1, 2, 3 }, 2), RAD_E_INVAL);
CHECK_EQ(k.add_doc("x", { 1, 2, 3 }, -1), RAD_E_INVAL);
CHECK_OK(k.add_doc("x", { 1, 2, 3 }, 1));
CHECK_EQ(k.n_rows(), (int64_t)1);
}
RAD_TEST_MAIN()
+522
View File
@@ -0,0 +1,522 @@
#include "chatdiff.h"
#include "text/tokenizer.h"
#include <cstdio>
#include <random>
namespace rad {
namespace chatdiff {
const std::vector<Model>& models() {
static const std::vector<Model> m = {
{ "qwen3.8", "qwen3.8", "", "<|im_end|>", { "<|im_end|>", "<|endoftext|>" } },
{ "qwen3.6", "qwen3.6", "", "<|im_end|>", { "<|im_end|>", "<|endoftext|>" } },
{ "minicpm5", "minicpm5", "<s>", "</s>", { "</s>", "<|im_end|>" } },
};
return m;
}
std::string describe(const ChatRequest& r) {
std::string s = r.tools ? "tools" : "no-tools";
if (!r.parallel) s += ",single";
if (!r.thinking) s += ",no-think";
if (!r.reasoning) s += ",reasoning-none";
if (!r.schema.empty()) s += ",response-format";
return s;
}
const ojson& agent_tools() {
static const ojson t = ojson::parse(R"([
{"type":"function","function":{"name":"bash","description":"Run a shell command.",
"parameters":{"type":"object","properties":{"command":{"type":"string"},
"timeout":{"type":"integer"},"description":{"type":"string"}},"required":["command"]}}},
{"type":"function","function":{"name":"read","description":"Read a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"offset":{"type":"integer"},"limit":{"type":"integer"}},"required":["path"]}}},
{"type":"function","function":{"name":"write","description":"Write a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"content":{"type":"string"}},"required":["path","content"]}}},
{"type":"function","function":{"name":"edit","description":"Apply edits to a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"edits":{"type":"array","items":{"type":"object","properties":{
"oldText":{"type":"string"},"newText":{"type":"string"}},
"required":["oldText","newText"]}}},"required":["path","edits"]}}},
{"type":"function","function":{"name":"todo_write","description":"Update the todo list.",
"parameters":{"type":"object","properties":{"todos":{"type":"array","items":{
"type":"object","properties":{"content":{"type":"string"},
"status":{"type":"string","enum":["pending","in_progress","completed"]}},
"required":["content","status"]}}},"required":["todos"]}}},
{"type":"function","function":{"name":"configure","description":"Set options.",
"parameters":{"type":"object","properties":{"verbose":{"type":"boolean"},
"level":{"type":"number"},"mode":{"enum":["fast","slow"]},"extra":{"type":"object"},
"label":{"type":["string","null"]},"tags":{"type":"array","items":{"type":"string"}},
"nothing":{"type":"null"}}}}},
{"type":"function","function":{"name":"ping","description":"Takes no arguments.",
"parameters":{"type":"object","properties":{}}}}
])");
return t;
}
int Bench::load(const Model& m, const std::string& jinja, std::string* why) {
model_ = m;
jinja_ = jinja;
tmpl_ = std::make_shared<ChatTemplate>();
if (tmpl_->load(jinja, m.bos, m.eos) < 0) {
*why = "the template did not compile";
return RAD_E_FORMAT;
}
std::string refused;
int st = chat_format_from_template(jinja, m.bos, m.eos, &fmt_, &refused, why);
if (st < 0) return st;
if (!refused.empty()) {
*why = "tool calls refused: " + refused;
return RAD_E_UNSUPPORTED;
}
return ReplyFormat::compile(fmt_, &rf_, why);
}
static ChatOptions options_for(const ChatRequest& rq) {
ChatOptions opt;
opt.add_generation_prompt = true;
opt.enable_thinking = rq.thinking;
opt.parallel_tool_calls = rq.parallel;
opt.reasoning_format = rq.reasoning ? "auto" : "none";
opt.json_schema = rq.schema;
return opt;
}
static ojson user_turn() {
return ojson::array({ ojson{ { "role", "user" }, { "content", "Fix the failing test in /work." } } });
}
int Bench::bind(const ChatRequest& rq, const ojson& tools, std::string* why) {
req_ = rq;
tools_ = tools;
prompt_ = ChatPrompt{};
const ChatOptions opt = options_for(rq);
if (tmpl_->apply(user_turn(), rq.tools ? tools_ : ojson(), opt, &prompt_) < 0) {
*why = "render failed: " + prompt_.error;
return RAD_E_INVAL;
}
old_ = std::make_unique<legacy::ToolParser>();
if (old_->init(prompt_, opt.reasoning_format, rq.tools) < 0) {
*why = "the old parser did not load";
return RAD_E_FORMAT;
}
ReplyOptions ro;
ro.generation_prompt = prompt_.generation_prompt;
ro.extract_reasoning = rq.reasoning;
ro.tools = rq.tools ? &tools_ : nullptr;
ro.parallel_tool_calls = rq.parallel;
ro.response_format = !rq.schema.empty();
ro.terminators = model_.terminators;
return ReplyParser::create(rf_, ro, &parser_, why);
}
legacy::Answer Bench::old_parse(const std::string& text, bool partial) const {
return legacy::legacy_parse(*old_, text, partial, req_.tools, model_.terminators);
}
ReplyMessage Bench::new_parse(const std::string& text, bool* strict) const {
return reply_parse(*parser_, text, strict);
}
std::string Bench::render_reply(const ojson& assistant) const {
ChatOptions opt = options_for(req_);
ChatPrompt head, whole;
if (tmpl_->apply(user_turn(), req_.tools ? tools_ : ojson(), opt, &head) < 0) return "";
ojson msgs = user_turn();
msgs.push_back(assistant);
opt.add_generation_prompt = false;
if (tmpl_->apply(msgs, req_.tools ? tools_ : ojson(), opt, &whole) < 0) return "";
if (whole.prompt.size() < head.prompt.size() ||
whole.prompt.compare(0, head.prompt.size(), head.prompt) != 0)
return "";
std::string reply = whole.prompt.substr(head.prompt.size());
while (!reply.empty() && reply.back() == '\n') reply.pop_back();
for (const std::string& t : model_.terminators)
if (reply.size() >= t.size() && reply.compare(reply.size() - t.size(), t.size(), t) == 0) {
reply.erase(reply.size() - t.size());
break;
}
return reply;
}
static std::string q(const std::string& s) {
return nlohmann::json(s).dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
}
std::string show(const ReplyMessage& m) {
std::string s = "content=" + q(m.content) + " reasoning=" + q(m.reasoning);
for (const ReplyCall& c : m.calls)
s += "\n call " + q(c.name) + " " + q(c.arguments) + (c.closed ? "" : " (open)");
return s;
}
std::string show(const legacy::Answer& a) {
std::string s = "content=" + q(a.content) + " reasoning=" + q(a.reasoning);
if (a.strict_failed) s += " [strict parse failed]";
if (a.lifted) s += " [" + std::to_string(a.lifted) + " lifted]";
for (const legacy::ToolCall& c : a.calls) s += "\n call " + q(c.name) + " " + q(c.arguments);
return s;
}
bool same(const ReplyMessage& a, const ReplyMessage& b) {
if (a.content != b.content || a.reasoning != b.reasoning || a.calls.size() != b.calls.size())
return false;
for (size_t i = 0; i < a.calls.size(); ++i)
if (a.calls[i].name != b.calls[i].name || a.calls[i].arguments != b.calls[i].arguments ||
a.calls[i].closed != b.calls[i].closed)
return false;
return true;
}
Verdict compare(const Bench& b, const std::string& text) {
Verdict v;
const legacy::Answer o = b.old_parse(text);
const ReplyMessage m = b.new_parse(text, &v.strict);
v.old_clean = !o.strict_failed && o.lifted == 0;
v.bare_lift = !o.strict_failed && o.lifted > 0;
const ChatFormat& f = b.format();
if (!f.call_open.empty()) {
size_t a = 0, e = f.call_open.size();
while (a < e && (unsigned char)f.call_open[a] <= ' ') ++a;
while (e > a && (unsigned char)f.call_open[e - 1] <= ' ') --e;
v.old_call_syntax = o.content.find(f.name_prefix) != std::string::npos ||
o.content.find(f.call_open.substr(a, e - a)) != std::string::npos;
}
v.same = o.content == m.content && o.reasoning == m.reasoning && o.calls.size() == m.calls.size();
for (size_t i = 0; v.same && i < o.calls.size(); ++i)
v.same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments;
if (!v.same) v.detail = " old: " + show(o) + "\n new: " + show(m);
return v;
}
std::string judge(const Verdict& v) {
if (v.strict) {
if (v.old_clean && !v.same) return "both read the reply within the grammar and disagree";
if (!v.old_clean && !v.bare_lift)
return "the new parser read within the grammar a reply the old grammar rejected";
return std::string();
}
if (v.old_clean && !v.old_call_syntax)
return "the new parser left the grammar on a reply the old grammar accepted";
return std::string();
}
std::string check_stream(const ReplyParser& p, const std::string& text,
const std::vector<size_t>& cuts, const ReplyMessage& expect) {
std::unique_ptr<ReplyStream> s = p.open();
ReplyMessage got;
std::vector<ReplyEvent> ev;
const size_t bound = p.hold_bound();
auto grew = [](const std::string& now, size_t before, const std::string& want) {
return now.size() <= want.size() &&
now.compare(before, std::string::npos, want, before, now.size() - before) == 0;
};
auto take = [&](const char* where) -> std::string {
for (const ReplyEvent& e : ev) {
switch (e.kind) {
case ReplyEvent::Reasoning: {
const size_t b = got.reasoning.size();
got.reasoning += e.text;
if (!grew(got.reasoning, b, expect.reasoning))
return std::string(where) + ": reasoning delta is not a prefix of the answer";
break;
}
case ReplyEvent::Content: {
const size_t b = got.content.size();
got.content += e.text;
if (!grew(got.content, b, expect.content))
return std::string(where) + ": content delta is not a prefix of the answer";
break;
}
case ReplyEvent::CallBegin:
if (e.call != got.calls.size() || e.call >= expect.calls.size() ||
expect.calls[e.call].name != e.text)
return std::string(where) + ": a call began that the answer does not have";
got.calls.push_back({ e.text, std::string(), false });
break;
case ReplyEvent::CallArgs: {
if (e.call >= got.calls.size()) return std::string(where) + ": arguments for no call";
std::string& a = got.calls[e.call].arguments;
const size_t b = a.size();
a += e.text;
if (!grew(a, b, expect.calls[e.call].arguments))
return std::string(where) + ": arguments delta is not a prefix of the answer";
break;
}
case ReplyEvent::CallEnd:
if (e.call >= got.calls.size() || !expect.calls[e.call].closed)
return std::string(where) + ": a call closed that the answer leaves open";
got.calls[e.call].closed = true;
break;
}
}
ev.clear();
return std::string();
};
size_t at = 0;
for (size_t c : cuts) {
if (c <= at || c > text.size()) continue;
s->feed(std::string_view(text).substr(at, c - at), &ev);
at = c;
std::string err = take("after a piece");
if (!err.empty()) return err + " (at byte " + std::to_string(at) + ")";
const ReplyHeld h = s->held();
if (h.delimiter > bound)
return "held " + std::to_string(h.delimiter) + " bytes of text, over the bound of " +
std::to_string(bound) + " (at byte " + std::to_string(at) + ")";
}
if (at < text.size()) s->feed(std::string_view(text).substr(at), &ev);
s->finish(&ev);
std::string err = take("at the end");
if (!err.empty()) return err;
if (!same(got, expect)) return "the deltas add up to\n " + show(got);
if (!same(s->message(), expect)) return "the message is\n " + show(s->message());
return std::string();
}
std::string sanitize(const std::string& s) { return utf8_sanitize(s); }
/* ================================================================== the corpora */
bool is_qwen(const Model& m) { return m.name != "minicpm5"; }
ojson call(const std::string& name, const ojson& args) {
return { { "type", "function" },
{ "function", { { "name", name }, { "arguments", args.dump() } } } };
}
ojson message(const std::string& reasoning, const std::string& content,
const std::vector<ojson>& calls) {
ojson m = { { "role", "assistant" }, { "content", content } };
if (!reasoning.empty()) m["reasoning_content"] = reasoning;
if (!calls.empty()) {
m["tool_calls"] = ojson::array();
for (size_t i = 0; i < calls.size(); ++i) {
ojson c = calls[i];
c["id"] = "call_" + std::to_string(i);
m["tool_calls"].push_back(c);
}
}
return m;
}
static const std::string kFile =
"def add(a, b):\n\n\t# sum\n return a + b \n\nclass X:\n s = \"<b>&amp;</b>\"\n";
std::vector<ojson> rendered_corpus() {
std::vector<ojson> v;
v.push_back(message("", "The tests pass now.", {}));
v.push_back(message("The user wants a summary.\nIt is short.", "It prints one.", {}));
v.push_back(message("I should look first.", "",
{ call("bash", { { "command", "ls -la /work" }, { "timeout", 30 } }) }));
v.push_back(message("", "Let me check the directory.",
{ call("bash", { { "command", "ls" } }) }));
v.push_back(message("Two things.", "", { call("read", { { "path", "/work/a.py" } }),
call("read", { { "path", "/work/b.py" },
{ "offset", 10 },
{ "limit", 40 } }) }));
{
std::vector<ojson> five;
for (int i = 0; i < 5; ++i)
five.push_back(call("bash", { { "command", "echo " + std::to_string(i) } }));
v.push_back(message("Five commands.", "Running them all.", five));
}
v.push_back(message("", "", { call("write", { { "path", "/work/a.py" }, { "content", kFile } }) }));
v.push_back(message("Editing.", "", { call("edit", { { "path", "/work/a.py" },
{ "edits", ojson::array({ { { "oldText", " return a + b" },
{ "newText", " return a + b + 1" } } }) } }) }));
v.push_back(message("", "", { call("todo_write", { { "todos", ojson::array({
{ { "content", "write the test" }, { "status", "completed" } },
{ { "content", "fix it" }, { "status", "in_progress" } } }) } }) }));
v.push_back(message("", "", { call("configure", { { "level", 1.5 },
{ "extra", { { "a", ojson::array({ 1, 2 }) },
{ "b", { { "c", nullptr } } } } },
{ "tags", ojson::array({ "x", "y" }) },
{ "mode", "fast" },
{ "label", "l" } }) }));
v.push_back(message("Unicode.", "Größe, 大小, 🚀.",
{ call("write", { { "path", "/work/中文.txt" },
{ "content", "こんにちは 🌍\nÀ la carte — «ok»\n" } }) }));
v.push_back(message("", "", { call("write", { { "path", "/work/x.xml" },
{ "content", "<param name=\"k\">v</param>\n</param\n</parameter\n</function>x" } }) }));
v.push_back(message("", "", { call("write", { { "path", "" }, { "content", "" } }) }));
v.push_back(message("", "", { call("ping", ojson::object()) }));
return v;
}
std::string qcall(const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
std::string s = "<tool_call>\n<function=" + name + ">\n";
for (const auto& a : args) s += "<parameter=" + a.first + ">\n" + a.second + "\n</parameter>\n";
return s + "</function>\n</tool_call>";
}
std::string mcall(const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
std::string s = "<function name=\"" + name + "\">";
for (const auto& a : args) s += "<param name=\"" + a.first + "\">" + a.second + "</param>";
return s + "</function>";
}
std::string C(const Model& m, const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
return is_qwen(m) ? qcall(name, args) : mcall(name, args);
}
std::vector<Adversarial> adversarial(const Model& m) {
const std::string T = "Thinking it over.\n</think>\n\n";
std::vector<Adversarial> v;
auto add = [&](const std::string& n, const std::string& t) { v.push_back({ n, t }); };
add("reasoning only, never closed", "Thinking and thinking");
add("reasoning only, closed", "Thinking.\n</think>\n\n");
add("content only", T + "The answer is 42.");
add("reasoning then a call", T + C(m, "bash", { { "command", "ls" } }));
add("content then a call", T + "Checking.\n" + C(m, "bash", { { "command", "ls" } }));
add("calls then trailing text", T + C(m, "bash", { { "command", "ls" } }) + "\nDone now.");
add("two calls", T + C(m, "bash", { { "command", "ls" } }) + "\n" +
C(m, "read", { { "path", "/a" } }));
add("two calls with a sentence between", T + C(m, "bash", { { "command", "ls" } }) +
"\nNow the file.\n" + C(m, "read", { { "path", "/a" } }));
{
std::string five = T;
for (int i = 0; i < 5; ++i) five += C(m, "bash", { { "command", "echo " + std::to_string(i) } }) + "\n";
add("five calls", five);
}
add("an integer", T + C(m, "read", { { "path", "/a" }, { "limit", "40" } }));
add("a number", T + C(m, "configure", { { "level", "-1.5e3" } }));
add("a boolean", T + C(m, "configure", { { "verbose", "true" } }));
add("a null", T + C(m, "configure", { { "nothing", "null" } }));
add("an object", T + C(m, "configure", { { "extra", "{\"a\": {\"b\": [1, {\"c\": \"d\"}]}}" } }));
add("an array", T + C(m, "configure", { { "tags", "[\"x\", \"y\"]" } }));
add("a Python-quoted array", T + C(m, "edit", { { "path", "/a" },
{ "edits", "[{'oldText': 'a', 'newText': 'b\\'s'}]" } }));
add("an integer with units", T + C(m, "bash", { { "command", "sleep" }, { "timeout", "30 seconds" } }));
add("JSON then a stray character", T + C(m, "configure", { { "extra", "{\"a\": 1}x" } }));
add("an unterminated JSON string", T + C(m, "configure", { { "extra", "\"abc" } }));
add("a number that is not one", T + C(m, "read", { { "path", "/a" }, { "limit", "01" } }));
add("unicode", T + "Größe 大小 🚀 " + C(m, "write", { { "path", "/中.txt" }, { "content", "こんにちは 🌍" } }));
add("CDATA with brackets and tags", T + C(m, "write", { { "path", "/a" },
{ "content", "<![CDATA[if (a[b[0]]) { x = \"]]\"; }\n <tag>\n indented\n]]>" } }));
add("CDATA holding almost a closer", T + C(m, "write", { { "path", "/a" }, { "content", "<![CDATA[a]]b]] >]]>" } }));
add("a value holding part of its closer", T + C(m, "write", { { "path", "/a" },
{ "content", "x </param y </parameter z </para" } }));
add("empty values", T + C(m, "write", { { "path", "" }, { "content", "" } }));
add("an undeclared argument", T + C(m, "read", { { "path", "/a" }, { "mode", "fast" } }));
add("only an undeclared argument", T + C(m, "read", { { "action", "read" } }));
add("arguments out of order", T + C(m, "write", { { "content", "x" }, { "path", "/a" } }));
add("a required argument missing", T + C(m, "write", { { "path", "/a" } }));
add("no arguments for a tool that needs one", T + C(m, "bash", {}));
add("an argument for a tool that takes none", T + C(m, "ping", { { "x", "1" } }));
add("a function that is not a tool", T + C(m, "which gcc cc clang make", {}));
add("unclosed think before a call", "I will list it.\n" + C(m, "bash", { { "command", "ls" } }));
add("a truncated reply inside a call", T + "Writing.\n" + C(m, "write", { { "path", "/a" }, { "content", "partial fi" } })
.substr(0, 40));
add("a truncated reply inside an argument name", T + (is_qwen(m) ? "<tool_call>\n<function=read>\n<parameter=pa"
: "<function name=\"read\"><param name=\"pa"));
add("a truncated reply inside a function name", T + (is_qwen(m) ? "<tool_call>\n<function=wri" : "<function name=\"wri"));
add("delimiter-like text in content", T + "Use `</think>`, `<tool_call>`, `<function=f>` and "
"`<function name=\"f\">` to call. </parameter> </param>");
add("a closing tag mentioned in reasoning", "The tag </thin is not </think>\n\nfine");
add("the call opener mentioned in reasoning",
std::string("I could write ") + (is_qwen(m) ? "<tool_call>\n" : "<function name=\"") +
" here.\n</think>\n\nNo.");
add("a second </think>", T + "Answer.\n</think>\nmore");
add("a turn terminator at the end", T + "Answer." + m.terminators[0]);
add("trailing spaces and newlines", T + "Answer. \n \n\n");
add("a call inside a sentence", T + "I will " + C(m, "bash", { { "command", "ls" } }) + " now.");
if (is_qwen(m)) {
add("the template's instructions echoed",
T + "<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\n"
"value_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for "
"the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n"
"</tool_call>");
add("a call without the newline after its opener",
T + "<tool_call><function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n</tool_call>");
add("a bare function without its wrapper",
T + "<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>");
add("a function name without its newline",
T + "<tool_call>\n<function=bash><parameter=command>\nls\n</parameter>\n</function>\n</tool_call>");
add("a close without its newline",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function></tool_call>");
add("two calls in one wrapper",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
"<function=bash>\n<parameter=command>\npwd\n</parameter>\n</function>\n</tool_call>");
add("a call with no closing wrapper",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
"<tool_call>\n<function=read>\n<parameter=path>\n/a\n</parameter>\n</function>\n</tool_call>");
add("an argument with no newline after its name",
T + "<tool_call>\n<function=bash>\n<parameter=command>ls</parameter>\n</function>\n</tool_call>");
} else {
add("the template's instructions echoed",
T + "<function name=\"function-name\"><param name=\"param-name\">param-value</param></function>");
add("the instruction's CDATA example echoed",
T + "<function name=\"write\"><param name=\"param-name\"><![CDATA[...multi-line value...]]></param></function>");
add("a value closed with the wrong tag",
T + "<function name=\"bash\"><param name=\"command\">ls\n</command></function>");
add("junk inside a call", T + "<function name=\"bash\"><param name=\"command\">ls</param>, "
"then<param name=\"timeout\">3</param></function>");
add("JSON arguments inside the tag", T + "<function name=\"bash\">{\"command\": \"ls\"}</function>");
}
return v;
}
std::vector<std::string> fragments(const Model& m) {
std::vector<std::string> f = {
"</think>\n\n", "<think>\n", "ls -la", "30", "-1.5e3", "[1,2]", "{\"a\":true}", "{'a': 1}",
"hello", "\n", " ", "<![CDATA[", "]]>", "]", "<", "</", "\"", "'", "\\", "{", "}", "true",
"null", "30 seconds", "中", "🚀", "x", "<|im_end|>", "</s>", "```json\n", "```",
};
const std::vector<std::string> q = {
"<tool_call>\n", "</tool_call>", "<function=bash>\n", "<function=read>\n",
"<function=ping>\n", "<function=configure>\n", "<function=zzz>\n", "</function>\n",
"<parameter=command>\n", "<parameter=timeout>\n", "<parameter=path>\n",
"<parameter=extra>\n", "<parameter=level>\n", "<parameter=xx>\n", "</parameter>\n",
"</parameter", "<tool_call>", "<function=", ">\n",
};
const std::vector<std::string> mc = {
"<function name=\"bash\">", "<function name=\"read\">", "<function name=\"ping\">",
"<function name=\"configure\">", "<function name=\"zz\">", "</function>",
"<param name=\"command\">", "<param name=\"timeout\">", "<param name=\"path\">",
"<param name=\"extra\">", "<param name=\"xx\">", "</param>", "</param", "<function name=\"",
"\">",
};
for (const std::string& s : is_qwen(m) ? q : mc) f.push_back(s);
return f;
}
std::string mutate(std::mt19937& rng, std::string s, const std::vector<std::string>& frag) {
const int n = 1 + (int)(rng() % 4);
for (int k = 0; k < n; ++k) {
const size_t at = s.empty() ? 0 : rng() % (s.size() + 1);
switch (rng() % 4) {
case 0: s.insert(at, frag[rng() % frag.size()]); break;
case 1: if (at < s.size()) s.erase(at, 1 + rng() % 8); break;
case 2: if (at < s.size()) s[at] = (char)(rng() & 0xFF); break;
default: s.insert(at, 1, (char)(rng() & 0xFF)); break;
}
}
return s;
}
std::string long_reply(const Model& m, size_t target) {
std::string think, file, prose;
while (think.size() < target / 4) think += "Considering the failing assertion in test_add again. ";
while (file.size() < target / 2) file += " x = compute(a, b) # <tag> & \"quoted\" ]] \n";
while (prose.size() < target / 4) prose += "The change keeps the interface and fixes the sum. ";
return think + "\n</think>\n\n" + prose + "\n" +
C(m, "write", { { "path", "/work/big.py" }, { "content", file } });
}
} /* namespace chatdiff */
} /* namespace rad */
+150
View File
@@ -0,0 +1,150 @@
/* chatdiff.h -- the streaming reply parser beside the legacy parser, on the same request.
*
* Shared by tests/chatparse_test.cpp and tools/rad_chatparse.cpp. A Bench holds one model's chat
* template, its reply format and, for one rendered request, both parsers: the legacy path
* (toolparse_legacy.h, the `old` side) and the streaming parser (core/text/chatparse.h, the `new`
* side). compare() says whether they agree on a reply and, when they do not, which side left its
* grammar; check_stream() feeds a reply to the streaming parser in pieces and checks the streaming
* contract on every piece.
*/
#pragma once
#include "text/chat.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include "toolparse_legacy.h"
#include <nlohmann/json.hpp>
#include <memory>
#include <random>
#include <string>
#include <vector>
namespace rad {
namespace chatdiff {
using ojson = nlohmann::ordered_json;
/* A model: where its template is and how its vocabulary spells the tokens a template reads. */
struct Model {
std::string name;
std::string dir; /* under the fixture root */
std::string bos, eos;
std::vector<std::string> terminators; /* its end-of-generation spellings */
};
const std::vector<Model>& models();
/* How a request is rendered. */
struct ChatRequest {
bool tools = true;
bool parallel = true;
bool thinking = true;
bool reasoning = true; /* reasoning_format "auto"; false is "none" */
std::string schema; /* a response format's schema, "" for none */
};
std::string describe(const ChatRequest& r);
/* An agent-shaped tool set, with every argument type the formats distinguish. */
const ojson& agent_tools();
class Bench {
public:
/* RAD_OK, or a status with *why. `jinja` is the template's text. */
int load(const Model& m, const std::string& jinja, std::string* why);
int bind(const ChatRequest& rq, const ojson& tools, std::string* why);
const Model& model() const { return model_; }
const ChatFormat& format() const { return fmt_; }
const ChatPrompt& prompt() const { return prompt_; }
const ReplyParser& parser() const { return *parser_; }
std::shared_ptr<const ReplyParser> parser_ptr() const { return parser_; }
const legacy::ToolParser& old_parser() const { return *old_; }
const ChatRequest& request() const { return req_; }
const ChatTemplate& tmpl() const { return *tmpl_; }
legacy::Answer old_parse(const std::string& text, bool partial = false) const;
ReplyMessage new_parse(const std::string& text, bool* strict = nullptr) const;
/* The reply as the template writes an assistant turn -- which is exactly what the model is
* trained to produce -- without the turn terminator the decoder would not render. "" when the
* template does not render the turn as a continuation of the generation prompt. */
std::string render_reply(const ojson& assistant) const;
private:
Model model_;
std::string jinja_;
std::shared_ptr<ChatTemplate> tmpl_;
ChatFormat fmt_;
std::shared_ptr<const ReplyFormat> rf_;
ChatRequest req_;
ojson tools_;
ChatPrompt prompt_;
std::unique_ptr<legacy::ToolParser> old_;
std::shared_ptr<const ReplyParser> parser_;
};
struct Verdict {
bool same = false; /* the two answers are identical */
bool strict = false; /* the streaming parser read the reply within the grammar */
bool old_clean = false; /* the legacy strict parse matched and nothing was lifted */
bool bare_lift = false; /* the legacy path lifted a call written without the call opener */
/* The legacy answer's content still carries a wrapped format's call syntax -- a call written
* without its wrapper, which the legacy lifter takes only when nothing else in the reply
* parses as a call, and which the streaming parser always reads as one. */
bool old_call_syntax = false;
std::string detail; /* both answers, when they differ */
};
Verdict compare(const Bench& b, const std::string& text);
/* Whether a verdict is one the streaming parser is allowed: identical where both read the reply
* within the grammar, and a documented difference otherwise. "" or the reason it is not. */
std::string judge(const Verdict& v);
/* Feed `text` to a fresh stream cut at `cuts` (ascending offsets), checking on every piece that
* what has been emitted is a prefix of `expect` and that the held bytes stay under the bound, and
* at the end that the concatenated deltas and the message both equal `expect`. "" or the first
* violation. */
std::string check_stream(const ReplyParser& p, const std::string& text,
const std::vector<size_t>& cuts, const ReplyMessage& expect);
std::string show(const ReplyMessage& m);
std::string show(const legacy::Answer& a);
bool same(const ReplyMessage& a, const ReplyMessage& b);
/* Replace every byte that is not part of well-formed UTF-8 with U+FFFD, as the decoder does
* before any reply reaches a parser. */
std::string sanitize(const std::string& s);
/* ================================================================== the corpora */
bool is_qwen(const Model& m);
/* A call, and an assistant message carrying calls, OpenAI-shaped. */
ojson call(const std::string& name, const ojson& args);
ojson message(const std::string& reasoning, const std::string& content,
const std::vector<ojson>& calls);
/* Assistant messages that, rendered through a model's template, are the replies the model is
* trained to write: content only, reasoning, one to five calls, every argument type, unicode, and
* values holding the format's own punctuation. */
std::vector<ojson> rendered_corpus();
/* Replies written by hand in a model's own spelling: the shapes models actually write when they
* leave their format, and the ones a streaming parser is easiest to get wrong. */
struct Adversarial { std::string name, text; };
std::vector<Adversarial> adversarial(const Model& m);
/* One call in a model's spelling. */
std::string C(const Model& m, const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args);
/* The pieces random replies are assembled from, and a random edit of a reply. */
std::vector<std::string> fragments(const Model& m);
std::string mutate(std::mt19937& rng, std::string s, const std::vector<std::string>& frag);
/* About `target` bytes of reasoning, prose and one call writing a file. */
std::string long_reply(const Model& m, size_t target);
} /* namespace chatdiff */
} /* namespace rad */
+377
View File
@@ -0,0 +1,377 @@
#include "toolparse_legacy.h"
#include "text/chat.h"
#include "llama/common/chat.h"
#include "llama/common/peg-parser.h"
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <nlohmann/json.hpp>
namespace rad {
namespace legacy {
/* ================================================================== the PEG parser */
struct ToolParser::Impl {
common_chat_parser_params params;
bool ready = false;
};
ToolParser::ToolParser() : impl_(std::make_unique<Impl>()) {}
ToolParser::~ToolParser() = default;
bool ToolParser::ready() const { return impl_ && impl_->ready; }
int ToolParser::init(const ChatPrompt& p, const std::string& reasoning_format,
bool parse_tool_calls) {
impl_->ready = false;
impl_->params = common_chat_parser_params{};
impl_->params.format = (common_chat_format)p.format;
impl_->params.generation_prompt = p.generation_prompt;
impl_->params.parse_tool_calls = parse_tool_calls;
impl_->params.reasoning_format = common_reasoning_format_from_name(reasoning_format);
impl_->params.reasoning_in_content =
impl_->params.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY;
if (!p.parser.empty()) {
try {
impl_->params.parser.load(p.parser);
} catch (const std::exception&) {
return RAD_E_FORMAT;
}
}
impl_->ready = true;
return RAD_OK;
}
int ToolParser::parse(const std::string& text, bool is_partial, ParsedReply* out) const {
if (!ready()) return RAD_E_STATE;
if (!out) return RAD_E_INVAL;
out->content.clear();
out->reasoning_content.clear();
out->tool_calls.clear();
common_chat_msg msg;
try {
if (!impl_->params.parser.empty())
msg = common_chat_peg_parse(impl_->params.parser, text, is_partial, impl_->params);
else
msg = common_chat_parse(text, is_partial, impl_->params);
} catch (const std::exception&) {
return RAD_E_FORMAT;
}
out->content = std::move(msg.content);
out->reasoning_content = std::move(msg.reasoning_content);
for (common_chat_tool_call& c : msg.tool_calls)
out->tool_calls.push_back({ std::move(c.name), std::move(c.arguments), std::move(c.id) });
return RAD_OK;
}
/* ================================================================== the by-hand lifter
*
* Two spellings, whatever the model's own format:
*
* attr <function name="N"><param name="K">V</param></function>
* eq <tool_call><function=N><parameter=K>V</parameter></function></tool_call>
*/
namespace {
struct XmlCallSyntax {
const char* wrap_open;
const char* wrap_close;
const char* fn_open;
const char* fn_name_end;
const char* fn_close;
const char* arg_open;
const char* arg_name_end;
const char* arg_close;
bool trim_value;
};
const XmlCallSyntax kAttr = { "", "", "<function name=\"", "\">", "</function>",
"<param name=\"", "\">", "</param>", false };
const XmlCallSyntax kEq = { "<tool_call>", "</tool_call>", "<function=", ">", "</function>",
"<parameter=", ">", "</parameter>", true };
size_t skip_ws(const std::string& s, size_t p) {
while (p < s.size() && (unsigned char)s[p] <= ' ') ++p;
return p;
}
std::string trimmed(const std::string& v) {
size_t a = 0, b = v.size();
while (a < b && (unsigned char)v[a] <= ' ') ++a;
while (b > a && (unsigned char)v[b - 1] <= ' ') --b;
return v.substr(a, b - a);
}
size_t read_call(const std::string& s, size_t f, const XmlCallSyntax& x,
std::string* name, nlohmann::ordered_json* args) {
const std::string fn_open(x.fn_open), fn_name_end(x.fn_name_end), fn_close(x.fn_close);
const std::string arg_open(x.arg_open), arg_name_end(x.arg_name_end), arg_close(x.arg_close);
if (s.compare(f, fn_open.size(), fn_open) != 0) return std::string::npos;
const size_t ns = f + fn_open.size();
const size_t ne = s.find(fn_name_end, ns);
if (ne == std::string::npos) return std::string::npos;
*name = s.substr(ns, ne - ns);
if (name->empty() || name->find('<') != std::string::npos) return std::string::npos;
*args = nlohmann::ordered_json::object();
size_t p = ne + fn_name_end.size();
while (true) {
p = skip_ws(s, p);
if (s.compare(p, fn_close.size(), fn_close) == 0) return p + fn_close.size();
if (s.compare(p, arg_open.size(), arg_open) != 0) return std::string::npos;
const size_t ks = p + arg_open.size();
const size_t ke = s.find(arg_name_end, ks);
if (ke == std::string::npos) return std::string::npos;
const std::string key = s.substr(ks, ke - ks);
if (key.empty() || key.find('<') != std::string::npos) return std::string::npos;
size_t vs = ke + arg_name_end.size();
std::string val;
if (s.compare(vs, 9, "<![CDATA[") == 0) {
const size_t ce = s.find("]]>", vs + 9);
if (ce == std::string::npos) return std::string::npos;
val = s.substr(vs + 9, ce - (vs + 9));
p = ce + 3;
if (s.compare(p, arg_close.size(), arg_close) != 0) return std::string::npos;
p += arg_close.size();
} else {
const size_t bound = std::min(s.find(arg_open, vs), s.find(fn_close, vs));
const size_t ve = s.find(arg_close, vs);
if (ve != std::string::npos && (bound == std::string::npos || ve <= bound)) {
val = s.substr(vs, ve - vs);
p = ve + arg_close.size();
} else if (bound != std::string::npos) {
const size_t lt = bound > vs ? s.rfind("</", bound - 1) : std::string::npos;
if (lt != std::string::npos && lt >= vs) {
const size_t gt = s.find('>', lt);
if (gt == std::string::npos || gt >= bound) return std::string::npos;
val = s.substr(vs, lt - vs);
p = gt + 1;
} else {
val = s.substr(vs, bound - vs);
p = bound;
}
} else {
return std::string::npos;
}
}
(*args)[key] = x.trim_value ? trimmed(val) : val;
}
}
std::string mint_call_id() {
static std::atomic<uint64_t> seq{0};
char buf[40];
std::snprintf(buf, sizeof buf, "call_%023llx",
(unsigned long long)seq.fetch_add(1, std::memory_order_relaxed));
return std::string(buf);
}
} /* namespace */
size_t toolparse_find_call_open(const std::string& s) {
static const char* const kMarks[] = { "<tool_call>", "<function name=\"", "<function=" };
size_t at = std::string::npos;
for (const char* m : kMarks) at = std::min(at, s.find(m));
if (at != std::string::npos) return at;
for (const char* m : kMarks) {
const size_t len = std::strlen(m);
for (size_t k = std::min(len - 1, s.size()); k >= 1; --k) {
if (s.compare(s.size() - k, k, m, k) == 0) {
at = std::min(at, s.size() - k);
break;
}
}
}
return at;
}
size_t toolparse_lift_xml_calls(std::string& s, std::vector<ToolCall>& out) {
std::string kept;
size_t cursor = 0, scan = 0, found = 0;
while (true) {
const size_t rel = toolparse_find_call_open(s.substr(scan));
const size_t at = rel == std::string::npos ? std::string::npos : scan + rel;
if (at == std::string::npos) break;
const XmlCallSyntax* x = nullptr;
size_t f = at, wrap = std::string::npos;
if (s.compare(at, strlen(kEq.wrap_open), kEq.wrap_open) == 0) {
wrap = at;
f = skip_ws(s, at + strlen(kEq.wrap_open));
x = &kEq;
} else if (s.compare(at, strlen(kAttr.fn_open), kAttr.fn_open) == 0) {
x = &kAttr;
} else if (s.compare(at, strlen(kEq.fn_open), kEq.fn_open) == 0) {
x = &kEq;
}
if (!x) { scan = at + 1; continue; }
std::string name;
nlohmann::ordered_json args;
size_t end = read_call(s, f, *x, &name, &args);
if (end == std::string::npos) { scan = at + 1; continue; }
if (wrap != std::string::npos) {
const size_t w = skip_ws(s, end);
if (s.compare(w, strlen(kEq.wrap_close), kEq.wrap_close) != 0) { scan = at + 1; continue; }
end = w + strlen(kEq.wrap_close);
}
const size_t span_start = (wrap != std::string::npos) ? wrap : f;
kept.append(s, cursor, span_start - cursor);
ToolCall tc;
tc.id = mint_call_id();
tc.name = name;
tc.arguments = args.dump();
out.push_back(std::move(tc));
cursor = end;
scan = end;
++found;
}
if (found == 0) return 0;
kept.append(s, cursor, std::string::npos);
while (!kept.empty() && (unsigned char)kept.back() <= ' ') kept.pop_back();
s = std::move(kept);
return found;
}
/* ================================================================== the bridge */
static void strip_terminator(std::string& s, const std::vector<std::string>& terms) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
for (const std::string& t : terms) {
if (!t.empty() && s.size() >= t.size() &&
s.compare(s.size() - t.size(), t.size(), t) == 0) {
s.erase(s.size() - t.size());
return;
}
}
}
Answer legacy_parse(const ToolParser& tp, const std::string& text, bool is_partial,
bool want_calls, const std::vector<std::string>& terminators) {
Answer a;
ParsedReply r;
if (tp.parse(text, is_partial, &r) < 0) {
a.strict_failed = true;
a.content = text;
} else {
a.content = std::move(r.content);
a.reasoning = std::move(r.reasoning_content);
a.calls = std::move(r.tool_calls);
}
strip_terminator(a.content, terminators);
if (!want_calls || a.content.empty()) return a;
const size_t at = toolparse_find_call_open(a.content);
if (at == std::string::npos) return a;
if (is_partial) { a.content.resize(at); return a; }
if (!a.calls.empty()) return a;
a.lifted = toolparse_lift_xml_calls(a.content, a.calls);
return a;
}
/* ================================================================== the streaming diff */
namespace {
size_t utf8_cut(const std::string& s) {
size_t n = s.size();
size_t k = n, back = 0;
while (k > 0 && back < 4) {
const unsigned char c = (unsigned char)s[k - 1];
if ((c & 0xC0) == 0x80) { --k; ++back; continue; }
size_t need = 1;
if ((c & 0x80) == 0x00) need = 1;
else if ((c & 0xE0) == 0xC0) need = 2;
else if ((c & 0xF0) == 0xE0) need = 3;
else if ((c & 0xF8) == 0xF0) need = 4;
else return n;
return n - (k - 1) >= need ? n : k - 1;
}
return n;
}
bool extends(const std::string& sent, const std::string& cand) {
return cand.size() >= sent.size() && cand.compare(0, sent.size(), sent) == 0;
}
std::string chunk(const nlohmann::ordered_json& delta) {
nlohmann::ordered_json ch;
ch["index"] = 0;
ch["delta"] = delta;
ch["finish_reason"] = nullptr;
nlohmann::ordered_json o;
o["id"] = "chatcmpl-legacy";
o["object"] = "chat.completion.chunk";
o["created"] = 0;
o["model"] = "legacy";
o["choices"] = nlohmann::ordered_json::array({ ch });
return "data: " + o.dump(-1, ' ', false, nlohmann::ordered_json::error_handler_t::replace) +
"\n\n";
}
} /* namespace */
size_t LegacyDeltaStream::push(const std::string& full_text, bool is_final) {
Answer p = legacy_parse(tp_, full_text, !is_final, want_calls_, terms_);
size_t out = 0;
if (p.reasoning.size() > reasoning_.size() && extends(reasoning_, p.reasoning)) {
const size_t safe = is_final ? p.reasoning.size() : utf8_cut(p.reasoning);
if (safe > reasoning_.size()) {
nlohmann::ordered_json d;
d["reasoning_content"] = p.reasoning.substr(reasoning_.size(), safe - reasoning_.size());
out += chunk(d).size();
reasoning_ = p.reasoning.substr(0, safe);
}
}
if (p.content.size() > content_.size() && extends(content_, p.content)) {
const size_t safe = is_final ? p.content.size() : utf8_cut(p.content);
if (safe > content_.size()) {
nlohmann::ordered_json d;
d["content"] = p.content.substr(content_.size(), safe - content_.size());
out += chunk(d).size();
content_ = p.content.substr(0, safe);
}
}
for (size_t i = 0; i < p.calls.size(); ++i) {
const ToolCall& tc = p.calls[i];
if (tc.name.empty()) continue;
if (names_.size() <= i) {
names_.resize(i + 1);
args_.resize(i + 1);
names_[i] = tc.name;
nlohmann::ordered_json f;
f["name"] = tc.name;
f["arguments"] = "";
nlohmann::ordered_json e;
e["index"] = (int64_t)i;
e["function"] = f;
nlohmann::ordered_json d;
d["tool_calls"] = nlohmann::ordered_json::array({ e });
out += chunk(d).size();
}
if (!extends(args_[i], tc.arguments)) continue;
const size_t safe = is_final ? tc.arguments.size() : utf8_cut(tc.arguments);
if (safe <= args_[i].size()) continue;
nlohmann::ordered_json f;
f["arguments"] = tc.arguments.substr(args_[i].size(), safe - args_[i].size());
nlohmann::ordered_json e;
e["index"] = (int64_t)i;
e["function"] = f;
nlohmann::ordered_json d;
d["tool_calls"] = nlohmann::ordered_json::array({ e });
out += chunk(d).size();
args_[i] = tc.arguments.substr(0, safe);
}
return out;
}
} /* namespace legacy */
} /* namespace rad */
+97
View File
@@ -0,0 +1,97 @@
/* toolparse_legacy.h -- a whole-reply parser built on llama.cpp's PEG auto-parser, kept as the
* ORACLE the differential tests compare the streaming parser (core/text/chatparse.h) against. It
* is test code: it is built into the test binaries and the acceptance tool, never into the engine.
*
* It is the whole legacy path, layer for layer, because its answer is what all of them produce
* together:
*
* * ToolParser -- llama.cpp's PEG parser, generated per request by the vendored auto-parser from
* the chat template (vendor/llama/common/chat-auto-parser*.cpp) and run over the WHOLE reply;
* * legacy_parse -- the bridge's reading of that: a turn terminator trimmed off the content,
* and, when the strict parse produced no call but the content still carries call syntax,
* calls lifted out of the text by hand;
* * LegacyDeltaStream -- a streaming diff that re-parses the accumulated reply on every chunk and
* sends what has grown.
*/
#pragma once
#include "rad_internal.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
struct ChatPrompt;
namespace legacy {
struct ToolCall {
std::string name;
std::string arguments;
std::string id;
};
struct ParsedReply {
std::string content;
std::string reasoning_content;
std::vector<ToolCall> tool_calls;
};
/* The by-hand lifter: `<function name="N"><param name="K">V</param></function>` and
* `<tool_call><function=N><parameter=K>V</parameter></function></tool_call>` spans read out of
* `text` whatever the model's format, appended to `out` and removed. */
size_t toolparse_lift_xml_calls(std::string& text, std::vector<ToolCall>& out);
/* The earliest byte of `text` that could begin a call in either spelling, or npos. */
size_t toolparse_find_call_open(const std::string& text);
/* The vendored PEG parser for one rendered request. */
class ToolParser {
public:
ToolParser();
~ToolParser();
int init(const ChatPrompt& p, const std::string& reasoning_format = "auto",
bool parse_tool_calls = true);
/* RAD_OK, or RAD_E_FORMAT when the reply does not match the format at all. */
int parse(const std::string& text, bool is_partial, ParsedReply* out) const;
bool ready() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
/* What the legacy path answers for a reply, and which of its layers produced the answer. */
struct Answer {
std::string content, reasoning;
std::vector<ToolCall> calls;
bool strict_failed = false; /* the PEG parse failed; the whole reply became content */
size_t lifted = 0; /* calls the by-hand lifter took out of the content */
};
/* The bridge's reading of a reply: the PEG parse, the terminator trim and, for a request that
* offered tools, the lifter. `is_partial` is the streaming path's question. */
Answer legacy_parse(const ToolParser& tp, const std::string& text, bool is_partial,
bool want_calls, const std::vector<std::string>& terminators);
/* The legacy streaming diff over the accumulated text: returns how many bytes of deltas it sends,
* and fills the concatenation of what it sent. */
class LegacyDeltaStream {
public:
LegacyDeltaStream(const ToolParser& tp, bool want_calls, std::vector<std::string> terminators)
: tp_(tp), want_calls_(want_calls), terms_(std::move(terminators)) {}
size_t push(const std::string& full_text, bool is_final);
const std::string& content() const { return content_; }
const std::string& reasoning() const { return reasoning_; }
const std::vector<std::string>& arguments() const { return args_; }
const std::vector<std::string>& names() const { return names_; }
private:
const ToolParser& tp_;
bool want_calls_;
std::vector<std::string> terms_;
std::string content_, reasoning_;
std::vector<std::string> names_, args_;
};
} /* namespace legacy */
} /* namespace rad */
+4008
View File
File diff suppressed because it is too large. Load diff
+120
View File
@@ -0,0 +1,120 @@
"""mkgolden.py PROCDIR OUT.h -- goldens for tests/mm_test.cpp, every number from transformers' own
code: smart_resize (image and video), sample_frames, the patches of an image and a video at sizes
the resize leaves alone, and get_rope_index over a prompt with an image and a video."""
import sys, types, io, math, hashlib
import numpy as np, torch
from PIL import Image
from transformers import AutoProcessor
from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize as sr_img
from transformers.models.qwen3_vl.video_processing_qwen3_vl import smart_resize as sr_vid
from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5Model
from transformers.video_utils import VideoMetadata
proc_dir, out = sys.argv[1], sys.argv[2]
P = AutoProcessor.from_pretrained(proc_dir)
L = ["/* mm_golden.h -- GENERATED by mkgolden.py from transformers %s; do not edit. */" % __import__("transformers").__version__,
"#pragma once", "#include <cstdint>", ""]
# ---- smart_resize, image form
L.append("struct GoldImageResize { int64_t h, w, min_px, max_px, oh, ow; };")
L.append("static const GoldImageResize kGoldImageResize[] = {")
for h, w, mn, mx in [(512, 512, 65536, 16777216), (360, 640, 65536, 16777216), (2160, 3840, 65536, 16777216),
(2160, 3840, 65536, 4194304), (100, 50, 65536, 16777216), (1, 1, 65536, 16777216),
(31, 4000, 65536, 16777216), (10000, 10000, 65536, 4194304), (1080, 1920, 65536, 4194304),
(777, 333, 65536, 4194304), (4000, 3000, 65536, 4194304), (257, 255, 65536, 16777216)]:
oh, ow = sr_img(h, w, factor=32, min_pixels=mn, max_pixels=mx)
L.append(f" {{ {h}, {w}, {mn}, {mx}, {oh}, {ow} }},")
L.append("};")
# ---- smart_resize, video form (the caller's per-frame cap already folded into max_px)
L.append("struct GoldVideoResize { int64_t t, h, w, min_px, max_px, oh, ow; };")
L.append("static const GoldVideoResize kGoldVideoResize[] = {")
def cap(nf, mn=4096, mx=25165824, rows=768, factor=32):
ppf = max(min(rows * factor * factor, mx // nf), int(mn * 1.05))
return ppf * nf
for t, h, w in [(18, 512, 512), (16, 360, 640), (4, 1080, 1920), (768, 1080, 1920), (100, 720, 1280),
(7, 20, 20), (2, 4000, 30), (300, 480, 854)]:
mx = cap(t)
oh, ow = sr_vid(t, h, w, temporal_factor=2, factor=32, min_pixels=4096, max_pixels=mx)
L.append(f" {{ {t}, {h}, {w}, 4096, {mx}, {oh}, {ow} }},")
L.append("};")
# ---- sample_frames
vp = P.video_processor
rows = []
for total, fps in [(270, 30.0), (200, 25.0), (3, 30.0), (10000, 29.97), (50, 0.0), (17, 2.0), (5000, 60.0)]:
md = VideoMetadata(total_num_frames=total, fps=fps if fps > 0 else None)
idx = vp.sample_frames(md, fps=2).tolist()
rows.append((total, fps, idx))
flat = [i for _, _, idx in rows for i in idx]
L.append("static const int64_t kGoldSampleIdx[] = { " + ", ".join(map(str, flat)) + " };")
L.append("struct GoldSample { int64_t total; double fps; int32_t first, n; };")
L.append("static const GoldSample kGoldSample[] = {")
at = 0
for total, fps, idx in rows:
L.append(f" {{ {total}, {fps!r}, {at}, {len(idx)} }},")
at += len(idx)
L.append("};")
# ---- patches: a picture and a clip at sizes the resize leaves as they are. The pixel values are a
# splitmix hash of their coordinates, so a stride that is wrong anywhere changes the result.
def pix(f, y, x, c):
z = (f * 0x9E3779B97F4A7C15 + y * 0xBF58476D1CE4E5B9 + x * 0x94D049BB133111EB + c * 0x2545F4914F6CDD1D + 12345) & (2**64 - 1)
z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & (2**64 - 1)
z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & (2**64 - 1)
return (z ^ (z >> 31)) & 255
def frame(f, h, w):
return np.array([[[pix(f, y, x, c) for c in range(3)] for x in range(w)] for y in range(h)], dtype=np.uint8)
def bf16_bits(t):
a = t.to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16)
return a
def fnv(a):
h = 0xcbf29ce484222325
for b in a.tobytes():
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
return h
img = frame(0, 256, 320)
o = P.image_processor(images=[Image.fromarray(img)], return_tensors="pt")
pv = bf16_bits(o["pixel_values"]); g = o["image_grid_thw"][0].tolist()
L.append(f"static const int32_t kGoldImageGrid[3] = {{ {g[0]}, {g[1]}, {g[2]} }};")
L.append(f"static const uint64_t kGoldImageFnv = 0x{fnv(pv):016x}ull;")
L.append("static const uint16_t kGoldImageHead[16] = { " + ", ".join(str(int(v)) for v in pv.reshape(-1)[:16]) + " };")
clip = np.stack([frame(f, 64, 96) for f in range(6)])
md = VideoMetadata(total_num_frames=6, fps=2.0, width=96, height=64, duration=3.0)
o = P.video_processor(videos=[clip], video_metadata=[md], do_sample_frames=True, fps=2,
cap_pixels_per_frame=True, return_tensors="pt", return_metadata=True)
pv = bf16_bits(o["pixel_values_videos"]); g = o["video_grid_thw"][0].tolist()
L.append(f"static const int32_t kGoldVideoGrid[3] = {{ {g[0]}, {g[1]}, {g[2]} }};")
L.append(f"static const uint64_t kGoldVideoFnv = 0x{fnv(pv):016x}ull;")
L.append("static const uint16_t kGoldVideoHead[16] = { " + ", ".join(str(int(v)) for v in pv.reshape(-1)[:16]) + " };")
mdo = o["video_metadata"][0]
ts = P._calculate_timestamps(list(mdo.frames_indices), mdo.fps, 2)
L.append("static const char* const kGoldVideoStamps[] = { " + ", ".join(f'"<{t:.1f} seconds>"' for t in ts) + " };")
# ---- get_rope_index over: 3 text, an image of 4 x 6 patches (2 x 3 rows) in its vision pair, 2 text,
# a video of 2 groups of 4 x 8 patches (2 x 4 rows) each behind its timestamp (5 text tokens here),
# 4 text. Ids are arbitrary except the pads.
IMG, VID, VS, VE = 248056, 248057, 248053, 248054
ids, tt = [], []
def text(n):
for i in range(n): ids.append(1000 + len(ids)); tt.append(0)
text(3); img_at = len(ids)
ids.append(VS); tt.append(0); ids += [IMG] * 6; tt += [1] * 6; ids.append(VE); tt.append(0)
text(2); vid_at = len(ids); vid_seg = []
for f in range(2):
text(5); ids.append(VS); tt.append(0); vid_seg.append(len(ids) - vid_at)
ids += [VID] * 8; tt += [2] * 8; ids.append(VE); tt.append(0)
text(4)
fake = types.SimpleNamespace(config=types.SimpleNamespace(vision_config=types.SimpleNamespace(spatial_merge_size=2)))
fake.get_vision_position_ids = types.MethodType(Qwen3_5Model.get_vision_position_ids, fake)
pos, delta = Qwen3_5Model.get_rope_index(fake, torch.tensor([ids]), torch.tensor([tt]),
image_grid_thw=torch.tensor([[1, 4, 6]]),
video_grid_thw=torch.tensor([[2, 4, 8]]))
pos = pos[:, 0].tolist()
L.append(f"static const int32_t kGoldRopeN = {len(ids)};")
L.append(f"static const int32_t kGoldRopeImageAt = {img_at}, kGoldRopeVideoAt = {vid_at};")
L.append(f"static const int32_t kGoldRopeVideoSeg[2] = {{ {vid_seg[0]}, {vid_seg[1]} }};")
L.append(f"static const int32_t kGoldRopeDelta = {int(delta[0][0])};")
for c, name in enumerate("THW"):
L.append(f"static const int32_t kGoldRope{name}[] = {{ " + ", ".join(map(str, pos[c])) + " };")
open(out, "w").write("\n".join(L) + "\n")
print("wrote", out, len(L), "lines")
+55
View File
@@ -0,0 +1,55 @@
/* mm_golden.h -- GENERATED by mkgolden.py from transformers 5.18.0; do not edit. */
#pragma once
#include <cstdint>
struct GoldImageResize { int64_t h, w, min_px, max_px, oh, ow; };
static const GoldImageResize kGoldImageResize[] = {
{ 512, 512, 65536, 16777216, 512, 512 },
{ 360, 640, 65536, 16777216, 352, 640 },
{ 2160, 3840, 65536, 16777216, 2176, 3840 },
{ 2160, 3840, 65536, 4194304, 1536, 2720 },
{ 100, 50, 65536, 16777216, 384, 192 },
{ 1, 1, 65536, 16777216, 256, 256 },
{ 31, 4000, 65536, 16777216, 32, 4000 },
{ 10000, 10000, 65536, 4194304, 2048, 2048 },
{ 1080, 1920, 65536, 4194304, 1088, 1920 },
{ 777, 333, 65536, 4194304, 768, 320 },
{ 4000, 3000, 65536, 4194304, 2336, 1760 },
{ 257, 255, 65536, 16777216, 256, 256 },
};
struct GoldVideoResize { int64_t t, h, w, min_px, max_px, oh, ow; };
static const GoldVideoResize kGoldVideoResize[] = {
{ 18, 512, 512, 4096, 14155776, 512, 512 },
{ 16, 360, 640, 4096, 12582912, 352, 640 },
{ 4, 1080, 1920, 4096, 3145728, 640, 1152 },
{ 768, 1080, 1920, 4096, 25165824, 128, 224 },
{ 100, 720, 1280, 4096, 25165800, 352, 640 },
{ 7, 20, 20, 4096, 5505024, 32, 32 },
{ 2, 4000, 30, 4096, 1572864, 4256, 32 },
{ 300, 480, 854, 4096, 25165800, 192, 384 },
};
static const int64_t kGoldSampleIdx[] = { 0, 16, 32, 47, 63, 79, 95, 111, 127, 142, 158, 174, 190, 206, 222, 237, 253, 269, 0, 13, 27, 40, 53, 66, 80, 93, 106, 119, 133, 146, 159, 172, 186, 199, 0, 1, 2, 0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 495, 510, 525, 540, 556, 571, 586, 601, 616, 631, 646, 661, 676, 691, 706, 721, 736, 751, 766, 781, 796, 811, 826, 841, 856, 871, 886, 901, 916, 931, 946, 961, 976, 991, 1006, 1021, 1036, 1051, 1066, 1081, 1096, 1111, 1126, 1141, 1156, 1171, 1186, 1201, 1216, 1231, 1246, 1261, 1276, 1291, 1306, 1321, 1336, 1351, 1366, 1381, 1396, 1411, 1426, 1441, 1456, 1471, 1486, 1501, 1516, 1531, 1546, 1561, 1576, 1591, 1606, 1621, 1636, 1651, 1666, 1682, 1697, 1712, 1727, 1742, 1757, 1772, 1787, 1802, 1817, 1832, 1847, 1862, 1877, 1892, 1907, 1922, 1937, 1952, 1967, 1982, 1997, 2012, 2027, 2042, 2057, 2072, 2087, 2102, 2117, 2132, 2147, 2162, 2177, 2192, 2207, 2222, 2237, 2252, 2267, 2282, 2297, 2312, 2327, 2342, 2357, 2372, 2387, 2402, 2417, 2432, 2447, 2462, 2477, 2492, 2507, 2522, 2537, 2552, 2567, 2582, 2597, 2612, 2627, 2642, 2657, 2672, 2687, 2702, 2717, 2732, 2747, 2762, 2778, 2793, 2808, 2823, 2838, 2853, 2868, 2883, 2898, 2913, 2928, 2943, 2958, 2973, 2988, 3003, 3018, 3033, 3048, 3063, 3078, 3093, 3108, 3123, 3138, 3153, 3168, 3183, 3198, 3213, 3228, 3243, 3258, 3273, 3288, 3303, 3318, 3333, 3348, 3363, 3378, 3393, 3408, 3423, 3438, 3453, 3468, 3483, 3498, 3513, 3528, 3543, 3558, 3573, 3588, 3603, 3618, 3633, 3648, 3663, 3678, 3693, 3708, 3723, 3738, 3753, 3768, 3783, 3798, 3813, 3828, 3843, 3858, 3873, 3888, 3904, 3919, 3934, 3949, 3964, 3979, 3994, 4009, 4024, 4039, 4054, 4069, 4084, 4099, 4114, 4129, 4144, 4159, 4174, 4189, 4204, 4219, 4234, 4249, 4264, 4279, 4294, 4309, 4324, 4339, 4354, 4369, 4384, 4399, 4414, 4429, 4444, 4459, 4474, 4489, 4504, 4519, 4534, 4549, 4564, 4579, 4594, 4609, 4624, 4639, 4654, 4669, 4684, 4699, 4714, 4729, 4744, 4759, 4774, 4789, 4804, 4819, 4834, 4849, 4864, 4879, 4894, 4909, 4924, 4939, 4954, 4969, 4984, 5000, 5015, 5030, 5045, 5060, 5075, 5090, 5105, 5120, 5135, 5150, 5165, 5180, 5195, 5210, 5225, 5240, 5255, 5270, 5285, 5300, 5315, 5330, 5345, 5360, 5375, 5390, 5405, 5420, 5435, 5450, 5465, 5480, 5495, 5510, 5525, 5540, 5555, 5570, 5585, 5600, 5615, 5630, 5645, 5660, 5675, 5690, 5705, 5720, 5735, 5750, 5765, 5780, 5795, 5810, 5825, 5840, 5855, 5870, 5885, 5900, 5915, 5930, 5945, 5960, 5975, 5990, 6005, 6020, 6035, 6050, 6065, 6080, 6095, 6110, 6126, 6141, 6156, 6171, 6186, 6201, 6216, 6231, 6246, 6261, 6276, 6291, 6306, 6321, 6336, 6351, 6366, 6381, 6396, 6411, 6426, 6441, 6456, 6471, 6486, 6501, 6516, 6531, 6546, 6561, 6576, 6591, 6606, 6621, 6636, 6651, 6666, 6681, 6696, 6711, 6726, 6741, 6756, 6771, 6786, 6801, 6816, 6831, 6846, 6861, 6876, 6891, 6906, 6921, 6936, 6951, 6966, 6981, 6996, 7011, 7026, 7041, 7056, 7071, 7086, 7101, 7116, 7131, 7146, 7161, 7176, 7191, 7206, 7222, 7237, 7252, 7267, 7282, 7297, 7312, 7327, 7342, 7357, 7372, 7387, 7402, 7417, 7432, 7447, 7462, 7477, 7492, 7507, 7522, 7537, 7552, 7567, 7582, 7597, 7612, 7627, 7642, 7657, 7672, 7687, 7702, 7717, 7732, 7747, 7762, 7777, 7792, 7807, 7822, 7837, 7852, 7867, 7882, 7897, 7912, 7927, 7942, 7957, 7972, 7987, 8002, 8017, 8032, 8047, 8062, 8077, 8092, 8107, 8122, 8137, 8152, 8167, 8182, 8197, 8212, 8227, 8242, 8257, 8272, 8287, 8302, 8317, 8332, 8348, 8363, 8378, 8393, 8408, 8423, 8438, 8453, 8468, 8483, 8498, 8513, 8528, 8543, 8558, 8573, 8588, 8603, 8618, 8633, 8648, 8663, 8678, 8693, 8708, 8723, 8738, 8753, 8768, 8783, 8798, 8813, 8828, 8843, 8858, 8873, 8888, 8903, 8918, 8933, 8948, 8963, 8978, 8993, 9008, 9023, 9038, 9053, 9068, 9083, 9098, 9113, 9128, 9143, 9158, 9173, 9188, 9203, 9218, 9233, 9248, 9263, 9278, 9293, 9308, 9323, 9338, 9353, 9368, 9383, 9398, 9413, 9428, 9444, 9459, 9474, 9489, 9504, 9519, 9534, 9549, 9564, 9579, 9594, 9609, 9624, 9639, 9654, 9669, 9684, 9699, 9714, 9729, 9744, 9759, 9774, 9789, 9804, 9819, 9834, 9849, 9864, 9879, 9894, 9909, 9924, 9939, 9954, 9969, 9984, 9999, 0, 16, 33, 49, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 30, 61, 91, 121, 151, 182, 212, 242, 273, 303, 333, 364, 394, 424, 454, 485, 515, 545, 576, 606, 636, 667, 697, 727, 757, 788, 818, 848, 879, 909, 939, 970, 1000, 1030, 1060, 1091, 1121, 1151, 1182, 1212, 1242, 1272, 1303, 1333, 1363, 1394, 1424, 1454, 1485, 1515, 1545, 1575, 1606, 1636, 1666, 1697, 1727, 1757, 1788, 1818, 1848, 1878, 1909, 1939, 1969, 2000, 2030, 2060, 2090, 2121, 2151, 2181, 2212, 2242, 2272, 2303, 2333, 2363, 2393, 2424, 2454, 2484, 2515, 2545, 2575, 2606, 2636, 2666, 2696, 2727, 2757, 2787, 2818, 2848, 2878, 2909, 2939, 2969, 2999, 3030, 3060, 3090, 3121, 3151, 3181, 3211, 3242, 3272, 3302, 3333, 3363, 3393, 3424, 3454, 3484, 3514, 3545, 3575, 3605, 3636, 3666, 3696, 3727, 3757, 3787, 3817, 3848, 3878, 3908, 3939, 3969, 3999, 4029, 4060, 4090, 4120, 4151, 4181,Line truncated
struct GoldSample { int64_t total; double fps; int32_t first, n; };
static const GoldSample kGoldSample[] = {
{ 270, 30.0, 0, 18 },
{ 200, 25.0, 18, 16 },
{ 3, 30.0, 34, 3 },
{ 10000, 29.97, 37, 667 },
{ 50, 0.0, 704, 4 },
{ 17, 2.0, 708, 17 },
{ 5000, 60.0, 725, 166 },
};
static const int32_t kGoldImageGrid[3] = { 1, 16, 20 };
static const uint64_t kGoldImageFnv = 0xc31622e033e97801ull;
static const uint16_t kGoldImageHead[16] = { 48827, 48984, 15633, 16204, 48914, 15785, 16144, 16136, 48900, 48775, 48994, 16238, 48938, 15425, 15997, 48924 };
static const int32_t kGoldVideoGrid[3] = { 3, 4, 6 };
static const uint64_t kGoldVideoFnv = 0x77e1d74d04428019ull;
static const uint16_t kGoldVideoHead[16] = { 48827, 48984, 15633, 16204, 48914, 15785, 16144, 16136, 48900, 48775, 48994, 16238, 48938, 15425, 15997, 48924 };
static const char* const kGoldVideoStamps[] = { "<0.2 seconds>", "<1.2 seconds>", "<2.2 seconds>" };
static const int32_t kGoldRopeN = 47;
static const int32_t kGoldRopeImageAt = 3, kGoldRopeVideoAt = 13;
static const int32_t kGoldRopeVideoSeg[2] = { 6, 21 };
static const int32_t kGoldRopeDelta = -11;
static const int32_t kGoldRopeT[] = { 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 20, 21, 22, 23, 24, 25, 26, 27, 27, 27, 27, 27, 27, 27, 27, 31, 32, 33, 34, 35 };
static const int32_t kGoldRopeH[] = { 0, 1, 2, 3, 4, 4, 4, 5, 5, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 17, 17, 17, 17, 20, 21, 22, 23, 24, 25, 26, 27, 27, 27, 27, 28, 28, 28, 28, 31, 32, 33, 34, 35 };
static const int32_t kGoldRopeW[] = { 0, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 27, 28, 29, 30, 31, 32, 33, 34, 35 };
+306
View File
@@ -0,0 +1,306 @@
/* mm_test.cpp -- the multimodal processor against the reference, number for number.
*
* Every expected value in mm_golden.h came out of transformers' own code (tests/mkgolden.py says
* which function made which table): smart_resize in both forms, the frames a video keeps, the
* patches of a picture and of a clip, the timestamps between a clip's groups, and get_rope_index's
* positions over a prompt carrying both. A model reads its prompt through all of these at once, so
* a mistake in any one is a model that still answers -- about a slightly different picture, or
* with its positions a row off -- and nothing downstream of this file can tell.
*
* The pixel inputs are a splitmix hash of their coordinates rather than a ramp: a patch taken with
* the wrong stride from a ramp is often another plausible ramp, and from this it is not.
*/
#include "rad_test.h"
#include "rad_types.h"
#include "mm/media.h"
#include "mm/processor.h"
#include "mm_golden.h"
#include <cstdio>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
using namespace rad;
using namespace rad::mm;
namespace {
uint8_t pix(uint64_t f, uint64_t y, uint64_t x, uint64_t c) {
uint64_t z = f * 0x9E3779B97F4A7C15ull + y * 0xBF58476D1CE4E5B9ull + x * 0x94D049BB133111EBull +
c * 0x2545F4914F6CDD1Dull + 12345ull;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return (uint8_t)((z ^ (z >> 31)) & 255);
}
Frame frame(int f, int h, int w) {
Frame fr;
fr.w = w;
fr.h = h;
fr.rgb.resize((size_t)w * h * 3);
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x)
for (int c = 0; c < 3; ++c)
fr.rgb[((size_t)y * w + x) * 3 + c] = pix((uint64_t)f, (uint64_t)y, (uint64_t)x, (uint64_t)c);
return fr;
}
uint64_t fnv(const std::vector<uint16_t>& v) {
uint64_t h = 0xcbf29ce484222325ull;
for (uint16_t u : v)
for (int b = 0; b < 2; ++b) h = (h ^ (uint8_t)(u >> (8 * b))) * 0x100000001b3ull;
return h;
}
/* The Qwen3.8 processor configuration, as a container converted from the checkpoint states it. */
VisionConfig qwen_cfg() {
VisionConfig c;
c.patch = 16;
c.temporal = 2;
c.merge = 2;
c.image_min_pixels = 65536;
c.image_max_pixels = 16777216;
c.video_min_pixels = 4096;
c.video_max_pixels = 25165824;
c.tok_image = 248056;
c.tok_video = 248057;
c.tok_start = 248053;
c.tok_end = 248054;
c.max_patches = 16384;
return c;
}
} /* namespace */
TEST(smart_resize_is_the_references_for_pictures) {
for (const GoldImageResize& g : kGoldImageResize) {
int64_t oh = 0, ow = 0;
std::string why;
CHECK_OK(smart_resize_image(g.h, g.w, 32, g.min_px, g.max_px, &oh, &ow, &why));
if (oh != g.oh || ow != g.ow)
std::fprintf(stderr, " %lld x %lld in [%lld, %lld]: %lld x %lld, reference %lld x %lld\n",
(long long)g.h, (long long)g.w, (long long)g.min_px, (long long)g.max_px,
(long long)oh, (long long)ow, (long long)g.oh, (long long)g.ow);
CHECK_EQ(oh, g.oh);
CHECK_EQ(ow, g.ow);
}
}
TEST(smart_resize_is_the_references_for_video) {
for (const GoldVideoResize& g : kGoldVideoResize) {
int64_t oh = 0, ow = 0;
std::string why;
CHECK_OK(smart_resize_video(g.t, g.h, g.w, 2, 32, g.min_px, g.max_px, &oh, &ow, &why));
if (oh != g.oh || ow != g.ow)
std::fprintf(stderr, " %lld frames of %lld x %lld: %lld x %lld, reference %lld x %lld\n",
(long long)g.t, (long long)g.h, (long long)g.w, (long long)oh,
(long long)ow, (long long)g.oh, (long long)g.ow);
CHECK_EQ(oh, g.oh);
CHECK_EQ(ow, g.ow);
}
}
TEST(the_frames_a_video_keeps_are_the_references) {
for (const GoldSample& g : kGoldSample) {
VideoInfo info;
info.n_frames = g.total;
info.fps = g.fps;
const std::vector<int64_t> idx = sample_frames(info, 2.0, 4, 768);
REQUIRE_EQ((int32_t)idx.size(), g.n);
int off = 0;
for (int32_t i = 0; i < g.n; ++i) off += idx[(size_t)i] != kGoldSampleIdx[g.first + i];
if (off)
std::fprintf(stderr, " %lld frames at %g fps: %d of %d indices differ\n",
(long long)g.total, g.fps, off, g.n);
CHECK_EQ(off, 0);
}
}
TEST(a_picture_patchifies_as_the_reference_does) {
Processor p;
REQUIRE(p.init(qwen_cfg(), [](const std::string&) { return std::vector<int32_t>{ 1 }; }) >= 0);
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.image_from(frame(0, 256, 320), &it, &why));
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_t, kGoldImageGrid[0]);
CHECK_EQ(it->grid_h, kGoldImageGrid[1]);
CHECK_EQ(it->grid_w, kGoldImageGrid[2]);
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1536);
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], kGoldImageHead[i]);
CHECK_EQ(fnv(it->pixels), kGoldImageFnv);
/* <|vision_start|>, a pad a merged row, <|vision_end|>: the template's triple with the pad run
* at its real length, which is what transformers substitutes. */
const int32_t rows = (kGoldImageGrid[1] / 2) * (kGoldImageGrid[2] / 2);
REQUIRE_EQ(it->expand.size(), (size_t)rows + 2);
CHECK_EQ(it->expand.front(), 248053);
CHECK_EQ(it->expand.back(), 248054);
for (int32_t i = 1; i <= rows; ++i) CHECK_EQ(it->expand[(size_t)i], 248056);
REQUIRE_EQ(it->seg_at.size(), (size_t)1);
CHECK_EQ(it->seg_at[0], 1);
CHECK_EQ(it->n_rows(), (int64_t)rows);
}
TEST(a_clip_patchifies_and_is_stamped_as_the_reference_does) {
std::vector<std::string> stamps;
Processor p;
REQUIRE(p.init(qwen_cfg(), [&](const std::string& s) {
stamps.push_back(s);
return std::vector<int32_t>(s.size(), 7); /* one token a byte: the length shows */
}) >= 0);
Video v;
v.info.n_frames = 6;
v.info.fps = 2.0;
v.info.w = 96;
v.info.h = 64;
v.index = sample_frames(v.info, 2.0, 4, 768);
for (int64_t i : v.index) v.frames.push_back(frame((int)i, 64, 96));
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.video_from(v, &it, &why));
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_t, kGoldVideoGrid[0]);
CHECK_EQ(it->grid_h, kGoldVideoGrid[1]);
CHECK_EQ(it->grid_w, kGoldVideoGrid[2]);
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1536);
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], kGoldVideoHead[i]);
CHECK_EQ(fnv(it->pixels), kGoldVideoFnv);
/* One stamp a group, in the reference's words and rounding: 0.25 s is "<0.2 seconds>". */
const size_t n_stamps = sizeof(kGoldVideoStamps) / sizeof(kGoldVideoStamps[0]);
REQUIRE_EQ(stamps.size(), n_stamps);
for (size_t i = 0; i < n_stamps; ++i) CHECK_EQ(stamps[i], std::string(kGoldVideoStamps[i]));
/* <stamp> <|vision_start|> pads <|vision_end|>, a group at a time, and nothing around them. */
const int32_t rows = (kGoldVideoGrid[1] / 2) * (kGoldVideoGrid[2] / 2);
size_t at = 0;
REQUIRE_EQ(it->seg_at.size(), (size_t)kGoldVideoGrid[0]);
for (int32_t g = 0; g < kGoldVideoGrid[0]; ++g) {
at += stamps[(size_t)g].size();
REQUIRE(at < it->expand.size());
CHECK_EQ(it->expand[at], 248053);
CHECK_EQ(it->seg_at[(size_t)g], (int32_t)(at + 1));
for (int32_t r = 0; r < rows; ++r) CHECK_EQ(it->expand[at + 1 + (size_t)r], 248057);
CHECK_EQ(it->expand[at + 1 + (size_t)rows], 248054);
at += (size_t)rows + 2;
}
CHECK_EQ(at, it->expand.size());
}
TEST(the_rotary_layout_is_get_rope_index) {
/* The prompt mkgolden.py built: an image of 2 x 3 merged rows in its vision pair, then a clip of
* two groups of 2 x 4 rows, each group behind five tokens of timestamp. Only the placement and
* the grids reach the layout, so the items carry nothing else. */
auto img = std::make_shared<Item>();
img->kind = Kind::Image;
img->grid_t = 1; img->grid_h = 4; img->grid_w = 6;
img->rows_h = 2; img->rows_w = 3; img->seg_rows = 6; img->n_seg = 1;
img->seg_at = { 1 };
auto vid = std::make_shared<Item>();
vid->kind = Kind::Video;
vid->grid_t = 2; vid->grid_h = 4; vid->grid_w = 8;
vid->rows_h = 2; vid->rows_w = 4; vid->seg_rows = 8; vid->n_seg = 2;
vid->seg_at = { kGoldRopeVideoSeg[0], kGoldRopeVideoSeg[1] };
PromptMedia pm;
Placed a; a.item = img; a.tok = kGoldRopeImageAt;
Placed b; b.item = vid; b.tok = kGoldRopeVideoAt;
pm.items = { a, b };
pm.layout();
REQUIRE_EQ(pm.rope.runs.size(), (size_t)3);
int off = 0;
for (int32_t i = 0; i < kGoldRopeN; ++i) {
int32_t p[3];
pm.rope.at(i, p);
if (p[0] != kGoldRopeT[i] || p[1] != kGoldRopeH[i] || p[2] != kGoldRopeW[i]) {
if (off < 4)
std::fprintf(stderr, " token %d: (%d, %d, %d), reference (%d, %d, %d)\n", i,
p[0], p[1], p[2], kGoldRopeT[i], kGoldRopeH[i], kGoldRopeW[i]);
++off;
}
}
CHECK_EQ(off, 0);
/* Generation continues from the reference's delta: position = index + delta, in all three. */
CHECK_EQ(pm.rope.shift_at(kGoldRopeN), kGoldRopeDelta);
int32_t p[3];
pm.rope.at(kGoldRopeN + 5, p);
CHECK_EQ(p[0], kGoldRopeN + 5 + kGoldRopeDelta);
CHECK_EQ(p[1], p[0]);
CHECK_EQ(p[2], p[0]);
}
/* THE DECODER ON EVERY FORMAT A REQUEST MAY CARRY. tests/data/media holds a solid red picture in
* each still format media.cpp admits and a short solid red clip in each container and codec
* (its README has the commands that made them); each must decode, at its size, to red. That is
* also what holds a reduced FFmpeg build -- the container image's -- to the formats the server
* accepts. A build without libavformat has no decoder, and the cases say so. */
namespace {
std::vector<uint8_t> media_file(const char* name) {
std::ifstream f(std::string(RAD_MEDIA_FIXTURES) + "/" + name, std::ios::binary);
return std::vector<uint8_t>(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
}
/* Solid red through a YUV codec and back comes out near (254, 0, 0), not exactly. */
bool is_red(const Frame& f) {
if (f.rgb.size() != (size_t)f.w * f.h * 3 || f.rgb.empty()) return false;
for (size_t i = 0; i < f.rgb.size(); i += 3)
if (f.rgb[i] < 200 || f.rgb[i + 1] > 60 || f.rgb[i + 2] > 60) return false;
return true;
}
std::vector<int64_t> first_and_last(const VideoInfo& info, const void*) {
if (info.n_frames <= 1) return {0};
return {0, info.n_frames - 1};
}
} /* namespace */
TEST(every_admitted_picture_format_decodes) {
if (!decoder_available()) { std::printf(" SKIP no media decoder in this build\n"); return; }
for (const char* name : { "red.png", "red.apng", "red.jpg", "red.webp", "red.gif", "red.bmp",
"red.tiff", "red.qoi", "red.ppm", "red.jls", "red.avif" }) {
const std::vector<uint8_t> b = media_file(name);
CHECK(!b.empty());
Frame f;
std::string why;
const int rc = decode_image(b.data(), b.size(), int64_t(1) << 24, &f, &why);
if (rc != RAD_OK) std::printf(" %s: %s\n", name, why.c_str());
CHECK_EQ(rc, RAD_OK);
const int want = std::string(name) == "red.avif" ? 64 : 32;
CHECK_EQ(f.w, want);
CHECK_EQ(f.h, want);
CHECK(is_red(f));
}
}
TEST(every_admitted_video_format_decodes) {
if (!decoder_available()) { std::printf(" SKIP no media decoder in this build\n"); return; }
for (const char* name : { "red-h264.mp4", "red-hevc.mp4", "red-av1.mp4", "red-vp8.webm",
"red-vp9.webm", "red-h264.mkv", "red-h264.ts", "red-mpeg4.avi",
"red-theora.ogv" }) {
const std::vector<uint8_t> b = media_file(name);
CHECK(!b.empty());
Video v;
std::string why;
const int rc = decode_video(b.data(), b.size(), first_and_last, nullptr, int64_t(1) << 24,
&v, &why);
if (rc != RAD_OK) std::printf(" %s: %s\n", name, why.c_str());
CHECK_EQ(rc, RAD_OK);
CHECK(v.info.n_frames >= 1);
CHECK(!v.frames.empty());
CHECK_EQ(v.frames.size(), v.index.size());
for (const Frame& f : v.frames) {
CHECK_EQ(f.w, 64);
CHECK_EQ(f.h, 64);
CHECK(is_red(f));
}
}
}
RAD_TEST_MAIN()
+162
View File
@@ -0,0 +1,162 @@
#!/bin/sh
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS]
#
# 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,
# every architecture -- is configured ON ITS OWN against that prefix with find_package(radiance),
# built, and installed into a home of its own. Nothing in the tree's build is reused: what is
# tested is the installed package a stranger would have.
#
# What has to hold afterwards:
# 1. the out-of-tree home holds the same plugins, file for file, as the tree's own build put in
# its home -- no plugin needs the tree to be built;
# 2. every kernel library declares exactly the vocabulary its in-tree twin declares;
# 3. the search path registers the same plugins, in the same order, with the same declarations
# (rad-info --plugins), from the out-of-tree home alone;
# 4. the installed rad-kbench replays the recorded fixture through the host libraries from that
# home, and every check passes;
# 5. with HIP_COMPILER given, 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.
set -eu
B=$1; S=$2; W=$3
HIPC=${4:-}; HIPT=${5:-}
GEN=${CMAKE_GENERATOR:-Ninja}
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
rm -rf "$W"
mkdir -p "$W/b" "$W/logs"
P="$W/prefix"
H="$W/home"
say() { printf '%s\n' "$*"; }
fail() { say "FAIL: $*"; exit 1; }
run() { # run LOG CMD... -- quiet unless it fails
log=$1; shift
if ! "$@" > "$log" 2>&1; then tail -40 "$log"; fail "$* (log: $log)"; fi
}
say "installing $B into $P"
run "$W/logs/install.log" cmake --install "$B" --prefix "$P"
dirs="libref libquant"
[ -d "$S/libavx" ] && [ -f "$B/radiance_home/kernels/libavx.so" ] && dirs="$dirs libavx"
for d in "$S"/arch/*/; do
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs arch/$(basename "$d")"
done
[ -n "$HIPC" ] && dirs="$dirs libr4d"
for d in $dirs; do
n=$(basename "$d")
say "building $d against the installed package"
extra=""
[ "$n" = libr4d ] && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT"
# 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"
done
# 1. The same plugins, file for file.
sets() {
for k in kernels architectures quantizers; do
[ -d "$1/$k" ] && (cd "$1/$k" && ls *.so 2>/dev/null | sed "s|^|$k/|")
done | sort
}
want=$(sets "$B/radiance_home")
[ -n "$HIPC" ] || want=$(printf '%s\n' "$want" | grep -v '^kernels/libr4d\.so$' || true)
have=$(sets "$H")
if [ "$want" != "$have" ]; then
say "in-tree:"; say "$want"; say "out of tree:"; say "$have"
fail "the out-of-tree home does not hold the plugins the tree's build does"
fi
say "1. same plugins: $(printf '%s\n' "$have" | wc -l | tr -d ' ') files"
# 2. The same vocabulary, op for op.
for so in "$H"/kernels/*.so; do
n=$(basename "$so")
"$B/bin/rad-schemas" "$B/radiance_home/kernels/$n" > "$W/schemas.tree.$n.txt"
"$B/bin/rad-schemas" "$so" > "$W/schemas.oot.$n.txt"
cmp -s "$W/schemas.tree.$n.txt" "$W/schemas.oot.$n.txt" ||
fail "$n declares a different vocabulary out of tree (diff $W/schemas.*.$n.txt)"
done
say "2. same schemas"
# 3. The same registration, from each home alone. No card: the test must not depend on one, and
# must not touch one a server is using.
listing() {
HIP_VISIBLE_DEVICES=-1 "$P/bin/rad-info" --plugins --home "$1" 2>/dev/null |
grep -v '^plugins on' | grep -v '^ /'
}
tree_list=$(listing "$B/radiance_home")
[ -n "$HIPC" ] || tree_list=$(printf '%s\n' "$tree_list" | grep -v ' libr4d ' || true)
oot_list=$(listing "$H")
# The in-tree list numbers libr4d's position when it is left out above; compare without the order
# column and check the order separately by name.
strip() { printf '%s\n' "$1" | sed 's/^ *[0-9]* //'; }
if [ "$(strip "$tree_list")" != "$(strip "$oot_list")" ]; then
say "in-tree:"; say "$tree_list"; say "out of tree:"; say "$oot_list"
fail "the plugins register differently out of tree"
fi
say "3. same registration:"
say "$oot_list"
# 4. The installed tools serve from the out-of-tree home. The replay runs every library its home
# holds, so it is given the out-of-tree home less its device library, which has no card here.
HH="$W/hosthome"
mkdir -p "$HH/kernels"
for k in architectures quantizers; do [ -d "$H/$k" ] && ln -s "$H/$k" "$HH/$k"; done
for so in "$H"/kernels/*.so; do
[ "$(basename "$so")" = libr4d.so ] || ln -s "$so" "$HH/kernels/"
done
run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 RADIANCE_HOME="$HH" \
"$P/bin/rad-kbench" --fixture "$P/share/radiance/kernels.rkb" --max-cases 1
grep -E "passed|failed" "$W/logs/kbench.log" | tail -3
say "4. the installed rad-kbench replays the fixture from the out-of-tree home: $(ls "$HH/kernels" | tr '\n' ' ')"
# 5. The device library's machine code, against the tree's, object by object. A code object also
# carries its compilation unit's ID, which clang hashes from the command line and the output path,
# so two builds of one source never agree byte for byte; their instructions (.text) and kernel
# descriptors (.rodata) do, unless the flags that reach the device compiler differ.
if [ -n "$HIPC" ]; then
L=$(dirname "$HIPC")
for t in llvm-objcopy clang-offload-bundler; do
[ -x "$L/$t" ] || fail "no $t beside $HIPC"
done
td="$B/libr4d/CMakeFiles/libr4d.dir"
od="$W/b/libr4d/CMakeFiles/libr4d.dir"
mkdir -p "$W/co"
fatbin() { # fatbin OBJ -- its fat binary into $W/co/fb; false for a source with no kernels
"$L/llvm-objcopy" --dump-section .hip_fatbin="$W/co/fb" "$1" /dev/null 2>/dev/null
}
code() { # code OBJ TARGET -- checksums of that target's instructions and kernel descriptors
fatbin "$1"
"$L/clang-offload-bundler" --type=o --input="$W/co/fb" --unbundle --targets="$2" \
--output="$W/co/co"
for sec in .text .rodata; do
"$L/llvm-objcopy" --dump-section "$sec=$W/co/sec" "$W/co/co" /dev/null 2>/dev/null ||
: > "$W/co/sec"
cksum < "$W/co/sec"
done
}
[ "$(ls "$td"/*.hip.o | wc -l)" = "$(ls "$od"/*.hip.o | wc -l)" ] ||
fail "libr4d compiles a different set of HIP sources out of tree"
n=0
for o in "$td"/*.hip.o; do
f=$(basename "$o")
[ -f "$od/$f" ] || fail "libr4d's $f has no out-of-tree twin"
if ! fatbin "$o"; then
if fatbin "$od/$f"; then fail "libr4d's $f has device code out of tree only"; fi
continue
fi
for t in $("$L/clang-offload-bundler" --type=o --input="$W/co/fb" --list | grep -v '^host-'); do
[ "$(code "$o" "$t")" = "$(code "$od/$f" "$t")" ] ||
fail "libr4d's $f compiles to different device code for $t out of tree"
n=$((n + 1))
done
done
say "5. libr4d's device code is the tree's: $n code objects, the same instructions and descriptors"
fi
say "PASS"
+2321
View File
File diff suppressed because it is too large. Load diff
+793
View File
@@ -0,0 +1,793 @@
/* plugin_test.cpp -- the plugin layer: loading, the hierarchy, op schemas, selection, bucket
* tables, the selection table and per-instance init. spec.md §2 and §16.
*
* The plugins it loads are core/plugin/testplugin/, built as real .so files: a loader tested
* against a mock is a loader that has never been dlopen'd. Their rows are chosen so that the
* assertions here are the spec's own claims -- §2.2's worked example is asserted band for band, so
* the paragraph is a regression test rather than a paragraph.
*
* A passing run PRINTS error and warning lines. They are the diagnostics under test: a refused
* plugin and a missing host kernel are meant to say so out loud, and asserting on a message nobody
* ever sees is how a message rots.
*/
#include "rad_test.h"
#include "plugin/registry.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include <nlohmann/json.hpp>
#include <dlfcn.h>
#include <cstdlib>
#include <string>
using namespace rad;
/* ------------------------------------------------------------------ fixtures */
namespace {
/* $RADIANCE_HOME is what ctest sets; RAD_TESTPLUGIN_HOME overrides it for a hand-built run. */
std::string home() {
if (const char* d = std::getenv("RAD_TESTPLUGIN_HOME")) return d;
const char* h = std::getenv("RADIANCE_HOME");
return h ? h : "radiance_home";
}
std::string kernels_dir() { return home() + "/testkernels"; }
std::string bad_dir() { return home() + "/testkernels/bad"; }
std::string order_dir() { return home() + "/testkernels/order"; }
std::string arch_dir() { return home() + "/testarch"; }
/* The hierarchy every test but the hierarchy tests uses: the override first, the base behind it. */
int load(Registry& r, std::vector<std::string> hierarchy = { "radtest_over", "radtest_base" }) {
const int st = r.load_dir(kernels_dir(), hierarchy);
if (st == RAD_E_IO)
fprintf(stderr, " (no test plugins in %s -- build the radtest_* targets)\n",
kernels_dir().c_str());
return st;
}
bool has(const std::string& hay, const std::string& needle) {
return hay.find(needle) != std::string::npos;
}
std::string errs(const Registry& r) {
std::string s;
for (const auto& e : r.load_errors()) { s += e; s += '\n'; }
return s;
}
Geometry gemm_geom(long long M, long long K = 4096, const char* dtype = "bf16") {
Geometry g;
g.set_i("M", M);
g.set_i("N", 4096);
g.set_i("K", K);
g.set_s("dtype", dtype);
return g;
}
/* A t_attn geometry every constraint of t_attn_paged holds for, WITHOUT the derived block_size --
* which is how a caller actually asks, since block_size is what it is trying to find out. The
* operator tests break exactly one key at a time, so the first unmet constraint is the one under
* test. */
Geometry attn_geom() {
Geometry g;
g.set_i("q_len", 8);
g.set_i("head_dim", 128);
g.set_i("window", 0);
g.set_i("causal", 1);
g.set_i("n_head", 8);
g.set_s("kv_dtype", "bf16");
return g;
}
/* The same question with the derived key PINNED by the caller. */
Geometry attn_geom_pinned(long long block_size) {
Geometry g = attn_geom();
g.set_i("block_size", block_size);
return g;
}
std::string picked(const KernelRow* k) { return k ? k->info->name : std::string("<none>"); }
/* The reason select() gives for a refusal, which is the miss column of §16's table. */
std::string refusal(Registry& r, const char* op, const Geometry& g, int domain = RAD_DOMAIN_DEVICE) {
SelectionTrace t;
const KernelRow* k = r.select(op, g, domain, &t);
return k ? std::string("<resolved to ") + k->info->name + ">" : t.reason;
}
RadParam pint(const char* k, long long v) { return RadParam{ k, RAD_P_INT, v, 0, nullptr, 0.0 }; }
RadParam pstr(const char* k, const char* v) { return RadParam{ k, RAD_P_STR, 0, 0, v, 0.0 }; }
RadParam pf64(const char* k, double v) { return RadParam{ k, RAD_P_F64, 0, 0, nullptr, v }; }
RadParam prange(const char* k, long long lo, long long hi) {
return RadParam{ k, RAD_P_RANGE, lo, hi, nullptr, 0.0 };
}
} /* namespace */
/* ================================================================== loading and the hierarchy */
TEST(loading_reads_identity_and_calls_open) {
Registry r;
CHECK_OK(load(r));
CHECK_EQ(r.plugins().size(), (size_t)2);
const Plugin* base = r.plugin("radtest_base");
CHECK(base != nullptr);
if (!base) return;
CHECK_EQ((int)base->kind, RAD_PLUGIN_KERNEL);
CHECK_EQ(base->version, "0.1");
CHECK_EQ(base->n_kernels, 13);
CHECK_EQ(base->n_schemas, 7);
/* The optional open hook runs once, after load and before any selection. */
auto open_calls = reinterpret_cast<int (*)(void)>(dlsym(base->handle, "radtest_open_calls"));
CHECK(open_calls != nullptr);
if (open_calls) CHECK(open_calls() >= 1);
}
/* The hierarchy is CONFIGURED, not discovered: a named plugin takes its position and one present
* on disk but absent from the list loads at the end, after everything named. */
TEST(hierarchy_order_is_configured) {
Registry r;
CHECK_OK(r.load_dir(kernels_dir(), { "radtest_base" }));
const Plugin* base = r.plugin("radtest_base");
const Plugin* over = r.plugin("radtest_over");
CHECK(base && over);
if (!base || !over) return;
CHECK_EQ(base->order, 0);
CHECK_EQ(over->order, 1); /* unnamed, so it loads behind everything named */
Registry r2;
CHECK_OK(r2.load_dir(kernels_dir(), { "radtest_over", "radtest_base" }));
CHECK_EQ(r2.plugin("radtest_over")->order, 0);
CHECK_EQ(r2.plugin("radtest_base")->order, 1);
}
/* AND WITH NOTHING NAMED, THE REFERENCE LIBRARY IS STILL LAST. It declares a kernel for every op
* in the vocabulary, so a plugin ranked behind it can never be selected: an unnamed kernel library
* for this machine's card would load, win nothing, and leave the whole model resolving to the
* naive implementation while the engine reported a full plugin set.
*
* The fixture is built so that alphabetical order alone would get this wrong -- `radtest_ord_a.so`
* is the one declaring itself a reference (RadPluginReferenceFn) and is staged first -- which is
* what makes the assertion mean something. Both plugins declare the same schemas, which is not a
* conflict. */
TEST(the_reference_library_sorts_last_with_no_hierarchy) {
Registry r;
const int st = r.load_dir(order_dir(), {});
if (st == RAD_E_IO) {
fprintf(stderr, " (no order fixture in %s -- build the radtest_ord_* targets)\n",
order_dir().c_str());
return;
}
CHECK_OK(st);
const Plugin* ref = r.plugin("radtest_reference");
const Plugin* other = r.plugin("radtest_base");
CHECK(ref && other);
if (!ref || !other) return;
CHECK(ref->reference);
CHECK(!other->reference);
CHECK(other->order < ref->order);
/* Naming it is still an override: an operator comparing a library against the reference puts
* the reference in front on purpose, and the pin must not defeat that. */
Registry r2;
CHECK_OK(r2.load_dir(order_dir(), { "radtest_reference" }));
CHECK_EQ(r2.plugin("radtest_reference")->order, 0);
CHECK(r2.plugin("radtest_base")->order > 0);
}
TEST(abi_mismatch_is_refused_by_name_with_both_versions) {
Registry r;
const int st = r.load_plugin(bad_dir() + "/radtest_badabi.so", 0);
CHECK_EQ(st, RAD_E_ABI);
CHECK_EQ(r.plugins().size(), (size_t)0);
const std::string e = errs(r);
CHECK(has(e, "radtest_badabi.so"));
CHECK(has(e, fmt("ABI version %u", (unsigned)RAD_ABI_VERSION + 7u)));
CHECK(has(e, fmt("this engine is version %u", (unsigned)RAD_ABI_VERSION)));
}
/* Two disagreeing schemas would make the same positional call mean different things depending on
* which plugin won selection. Refused at load, with both plugins named. */
TEST(schema_conflict_is_refused_with_both_plugins_named) {
Registry r;
CHECK_OK(load(r));
const size_t rows_before = r.rows().size();
const Plugin* owner = r.schema_owner("t_gemm");
CHECK(owner != nullptr);
const int st = r.load_plugin(bad_dir() + "/radtest_conflict.so", 9);
CHECK_EQ(st, RAD_E_DUPLICATE);
CHECK(r.plugin("radtest_conflict") == nullptr);
CHECK_EQ(r.rows().size(), rows_before); /* nothing of a refused plugin is registered */
const std::string e = errs(r);
CHECK(has(e, "t_gemm"));
CHECK(has(e, "radtest_conflict"));
if (owner) CHECK(has(e, owner->name));
/* Its priority-1000 row would have won every t_gemm question had it registered. */
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(8), RAD_DOMAIN_DEVICE)), "t_gemm_m16");
}
/* An architecture plugin is loaded and IDENTIFIED here; the build component drives it. One plugin
* implements one architecture id and no two may claim the same one, because the id is what selects
* the plugin a model is built from. */
TEST(architecture_plugins_are_identified_and_deduplicated) {
Registry r;
const int st = r.load_dir(arch_dir(), {});
CHECK_EQ(st, RAD_E_DUPLICATE);
CHECK_EQ(r.plugins().size(), (size_t)1);
const Plugin* a = r.plugin("radtest_arch");
CHECK(a != nullptr);
if (!a) return;
CHECK_EQ((int)a->kind, RAD_PLUGIN_ARCH);
CHECK_EQ(a->arch_id, "radtest.v1");
CHECK(a->arch_declare != nullptr);
CHECK(a->arch_step != nullptr);
CHECK_EQ(a->n_kernels, 0); /* it exports no kernel symbols, and that is not an error */
const std::string e = errs(r);
CHECK(has(e, "radtest.v1"));
CHECK(has(e, "radtest_arch2"));
}
/* THE REPLY FORMAT IS AN OPTIONAL EXPORT. Absent, the loader leaves the slot null and the plugin
* loads -- rad_arch_probe, which this plugin does not export either, shows the same rule -- and
* the engine derives the format from the chat template. Present, it is resolved, and what it
* returns is a description the reply parser can run. */
TEST(an_architecture_plugin_may_declare_its_reply_format) {
Registry r;
(void)r.load_dir(arch_dir(), {});
const Plugin* a = r.plugin("radtest_arch");
CHECK(a != nullptr);
if (!a) return;
CHECK(a->arch_probe == nullptr);
REQUIRE(a->arch_chat_format != nullptr);
const RadChatFormat* d = a->arch_chat_format(nullptr);
REQUIRE(d != nullptr);
CHECK_EQ(d->struct_size, (uint32_t)sizeof(RadChatFormat));
ChatFormat f;
std::string why;
CHECK_OK(chat_format_from_abi(d, &f, &why));
CHECK_OK(chat_format_check(f, &why));
CHECK_EQ(f.name, std::string("radtest-format"));
CHECK_EQ(f.call_open, std::string("<call>"));
CHECK_EQ(f.arg_value_prefix, std::string("="));
CHECK(f.triggers == std::vector<std::string>{ "<call>" });
/* And the parser reads a reply in it. */
std::shared_ptr<const ReplyFormat> rf;
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
const nlohmann::ordered_json tools = nlohmann::ordered_json::parse(
R"([{"type":"function","function":{"name":"go","parameters":{"type":"object",)"
R"("properties":{"n":{"type":"integer"},"s":{"type":"string"}}}}}])");
ReplyOptions ro;
ro.tools = &tools;
std::shared_ptr<const ReplyParser> rp;
CHECK_OK(ReplyParser::create(rf, ro, &rp, &why));
const ReplyMessage m = reply_parse(*rp, "<reason>hm</reason>ok<call><fn go><arg n=3</arg>"
"<arg s=<![CDATA[x<y]]></arg></fn></call>");
CHECK_EQ(m.reasoning, std::string("hm"));
CHECK_EQ(m.content, std::string("ok"));
REQUIRE(m.calls.size() == 1);
CHECK_EQ(m.calls[0].name, std::string("go"));
CHECK_EQ(m.calls[0].arguments, std::string("{\"n\":3,\"s\":\"x<y\"}"));
}
TEST(every_row_s_op_has_a_schema) {
Registry r;
CHECK_OK(load(r));
CHECK_OK(r.check_complete());
const auto ops = r.op_names();
CHECK_EQ(ops.size(), (size_t)7);
CHECK_EQ(ops[0], "t_attn");
}
/* ================================================================== op schemas */
TEST(schema_validation_accepts_the_declared_shape) {
Registry r;
CHECK_OK(load(r));
const RadOpSchema* s = r.schema("t_gemm");
CHECK(s != nullptr);
if (!s) return;
CHECK_EQ(s->n_params, 4);
std::string err;
RadParam ok[] = { pint("M", 8), pint("N", 4096), pint("K", 4096), pstr("dtype", "bf16") };
CHECK_OK(r.validate("t_gemm", ok, 4, &err));
/* A range is an integer that has not been collapsed yet, so it satisfies an integer slot. */
RadParam ranged[] = { prange("M", 1, 8192), pint("N", 4096), pint("K", 4096),
pstr("dtype", "bf16") };
CHECK_OK(r.validate("t_gemm", ranged, 4, &err));
}
TEST(schema_validation_names_the_near_miss) {
Registry r;
CHECK_OK(load(r));
std::string err;
RadParam ok[] = { pint("M", 8), pint("N", 4096), pint("K", 4096), pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_gemmm", ok, 4, &err), RAD_E_NOSCHEMA);
CHECK(has(err, "did you mean 't_gemm'"));
CHECK_EQ(r.near_miss("t_atn"), "t_attn");
CHECK_EQ(r.near_miss("completely_different"), "");
RadParam typo[] = { pint("M", 8), pint("N", 4096), pint("KK", 4096), pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_gemm", typo, 4, &err), RAD_E_SCHEMA);
CHECK(has(err, "did you mean 'K'"));
}
TEST(schema_validation_rejects_a_bad_param_set) {
Registry r;
CHECK_OK(load(r));
std::string err;
RadParam missing[] = { pint("M", 8), pint("N", 4096), pint("K", 4096) };
CHECK_EQ(r.validate("t_gemm", missing, 3, &err), RAD_E_SCHEMA);
CHECK(has(err, "dtype"));
RadParam wrong_kind[] = { pstr("M", "eight"), pint("N", 4096), pint("K", 4096),
pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_gemm", wrong_kind, 4, &err), RAD_E_SCHEMA);
CHECK(has(err, "integer"));
RadParam twice[] = { pint("M", 8), pint("M", 9), pint("N", 4096), pint("K", 4096),
pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_gemm", twice, 5, &err), RAD_E_SCHEMA);
CHECK(has(err, "twice"));
/* At most one ranged parameter per op: that is what keeps the bucket-table index a single
* integer at issue. */
RadParam two_ranges[] = { prange("M", 1, 64), pint("N", 4096), prange("K", 1, 64),
pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_gemm", two_ranges, 4, &err), RAD_E_SCHEMA);
CHECK(has(err, "at most one ranged parameter"));
}
/* A RAD_DERIVED parameter is not one the caller owes: demanding it would re-create the very
* circularity it exists to break. Supplying it is allowed, and pins it. */
TEST(schema_validation_does_not_demand_a_derived_parameter) {
Registry r;
CHECK_OK(load(r));
std::string err;
RadParam without[] = { pint("q_len", 8), pint("head_dim", 128), pint("window", 0),
pint("causal", 1), pint("n_head", 8), pstr("kv_dtype", "bf16") };
CHECK_OK(r.validate("t_attn", without, 6, &err));
RadParam with[] = { pint("q_len", 8), pint("head_dim", 128), pint("window", 0),
pint("block_size", 16), pint("causal", 1), pint("n_head", 8),
pstr("kv_dtype", "bf16") };
CHECK_OK(r.validate("t_attn", with, 7, &err));
}
/* Constraints never match on a float, so the schema check is the only thing standing between
* RAD_F64("eps", 1e-6) and an integer spelling of it that reaches the kernel as a zero. */
TEST(schema_validation_separates_a_float_from_an_integer) {
Registry r;
CHECK_OK(load(r));
std::string err;
RadParam f64[] = { pint("M", 8), pint("n", 4096), pf64("eps", 1e-6), pstr("dtype", "bf16") };
CHECK_OK(r.validate("t_norm", f64, 4, &err));
RadParam as_int[] = { pint("M", 8), pint("n", 4096), pint("eps", 0), pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_norm", as_int, 4, &err), RAD_E_SCHEMA);
CHECK(has(err, "declare it with RAD_F64()"));
RadParam f64_for_int[] = { pf64("M", 8.0), pint("n", 4096), pstr("dtype", "bf16") };
CHECK_EQ(r.validate("t_norm", f64_for_int, 3, &err), RAD_E_SCHEMA);
CHECK(has(err, "is a float"));
}
/* ================================================================== selection */
TEST(selection_takes_the_highest_declared_priority) {
Registry r;
CHECK_OK(load(r));
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(16), RAD_DOMAIN_DEVICE)), "t_gemm_m16");
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(17), RAD_DOMAIN_DEVICE)), "t_gemm_m64");
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(65), RAD_DOMAIN_DEVICE)), "t_gemm_any");
/* K = 1000 is divisible by neither 256 nor 16, and w8a8 is in no row's set: both specialised
* rows drop out and the unconstrained one serves it. */
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(8, 1000), RAD_DOMAIN_DEVICE)), "t_gemm_any");
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(8, 4096, "w8a8"), RAD_DOMAIN_DEVICE)),
"t_gemm_any");
SelectionTrace t;
r.select("t_gemm", gemm_geom(8, 1000), RAD_DOMAIN_DEVICE, &t);
CHECK_EQ(t.candidates.size(), (size_t)3); /* the host row is not a candidate */
CHECK(t.reason.empty());
}
/* Specificity is declared, not derived, and a tie goes to the row declared first. */
TEST(selection_breaks_ties_on_declaration_order) {
Registry r;
CHECK_OK(load(r));
Geometry g;
g.set_i("M", 4);
g.set_i("n", 1);
CHECK_EQ(picked(r.select("t_tie", g, RAD_DOMAIN_DEVICE)), "t_tie_first");
}
/* THE HIERARCHY IS ABSOLUTE. radtest_over's t_norm row is unconstrained and priority 1;
* radtest_base's is EQ n==4096 and priority 100. Whichever plugin is named first wins, and
* priority never crosses the plugin boundary. */
TEST(hierarchy_beats_priority_and_specificity) {
Geometry g;
g.set_i("M", 1);
g.set_i("n", 4096);
g.set_s("dtype", "bf16");
Registry over_first;
CHECK_OK(over_first.load_dir(kernels_dir(), { "radtest_over", "radtest_base" }));
CHECK_EQ(picked(over_first.select("t_norm", g, RAD_DOMAIN_DEVICE)), "t_over_norm");
Registry base_first;
CHECK_OK(base_first.load_dir(kernels_dir(), { "radtest_base", "radtest_over" }));
CHECK_EQ(picked(base_first.select("t_norm", g, RAD_DOMAIN_DEVICE)), "t_norm_specialised");
/* Domains resolve independently: radtest_over has no host row, so the host question falls
* through to the plugin below it rather than being answered "none". */
CHECK_EQ(picked(over_first.select("t_norm", g, RAD_DOMAIN_HOST)), "t_norm_host");
}
TEST(a_missing_domain_is_reported_not_substituted) {
Registry r;
CHECK_OK(load(r));
CHECK_EQ(picked(r.select("t_gemm", gemm_geom(8), RAD_DOMAIN_HOST)), "t_gemm_host");
SelectionTrace t;
const KernelRow* k = r.select("t_attn", attn_geom(), RAD_DOMAIN_HOST, &t);
CHECK(k == nullptr);
CHECK(t.other_domain_has_rows);
CHECK(has(t.reason, "no host kernel"));
}
TEST(an_unknown_op_names_the_near_miss) {
Registry r;
CHECK_OK(load(r));
const std::string why = refusal(r, "t_gem", gemm_geom(8));
CHECK(has(why, "no loaded kernel plugin implements op 't_gem'"));
CHECK(has(why, "did you mean 't_gemm'"));
}
/* Every constraint operator, and the sentence each one produces when it refuses. */
TEST(every_constraint_operator_refuses_with_its_own_reason) {
Registry r;
CHECK_OK(load(r));
CHECK_EQ(picked(r.select("t_attn", attn_geom(), RAD_DOMAIN_DEVICE)), "t_attn_paged");
Geometry g = attn_geom(); g.set_i("head_dim", 64);
CHECK(has(refusal(r, "t_attn", g), "head_dim == 128, have 64"));
g = attn_geom(); g.set_i("window", -1);
CHECK(has(refusal(r, "t_attn", g), "window >= 0, have -1"));
/* Pinned by the caller, and therefore matched normally rather than skipped. */
CHECK(has(refusal(r, "t_attn", attn_geom_pinned(32)), "block_size == 16, have 32"));
g = attn_geom(); g.set_i("causal", 2);
CHECK(has(refusal(r, "t_attn", g), "causal in {0 1}, have 2"));
g = attn_geom(); g.set_i("q_len", 17);
CHECK(has(refusal(r, "t_attn", g), "q_len <= 16, have 17"));
g = attn_geom(); g.set_i("n_head", 6);
CHECK(has(refusal(r, "t_attn", g), "n_head % 4 == 0, have 6"));
g = attn_geom(); g.set_s("kv_dtype", "f32");
CHECK(has(refusal(r, "t_attn", g), "kv_dtype in {bf16 fp8_e4m3}, have f32"));
/* A constraint whose key the geometry lacks does NOT hold -- libr4d's rule, and the reason its
* two-shot all-reduce rows can be reached at all. */
Geometry partial;
partial.set_i("q_len", 8);
CHECK(has(refusal(r, "t_attn", partial), "did not name head_dim"));
}
/* RAD_DERIVED: the parameter the KERNEL supplies. Skipped during matching when the caller did not
* name it -- otherwise spec §7.2 is circular, since the block manager reads the block size off the
* resolved kernel and the kernel cannot resolve without it -- and written into the resolved
* geometry once a winner exists. */
TEST(a_derived_parameter_is_skipped_then_supplied) {
Registry r;
CHECK_OK(load(r));
SelectionTrace t;
const KernelRow* k = r.select("t_attn", attn_geom(), RAD_DOMAIN_DEVICE, &t);
CHECK_EQ(picked(k), "t_attn_paged"); /* would refuse "did not name block_size" without */
CHECK_EQ(t.derived.size(), (size_t)1);
if (t.derived.size() == 1) {
CHECK_EQ(t.derived[0].key, "block_size");
CHECK(t.derived[0].known);
CHECK_EQ(t.derived[0].value, 16);
}
/* The resolved geometry carries it, so rad_kv_block_size() and RadArgs.p see one number. */
Resolved res = r.resolve("t_attn", attn_geom(), RAD_DOMAIN_DEVICE);
CHECK(res);
long long bs = 0;
CHECK(res.geom.get_i("block_size", &bs));
CHECK_EQ(bs, 16);
/* A caller that supplies it has pinned it: matched normally, so a mismatch is a refusal by
* name rather than a silent substitution, and nothing is derived afterwards. */
SelectionTrace pinned;
CHECK_EQ(picked(r.select("t_attn", attn_geom_pinned(16), RAD_DOMAIN_DEVICE, &pinned)),
"t_attn_paged");
CHECK_EQ(pinned.derived.size(), (size_t)0);
CHECK(r.select("t_attn", attn_geom_pinned(32), RAD_DOMAIN_DEVICE) == nullptr);
}
/* A winner with no RAD_C_EQ on the derived key -- ref's `block_size >= 1`, which admits every
* value -- leaves it unset. "any" is not a number, and the caller has to decide rather than be
* handed a zero that looks like an answer. */
TEST(a_derived_key_with_no_eq_stays_unset) {
Registry r;
CHECK_OK(load(r));
SelectionTrace t;
CHECK_EQ(picked(r.select("t_attn_ref", attn_geom(), RAD_DOMAIN_DEVICE, &t)), "t_attn_ref_any");
CHECK_EQ(t.derived.size(), (size_t)1);
if (t.derived.size() == 1) {
CHECK_EQ(t.derived[0].key, "block_size");
CHECK(!t.derived[0].known);
}
Resolved res = r.resolve("t_attn_ref", attn_geom(), RAD_DOMAIN_DEVICE);
CHECK(res);
CHECK(!res.geom.has("block_size"));
}
TEST(bands_carry_the_derived_value_into_every_band) {
Registry r;
CHECK_OK(load(r));
std::vector<Band> b = r.build_bands("t_attn", "q_len", 1, 64, attn_geom());
/* q_len <= 16 is the only boundary the rows place on it, so (0,16] resolves and (16,64] does
* not -- and the resolved band still carries the kernel's block size. */
CHECK_EQ(b.size(), (size_t)2);
if (b.size() != 2) return;
CHECK_EQ(b[0].hi, 16);
CHECK_EQ(picked(b[0].dom[RAD_DOMAIN_DEVICE].row), "t_attn_paged");
long long bs = 0;
CHECK(b[0].dom[RAD_DOMAIN_DEVICE].geom.get_i("block_size", &bs));
CHECK_EQ(bs, 16);
CHECK(!b[1].dom[RAD_DOMAIN_DEVICE]);
}
/* §7.2: the block size comes from the resolved attention kernel's own constraints, not from a core
* constant. This is the accessor the block manager reads it with. */
TEST(a_resolved_kernel_s_constraints_are_readable) {
Registry r;
CHECK_OK(load(r));
const KernelRow* k = r.select("t_attn", attn_geom(), RAD_DOMAIN_DEVICE);
CHECK(k != nullptr);
if (!k) return;
long long v = 0;
CHECK(kernel_constraint(*k, "block_size", RAD_C_EQ, &v));
CHECK_EQ(v, 16);
CHECK(kernel_constraint(*k, "q_len", RAD_C_LE, &v));
CHECK_EQ(v, 16);
/* Absent is not a default: the kernel says nothing about window with EQ, and the caller has to
* notice rather than being handed a zero. */
CHECK(!kernel_constraint(*k, "window", RAD_C_EQ, &v));
CHECK(!kernel_constraint(*k, "nonesuch", RAD_C_EQ, &v));
}
/* ================================================================== bucket tables */
/* spec.md §2.2's worked example, asserted band for band: three kernels constraining M<=16, M<=64
* and nothing produce (0,16], (16,64], (64,max] and no policy was chosen by anyone. */
TEST(band_table_is_the_worked_example) {
Registry r;
CHECK_OK(load(r));
Geometry base;
base.set_i("N", 4096);
base.set_i("K", 4096);
base.set_s("dtype", "bf16");
std::vector<Band> b = r.build_bands("t_gemm", "M", 1, 8192, base);
CHECK_EQ(b.size(), (size_t)3);
if (b.size() != 3) return;
CHECK_EQ(b[0].hi, 16);
CHECK_EQ(b[1].hi, 64);
CHECK_EQ(b[2].hi, 8192);
CHECK_EQ(picked(b[0].dom[RAD_DOMAIN_DEVICE].row), "t_gemm_m16");
CHECK_EQ(picked(b[1].dom[RAD_DOMAIN_DEVICE].row), "t_gemm_m64");
CHECK_EQ(picked(b[2].dom[RAD_DOMAIN_DEVICE].row), "t_gemm_any");
/* Both domains are resolved wherever both exist, so the core can change execution site at
* runtime without re-resolving. */
for (const Band& band : b) {
CHECK_EQ(picked(band.dom[RAD_DOMAIN_HOST].row), "t_gemm_host");
CHECK(band.miss[RAD_DOMAIN_DEVICE].empty());
}
/* Each band is frozen AT ITS UPPER BOUND, which is the worst case in the band. */
long long m = 0;
CHECK(b[1].dom[RAD_DOMAIN_DEVICE].geom.get_i("M", &m));
CHECK_EQ(m, 64);
CHECK_EQ(b[1].dom[RAD_DOMAIN_DEVICE].tune_source, "axis defaults");
}
/* A range with a hole in it is reported as that band, not as the whole op. The boundaries are the
* constraint values themselves: LE 64 gives 64, GE 4096 ends the band below it at 4095. */
TEST(band_boundaries_come_from_the_constraints) {
Registry r;
CHECK_OK(load(r));
Geometry base;
base.set_i("N", 4096);
base.set_i("K", 4096);
base.set_s("dtype", "bf16");
std::vector<Band> b = r.build_bands("t_skinny", "M", 1, 8192, base);
CHECK_EQ(b.size(), (size_t)3);
if (b.size() != 3) return;
CHECK_EQ(b[0].hi, 64);
CHECK_EQ(b[1].hi, 4095);
CHECK_EQ(b[2].hi, 8192);
CHECK_EQ(picked(b[0].dom[RAD_DOMAIN_DEVICE].row), "t_skinny_m64");
CHECK(!b[1].dom[RAD_DOMAIN_DEVICE]);
CHECK(has(b[1].miss[RAD_DOMAIN_DEVICE], "M <= 64, have 4095"));
CHECK(has(b[1].miss[RAD_DOMAIN_DEVICE], "M >= 4096, have 4095"));
CHECK_EQ(picked(b[2].dom[RAD_DOMAIN_DEVICE].row), "t_skinny_big");
/* No host kernel anywhere for this op: every band says which placement option that removed. */
for (const Band& band : b) {
CHECK(!band.dom[RAD_DOMAIN_HOST]);
CHECK(has(band.miss[RAD_DOMAIN_HOST], "site 'host' is unavailable"));
}
}
TEST(an_eq_constraint_cuts_both_edges) {
Registry r;
CHECK_OK(load(r));
Geometry base;
base.set_i("n", 1);
std::vector<Band> b = r.build_bands("t_eq", "M", 1, 64, base);
CHECK_EQ(b.size(), (size_t)3);
if (b.size() != 3) return;
CHECK_EQ(b[0].hi, 31);
CHECK_EQ(b[1].hi, 32);
CHECK_EQ(b[2].hi, 64);
CHECK(!b[0].dom[RAD_DOMAIN_DEVICE]);
CHECK_EQ(picked(b[1].dom[RAD_DOMAIN_DEVICE].row), "t_eq_m32");
CHECK(!b[2].dom[RAD_DOMAIN_DEVICE]);
}
TEST(bands_clamp_to_the_declared_range) {
Registry r;
CHECK_OK(load(r));
Geometry base;
base.set_i("N", 4096);
base.set_i("K", 4096);
base.set_s("dtype", "bf16");
/* 16 is below the range and 64 is at or above its top: neither cuts anything. */
std::vector<Band> narrow = r.build_bands("t_gemm", "M", 32, 48, base);
CHECK_EQ(narrow.size(), (size_t)1);
CHECK_EQ(narrow[0].hi, 48);
CHECK_EQ(picked(narrow[0].dom[RAD_DOMAIN_DEVICE].row), "t_gemm_m64");
std::vector<Band> tiny = r.build_bands("t_gemm", "M", 1, 16, base);
CHECK_EQ(tiny.size(), (size_t)1);
CHECK_EQ(tiny[0].hi, 16);
CHECK_EQ(picked(tiny[0].dom[RAD_DOMAIN_DEVICE].row), "t_gemm_m16");
}
TEST(an_op_with_no_range_gets_one_band) {
Registry r;
CHECK_OK(load(r));
std::vector<Band> b = r.build_bands("t_attn", "", 0, 0, attn_geom());
CHECK_EQ(b.size(), (size_t)1);
if (b.empty()) return;
CHECK_EQ(b[0].hi, INT64_MAX);
CHECK_EQ(picked(b[0].dom[RAD_DOMAIN_DEVICE].row), "t_attn_paged");
CHECK(!b[0].dom[RAD_DOMAIN_HOST]);
}
/* ================================================================== instances */
TEST(init_runs_once_per_resolved_instance) {
Registry r;
CHECK_OK(load(r));
const Plugin* base = r.plugin("radtest_base");
CHECK(base != nullptr);
if (!base) return;
auto n_init = reinterpret_cast<int (*)(void)>(dlsym(base->handle, "radtest_init_calls"));
auto n_fini = reinterpret_cast<int (*)(void)>(dlsym(base->handle, "radtest_fini_calls"));
auto inst_m = reinterpret_cast<long long (*)(void*)>(dlsym(base->handle, "radtest_instance_m"));
CHECK(n_init && n_fini && inst_m);
if (!n_init || !n_fini || !inst_m) return;
const int init0 = n_init(), fini0 = n_fini();
Geometry g;
g.set_i("N", 4096);
g.set_i("K", 4096);
g.set_s("dtype", "bf16");
std::vector<Band> b = r.build_bands("t_gemm", "M", 1, 8192, g);
CHECK_EQ(b.size(), (size_t)3);
if (b.size() != 3) return;
for (Band& band : b) CHECK_OK(r.init_instance(band.dom[RAD_DOMAIN_DEVICE], 0, 1));
CHECK_EQ(n_init() - init0, 3);
CHECK_EQ(r.n_instances(), (size_t)3);
/* The instance saw the FROZEN geometry -- its own band's upper bound, not the range. */
CHECK_EQ(inst_m(b[0].dom[RAD_DOMAIN_DEVICE].instance), 16);
CHECK_EQ(inst_m(b[2].dom[RAD_DOMAIN_DEVICE].instance), 8192);
/* The host rows have no init hook: that is RAD_OK and a null instance, not a call. */
CHECK_OK(r.init_instance(b[0].dom[RAD_DOMAIN_HOST], 0, 1));
CHECK(b[0].dom[RAD_DOMAIN_HOST].instance == nullptr);
CHECK_EQ(n_init() - init0, 3);
r.fini_instances();
CHECK_EQ(n_fini() - fini0, 3);
CHECK_EQ(r.n_instances(), (size_t)0);
}
TEST(a_negative_init_is_a_value_not_a_crash) {
Registry r;
CHECK_OK(load(r));
Geometry base;
base.set_i("n", 1);
std::vector<Band> b = r.build_bands("t_eq", "M", 32, 32, base);
CHECK_EQ(b.size(), (size_t)1);
if (b.empty()) return;
CHECK_EQ(picked(b[0].dom[RAD_DOMAIN_DEVICE].row), "t_eq_m32");
CHECK_EQ(r.init_instance(b[0].dom[RAD_DOMAIN_DEVICE], 0, 1), RAD_E_NOMEM);
CHECK_EQ(r.n_instances(), (size_t)0);
}
/* ================================================================== the selection table (§16) */
TEST(the_selection_table_folds_repeats_and_names_the_refusal) {
Registry r;
CHECK_OK(load(r));
r.clear_selections();
r.select("t_gemm", gemm_geom(16), RAD_DOMAIN_DEVICE);
r.select("t_gemm", gemm_geom(16), RAD_DOMAIN_DEVICE); /* the same question, folded */
CHECK_EQ(r.n_selections(), (size_t)1);
r.select("t_gemm", gemm_geom(16), RAD_DOMAIN_HOST); /* a different domain is a different
* question */
CHECK_EQ(r.n_selections(), (size_t)2);
Geometry g = attn_geom();
g.set_i("q_len", 17);
r.select("t_attn", g, RAD_DOMAIN_DEVICE);
CHECK_EQ(r.n_selections(), (size_t)3);
r.select("t_attn", attn_geom(), RAD_DOMAIN_DEVICE);
CHECK_EQ(r.n_selections(), (size_t)4);
const std::string table = r.selection_table();
CHECK(has(table, "4 distinct questions, 5 asked"));
CHECK(has(table, "t_gemm_m16 (radtest_base, prio 30)"));
CHECK(has(table, "M=16 N=4096 K=4096 dtype=bf16"));
CHECK(has(table, "-- none: q_len <= 16, have 17"));
/* A derived key was not part of the question, so it is printed as the kernel's answer and not
* inside the geometry column. */
CHECK(has(table, "derived block_size:=16"));
CHECK(!has(table, "block_size=16 "));
r.clear_selections();
CHECK_EQ(r.n_selections(), (size_t)0);
}
RAD_TEST_MAIN()
+351
View File
@@ -0,0 +1,351 @@
/* quant_algo_test.cpp -- libquant's calibrated algorithms: GPTQ's act order, AWQ, AutoRound and
* ParoQuant, each against round-to-nearest on the same grid.
*
* WHAT THEY ARE HELD TO is the number every one of them minimises: the layer's output error, the
* Hessian's quadratic form sum_r (w_hat_r - w_r) H (w_hat_r - w_r)^T, with H the Gram of a
* synthetic input whose channels are as uneven as a real layer's -- a few carry most of the
* energy, and neighbours are correlated. The decoded weight is read back through the core's
* decoder, so a transform or a column scale the quantiser wrote and the reader did not undo is an
* error of order one, not a near miss. Each is also run twice at two thread counts and must give
* the same bytes: its output is a file.
*/
#include "quant_fixture.h"
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace rad;
using namespace qfix;
namespace {
constexpr int64_t kR = 64, kC = 256, kT = 4096;
/* The input: per-channel energy spread over two decades, a few channels ten times the rest, and
* each channel mixed with its neighbours. */
std::vector<float> gram() {
const std::vector<float> z = draw(kT * kC, 101);
std::vector<float> amp((size_t)kC);
for (int64_t c = 0; c < kC; ++c)
amp[(size_t)c] = (float)std::pow(10.0, (double)((c * 37) % kC) / kC * 2.0) *
((c % 31 == 3) ? 10.0f : 1.0f);
std::vector<float> x((size_t)(kT * kC));
for (int64_t t = 0; t < kT; ++t)
for (int64_t c = 0; c < kC; ++c) {
const float* zr = &z[(size_t)(t * kC)];
const float v = zr[c] + 0.5f * zr[(c + 1) % kC] + 0.25f * zr[(c + 7) % kC];
x[(size_t)(t * kC + c)] = v * amp[(size_t)c];
}
std::vector<double> h((size_t)(kC * kC), 0.0);
for (int64_t t = 0; t < kT; ++t)
for (int64_t i = 0; i < kC; ++i) {
const double xi = x[(size_t)(t * kC + i)];
for (int64_t j = 0; j < kC; ++j) h[(size_t)(i * kC + j)] += xi * x[(size_t)(t * kC + j)];
}
std::vector<float> hf(h.size());
for (size_t i = 0; i < h.size(); ++i) hf[i] = (float)h[i];
return hf;
}
const std::vector<float>& H() {
static const std::vector<float> h = gram();
return h;
}
/* A calibration directory holding the Gram for `stem`, made once. */
const std::string& calib_dir() {
static std::string d;
if (d.empty()) {
char tmpl[] = "/tmp/rad_quant_algo_XXXXXX";
if (mkdtemp(tmpl)) {
d = tmpl;
write_gram(d + "/gram.r0.blk.2.attn_q.bin", kC, kT, H());
}
}
return d;
}
double out_err(const std::vector<float>& w, const std::vector<float>& d) {
double e = 0.0;
const std::vector<float>& h = H();
for (int64_t r = 0; r < kR; ++r)
for (int64_t i = 0; i < kC; ++i) {
const double di = (double)d[(size_t)(r * kC + i)] - w[(size_t)(r * kC + i)];
if (di == 0.0) continue;
double hi = 0.0;
for (int64_t j = 0; j < kC; ++j)
hi += (double)h[(size_t)(i * kC + j)] *
((double)d[(size_t)(r * kC + j)] - w[(size_t)(r * kC + j)]);
e += di * hi;
}
return e;
}
const std::vector<float>& weight() {
static const std::vector<float> w = draw(kR * kC, 102, 6.0f);
return w;
}
const char* kName = "blk.2.attn_q.weight";
/* The thread count of the OpenMP runtime the plugin loaded, so a run can be repeated at another. */
void threads(int n) {
using Fn = void (*)(int);
if (Fn f = (Fn)dlsym(RTLD_DEFAULT, "omp_set_num_threads")) f(n);
}
/* rtn, then the algorithm, on the same grid; the algorithm decoded, its output error below rtn's
* by `margin`, and its bytes the same at one thread and at four. */
void beats_rtn(const char* algo, Opts grid, Opts extra, double margin, const char* want_enc) {
const std::vector<float>& w = weight();
Quantised r = quantise(quantizer("rtn"), grid, kName, kR, kC, w);
REQUIRE_EQ(r.status, RAD_OK);
Opts o = grid;
for (size_t i = 0; i < extra.p.size(); ++i) {
if (extra.p[i].kind == RAD_P_STR) o.s(extra.keys[i].c_str(), extra.vals[i].c_str());
else if (extra.p[i].kind == RAD_P_INT) o.i(extra.keys[i].c_str(), extra.p[i].ival);
else o.f(extra.keys[i].c_str(), extra.p[i].dval);
}
o.s("calib", calib_dir().c_str());
threads(1);
Quantised a = quantise(quantizer(algo), o, kName, kR, kC, w);
threads(4);
Quantised b = quantise(quantizer(algo), o, kName, kR, kC, w);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(b.status, RAD_OK);
if (want_enc) CHECK_EQ(enc_name(a.enc), std::string(want_enc));
int same = 1;
for (int i = 0; i < a.enc.n_planes; ++i) same &= a.planes[(size_t)i] == b.planes[(size_t)i];
CHECK(same);
const std::vector<float> dr = decode(r, kR, kC), da = decode(a, kR, kC);
REQUIRE(!da.empty());
const double er = out_err(w, dr), ea = out_err(w, da);
std::fprintf(stderr, " %s: output error %.4g of rtn's, weight error %.4f (rtn %.4f)\n",
algo, ea / er, rel_err(w, da), rel_err(w, dr));
CHECK(ea < er * margin);
}
} /* namespace */
TEST(the_calibrated_quantisers_are_in_the_registry) {
NEED_LIBQUANT();
for (const char* q : { "awq", "autoround", "paroquant", "cast" }) CHECK(quantizer(q) != nullptr);
}
TEST(gptq_act_order_stores_the_permutation_it_quantised_in) {
NEED_LIBQUANT();
const std::vector<float>& w = weight();
Opts o;
o.s("codes", "i4").i("group", 32).s("scale", "f16").i("act_order", 1)
.s("calib", calib_dir().c_str());
Quantised q = quantise(quantizer("gptq"), o, kName, kR, kC, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("i4*f16[1x32]/perm"));
/* the permutation is the columns by descending Hessian diagonal */
std::vector<int32_t> perm((size_t)kC);
std::memcpy(perm.data(), q.planes[2].data(), (size_t)kC * 4);
int bad = 0;
for (int64_t j = 1; j < kC; ++j)
bad += H()[(size_t)(perm[(size_t)j - 1] * (kC + 1))] < H()[(size_t)(perm[(size_t)j] * (kC + 1))];
CHECK_EQ(bad, 0);
Opts n;
n.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", calib_dir().c_str());
Opts m;
m.s("codes", "i4").i("group", 32).s("scale", "f16");
Quantised g = quantise(quantizer("gptq"), n, kName, kR, kC, w);
Quantised r = quantise(quantizer("rtn"), m, kName, kR, kC, w);
const double ea = out_err(w, decode(q, kR, kC)), eg = out_err(w, decode(g, kR, kC));
const double er = out_err(w, decode(r, kR, kC));
std::fprintf(stderr, " output error of rtn's: gptq %.4f, gptq act order %.4f\n", eg / er,
ea / er);
CHECK(ea < er * 0.8);
}
/* The width-n Hadamard over each n-block of a row, unnormalised: libquant's own butterflies, in
* its order, so a file this writes is the bytes libquant would make of the model-domain one. */
void fwht_rows(std::vector<double>& h, int64_t k, int64_t n) {
for (int64_t r = 0; r < k; ++r) {
double* v = h.data() + r * k;
for (int64_t b0 = 0; b0 < k; b0 += n)
for (int64_t s = 1; s < n; s *= 2)
for (int64_t i = b0; i < b0 + n; i += 2 * s)
for (int64_t j = i; j < i + s; ++j) {
const double x = v[j], y = v[j + s];
v[j] = x + y;
v[j + s] = x - y;
}
}
}
TEST(a_hessian_is_brought_into_the_domain_its_grid_quantises_in) {
/* The same Gram twice over: as the model's input (domain 0, what a bf16 model's tap writes)
* and rotated by the width-128 Hadamard (domain 128, what a rotated container's tap writes).
* A rotated grid quantised against either must come out byte for byte the same -- the reader
* rotates the first exactly as the second was rotated -- and an unrotated grid against the
* rotated file must too, after the reader rotates it back. */
NEED_LIBQUANT();
const std::vector<float>& hf = H();
std::vector<double> h(hf.begin(), hf.end());
fwht_rows(h, kC, 128);
std::vector<double> t((size_t)(kC * kC));
for (int64_t r = 0; r < kC; ++r)
for (int64_t c = 0; c < kC; ++c) t[(size_t)(c * kC + r)] = h[(size_t)(r * kC + c)];
fwht_rows(t, kC, 128);
std::vector<float> rot((size_t)(kC * kC));
for (int64_t r = 0; r < kC; ++r)
for (int64_t c = 0; c < kC; ++c) rot[(size_t)(r * kC + c)] = (float)t[(size_t)(c * kC + r)];
char tmpl[] = "/tmp/rad_quant_dom_XXXXXX";
REQUIRE(mkdtemp(tmpl) != nullptr);
const std::string dm = tmpl;
REQUIRE(write_gram(dm + "/gram.r0.blk.2.attn_q.bin", kC, kT, rot, 128));
auto run = [&](const std::string& dir, bool rotated) {
Opts o;
o.s("codes", "i4").i("group", 128).s("scale", "f16").s("calib", dir.c_str());
if (rotated) o.s("transform", "fwht128");
return quantise(quantizer("gptq"), o, kName, kR, kC, weight());
};
const Quantised a = run(calib_dir(), true), b = run(dm, true);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(b.status, RAD_OK);
int same = a.enc.n_planes == b.enc.n_planes;
for (int i = 0; same && i < a.enc.n_planes; ++i) same &= a.planes[(size_t)i] == b.planes[(size_t)i];
CHECK(same);
/* And the way back: a rotated file read for an unrotated grid is the model's Gram up to the
* rounding of a rotation there and back, so the two quantise within a hair of each other. */
const Quantised c = run(calib_dir(), false), d = run(dm, false);
REQUIRE_EQ(c.status, RAD_OK);
REQUIRE_EQ(d.status, RAD_OK);
const double ec = out_err(weight(), decode(c, kR, kC)), ed = out_err(weight(), decode(d, kR, kC));
std::fprintf(stderr, " unrotated grid: model-domain %.6g, back from rotated %.6g\n", ec, ed);
CHECK(std::fabs(ec - ed) <= 1e-3 * ec);
std::remove((dm + "/gram.r0.blk.2.attn_q.bin").c_str());
rmdir(dm.c_str());
}
TEST(an_expert_reads_its_own_hessian_before_its_layers) {
/* A layer's pooled Gram and one expert's own, which differ (the own one is the pooled one with
* its channels reversed). The expert with a file of its own must quantise exactly as against
* that Gram alone, wherever its rank put it; an expert with no file of its own, and one whose
* file says fewer rows than libquant trusts an own Gram with, exactly as against the pooled
* one. And the two answers must differ, or the test could not tell them apart. */
NEED_LIBQUANT();
const std::vector<float>& pool = H();
std::vector<float> own((size_t)(kC * kC));
for (int64_t i = 0; i < kC; ++i)
for (int64_t j = 0; j < kC; ++j)
own[(size_t)(i * kC + j)] = pool[(size_t)((kC - 1 - i) * kC + (kC - 1 - j))];
char t1[] = "/tmp/rad_quant_exp_XXXXXX", t2[] = "/tmp/rad_quant_own_XXXXXX",
t3[] = "/tmp/rad_quant_pool_XXXXXX";
REQUIRE(mkdtemp(t1) && mkdtemp(t2) && mkdtemp(t3));
const std::string both = t1, only_own = t2, only_pool = t3;
const std::vector<std::string> files = {
both + "/gram.r0.blk.2.ffn_down_exps.bin", both + "/gram.r1.blk.2.ffn_down_exps.7.bin",
both + "/gram.r0.blk.2.ffn_down_exps.9.bin", only_own + "/gram.r0.blk.2.ffn_down_exps.bin",
only_pool + "/gram.r0.blk.2.ffn_down_exps.bin" };
REQUIRE(write_gram(files[0], kC, kT, pool));
/* libquant's lq::kOwnRowsPerK: the rows an own Gram needs, in units of K */
constexpr int64_t kOwnRowsPerK = 4;
REQUIRE(write_gram(files[1], kC, kOwnRowsPerK * kC, own));
REQUIRE(write_gram(files[2], kC, kOwnRowsPerK * kC - 1, own));
REQUIRE(write_gram(files[3], kC, kT, own));
REQUIRE(write_gram(files[4], kC, kT, pool));
auto run = [&](const std::string& dir, const char* name) -> Quantised {
Opts o;
o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str());
Quantised q = quantise(quantizer("gptq"), o, name, kR, kC, weight());
CHECK_EQ(q.status, RAD_OK);
return q;
};
auto same = [](const Quantised& a, const Quantised& b) {
int s = a.enc.n_planes == b.enc.n_planes;
for (int i = 0; s && i < a.enc.n_planes; ++i) s &= a.planes[(size_t)i] == b.planes[(size_t)i];
return s != 0;
};
const char* e7 = "blk.2.ffn_down_exps.7.weight";
const char* e9 = "blk.2.ffn_down_exps.9.weight";
const char* e11 = "blk.2.ffn_down_exps.11.weight";
CHECK(same(run(both, e7), run(only_own, e7)));
CHECK(!same(run(both, e7), run(only_pool, e7)));
CHECK(same(run(both, e9), run(only_pool, e9)));
CHECK(same(run(both, e11), run(only_pool, e11)));
for (const std::string& f : files) std::remove(f.c_str());
for (const std::string& d : { both, only_own, only_pool }) rmdir(d.c_str());
}
TEST(awq_scales_the_columns_the_input_says_matter) {
NEED_LIBQUANT();
Opts g, x;
g.s("codes", "i4").i("group", 64).s("scale", "f16");
beats_rtn("awq", g, x, 0.9, "i4*f16[1x64]*f16[*x1]");
/* asymmetric, and over a codebook */
Opts g2, g3;
g2.s("codes", "u3").s("zero", "u4").i("group", 64).s("scale", "f16");
beats_rtn("awq", g2, x, 0.95, nullptr);
g3.s("table", "nf4").i("group", 64).s("scale", "bf16");
beats_rtn("awq", g3, x, 0.95, nullptr);
}
TEST(autoround_descends_below_round_to_nearest) {
NEED_LIBQUANT();
Opts g, x, g2;
g.s("codes", "i4").i("group", 32).s("scale", "f16");
x.i("iters", 60);
beats_rtn("autoround", g, x, 0.8, "i4*f16[1x32]");
g2.s("codes", "u2").s("zero", "u4").i("group", 64).s("scale", "f16");
beats_rtn("autoround", g2, x, 0.9, nullptr);
}
TEST(paroquant_learns_a_rotation_the_reader_undoes) {
NEED_LIBQUANT();
Opts g, x;
g.s("codes", "u4").s("zero", "u4").i("group", 128).s("scale", "f16");
x.i("steps", 60).i("iters", 40).i("sample_rows", 32);
beats_rtn("paroquant", g, x, 0.85, "u4*f16[1x128]-u4[1x128]/givens");
/* the rotation alone, stage two off, is already below rounding to nearest */
Opts x1;
x1.i("steps", 60).i("iters", 0).i("sample_rows", 32);
beats_rtn("paroquant", g, x1, 0.95, nullptr);
/* the pairs: every stage a perfect matching inside each 128-channel group */
Opts ident = g;
ident.i("steps", 0).i("iters", 0);
Quantised q = quantise(quantizer("paroquant"), ident, kName, kR, kC, weight());
REQUIRE_EQ(q.status, RAD_OK);
const int32_t* p = (const int32_t*)q.planes[4].data();
int bad = 0;
for (int s = 0; s < 8; ++s) {
std::vector<int> seen((size_t)kC, 0);
for (int64_t k = 0; k < kC; k += 2) {
const int32_t a = p[s * kC + k], b = p[s * kC + k + 1];
bad += a / 128 != b / 128 || a == b;
++seen[(size_t)a];
++seen[(size_t)b];
}
for (int v : seen) bad += v != 1;
}
CHECK_EQ(bad, 0);
}
TEST(a_calibrated_quantiser_refuses_a_grid_it_cannot_serve) {
NEED_LIBQUANT();
RadQuantWeight qw{};
qw.name = kName;
qw.rank = 2; qw.shape[0] = kR; qw.shape[1] = kC; qw.rows = kR; qw.cols = kC;
RadEncoding e;
auto refused = [&](const char* q, Opts o) {
return quantizer(q)->encoding(o.data(), o.n(), &qw, &e) != RAD_OK;
};
{ Opts o; o.s("codes", "i4").s("transform", "fwht128"); CHECK(refused("awq", o)); }
{ Opts o; o.s("codes", "fp4_e2m1").i("group", 32); CHECK(refused("autoround", o)); }
{ Opts o; o.s("codes", "i4").s("block", "128x128"); CHECK(refused("autoround", o)); }
{ Opts o; o.s("codes", "i4").s("transform", "fwht128"); CHECK(refused("paroquant", o)); }
{ Opts o; o.s("codes", "i4").i("rot_group", 96); CHECK(refused("paroquant", o)); }
{ Opts o; o.s("codes", "i4").i("act_order", 1).s("transform", "fwht128"); CHECK(refused("gptq", o)); }
}
RAD_TEST_MAIN()
+194
View File
@@ -0,0 +1,194 @@
/* quant_fixture.h -- quantising a weight through a quantiser plugin exactly as rad-convert does.
*
* Shared by the tests that hold a quantiser's output to something: quant_test reads it back
* through the core's decoder, relayout_parity_test hands it to the kernel libraries' relayouts.
* Both have to quantise the way the converter will -- ask the encoding, size the planes, pass the
* rows over in the quantiser's own blocks -- or what they check is a path no container is made by.
*/
#pragma once
#include "rad_test.h"
#include "rad_plugin.h"
#include "rad_quant.h"
#include "format/encoding.h"
#include "plugin/registry.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace qfix {
inline std::string home() {
const char* h = std::getenv("RADIANCE_HOME");
return h ? h : "radiance_home";
}
inline rad::Registry& reg() {
static rad::Registry r;
static bool tried = false;
if (!tried) {
tried = true;
r.load_plugin(home() + "/quantizers/libquant.so", 0);
}
return r;
}
inline const RadQuantizerInfo* quantizer(const char* name) {
const rad::Registry::QuantRow* q = reg().quantizer(name);
return q ? q->info : nullptr;
}
#define NEED_LIBQUANT() \
do { \
if (!::qfix::quantizer("rtn")) { \
std::fprintf(stderr, " SKIP no libquant under %s\n", ::qfix::home().c_str()); \
return; \
} \
} while (0)
/* Parameters as a caller hands them over: text for strings, typed for the rest. The keys and
* strings are owned here and the RadParam pointers patched on every data(), so a copy is safe. */
struct Opts {
std::vector<std::string> keys, vals;
std::vector<RadParam> p;
Opts& s(const char* k, const char* v) {
keys.emplace_back(k);
vals.emplace_back(v);
p.push_back(RAD_STR(nullptr, nullptr));
return *this;
}
Opts& i(const char* k, long long v) {
keys.emplace_back(k);
vals.emplace_back("");
p.push_back(RAD_INT(nullptr, v));
return *this;
}
Opts& f(const char* k, double v) {
keys.emplace_back(k);
vals.emplace_back("");
p.push_back(RAD_F64(nullptr, v));
return *this;
}
const RadParam* data() {
for (size_t j = 0; j < p.size(); ++j) {
p[j].key = keys[j].c_str();
if (p[j].kind == RAD_P_STR) p[j].sval = vals[j].c_str();
}
return p.data();
}
int n() const { return (int)p.size(); }
};
/* A splitmix draw, normal-ish via the sum of four uniforms, with a few outliers. Integer state and
* one double product a value, so the same seed is the same weight on every machine. */
inline std::vector<float> draw(int64_t n, uint64_t seed, float outlier = 0.0f) {
std::vector<float> v((size_t)n);
uint64_t z = seed;
auto next = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return (double)((x ^ (x >> 31)) >> 11) / 9007199254740992.0;
};
for (int64_t i = 0; i < n; ++i) {
double s = 0;
for (int k = 0; k < 4; ++k) s += next() - 0.5;
v[(size_t)i] = (float)(s * 0.05);
if (outlier > 0 && next() < 0.002) v[(size_t)i] *= outlier;
}
return v;
}
struct Quantised {
RadEncoding enc{};
std::vector<std::vector<uint8_t>> planes;
int status = RAD_OK;
};
/* Quantise as rad-convert does: ask the encoding, size the planes, hand the rows over in the
* quantiser's own blocks. `importance` is the imatrix's column importances the converter would
* hand over, or null -- and null when the encoding is asked, as at declare. */
inline Quantised quantise(const RadQuantizerInfo* q, Opts& o, const char* name, int64_t rows,
int64_t cols, const std::vector<float>& w,
const float* importance = nullptr) {
Quantised out;
RadQuantWeight qw{};
qw.name = name;
qw.rank = 2;
qw.shape[0] = rows;
qw.shape[1] = cols;
qw.rows = rows;
qw.cols = cols;
qw.layer = qw.expert = -1;
out.status = q->encoding(o.data(), o.n(), &qw, &out.enc);
if (out.status != RAD_OK) return out;
qw.importance = importance;
for (int i = 0; i < out.enc.n_planes; ++i)
out.planes.emplace_back((size_t)rad_enc_plane_bytes(&out.enc.plane[i], rows, cols), 0);
int64_t rb = q->row_block(o.data(), o.n(), &qw);
if (rb <= 0) rb = rows;
for (int64_t r0 = 0; r0 < rows; r0 += rb) {
const int64_t n = r0 + rb < rows ? rb : rows - r0;
std::vector<float> blk(w.begin() + r0 * cols, w.begin() + (r0 + n) * cols);
std::vector<void*> pp;
for (int i = 0; i < out.enc.n_planes; ++i) {
const RadEncPlane& p = out.enc.plane[i];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, rows, cols, &pr, &pc);
const bool banded = p.kind == RAD_PLANE_TILED && p.block[0] > 0;
const int64_t prow = banded ? r0 / p.block[0] : 0;
pp.push_back(out.planes[(size_t)i].data() + prow * rad_enc_row_bytes(p.dtype, pc));
}
out.status = q->quantize(o.data(), o.n(), &qw, blk.data(), r0, n, pp.data());
if (out.status != RAD_OK) return out;
}
return out;
}
inline std::vector<float> decode(const Quantised& q, int64_t rows, int64_t cols) {
std::vector<const void*> d;
for (auto& p : q.planes) d.push_back(p.data());
rad::EncodedView v;
rad::enc_view(q.enc, rows, cols, d.data(), &v);
std::vector<float> out((size_t)(rows * cols));
std::string why;
if (rad::enc_decode_rows(v, 0, rows, out.data(), &why) != RAD_OK) {
std::fprintf(stderr, " decode: %s\n", why.c_str());
out.clear();
}
return out;
}
inline double rel_err(const std::vector<float>& a, const std::vector<float>& b) {
double num = 0, den = 0;
for (size_t i = 0; i < a.size(); ++i) {
num += (double)(a[i] - b[i]) * (a[i] - b[i]);
den += (double)a[i] * a[i];
}
return den > 0 ? std::sqrt(num / den) : 0;
}
/* A calibration file as the engine's tap writes one: "RADGRAM2", k, rank, rows, domain, a pad word,
* then k*k f32 row-major. `domain` 0 is the model's own input, N the input rotated by the width-N
* Hadamard. False if it could not be written. */
inline bool write_gram(const std::string& path, int64_t k, int64_t rows,
const std::vector<float>& h, uint32_t domain = 0) {
FILE* f = std::fopen(path.c_str(), "wb");
if (!f) return false;
char hdr[32] = { 'R', 'A', 'D', 'G', 'R', 'A', 'M', '2' };
const uint32_t kk = (uint32_t)k, rank = 0;
const uint64_t rr = (uint64_t)rows;
std::memcpy(hdr + 8, &kk, 4);
std::memcpy(hdr + 12, &rank, 4);
std::memcpy(hdr + 16, &rr, 8);
std::memcpy(hdr + 24, &domain, 4);
bool ok = std::fwrite(hdr, 1, 32, f) == 32;
ok = ok && std::fwrite(h.data(), 4, h.size(), f) == h.size();
return std::fclose(f) == 0 && ok;
}
} /* namespace qfix */
+396
View File
@@ -0,0 +1,396 @@
/* quant_ggml_test.cpp -- libquant's `ggml` quantiser through the plugin registry, read back
* through the core's decoder.
*
* WHAT IS PINNED AND WHY. The quantiser's claim is that its codes and scales are llama.cpp's own,
* at the commit vendor/UPSTREAM names (06938ac12, ggml-quants.c built as its ggml-base builds it):
* the same weights and imatrix through llama.cpp's quantize_<type> and through this port give
* identical GGUF blocks for all nineteen types, and llama.cpp's dequantize_row_<type> of those
* blocks equals enc_decode_rows of these planes value for value. llama.cpp's quantisers are not in
* this build, so the hashes in bit_exact_against_llama_cpp record those planes for this file's
* inputs, and an edit that moves a single code or scale away from llama.cpp's fails here. The
* error bounds carry margin; they catch a wrong plane layout, which decodes to noise, and the
* hashes catch the rest.
*/
#include "quant_fixture.h"
#include <cstdint>
using namespace rad;
using namespace qfix;
namespace {
struct Type {
const char* name;
const char* enc; /* the canonical spelling of its encoding */
bool needs_im; /* llama.cpp's search has no path without an imatrix */
int64_t block; /* values one GGUF block covers */
double bound; /* rel_err on every_type_decodes_within_its_bound's weight */
};
/* The bounds are 1.3x the larger of the plain and imatrix errors measured on that weight, whose
* 0.2% outliers at 10x widen every block they land in -- hence q4_0 at 0.11 rather than the 0.07
* a clean Gaussian gives it. */
const Type kTypes[] = {
{ "q4_0", "i4*f16[1x32]", false, 32, 0.141 },
{ "q4_1", "affine:codes=u4[1x1],scale=f16[1x32],min=f16[1x32]", false, 32, 0.110 },
{ "q5_0", "i5*f16[1x32]", false, 32, 0.073 },
{ "q5_1", "affine:codes=u5[1x1],scale=f16[1x32],min=f16[1x32]", false, 32, 0.053 },
{ "q8_0", "i8*f16[1x32]", false, 32, 0.0090 },
{ "q2_K", "affine:codes=u2[1x1],scale=u4[1x16],scale.1=f16[1x256],min=u4[1x16],"
"min.1=f16[1x256]", false, 256, 0.407 },
{ "q3_K", "i3*i6[1x16]*f16[1x256]", false, 256, 0.223 },
{ "q4_K", "affine:codes=u4[1x1],scale=u6[1x32],scale.1=f16[1x256],min=u6[1x32],"
"min.1=f16[1x256]", false, 256, 0.103 },
{ "q5_K", "affine:codes=u5[1x1],scale=u6[1x32],scale.1=f16[1x256],min=u6[1x32],"
"min.1=f16[1x256]", false, 256, 0.052 },
{ "q6_K", "i6*i8[1x16]*f16[1x256]", false, 256, 0.028 },
{ "iq4_nl", "affine:codes=u4[1x1],table=i8{1x16},scale=f16[1x32]", false, 32, 0.116 },
{ "iq4_xs", "affine:codes=u4[1x1],table=i8{1x16},scale=i6[1x32],scale.1=f16[1x256]", false,
256, 0.118 },
{ "iq2_xxs", "affine:codes=u8[1x8],grid=u8{256x8},signs=u1[1x1],scale=u5[1x32],"
"scale.1=f16[1x256],scale.2=f32[*x*]", true, 256, 0.560 },
{ "iq2_xs", "affine:codes=u9[1x8],grid=u8{512x8},signs=u1[1x1],scale=u5[1x16],"
"scale.1=f16[1x256],scale.2=f32[*x*]", true, 256, 0.467 },
{ "iq2_s", "affine:codes=u10[1x8],grid=u8{1024x8},signs=u1[1x1],scale=u5[1x16],"
"scale.1=f16[1x256],scale.2=f32[*x*]", false, 256, 0.425 },
{ "iq3_xxs", "affine:codes=u8[1x4],grid=u8{256x4},signs=u1[1x1],scale=u5[1x32],"
"scale.1=f16[1x256],scale.2=f32[*x*]", false, 256, 0.318 },
{ "iq3_s", "affine:codes=u9[1x4],grid=u8{512x4},signs=u1[1x1],scale=u5[1x32],"
"scale.1=f16[1x256]", false, 256, 0.242 },
{ "iq1_s", "affine:codes=u11[1x8],grid=i8{2048x8},scale=u4[1x32],scale.1=f16[1x256],"
"zero=bf16[1x32]", true, 256, 0.737 },
{ "iq1_m", "affine:codes=u11[1x8],grid=i8{2048x8},scale=u4[1x16],scale.1=f16[1x256],"
"zero=bf16[1x8]", false, 256, 0.765 },
};
RadQuantWeight weight_of(const char* name, int64_t rows, int64_t cols, const float* imp) {
RadQuantWeight qw{};
qw.name = name;
qw.rank = 2;
qw.shape[0] = rows;
qw.shape[1] = cols;
qw.rows = rows;
qw.cols = cols;
qw.layer = qw.expert = -1;
qw.importance = imp;
return qw;
}
/* quant_fixture.h's quantise, with the imatrix's importances handed over as rad-convert hands
* them -- to quantize, never to encoding -- and `blk` rows a call (0: the quantiser's own
* row_block, which for `ggml` is one row). */
Quantised quantise_ggml(const char* type, int64_t rows, int64_t cols, const std::vector<float>& w,
const float* imp, int64_t blk = 0) {
Quantised out;
const RadQuantizerInfo* q = quantizer("ggml");
Opts o;
o.s("type", type);
const RadQuantWeight declared = weight_of("blk.0.ffn_down.weight", rows, cols, nullptr);
const RadQuantWeight qw = weight_of("blk.0.ffn_down.weight", rows, cols, imp);
out.status = q->encoding(o.data(), o.n(), &declared, &out.enc);
if (out.status != RAD_OK) return out;
for (int i = 0; i < out.enc.n_planes; ++i)
out.planes.emplace_back((size_t)rad_enc_plane_bytes(&out.enc.plane[i], rows, cols), 0);
if (blk <= 0) blk = q->row_block(o.data(), o.n(), &qw);
if (blk <= 0) blk = rows;
for (int64_t r0 = 0; r0 < rows; r0 += blk) {
const int64_t n = r0 + blk < rows ? blk : rows - r0;
std::vector<float> part(w.begin() + r0 * cols, w.begin() + (r0 + n) * cols);
std::vector<void*> pp;
for (int i = 0; i < out.enc.n_planes; ++i) {
const RadEncPlane& p = out.enc.plane[i];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, rows, cols, &pr, &pc);
const bool banded = p.kind == RAD_PLANE_TILED && p.block[0] > 0;
pp.push_back(out.planes[(size_t)i].data() +
(banded ? r0 / p.block[0] : 0) * rad_enc_row_bytes(p.dtype, pc));
}
out.status = q->quantize(o.data(), o.n(), &qw, part.data(), r0, n, pp.data());
if (out.status != RAD_OK) return out;
}
return out;
}
/* A column importance as an imatrix holds one: positive, and uneven enough to steer a search. */
std::vector<float> importance(int64_t cols, uint64_t seed) {
const std::vector<float> d = draw(cols, seed);
std::vector<float> imp((size_t)cols);
for (int64_t c = 0; c < cols; ++c) imp[(size_t)c] = 0.05f + 40.0f * std::fabs(d[(size_t)c]);
return imp;
}
uint64_t fnv1a(const Quantised& q) {
uint64_t h = 0xcbf29ce484222325ull;
for (const auto& p : q.planes)
for (uint8_t b : p) {
h ^= b;
h *= 0x100000001b3ull;
}
return h;
}
/* The relative error under the imatrix's weighting: what a search given the imatrix minimises. */
double weighted_err(const std::vector<float>& w, const std::vector<float>& d,
const std::vector<float>& imp, int64_t cols) {
double num = 0, den = 0;
for (size_t i = 0; i < w.size(); ++i) {
const double wi = imp[i % (size_t)cols], e = (double)w[i] - d[i];
num += wi * e * e;
den += wi * (double)w[i] * w[i];
}
return std::sqrt(num / den);
}
int encoding_status(const char* type, int64_t rows, int64_t cols, uint32_t rank = 2) {
const RadQuantizerInfo* q = quantizer("ggml");
Opts o;
if (type) o.s("type", type);
RadQuantWeight qw = weight_of("blk.0.attn_q.weight", rows, cols, nullptr);
if (rank == 1) {
qw.rank = 1;
qw.shape[0] = cols;
}
RadEncoding e;
return q->encoding(o.data(), o.n(), &qw, &e);
}
} /* namespace */
TEST(ggml_writes_each_type_as_its_affine_planes) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("ggml");
REQUIRE(q != nullptr);
for (const Type& t : kTypes) {
Opts o;
o.s("type", t.name);
const RadQuantWeight qw = weight_of("w", 4, 512, nullptr);
RadEncoding e;
REQUIRE_EQ(q->encoding(o.data(), o.n(), &qw, &e), RAD_OK);
CHECK(rad_enc_valid(&e));
CHECK_EQ(enc_name(e), std::string(t.enc));
CHECK_EQ(q->row_block(o.data(), o.n(), &qw), (int64_t)1);
}
}
TEST(every_type_decodes_within_its_bound) {
NEED_LIBQUANT();
const int64_t R = 32, C = 1024;
const std::vector<float> w = draw(R * C, 11, 10.0f);
const std::vector<float> imp = importance(C, 12);
for (const Type& t : kTypes) {
double e[2] = { 0, 0 };
for (int m = 0; m < 2; ++m) {
if (m == 0 && t.needs_im) continue;
Quantised qz = quantise_ggml(t.name, R, C, w, m ? imp.data() : nullptr, 8);
REQUIRE_EQ(qz.status, RAD_OK);
const std::vector<float> d = decode(qz, R, C);
REQUIRE(!d.empty());
e[m] = rel_err(w, d);
CHECK(e[m] < t.bound);
}
std::fprintf(stderr, " %-8s rel_err plain %.4f, imatrix %.4f\n", t.name, e[0], e[1]);
}
}
TEST(the_imatrix_reaches_the_search) {
NEED_LIBQUANT();
/* With the importances the search minimises the importance-weighted error, and every type
* that has such a search gets measurably lower there (by 2.5-25% on this weight). q8_0 has
* none -- llama.cpp rounds it to nearest either way -- and must not move at all. */
const int64_t R = 32, C = 1024;
const std::vector<float> w = draw(R * C, 11, 10.0f);
const std::vector<float> imp = importance(C, 12);
for (const Type& t : kTypes) {
if (t.needs_im) continue;
Quantised a = quantise_ggml(t.name, R, C, w, nullptr, 8);
Quantised b = quantise_ggml(t.name, R, C, w, imp.data(), 8);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(b.status, RAD_OK);
if (!std::strcmp(t.name, "q8_0")) {
CHECK(a.planes == b.planes);
continue;
}
const double ea = weighted_err(w, decode(a, R, C), imp, C);
const double eb = weighted_err(w, decode(b, R, C), imp, C);
CHECK(eb < 0.99 * ea);
}
}
TEST(q8_0_is_round_to_nearest_against_amax_over_127) {
NEED_LIBQUANT();
/* One format restated from its definition rather than from the port: without an imatrix
* llama.cpp's q8_0 is d = amax/127, a code roundf(x * (1/d)), and d stored as f16. */
const int64_t R = 4, C = 256;
const std::vector<float> w = draw(R * C, 21, 6.0f);
Quantised q = quantise_ggml("q8_0", R, C, w, nullptr);
REQUIRE_EQ(q.status, RAD_OK);
int off = 0;
for (int64_t r = 0; r < R; ++r)
for (int64_t b = 0; b < C / 32; ++b) {
float amax = 0;
const float* x = w.data() + r * C + 32 * b;
for (int64_t j = 0; j < 32; ++j) amax = std::fmax(amax, std::fabs(x[j]));
const float d = amax / 127, id = d ? 1.0f / d : 0.0f;
uint16_t s;
std::memcpy(&s, q.planes[1].data() + 2 * (r * (C / 32) + b), 2);
off += s != rad_f32_to_f16(d);
for (int64_t j = 0; j < 32; ++j) {
const int8_t code = (int8_t)q.planes[0][(size_t)(r * C + 32 * b + j)];
off += code != (int8_t)std::roundf(x[j] * id);
}
}
CHECK_EQ(off, 0);
}
TEST(quantisation_is_deterministic_and_rows_are_independent) {
NEED_LIBQUANT();
/* A row's planes do not depend on which call carried it, nor on the thread that ran it. */
const int64_t R = 12, C = 768;
const std::vector<float> w = draw(R * C, 31, 10.0f);
const std::vector<float> imp = importance(C, 32);
for (const char* t : { "q4_K", "q5_1", "iq4_xs", "iq2_xxs", "iq3_s", "iq1_m" }) {
Quantised one = quantise_ggml(t, R, C, w, imp.data(), 1);
Quantised odd = quantise_ggml(t, R, C, w, imp.data(), 5);
Quantised all = quantise_ggml(t, R, C, w, imp.data(), R);
Quantised again = quantise_ggml(t, R, C, w, imp.data(), R);
REQUIRE_EQ(one.status, RAD_OK);
CHECK(one.planes == odd.planes);
CHECK(one.planes == all.planes);
CHECK(all.planes == again.planes);
}
}
TEST(bit_exact_against_llama_cpp) {
NEED_LIBQUANT();
/* FNV-1a of every plane's bytes, in plane order, for the [8 x 512] weight below without (0)
* and with (1) the importances below -- each confirmed equal to llama.cpp's own blocks and
* dequantisation (see the head of this file). */
struct Pin { const char* type; int imatrix; uint64_t fnv; };
const Pin kPins[] = {
{ "q4_0", 0, 0xafebf0225eb23c08ull }, { "q4_0", 1, 0x249e07415953dc83ull },
{ "q4_1", 0, 0x249f8507ccb28e84ull }, { "q4_1", 1, 0x861511021f1487d2ull },
{ "q5_0", 0, 0x68804fa0a750a161ull }, { "q5_0", 1, 0xe6de81cdcfa44e86ull },
{ "q5_1", 0, 0x2d8c51fe36496843ull }, { "q5_1", 1, 0xbd0ad8622f10a79eull },
{ "q8_0", 0, 0xe7fcb3f3b4ac3c32ull }, { "q8_0", 1, 0xe7fcb3f3b4ac3c32ull },
{ "q2_K", 0, 0x4126a37ae0eee6b7ull }, { "q2_K", 1, 0x6787af0669a459deull },
{ "q3_K", 0, 0xeda92060a51bdbd8ull }, { "q3_K", 1, 0x6bfc5154fab3c858ull },
{ "q4_K", 0, 0x1d7b53e854a01425ull }, { "q4_K", 1, 0x162638ae5f75f636ull },
{ "q5_K", 0, 0xd3ad81aef94faccdull }, { "q5_K", 1, 0x35ede462bc992c26ull },
{ "q6_K", 0, 0x27555bd1e0400234ull }, { "q6_K", 1, 0xa66725529adadf63ull },
{ "iq4_nl", 0, 0x9a5857bd0a27cf6eull }, { "iq4_nl", 1, 0xeda63216d5ce2c6bull },
{ "iq4_xs", 0, 0xe563a372ddd7506full }, { "iq4_xs", 1, 0x9b31075d3303262bull },
{ "iq2_xxs", 1, 0xd86fa2fa5fd2ecb3ull }, { "iq2_xs", 1, 0x5dcb565c62932519ull },
{ "iq2_s", 0, 0x892bc05ac8bbf27bull }, { "iq2_s", 1, 0x3a60de31653861e1ull },
{ "iq3_xxs", 0, 0xb7bb19b90de20079ull }, { "iq3_xxs", 1, 0xc0f103a573450456ull },
{ "iq3_s", 0, 0x7feeb3c566708bebull }, { "iq3_s", 1, 0xae2be8d72969b54aull },
{ "iq1_s", 1, 0xd527fc0b9d1bbb0aull },
{ "iq1_m", 0, 0xba4b5b012fb32412ull }, { "iq1_m", 1, 0x691e880c1d50e84dull },
};
const int64_t R = 8, C = 512;
const std::vector<float> w = draw(R * C, 0x6a6, 8.0f);
const std::vector<float> imp = importance(C, 0x1b1);
for (const Pin& p : kPins) {
Quantised q = quantise_ggml(p.type, R, C, w, p.imatrix ? imp.data() : nullptr);
REQUIRE_EQ(q.status, RAD_OK);
const uint64_t h = fnv1a(q);
if (h != p.fnv)
std::fprintf(stderr, " %s imatrix=%d: fnv 0x%016llx, pinned 0x%016llx\n", p.type,
p.imatrix, (unsigned long long)h, (unsigned long long)p.fnv);
CHECK(h == p.fnv);
}
}
TEST(the_shared_planes_hold_llama_cpps_tables) {
NEED_LIBQUANT();
const int64_t R = 2, C = 256;
const std::vector<float> w = draw(R * C, 41);
const std::vector<float> imp = importance(C, 42);
/* kvalues_iq4nl */
Quantised nl = quantise_ggml("iq4_nl", R, C, w, nullptr);
REQUIRE_EQ(nl.status, RAD_OK);
const int8_t kv[16] = { -127, -104, -83, -65, -49, -35, -22, -10,
1, 13, 25, 38, 53, 69, 89, 113 };
REQUIRE_EQ(nl.planes[1].size(), (size_t)16);
CHECK(std::memcmp(nl.planes[1].data(), kv, 16) == 0);
/* iq2xxs_grid[0] and [255], iq3xxs_grid[1], iq1s_grid[0] and [2047], and the per-tensor 1/8
* and 1/4 */
Quantised x2 = quantise_ggml("iq2_xxs", R, C, w, imp.data());
Quantised x3 = quantise_ggml("iq3_xxs", R, C, w, nullptr);
Quantised s1 = quantise_ggml("iq1_s", R, C, w, imp.data());
REQUIRE_EQ(x2.status, RAD_OK);
REQUIRE_EQ(x3.status, RAD_OK);
REQUIRE_EQ(s1.status, RAD_OK);
const uint8_t g2_0[8] = { 8, 8, 8, 8, 8, 8, 8, 8 };
const uint8_t g2_255[8] = { 8, 25, 8, 8, 25, 43, 43, 43 };
CHECK(std::memcmp(x2.planes[1].data(), g2_0, 8) == 0);
CHECK(std::memcmp(x2.planes[1].data() + 255 * 8, g2_255, 8) == 0);
const uint8_t g3_1[4] = { 20, 4, 4, 4 };
CHECK(std::memcmp(x3.planes[1].data() + 4, g3_1, 4) == 0);
const int8_t g1_0[8] = { -1, -1, -1, -1, -1, -1, -1, -1 };
const int8_t g1_last[8] = { 1, 1, 1, 1, 1, 1, 1, 1 };
CHECK(std::memcmp(s1.planes[1].data(), g1_0, 8) == 0);
CHECK(std::memcmp(s1.planes[1].data() + 2047 * 8, g1_last, 8) == 0);
float k2, k3;
std::memcpy(&k2, x2.planes[5].data(), 4);
std::memcpy(&k3, x3.planes[5].data(), 4);
CHECK_EQ(k2, 0.125f);
CHECK_EQ(k3, 0.25f);
}
TEST(a_weight_the_type_cannot_tile_is_declined) {
NEED_LIBQUANT();
CHECK_EQ(encoding_status("q4_0", 4, 96), RAD_OK);
CHECK_EQ(encoding_status("q4_0", 4, 100), RAD_E_UNSUPPORTED);
CHECK_EQ(encoding_status("q4_K", 4, 512), RAD_OK);
CHECK_EQ(encoding_status("q4_K", 4, 512 + 32), RAD_E_UNSUPPORTED);
CHECK_EQ(encoding_status("iq4_nl", 4, 2880), RAD_OK);
CHECK_EQ(encoding_status("iq4_xs", 4, 2880), RAD_E_UNSUPPORTED);
/* a vector is declined, not an error */
CHECK_EQ(encoding_status("q8_0", 1, 256, 1), RAD_E_UNSUPPORTED);
}
TEST(a_type_is_named_in_any_case_and_an_unknown_one_is_an_error) {
NEED_LIBQUANT();
CHECK_EQ(encoding_status("Q4_K", 4, 256), RAD_OK);
CHECK_EQ(encoding_status("IQ2_XXS", 4, 256), RAD_OK);
CHECK_EQ(encoding_status("q4_9", 4, 256), RAD_E_INVAL);
CHECK_EQ(encoding_status("q4", 4, 256), RAD_E_INVAL);
CHECK_EQ(encoding_status(nullptr, 4, 256), RAD_E_INVAL);
const int64_t R = 3, C = 256;
const std::vector<float> w = draw(R * C, 51);
Quantised a = quantise_ggml("q4_K", R, C, w, nullptr);
Quantised b = quantise_ggml("Q4_k", R, C, w, nullptr);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(b.status, RAD_OK);
CHECK(rad_enc_equal(&a.enc, &b.enc));
CHECK(a.planes == b.planes);
}
TEST(the_imatrix_types_refuse_to_run_without_one) {
NEED_LIBQUANT();
const int64_t R = 2, C = 256;
const std::vector<float> w = draw(R * C, 61);
for (const Type& t : kTypes) {
/* the encoding is asked at declare, where there is never an imatrix, so it answers */
CHECK_EQ(encoding_status(t.name, R, C), RAD_OK);
Quantised q = quantise_ggml(t.name, R, C, w, nullptr);
CHECK_EQ(q.status, t.needs_im ? RAD_E_INVAL : RAD_OK);
}
}
TEST(quantize_refuses_rows_outside_the_weight) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("ggml");
Opts o;
o.s("type", "q8_0");
const RadQuantWeight qw = weight_of("w", 4, 64, nullptr);
std::vector<float> src(5 * 64, 0.5f);
std::vector<uint8_t> codes(5 * 64), scale(5 * 2 * 2);
void* pp[2] = { codes.data(), scale.data() };
CHECK_EQ(q->quantize(o.data(), o.n(), &qw, src.data(), 2, 3, pp), RAD_E_SHAPE);
CHECK_EQ(q->quantize(o.data(), o.n(), &qw, src.data(), -1, 1, pp), RAD_E_SHAPE);
CHECK_EQ(q->quantize(o.data(), o.n(), &qw, src.data(), 0, 4, pp), RAD_OK);
}
RAD_TEST_MAIN()
+604
View File
@@ -0,0 +1,604 @@
/* quant_test.cpp -- libquant through the plugin registry, read back through the core's decoder.
*
* Every case quantises through the quantiser's own hooks, exactly as rad-convert will, and checks
* the result through enc_decode_rows rather than through anything libquant says about itself: the
* point of an encoding is that a reader who never saw the quantiser recovers the weight. Where a
* rule is exact -- a block scale that is the bf16 of amax/448, an MX exponent that is a power of
* two, a fixed scale -- the exact value is checked; where it is approximate, the error is bounded
* by the grid's own step, which a wrong block, a wrong zero or a missing rotation all exceed.
*/
#include "quant_fixture.h"
#include <sys/stat.h>
#include <unistd.h>
using namespace rad;
using namespace qfix;
TEST(libquant_offers_its_quantisers_through_the_registry) {
NEED_LIBQUANT();
CHECK(quantizer("rtn") != nullptr);
CHECK(quantizer("gptq") != nullptr);
CHECK(quantizer("no-such-quantiser") == nullptr);
/* a second copy of the same plugin is refused, not merged */
Registry r2;
CHECK_EQ(r2.load_plugin(home() + "/quantizers/libquant.so", 0), RAD_OK);
CHECK(r2.load_plugin(home() + "/quantizers/libquant.so", 1) < 0);
}
TEST(block_fp8_is_the_bf16_of_amax_over_448_and_codes_against_it) {
NEED_LIBQUANT();
const int64_t R = 256, C = 384;
const std::vector<float> w = draw(R * C, 1, 20.0f);
Opts o;
o.s("codes", "fp8_e4m3").s("block", "128x128").s("scale", "bf16");
Quantised q = quantise(quantizer("rtn"), o, "blk.0.attn_q.weight", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("fp8_e4m3*bf16[128x128]"));
REQUIRE_EQ(q.planes[1].size(), (size_t)(2 * 3 * 2));
/* block (1, 2) */
float amax = 0;
for (int64_t r = 128; r < 256; ++r)
for (int64_t c = 256; c < 384; ++c)
amax = std::fmax(amax, std::fabs(w[(size_t)(r * C + c)]));
const uint16_t want = rad_f32_to_bf16(amax * (1.0f / 448.0f));
uint16_t got;
std::memcpy(&got, q.planes[1].data() + (1 * 3 + 2) * 2, 2);
CHECK_EQ((int)got, (int)want);
const std::vector<float> d = decode(q, R, C);
REQUIRE(!d.empty());
CHECK(rel_err(w, d) < 0.04);
}
TEST(a_rotated_int4_group_decodes_back_through_the_hadamard) {
NEED_LIBQUANT();
const int64_t R = 32, C = 512;
const std::vector<float> w = draw(R * C, 2, 30.0f);
Opts plain, rot;
plain.s("codes", "i4").i("group", 128).s("scale", "bf16");
rot.s("codes", "i4").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("i4*bf16[1x128]/fwht128"));
const double ea = rel_err(w, decode(a, R, C)), eb = rel_err(w, decode(b, R, C));
std::fprintf(stderr, " int4 g128: plain %.4f, rotated %.4f\n", ea, eb);
/* Both are a 4-bit grid's error, and the rotated one is decoded THROUGH the rotation, so a
* reader that forgot it would see noise, ~1.0. On weights with outliers the rotation is also
* the better grid: it spreads one large value over the group instead of letting it set the
* scale every other value is rounded against. */
CHECK(ea < 0.35);
CHECK(eb < 0.15);
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 stores
* them; and against -8..7 at the same bytes, under the same rotation and scale search, they
* are the better grid for the near-normal weight they were fitted to. Not with outliers: the
* rotation turns one outlier into a +-o pattern across its whole group, which is bimodal. */
const int64_t R = 32, C = 512;
const std::vector<float> w = draw(R * C, 2);
Opts i4, nl;
i4.s("codes", "i4").i("group", 128).s("scale", "bf16").s("transform", "fwht128")
.s("rule", "search");
nl.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128")
.s("rule", "search");
Quantised a = quantise(quantizer("rtn"), i4, "x", R, C, w);
Quantised b = quantise(quantizer("rtn"), nl, "x", R, C, w);
REQUIRE_EQ(a.status, RAD_OK);
REQUIRE_EQ(b.status, RAD_OK);
CHECK_EQ(enc_name(b.enc),
std::string("affine:codes=u4[1x1],scale=bf16[1x128],table=f32{1x16}/fwht128"));
const int t = rad_enc_find(&b.enc, "table");
REQUIRE(t >= 0);
const float want[16] = { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f,
-1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f };
float got[16];
std::memcpy(got, b.planes[(size_t)t].data(), sizeof got);
for (int i = 0; i < 16; ++i) {
CHECK_EQ(got[i], want[i]);
CHECK_EQ(rad_fp8e4m3_to_f32(rad_f32_to_fp8e4m3(want[i])), want[i]);
}
const double ea = rel_err(w, decode(a, R, C)), eb = rel_err(w, decode(b, R, C));
std::fprintf(stderr, " rotated g128, searched scale: -8..7 %.4f, w4nl %.4f\n", ea, eb);
CHECK(eb < ea * 0.95);
}
TEST(an_asymmetric_two_bit_grid_keeps_its_zero_in_range) {
NEED_LIBQUANT();
const int64_t R = 16, C = 256;
const std::vector<float> w = draw(R * C, 3);
Opts o;
o.s("codes", "u2").i("group", 128).s("scale", "f16").s("zero", "u8");
Quantised q = quantise(quantizer("rtn"), o, "head", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("u2*f16[1x128]-u8[1x128]"));
int bad = 0;
for (uint8_t z : q.planes[2]) bad += z > 3;
CHECK_EQ(bad, 0);
CHECK(rel_err(w, decode(q, R, C)) < 0.6);
}
TEST(mxfp4_shares_a_power_of_two_a_32) {
NEED_LIBQUANT();
const int64_t R = 8, C = 256;
const std::vector<float> w = draw(R * C, 4, 10.0f);
Opts o;
o.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0");
Quantised q = quantise(quantizer("rtn"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("fp4_e2m1*e8m0[1x32]"));
/* the OCP rule: floor(log2 amax) - 2, so amax / 2^e lands in [4, 8) */
for (int64_t r = 0; r < R; ++r)
for (int64_t g = 0; g < C / 32; ++g) {
float amax = 0;
for (int64_t c = g * 32; c < g * 32 + 32; ++c)
amax = std::fmax(amax, std::fabs(w[(size_t)(r * C + c)]));
const float s = rad_e8m0_to_f32(q.planes[1][(size_t)(r * (C / 32) + g)]);
CHECK(amax / s >= 4.0f && amax / s < 8.0f);
}
CHECK(rel_err(w, decode(q, R, C)) < 0.2);
}
TEST(a_fixed_per_tensor_scale_streams_a_row_at_a_time) {
NEED_LIBQUANT();
const int64_t R = 64, C = 160;
const std::vector<float> w = draw(R * C, 5);
Opts o;
o.s("codes", "fp8_e4m3").s("block", "*x*").s("scale", "bf16").s("rule", "fixed")
.f("scale_value", 1.99317932128906e-4);
const RadQuantizerInfo* q = quantizer("rtn");
RadQuantWeight qw{};
qw.name = "t";
qw.rank = 2; qw.shape[0] = R; qw.shape[1] = C; qw.rows = R; qw.cols = C;
CHECK_EQ(q->row_block(o.data(), o.n(), &qw), 1);
Quantised a = quantise(q, o, "t", R, C, w);
REQUIRE_EQ(a.status, RAD_OK);
CHECK_EQ(enc_name(a.enc), std::string("fp8_e4m3*bf16[*x*]"));
uint16_t s;
std::memcpy(&s, a.planes[1].data(), 2);
CHECK_EQ((int)s, 0x3951);
/* the rule's reciprocal is the unrounded value's, in double */
const double inv = 1.0 / 1.99317932128906e-4;
int off = 0;
for (int64_t i = 0; i < R * C; ++i)
off += a.planes[0][(size_t)i] != rad_f32_to_fp8e4m3((float)((double)w[(size_t)i] * inv));
CHECK_EQ(off, 0);
}
TEST(gptq_without_a_hessian_is_round_to_nearest_byte_for_byte) {
NEED_LIBQUANT();
const int64_t R = 64, C = 256;
const std::vector<float> w = draw(R * C, 6, 20.0f);
Opts a, b;
a.s("codes", "i4").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
b.s("codes", "i4").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
Quantised r = quantise(quantizer("rtn"), a, "blk.0.ffn_down_exps.0.weight", R, C, w);
Quantised g = quantise(quantizer("gptq"), b, "blk.0.ffn_down_exps.0.weight", R, C, w);
REQUIRE_EQ(r.status, RAD_OK);
REQUIRE_EQ(g.status, RAD_OK);
for (int i = 0; i < r.enc.n_planes; ++i) CHECK(r.planes[(size_t)i] == g.planes[(size_t)i]);
}
TEST(gptq_with_a_hessian_lowers_the_output_error) {
NEED_LIBQUANT();
/* Correlated activations: x = A z, so H = sum x x^T is far from diagonal and error feedback
* has something to exploit that rounding each column alone cannot. */
const int64_t R = 48, C = 128, T = 2048;
const std::vector<float> w = draw(R * C, 7, 10.0f);
const std::vector<float> z = draw(T * C, 8);
const std::vector<float> mix = draw(C * C, 9);
std::vector<float> x((size_t)(T * C), 0.0f);
for (int64_t t = 0; t < T; ++t)
for (int64_t i = 0; i < C; ++i) {
double s = z[(size_t)(t * C + i)] * 4.0;
for (int64_t j = 0; j < 8; ++j)
s += mix[(size_t)(i * C + j)] * z[(size_t)(t * C + j)] * 40.0;
x[(size_t)(t * C + i)] = (float)s;
}
std::vector<float> h((size_t)(C * C), 0.0f);
for (int64_t t = 0; t < T; ++t)
for (int64_t i = 0; i < C; ++i)
for (int64_t j = 0; j < C; ++j)
h[(size_t)(i * C + j)] += x[(size_t)(t * C + i)] * x[(size_t)(t * C + j)];
char dir[] = "/tmp/rad_quant_test_XXXXXX";
REQUIRE(mkdtemp(dir) != nullptr);
const std::string path = std::string(dir) + "/gram.r0.blk.3.ffn_down_exps.bin";
REQUIRE(write_gram(path, C, T, h));
Opts a, b;
a.s("codes", "i4").i("group", 32).s("scale", "f32");
b.s("codes", "i4").i("group", 32).s("scale", "f32").s("calib", dir);
Quantised r = quantise(quantizer("rtn"), a, "blk.3.ffn_down_exps.17.weight", R, C, w);
Quantised g = quantise(quantizer("gptq"), b, "blk.3.ffn_down_exps.17.weight", R, C, w);
REQUIRE_EQ(r.status, RAD_OK);
REQUIRE_EQ(g.status, RAD_OK);
const std::vector<float> dr = decode(r, R, C), dg = decode(g, R, C);
auto out_err = [&](const std::vector<float>& d) {
double e = 0, n = 0;
for (int64_t t = 0; t < T; t += 4)
for (int64_t o = 0; o < R; ++o) {
double a1 = 0, a2 = 0;
for (int64_t i = 0; i < C; ++i) {
a1 += (double)w[(size_t)(o * C + i)] * x[(size_t)(t * C + i)];
a2 += (double)d[(size_t)(o * C + i)] * x[(size_t)(t * C + i)];
}
e += (a1 - a2) * (a1 - a2);
n += a1 * a1;
}
return std::sqrt(e / n);
};
const double er = out_err(dr), eg = out_err(dg);
std::fprintf(stderr, " output error: rtn %.4f, gptq %.4f\n", er, eg);
CHECK(eg < er * 0.9);
/* COORDINATE DESCENT AFTER IT never raises the form it descends, which on the corpus the
* Gram came from is the output error, and on a correlated Hessian it finds codes to move. */
Opts c;
c.s("codes", "i4").i("group", 32).s("scale", "f32").s("calib", dir).i("cd", 3);
Quantised gc = quantise(quantizer("gptq"), c, "blk.3.ffn_down_exps.17.weight", R, C, w);
REQUIRE_EQ(gc.status, RAD_OK);
const double ec = out_err(decode(gc, R, C));
std::fprintf(stderr, " output error: gptq + cd=3 %.4f\n", ec);
CHECK(ec < eg);
/* The scales are GPTQ's, untouched: only codes move. */
CHECK(gc.planes[1] == g.planes[1]);
std::remove(path.c_str());
rmdir(dir);
}
TEST(w4nl_at_64_with_e4m3_scales_under_a_row_scale_beats_128_with_bf16_at_the_same_bytes) {
NEED_LIBQUANT();
/* The rotated expert grid two ways at the same bytes a row: a bf16 scale a 128 columns, or an
* E4M3 one a 64 under a bf16 scale a row (whose bytes are a row's, not a group's). The second
* searches its sub-scales as they are stored -- rounded to E4M3 relative to the row's -- so
* its rounding does not give back what the finer groups won. Rows whose magnitude varies
* along K, so a 64-column group is worth having. */
const int64_t R = 64, C = 1024;
std::vector<float> w = draw(R * C, 21, 1.0f);
for (int64_t r = 0; r < R; ++r)
for (int64_t c = 0; c < C; ++c)
w[(size_t)(r * C + c)] *= 1.0f + 3.0f * (float)((c / 64 + r) % 5) / 4.0f;
Opts a, b;
a.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128")
.s("rule", "search");
b.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "bf16")
.s("block2", "1x*").s("transform", "fwht128").s("rule", "search");
Quantised qa = quantise(quantizer("rtn"), a, "blk.0.ffn_gate_up_exps.0.weight", R, C, w);
Quantised qb = quantise(quantizer("rtn"), b, "blk.0.ffn_gate_up_exps.0.weight", R, C, w);
REQUIRE_EQ(qa.status, RAD_OK);
REQUIRE_EQ(qb.status, RAD_OK);
std::fprintf(stderr, " %s\n %s\n", enc_name(qa.enc).c_str(), enc_name(qb.enc).c_str());
size_t ba = 0, bb = 0;
for (const auto& p : qa.planes) ba += p.size();
for (const auto& p : qb.planes) bb += p.size();
const double ea = rel_err(w, decode(qa, R, C)), eb = rel_err(w, decode(qb, R, C));
std::fprintf(stderr, " g128 bf16: %.4f (%zu bytes) g64 e4m3 + row bf16: %.4f (%zu bytes)\n",
ea, ba, eb, bb);
CHECK(eb < ea * 0.97);
CHECK(bb <= ba + (size_t)R * 2 + 64);
/* THE SAME GRID WITH THE SECOND LEVEL FIXED, one f32 for the tensor: the E4M3 sub-scales
* carry every row's magnitude themselves, which they can because this weight's scales sit well
* inside E4M3's range -- and the error is the per-row form's, at a row's two bytes fewer. */
Opts c;
c.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128").s("rule", "search");
Quantised qc = quantise(quantizer("rtn"), c, "blk.0.ffn_gate_up_exps.0.weight", R, C, w);
REQUIRE_EQ(qc.status, RAD_OK);
std::fprintf(stderr, " %s\n", enc_name(qc.enc).c_str());
float s2 = 0.0f;
std::memcpy(&s2, qc.planes[2].data(), 4);
CHECK_EQ(s2, 0x1p-13f);
const double ec = rel_err(w, decode(qc, R, C));
std::fprintf(stderr, " g64 e4m3 under a fixed 2^-13: %.4f\n", ec);
CHECK(ec < ea * 0.97);
CHECK(std::fabs(ec - eb) < 0.002);
/* A value the second level's dtype cannot hold exactly is refused. */
Opts d;
d.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "bf16")
.s("block2", "*x*").f("scale2_value", 0.1).s("transform", "fwht128");
CHECK(quantise(quantizer("rtn"), d, "x", R, C, w).status != RAD_OK);
}
TEST(gptq_cd_and_act_order_are_refused_together) {
NEED_LIBQUANT();
const int64_t R = 16, C = 128;
const std::vector<float> w = draw(R * C, 12, 4.0f);
Opts o;
o.s("codes", "i4").i("group", 32).s("scale", "f32").i("act_order", 1).i("cd", 2);
Quantised q = quantise(quantizer("gptq"), o, "blk.0.ffn_down_exps.0.weight", R, C, w);
CHECK(q.status != RAD_OK);
}
TEST(a_codebook_indexes_its_table_and_the_scale_multiplies_it) {
NEED_LIBQUANT();
const int64_t R = 32, C = 256;
const std::vector<float> w = draw(R * C, 11, 8.0f);
/* NF4: sixteen f32 quantiles, a u4 code each, the extremes at +-1 so the scale is absmax */
{
Opts o;
o.s("table", "nf4").i("group", 64).s("scale", "bf16");
Quantised q = quantise(quantizer("rtn"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc),
std::string("affine:codes=u4[1x1],scale=bf16[1x64],table=f32{1x16}"));
float t[16];
std::memcpy(t, q.planes[2].data(), sizeof t);
CHECK_EQ(t[0], -1.0f);
CHECK_EQ(t[7], 0.0f);
CHECK_EQ(t[15], 1.0f);
const double e = rel_err(w, decode(q, R, C));
std::fprintf(stderr, " nf4 g64: %.4f\n", e);
CHECK(e < 0.15);
}
/* IQ4_NL's values: unequal ends, so a block's scale takes its largest value's sign and that
* value lands on -127 exactly (to the bf16 of the scale) */
{
Opts o;
o.s("table", "iq4nl").i("group", 32).s("scale", "f32");
Quantised q = quantise(quantizer("rtn"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
const std::vector<float> d = decode(q, R, C);
REQUIRE(!d.empty());
int off = 0;
for (int64_t r = 0; r < R; ++r)
for (int64_t g = 0; g < C / 32; ++g) {
int64_t at = g * 32;
for (int64_t c = g * 32; c < g * 32 + 32; ++c)
if (std::fabs(w[(size_t)(r * C + c)]) > std::fabs(w[(size_t)(r * C + at)]))
at = c;
off += std::fabs(d[(size_t)(r * C + at)] - w[(size_t)(r * C + at)]) >
1e-6f * std::fabs(w[(size_t)(r * C + at)]);
}
CHECK_EQ(off, 0);
CHECK(rel_err(w, d) < 0.15);
}
/* one bit: every value decodes to plus or minus its block's scale */
{
Opts o;
o.s("table", "binary").i("group", 128).s("scale", "bf16");
Quantised q = quantise(quantizer("rtn"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(q.enc.plane[0].dtype, (uint32_t)RAD_U1);
const std::vector<float> d = decode(q, R, C);
int bad = 0;
for (int64_t r = 0; r < R; ++r)
for (int64_t c = 0; c < C; ++c) {
const float s = rad_bf16_to_f32(((const uint16_t*)q.planes[1].data())[r * 2 + c / 128]);
bad += std::fabs(d[(size_t)(r * C + c)]) != s ||
(w[(size_t)(r * C + c)] < 0) != (d[(size_t)(r * C + c)] < 0);
}
CHECK_EQ(bad, 0);
}
}
TEST(nvfp4_is_two_scale_levels_the_second_a_tensor) {
NEED_LIBQUANT();
const int64_t R = 16, C = 256;
const std::vector<float> w = draw(R * C, 12, 30.0f);
Opts o;
o.s("codes", "fp4_e2m1").i("group", 16).s("scale", "fp8_e4m3").s("scale2", "f32");
Quantised q = quantise(quantizer("rtn"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("fp4_e2m1*fp8_e4m3[1x16]*f32[*x*]"));
/* the second level is the widest block's ideal scale, amax / 6, over E4M3's top, so that
* block's sub-scale is 448 */
float amax = 0;
for (float v : w) amax = std::fmax(amax, std::fabs(v));
float s2;
std::memcpy(&s2, q.planes[2].data(), 4);
CHECK_EQ(s2, (amax / 6.0f) / 448.0f);
int top = 0;
for (uint8_t b : q.planes[1]) top += b == 0x7e;
CHECK(top >= 1);
const double e = rel_err(w, decode(q, R, C));
std::fprintf(stderr, " nvfp4: %.4f\n", e);
CHECK(e < 0.15);
}
TEST(an_integer_sub_scale_under_a_superblock_scale) {
NEED_LIBQUANT();
/* a K-quant's shape: 4-bit codes a group of 32, a six-bit sub-scale each, an f16 a 256 */
const int64_t R = 8, C = 512;
const std::vector<float> w = draw(R * C, 13, 6.0f);
Opts o;
o.s("codes", "i4").i("group", 32).s("scale", "u6").s("scale2", "f16").i("group2", 256);
const RadQuantizerInfo* rtn = quantizer("rtn");
RadQuantWeight qw{};
qw.name = "x";
qw.rank = 2; qw.shape[0] = R; qw.shape[1] = C; qw.rows = R; qw.cols = C;
CHECK_EQ(rtn->row_block(o.data(), o.n(), &qw), 1);
Quantised q = quantise(rtn, o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string("i4*u6[1x32]*f16[1x256]"));
/* each superblock's widest group sits at 63 and none is 0 */
for (int64_t r = 0; r < R; ++r)
for (int64_t sb = 0; sb < 2; ++sb) {
int mx = 0, mn = 64;
for (int64_t g = 0; g < 8; ++g) {
const int v = (int)rad_load_f32(q.planes[1].data() + r * 12, RAD_U6, sb * 8 + g);
mx = std::max(mx, v);
mn = std::min(mn, v);
}
CHECK_EQ(mx, 63);
CHECK(mn >= 1);
}
CHECK(rel_err(w, decode(q, R, C)) < 0.2);
}
TEST(sixteen_and_thirty_two_bit_codes_are_nearly_exact) {
NEED_LIBQUANT();
const int64_t R = 8, C = 128;
const std::vector<float> w = draw(R * C, 14, 5.0f);
Opts a, b;
a.s("codes", "i16").s("scale", "f32");
b.s("codes", "i32").s("scale", "f32");
Quantised qa = quantise(quantizer("rtn"), a, "x", R, C, w);
Quantised qb = quantise(quantizer("rtn"), b, "x", R, C, w);
REQUIRE_EQ(qa.status, RAD_OK);
REQUIRE_EQ(qb.status, RAD_OK);
CHECK_EQ(enc_name(qb.enc), std::string("i32*f32[1x*]"));
const double ea = rel_err(w, decode(qa, R, C)), eb = rel_err(w, decode(qb, R, C));
std::fprintf(stderr, " i16 %.3g, i32 %.3g\n", ea, eb);
CHECK(ea < 1e-4);
CHECK(eb < 1e-6);
}
TEST(the_searched_scale_never_loses_to_absmax_and_weighs_by_importance) {
NEED_LIBQUANT();
const int64_t R = 32, C = 256;
const std::vector<float> w = draw(R * C, 15, 12.0f);
std::vector<float> imp((size_t)C);
for (int64_t c = 0; c < C; ++c) imp[(size_t)c] = (c % 7 == 0) ? 50.0f : 1.0f;
for (const char* codes : { "i4", "i3" }) {
Opts a, b;
a.s("codes", codes).i("group", 32).s("scale", "bf16");
b.s("codes", codes).i("group", 32).s("scale", "bf16").s("rule", "search");
Quantised qa = quantise(quantizer("rtn"), a, "x", R, C, w, imp.data());
Quantised qb = quantise(quantizer("rtn"), b, "x", R, C, w, imp.data());
REQUIRE_EQ(qa.status, RAD_OK);
REQUIRE_EQ(qb.status, RAD_OK);
const std::vector<float> da = decode(qa, R, C), db = decode(qb, R, C);
/* per block, in the importance-weighted error the search minimises */
int worse = 0;
double ta = 0, tb = 0;
for (int64_t r = 0; r < R; ++r)
for (int64_t g = 0; g < C / 32; ++g) {
double ea = 0, eb = 0;
for (int64_t c = g * 32; c < g * 32 + 32; ++c) {
const size_t i = (size_t)(r * C + c);
ea += imp[(size_t)c] * (double)(w[i] - da[i]) * (w[i] - da[i]);
eb += imp[(size_t)c] * (double)(w[i] - db[i]) * (w[i] - db[i]);
}
worse += eb > ea * (1 + 1e-9);
ta += ea;
tb += eb;
}
std::fprintf(stderr, " %s weighted error: absmax %.4g, search %.4g\n", codes, ta, tb);
CHECK_EQ(worse, 0);
CHECK(tb < ta * 0.9);
}
/* and asymmetric */
Opts a, b;
a.s("codes", "u3").s("zero", "u4").i("group", 32).s("scale", "f16");
b.s("codes", "u3").s("zero", "u4").i("group", 32).s("scale", "f16").s("rule", "search");
Quantised qa = quantise(quantizer("rtn"), a, "x", R, C, w);
Quantised qb = quantise(quantizer("rtn"), b, "x", R, C, w);
REQUIRE_EQ(qa.status, RAD_OK);
REQUIRE_EQ(qb.status, RAD_OK);
CHECK(rel_err(w, decode(qb, R, C)) <= rel_err(w, decode(qa, R, C)));
}
TEST(cast_converts_to_nearest_even_with_no_scale) {
NEED_LIBQUANT();
const int64_t R = 4, C = 64;
const std::vector<float> w = draw(R * C, 16, 100.0f);
const struct { const char* dt; uint32_t code; } cases[] = {
{ "bf16", RAD_BF16 }, { "f16", RAD_F16 }, { "fp8_e4m3", RAD_F8E4M3 }, { "f32", RAD_F32 } };
for (const auto& k : cases) {
Opts o;
o.s("dtype", k.dt);
Quantised q = quantise(quantizer("cast"), o, "x", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(enc_name(q.enc), std::string(k.dt));
int off = 0;
for (int64_t i = 0; i < R * C; ++i) {
std::vector<uint8_t> one(4);
rad_store_f32(one.data(), k.code, 0, w[(size_t)i]);
off += std::memcmp(one.data(), q.planes[0].data() + i * rad_dtype_bytes(k.code, 1),
(size_t)rad_dtype_bytes(k.code, 1)) != 0;
}
CHECK_EQ(off, 0);
}
Opts bad;
bad.s("dtype", "i4");
CHECK(quantise(quantizer("cast"), bad, "x", R, C, w).status != RAD_OK);
}
TEST(a_grid_the_options_do_not_describe_is_refused) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("rtn");
RadQuantWeight qw{};
qw.name = "x";
qw.rank = 2; qw.shape[0] = 4; qw.shape[1] = 256; qw.rows = 4; qw.cols = 256;
RadEncoding e;
auto refused = [&](Opts o) { return q->encoding(o.data(), o.n(), &qw, &e) != RAD_OK; };
{ Opts o; o.s("codes", "u4").i("group", 32); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").s("zero", "u8"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "fp4_e2m1").s("scale", "e8m0").s("rule", "absmax"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").i("group", 32).s("block", "1x32"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").s("transform", "fwht96"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "bf16"); CHECK(refused(o)); }
{ Opts o; o.s("table", "nf4").s("zero", "u8"); CHECK(refused(o)); }
{ Opts o; o.s("table", "nf4").s("codes", "u8"); CHECK(refused(o)); }
{ Opts o; o.s("table", "1;2;x"); CHECK(refused(o)); }
{ Opts o; o.s("table", "iq4nl").s("scale", "u6").s("scale2", "f16"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").s("scale", "u6"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").i("group", 32).s("scale2", "f16").i("group2", 48);
CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").i("group2", 256); CHECK(refused(o)); }
{ Opts o; o.s("codes", "fp4_e2m1").s("scale", "e8m0").s("scale2", "f32"); CHECK(refused(o)); }
{ Opts o; o.s("codes", "i4").s("rule", "fixed").f("scale_value", 1.0).s("scale2", "f32");
CHECK(refused(o)); }
/* a vector is declined, not an error */
RadQuantWeight v = qw;
v.rank = 1; v.shape[0] = 256; v.rows = 1;
{
Opts o;
o.s("codes", "i4");
CHECK_EQ(q->encoding(o.data(), o.n(), &v, &e), RAD_E_UNSUPPORTED);
}
}
RAD_TEST_MAIN()
/* A SCHEME OF A QUANTISER'S OWN IS READ THROUGH THAT QUANTISER. The core decodes plain and affine
* and nothing else; for any other scheme enc_decode_rows asks the loaded quantisers' decode hooks
* (abi/rad_quant.h) -- which is how the oracle, rad-kbench and rad-convert's error report read a
* weight whose format the engine has never heard of. Unloaded, the same weight is refused by name. */
TEST(a_quantisers_own_scheme_decodes_through_its_hook_and_only_while_it_is_loaded) {
const std::string so = home() + "/testquant/radtest_quant.so";
struct stat st {};
if (stat(so.c_str(), &st) != 0) {
std::fprintf(stderr, " SKIP no %s\n", so.c_str());
return;
}
const int64_t R = 8, C = 64;
const std::vector<float> w = draw(R * C, 7, 4.0f);
Quantised q;
{
Registry r;
REQUIRE_EQ(r.load_plugin(so, 0), RAD_OK);
const Registry::QuantRow* qr = r.quantizer("radtest-halves");
REQUIRE(qr && qr->info);
Opts o;
q = quantise(qr->info, o, "blk.0.ffn_down.weight", R, C, w);
REQUIRE_EQ(q.status, RAD_OK);
CHECK_EQ(std::string(q.enc.scheme), std::string("radtest-halves"));
const std::vector<float> d = decode(q, R, C);
REQUIRE_EQ(d.size(), w.size());
for (size_t i = 0; i < w.size(); ++i) CHECK(std::fabs(d[i] - w[i]) <= 0.25f + 1e-6f);
/* rows from the middle, as the oracle and rad-convert ask for them */
std::vector<const void*> pd;
for (auto& p : q.planes) pd.push_back(p.data());
EncodedView v;
enc_view(q.enc, R, C, pd.data(), &v);
std::vector<float> part((size_t)(2 * C));
REQUIRE_EQ(enc_decode_rows(v, 3, 2, part.data()), RAD_OK);
for (int64_t i = 0; i < 2 * C; ++i) CHECK_EQ(part[(size_t)i], d[(size_t)(3 * C + i)]);
}
/* the registry closed: its decoder went with it */
std::vector<const void*> pd;
for (auto& p : q.planes) pd.push_back(p.data());
EncodedView v;
enc_view(q.enc, R, C, pd.data(), &v);
std::vector<float> out((size_t)(R * C));
std::string why;
CHECK_EQ(enc_decode_rows(v, 0, R, out.data(), &why), RAD_E_UNSUPPORTED);
CHECK(why.find("radtest-halves") != std::string::npos);
}
+123
View File
@@ -0,0 +1,123 @@
/* A test harness small enough to read in one sitting. No framework, no Python, no dependency.
* TEST(name) { CHECK(cond); CHECK_EQ(a, b); }
* main() runs every registered test and returns non-zero on the first failure count.
*
* A BINARY THAT CHECKED NOTHING IS NOT A BINARY THAT PASSED, and that is what the exit code says.
* Several files here guard cases on a model file, a vocabulary or a backend, and print a " SKIP "
* line and return when it is absent. ctest's SKIP_REGULAR_EXPRESSION cannot carry that signal:
* the property is evaluated BEFORE the return code, so a binary that prints one skip line and
* then FAILS is reported Skipped and counted toward "100% tests passed".
*
* So the skip signal is the exit code and it is derived rather than declared: every CHECK
* increments a counter, and main returns 77 (ctest's SKIP_RETURN_CODE) only when nothing failed
* AND nothing was checked at all. A file where some cases ran and others skipped passes on the
* ones that ran, which is the honest answer, and a failure in any of them is a failure.
*/
#pragma once
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <functional>
#include <cmath>
namespace radtest {
struct Case { const char* name; std::function<void()> fn; };
inline std::vector<Case>& cases() { static std::vector<Case> v; return v; }
inline int& failures() { static int n = 0; return n; }
/* How many assertions actually ran. The difference between "everything passed" and "nothing was
* asked" is not visible in the failure count, and it is the whole of what a skip means. */
inline int& checks() { static int n = 0; return n; }
inline const char*& current() { static const char* s = ""; return s; }
struct Reg { Reg(const char* n, std::function<void()> f) { cases().push_back({n, f}); } };
inline void fail(const char* file, int line, const std::string& what) {
++failures();
fprintf(stderr, " FAIL %s\n %s:%d: %s\n", current(), file, line, what.c_str());
}
template <class A, class B>
inline std::string show(const A& a, const B& b) {
char buf[512];
if constexpr (std::is_convertible_v<A, std::string> && std::is_convertible_v<B, std::string>)
snprintf(buf, sizeof buf, "\"%s\" vs \"%s\"",
std::string(a).c_str(), std::string(b).c_str());
else if constexpr (std::is_floating_point_v<A> || std::is_floating_point_v<B>)
snprintf(buf, sizeof buf, "%g vs %g", (double)a, (double)b);
else
snprintf(buf, sizeof buf, "%lld vs %lld", (long long)a, (long long)b);
return buf;
}
} /* namespace radtest */
#define TEST(name) \
static void radtest_##name(); \
static ::radtest::Reg radtest_reg_##name(#name, radtest_##name); \
static void radtest_##name()
#define CHECK(cond) \
do { ++::radtest::checks(); \
if (!(cond)) ::radtest::fail(__FILE__, __LINE__, "CHECK(" #cond ")"); } while (0)
#define CHECK_EQ(a, b) \
do { ++::radtest::checks(); \
auto _a = (a); auto _b = (b); \
if (!(_a == _b)) ::radtest::fail(__FILE__, __LINE__, \
std::string("CHECK_EQ(" #a ", " #b "): ") + ::radtest::show(_a, _b)); \
} while (0)
/* A CHECK WHOSE FAILURE MAKES THE REST OF THE CASE MEANINGLESS -- the size of a container the
* next line indexes, a pointer the next line dereferences. It reports exactly like CHECK and
* then leaves the case, because the alternative is a segfault: the binary dies mid-suite, every
* case after it never runs, and a run that should have reported one failure reports one crash
* and no detail at all. Use CHECK where the case can keep going and learn more. */
#define REQUIRE(cond) \
do { ++::radtest::checks(); \
if (!(cond)) { ::radtest::fail(__FILE__, __LINE__, "REQUIRE(" #cond ")"); \
return; } } while (0)
#define REQUIRE_EQ(a, b) \
do { ++::radtest::checks(); \
auto _a = (a); auto _b = (b); \
if (!(_a == _b)) { ::radtest::fail(__FILE__, __LINE__, \
std::string("REQUIRE_EQ(" #a ", " #b "): ") + ::radtest::show(_a, _b)); \
return; } } while (0)
#define CHECK_NEAR(a, b, tol) \
do { ++::radtest::checks(); \
double _a = (double)(a), _b = (double)(b); \
if (!(std::fabs(_a - _b) <= (tol))) ::radtest::fail(__FILE__, __LINE__, \
std::string("CHECK_NEAR(" #a ", " #b "): ") + ::radtest::show(_a, _b)); \
} while (0)
#define CHECK_OK(expr) \
do { ++::radtest::checks(); \
int _s = (expr); \
if (_s < 0) ::radtest::fail(__FILE__, __LINE__, \
std::string("CHECK_OK(" #expr "): ") + rad_strerror(_s)); } while (0)
/* 77 is ctest's SKIP_RETURN_CODE, set in tests/CMakeLists.txt. Returned ONLY when nothing failed
* and nothing was checked -- a file whose every case guarded itself out. */
#define RAD_TEST_MAIN() \
int main() { \
for (auto& c : ::radtest::cases()) { \
::radtest::current() = c.name; \
int before = ::radtest::failures(); \
c.fn(); \
if (::radtest::failures() == before) fprintf(stderr, " ok %s\n", c.name); \
} \
if (::radtest::failures()) \
fprintf(stderr, "%d failure(s)\n", ::radtest::failures()); \
if (::radtest::failures()) return 1; \
if (::radtest::checks() == 0) { \
fprintf(stderr, "nothing was checked: every case in this binary guarded " \
"itself out\n"); \
return 77; \
} \
fprintf(stderr, "%d check(s) over %zu case(s)\n", ::radtest::checks(), \
::radtest::cases().size()); \
return 0; \
}
+120
View File
@@ -0,0 +1,120 @@
/* recipe_test.cpp -- the rules rad-convert quantises by (core/format/recipe.h).
*
* A recipe decides every weight of a conversion that can take hours, and a rule that silently
* matched the wrong weights -- or none -- is found only by measuring the container afterwards. So
* the matching, the order and the two spellings are held here to what spec §4.4 says they are.
*/
#include "rad_test.h"
#include "format/recipe.h"
#include <cstdlib>
#include <string>
using namespace rad;
TEST(a_glob_matches_the_whole_name) {
CHECK(recipe_glob("blk.*.ffn_*_exps.*.weight", "blk.12.ffn_down_exps.511.weight"));
CHECK(recipe_glob("*", "output.weight"));
CHECK(recipe_glob("output.weight", "output.weight"));
CHECK(recipe_glob("blk.?.attn_q.weight", "blk.7.attn_q.weight"));
CHECK(!recipe_glob("blk.?.attn_q.weight", "blk.17.attn_q.weight")); /* ? is one character */
CHECK(recipe_glob("blk.*.weight", "blk.1.2.3.weight")); /* * crosses dots */
CHECK(!recipe_glob("blk.*.weight", "blk.1.scale"));
CHECK(!recipe_glob("output", "output.weight")); /* not a prefix match */
CHECK(recipe_glob("*_exps.*", "blk.0.ffn_gate_up_exps.3.weight"));
CHECK(recipe_glob("a*b*c", "aXXbYYbZc")); /* backtracks */
CHECK(!recipe_glob("a*b*c", "aXXbYY"));
}
TEST(the_first_rule_that_matches_decides) {
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text("blk.*.ffn_down_exps.*.weight gptq codes=i4 group=128\n"
"blk.*.weight rtn codes=fp8_e4m3 block=128x128\n",
"r", &why), RAD_OK);
const RecipeRule* a = r.match("blk.3.ffn_down_exps.7.weight");
const RecipeRule* b = r.match("blk.3.attn_q.weight");
REQUIRE(a && b);
CHECK_EQ(a->quantizer, std::string("gptq"));
CHECK_EQ(b->quantizer, std::string("rtn"));
CHECK(r.match("output.weight") == nullptr); /* kept as the checkpoint holds it */
}
TEST(a_command_line_rule_goes_ahead_of_the_file) {
Recipe r;
std::string why;
REQUIRE_EQ(r.add_flag("output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16", &why),
RAD_OK);
REQUIRE_EQ(r.add_text("* rtn codes=i8 group=128\n", "file", &why), RAD_OK);
const RecipeRule* m = r.match("output.weight");
REQUIRE(m != nullptr);
CHECK_EQ(m->origin, std::string("--quant"));
CHECK_EQ(m->options.size(), (size_t)3);
CHECK_EQ(m->options[0].first, std::string("codes"));
CHECK_EQ(m->options[2].second, std::string("bf16"));
CHECK_EQ(r.match("blk.0.attn_q.weight")->origin, std::string("file:1"));
}
TEST(comments_and_blank_lines_are_not_rules_and_a_bad_line_is_named) {
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text("# a recipe\n\n \nout* rtn codes=i8 # trailing\n", "x.recipe", &why),
RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)1);
CHECK_EQ(r.rules()[0].options.size(), (size_t)1);
CHECK_EQ(r.rules()[0].origin, std::string("x.recipe:4"));
Recipe bad;
CHECK_EQ(bad.add_text("a rtn\nlonely\n", "y.recipe", &why), RAD_E_FORMAT);
CHECK(why.find("y.recipe:2") != std::string::npos);
CHECK_EQ(bad.add_text("a rtn group\n", "z", &why), RAD_E_FORMAT); /* not key=value */
CHECK_EQ(bad.add_text("a rtn k=1 k=2\n", "z", &why), RAD_E_FORMAT); /* given twice */
CHECK(why.find("twice") != std::string::npos);
CHECK_EQ(bad.add_flag("noquantiser", &why), RAD_E_FORMAT);
CHECK_EQ(bad.add_flag("p=:k=v", &why), RAD_E_FORMAT);
}
/* $NAME is the environment's, so one recipe serves every machine -- and an unset name is refused,
* because a recipe that quantised against an empty calibration directory did something else. */
TEST(a_variable_is_the_environments_and_an_unset_one_is_refused) {
::setenv("RAD_RECIPE_TEST_DIR", "/data/calib", 1);
::unsetenv("RAD_RECIPE_TEST_UNSET");
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text("* gptq calib=$RAD_RECIPE_TEST_DIR/q38 tag=${RAD_RECIPE_TEST_DIR}x\n",
"v", &why), RAD_OK);
CHECK_EQ(r.rules()[0].options[0].second, std::string("/data/calib/q38"));
CHECK_EQ(r.rules()[0].options[1].second, std::string("/data/calibx"));
CHECK_EQ(r.add_text("* gptq calib=$RAD_RECIPE_TEST_UNSET\n", "v", &why), RAD_E_FORMAT);
CHECK(why.find("RAD_RECIPE_TEST_UNSET") != std::string::npos);
CHECK_EQ(r.add_text("* gptq calib=${RAD_RECIPE_TEST_DIR\n", "v", &why), RAD_E_FORMAT);
}
/* WHAT A CONTAINER RECORDS: the options in one canonical spelling, so --reuse compares two
* conversions by what they asked for rather than by how the rule was typed. */
TEST(the_recorded_options_do_not_depend_on_how_they_were_written) {
Recipe a, b;
std::string why;
REQUIRE_EQ(a.add_text("* rtn scale=bf16 codes=i4 group=128\n", "a", &why), RAD_OK);
REQUIRE_EQ(b.add_flag("*=rtn:group=128,codes=i4,scale=bf16", &why), RAD_OK);
CHECK_EQ(a.rules()[0].options_text(), b.rules()[0].options_text());
CHECK_EQ(a.rules()[0].options_text(), std::string("codes=i4,group=128,scale=bf16"));
}
/* The recipe a container carries reads back as the same rules. */
TEST(the_recorded_recipe_reads_back_as_the_same_rules) {
Recipe r;
std::string why;
REQUIRE_EQ(r.add_flag("output.weight=rtn:codes=fp8_e4m3,block=128x128", &why), RAD_OK);
REQUIRE_EQ(r.add_text("blk.*.weight gptq codes=i4 group=128 damp=0.02\n", "f", &why), RAD_OK);
Recipe back;
REQUIRE_EQ(back.add_text(r.text(), "header", &why), RAD_OK);
REQUIRE_EQ(back.rules().size(), r.rules().size());
for (size_t i = 0; i < r.rules().size(); ++i) {
CHECK_EQ(back.rules()[i].pattern, r.rules()[i].pattern);
CHECK_EQ(back.rules()[i].quantizer, r.rules()[i].quantizer);
CHECK(back.rules()[i].options == r.rules()[i].options);
}
}
RAD_TEST_MAIN()
+2913
View File
File diff suppressed because it is too large. Load diff
+623
View File
@@ -0,0 +1,623 @@
/* relayout_parity_test.cpp -- a kernel's relayout of libquant's planes is the stored form the
* kernel reads, pinned byte for byte.
*
* A container holds a quantiser's canonical planes and the kernel only arranges them at load
* (spec.md §4.3). For every stored format, libquant's planes passed through the kernel's relayout
* are held to a recorded FNV-1a hash of the stored bytes -- the hashes are what the containers in
* service were quantised to, so a recipe reconverts one without moving a single served bit, and a
* relayout or quantiser edit that changes a format fails here rather than as a quality drift no
* test downstream is sharp enough to see. Where the kernel can be read back, the inverse has to
* give the planes back exactly.
*
* libr4d needs a HIP toolchain to build and its layouts do not, so their host sources are compiled
* into this test (tests/CMakeLists.txt). The n-gram table's hook is libavx's, from the plugin.
*/
#include "quant_fixture.h"
#include "r4d_plugin.h"
#include <dlfcn.h>
#include <unistd.h>
using namespace qfix;
namespace {
/* One kernel family's hooks. */
struct Hooks {
RadLayoutFn layout = nullptr;
RadRelayoutFn relayout = nullptr;
RadUnrelayoutFn unrelayout = nullptr;
};
uint64_t fnv(const std::vector<uint8_t>& b, uint64_t h = 0xcbf29ce484222325ull) {
for (uint8_t c : b) h = (h ^ c) * 0x100000001b3ull;
return h;
}
/* Two hashes into one, order-sensitive -- a XOR would cancel two equal planes to zero. */
uint64_t chain(uint64_t a, uint64_t b) {
for (int i = 0; i < 8; ++i) a = (a ^ ((b >> (8 * i)) & 0xFF)) * 0x100000001b3ull;
return a;
}
/* The planes `roles` names, as the loader will hand them to a relayout: dense [rows, cols] in each
* plane's own elements. `bufs` replaces the data when given -- the inverse's destinations. */
struct Selection {
std::vector<int> sel;
std::vector<RadTensor> t;
};
Selection select(const Quantised& q, int64_t R, int64_t C, const std::vector<const char*>& roles,
std::vector<std::vector<uint8_t>>* bufs = nullptr) {
Selection s;
for (const char* role : roles) {
const int i = rad_enc_find(&q.enc, role);
s.sel.push_back(i);
RadTensor t{};
if (i < 0) { s.t.push_back(t); continue; }
const RadEncPlane& p = q.enc.plane[i];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, R, C, &pr, &pc);
if (bufs) bufs->emplace_back(q.planes[(size_t)i].size(), 0);
t.data = bufs ? bufs->back().data() : const_cast<uint8_t*>(q.planes[(size_t)i].data());
t.dtype = p.dtype;
t.rank = 2;
t.shape[0] = pr;
t.shape[1] = pc;
t.stride[0] = pc;
t.stride[1] = 1;
s.t.push_back(t);
}
return s;
}
/* One operand of one weight: what to compare. */
struct Op {
int operand;
std::vector<const char*> roles;
};
/* THE CHECK. Quantise `w` with libquant, store each operand through the kernel's hooks, invert.
* Returns the hash of everything stored, in operand order. */
uint64_t stored(const char* label, const Hooks& nf, Opts kp, const char* quant,
Opts qo, const char* wname, int64_t R, int64_t C, const std::vector<float>& w,
const std::vector<Op>& ops, Quantised* keep = nullptr) {
uint64_t h = 0xcbf29ce484222325ull;
const Quantised q = quantise(quantizer(quant), qo, wname, R, C, w);
if (q.status != RAD_OK) {
CHECK_EQ(q.status, RAD_OK);
return 0;
}
for (const Op& op : ops) {
Selection s = select(q, R, C, op.roles);
RadLayout L{};
const int lrc = nf.layout(kp.data(), kp.n(), op.operand, &q.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), &L);
std::vector<uint8_t> got;
if (lrc == RAD_E_UNSUPPORTED) {
/* stored as it is: the one plane, untouched */
CHECK_EQ(op.roles.size(), (size_t)1);
got = q.planes[(size_t)s.sel[0]];
} else {
CHECK_EQ(lrc, RAD_OK);
CHECK(nf.relayout != nullptr);
if (lrc != RAD_OK || !nf.relayout) {
std::fprintf(stderr, " %s operand %d: layout %d\n", label, op.operand, lrc);
return 0;
}
got.assign((size_t)L.bytes, 0xA5);
CHECK_EQ(nf.relayout(kp.data(), kp.n(), op.operand, &q.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), got.data(), L.bytes), RAD_OK);
}
h = fnv(got, h);
/* ...and back, where the kernel can be read back at all */
if (lrc == RAD_OK && nf.unrelayout) {
std::vector<std::vector<uint8_t>> bufs;
Selection back = select(q, R, C, op.roles, &bufs);
CHECK_EQ(nf.unrelayout(kp.data(), kp.n(), op.operand, &q.enc, back.sel.data(),
got.data(), (int64_t)got.size(), back.t.data(),
(int)back.t.size()), RAD_OK);
for (size_t i = 0; i < bufs.size(); ++i)
CHECK(bufs[i] == q.planes[(size_t)s.sel[i]]);
}
}
if (keep) *keep = q;
return h;
}
/* A golden: the stored bytes' hash as the containers in service hold them. */
void golden(const char* label, uint64_t got, uint64_t want) {
if (got != want)
std::fprintf(stderr, " %s: stored hash 0x%016llxull, recorded 0x%016llxull\n", label,
(unsigned long long)got, (unsigned long long)want);
CHECK_EQ(got, want);
}
/* The edges every scale rule has a case for: a zero block, an all-positive one and an all-negative
* one -- an asymmetric grid widens each to take in zero -- at blocks (0, 0), (1, 1) and (2, 0) of a
* [br x bc] grid, clipped to the weight. */
void edges(std::vector<float>& w, int64_t R, int64_t C, int64_t br, int64_t bc) {
auto block = [&](int64_t bi, int64_t bj, int sign) {
const int64_t r0 = bi * br, c0 = (bj * bc < C) ? bj * bc : 0;
for (int64_t r = r0; r < r0 + br && r < R; ++r)
for (int64_t c = c0; c < c0 + bc && c < C; ++c) {
float& v = w[(size_t)(r * C + c)];
v = sign == 0 ? 0.0f : (float)sign * std::fabs(v);
}
};
block(0, 0, 0);
block(1, 1, 1);
block(2, 0, -1);
}
std::vector<float> weight(int64_t R, int64_t C, uint64_t seed, int64_t br, int64_t bc) {
std::vector<float> w = draw(R * C, seed, 20.0f);
edges(w, R, C, br, bc);
return w;
}
const Hooks nFp8Frag { r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block,
r4d_rad_unrelayout_fp8_block };
const Hooks nFp8Rows { r4d_rad_layout_fp8_rowmajor, nullptr, nullptr };
const Hooks nFp8Lm { r4d_rad_layout_fp8_logits, r4d_rad_relayout_fp8_logits,
r4d_rad_unrelayout_fp8_logits };
const Hooks nHc { r4d_rad_layout_hc_e4m3, r4d_rad_relayout_hc_e4m3,
r4d_rad_unrelayout_hc_e4m3 };
const Hooks nMtp { r4d_rad_layout_mtp_e4m3, r4d_rad_relayout_mtp_e4m3,
r4d_rad_unrelayout_mtp_e4m3 };
const Hooks nW4 { r4d_rad_layout_w4, r4d_rad_relayout_w4, r4d_rad_unrelayout_w4 };
const Hooks nW8a16 { r4d_rad_layout_w8a16, r4d_rad_relayout_w8a16, nullptr };
const Hooks nW8a8 { r4d_rad_layout_w8a8, r4d_rad_relayout_w8a8, nullptr };
const Hooks nW2 { r4d_rad_layout_w2a8, r4d_rad_relayout_w2a8, r4d_rad_unrelayout_w2a8 };
const Hooks nMx { r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4, nullptr };
const Hooks nMoeW4 { r4d_rad_layout_moe_w4, r4d_rad_relayout_moe_w4,
r4d_rad_unrelayout_moe_w4 };
/* gemm_nt_q's operands and the other ops' weight slots, as the kernels number them */
enum { B = 2, BSCALE = 3, BREF = 6, LM_W = 1, HC_DOWN = 2, HC_UP = 3, MTP_FCH = 4, MTP_FCE = 5 };
Opts fp8_grid() {
Opts o;
o.s("codes", "fp8_e4m3").s("block", "128x128").s("scale", "bf16");
return o;
}
} /* namespace */
TEST(block_fp8_in_fragment_order_and_row_major) {
NEED_LIBQUANT();
{
const int64_t N = 272, K = 384; /* a short last row block */
const std::vector<float> w = weight(N, K, 11, 128, 128);
Opts kp;
kp.i("N", N).i("K", K);
golden("fp8 frag", stored("fp8 frag", nFp8Frag, kp, "rtn", fp8_grid(),
"blk.0.attn_q.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
0xd60d2b6299d47a63ull);
}
{
const int64_t N = 400, K = 320; /* short blocks on both axes */
const std::vector<float> w = weight(N, K, 12, 128, 128);
Opts kp;
kp.i("N", N).i("K", K);
golden("fp8 rows", stored("fp8 rows", nFp8Rows, kp, "rtn", fp8_grid(),
"blk.0.attn_o.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
0xe90f8e25169cc5e5ull);
}
}
TEST(the_fp8_lm_head_carries_its_block_scales_in_each_row) {
NEED_LIBQUANT();
const int64_t V = 300, E = 384;
const std::vector<float> w = weight(V, E, 13, 128, 128);
Opts kp;
kp.i("n_vocab", V).i("n_embd", E);
golden("fp8 lm", stored("fp8 lm", nFp8Lm, kp, "rtn", fp8_grid(), "output.weight", V, E,
w, { { LM_W, { "codes", "scale" } } }),
0x4a710b4ca7fa4db0ull);
}
TEST(the_fp8_hyper_connection_and_mtp_rows) {
NEED_LIBQUANT();
const int64_t n = 128, hc = 4, lr = 256;
Opts kp;
kp.i("n", n).i("hc", hc).i("lowrank", lr);
{
/* mix_down: [lowrank, hc*n], 128 columns a scale */
const std::vector<float> w = weight(lr, hc * n, 14, 1, 128);
Opts g;
g.s("codes", "fp8_e4m3").i("group", 128).s("scale", "f32");
golden("hc down", stored("hc down", nHc, kp, "rtn", g, "blk.0.hc_down.weight", lr,
hc * n, w, { { HC_DOWN, { "codes", "scale" } } }),
0x62a46db4dbf831aeull);
}
{
/* mix_up: [hc*n, lowrank], a quarter of the row a scale */
const std::vector<float> w = weight(hc * n, lr, 15, 1, lr / 4);
Opts g;
g.s("codes", "fp8_e4m3").i("group", lr / 4).s("scale", "f32");
golden("hc up", stored("hc up", nHc, kp, "rtn", g, "blk.0.hc_up.weight", hc * n, lr,
w, { { HC_UP, { "codes", "scale" } } }),
0x764b1ae9ee02e27full);
}
{
const int64_t m = 256;
Opts mp;
mp.i("n", m);
const std::vector<float> wh = weight(m, m, 16, 1, 128);
const std::vector<float> we = weight(m, m, 116, 1, 128);
Opts g;
g.s("codes", "fp8_e4m3").i("group", 128).s("scale", "f32");
golden("mtp", chain(stored("mtp fc_hidden", nMtp, mp, "rtn", g,
"mtp.fc_hidden.weight", m, m, wh,
{ { MTP_FCH, { "codes", "scale" } } }),
stored("mtp fc_embedding", nMtp, mp, "rtn", g,
"mtp.fc_embd.weight", m, m, we,
{ { MTP_FCE, { "codes", "scale" } } })),
0x5fb1a57420d4471dull);
}
}
TEST(dense_int4_symmetric_and_asymmetric) {
NEED_LIBQUANT();
const int64_t N = 64, K = 256;
const std::vector<float> w = weight(N, K, 17, 1, 128);
{
Opts kp, g;
kp.i("N", N).i("K", K).s("dtype", "w4a8");
g.s("codes", "i4").i("group", 128).s("scale", "f16");
golden("w4", stored("w4", nW4, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
0x289633b39d08e864ull);
}
for (const char* z : { "u4", "u8" }) {
Opts kp, g;
kp.i("N", N).i("K", K).s("dtype", "w4a8_asym");
g.s("codes", "u4").s("zero", z).i("group", 128).s("scale", "f16");
golden("w4 asym", stored("w4 asym", nW4, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale", "zero" } } }),
0x5854c2996f14a80eull);
}
}
TEST(dense_int8_for_the_f16_and_the_int8_kernel) {
NEED_LIBQUANT();
const int64_t N = 48, K = 256;
const std::vector<float> w = weight(N, K, 18, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K);
g.s("codes", "i8").i("group", 128).s("scale", "f16").s("clamp", "sym");
golden("w8a16", stored("w8a16", nW8a16, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
0x61e5176f24b6d72bull);
golden("w8a8", stored("w8a8", nW8a8, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
0x7c2b502335fe84bbull);
}
TEST(two_bit_asymmetric) {
NEED_LIBQUANT();
const int64_t N = 32, K = 256;
const std::vector<float> w = weight(N, K, 19, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K);
g.s("codes", "u2").s("zero", "u8").i("group", 128).s("scale", "f16");
golden("w2a8", stored("w2a8", nW2, kp, "rtn", g, "output.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale", "zero" } } }),
0x3bfb973c838751c2ull);
}
TEST(mxfp4_codes_exponents_and_the_row_reference) {
NEED_LIBQUANT();
const int64_t N = 32, K = 256;
const std::vector<float> w = weight(N, K, 20, 1, 32);
Opts kp, g;
kp.i("N", N).i("K", K);
g.s("codes", "fp4_e2m1").i("group", 32).s("scale", "e8m0");
golden("mxfp4", stored("mxfp4", nMx, kp, "rtn", g, "blk.0.ffn_up.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } }, { BREF, { "scale" } } }),
0xc35d26b146836d77ull);
}
TEST(moe_int4_experts_plain_and_rotated_both_classes) {
NEED_LIBQUANT();
const int64_t N = 64, K = 256, N1 = 48, K1 = 128;
const std::vector<float> w = weight(N, K, 21, 1, 128);
const std::vector<float> w1 = weight(N1, K1, 22, 1, 128);
for (const char* dt : { "w4a8", "w4a8h" }) {
const bool rot = std::strcmp(dt, "w4a8h") == 0;
Opts kp, g;
kp.i("N", N).i("K", K).i("N_odd", N1).i("K_odd", K1).s("dtype", dt);
g.s("codes", "i4").i("group", 128).s("scale", "bf16");
if (rot) g.s("transform", "fwht128");
const uint64_t h = chain(
stored(dt, nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.0.weight", N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }),
stored(dt, nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.1.weight", N1, K1, w1,
{ { 6, { "codes" } }, { 7, { "scale" } } }));
golden(dt, h, rot ? 0xcc329df22f1f6c40ull : 0x15a0093ea83a5a90ull);
}
}
TEST(moe_codebook_experts_both_classes) {
NEED_LIBQUANT();
/* w4nla8h: the rotated plane whose codes index libquant's w4nl table. The codes view takes the
* table beside the codes, the relayout checks it against the kernel's and stores the codes
* exactly as w4a8h stores its own, and the inverse gives back both planes. */
const int64_t N = 64, K = 256, N1 = 48, K1 = 128;
const std::vector<float> w = weight(N, K, 21, 1, 128);
const std::vector<float> w1 = weight(N1, K1, 22, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K).i("N_odd", N1).i("K_odd", K1).s("dtype", "w4nla8h");
g.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128")
.s("rule", "search");
const uint64_t h = chain(
stored("w4nla8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.0.weight", N, K, w,
{ { B, { "codes", "table" } }, { BSCALE, { "scale" } } }),
stored("w4nla8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.1.weight", N1, K1, w1,
{ { 6, { "codes", "table" } }, { 7, { "scale" } } }));
golden("w4nla8h", h, 0xbb9b202196aef720ull);
}
TEST(moe_codebook_experts_at_e4m3_scales_a_64) {
NEED_LIBQUANT();
/* w4nl64a8h: the codebook's codes, stored as w4nla8h stores them, and an E4M3 scale a
* (row, 64 of K) under one fixed f32 -- the scale view selects both, the relayout checks the
* second is the kernel's constant and stores the E4M3 plane as it is, and the inverse gives
* back both. A second level of any other value is refused when its bytes are relaid. */
const int64_t N = 64, K = 256, N1 = 48, K1 = 128;
const std::vector<float> w = weight(N, K, 21, 1, 128);
const std::vector<float> w1 = weight(N1, K1, 22, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K).i("N_odd", N1).i("K_odd", K1).s("dtype", "w4nl64a8h").i("group", 128);
g.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128").s("rule", "search");
const uint64_t h = chain(
stored("w4nl64a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.0.weight", N, K, w,
{ { B, { "codes", "table" } }, { BSCALE, { "scale", "scale.1" } } }),
stored("w4nl64a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.1.weight", N1, K1, w1,
{ { 6, { "codes", "table" } }, { 7, { "scale", "scale.1" } } }));
golden("w4nl64a8h", h, 0x528e273bdee3be1dull);
Opts g2;
g2.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-12).s("transform", "fwht128").s("rule", "search");
const Quantised q2 = quantise(quantizer("rtn"), g2, "blk.0.ffn_down_exps.0.weight", N, K, w);
REQUIRE_EQ(q2.status, RAD_OK);
Selection s = select(q2, N, K, { "scale", "scale.1" });
RadLayout L{};
REQUIRE_EQ(r4d_rad_layout_moe_w4(kp.data(), kp.n(), BSCALE, &q2.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), &L), RAD_OK);
std::vector<uint8_t> dst((size_t)L.bytes);
CHECK_EQ(r4d_rad_relayout_moe_w4(kp.data(), kp.n(), BSCALE, &q2.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), dst.data(), L.bytes), RAD_E_DTYPE);
/* and the bf16-scaled codebook's encoding is not this dtype's */
Opts g3;
g3.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
const Quantised q3 = quantise(quantizer("rtn"), g3, "blk.0.ffn_down_exps.0.weight", N, K, w);
REQUIRE_EQ(q3.status, RAD_OK);
Selection s3 = select(q3, N, K, { "codes", "table" });
CHECK_EQ(r4d_rad_layout_moe_w4(kp.data(), kp.n(), B, &q3.enc, s3.sel.data(), s3.t.data(),
(int)s3.t.size(), &L), RAD_E_DTYPE);
}
TEST(moe_codebook_experts_at_e4m3_scales_a_32) {
NEED_LIBQUANT();
/* w4nl32a8h: the 64-wide form's planes at a scale a 32 of K, four E4M3 bytes a 128. */
const int64_t N = 64, K = 256, N1 = 48, K1 = 128;
const std::vector<float> w = weight(N, K, 21, 1, 128);
const std::vector<float> w1 = weight(N1, K1, 22, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K).i("N_odd", N1).i("K_odd", K1).s("dtype", "w4nl32a8h").i("group", 128);
g.s("table", "w4nl").i("group", 32).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128").s("rule", "search");
const uint64_t h = chain(
stored("w4nl32a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.0.weight", N, K, w,
{ { B, { "codes", "table" } }, { BSCALE, { "scale", "scale.1" } } }),
stored("w4nl32a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.1.weight", N1, K1, w1,
{ { 6, { "codes", "table" } }, { 7, { "scale", "scale.1" } } }));
golden("w4nl32a8h", h, 0xf5ce1cb0bac69211ull);
/* and the 64-wide encoding is not this dtype's */
Opts g64;
g64.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128");
const Quantised q = quantise(quantizer("rtn"), g64, "blk.0.ffn_down_exps.0.weight", N, K, w);
REQUIRE_EQ(q.status, RAD_OK);
Selection s = select(q, N, K, { "codes", "table" });
RadLayout L{};
CHECK_EQ(r4d_rad_layout_moe_w4(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(),
(int)s.t.size(), &L), RAD_E_DTYPE);
}
TEST(moe_codebook_experts_at_five_bits) {
NEED_LIBQUANT();
/* w5nl64a8h: u5 codes into libquant's 32-entry w5nl table at w4nl64a8h's scales. The codes
* view relays each row into its nibbles and its sign bits, the scale view is the 64-wide
* form's, and the inverse gives back the packed codes and the table. A table that is not the
* kernel's is refused when its bytes are relaid, and the four-bit encoding is not this
* dtype's. */
const int64_t N = 64, K = 256, N1 = 48, K1 = 128;
const std::vector<float> w = weight(N, K, 21, 1, 128);
const std::vector<float> w1 = weight(N1, K1, 22, 1, 128);
Opts kp, g;
kp.i("N", N).i("K", K).i("N_odd", N1).i("K_odd", K1).s("dtype", "w5nl64a8h").i("group", 128);
g.s("table", "w5nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128").s("rule", "search");
const uint64_t h = chain(
stored("w5nl64a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.0.weight", N, K, w,
{ { B, { "codes", "table" } }, { BSCALE, { "scale", "scale.1" } } }),
stored("w5nl64a8h", nMoeW4, kp, "rtn", g, "blk.0.ffn_down_exps.1.weight", N1, K1, w1,
{ { 6, { "codes", "table" } }, { 7, { "scale", "scale.1" } } }));
golden("w5nl64a8h", h, 0xd773da64690cb3f6ull);
/* the same 32 levels with one moved: the kernel's table is the only one it decodes */
Opts g2;
g2.s("table", "0.8125;2.5;4;5.5;7.5;9;11;12;14;16;18;20;22;24;28;30;-0.8125;-2.5;-4;-5.5;"
"-7.5;-9;-11;-12;-14;-16;-18;-20;-22;-24;-28;-30")
.i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32").s("block2", "*x*")
.f("scale2_value", 0x1p-13).s("transform", "fwht128");
const Quantised q2 = quantise(quantizer("rtn"), g2, "blk.0.ffn_down_exps.0.weight", N, K, w);
REQUIRE_EQ(q2.status, RAD_OK);
Selection s2 = select(q2, N, K, { "codes", "table" });
RadLayout L{};
REQUIRE_EQ(r4d_rad_layout_moe_w4(kp.data(), kp.n(), B, &q2.enc, s2.sel.data(), s2.t.data(),
(int)s2.t.size(), &L), RAD_OK);
CHECK_EQ(L.bytes, N * K / 8 * 5);
std::vector<uint8_t> dst((size_t)L.bytes);
CHECK_EQ(r4d_rad_relayout_moe_w4(kp.data(), kp.n(), B, &q2.enc, s2.sel.data(), s2.t.data(),
(int)s2.t.size(), dst.data(), L.bytes), RAD_E_DTYPE);
/* and the four-bit codebook's encoding is not this dtype's */
Opts g4;
g4.s("table", "w4nl").i("group", 64).s("scale", "fp8_e4m3").s("scale2", "f32")
.s("block2", "*x*").f("scale2_value", 0x1p-13).s("transform", "fwht128");
const Quantised q4 = quantise(quantizer("rtn"), g4, "blk.0.ffn_down_exps.0.weight", N, K, w);
REQUIRE_EQ(q4.status, RAD_OK);
Selection s4 = select(q4, N, K, { "codes", "table" });
CHECK_EQ(r4d_rad_layout_moe_w4(kp.data(), kp.n(), B, &q4.enc, s4.sel.data(), s4.t.data(),
(int)s4.t.size(), &L), RAD_E_DTYPE);
}
TEST(moe_int4_gptq_against_a_calibration_hessian) {
NEED_LIBQUANT();
/* Correlated activations, so the Hessian is far from diagonal and the error feedback moves
* codes rounding alone would not -- checked below, or a GPTQ that silently fell back to
* rounding would pass as parity. */
const int64_t N = 64, K = 256, T = 1024;
const std::vector<float> w = weight(N, K, 23, 1, 128);
const std::vector<float> z = draw(T * K, 24);
const std::vector<float> mix = draw(K * K, 25);
std::vector<float> x((size_t)(T * K), 0.0f);
for (int64_t t = 0; t < T; ++t)
for (int64_t i = 0; i < K; ++i) {
double s = z[(size_t)(t * K + i)] * 4.0;
for (int64_t j = 0; j < 8; ++j)
s += mix[(size_t)(i * K + j)] * z[(size_t)(t * K + j)] * 40.0;
x[(size_t)(t * K + i)] = (float)s;
}
std::vector<float> h((size_t)(K * K), 0.0f);
for (int64_t t = 0; t < T; ++t)
for (int64_t i = 0; i < K; ++i)
for (int64_t j = 0; j < K; ++j)
h[(size_t)(i * K + j)] += x[(size_t)(t * K + i)] * x[(size_t)(t * K + j)];
char dir[] = "/tmp/rad_relayout_parity_XXXXXX";
REQUIRE(mkdtemp(dir) != nullptr);
const std::string path = std::string(dir) + "/gram.r0.blk.5.ffn_down_exps.bin";
/* The Gram of `x` as it stands -- the model's own domain -- so the rotated recipe below reads it
* rotated into its own, as it would a bf16 model's calibration. */
REQUIRE(write_gram(path, K, T, h, 0));
const char* name = "blk.5.ffn_down_exps.9.weight";
for (const char* dt : { "w4a8", "w4a8h" }) {
const bool rot = std::strcmp(dt, "w4a8h") == 0;
Opts kp, g, r;
kp.i("N", N).i("K", K).s("dtype", dt).s("calib", dir).s("weight", name);
g.s("codes", "i4").i("group", 128).s("scale", "bf16").s("calib", dir);
r.s("codes", "i4").i("group", 128).s("scale", "bf16");
if (rot) { g.s("transform", "fwht128"); r.s("transform", "fwht128"); }
Quantised qg, qr;
const uint64_t hg = stored(dt, nMoeW4, kp, "gptq", g, name, N, K, w,
{ { B, { "codes" } }, { BSCALE, { "scale" } } }, &qg);
qr = quantise(quantizer("rtn"), r, name, N, K, w);
REQUIRE_EQ(qr.status, RAD_OK);
CHECK(qg.planes[0] != qr.planes[0]); /* the Hessian moved codes */
CHECK(qg.planes[1] == qr.planes[1]); /* and not the scales: static groups */
golden(rot ? "gptq w4a8h" : "gptq w4a8", hg,
rot ? 0x761cbdd0aff4adedull : 0x4a4db9378ca02303ull);
}
std::remove(path.c_str());
rmdir(dir);
}
TEST(the_ngram_table_is_the_canonical_plane) {
NEED_LIBQUANT();
void* so = dlopen((home() + "/kernels/libavx.so").c_str(), RTLD_NOW | RTLD_LOCAL);
if (!so) {
std::fprintf(stderr, " SKIP no libavx under %s\n", home().c_str());
return;
}
Hooks nf;
nf.layout = (RadLayoutFn)dlsym(so, "avx_layout_ngram");
REQUIRE(nf.layout != nullptr);
const int64_t V = 100, E = 64;
const double wscale = 1.99317932128906e-4;
const std::vector<float> w = draw(V * E, 26, 20.0f);
Opts kp, g;
kp.i("n_vocab", V).i("n_embd", E);
g.s("codes", "fp8_e4m3").s("block", "*x*").s("scale", "bf16").s("rule", "fixed")
.f("scale_value", wscale);
golden("ngram", stored("ngram", nf, kp, "rtn", g, "ple.ngram.weight", V, E, w,
{ { 1, { "codes" } }, { 2, { "scale" } } }),
0xa5e81d9b9ff05c2aull);
dlclose(so);
}
TEST(a_kernel_refuses_an_encoding_it_does_not_read) {
NEED_LIBQUANT();
const int64_t N = 64, K = 256;
const std::vector<float> w = draw(N * K, 27);
Opts i4, i4r, u4, f8;
i4.s("codes", "i4").i("group", 128).s("scale", "bf16");
i4r.s("codes", "i4").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
u4.s("codes", "u4").s("zero", "u4").i("group", 128).s("scale", "f16");
f8 = fp8_grid();
const Quantised q_i4 = quantise(quantizer("rtn"), i4, "x", N, K, w);
const Quantised q_i4r = quantise(quantizer("rtn"), i4r, "x", N, K, w);
const Quantised q_u4 = quantise(quantizer("rtn"), u4, "x", N, K, w);
const Quantised q_f8 = quantise(quantizer("rtn"), f8, "x", N, K, w);
Opts nl, nf4;
nl.s("table", "w4nl").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
nf4.s("table", "nf4").i("group", 128).s("scale", "bf16").s("transform", "fwht128");
const Quantised q_nl = quantise(quantizer("rtn"), nl, "x", N, K, w);
const Quantised q_nf4 = quantise(quantizer("rtn"), nf4, "x", N, K, w);
auto lay = [&](RadLayoutFn f, Opts kp, int operand, const Quantised& q,
std::vector<const char*> roles) {
Selection s = select(q, N, K, roles);
RadLayout L{};
return f(kp.data(), kp.n(), operand, &q.enc, s.sel.data(), s.t.data(), (int)s.t.size(), &L);
};
Opts dense, plain, rot, sym, asym;
dense.i("N", N).i("K", K);
plain.i("N", N).i("K", K).s("dtype", "w4a8");
rot.i("N", N).i("K", K).s("dtype", "w4a8h");
sym.i("N", N).i("K", K).s("dtype", "w4a8");
asym.i("N", N).i("K", K).s("dtype", "w4a8_asym");
/* an fp8 GEMM handed int4 */
CHECK_EQ(lay(r4d_rad_layout_fp8_block, dense, B, q_i4, { "codes" }), RAD_E_DTYPE);
/* a rotated weight to the experts that do not rotate their activation, and the reverse */
CHECK_EQ(lay(r4d_rad_layout_moe_w4, plain, B, q_i4r, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_moe_w4, rot, B, q_i4, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_moe_w4, rot, B, q_i4r, { "codes" }), RAD_OK);
/* the symmetric dense kernel handed an asymmetric grid, and the reverse; and a bf16 scale */
CHECK_EQ(lay(r4d_rad_layout_w4, sym, B, q_u4, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_w4, asym, B, q_i4, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_w4, sym, B, q_i4, { "codes" }), RAD_E_DTYPE);
/* a block-fp8 weight to the int8 kernel */
CHECK_EQ(lay(r4d_rad_layout_w8a8, dense, B, q_f8, { "codes" }), RAD_E_DTYPE);
/* the right encoding with the wrong planes selected is a shape error, not a pass */
CHECK_EQ(lay(r4d_rad_layout_fp8_block, dense, B, q_f8, { "scale" }), RAD_E_SHAPE);
/* a codebook to the two's complement experts, and -8..7 to the codebook's; the codebook's codes
* without their table */
Opts nlk;
nlk.i("N", N).i("K", K).s("dtype", "w4nla8h");
CHECK_EQ(lay(r4d_rad_layout_moe_w4, rot, B, q_nl, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_moe_w4, nlk, B, q_i4r, { "codes" }), RAD_E_DTYPE);
CHECK_EQ(lay(r4d_rad_layout_moe_w4, nlk, B, q_nl, { "codes" }), RAD_E_SHAPE);
CHECK_EQ(lay(r4d_rad_layout_moe_w4, nlk, B, q_nl, { "codes", "table" }), RAD_OK);
/* ANOTHER TABLE OF THE SAME SHAPE declares -- an encoding cannot say what its table holds --
* and is refused when its bytes are relaid, before the kernel could decode them as w4nl */
CHECK_EQ(lay(r4d_rad_layout_moe_w4, nlk, B, q_nf4, { "codes", "table" }), RAD_OK);
{
Selection s = select(q_nf4, N, K, { "codes", "table" });
RadLayout L{};
REQUIRE_EQ(r4d_rad_layout_moe_w4(nlk.data(), nlk.n(), B, &q_nf4.enc, s.sel.data(),
s.t.data(), (int)s.t.size(), &L), RAD_OK);
std::vector<uint8_t> dst((size_t)L.bytes);
CHECK_EQ(r4d_rad_relayout_moe_w4(nlk.data(), nlk.n(), B, &q_nf4.enc, s.sel.data(),
s.t.data(), (int)s.t.size(), dst.data(), L.bytes),
RAD_E_DTYPE);
}
}
RAD_TEST_MAIN()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2042
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+240
View File
@@ -0,0 +1,240 @@
/* share_test.cpp -- which bytes of a container entry one rank takes (core/format/share.h).
*
* The loader reads exactly the rectangles weight_share names, so a wrong one is a rank serving
* another rank's rows -- a model that loads, runs and is wrong in the way spec §17 exists to
* prevent. Each case is a shape tensor parallelism actually produces, worked by hand.
*/
#include "rad_test.h"
#include "format/share.h"
#include <cstring>
#include <string>
using namespace rad;
namespace {
/* A declaration of `planes` of `e` over a logical [R, C] weight at rank `world`, as the builder
* records it: one plane at its own extents, several at the logical ones, this rank's share of
* them under a shard. */
WeightInfo decl(const RadEncoding& e, std::initializer_list<int> planes, int64_t R, int64_t C,
int shard, int world, std::initializer_list<int64_t> parts = {}) {
WeightInfo w;
w.enc = e;
w.enc_known = true;
w.decl.shard = shard;
w.decl.rank = 2;
int64_t r = R, c = C;
if (shard == RAD_SHARD_ROW && world > 1) r = R / world;
if (shard == RAD_SHARD_COL && world > 1) c = C / world;
w.decl.shape[0] = r;
w.decl.shape[1] = c;
int n = 0;
for (int64_t p : parts) w.decl.row_parts[n++] = p;
w.decl.n_row_parts = n;
for (int k : planes) {
w.sel[w.n_sel] = k;
rad_enc_plane_dims(&e.plane[k], r, c, &w.sel_rows[w.n_sel], &w.sel_cols[w.n_sel]);
++w.n_sel;
}
return w;
}
RadEncoding fp8_block() {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "codes", RAD_F8E4M3, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_BF16, 128, 128);
return e;
}
int share(const WeightInfo& w, int64_t R, int64_t C, int world, int index, PlaneShare* out,
std::string* why = nullptr) {
const int64_t shape[2] = { R, C };
return weight_share(w, w.enc, 2, shape, world, index, out, why);
}
} /* namespace */
/* Unsharded, a rank takes every plane whole: one rectangle, every byte of every row. */
TEST(an_unsharded_weight_is_every_plane_whole) {
const RadEncoding e = fp8_block();
const WeightInfo w = decl(e, { 0, 1 }, 256, 384, RAD_SHARD_NONE, 2);
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 256, 384, 2, 1, s), RAD_OK);
REQUIRE_EQ(s[0].rects.size(), (size_t)1);
CHECK_EQ(s[0].rects[0].row0, (int64_t)0);
CHECK_EQ(s[0].rects[0].rows, (int64_t)256);
CHECK_EQ(s[0].rects[0].bytes, (int64_t)384);
CHECK_EQ(s[0].dense_bytes(), (int64_t)(256 * 384));
CHECK_EQ(s[1].rows, (int64_t)2);
CHECK_EQ(s[1].cols, (int64_t)3);
CHECK_EQ(s[1].dense_bytes(), (int64_t)(2 * 3 * 2));
}
/* A ROW shard of a block-fp8 linear is rows of every plane, the scales a block of 128 rows each. */
TEST(a_row_shard_takes_rows_of_the_codes_and_their_scale_blocks) {
const RadEncoding e = fp8_block();
for (int index = 0; index < 2; ++index) {
const WeightInfo w = decl(e, { 0, 1 }, 512, 256, RAD_SHARD_ROW, 2);
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 512, 256, 2, index, s), RAD_OK);
CHECK_EQ(s[0].rects[0].row0, (int64_t)(index * 256));
CHECK_EQ(s[0].rects[0].rows, (int64_t)256);
CHECK_EQ(s[1].rects[0].row0, (int64_t)(index * 2));
CHECK_EQ(s[1].rects[0].rows, (int64_t)2);
CHECK_EQ(s[1].rects[0].bytes, (int64_t)(2 * 2));
}
/* the scale plane declared on its own, as gemm_nt_q's b_scale operand: its own extents */
const WeightInfo ws = decl(e, { 1 }, 512, 256, RAD_SHARD_ROW, 2);
CHECK_EQ(ws.sel_rows[0], (int64_t)2);
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(ws, 512, 256, 2, 1, s), RAD_OK);
CHECK_EQ(s[0].rects[0].row0, (int64_t)2);
CHECK_EQ(s[0].rects[0].rows, (int64_t)2);
}
/* A STACKED [gate|up] IS CUT IN EACH PART: rank 1 of 2 takes the second half of gate AND the second
* half of up, never "all of up". */
TEST(a_stacked_weight_is_cut_in_every_part) {
const RadEncoding e = rad_enc_plain(RAD_BF16);
/* entry [2 * 512, 64]: gate rows 0..511, up rows 512..1023; a rank's parts are 256 rows each */
const WeightInfo w = decl(e, { 0 }, 1024, 64, RAD_SHARD_ROW, 2, { 256, 256 });
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 1024, 64, 2, 1, s), RAD_OK);
REQUIRE_EQ(s[0].rects.size(), (size_t)2);
CHECK_EQ(s[0].rects[0].row0, (int64_t)256);
CHECK_EQ(s[0].rects[1].row0, (int64_t)768);
CHECK_EQ(s[0].rows, (int64_t)512);
/* parts that do not sum to the rank's share are refused */
const WeightInfo bad = decl(e, { 0 }, 1024, 64, RAD_SHARD_ROW, 2, { 200, 256 });
std::string why;
CHECK_EQ(share(bad, 1024, 64, 2, 0, s, &why), RAD_E_SHAPE);
CHECK(why.find("row parts") != std::string::npos);
}
/* A COL shard is columns of each row, and a column cut has to land on a whole byte. */
TEST(a_col_shard_takes_a_byte_range_of_every_row) {
const RadEncoding e = rad_enc_plain(RAD_BF16);
const WeightInfo w = decl(e, { 0 }, 8, 128, RAD_SHARD_COL, 4);
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 8, 128, 4, 3, s), RAD_OK);
REQUIRE_EQ(s[0].rects.size(), (size_t)1);
CHECK_EQ(s[0].rects[0].rows, (int64_t)8);
CHECK_EQ(s[0].rects[0].byte0, (int64_t)(96 * 2));
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(32 * 2));
CHECK_EQ(s[0].row_bytes, (int64_t)(128 * 2));
RadEncoding i4;
rad_enc_clear(&i4);
rad_enc_copy_str(i4.scheme, "plain");
rad_enc_add_plane(&i4, "codes", RAD_I4, 1, 1);
const WeightInfo odd = decl(i4, { 0 }, 4, 6, RAD_SHARD_COL, 2); /* 3 nibbles a rank */
std::string why;
CHECK_EQ(share(odd, 4, 6, 2, 1, s, &why), RAD_E_SHAPE);
CHECK(why.find("whole bytes") != std::string::npos);
}
/* A cut that splits a scale block belongs to neither rank, and is refused. */
TEST(a_shard_that_splits_a_block_is_refused) {
const RadEncoding e = fp8_block();
const WeightInfo w = decl(e, { 0, 1 }, 384, 256, RAD_SHARD_ROW, 2); /* 192 rows a rank */
PlaneShare s[RAD_ENC_MAX_PLANES];
std::string why;
CHECK_EQ(share(w, 384, 256, 2, 0, s, &why), RAD_E_SHAPE);
}
/* AN UNEVEN SPAN: the plugin names this rank's rows of each part, and the scale plane takes the
* same slice in its own blocks. */
TEST(an_uneven_span_is_the_rows_the_plugin_names) {
const RadEncoding e = fp8_block();
WeightInfo w = decl(e, { 0, 1 }, 640, 128, RAD_SHARD_ROW, 2);
w.decl.shape[0] = 384;
w.shard_lo = 256;
w.shard_hi = 640;
rad_enc_plane_dims(&e.plane[0], 384, 128, &w.sel_rows[0], &w.sel_cols[0]);
rad_enc_plane_dims(&e.plane[1], 384, 128, &w.sel_rows[1], &w.sel_cols[1]);
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 640, 128, 2, 1, s), RAD_OK);
CHECK_EQ(s[0].rects[0].row0, (int64_t)256);
CHECK_EQ(s[0].rows, (int64_t)384);
CHECK_EQ(s[1].rects[0].row0, (int64_t)2);
CHECK_EQ(s[1].rows, (int64_t)3);
}
/* A per-tensor scale is one value every rank carries whole, once, whatever the codes' cut. */
TEST(a_per_tensor_scale_is_carried_whole_by_every_rank) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
rad_enc_add_plane(&e, "codes", RAD_F8E4M3, 1, 1);
rad_enc_add_plane(&e, "scale", RAD_BF16, 0, 0);
const WeightInfo w = decl(e, { 0, 1 }, 1000, 64, RAD_SHARD_ROW, 2, { 250, 250 });
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(share(w, 1000, 64, 2, 1, s), RAD_OK);
CHECK_EQ(s[0].rects.size(), (size_t)2);
REQUIRE_EQ(s[1].rects.size(), (size_t)1);
CHECK_EQ(s[1].rows, (int64_t)1);
CHECK_EQ(s[1].cols, (int64_t)1);
}
/* A rank-1 ROW shard is a contiguous slice of the vector: one value per head. */
TEST(a_sharded_vector_is_a_slice_of_it) {
const RadEncoding e = rad_enc_plain(RAD_F32);
WeightInfo w;
w.enc = e;
w.enc_known = true;
w.decl.shard = RAD_SHARD_ROW;
w.decl.rank = 1;
w.decl.shape[0] = 16;
w.n_sel = 1;
w.sel[0] = 0;
w.sel_rows[0] = 1;
w.sel_cols[0] = 16;
const int64_t shape[1] = { 64 };
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(weight_share(w, e, 1, shape, 4, 2, s, nullptr), RAD_OK);
CHECK_EQ(s[0].rects[0].byte0, (int64_t)(32 * 4));
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(16 * 4));
}
/* A RESHAPE: a conv kernel [O, C, T, H, W] declared as the [O, C*T*H*W] matrix it is. The bytes
* do not move, so the share is the whole plane in the declared view -- and a shard of a reshape
* is a different cut, so it is refused. */
TEST(a_whole_plane_may_be_declared_under_another_shape) {
const RadEncoding e = rad_enc_plain(RAD_BF16);
WeightInfo w = decl(e, { 0 }, 1152, 1536, RAD_SHARD_NONE, 2);
const int64_t conv[5] = { 1152, 3, 2, 16, 16 };
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(weight_share(w, e, 5, conv, 2, 1, s, nullptr), RAD_OK);
CHECK_EQ(s[0].rows, (int64_t)1152);
CHECK_EQ(s[0].cols, (int64_t)1536);
CHECK_EQ(s[0].dense_bytes(), (int64_t)(1152 * 1536 * 2));
WeightInfo r = decl(e, { 0 }, 1152, 1536, RAD_SHARD_ROW, 2);
std::string why;
CHECK_EQ(weight_share(r, e, 5, conv, 2, 0, s, &why), RAD_E_SHAPE);
}
/* A depthwise conv kernel [C, 1, K] is the [C, K] matrix its inner 1 leaves, so a row shard of
* it is rows of that matrix -- contiguous, K elements each. An inner dimension that is not 1 is
* still a rank-3 weight, and which of its dimensions a rank owns is not the loader's to guess. */
TEST(a_unit_inner_dimension_is_sharded_as_the_matrix_it_leaves) {
const RadEncoding e = rad_enc_plain(RAD_BF16);
WeightInfo w = decl(e, { 0 }, 10240, 4, RAD_SHARD_ROW, 2);
const int64_t conv[3] = { 10240, 1, 4 };
PlaneShare s[RAD_ENC_MAX_PLANES];
REQUIRE_EQ(weight_share(w, e, 3, conv, 2, 1, s, nullptr), RAD_OK);
REQUIRE_EQ(s[0].rects.size(), (size_t)1);
CHECK_EQ(s[0].rects[0].row0, (int64_t)5120);
CHECK_EQ(s[0].rects[0].rows, (int64_t)5120);
CHECK_EQ(s[0].rects[0].byte0, (int64_t)0);
CHECK_EQ(s[0].rects[0].bytes, (int64_t)(4 * 2));
const int64_t stack[3] = { 10240, 2, 2 };
std::string why;
CHECK_EQ(weight_share(w, e, 3, stack, 2, 0, s, &why), RAD_E_SHAPE);
}
RAD_TEST_MAIN()
+1216
View File
File diff suppressed because it is too large. Load diff
+280
View File
@@ -0,0 +1,280 @@
/* tokenizer_fixture.h -- vocabularies and text for the tokenizer tests, made on the spot.
*
* The tests need no model file. A byte-level BPE vocabulary is TRAINED here, deterministically,
* on generated text -- the textbook algorithm: count adjacent pairs over the pre-tokenised words,
* merge the most frequent, repeat -- so it has the shape of a real one: every byte is a token,
* common words are single tokens, rare ones take several merges, and some merges produce text
* other merges build on. The generators draw from every general category, the scripts and
* sequences that stress a pre-tokeniser (combining marks, ZWJ emoji, CJK, Hangul, RTL), digit runs
* of every length, every kind of whitespace, contractions in mixed case, and optionally bytes that
* are not UTF-8.
*/
#pragma once
#include "text/tokenizer.h"
#include "text/tokenizer_regex.h"
#include "text/tokenizer_ucd.h"
#include <algorithm>
#include <cstdint>
#include <map>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>
namespace tokfix {
using namespace rad;
/* The patterns real tokenizer.json files carry, in the spelling they carry them. */
inline const char* k_qwen35 =
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
inline const char* k_minicpm_digits = "\\p{N}{1,3}";
inline const char* k_minicpm =
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}+| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
inline const char* k_llama3 =
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
inline const char* k_gpt2 =
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+";
/* The GPT-2 byte alphabet: byte -> its mapped character's UTF-8. */
inline std::string bytelevel_char(uint8_t b) {
static std::vector<std::string> map = [] {
std::vector<std::string> m(256);
bool taken[256] = {};
auto utf8 = [](uint32_t c) {
std::string s;
if (c < 0x80) s += (char)c;
else { s += (char)(0xC0 | (c >> 6)); s += (char)(0x80 | (c & 0x3F)); }
return s;
};
for (int c = 0x21; c <= 0x7E; ++c) { m[c] = utf8(c); taken[c] = true; }
for (int c = 0xA1; c <= 0xAC; ++c) { m[c] = utf8(c); taken[c] = true; }
for (int c = 0xAE; c <= 0xFF; ++c) { m[c] = utf8(c); taken[c] = true; }
uint32_t n = 0;
for (int c = 0; c < 256; ++c) if (!taken[c]) m[c] = utf8(256 + n++);
return m;
}();
return map[b];
}
inline std::string cp_utf8(uint32_t c) {
std::string s;
if (c < 0x80) { s += (char)c; }
else if (c < 0x800) { s += (char)(0xC0 | (c >> 6)); s += (char)(0x80 | (c & 0x3F)); }
else if (c < 0x10000) {
s += (char)(0xE0 | (c >> 12)); s += (char)(0x80 | ((c >> 6) & 0x3F)); s += (char)(0x80 | (c & 0x3F));
} else {
s += (char)(0xF0 | (c >> 18)); s += (char)(0x80 | ((c >> 12) & 0x3F));
s += (char)(0x80 | ((c >> 6) & 0x3F)); s += (char)(0x80 | (c & 0x3F));
}
return s;
}
/* The general category of `c` from the compiler's own tables. */
inline uint32_t gc_of(uint32_t c) {
size_t lo = 0, hi = ucd::k_gc_runs_n;
while (hi - lo > 1) {
const size_t mid = (lo + hi) / 2;
if (ucd::k_gc_runs[mid].first <= c) lo = mid; else hi = mid;
}
return ucd::k_gc_runs[lo].gc;
}
/* Random text. `junk` adds bytes that are not UTF-8; `exclude(c)` removes codepoints the caller
* does not want (the reference encoder's known disagreements, for one). */
class TextGen {
public:
explicit TextGen(uint32_t seed) : rng_(seed) {
std::vector<std::vector<uint32_t>> by_gc(ucd::kGcCount);
for (size_t i = 0; i < ucd::k_gc_runs_n; ++i) {
const uint32_t a = ucd::k_gc_runs[i].first;
const uint32_t b = i + 1 < ucd::k_gc_runs_n ? ucd::k_gc_runs[i + 1].first : 0x110000;
for (uint32_t c = a; c < b && c < a + 64; ++c) by_gc[ucd::k_gc_runs[i].gc].push_back(c);
}
by_gc_ = std::move(by_gc);
}
template <class Exclude>
std::string text(size_t n_cps, bool junk, Exclude exclude) {
std::string out;
size_t n = 0;
while (n < n_cps) {
const int k = pick(100);
std::string piece;
if (k < 30) piece = word();
else if (k < 40) piece = pick_of(k_space);
else if (k < 47) piece = digits();
else if (k < 54) piece = contraction();
else if (k < 62) piece = pick_of(k_sequences);
else if (k < 70) piece = pick_of(k_punct);
else if (k < 92) {
const uint32_t g = pick((int)by_gc_.size());
if (g == ucd::Cs || by_gc_[g].empty()) continue;
const uint32_t c = by_gc_[g][pick((int)by_gc_[g].size())];
if (exclude(c)) continue;
piece = cp_utf8(c);
} else if (junk) {
piece = pick_of(k_junk);
} else {
piece = " ";
}
out += piece;
++n;
}
return out;
}
std::string text(size_t n_cps, bool junk = false) {
return text(n_cps, junk, [](uint32_t) { return false; });
}
int pick(int n) { return (int)(rng_() % (uint32_t)n); }
private:
std::mt19937 rng_;
std::vector<std::vector<uint32_t>> by_gc_;
template <size_t N> std::string pick_of(const char* const (&a)[N]) { return a[pick((int)N)]; }
std::string word() {
static const char* const words[] = {
"the", "cache", "shard", "value", "func", "return", "struct", "Hello", "WORLD", "tokenizer",
"naïve", "café", "Straße", "über", "мир", "привет", "κόσμος", "世界", "更新", "東京", "한국어",
"مرحبا", "שלום", "नमस्ते", "สวัสดี", "Džemal", "finance", "aaaa", "abab", "xyzzy", "Z",
};
std::string w = pick_of(words);
if (pick(4) == 0) w = " " + w;
return w;
}
std::string digits() {
static const char* const sys[] = { "0123456789", "٠١٢٣٤٥٦٧٨٩", "०१२३४५६७८९" };
const std::string s = sys[pick(8) == 0 ? 1 + pick(2) : 0];
const size_t cp = s.size() / 10;
std::string out;
const int n = 1 + pick(pick(4) == 0 ? 25 : 7);
for (int i = 0; i < n; ++i) out += s.substr((size_t)pick(10) * cp, cp);
return out;
}
std::string contraction() {
static const char* const base[] = { "it", "IT", "We", "they", "YOU", "i", "He" };
static const char* const suf[] = { "'s", "'S", "'t", "'T", "'re", "'RE", "'Re", "'rE", "'ve",
"'VE", "'m", "'M", "'ll", "'LL", "'lL", "'d", "'D", "'x", "'" };
return std::string(pick_of(base)) + pick_of(suf);
}
static constexpr const char* k_space[] = {
" ", " ", " ", " ", "\t", "\n", "\n\n", "\r\n", "\r", " \n", "\t\t", "\n ", " \n ",
"\xc2\xa0", "\xe3\x80\x80", "\xe2\x80\x80", "\xe2\x80\xa8", "\xe2\x80\xa9", "\xc2\x85",
"\x0b", "\x0c", "\xe1\x9a\x80", "\xe2\x80\xaf",
};
static constexpr const char* k_sequences[] = {
"e\xcc\x81", "a\xcc\x88\xcc\x81", "\xcc\x81", "\xcc\x81\xcc\x81", /* combining marks */
"\xf0\x9f\x91\xa8\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7", /* ZWJ family */
"\xf0\x9f\x91\x8d\xf0\x9f\x8f\xbd", "\xf0\x9f\x87\xaf\xf0\x9f\x87\xb5", /* skin tone, flag */
"\xe2\x9d\xa4\xef\xb8\x8f", "\xe2\x80\x8d", "\xe2\x80\x8b", "\xef\xbb\xbf",
"\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8", /* Hangul jamo */
"\xed\x95\x9c\xea\xb8\x80", "\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7", /* Hangul, Devanagari */
"\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d", "\xd9\x85\xd8\xb1\xd8\xad\xd8\xa8\xd8\xa7", /* RTL */
"\xe2\x80\x8f", "\xe2\x80\xae", "\xef\xbc\xa1\xef\xbc\x91", /* marks, fullwidth */
"\xc5\xbf", "'\xc5\xbf", /* long s */
};
static constexpr const char* k_punct[] = {
".", ",", "!", "?", "...", "->", "::", "();", "{}", "[]", "//", "/*", "*/", "#", "@", "$",
"%", "^", "&", "*", "_", "=", "+", "-", "`", "~", "|", "\\", "\"", "<", ">", "'", "\xe2\x80\x94",
"\xe2\x80\x9c", "\xe2\x80\x9d", "\xc2\xab", "\xe3\x80\x82", "\xc2\xbd", "\xc2\xb2", "\xe2\x91\xa0",
};
static constexpr const char* k_junk[] = {
"\xc3", "\xe4\xb8", "\xf0\x9f\x98", "\x80", "\xbf\xbf", "\xc0\x80", "\xc1\xbf", "\xe0\x80\x80",
"\xed\xa0\x80", "\xed\xbf\xbf", "\xf4\x90\x80\x80", "\xf5\x80\x80\x80", "\xf8\x88\x80\x80\x80",
"\xfe", "\xff", "\xf0\x80\x80\x80",
};
};
/* A byte-level BPE vocabulary trained on `corpus` pre-tokenised by `pattern`: 256 byte tokens,
* then one token per merge, `n_merges` of them (fewer if the pairs run out). Ties between equally
* frequent pairs go to the smaller (left id, right id), so the result is a function of the
* inputs. */
inline VocabBuild train_bytelevel(const std::string& corpus, const char* pattern, int n_merges) {
VocabBuild vb;
vb.kind = RAD_TOK_BPE;
for (int b = 0; b < 256; ++b) vb.tokens.push_back(bytelevel_char((uint8_t)b));
std::unique_ptr<TokRegex> re;
std::string why;
TokRegex::compile(pattern, &re, &why);
std::string canon;
std::string_view text = corpus;
if (!utf8_is_canonical(text)) { utf8_canonicalize(text, canon); text = canon; }
std::vector<TokSpan> pieces, scratch;
tok_split(*re, text, TOK_SPLIT_ISOLATED, false, pieces, scratch);
std::map<std::string, int> counts;
for (const TokSpan& p : pieces) ++counts[std::string(text.substr(p.begin, p.end - p.begin))];
std::vector<std::pair<std::vector<int32_t>, int>> words;
for (const auto& [w, c] : counts) {
std::vector<int32_t> ids;
for (unsigned char b : w) ids.push_back(b);
words.push_back({ ids, c });
}
std::unordered_map<uint64_t, long> pairs;
for (int m = 0; m < n_merges; ++m) {
pairs.clear();
for (const auto& [ids, c] : words)
for (size_t i = 0; i + 1 < ids.size(); ++i)
pairs[((uint64_t)(uint32_t)ids[i] << 32) | (uint32_t)ids[i + 1]] += c;
if (pairs.empty()) break;
uint64_t best = 0;
long best_n = -1;
for (const auto& [k, n] : pairs)
if (n > best_n || (n == best_n && k < best)) { best = k; best_n = n; }
const int32_t l = (int32_t)(best >> 32), r = (int32_t)(best & 0xFFFFFFFF);
const int32_t id = (int32_t)vb.tokens.size();
vb.tokens.push_back(vb.tokens[l] + vb.tokens[r]);
vb.merges.push_back({ (uint32_t)l, (uint32_t)r });
for (auto& [ids, c] : words) {
std::vector<int32_t> next;
for (size_t i = 0; i < ids.size(); ++i) {
if (i + 1 < ids.size() && ids[i] == l && ids[i + 1] == r) { next.push_back(id); ++i; }
else next.push_back(ids[i]);
}
ids.swap(next);
}
}
vb.types.assign(vb.tokens.size(), (uint8_t)RAD_TT_NORMAL);
return vb;
}
inline VocabStep split_step(const char* pattern) {
VocabStep s;
s.kind = RAD_PRE_SPLIT;
s.arg0 = pattern;
s.iarg = TOK_SPLIT_ISOLATED;
return s;
}
inline VocabStep bytelevel_step(bool prefix = false, bool regex = false) {
VocabStep s;
s.kind = RAD_PRE_BYTELEVEL;
s.flags = (prefix ? 1u : 0u) | (regex ? 2u : 0u);
return s;
}
inline VocabStep simple_step(uint32_t kind) {
VocabStep s;
s.kind = kind;
return s;
}
/* Add control tokens to a vocabulary. */
inline void add_specials(VocabBuild& vb, const std::vector<std::pair<std::string, uint8_t>>& specials) {
for (const auto& [text, type] : specials) {
vb.tokens.push_back(text);
vb.types.push_back(type);
}
}
inline std::shared_ptr<const Vocab> load(VocabBuild vb) {
auto v = std::make_shared<Vocab>();
if (v->load(std::move(vb)) < 0) return nullptr;
return v;
}
} /* namespace tokfix */
+184
View File
@@ -0,0 +1,184 @@
/* tokenizer_perf_test.cpp -- the tokeniser's speed, held to budgets.
*
* Tokenisation runs on the request path: an agent re-sends its whole conversation every turn and
* every byte of it is encoded before the first token can be generated. So speed is a property
* with a test:
*
* - throughput on prose-and-code text, against an absolute floor and against the reference
* encoder (tools/tokref) on the same text -- the ratio holds on a loaded machine where an
* absolute number would not;
* - LINEAR SCALING: twice the text takes about twice the time, on ordinary text and on the
* inputs a pre-tokeniser is quadratic on when it goes wrong (one enormous word, one
* enormous run of whitespace, digits, alternating classes);
* - the segment cache: the last turn of a long conversation costs a fraction of encoding it.
*
* Budgets are set well inside what this build does, so a failure is a regression and not noise.
* Every time is the best of several runs.
*/
#include "rad_test.h"
#include "tokenizer_fixture.h"
#include "tokref.h"
#include "rad_internal.h"
#include <chrono>
#include <cstdio>
#include <functional>
using namespace rad;
using namespace tokfix;
namespace {
double best_of(int n, const std::function<void()>& f) {
double best = 1e30;
for (int i = 0; i < n; ++i) {
const auto t0 = std::chrono::steady_clock::now();
f();
best = std::min(best, std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
}
return best;
}
/* Prose and code in the proportions an agent's conversation has them. */
std::string document(uint32_t seed, size_t bytes) {
static const char* words[] = {
"the", "cache", "is", "sharded", "by", "key", "and", "each", "shard", "has", "its", "own",
"lock", "so", "that", "readers", "never", "wait", "on", "writers", "of", "another", "we",
"measured", "it", "at", "requests", "per", "second", "with", "p99", "latency", "under",
"load", "tokenizer", "encode", "returns", "ids", "for", "text", "value", "struct", "func",
"return", "if", "else", "nil", "err", "string", "int", "len", "make", "map", "append",
"更新", "缓存", "naïve", "café", "über", "Straße", "ünïcode", "don't", "it's", "we'll",
};
static const char* punct[] = { ".", ",", ";", ":", "(", ")", "{", "}", "[", "]", " =", " :=",
" ==", " !=", " //", " ->", "\"", "'", "?", "!" };
std::mt19937 rng(seed);
std::string s;
while (s.size() < bytes) {
const int n = 3 + rng() % 14;
for (int k = 0; k < n; ++k) {
if (k) s += ' ';
s += words[rng() % (sizeof(words) / sizeof(words[0]))];
if (rng() % 5 == 0) s += punct[rng() % (sizeof(punct) / sizeof(punct[0]))];
if (rng() % 17 == 0) s += std::to_string(rng() % 100000);
}
s += rng() % 3 ? ".\n" : (rng() % 2 ? "\n\t" : "\n\n ");
}
return s;
}
std::shared_ptr<const Vocab> vocab() {
static std::shared_ptr<const Vocab> v = [] {
VocabBuild vb = train_bytelevel(document(1, 300000), k_qwen35, 1500);
vb.steps = { simple_step(RAD_NORM_NFC), split_step(k_qwen35), bytelevel_step() };
add_specials(vb, { { "<|im_start|>", RAD_TT_CONTROL }, { "<|im_end|>", RAD_TT_CONTROL } });
return load(std::move(vb));
}();
return v;
}
double encode_seconds(const Tokenizer& t, const std::string& text, int runs = 5) {
std::vector<int32_t> ids;
return best_of(runs, [&] { ids.clear(); t.encode(text, ids, false, true); });
}
} /* namespace */
TEST(throughput_has_a_floor_and_beats_the_reference) {
auto v = vocab();
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
t.set_segment_cache(false);
const std::string text = document(2, 2 << 20);
const double s = encode_seconds(t, text);
const double mbs = text.size() / s / 1e6;
std::vector<int32_t> ids;
const double r = best_of(2, [&] { ids.clear(); tokref::encode(*v, text, ids, false, true); });
std::fprintf(stderr, " %.1f MB/s (reference %.1f MB/s, %.1fx)\n", mbs, text.size() / r / 1e6, r / s);
CHECK(mbs > 25.0);
CHECK(r / s > 4.0);
}
/* TWICE THE TEXT, ABOUT TWICE THE TIME. The texts differ, so a cache that remembered one would
* not help the other; the ratio is allowed well past 2 because the larger one also walks more of
* memory. */
TEST(encoding_time_is_linear_in_the_text) {
auto v = vocab();
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
t.set_segment_cache(false);
const std::string one = document(3, 1 << 20), two = document(4, 2 << 20);
const double a = encode_seconds(t, one), b = encode_seconds(t, two);
std::fprintf(stderr, " 1 MB %.2f ms, 2 MB %.2f ms, ratio %.2f\n", a * 1e3, b * 1e3, b / a);
CHECK(b / a > 1.3);
CHECK(b / a < 2.8);
}
/* THE INPUTS A SPLITTER GOES QUADRATIC ON. A backtracking `\s+(?!\S)` rescans a whitespace run
* from every position in it, and a merge that is quadratic in the word shows on one enormous
* word; both must stay linear. */
TEST(pathological_inputs_stay_linear) {
auto v = vocab();
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
t.set_segment_cache(false);
const struct { const char* name; std::function<std::string(size_t)> make; } inputs[] = {
{ "one word", [](size_t n) { return std::string(n, 'a'); } },
{ "whitespace", [](size_t n) { return std::string(n, ' ') + "x"; } },
{ "mixed whitespace", [](size_t n) { std::string s; while (s.size() < n) s += " \t \n"; return s + "x"; } },
{ "digits", [](size_t n) { std::string s; while (s.size() < n) s += "0123456789"; return s; } },
{ "alternating", [](size_t n) { std::string s; while (s.size() < n) s += "a1!"; return s; } },
{ "apostrophes", [](size_t n) { std::string s; while (s.size() < n) s += "''s"; return s; } },
};
/* A megabyte and two, best of five: at a few hundred kilobytes one of these runs in a couple of
* milliseconds, which one preemption under a parallel ctest turns into a false quadratic. */
for (const auto& in : inputs) {
const std::string one = in.make(1000000), two = in.make(2000000);
const double a = encode_seconds(t, one, 5), b = encode_seconds(t, two, 5);
std::fprintf(stderr, " %-17s 1 MB %7.2f ms, 2 MB %7.2f ms, ratio %.2f\n", in.name,
a * 1e3, b * 1e3, b / a);
CHECK(b / a < 3.0);
}
}
/* THE LAST TURN OF A LONG CONVERSATION costs what is new in it. */
TEST(a_resent_conversation_costs_its_new_turn) {
auto v = vocab();
REQUIRE(v != nullptr);
Tokenizer plain, cached;
plain.init(v);
plain.set_segment_cache(false);
cached.init(v);
cached.clear_cache();
std::string conv;
std::vector<std::string> prompts;
for (int k = 0; k < 40; ++k) {
conv += std::string("<|im_start|>") + (k % 2 ? "assistant" : "user") + "\n" +
document(100 + k, 15000) + "<|im_end|>\n";
prompts.push_back(conv + "<|im_start|>assistant\n");
}
std::vector<int32_t> ids;
for (size_t k = 0; k + 1 < prompts.size(); ++k) { ids.clear(); cached.encode(prompts[k], ids, false, true); }
const std::string& last = prompts.back();
const double warm = best_of(1, [&] { ids.clear(); cached.encode(last, ids, false, true); });
const double cold = encode_seconds(plain, last, 3);
std::fprintf(stderr, " %zu bytes: uncached %.2f ms, cached %.2f ms (%.0fx)\n", last.size(),
cold * 1e3, warm * 1e3, cold / warm);
CHECK(warm * 5 < cold);
}
/* Compiling a shipped pattern is a load-time cost, paid once; it stays small. */
TEST(compiling_a_shipped_pattern_is_cheap) {
for (const char* p : { k_qwen35, k_minicpm, k_llama3, k_gpt2 }) {
std::unique_ptr<TokRegex> re;
std::string why;
const double s = best_of(3, [&] { re.reset(); TokRegex::compile(p, &re, &why); });
CHECK(re != nullptr);
CHECK(s < 0.05);
}
}
RAD_TEST_MAIN()
+617
View File
@@ -0,0 +1,617 @@
/* tokenizer_regex_test.cpp -- the pre-tokeniser pattern compiler, construct by construct.
*
* The expected splits are Oniguruma's: each table row was run through HuggingFace tokenizers'
* Split (behaviour and invert as given) and its pieces recorded, because that is the engine a
* tokenizer.json pattern is written for and the only definition of what one means. A row per
* construct the dialect covers -- escapes, classes and their set operations, every shorthand and
* property, groups, greedy and lazy quantifiers, the flags and their scope, anchors, one-codepoint
* lookaround, and the iteration rules for empty matches -- so a regression names the construct.
*
* Then the refusals: every construct outside the dialect must fail to compile, with a message
* that names it, since a pattern that does not compile is a vocabulary that does not load.
*/
#include "rad_test.h"
#include "rad_internal.h"
#include "text/tokenizer_regex.h"
#include <cstdio>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
using namespace rad;
using namespace std::literals;
namespace {
std::vector<std::string> split(const TokRegex& re, std::string_view text, int behavior = TOK_SPLIT_ISOLATED,
bool invert = false) {
std::vector<TokSpan> out, scratch;
tok_split(re, text, behavior, invert, out, scratch);
std::vector<std::string> pieces;
for (const TokSpan& s : out) pieces.emplace_back(text.substr(s.begin, s.end - s.begin));
return pieces;
}
std::string show(const std::vector<std::string>& v) {
std::string o = "[";
for (size_t i = 0; i < v.size(); ++i) {
if (i) o += ", ";
o += "'";
for (unsigned char c : v[i]) o += (c < 0x20 || c == 0x7F) ? fmt("\\x%02x", c) : std::string(1, (char)c);
o += "'";
}
return o + "]";
}
std::unique_ptr<TokRegex> compile(std::string_view pat) {
std::unique_ptr<TokRegex> re;
std::string why;
if (TokRegex::compile(pat, &re, &why) < 0) {
std::fprintf(stderr, " compile failed: %s\n", why.c_str());
return nullptr;
}
return re;
}
struct Case {
std::string_view name, pattern, text;
std::vector<std::string_view> pieces;
};
/* Recorded from HuggingFace tokenizers 0.23.2 (Oniguruma), Split(behavior="isolated"). */
const std::vector<Case> k_cases = {
{ "literal"sv,
"ab|."sv, "xabab"sv,
{ "x"sv, "ab"sv, "ab"sv } },
{ "escapes"sv,
"\\t|\\n|\\r|\\f|\\v|\\a|\\e|\\x41|\\x{1F600}|\xc3""\xa9""|\\0|."sv, "\x09""\x0a""\x0d""\x0c""\x0b""\x07""\x1b""A\xf0""\x9f""\x98""\x80""\xc3""\xa9""\x00""z"sv,
{ "\x09"""sv, "\x0a"""sv, "\x0d"""sv, "\x0c"""sv, "\x0b"""sv, "\x07"""sv, "\x1b"""sv, "A"sv, "\xf0""\x9f""\x98""\x80"""sv, "\xc3""\xa9"""sv, "\x00"""sv, "z"sv } },
{ "escaped metachar"sv,
"\\.|\\*|\\(|\\[|\\{|\\||\\\\|\\$|\\^|\\?|\\+|\\)|."sv, ".*([{|\\$^?+)x"sv,
{ "."sv, "*"sv, "("sv, "["sv, "{"sv, "|"sv, "\\"sv, "$"sv, "^"sv, "?"sv, "+"sv, ")"sv, "x"sv } },
{ "dot excludes newline"sv,
".+"sv, "ab\x0a""cd\x0d""\x0a""ef"sv,
{ "ab"sv, "\x0a"""sv, "cd\x0d"""sv, "\x0a"""sv, "ef"sv } },
{ "(?m) dot includes newline"sv,
"(?m:.)+"sv, "ab\x0a""cd"sv,
{ "ab\x0a""cd"sv } },
{ "control escape"sv,
"\\cA|."sv, "\x01""b"sv,
{ "\x01"""sv, "b"sv } },
{ "class range"sv,
"[a-c]+|."sv, "abcdcba"sv,
{ "abc"sv, "d"sv, "cba"sv } },
{ "negated class"sv,
"[^a-c]+|."sv, "xyzabc"sv,
{ "xyz"sv, "a"sv, "b"sv, "c"sv } },
{ "class with first ]"sv,
"[]a]+|."sv, "a]b"sv,
{ "a]"sv, "b"sv } },
{ "class with trailing -"sv,
"[a-]+|."sv, "a-b"sv,
{ "a-"sv, "b"sv } },
{ "class range from -"sv,
"[--/]+|."sv, "-./a"sv,
{ "-./"sv, "a"sv } },
{ "class with escapes"sv,
"[\\]\\[]+|."sv, "a[]b"sv,
{ "a"sv, "[]"sv, "b"sv } },
{ "class with shorthands"sv,
"[a\\d\\s]+|."sv, "a1 b"sv,
{ "a1 "sv, "b"sv } },
{ "nested class union"sv,
"[a-c[x-z]]+|."sv, "abxyzd"sv,
{ "abxyz"sv, "d"sv } },
{ "class intersection"sv,
"[a-z&&[^aeiou]]+|."sv, "bcdaefg"sv,
{ "bcd"sv, "a"sv, "e"sv, "fg"sv } },
{ "property intersection"sv,
"[\\p{L}&&\\p{Lu}]+|."sv, "aBC"sv,
{ "a"sv, "BC"sv } },
{ "negated intersection"sv,
"[^\\p{L}\\p{N}&&[^\\s]]+|."sv, "ab ,."sv,
{ "a"sv, "b"sv, " ,."sv } },
{ "bloom class"sv,
" ?[^(\\s|[.,!?\xe2""\x80""\xa6""\xe3""\x80""\x82""\xef""\xbc""\x8c""\xe3""\x80""\x81""\xe0""\xa5""\xa4""\xdb""\x94""\xd8""\x8c""])]+"sv, "hello, world. (x|y)"sv,
{ "hello"sv, ","sv, " world"sv, ". ("sv, "x"sv, "|"sv, "y"sv, ")"sv } },
{ "\\d \\D"sv,
"\\d+|\\D+"sv, "ab12\xd9""\xa3""\xe0""\xa5""\xaa""x"sv,
{ "ab"sv, "12\xd9""\xa3""\xe0""\xa5""\xaa"""sv, "x"sv } },
{ "\\s \\S"sv,
"\\s+|\\S+"sv, "a \x09""\xc2""\xa0""\xe3""\x80""\x80""b\xe2""\x80""\xa8""c"sv,
{ "a"sv, " \x09""\xc2""\xa0""\xe3""\x80""\x80"""sv, "b"sv, "\xe2""\x80""\xa8"""sv, "c"sv } },
{ "\\w atom counts the Latin-1 fractions"sv,
"\\w+"sv, "a\xc2""\xbd""b\xc2""\xb2""c\xe2""\x91""\xa0""d"sv,
{ "a\xc2""\xbd""b\xc2""\xb2""c"sv, "\xe2""\x91""\xa0"""sv, "d"sv } },
{ "\\w in a class does not"sv,
"[\\w]+"sv, "a\xc2""\xbd""b\xc2""\xb2""c\xe2""\x91""\xa0""d"sv,
{ "a"sv, "\xc2""\xbd"""sv, "b"sv, "\xc2""\xb2"""sv, "c"sv, "\xe2""\x91""\xa0"""sv, "d"sv } },
{ "\\h hex digit"sv,
"\\h+|."sv, "ab 09 xyz"sv,
{ "ab"sv, " "sv, "09"sv, " "sv, "x"sv, "y"sv, "z"sv } },
{ "letter property"sv,
"\\p{L}+|."sv, "h\xc3""\xa9""llo \xd0""\xbc""\xd0""\xb8""\xd1""\x80"" \xe4""\xb8""\x96""\xe7""\x95""\x8c"" 1"sv,
{ "h\xc3""\xa9""llo"sv, " "sv, "\xd0""\xbc""\xd0""\xb8""\xd1""\x80"""sv, " "sv, "\xe4""\xb8""\x96""\xe7""\x95""\x8c"""sv, " "sv, "1"sv } },
{ "negated property"sv,
"\\P{L}+|."sv, "ab12"sv,
{ "a"sv, "b"sv, "12"sv } },
{ "caret negated property"sv,
"\\p{^L}+|."sv, "ab12"sv,
{ "a"sv, "b"sv, "12"sv } },
{ "long property name"sv,
"\\p{Uppercase_Letter}+|."sv, "aBCd"sv,
{ "a"sv, "BC"sv, "d"sv } },
{ "property name normalisation"sv,
"\\p{ lu }+|."sv, "aBCd"sv,
{ "a"sv, "BC"sv, "d"sv } },
{ "subcategories"sv,
"\\p{Nd}+|\\p{No}+|\\p{Nl}+|."sv, "12\xc2""\xbd""\xe2""\x85""\xab""\xd9""\xa3"""sv,
{ "12"sv, "\xc2""\xbd"""sv, "\xe2""\x85""\xab"""sv, "\xd9""\xa3"""sv } },
{ "marks"sv,
"[\\p{Mn}\\p{Mc}\\p{Me}]+|."sv, "e\xcc""\x81""\xe0""\xa4""\x83""\xe2""\x83""\x9d"" x"sv,
{ "e"sv, "\xcc""\x81""\xe0""\xa4""\x83""\xe2""\x83""\x9d"""sv, " "sv, "x"sv } },
{ "script"sv,
"\\p{Han}+|\\p{Hiragana}+|\\p{Katakana}+|."sv, "\xe6""\xbc""\xa2""\xe5""\xad""\x97""\xe3""\x81""\xb2""\xe3""\x82""\x89""\xe3""\x81""\x8c""\xe3""\x81""\xaa""\xe3""\x82""\xab""\xe3""\x82""\xbf""\xe3""\x82""\xab""\xe3""\x83""\x8a""a"sv,
{ "\xe6""\xbc""\xa2""\xe5""\xad""\x97"""sv, "\xe3""\x81""\xb2""\xe3""\x82""\x89""\xe3""\x81""\x8c""\xe3""\x81""\xaa"""sv, "\xe3""\x82""\xab""\xe3""\x82""\xbf""\xe3""\x82""\xab""\xe3""\x83""\x8a"""sv, "a"sv } },
{ "separators and others"sv,
"[\\p{Zs}]+|[\\p{Cf}\\p{Co}\\p{Cn}]+|."sv, "a \xc2""\xa0""\xe2""\x80""\x8b""\xee""\x80""\x80""\xcd""\xb8""b"sv,
{ "a"sv, " \xc2""\xa0"""sv, "\xe2""\x80""\x8b""\xee""\x80""\x80""\xcd""\xb8"""sv, "b"sv } },
{ "leftmost-first alternation"sv,
"a|ab|abc"sv, "abc"sv,
{ "a"sv, "bc"sv } },
{ "alternation order inside groups"sv,
"(a|ab)(c|bcd)(d*)"sv, "abcd"sv,
{ "abcd"sv } },
{ "capturing and named groups"sv,
"(a)|(?:b)|(?<n>c)|."sv, "abcd"sv,
{ "a"sv, "b"sv, "c"sv, "d"sv } },
{ "comment group"sv,
"(?#comment)a|."sv, "ab"sv,
{ "a"sv, "b"sv } },
{ "empty alternative"sv,
"a|"sv, "bab"sv,
{ "b"sv, "a"sv, "b"sv } },
{ "empty first alternative"sv,
"|a"sv, "bab"sv,
{ "b"sv, "a"sv, "b"sv } },
{ "empty group"sv,
"(?:)"sv, "ab"sv,
{ "a"sv, "b"sv } },
{ "greedy star"sv,
"a*"sv, "baab"sv,
{ "b"sv, "aa"sv, "b"sv } },
{ "lazy star"sv,
"a*?"sv, "baab"sv,
{ "b"sv, "a"sv, "a"sv, "b"sv } },
{ "lazy plus"sv,
"a+?b|."sv, "aaab"sv,
{ "aaab"sv } },
{ "lazy interval"sv,
"a{2,3}?|."sv, "aaaaa"sv,
{ "aa"sv, "aa"sv, "a"sv } },
{ "interval"sv,
"a{2}|."sv, "aaa"sv,
{ "aa"sv, "a"sv } },
{ "open interval"sv,
"a{2,}|."sv, "aaa b"sv,
{ "aaa"sv, " "sv, "b"sv } },
{ "interval without minimum"sv,
"a{,2}|."sv, "aaa"sv,
{ "aa"sv, "a"sv } },
{ "zero interval"sv,
"a{0}|."sv, "ab"sv,
{ "a"sv, "b"sv } },
{ "literal brace"sv,
"a{x}|{|."sv, "a{x}{"sv,
{ "a{x}"sv, "{"sv } },
{ "counted group"sv,
"(?:a{2}){2,3}|."sv, "aaaaaaa"sv,
{ "aaaaaa"sv, "a"sv } },
{ "optional inside counted"sv,
"(a?){3}b|."sv, "aab"sv,
{ "aab"sv } },
{ "star over alternation"sv,
"(?:a|ab)*c|."sv, "ababc"sv,
{ "ababc"sv } },
{ "digit groups"sv,
"\\p{N}{1,3}"sv, "1234567 12"sv,
{ "123"sv, "456"sv, "7"sv, " "sv, "12"sv } },
{ "(?i) group"sv,
"(?i:[a-c])+|."sv, "ABCabcd"sv,
{ "ABCabc"sv, "d"sv } },
{ "(?i) Kelvin sign"sv,
"(?i:k)+|."sv, "kK\xe2""\x84""\xaa"""sv,
{ "kK\xe2""\x84""\xaa"""sv } },
{ "(?i) long s"sv,
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|\\p{L}+|."sv, "it'\xc5""\xbf""x 'S '\xc5""\xbf"" 'K 'LL 'Re"sv,
{ "it"sv, "'\xc5""\xbf"""sv, "x"sv, " "sv, "'S"sv, " "sv, "'\xc5""\xbf"""sv, " "sv, "'"sv, "K"sv, " "sv, "'LL"sv, " "sv, "'Re"sv } },
{ "(?i) negated class"sv,
"(?i:[^a-z])+|."sv, "aA1B"sv,
{ "a"sv, "A"sv, "1"sv, "B"sv } },
{ "(?i) to the end of the group"sv,
"a(?i)b|c"sv, "aBcC ab"sv,
{ "aB"sv, "cC "sv, "ab"sv } },
{ "(?i) then (?-i)"sv,
"(?i)a(?-i:b)|."sv, "AbAB"sv,
{ "Ab"sv, "A"sv, "B"sv } },
{ "(?i) scoped"sv,
"(?i:a)b|."sv, "AbAB"sv,
{ "Ab"sv, "A"sv, "B"sv } },
{ "(?x) extended"sv,
"(?x: a b # comment\x0a"" )+|."sv, "abab"sv,
{ "abab"sv } },
{ "line anchors"sv,
"^a|b$|\\n"sv, "ab\x0a""ab\x0a""a\x0a""b"sv,
{ "a"sv, "b"sv, "\x0a"""sv, "a"sv, "b"sv, "\x0a"""sv, "a"sv, "\x0a"""sv, "b"sv } },
{ "line start and end"sv,
"^.|.$"sv, "xy\x0a""zw"sv,
{ "x"sv, "y"sv, "\x0a"""sv, "z"sv, "w"sv } },
{ "dollar before newline"sv,
"\\s+$|\\S+|\\s+"sv, "a \x0a"" b "sv,
{ "a"sv, " "sv, "\x0a"" "sv, "b"sv, " "sv } },
{ "text anchors"sv,
"\\A.|.\\z"sv, "abc"sv,
{ "a"sv, "b"sv, "c"sv } },
{ "empty dollar matches"sv,
"$"sv, "a\x0a""b"sv,
{ "a"sv, "\x0a""b"sv } },
{ "empty caret matches"sv,
"^"sv, "ab\x0a""cd"sv,
{ "ab\x0a"""sv, "cd"sv } },
{ "word boundary"sv,
"\\ba|."sv, "a ba a"sv,
{ "a"sv, " "sv, "b"sv, "a"sv, " "sv, "a"sv } },
{ "not word boundary"sv,
"\\B.|x"sv, "ab cd"sv,
{ "a"sv, "b"sv, " c"sv, "d"sv } },
{ "empty word boundaries"sv,
"\\b"sv, "ab cd"sv,
{ "ab"sv, " "sv, "cd"sv } },
{ "word boundary over a fraction"sv,
"\\b"sv, "a\xc2""\xbd"" b"sv,
{ "a\xc2""\xbd"""sv, " "sv, "b"sv } },
{ "negative lookahead"sv,
"x(?!y)|."sv, "xyxz x"sv,
{ "x"sv, "y"sv, "x"sv, "z"sv, " "sv, "x"sv } },
{ "the \\s+(?!\\S) idiom"sv,
"\\s+(?!\\S)|\\s+"sv, "a b "sv,
{ "a"sv, " "sv, " "sv, "b"sv, " "sv } },
{ "positive lookahead"sv,
"(?=[\\p{L}])[^a-z]+|."sv, "ABcD\xc3""\xa9"""sv,
{ "AB"sv, "c"sv, "D\xc3""\xa9"""sv } },
{ "empty lookahead matches"sv,
"(?=a)"sv, "baab"sv,
{ "b"sv, "a"sv, "ab"sv } },
{ "lookbehind"sv,
"(?<=a)b|."sv, "abcb"sv,
{ "a"sv, "b"sv, "c"sv, "b"sv } },
{ "negative lookbehind"sv,
"(?<!a)b|."sv, "abcb"sv,
{ "a"sv, "b"sv, "c"sv, "b"sv } },
{ "lookbehind of a class"sv,
"(?<=\\s)\\S+|\\s+|\\S+"sv, "ab cd ef"sv,
{ "ab"sv, " "sv, "cd"sv, " "sv, "ef"sv } },
{ "empty match after a match is skipped"sv,
"x*|b"sv, "abc"sv,
{ "a"sv, "b"sv, "c"sv } },
};
struct Behaviour {
std::string_view pattern, text;
int behavior;
bool invert;
std::vector<std::string_view> pieces;
};
/* The same, for every SplitDelimiterBehavior with and without invert. */
const std::vector<Behaviour> k_behaviours = {
{ "\\s+"sv, " hello big world "sv, 0, false,
{ "hello"sv, "big"sv, "world"sv } },
{ "\\s+"sv, " hello big world "sv, 0, true,
{ " "sv, " "sv, " "sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 1, false,
{ " "sv, "hello"sv, " "sv, "big"sv, " "sv, "world"sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 1, true,
{ " "sv, "hello"sv, " "sv, "big"sv, " "sv, "world"sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 2, false,
{ " "sv, "hello "sv, "big "sv, "world "sv } },
{ "\\s+"sv, " hello big world "sv, 2, true,
{ " hello"sv, " big"sv, " world"sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 3, false,
{ " hello"sv, " big"sv, " world"sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 3, true,
{ " "sv, "hello "sv, "big "sv, "world "sv } },
{ "\\s+"sv, " hello big world "sv, 4, false,
{ " "sv, "hello"sv, " "sv, "big"sv, " "sv, "world"sv, " "sv } },
{ "\\s+"sv, " hello big world "sv, 4, true,
{ " "sv, "hello"sv, " "sv, "big"sv, " "sv, "world"sv, " "sv } },
{ "[,.]"sv, "a,b..c,"sv, 0, false,
{ "a"sv, "b"sv, "c"sv } },
{ "[,.]"sv, "a,b..c,"sv, 0, true,
{ ","sv, "."sv, "."sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 1, false,
{ "a"sv, ","sv, "b"sv, "."sv, "."sv, "c"sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 1, true,
{ "a"sv, ","sv, "b"sv, "."sv, "."sv, "c"sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 2, false,
{ "a,"sv, "b."sv, "."sv, "c,"sv } },
{ "[,.]"sv, "a,b..c,"sv, 2, true,
{ "a"sv, ",b"sv, "."sv, ".c"sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 3, false,
{ "a"sv, ",b"sv, "."sv, ".c"sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 3, true,
{ "a,"sv, "b."sv, "."sv, "c,"sv } },
{ "[,.]"sv, "a,b..c,"sv, 4, false,
{ "a"sv, ","sv, "b"sv, ".."sv, "c"sv, ","sv } },
{ "[,.]"sv, "a,b..c,"sv, 4, true,
{ "a"sv, ","sv, "b"sv, ".."sv, "c"sv, ","sv } },
{ "\\d+"sv, "12ab345c6"sv, 0, false,
{ "ab"sv, "c"sv } },
{ "\\d+"sv, "12ab345c6"sv, 0, true,
{ "12"sv, "345"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 1, false,
{ "12"sv, "ab"sv, "345"sv, "c"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 1, true,
{ "12"sv, "ab"sv, "345"sv, "c"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 2, false,
{ "12"sv, "ab345"sv, "c6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 2, true,
{ "12ab"sv, "345c"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 3, false,
{ "12ab"sv, "345c"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 3, true,
{ "12"sv, "ab345"sv, "c6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 4, false,
{ "12"sv, "ab"sv, "345"sv, "c"sv, "6"sv } },
{ "\\d+"sv, "12ab345c6"sv, 4, true,
{ "12"sv, "ab"sv, "345"sv, "c"sv, "6"sv } },
{ "x*"sv, "axxbx"sv, 0, false,
{ "a"sv, "b"sv } },
{ "x*"sv, "axxbx"sv, 0, true,
{ "xx"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 1, false,
{ "a"sv, "xx"sv, "b"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 1, true,
{ "a"sv, "xx"sv, "b"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 2, false,
{ "axx"sv, "bx"sv } },
{ "x*"sv, "axxbx"sv, 2, true,
{ "a"sv, "xxb"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 3, false,
{ "a"sv, "xxb"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 3, true,
{ "axx"sv, "bx"sv } },
{ "x*"sv, "axxbx"sv, 4, false,
{ "a"sv, "xx"sv, "b"sv, "x"sv } },
{ "x*"sv, "axxbx"sv, 4, true,
{ "a"sv, "xx"sv, "b"sv, "x"sv } },
{ "$"sv, "a\x0a""b"sv, 0, false,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 0, true,
{ } },
{ "$"sv, "a\x0a""b"sv, 1, false,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 1, true,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 2, false,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 2, true,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 3, false,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 3, true,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 4, false,
{ "a"sv, "\x0a""b"sv } },
{ "$"sv, "a\x0a""b"sv, 4, true,
{ "a"sv, "\x0a""b"sv } },
};
} /* namespace */
TEST(every_construct_splits_as_oniguruma_does) {
for (const Case& c : k_cases) {
auto re = compile(c.pattern);
REQUIRE(re != nullptr);
const std::vector<std::string> got = split(*re, c.text);
std::vector<std::string> want(c.pieces.begin(), c.pieces.end());
CHECK(got == want);
if (got != want)
std::fprintf(stderr, " %.*s: /%.*s/\n got %s\n want %s\n", (int)c.name.size(),
c.name.data(), (int)c.pattern.size(), c.pattern.data(), show(got).c_str(),
show(want).c_str());
}
}
TEST(every_split_behaviour_and_invert_folds_as_huggingface_does) {
for (const Behaviour& b : k_behaviours) {
auto re = compile(b.pattern);
REQUIRE(re != nullptr);
const std::vector<std::string> got = split(*re, b.text, b.behavior, b.invert);
std::vector<std::string> want(b.pieces.begin(), b.pieces.end());
CHECK(got == want);
if (got != want)
std::fprintf(stderr, " /%.*s/ behaviour %d invert %d\n got %s\n want %s\n",
(int)b.pattern.size(), b.pattern.data(), b.behavior, b.invert ? 1 : 0,
show(got).c_str(), show(want).c_str());
}
}
/* match_at is the primitive find_iter is built from: the leftmost-FIRST match anchored at a
* position, which is not the longest one. */
TEST(match_at_is_leftmost_first_not_longest) {
auto re = compile("a|ab|abc");
REQUIRE(re != nullptr);
CHECK_EQ(re->match_at("abc", 0), (int64_t)1);
auto greedy = compile("a+");
REQUIRE(greedy != nullptr);
CHECK_EQ(greedy->match_at("aaab", 0), (int64_t)3);
CHECK_EQ(greedy->match_at("aaab", 3), (int64_t)-1);
auto lazy = compile("a+?");
REQUIRE(lazy != nullptr);
CHECK_EQ(lazy->match_at("aaab", 0), (int64_t)1);
/* The lookahead is decided by the codepoint after the match, including the end of the text. */
auto ws = compile("\\s+(?!\\S)");
REQUIRE(ws != nullptr);
CHECK_EQ(ws->match_at(" x", 0), (int64_t)2);
CHECK_EQ(ws->match_at(" ", 0), (int64_t)3);
CHECK_EQ(ws->match_at(" x", 0), (int64_t)-1);
}
/* EVERY CONSTRUCT OUTSIDE THE DIALECT IS REFUSED BY NAME. The phrase checked is the one a reader
* of the load error needs to find the construct in a 200-character pattern. */
TEST(constructs_outside_the_dialect_are_refused_by_name) {
const struct { const char* pattern; const char* says; } refused[] = {
{ "(a)\\1", "backreference" },
{ "\\k<n>", "backreference" },
{ "(?>a+)", "atomic group" },
{ "a++", "possessive" },
{ "a*+", "possessive" },
{ "a{2}{3}", "quantifier applied to a quantifier" },
{ "a{1,2}+", "quantifier applied to a quantifier" },
{ "a**", "quantifier applied to a quantifier" },
{ "\\d{1,3}(?=(?:\\d{3})*\\b)", "lookaround wider than one codepoint" },
{ "(?=ab)", "lookaround wider than one codepoint" },
{ "(?<=ab)c", "lookaround wider than one codepoint" },
{ "(?i:\xc3\x9f)", "multi-codepoint" }, /* U+00DF matches "ss" */
{ "(?i:[a-\xc3\xbf])", "multi-codepoint" }, /* the range holds U+00DF */
{ "(?i:[a-z&&[^k]])", "intersection under (?i)" },
{ "(?i:[\\p{Lu}])", "property inside a class under (?i)" },
{ "(?i:[a[b]])", "nested class under (?i)" },
{ "(a*)*", "can match empty" },
{ "(?:|a)+", "can match empty" },
{ "(?:^)*", "quantifier on an assertion" },
{ "^*", "quantifier on an assertion" },
{ "[[:alpha:]]", "POSIX bracket" },
{ "\\p{Alphabetic}", "property the tables do not carry" },
{ "\\p{InBasicLatin}", "property the tables do not carry" },
{ "\\p{Klingon}", "property the tables do not carry" },
{ "\\pL", "without braces" },
{ "\\Z", "\\Z" },
{ "\\G", "\\G" },
{ "\\R", "\\R" },
{ "\\X", "\\X" },
{ "\\K", "\\K" },
{ "\\Qa.b\\E", "\\Q" },
{ "\\y", "unknown escape" },
{ "(?s:.)", "unknown group option" },
{ "(?~abc)", "absent operator" },
{ "a{1001}", "above 1000" },
{ "a{3,2}", "minimum exceeds its maximum" },
{ "*a", "nothing to repeat" },
{ "(ab", "unterminated group" },
{ "ab)", "unmatched ')'" },
{ "[ab", "unterminated character class" },
{ "[b-a]", "out of order" },
{ "\\x{110000}", "above U+10FFFF" },
{ "\xff", "not UTF-8" },
};
for (const auto& r : refused) {
std::unique_ptr<TokRegex> re;
std::string why;
const int st = TokRegex::compile(r.pattern, &re, &why);
CHECK_EQ(st, RAD_E_UNSUPPORTED);
CHECK(why.find(r.says) != std::string::npos);
if (why.find(r.says) == std::string::npos)
std::fprintf(stderr, " /%s/ refused with \"%s\", expected it to name \"%s\"\n",
r.pattern, why.c_str(), r.says);
}
}
/* THE PATTERNS MODELS SHIP compile, and to small machines: a pre-tokeniser DFA that needed
* thousands of states would be a sign the construction had gone wrong, not a feature of the
* pattern. */
TEST(shipped_patterns_compile_to_small_dfas) {
const char* shipped[] = {
/* Qwen3.5 / 3.6 / 3.8 */
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* MiniCPM5 */
"\\p{N}{1,3}",
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}+| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* Llama 3 */
"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* GPT-2 */
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",
/* o200k */
"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* Kimi K2 */
"[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* DeepSeek V3 */
"[\xe4\xb8\x80-\xe9\xbe\xa5\xe3\x81\x80-\xe3\x82\x9f\xe3\x82\xa0-\xe3\x83\xbf]+",
"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\\r\\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
/* DeepSeek Coder */
"\\s+$", "[\\r\\n]",
/* BLOOM */
" ?[^(\\s|[.,!?\xe2\x80\xa6\xe3\x80\x82\xef\xbc\x8c\xe3\x80\x81\xe0\xa5\xa4\xdb\x94\xd8\x8c])]+",
/* llama.cpp's gpt-4o adaptation */
"[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
"[^\\n]+|[\\n]+", "\\S+", "[\\p{P}\\$\\+<=>\\^~\\|]+", "[0-9][0-9][0-9]",
};
for (const char* p : shipped) {
auto re = compile(p);
CHECK(re != nullptr);
if (!re) continue;
CHECK(re->n_states() < 200);
CHECK(re->n_classes() < 64);
}
}
/* ================================================================== the text a split sees */
TEST(canonical_utf8_is_exactly_what_round_trips) {
const struct { std::string_view s; bool canonical; } cases[] = {
{ ""sv, true }, { "abc"sv, true }, { "\xc3\xa9"sv, true }, { "\xe4\xb8\xad"sv, true },
{ "\xf0\x9f\x98\x80"sv, true }, { "\xf4\x8f\xbf\xbf"sv, true },
{ "\xed\xa0\x80"sv, true }, /* a surrogate decodes and re-encodes as itself */
{ "\xc3"sv, false }, { "\x80"sv, false }, { "\xc0\x80"sv, false }, { "\xc1\xbf"sv, false },
{ "\xe0\x80\x80"sv, false }, { "\xe0\x9f\xbf"sv, false }, { "\xf0\x80\x80\x80"sv, false },
{ "\xf0\x8f\xbf\xbf"sv, false }, { "\xf4\x90\x80\x80"sv, false }, { "\xf5\x80\x80\x80"sv, false },
{ "\xf8\x88\x80\x80\x80"sv, false }, { "\xff"sv, false }, { "ab\xe4\xb8"sv, false },
{ "abcdefgh\xc3"sv, false }, /* past the eight-byte ASCII stride */
};
for (const auto& c : cases) {
CHECK_EQ(utf8_is_canonical(c.s), c.canonical);
std::string out;
utf8_canonicalize(c.s, out);
CHECK_EQ(out == c.s, c.canonical);
CHECK(utf8_is_canonical(out));
}
/* The decoder's rules: one U+FFFD per byte that starts nothing decodable, overlong forms
* shortened, surrogates kept. */
const std::string fffd = "\xef\xbf\xbd";
const struct { std::string_view in; std::string out; } fix[] = {
{ "\xc3"sv, fffd },
{ "\xe4\xb8" "a"sv, fffd + fffd + "a" },
{ "\xc0\x80"sv, std::string(1, '\0') },
{ "\xe0\x80\xaf"sv, "/" },
{ "\xf0\x82\x82\xac"sv, "\xe2\x82\xac" },
{ "\xf4\x90\x80\x80"sv, fffd + fffd + fffd + fffd },
{ "\xf8\x88\x80\x80\x80"sv, fffd + fffd + fffd + fffd + fffd },
{ "\xed\xa0\x80"sv, "\xed\xa0\x80" },
};
for (const auto& f : fix) {
std::string out;
utf8_canonicalize(f.in, out);
CHECK(out == f.out);
}
}
/* Replace follows HuggingFace: the content is inserted verbatim, `$` included, at every match,
* empty ones too. */
TEST(replace_inserts_the_content_verbatim) {
auto re = compile("\\s+");
REQUIRE(re != nullptr);
std::string out;
tok_replace(*re, "a b\t\nc ", "$1_", out);
CHECK(out == "a$1_b$1_c$1_");
auto empty = compile("x*");
REQUIRE(empty != nullptr);
out.clear();
tok_replace(*empty, "ab", "-", out);
CHECK(out == "-a-b-");
}
RAD_TEST_MAIN()
+710
View File
@@ -0,0 +1,710 @@
/* tokenizer_test.cpp -- the encoder against its reference, and the parts under it.
*
* THE REFERENCE is tools/tokref: an encoder built on llama.cpp's structural splitters, std::regex
* for every other pattern and a string-keyed merge. It shares no code with what it checks. The
* differential tests here hold the engine's splitter and encoder (`encode_new`) to it over tens of
* thousands of random strings, and every place the two are ALLOWED to differ is a place the
* reference is wrong about HuggingFace -- tokref.h lists them -- so each one has its own test
* saying exactly what the difference is and that the engine's side is HuggingFace's answer.
*
* Then the parts: the merge on small vocabularies whose answers are worked out by hand, the linear
* and heap merges against each other, special-token priority, the NFC shortcut against the full
* normaliser, and the segment cache -- cold, warm, evicted, across a growing conversation, and
* under concurrent encodes.
*/
#include "rad_test.h"
#include "tokenizer_fixture.h"
#include "tokref.h"
#include "rad_internal.h"
#include "text/tokenizer_bpe.h"
#include "text/tokenizer_nfc.h"
#include "text/unicode_norm.h"
#include "llama/src/unicode.h"
#include <atomic>
#include <cstdio>
#include <map>
#include <thread>
using namespace rad;
using namespace tokfix;
namespace {
/* ------------------------------------------------------------------ helpers */
/* Compiled once per pattern: compiling is a load-time cost and the tests split thousands of
* strings with each one. */
const TokRegex* compiled(const char* pattern) {
static std::map<std::string, std::unique_ptr<TokRegex>> cache;
auto it = cache.find(pattern);
if (it == cache.end()) {
std::unique_ptr<TokRegex> re;
std::string why;
TokRegex::compile(pattern, &re, &why);
it = cache.emplace(pattern, std::move(re)).first;
}
return it->second.get();
}
std::vector<std::string> new_split(const char* pattern, const std::string& word) {
const TokRegex* re = compiled(pattern);
if (!re) return { "<refused>" };
std::string canon;
std::string_view v = word;
if (!utf8_is_canonical(v)) { utf8_canonicalize(v, canon); v = canon; }
std::vector<TokSpan> out, scratch;
tok_split(*re, v, TOK_SPLIT_ISOLATED, false, out, scratch);
std::vector<std::string> pieces;
for (const TokSpan& s : out) pieces.emplace_back(v.substr(s.begin, s.end - s.begin));
return pieces;
}
std::string escaped(const std::string& s) {
std::string o;
for (unsigned char c : s) {
if (c >= 0x20 && c < 0x7F && c != '\\') o += (char)c;
else o += fmt("\\x%02x", c);
}
return o;
}
std::string show(const std::vector<std::string>& v) {
std::string o;
for (const std::string& p : v) o += "[" + escaped(p) + "]";
return o;
}
std::string show_ids(const std::vector<int32_t>& v, size_t from = 0, size_t n = 12) {
std::string o;
for (size_t i = from; i < v.size() && i < from + n; ++i) o += fmt("%d ", v[i]);
return o;
}
/* Where llama.cpp's category tables (Unicode 15.1) and the compiler's (Oniguruma, 16.0) put a
* codepoint in different categories. */
bool tables_disagree(uint32_t c) {
const auto f = unicode_cpt_flags_from_cpt(c);
const uint32_t g = gc_of(c);
const bool L = g <= ucd::Lo, M = g >= ucd::Mn && g <= ucd::Me, N = g >= ucd::Nd && g <= ucd::No;
const bool P = g >= ucd::Pc && g <= ucd::Po, S = g >= ucd::Sm && g <= ucd::So;
return f.is_letter != L || f.is_accent_mark != M || f.is_number != N ||
f.is_punctuation != P || f.is_symbol != S;
}
std::vector<int32_t> encode_new(const Tokenizer& t, const std::string& s, bool parse_special = true) {
std::vector<int32_t> ids;
t.encode(s, ids, false, parse_special);
return ids;
}
std::vector<int32_t> encode_ref(const Vocab& v, const std::string& s, bool parse_special = true) {
std::vector<int32_t> ids;
tokref::encode(v, s, ids, false, parse_special);
return ids;
}
/* Compare the two encoders over `n` texts from `gen`; report the first few differences. */
template <class Gen>
int compare_encoders(const char* what, std::shared_ptr<const Vocab> v, int n, Gen gen,
bool parse_special = true) {
Tokenizer t;
t.init(v);
t.set_segment_cache(false);
int bad = 0;
for (int i = 0; i < n; ++i) {
const std::string s = gen(i);
const std::vector<int32_t> a = encode_new(t, s, parse_special), b = encode_ref(*v, s, parse_special);
if (a == b) continue;
if (++bad <= 3) {
size_t k = 0;
while (k < a.size() && k < b.size() && a[k] == b[k]) ++k;
std::fprintf(stderr, " %s: differs at id %zu for '%s'\n new %s\n ref %s\n", what, k,
escaped(s.substr(0, 200)).c_str(), show_ids(a, k > 3 ? k - 3 : 0).c_str(),
show_ids(b, k > 3 ? k - 3 : 0).c_str());
}
}
return bad;
}
/* The corpus the trained vocabularies learn from: code, prose, every script. */
std::string training_corpus() {
TextGen g(7);
std::string s;
for (int i = 0; i < 400; ++i) s += g.text(60) + "\n";
return s;
}
const VocabBuild& trained() {
static const VocabBuild vb = train_bytelevel(training_corpus(), k_qwen35, 1200);
return vb;
}
} /* namespace */
/* ================================================================== splits against the reference */
/* THE SPLITTER AGAINST THE REFERENCE, on every pattern the reference implements: its structural
* splitters (GPT-2, Llama-3, Qwen2, Qwen3.5, in both spellings llama.cpp keys them on,
* and "[^\n]+|[\n]+") and patterns it runs through std::regex (MiniCPM5's two, the GGUF defaults,
* the gpt-4o adaptation). The text has every general category, marks and ZWJ sequences, CJK,
* Hangul and RTL, digit runs of every length, every kind of whitespace including CRLF and the
* Unicode spaces, contractions in mixed case, and bytes that are not UTF-8.
*
* Two inputs are held out, each with its own test below: the codepoints the two category tables
* disagree on, and -- for the `(?i)` spelling only -- an apostrophe before U+017F. */
TEST(splits_match_the_reference_splitters) {
struct P { const char* pattern; bool ci; };
const P patterns[] = {
{ "'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)", false },
{ "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", false },
{ k_llama3, true },
{ "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", false },
{ "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", true },
{ "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", false },
{ k_qwen35, true },
{ "[^\\n]+|[\\n]+", false },
{ k_minicpm_digits, false },
{ k_minicpm, true },
{ "[\\p{P}\\$\\+<=>\\^~\\|]+", false },
{ "\\p{N}+", false },
{ "[0-9][0-9][0-9]", false },
{ "\\S+", false },
{ "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", false },
};
const std::string long_s = "'\xc5\xbf";
size_t compared = 0;
for (const P& p : patterns) {
TextGen g(1234);
int bad = 0;
/* Few long strings rather than many short ones: the reference builds a std::regex per
* call for the patterns it has no splitter for. */
for (int i = 0; i < 160; ++i) {
const std::string s = g.text(1 + g.pick(i < 80 ? 40 : 1200), /*junk=*/true, tables_disagree);
if (p.ci && s.find(long_s) != std::string::npos) continue;
const std::vector<std::string> a = new_split(p.pattern, s), b = tokref::split(p.pattern, s);
compared += s.size();
if (a == b) continue;
if (++bad <= 3)
std::fprintf(stderr, " /%.60s/ on '%s'\n new %s\n ref %s\n", p.pattern,
escaped(s.substr(0, 300)).c_str(), show(a).c_str(), show(b).c_str());
}
CHECK_EQ(bad, 0);
}
CHECK(compared > (size_t)15 << 20 >> 4);
}
/* Digit runs of every length and whitespace of every shape, exhaustively, since the structural
* splitters special-case both. */
TEST(splits_match_the_reference_on_every_digit_run_and_whitespace_run) {
const char* patterns[] = { k_llama3, k_qwen35,
"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)" };
const char* ws[] = { " ", "\t", "\n", "\r", "\r\n", "\xc2\xa0", "\xe3\x80\x80", "\x0b", "\xe2\x80\xa8" };
int bad = 0;
for (const char* p : patterns) {
for (int n = 1; n <= 24; ++n) {
for (const char* before : { "", "a", " ", "x ", "!" }) {
for (const char* after : { "", "a", " ", "\n", "," }) {
const std::string s = std::string(before) + std::string((size_t)n, '7') + after;
if (new_split(p, s) != tokref::split(p, s)) ++bad;
}
}
}
for (int mask = 1; mask < 4096; mask += 7) {
std::string s = "w";
for (int k = 0, m = mask; k < 4; ++k, m /= 9) s += ws[m % 9];
for (const char* after : { "", "x", "!", "1", "\n" }) {
const std::string t = s + after;
if (new_split(p, t) != tokref::split(p, t)) ++bad;
}
}
}
CHECK_EQ(bad, 0);
}
/* ================================================================== where the reference is wrong */
/* THE REFERENCE REWRITES `(?i:'s|...)` INTO `'[sS]|...`, which loses U+017F: Oniguruma folds
* LATIN SMALL LETTER LONG S to 's', so "'ſ" is a contraction to HuggingFace. The pieces below are
* HuggingFace's. Only the (?i) spelling is affected; llama.cpp's expanded one has no ſ in it. */
TEST(long_s_is_a_contraction_under_case_folding_as_in_huggingface) {
const std::string s = "x'\xc5\xbfy it'S";
const std::vector<std::string> want = { "x", "'\xc5\xbf", "y", " it", "'S" };
CHECK(new_split(k_qwen35, s) == want);
CHECK(tokref::split(k_qwen35, s) != want);
const char* expanded =
"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
CHECK(new_split(expanded, s) == tokref::split(expanded, s));
}
/* THE TWO CATEGORY TABLES DIFFER BY UNICODE 16.0 AND BY NOTHING ELSE: every codepoint they
* disagree on is unassigned in llama.cpp's and assigned in Oniguruma's, and there are 5185 of
* them. A split over one of them follows Oniguruma's category, as HuggingFace does -- U+10D40 GARAY
* DIGIT ZERO is a digit and U+10D6E GARAY HYPHEN is punctuation. */
TEST(the_category_tables_differ_only_by_what_unicode_16_assigned) {
size_t n = 0, bad = 0;
for (uint32_t c = 0; c < 0x110000; ++c) {
if (c >= 0xD800 && c <= 0xDFFF) continue;
if (!tables_disagree(c)) continue;
++n;
if (!unicode_cpt_flags_from_cpt(c).is_undefined || gc_of(c) == ucd::Cn) ++bad;
}
CHECK_EQ(n, (size_t)5185);
CHECK_EQ(bad, (size_t)0);
const std::string s = "a\xf0\x90\xb5\x80" "b!\xf0\x90\xb5\xae.";
const std::vector<std::string> want = { "a", "\xf0\x90\xb5\x80", "b", "!\xf0\x90\xb5\xae." };
CHECK(new_split(k_qwen35, s) == want);
CHECK(tokref::split(k_qwen35, s) != want);
}
/* `\p{Han}+` IS NOT KIMI-K2's PATTERN, it is llama.cpp's key for a splitter approximating it.
* The GGUF table carries the real pattern, whose letter classes split camel case. */
TEST(the_kimi_k2_entry_is_the_real_pattern) {
const char* k2 =
"[\\p{Han}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}&&[^\\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+";
const std::string s = "HelloWorld \xe4\xb8\xad\xe6\x96\x87" "ABc";
const std::vector<std::string> want = { "Hello", "World", " ", "\xe4\xb8\xad\xe6\x96\x87", "ABc" };
CHECK(new_split(k2, s) == want);
CHECK(tokref::split("\\p{Han}+", s) != want);
}
/* A digit-grouping lookahead is refused rather than run through a rule that means something
* else: llama.cpp's AFMoE splitter splits "12345abc", the pattern does not. */
TEST(a_wide_lookahead_is_refused_where_the_reference_approximated_it) {
std::unique_ptr<TokRegex> re;
std::string why;
CHECK_EQ(TokRegex::compile("\\d{1,3}(?=(?:\\d{3})*\\b)", &re, &why), RAD_E_UNSUPPORTED);
CHECK(why.find("lookaround") != std::string::npos);
VocabBuild vb = trained();
vb.steps = { split_step("\\d{1,3}(?=(?:\\d{3})*\\b)"), bytelevel_step() };
auto v = std::make_shared<Vocab>();
CHECK_EQ(v->load(std::move(vb)), RAD_E_UNSUPPORTED);
CHECK(!v->ready());
}
/* ================================================================== BPE by hand */
namespace {
/* A byte-level vocabulary small enough to work every answer out on paper. "c c" merges to text
* that is not a token, which blocks "c ab" -> "cab" behind it; "Ġab" is a user-defined token the
* raw text can only reach through the byte-level mapping. */
const char* k_tiny = R"JSON({
"added_tokens": [ {"id": 12, "content": "<|end|>", "special": true},
{"id": 13, "content": "Ġab", "special": false} ],
"pre_tokenizer": { "type": "Sequence", "pretokenizers": [
{"type": "Split", "pattern": {"Regex": " ?\\p{L}+|\\p{N}|\\s+|[^\\s\\p{L}\\p{N}]+"}, "behavior": "Isolated"},
{"type": "ByteLevel", "add_prefix_space": false, "use_regex": false} ] },
"decoder": { "type": "ByteLevel" },
"model": { "type": "BPE",
"vocab": {"a": 0, "b": 1, "c": 2, "Ġ": 3, "ab": 4, "bc": 5, "abc": 6, "Ġa": 7, "aa": 8, "1": 9,
"cab": 10, "x": 11},
"merges": ["a b", "b c", "ab c", "Ġ a", "a a", "c c", "c ab"] }
})JSON";
/* SentencePiece-shaped: Metaspace, codepoint symbols, "<0xNN>" byte fallback. */
const char* k_spm = R"JSON({
"pre_tokenizer": { "type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": false },
"decoder": { "type": "Metaspace", "replacement": "▁", "prepend_scheme": "always" },
"model": { "type": "BPE", "byte_fallback": true,
"vocab": {"<unk>": 0, "▁": 1, "h": 2, "i": 3, "▁h": 4, "▁hi": 5, "<0xE2>": 6, "<0x82>": 7, "<0xAC>": 8},
"merges": ["▁ h", "▁h i"] }
})JSON";
std::shared_ptr<const Vocab> from_json(const char* js, int32_t unk = -1) {
VocabBuild vb;
if (parse_tokenizer_json_buf(js, "test.json", vb) < 0) return nullptr;
if (unk >= 0) vb.unk = unk;
return load(std::move(vb));
}
} /* namespace */
TEST(bpe_merges_as_worked_out_by_hand) {
auto v = from_json(k_tiny);
REQUIRE(v != nullptr);
Tokenizer t;
CHECK_OK(t.init(v));
t.set_segment_cache(false);
const struct { const char* text; bool parse_special; std::vector<int32_t> ids; } cases[] = {
{ "abc", true, { 6 } }, /* a b -> ab (rank 0), ab c -> abc (2) */
{ "bcab", true, { 5, 4 } }, /* a b first (0), then b c (1); bc ab has no rank */
{ "aaa", true, { 8, 0 } }, /* two equal ranks: the leftmost pair merges */
{ "cc", true, { 2, 2 } }, /* merged into text that is no token: spelled by byte */
{ "ccab", true, { 2, 2, 4 } }, /* and that merge (5) blocks c ab (6) */
{ " a", true, { 7 } },
{ " ab", true, { 13 } }, /* "Ġab" is user-defined: taken whole */
{ "abx", true, { 4, 11 } },
{ "1a", true, { 9, 0 } },
{ "a<|end|>b", true, { 0, 12, 1 } },
{ "a<|end|>b", false, { 0, 1 } }, /* not parsed: its bytes have no tokens, dropped */
};
for (const auto& c : cases) {
const std::vector<int32_t> got = encode_new(t, c.text, c.parse_special);
CHECK(got == c.ids);
CHECK(encode_ref(*v, c.text, c.parse_special) == c.ids);
if (got != c.ids) std::fprintf(stderr, " '%s': %s\n", c.text, show_ids(got).c_str());
}
}
TEST(byte_fallback_and_unk_follow_the_declared_chain) {
auto v = from_json(k_spm);
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
CHECK(encode_new(t, "hi") == (std::vector<int32_t>{ 5 }));
CHECK(encode_new(t, "hi\xe2\x82\xac") == (std::vector<int32_t>{ 5, 6, 7, 8 })); /* the euro sign, by byte */
CHECK(encode_new(t, "hix") == (std::vector<int32_t>{ 5 })); /* no <0x78>, no unk: dropped */
auto u = from_json(k_spm, 0);
REQUIRE(u != nullptr);
Tokenizer tu;
tu.init(u);
CHECK(encode_new(tu, "hix") == (std::vector<int32_t>{ 5, 0 })); /* no <0x78>: unk */
for (const char* s : { "hi", "hi\xe2\x82\xac", "hix", "h i hi", "\xe2\x82\xac\xe2\x82\xac" }) {
CHECK(encode_new(t, s) == encode_ref(*v, s));
CHECK(encode_new(tu, s) == encode_ref(*u, s));
}
}
/* THE LINEAR AND HEAP MERGES PICK THE SAME PAIR AT EVERY STEP: lowest rank, then leftmost. Held
* to each other on random words over a random merge table dense enough that most words merge
* many times, with results that are and are not tokens. */
TEST(linear_and_heap_merges_agree) {
std::mt19937 rng(99);
MergeTable mt;
const int n_ids = 24;
for (uint32_t r = 0; r < 300; ++r) {
const int32_t l = (int32_t)(rng() % n_ids), rr = (int32_t)(rng() % n_ids);
const int32_t merged = rng() % 5 == 0 ? -1 : (int32_t)(rng() % n_ids);
mt.insert(l, rr, r, merged);
}
int bad = 0;
for (int i = 0; i < 20000; ++i) {
std::vector<BpeSym> a;
const size_t n = 1 + rng() % kBpeLinearMax;
for (size_t k = 0; k < n; ++k) a.push_back({ (uint32_t)k, 1, (int32_t)(rng() % n_ids) });
std::vector<BpeSym> b = a;
bpe_merge(a, mt, false);
bpe_merge(b, mt, true);
bool same = a.size() == b.size();
for (size_t k = 0; same && k < a.size(); ++k)
same = a[k].start == b[k].start && a[k].len == b[k].len && a[k].id == b[k].id;
if (!same) ++bad;
}
CHECK_EQ(bad, 0);
}
/* ================================================================== the whole encoder against the reference */
/* Trained vocabularies, every chain shape the encoder takes a different route through: the
* byte-level fast path (Split then ByteLevel, merged on raw bytes), two Splits, ByteLevel with
* its own regex and prefix space, ByteLevel before a Split (the mapped text is split and merged),
* NFC, special and user-defined tokens including one that is a prefix of another, SentencePiece's
* Metaspace with byte fallback, WordPiece and Unigram. */
TEST(the_encoder_matches_the_reference_on_trained_vocabularies) {
const std::vector<std::pair<std::string, uint8_t>> specials = {
{ "<|im_start|>", RAD_TT_CONTROL }, { "<|im_end|>", RAD_TT_CONTROL }, { "<|im", RAD_TT_CONTROL },
{ "XYZ", RAD_TT_CONTROL }, { "YZWV", RAD_TT_CONTROL }, { "<think>", RAD_TT_USER_DEFINED },
{ "</think>", RAD_TT_USER_DEFINED }, { "Wv", RAD_TT_USER_DEFINED },
};
auto with = [&](std::vector<VocabStep> steps, bool add_sp = true) {
VocabBuild vb = trained();
vb.steps = std::move(steps);
if (add_sp) add_specials(vb, specials);
return load(std::move(vb));
};
auto gen_for = [&](uint32_t seed, bool no_long_s) {
auto g = std::make_shared<TextGen>(seed);
return [g, no_long_s](int) {
std::string s;
const int parts = 1 + g->pick(5);
for (int k = 0; k < parts; ++k) {
s += g->text(g->pick(60), true, tables_disagree);
static const char* inject[] = { "<|im_start|>", "<|im_end|>", "<|im", "XYZWV", "XYZ",
"YZWV", "<think>", "</think>", "Wv", "WWv" };
if (g->pick(2)) s += inject[g->pick(10)];
}
if (no_long_s) {
for (size_t p; (p = s.find("'\xc5\xbf")) != std::string::npos; ) s.replace(p, 1, "_");
}
return s;
};
};
VocabStep nfc = simple_step(RAD_NORM_NFC);
struct Chain { const char* name; std::shared_ptr<const Vocab> v; bool ci; };
const Chain chains[] = {
{ "split+bytelevel", with({ split_step(k_qwen35), bytelevel_step() }), true },
{ "nfc+split+bytelevel", with({ nfc, split_step(k_qwen35), bytelevel_step() }), true },
{ "two splits", with({ split_step(k_minicpm_digits), split_step(k_minicpm), bytelevel_step() }), true },
{ "bytelevel regex", with({ bytelevel_step(true, true) }), false },
{ "bytelevel then split", with({ bytelevel_step(), split_step("\\S+|\\s+") }), false },
{ "gpt2 without \\s+", with({ split_step("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)"), bytelevel_step() }), false },
};
uint32_t seed = 500;
for (const Chain& c : chains) {
REQUIRE(c.v != nullptr);
for (bool ps : { true, false })
CHECK_EQ(compare_encoders(c.name, c.v, 500, gen_for(seed++, c.ci), ps), 0);
}
/* SentencePiece-shaped: codepoint symbols and byte fallback, no byte-level mapping. */
{
VocabBuild vb;
vb.kind = RAD_TOK_BPE;
for (int b = 0; b < 256; ++b) vb.tokens.push_back(fmt("<0x%02X>", b));
vb.types.assign(256, (uint8_t)RAD_TT_BYTE);
const std::vector<std::string> base = { "\xe2\x96\x81", "a", "b", "c", "d", "e", "h", "i",
"l", "o", "t", "\xe4\xb8\x96", "\xe7\x95\x8c" };
for (const std::string& t : base) { vb.tokens.push_back(t); vb.types.push_back(RAD_TT_NORMAL); }
auto id = [&](const std::string& t) {
for (size_t i = 0; i < vb.tokens.size(); ++i) if (vb.tokens[i] == t) return (uint32_t)i;
return UINT32_MAX;
};
const std::vector<std::pair<std::string, std::string>> merges = {
{ "\xe2\x96\x81", "t" }, { "h", "e" }, { "\xe2\x96\x81t", "he" }, { "l", "l" },
{ "ll", "o" }, { "e", "llo" }, { "h", "ello" }, { "\xe2\x96\x81", "hello" },
{ "\xe4\xb8\x96", "\xe7\x95\x8c" }, { "a", "b" }, { "ab", "c" }, { "\xe2\x96\x81", "abc" },
};
for (const auto& [l, r] : merges) {
if (id(l + r) == UINT32_MAX) { vb.tokens.push_back(l + r); vb.types.push_back(RAD_TT_NORMAL); }
vb.merges.push_back({ id(l), id(r) });
}
VocabStep ms;
ms.kind = RAD_PRE_METASPACE;
ms.arg0 = "\xe2\x96\x81";
ms.iarg = 2;
vb.steps = { ms, simple_step(RAD_PRE_BYTE_FALLBACK) };
add_specials(vb, specials);
auto v = load(std::move(vb));
REQUIRE(v != nullptr);
CHECK_EQ(compare_encoders("spm", v, 800, gen_for(seed++, false)), 0);
}
/* WordPiece and Unigram over the trained vocabulary's pieces. */
{
VocabBuild vb;
vb.kind = RAD_TOK_WORDPIECE;
vb.tokens = { "[UNK]", "the", "cache", "##s", "##ing", "sh", "##ard", "val", "##ue", "a", "##b",
"\xe4\xb8\x96", "##\xe7\x95\x8c", ",", "." };
vb.unk = 0;
vb.steps = { simple_step(RAD_NORM_LOWERCASE), simple_step(RAD_PRE_WHITESPACE) };
auto v = load(std::move(vb));
REQUIRE(v != nullptr);
CHECK_EQ(compare_encoders("wordpiece", v, 800, gen_for(seed++, false)), 0);
}
{
VocabBuild vb = trained();
vb.kind = RAD_TOK_UNIGRAM;
vb.merges.clear();
vb.scores.resize(vb.tokens.size());
for (size_t i = 0; i < vb.tokens.size(); ++i) vb.scores[i] = -1.0f - 0.001f * (float)(i % 997);
vb.tokens.push_back("<unk>");
vb.types.push_back(RAD_TT_UNKNOWN);
vb.scores.push_back(0.0f);
vb.unk = (int32_t)vb.tokens.size() - 1;
VocabStep ms;
ms.kind = RAD_PRE_METASPACE;
ms.arg0 = "\xe2\x96\x81";
ms.iarg = 1;
ms.flags = 1;
vb.steps = { simple_step(RAD_NORM_STRIP), ms };
auto v = load(std::move(vb));
REQUIRE(v != nullptr);
CHECK_EQ(compare_encoders("unigram", v, 400, gen_for(seed++, false)), 0);
}
}
/* SPECIAL TOKENS ARE CLAIMED LONGEST FIRST, not leftmost: "bcde" wins over "ab" in "abcde" even
* though "ab" starts earlier, and "<|im_start|>" is never cut by its prefix "<|im". */
TEST(special_tokens_are_claimed_by_priority) {
VocabBuild vb = trained();
vb.steps = { split_step(k_qwen35), bytelevel_step() };
const int32_t base = (int32_t)vb.tokens.size();
add_specials(vb, { { "ab", RAD_TT_CONTROL }, { "bcde", RAD_TT_CONTROL },
{ "<|im", RAD_TT_CONTROL }, { "<|im_start|>", RAD_TT_CONTROL } });
auto v = load(std::move(vb));
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
const std::vector<int32_t> ids = encode_new(t, "abcde");
REQUIRE(ids.size() == 2);
CHECK_EQ(ids[1], base + 1);
CHECK(ids == encode_ref(*v, "abcde"));
CHECK(encode_new(t, "x<|im_start|>y<|im") == encode_ref(*v, "x<|im_start|>y<|im"));
const std::vector<int32_t> im = encode_new(t, "<|im_start|>");
CHECK(im == (std::vector<int32_t>{ base + 3 }));
/* Not parsed, a control token is text. */
CHECK(encode_new(t, "<|im_start|>", false) != im);
CHECK(encode_new(t, "<|im_start|>", false) == encode_ref(*v, "<|im_start|>", false));
}
/* ================================================================== NFC */
/* NORMALISING ONLY AROUND WHAT CAN CHANGE IS NORMALISING THE WHOLE TEXT. Every codepoint on its
* own, then random runs of starters, marks in and out of canonical order, Hangul jamo, composed
* and decomposed forms, and bytes that are not UTF-8. */
TEST(nfc_between_boundaries_is_the_whole_text_normalised) {
size_t bad = 0;
for (uint32_t c = 0; c < 0x110000; ++c) {
if (c >= 0xD800 && c <= 0xDFFF) continue;
std::string s = cp_utf8(c);
const std::string want = unorm_utf8(s, false, true);
tok_nfc(s);
if (s != want) ++bad;
}
CHECK_EQ(bad, (size_t)0);
static const char* parts[] = {
"a", "e", "o", "A", " ", "x", "\xcc\x81", "\xcc\x80", "\xcc\x88", "\xcc\xa3", "\xcc\x9b",
"\xcd\x85", "\xe0\xb9\x88", "\xd6\xb0", "\xe1\x84\x80", "\xe1\x85\xa1", "\xe1\x86\xa8",
"\xea\xb0\x80", "\xc3\xa9", "\xc3\x85", "\xe2\x84\xab", "\xef\xac\x81", "\xe2\x80\x8d",
"\xf0\x90\xbd\x8a", "\xe0\xbb\x8b", "\xe0\xbd\xb3", "\xcd\x84", "\xe4\xb8\x96", "\xc3",
"\x80", "\xed\xa0\x80", "\xc0\x80", "\xf4\x90\x80\x80", "abcdefgh",
};
std::mt19937 rng(5);
for (int i = 0; i < 100000; ++i) {
std::string s;
const int n = 1 + rng() % 12;
for (int k = 0; k < n; ++k) s += parts[rng() % (sizeof(parts) / sizeof(parts[0]))];
const std::string want = unorm_utf8(s, false, true);
std::string got = s;
const bool touched = tok_nfc(got);
/* Untouched means already normalised; touched text may still come out as it went in. */
if (got != want || (!touched && want != s)) ++bad;
}
CHECK_EQ(bad, (size_t)0);
}
/* ================================================================== the segment cache */
namespace {
std::shared_ptr<const Vocab> chat_vocab() {
static std::shared_ptr<const Vocab> v = [] {
VocabBuild vb = trained();
vb.steps = { simple_step(RAD_NORM_NFC), split_step(k_qwen35), bytelevel_step() };
add_specials(vb, { { "<|im_start|>", RAD_TT_CONTROL }, { "<|im_end|>", RAD_TT_CONTROL },
{ "<think>", RAD_TT_USER_DEFINED } });
return load(std::move(vb));
}();
return v;
}
/* A conversation: every turn is every message so far, framed as a chat template frames them. */
std::vector<std::string> conversation(uint32_t seed, int turns) {
TextGen g(seed);
std::vector<std::string> prompts;
std::string conv = "<|im_start|>system\nYou are a coding agent.<|im_end|>\n";
for (int k = 0; k < turns; ++k) {
const char* role = k % 2 ? "assistant" : "user";
conv += std::string("<|im_start|>") + role + "\n" + (k % 3 == 1 ? "<think>\n" : "") +
g.text(50 + g.pick(400)) + "<|im_end|>\n";
prompts.push_back(conv + "<|im_start|>assistant\n");
}
return prompts;
}
} /* namespace */
TEST(the_cache_returns_what_encoding_returns_cold_warm_and_evicted) {
auto v = chat_vocab();
REQUIRE(v != nullptr);
Tokenizer plain, cached;
plain.init(v);
plain.set_segment_cache(false);
cached.init(v);
cached.clear_cache();
cached.set_cache_limit(Tokenizer::kSegmentCacheDefault);
const std::vector<std::string> prompts = conversation(11, 12);
const std::string& last = prompts.back();
const std::vector<int32_t> want = encode_new(plain, last);
CHECK(encode_new(cached, last) == want); /* cold */
const Tokenizer::CacheStats cold = cached.cache_stats();
CHECK(cold.entries > 0);
CHECK(encode_new(cached, last) == want); /* warm */
const Tokenizer::CacheStats warm = cached.cache_stats();
CHECK(warm.hits >= cold.entries);
CHECK(warm.bytes <= warm.limit);
/* A bound smaller than the conversation evicts, and what is left still answers exactly. */
cached.set_cache_limit(cold.bytes / 3);
const Tokenizer::CacheStats small = cached.cache_stats();
CHECK(small.bytes <= small.limit);
CHECK(small.entries < cold.entries);
for (int k = 0; k < 3; ++k) CHECK(encode_new(cached, last) == want);
CHECK(cached.cache_stats().bytes <= cold.bytes / 3);
/* No room at all: every segment is encoded, nothing is kept. */
cached.set_cache_limit(0);
CHECK_EQ(cached.cache_stats().entries, (size_t)0);
CHECK(encode_new(cached, last) == want);
CHECK_EQ(cached.cache_stats().entries, (size_t)0);
cached.set_cache_limit(Tokenizer::kSegmentCacheDefault);
}
/* A GROWING CONVERSATION costs its new turn: every earlier message is a hit, and the ids of every
* turn are the uncached ids. */
TEST(the_cache_serves_a_growing_conversation_exactly) {
auto v = chat_vocab();
REQUIRE(v != nullptr);
Tokenizer plain, cached;
plain.init(v);
plain.set_segment_cache(false);
cached.init(v);
cached.clear_cache();
const std::vector<std::string> prompts = conversation(21, 30);
uint64_t prev_hits = 0;
for (size_t k = 0; k < prompts.size(); ++k) {
CHECK(encode_new(cached, prompts[k]) == encode_new(plain, prompts[k]));
const Tokenizer::CacheStats s = cached.cache_stats();
/* Turn k re-sends k earlier messages; each long enough to cache is a hit. */
if (k >= 2) CHECK(s.hits - prev_hits >= k / 2);
prev_hits = s.hits;
}
/* A segment under the minimum is never cached. */
cached.clear_cache();
encode_new(cached, "<|im_start|>user\nhi<|im_end|>");
CHECK_EQ(cached.cache_stats().entries, (size_t)0);
}
/* CONCURRENT ENCODES, sharing prefixes and evicting under each other, each get the uncached
* answer. */
TEST(the_cache_is_exact_under_concurrent_encodes) {
auto v = chat_vocab();
REQUIRE(v != nullptr);
Tokenizer plain;
plain.init(v);
plain.set_segment_cache(false);
std::vector<std::vector<std::string>> convs;
std::vector<std::vector<std::vector<int32_t>>> want;
for (uint32_t c = 0; c < 4; ++c) {
convs.push_back(conversation(100 + c, 16));
want.emplace_back();
for (const std::string& p : convs.back()) want.back().push_back(encode_new(plain, p));
}
Tokenizer shared;
shared.init(v);
shared.clear_cache();
/* Small enough that the threads evict each other's segments. */
shared.set_cache_limit(64 << 10);
std::atomic<int> bad{ 0 };
std::vector<std::thread> threads;
for (int t = 0; t < 8; ++t) {
threads.emplace_back([&, t] {
const size_t c = (size_t)t % convs.size();
for (int round = 0; round < 3; ++round)
for (size_t k = 0; k < convs[c].size(); ++k)
if (encode_new(shared, convs[c][k]) != want[c][k]) ++bad;
});
}
for (std::thread& th : threads) th.join();
CHECK_EQ(bad.load(), 0);
const Tokenizer::CacheStats s = shared.cache_stats();
CHECK(s.bytes <= s.limit);
CHECK(s.hits > 0);
shared.set_cache_limit(Tokenizer::kSegmentCacheDefault);
}
RAD_TEST_MAIN()
+396
View File
@@ -0,0 +1,396 @@
/* trigger_test.cpp -- the lazy grammar's trigger: the word scanner, and the grammar around it.
*
* The scanner is checked against the plain definition of what it computes -- after each piece,
* search everything fed so far for every word and take the leftmost start -- over enough random
* streams, with a small alphabet so that words overlap, prefix one another and repeat inside
* themselves, that the failure-link construction is exercised rather than trusted. The grammar is
* checked the same way one level up: a lazy grammar that has fired must be in exactly the state an
* eager grammar reaches when it is handed the text from the word onward, which the two masks
* show. The costs are checked as costs: waiting on a trigger has to be as cheap on the last token
* of a long reply as on the first, because it runs on the scheduler thread for every one.
*/
#include "rad_test.h"
#include "sample/gbnf.h"
#include "sample/grammar.h"
#include "sample/vocab_view.h"
#include "sample/word_scan.h"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <random>
#include <string>
#include <vector>
using namespace rad;
/* ================================================================== the scanner */
namespace {
struct Hit {
long piece = -1;
uint64_t start = WordScanner::npos;
bool operator==(const Hit& o) const { return piece == o.piece && start == o.start; }
};
/* What the scanner is defined to compute, by brute force over the whole text so far. */
Hit oracle(const std::vector<std::string>& words, const std::vector<std::string>& pieces) {
std::string buf;
for (size_t i = 0; i < pieces.size(); ++i) {
buf += pieces[i];
uint64_t best = WordScanner::npos;
for (const std::string& w : words) {
const size_t p = buf.find(w);
if (p != std::string::npos && p < best) best = p;
}
if (best != WordScanner::npos) return { (long)i, best };
}
return {};
}
Hit scan(const WordScanner& sc, const std::vector<std::string>& pieces) {
WordScanner::State st;
for (size_t i = 0; i < pieces.size(); ++i) {
const uint64_t s = sc.feed(st, pieces[i].data(), pieces[i].size());
if (s != WordScanner::npos) return { (long)i, s };
}
return {};
}
WordScanner built(const std::vector<std::string>& words) {
WordScanner sc;
std::string err;
const int st = sc.build(words, &err);
if (st < 0) radtest::fail(__FILE__, __LINE__, "build failed: " + err);
return sc;
}
} /* namespace */
TEST(scanner_finds_a_word_split_across_pieces) {
const WordScanner sc = built({ "<tool_call>\n" });
CHECK(scan(sc, { "Sure, ", "<tool", "_call", ">", "\n", "{" }) == (Hit{ 4, 6 }));
CHECK(scan(sc, { "<tool_call>" }) == Hit{});
CHECK(scan(sc, { "x<tool_call>\ny" }) == (Hit{ 0, 1 }));
}
/* Of the occurrences completing in one piece the leftmost start wins, and an occurrence that has
* not completed yet does not count however early it began. */
TEST(scanner_reports_the_leftmost_start_among_completed_words) {
const WordScanner sc = built({ "bc", "abcd" });
CHECK(scan(sc, { "abcd" }) == (Hit{ 0, 0 }));
CHECK(scan(sc, { "abc", "d" }) == (Hit{ 0, 1 }));
CHECK(scan(sc, { "a", "b", "c" }) == (Hit{ 2, 1 }));
}
TEST(scanner_on_the_classic_overlapping_set) {
const WordScanner sc = built({ "he", "she", "his", "hers" });
CHECK(scan(sc, { "ushers" }) == (Hit{ 0, 1 }));
CHECK(scan(sc, { "us", "hers" }) == (Hit{ 1, 1 })); /* "she" spans the split */
CHECK(scan(sc, { "ahishers" }) == (Hit{ 0, 1 }));
}
TEST(scanner_on_words_that_overlap_themselves) {
CHECK(scan(built({ "aab" }), { "aaab" }) == (Hit{ 0, 1 }));
CHECK(scan(built({ "abab" }), { "abaabab" }) == (Hit{ 0, 3 }));
CHECK(scan(built({ "aaa" }), { "a", "a", "a", "a" }) == (Hit{ 2, 0 }));
}
TEST(scanner_on_multibyte_and_zero_bytes) {
const std::string arrow = "\xE2\x86\x92";
const WordScanner sc = built({ arrow + "call", std::string("\0x", 2) });
CHECK(scan(sc, { "go \xE2\x86", "\x92" "ca", "ll" }) == (Hit{ 2, 3 }));
CHECK(scan(sc, { std::string("ab\0", 3), "x" }) == (Hit{ 1, 2 }));
CHECK(scan(sc, { "\xE2\x86\x93" "call" }) == Hit{});
}
TEST(scanner_refuses_an_empty_word_and_matches_nothing_without_words) {
WordScanner sc;
std::string err;
CHECK_EQ(sc.build({ "ok", "" }, &err), RAD_E_INVAL);
CHECK(!err.empty());
const WordScanner none = built({});
CHECK(none.empty());
CHECK(scan(none, { "anything", "at all" }) == Hit{});
}
/* A copied state continues exactly as the original: the speculative window depends on it. */
TEST(scanner_state_copies_are_exact) {
const WordScanner sc = built({ "<tool_call>\n", "[TOOL" });
WordScanner::State a;
CHECK_EQ(sc.feed(a, "text <tool_c", 12), WordScanner::npos);
WordScanner::State b = a;
CHECK_EQ(sc.feed(b, "all>x", 5), WordScanner::npos);
CHECK_EQ(sc.feed(a, "all>\n", 5), 5u);
CHECK_EQ(b.off, 17u);
}
TEST(scanner_agrees_with_the_definition_on_random_streams) {
/* Five symbols, one of them the lead byte of a multi-byte sequence, so that most random words
* share prefixes and suffixes with one another and with themselves. */
const char alpha[] = { 'a', 'b', 'c', '\xE2', '\n' };
std::mt19937 rng(20240917u);
auto pick = [&](int lo, int hi) { return std::uniform_int_distribution<int>(lo, hi)(rng); };
int matched = 0;
for (int iter = 0; iter < 20000; ++iter) {
std::vector<std::string> words((size_t)pick(1, 6));
for (auto& w : words) {
w.resize((size_t)pick(1, 7));
for (char& c : w) c = alpha[pick(0, 4)];
}
std::vector<std::string> pieces((size_t)pick(0, 60));
for (auto& p : pieces) {
p.resize((size_t)pick(0, 6));
for (char& c : p) c = alpha[pick(0, 4)];
}
const WordScanner sc = built(words);
const Hit want = oracle(words, pieces);
const Hit got = scan(sc, pieces);
if (!(got == want)) {
std::string ws;
for (auto& w : words) ws += "'" + w + "' ";
radtest::fail(__FILE__, __LINE__, "iteration " + std::to_string(iter) + " words " +
ws + "want piece " + std::to_string(want.piece) + " start " +
std::to_string((long long)want.start) + ", got piece " +
std::to_string(got.piece) + " start " +
std::to_string((long long)got.start));
return;
}
matched += want.piece >= 0;
}
CHECK(matched > 5000); /* the generator reaches matches, not only misses */
}
/* One table load a byte, at any length: the second half of a stream costs what the first did. */
TEST(scanner_cost_is_linear_in_the_stream) {
const WordScanner sc = built({ "<tool_call>\n", "<function=" });
std::mt19937 rng(7u);
std::string text(size_t(32) << 20, ' ');
for (char& c : text) c = (char)(' ' + (int)(rng() % 90));
auto run = [&](size_t n) {
WordScanner::State st;
uint64_t sink = 0;
const auto t0 = std::chrono::steady_clock::now();
for (size_t i = 0; i + 4 <= n; i += 4) sink += sc.feed(st, text.data() + i, 4);
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
CHECK(sink != 1);
return s;
};
/* Best of three, since ctest runs this beside other suites: the question is what the scan
* costs, not what the machine was doing. 40 MB/s is 100 ns for a four-byte token. */
auto best = [&](size_t n) { return std::min({ run(n), run(n), run(n) }); };
const double half = best(text.size() / 2), full = best(text.size());
const double mb_s = (double)text.size() / (1 << 20) / full;
std::printf(" scanner: %.0f MB/s in 4-byte pieces, full/half %.2f\n", mb_s, full / half);
CHECK(mb_s > 40.0);
CHECK(full / half < 2.6);
}
/* ================================================================== the lazy grammar */
namespace {
/* Characters, the pieces a tokeniser might split the trigger into, the marker as one control
* token, and an end-of-generation token. */
struct Vocab {
SimpleVocab v;
int32_t marker = -1, nl = -1, close = -1, eog = -1;
std::vector<int32_t> letters, prose;
Vocab() {
for (char c = 'a'; c <= 'z'; ++c) letters.push_back(v.add(std::string(1, c)));
prose = letters;
for (const char* p : { " ", ",", ".", "<", ">", "/", "_", "tool", "call", "xx<tool",
"_call>\n", "<tool_c", "all>", "ok ", "\n\n" })
prose.push_back(v.add(p));
nl = v.add("\n");
marker = v.add("<tool_call>");
close = v.add("</tool_call>");
eog = v.add("<|end|>", true);
prose.push_back(nl);
prose.push_back(marker);
}
int64_t n() const { return v.n_tokens(); }
};
const char* kCall = R"(root ::= "<tool_call>\n" [a-z]+ ("," [a-z]+)* "\n</tool_call>")";
std::unique_ptr<GbnfGrammar> make(const Vocab& vb, bool lazy,
const std::vector<std::string>& words,
const std::vector<int32_t>& tokens) {
std::unique_ptr<GbnfGrammar> g;
std::string err;
if (GbnfGrammar::create(kCall, "root", &vb.v, lazy, words, tokens, &g, &err) < 0)
radtest::fail(__FILE__, __LINE__, "create: " + err);
return g;
}
std::vector<uint32_t> mask_of(const GbnfGrammar& g, int64_t n) {
std::vector<uint32_t> m((size_t)bitmask_words(n), 0u);
const int st = g.fill_mask(m.data(), (int64_t)m.size());
if (st < 0) m.assign(m.size(), 0xDEADBEEFu);
return m;
}
bool admits(const std::vector<uint32_t>& m, int32_t id) {
return (m[(size_t)id >> 5] >> ((uint32_t)id & 31u)) & 1u;
}
} /* namespace */
TEST(lazy_grammar_waits_then_constrains_from_the_word) {
Vocab vb;
auto g = make(vb, true, { "<tool_call>\n" }, {});
for (int32_t t : { vb.letters[7], vb.letters[8], vb.prose[26] }) CHECK_OK(g->accept_token(t));
CHECK(g->awaiting_trigger());
CHECK_OK(g->accept_token(vb.marker));
CHECK(g->awaiting_trigger()); /* the word ends with the newline */
CHECK_OK(g->accept_token(vb.nl));
CHECK(!g->awaiting_trigger());
const auto m = mask_of(*g, vb.n());
CHECK(admits(m, vb.letters[0]));
CHECK(!admits(m, vb.marker));
CHECK(!admits(m, vb.nl));
}
/* The word may begin inside a token and end inside another; only its own bytes are replayed. */
TEST(lazy_grammar_replays_from_inside_a_token) {
Vocab vb;
auto lazy = make(vb, true, { "<tool_call>\n" }, {});
auto eager = make(vb, false, {}, {});
int32_t xx = -1, rest = -1;
for (int32_t i = 0; i < (int32_t)vb.n(); ++i) {
if (vb.v.token_piece(i) == "xx<tool") xx = i;
if (vb.v.token_piece(i) == "_call>\n") rest = i;
}
REQUIRE(xx >= 0 && rest >= 0);
CHECK_OK(lazy->accept_token(xx));
CHECK_OK(lazy->accept_token(rest));
CHECK(!lazy->awaiting_trigger());
CHECK_OK(eager->accept_str("<tool_call>\n"));
CHECK(mask_of(*lazy, vb.n()) == mask_of(*eager, vb.n()));
}
TEST(lazy_grammar_fires_on_a_trigger_token_id) {
Vocab vb;
auto g = make(vb, true, {}, { vb.marker });
CHECK_OK(g->accept_token(vb.letters[0]));
CHECK(g->awaiting_trigger());
CHECK_OK(g->accept_token(vb.marker));
CHECK(!g->awaiting_trigger());
const auto m = mask_of(*g, vb.n());
CHECK(admits(m, vb.nl));
CHECK(!admits(m, vb.letters[0]));
}
/* A partial word seen inside a speculative window is rewound with the window. */
TEST(lazy_grammar_rollback_forgets_a_partial_word) {
Vocab vb;
auto g = make(vb, true, { "<tool_call>\n" }, {});
g->push_state();
CHECK_OK(g->accept_token(vb.marker));
CHECK(g->awaiting_trigger());
CHECK_OK(g->rollback());
CHECK_OK(g->accept_token(vb.nl)); /* "\n" alone: the marker was rewound */
CHECK(g->awaiting_trigger());
g->push_state();
CHECK_OK(g->accept_token(vb.marker));
CHECK_OK(g->accept_token(vb.nl));
CHECK(!g->awaiting_trigger()); /* fired inside the window */
CHECK_OK(g->rollback());
CHECK(g->awaiting_trigger()); /* and rewound with it */
CHECK_OK(g->accept_token(vb.marker));
CHECK_OK(g->accept_token(vb.nl));
CHECK(!g->awaiting_trigger());
}
/* THE GRAMMAR-LEVEL DIFFERENTIAL. Random prose from pieces that spell the word in several splits,
* with speculative windows walked and rewound in between the way the sampler does, until the
* word appears; from there tokens are drawn from the lazy grammar's own mask. At every position
* after the trigger the lazy grammar must admit exactly what an eager grammar admits after being
* handed the same text from the word onward. */
TEST(lazy_grammar_agrees_with_an_eager_grammar_on_random_streams) {
Vocab vb;
std::mt19937 rng(424242u);
auto pick = [&](size_t n) { return (size_t)(rng() % n); };
int fired = 0, refused = 0;
for (int iter = 0; iter < 400; ++iter) {
auto lazy = make(vb, true, { "<tool_call>\n" }, {});
std::string text;
int last = RAD_OK;
for (int k = 0; k < 400 && lazy->awaiting_trigger(); ++k) {
if (pick(4) == 0) {
lazy->push_state();
for (int d = 0; d < 3; ++d) lazy->accept_token(vb.prose[pick(vb.prose.size())]);
CHECK_OK(lazy->rollback());
}
const int32_t t = vb.prose[pick(vb.prose.size())];
text += vb.v.token_piece(t);
last = lazy->accept_token(t);
}
if (lazy->awaiting_trigger()) continue;
++fired;
const size_t at = text.find("<tool_call>\n");
REQUIRE(at != std::string::npos);
auto eager = make(vb, false, {}, {});
/* The token that completed the word may carry bytes past it that the grammar refuses
* ("<tool_call>" then "\n\n"): the lazy grammar must refuse exactly when the eager one
* refuses the same text. */
const int est = eager->accept_str(text.substr(at));
CHECK_EQ(last < 0, est < 0);
if (last < 0 || est < 0) { ++refused; continue; }
for (int k = 0; k < 12; ++k) {
const auto ml = mask_of(*lazy, vb.n());
const auto me = mask_of(*eager, vb.n());
if (ml != me) {
radtest::fail(__FILE__, __LINE__, "masks differ at iteration " +
std::to_string(iter) + " step " + std::to_string(k));
return;
}
std::vector<int32_t> ok;
for (int32_t i = 0; i < (int32_t)vb.n(); ++i) if (admits(ml, i)) ok.push_back(i);
if (ok.empty() || ml[0] == 0xDEADBEEFu) break;
const int32_t t = ok[pick(ok.size())];
if (vb.v.is_eog(t)) break;
REQUIRE(lazy->accept_token(t) >= 0);
REQUIRE(eager->accept_token(t) >= 0);
}
}
CHECK(fired - refused > 100);
}
/* WAITING COSTS THE SAME AT ANY LENGTH. A lazy grammar sees every token of the reply until its
* word appears, and each speculative window copies its state twice; a reply of 200k tokens must
* cost its last ten thousand what it cost its first. */
TEST(lazy_grammar_waiting_cost_does_not_grow_with_the_reply) {
Vocab vb;
auto g = make(vb, true, { "<tool_call>\n" }, {});
const int32_t w = vb.letters[22], sp = vb.prose[26];
auto window = [&](int n) {
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < n; ++i) {
g->push_state();
g->accept_token(w);
g->accept_token(sp);
g->accept_token(w);
g->rollback();
g->accept_token(i % 3 ? w : sp);
}
return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
};
/* Best of three windows at each end, since ctest runs this beside other suites and one
* preemption is longer than a window. */
auto best = [&]() { return std::min({ window(20000), window(20000), window(20000) }); };
const double first = best();
window(200000);
const double last = best();
CHECK(g->awaiting_trigger());
std::printf(" lazy wait: %.3f us/token first, %.3f us/token after 320k\n",
first * 1e6 / 20000, last * 1e6 / 20000);
CHECK(last < first * 2.0 + 0.001);
CHECK(last * 1e6 / 20000 < 5.0);
}
RAD_TEST_MAIN()
+393
View File
@@ -0,0 +1,393 @@
/* util_test.cpp -- core/util/rad_util.cpp: the bedrock every other translation unit links against.
*
* WHY THIS FILE EXISTS. Nothing here is interesting on its own, and every one of these is small
* enough to read and believe -- which is what leaves such code untested. The two that are not
* merely cosmetic are `Geometry` and `constraint_holds`, and they decide WHICH KERNEL RUNS. A
* geometry that hands a kernel dangling parameter pointers, or a constraint that holds when it
* should not, does not fail -- it selects a different implementation, which produces plausible
* output on a path nobody is looking at. The rest are here because a formatter that rounds the
* wrong way makes every report that prints a size disagree with every other one.
*
* No device, no model, no core: one translation unit and its header.
*/
#include "rad_test.h"
#include "rad_internal.h"
#include <string>
using namespace rad;
/* ================================================================== small helpers */
TEST(align_up_rounds_up_and_leaves_an_exact_multiple_alone) {
CHECK_EQ(align_up(0, 256), 0ll);
CHECK_EQ(align_up(1, 256), 256ll);
CHECK_EQ(align_up(255, 256), 256ll);
CHECK_EQ(align_up(256, 256), 256ll); /* already aligned: not bumped to the next unit */
CHECK_EQ(align_up(257, 256), 512ll);
CHECK_EQ(align_up(12345, 1), 12345ll); /* an alignment of one is the identity */
/* The sizes this is actually used on are pool extents, which are large. */
CHECK_EQ(align_up(1073741825ll, 4096), 1073745920ll);
}
TEST(humanb_changes_unit_at_the_boundary_and_not_before) {
CHECK_EQ(humanb(0), std::string("0 B"));
CHECK_EQ(humanb(1), std::string("1 B"));
/* 1023 IS STILL BYTES. A ladder that switched a unit early would print "1.00 KiB" for a
* number below a kibibyte, and every size in every report is read against the others. */
CHECK_EQ(humanb(1023), std::string("1023 B"));
CHECK_EQ(humanb(1024), std::string("1.00 KiB"));
CHECK_EQ(humanb(1536), std::string("1.50 KiB"));
CHECK_EQ(humanb(1048576), std::string("1.00 MiB"));
CHECK_EQ(humanb(1073741824ll), std::string("1.00 GiB"));
CHECK_EQ(humanb(1099511627776ll), std::string("1.00 TiB"));
/* THE LADDER STOPS AT TiB and says so in TiB rather than inventing a unit. */
CHECK_EQ(humanb(1125899906842624ll), std::string("1024.00 TiB"));
}
TEST(fmt_sizes_its_own_buffer) {
CHECK_EQ(fmt("%d", 7), std::string("7"));
CHECK_EQ(fmt("%s=%lld", "M", 64ll), std::string("M=64"));
CHECK_EQ(fmt("%s", ""), std::string(""));
/* LONGER THAN ANY FIXED BUFFER SOMEBODY MIGHT HAVE REACHED FOR. It measures with vsnprintf
* first, so there is no cap to find -- but a regression to a stack buffer would truncate
* here and nowhere else, and the strings this formats include whole selection tables. */
const std::string big = fmt("%s", std::string(10000, 'x').c_str());
CHECK_EQ(big.size(), (size_t)10000);
CHECK_EQ(big.front(), 'x');
CHECK_EQ(big.back(), 'x');
}
TEST(rad_mono_ns_moves_forward_and_is_not_the_wall_clock) {
const uint64_t a = rad_mono_ns();
CHECK(a > 0);
uint64_t b = a;
/* Spin rather than sleep: the property is that it advances at all, and a test that sleeps
* for it is a test that takes a millisecond to assert one comparison. */
for (int i = 0; i < 1000000 && b == a; ++i) b = rad_mono_ns();
CHECK(b >= a);
/* Not a Unix timestamp. A monotonic clock counts from an arbitrary epoch -- usually boot --
* and anything comparing it against time() would be comparing two different origins. */
CHECK(a < 1000000000000000000ull);
}
/* SPLIT_WS SPLITS ON COMMAS TOO, which its name does not say and RAD_C_IN depends on: a kernel
* writing RAD_CIN("dtype", "bf16,fp8") and one writing "bf16 fp8" mean the same set. */
TEST(split_ws_takes_spaces_tabs_and_commas) {
auto v = split_ws("a b c");
CHECK_EQ(v.size(), 3u);
CHECK_EQ(std::string(v[0]), std::string("a"));
CHECK_EQ(std::string(v[2]), std::string("c"));
v = split_ws("bf16,fp8");
CHECK_EQ(v.size(), 2u);
CHECK_EQ(std::string(v[1]), std::string("fp8"));
v = split_ws("\ta ,, b\t,c ");
CHECK_EQ(v.size(), 3u);
CHECK_EQ(std::string(v[0]), std::string("a"));
CHECK_EQ(std::string(v[1]), std::string("b"));
CHECK_EQ(std::string(v[2]), std::string("c"));
/* An empty set is empty rather than one empty token, or a constraint naming no values would
* hold for a geometry whose value is the empty string. */
CHECK_EQ(split_ws("").size(), 0u);
CHECK_EQ(split_ws(" ,, \t ").size(), 0u);
CHECK_EQ(split_ws("one").size(), 1u);
}
TEST(the_log_level_is_readable_and_settable) {
const Log saved = log_level();
log_set_level(Log::Trace);
CHECK((int)log_level() == (int)Log::Trace);
log_set_level(Log::Error);
CHECK((int)log_level() == (int)Log::Error);
log_set_level(saved);
CHECK((int)log_level() == (int)saved);
}
/* ================================================================== Geometry */
TEST(geometry_stores_by_kind_and_a_reader_of_the_wrong_kind_misses) {
Geometry g;
g.set_i("M", 64);
g.set_s("dtype", "w4a8");
g.set_f("eps", 1e-6);
long long i = 0;
CHECK(g.get_i("M", &i));
CHECK_EQ(i, 64ll);
CHECK_EQ(std::string(g.get_s("dtype")), std::string("w4a8"));
double d = 0;
CHECK(g.get_f("eps", &d));
CHECK_NEAR(d, 1e-6, 1e-12);
/* THE KIND IS PART OF THE MATCH. get_i on a string slot missing is what makes a constraint
* naming a float key fail rather than comparing against a truncation of it. */
CHECK(!g.get_i("dtype", &i));
CHECK(!g.get_i("eps", &i));
CHECK(!g.get_f("M", &d));
CHECK(g.get_s("M") == nullptr);
CHECK(g.get_s("missing") == nullptr);
CHECK(!g.get_i("missing", &i));
/* has() is kind-agnostic: it answers whether the key is carried at all. */
CHECK(g.has("M")); CHECK(g.has("dtype")); CHECK(g.has("eps"));
CHECK(!g.has("N"));
/* A null out pointer is a membership test. */
CHECK(g.get_i("M", nullptr));
CHECK(!g.get_i("dtype", nullptr));
}
TEST(setting_a_key_again_replaces_its_value_and_its_kind) {
Geometry g;
g.set_i("x", 1);
g.set_i("x", 2);
long long i = 0;
CHECK(g.get_i("x", &i));
CHECK_EQ(i, 2ll);
CHECK_EQ(g.n_params(), 1); /* replaced, not appended */
g.set_s("x", "str");
CHECK(!g.get_i("x", &i)); /* it is a string now and nothing else */
CHECK_EQ(std::string(g.get_s("x")), std::string("str"));
CHECK_EQ(g.n_params(), 1);
}
TEST(the_param_view_is_rebuilt_after_a_mutation) {
Geometry g;
g.set_i("M", 8);
CHECK_EQ(g.n_params(), 1);
CHECK_EQ(g.params()[0].ival, 8ll);
/* The view is cached, so the question is whether the cache is invalidated. A stale view hands
* a kernel the geometry it was resolved against rather than the one it is being run on. */
g.set_i("M", 9);
CHECK_EQ(g.params()[0].ival, 9ll);
g.set_i("N", 4096);
CHECK_EQ(g.n_params(), 2);
/* A string param carries sval and an integer one carries a null sval, which is what lets a
* kernel tell "not set" from "the empty string". */
g.set_s("dtype", "bf16");
const RadParam* p = g.params();
int seen = 0;
for (int k = 0; k < g.n_params(); ++k) {
if (std::string(p[k].key) == "dtype") {
CHECK(p[k].sval != nullptr);
CHECK_EQ(std::string(p[k].sval), std::string("bf16"));
++seen;
} else {
CHECK(p[k].sval == nullptr);
}
}
CHECK_EQ(seen, 1);
}
/* THE COPY MUST OWN ITS OWN STRINGS, and the header says why at length: the cached view holds
* char* into the object's own storage, so a copy that took the view along with the storage would
* hand a kernel pointers into the source -- which dies first about as often as not, since every
* Resolved holds a Geometry and every Band holds two. */
TEST(a_copied_geometry_points_into_itself_and_not_at_the_source) {
Geometry a;
a.set_s("dtype", "w4a8");
a.set_i("M", 64);
const char* a_key = a.params()[0].key; /* force the source to build its view */
Geometry b = a;
CHECK_EQ(b.n_params(), 2);
CHECK_EQ(std::string(b.params()[0].key), std::string("dtype"));
CHECK(b.params()[0].key != a_key); /* a different object's storage */
CHECK(b.params()[0].sval != a.params()[0].sval);
CHECK_EQ(std::string(b.params()[0].sval), std::string("w4a8"));
/* And the two are independent afterwards, in both directions. */
a.set_i("M", 1);
long long i = 0;
CHECK(b.get_i("M", &i));
CHECK_EQ(i, 64ll);
b.set_i("M", 2);
CHECK(a.get_i("M", &i));
CHECK_EQ(i, 1ll);
/* Assignment is the same rule. */
Geometry c;
c.set_i("junk", 7);
c = a;
CHECK(!c.has("junk"));
CHECK_EQ(c.n_params(), 2);
CHECK(c.params()[0].key != a.params()[0].key);
}
TEST(a_moved_geometry_does_not_leave_the_view_pointing_at_a_stolen_buffer) {
Geometry a;
a.set_s("dtype", "fp8");
a.set_i("K", 5120);
(void)a.params(); /* build the view, then move out from under it */
Geometry b = std::move(a);
CHECK_EQ(b.n_params(), 2);
CHECK_EQ(std::string(b.params()[0].sval), std::string("fp8"));
/* The moved-from object is empty rather than holding a view of a buffer it no longer owns. */
CHECK_EQ(a.n_params(), 0);
Geometry c;
c.set_i("x", 1);
c = std::move(b);
CHECK_EQ(c.n_params(), 2);
CHECK(!c.has("x"));
CHECK_EQ(b.n_params(), 0);
}
TEST(geometry_str_prints_every_kind_in_declaration_order) {
Geometry g;
g.set_i("M", 64);
g.set_i("N", 8192);
g.set_s("dtype", "w4a8");
CHECK_EQ(g.str(), std::string("M=64 N=8192 dtype=w4a8"));
Geometry f;
f.set_f("eps", 1e-6);
CHECK_EQ(f.str(), std::string("eps=1e-06"));
CHECK_EQ(Geometry{}.str(), std::string(""));
}
/* ================================================================== constraint matching */
static RadConstraint c_eq(const char* k, long long v) { return RadConstraint RAD_CEQ(k, v); }
static RadConstraint c_le(const char* k, long long v) { return RadConstraint RAD_CLE(k, v); }
static RadConstraint c_ge(const char* k, long long v) { return RadConstraint RAD_CGE(k, v); }
static RadConstraint c_div(const char* k, long long v) { return RadConstraint RAD_CDIV(k, v); }
static RadConstraint c_in(const char* k, const char* s) { return RadConstraint RAD_CIN(k, s); }
TEST(the_four_integer_constraints_compare_the_way_they_read) {
Geometry g;
g.set_i("M", 64);
CHECK(constraint_holds(c_eq("M", 64), g));
CHECK(!constraint_holds(c_eq("M", 63), g));
CHECK(constraint_holds(c_le("M", 64), g)); /* inclusive at the bound */
CHECK(constraint_holds(c_le("M", 65), g));
CHECK(!constraint_holds(c_le("M", 63), g));
CHECK(constraint_holds(c_ge("M", 64), g)); /* inclusive at the bound */
CHECK(constraint_holds(c_ge("M", 1), g));
CHECK(!constraint_holds(c_ge("M", 65), g));
CHECK(constraint_holds(c_div("M", 16), g));
CHECK(constraint_holds(c_div("M", 1), g));
CHECK(!constraint_holds(c_div("M", 5), g));
}
/* A DIVISOR OF ZERO IS NOT "DIVIDES EVERYTHING", it is a kernel-set typo. Answering true would
* route every geometry to that row, which is the widest possible band by accident. */
TEST(a_zero_divisor_holds_for_nothing_rather_than_faulting) {
Geometry g;
g.set_i("M", 64);
CHECK(!constraint_holds(c_div("M", 0), g));
g.set_i("Z", 0);
CHECK(!constraint_holds(c_div("Z", 0), g));
CHECK(constraint_holds(c_div("Z", 16), g)); /* zero is divisible by anything non-zero */
}
/* A CONSTRAINT WHOSE KEY THE GEOMETRY DOES NOT CARRY DOES NOT HOLD. The header names what this
* buys: libr4d's two-shot all-reduce rows are reachable only by a query that asks for `hops`,
* because a query that omits it fails the more constrained row. */
TEST(an_absent_key_fails_every_constraint) {
Geometry g;
g.set_i("M", 64);
CHECK(!constraint_holds(c_eq("hops", 2), g));
CHECK(!constraint_holds(c_le("hops", 99), g));
CHECK(!constraint_holds(c_ge("hops", 0), g));
CHECK(!constraint_holds(c_div("hops", 1), g));
CHECK(!constraint_holds(c_in("hops", "1 2"), g));
}
/* A FLOAT PARAMETER CAN NEVER SATISFY ONE, and that is the intended answer rather than an
* oversight: a tolerance is not a predicate, and a kernel discriminating on eps to that precision
* has a bug. */
TEST(a_float_parameter_satisfies_no_constraint) {
Geometry g;
g.set_f("eps", 1e-6);
g.set_f("scale", 1.0);
CHECK(!constraint_holds(c_eq("scale", 1), g));
CHECK(!constraint_holds(c_le("scale", 2), g));
CHECK(!constraint_holds(c_ge("eps", 0), g));
CHECK(!constraint_holds(c_div("scale", 1), g));
CHECK(!constraint_holds(c_in("scale", "1"), g));
}
TEST(a_set_constraint_matches_a_string_and_an_integers_decimal_form) {
Geometry g;
g.set_s("dtype", "fp8");
CHECK(constraint_holds(c_in("dtype", "bf16 fp8"), g));
CHECK(constraint_holds(c_in("dtype", "bf16,fp8"), g));
CHECK(!constraint_holds(c_in("dtype", "bf16 w4a8"), g));
/* A PREFIX IS NOT A MEMBER. Matching "fp8" against a set containing "fp8e5" would route a
* kernel compiled for one encoding at another. */
CHECK(!constraint_holds(c_in("dtype", "fp8e5m2"), g));
/* The integer form, which is what makes RAD_CIN("causal", "0 1") work. */
Geometry i;
i.set_i("causal", 1);
CHECK(constraint_holds(c_in("causal", "0 1"), i));
i.set_i("causal", 2);
CHECK(!constraint_holds(c_in("causal", "0 1"), i));
i.set_i("neg", -1);
CHECK(constraint_holds(c_in("neg", "-1 0"), i));
/* An empty or absent set matches nothing, including the empty string. */
Geometry e;
e.set_s("k", "");
CHECK(!constraint_holds(c_in("k", ""), e));
RadConstraint nullset = c_in("k", nullptr);
CHECK(!constraint_holds(nullset, e));
}
TEST(an_unknown_constraint_operator_holds_for_nothing) {
Geometry g;
g.set_i("M", 64);
RadConstraint c{};
c.key = "M";
c.op = 99;
c.ival = 64;
CHECK(!constraint_holds(c, g));
}
/* THE MISS COLUMN OF THE SELECTION TABLE (spec §16). Its job is to say which kernel was rejected
* and why in terms an operator can act on, so it has to name the key, the bound and the value --
* and it has to distinguish "your number is wrong" from "you did not supply that number at all". */
TEST(constraint_why_names_the_key_the_bound_and_what_was_there) {
Geometry g;
g.set_i("M", 64);
const std::string le = constraint_why(c_le("M", 32), g);
CHECK(le.find("M") != std::string::npos);
CHECK(le.find("<=") != std::string::npos);
CHECK(le.find("32") != std::string::npos);
CHECK(le.find("64") != std::string::npos);
const std::string dv = constraint_why(c_div("M", 5), g);
CHECK(dv.find("%") != std::string::npos);
CHECK(dv.find("5") != std::string::npos);
/* Absent reads differently from wrong, because the repair is different. */
const std::string ab = constraint_why(c_ge("hops", 2), g);
CHECK(ab.find("did not name") != std::string::npos);
CHECK(ab.find("hops") != std::string::npos);
Geometry s;
s.set_s("dtype", "fp8");
const std::string in = constraint_why(c_in("dtype", "bf16"), s);
CHECK(in.find("bf16") != std::string::npos);
CHECK(in.find("fp8") != std::string::npos);
const std::string miss = constraint_why(c_in("dtype", "bf16"), g);
CHECK(miss.find("<absent>") != std::string::npos);
}
RAD_TEST_MAIN()
+576
View File
@@ -0,0 +1,576 @@
/* wire_test.cpp -- the pieces of the HTTP and OpenAI surface that are not a route.
*
* server_test drives the server end to end and is where a handler's behaviour belongs. What it
* cannot reach is the half-dozen small functions underneath: a target splitter, a percent
* decoder, a base64 pair, the UTF-8 back-off that keeps a streamed delta from cutting a code
* point in half, the bucket ladders every Prometheus quantile is computed against, and the body
* builders. Each of them is reachable from exactly one route, so a fault in one shows up as one
* endpoint being subtly wrong -- a query parameter that silently does not arrive, a stream a
* client cannot decode, a histogram whose quantiles moved across a version boundary.
*
* WHAT MAKES THESE WORTH A TEST RATHER THAN A READING. Every one of them has a case that is not
* the obvious one: base64 has two padding lengths, the decoder has to reject a character rather
* than skip it, `+` means two different things in the two halves of a target, and `utf8_trunc`
* exists precisely because the easy implementation is wrong.
*/
#include "rad_test.h"
#include <nlohmann/json.hpp>
#include "server/http.h"
#include "server/json_partial.h"
#include "server/metrics.h"
#include "server/oai.h"
#include "server/sink.h"
#include <cmath>
#include <cstring>
#include <map>
#include <string>
#include <vector>
using namespace rad;
using namespace rad::server;
/* ================================================================== the target */
TEST(a_target_splits_into_a_path_and_decoded_query_parameters) {
std::string path;
std::map<std::string, std::string> q;
parse_target("/v1/models/foo?x=1&y=two", &path, &q);
CHECK_EQ(path, std::string("/v1/models/foo"));
CHECK_EQ(q.size(), 2u);
CHECK_EQ(q["x"], std::string("1"));
CHECK_EQ(q["y"], std::string("two"));
/* No query at all leaves the map untouched rather than inventing an empty entry. */
std::map<std::string, std::string> none;
parse_target("/health", &path, &none);
CHECK_EQ(path, std::string("/health"));
CHECK_EQ(none.size(), 0u);
/* A key with no value is present and empty -- "?stream" is a flag, and a caller asking
* whether the key is there must be able to tell it from a key that was never sent. */
std::map<std::string, std::string> flag;
parse_target("/x?stream", &path, &flag);
CHECK_EQ(flag.size(), 1u);
CHECK(flag.count("stream") == 1);
CHECK_EQ(flag["stream"], std::string(""));
/* An empty query after the '?' contributes nothing. */
std::map<std::string, std::string> empty;
parse_target("/x?", &path, &empty);
CHECK_EQ(path, std::string("/x"));
CHECK_EQ(empty.size(), 0u);
/* Both outputs are optional: the router asks for the path alone on the hot path. */
std::string only;
parse_target("/x?a=b", &only, nullptr);
CHECK_EQ(only, std::string("/x"));
std::map<std::string, std::string> qonly;
parse_target("/x?a=b", nullptr, &qonly);
CHECK_EQ(qonly["a"], std::string("b"));
}
TEST(query_values_are_percent_decoded_and_survive_an_embedded_equals) {
std::string path;
std::map<std::string, std::string> q;
parse_target("/x?name=a%20b&eq=1%3D2&plus=a+b", &path, &q);
CHECK_EQ(q["name"], std::string("a b"));
/* Split on the FIRST '=' only, or a base64 value -- which ends in '=' padding -- loses its
* tail every time. */
CHECK_EQ(q["eq"], std::string("1=2"));
CHECK_EQ(q["plus"], std::string("a b"));
std::map<std::string, std::string> raw;
parse_target("/x?v=a=b=c", &path, &raw);
CHECK_EQ(raw["v"], std::string("a=b=c"));
}
/* `+` IS A SPACE IN A QUERY STRING AND A PLUS SIGN IN A PATH. The form encoding that gives it the
* second meaning applies to form data, which is what a query string is and a path is not --
* so /v1/models/gpt+4 must not become a request for "gpt 4". */
TEST(a_plus_in_the_path_stays_a_plus) {
std::string path;
std::map<std::string, std::string> q;
parse_target("/v1/models/gpt+4?q=a+b", &path, &q);
CHECK_EQ(path, std::string("/v1/models/gpt+4"));
CHECK_EQ(q["q"], std::string("a b"));
CHECK_EQ(url_decode("a+b"), std::string("a b"));
CHECK_EQ(url_decode("a+b", false), std::string("a+b"));
/* Percent-encoding works the same in both. */
CHECK_EQ(url_decode("a%2Bb", false), std::string("a+b"));
}
TEST(url_decode_leaves_a_truncated_or_invalid_escape_alone) {
CHECK_EQ(url_decode("plain"), std::string("plain"));
CHECK_EQ(url_decode(""), std::string(""));
CHECK_EQ(url_decode("%41%42"), std::string("AB"));
CHECK_EQ(url_decode("%4a"), std::string("J")); /* lower-case hex */
CHECK_EQ(url_decode("%4A"), std::string("J"));
/* A DECODER THAT CONSUMED A BAD ESCAPE WOULD EAT THE BYTES AFTER IT. Leaving it verbatim
* makes the mistake visible in the value rather than shortening the string silently. */
CHECK_EQ(url_decode("%zz"), std::string("%zz"));
CHECK_EQ(url_decode("%4"), std::string("%4"));
CHECK_EQ(url_decode("%"), std::string("%"));
CHECK_EQ(url_decode("100%"), std::string("100%"));
/* A percent-encoded percent. */
CHECK_EQ(url_decode("%2541"), std::string("%41"));
}
/* ================================================================== base64 */
TEST(base64_round_trips_at_every_padding_length) {
/* The three residues are the whole of the encoder's branching, and they are what the padding
* length encodes: a decoder that got the two-byte tail wrong would return a trailing zero. */
const char* cases[] = { "", "f", "fo", "foo", "foob", "fooba", "foobar" };
const char* want[] = { "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy" };
for (int i = 0; i < 7; ++i) {
const std::string in = cases[i];
const std::string enc = base64_encode(in.data(), in.size());
CHECK_EQ(enc, std::string(want[i]));
std::vector<uint8_t> back;
CHECK(base64_decode(enc, &back));
CHECK_EQ(back.size(), in.size());
CHECK_EQ(std::string(back.begin(), back.end()), in);
}
}
TEST(base64_carries_every_byte_value_including_zero) {
std::vector<uint8_t> all(256);
for (int i = 0; i < 256; ++i) all[(size_t)i] = (uint8_t)i;
const std::string enc = base64_encode(all.data(), all.size());
/* 256 bytes is not a multiple of three, so this exercises a padded tail on real data. */
CHECK_EQ(enc.size(), (size_t)344);
std::vector<uint8_t> back;
CHECK(base64_decode(enc, &back));
CHECK_EQ(back.size(), (size_t)256);
for (int i = 0; i < 256; ++i) CHECK_EQ((int)back[(size_t)i], i);
/* The alphabet is the standard one and not the URL-safe variant: a decoder on the other end
* chooses by which characters it sees, and '+' and '/' are what it must see here. */
bool plus = false, slash = false;
for (char c : enc) { if (c == '+') plus = true; if (c == '/') slash = true; }
CHECK(plus);
CHECK(slash);
}
/* AN EMBEDDING ARRIVES AS BASE64 FROM A CLIENT, so the decoder is parsing untrusted input: a
* character outside the alphabet has to be an error and not a byte skipped, or a corrupted
* payload decodes to a shorter vector that the shape check then accepts or rejects for the
* wrong reason. */
TEST(base64_decode_rejects_a_character_outside_the_alphabet) {
std::vector<uint8_t> out;
CHECK(!base64_decode("Zm9v!", &out));
CHECK(!base64_decode("****", &out));
CHECK(!base64_decode("Zm-9v", &out)); /* the URL-safe alphabet is not accepted */
CHECK(!base64_decode("Zm_9v", &out));
/* Whitespace and padding are skipped, because a wrapped MIME payload is still the value. */
CHECK(base64_decode("Zm9v\nYmFy", &out));
CHECK_EQ(std::string(out.begin(), out.end()), std::string("foobar"));
CHECK(base64_decode("Zm9v YmFy\t\r\n", &out));
CHECK_EQ(std::string(out.begin(), out.end()), std::string("foobar"));
CHECK(base64_decode("", &out));
CHECK_EQ(out.size(), 0u);
/* The output is cleared first: a failed decode after a successful one must not leave the
* previous payload behind for the caller to read as this one's. */
CHECK(base64_decode("Zm9v", &out));
CHECK_EQ(out.size(), 3u);
CHECK(!base64_decode("!", &out));
CHECK_EQ(out.size(), 0u);
}
/* ================================================================== ids and errors */
TEST(a_random_id_carries_its_prefix_and_does_not_repeat) {
const std::string a = random_id("chatcmpl-");
const std::string b = random_id("chatcmpl-");
CHECK(a.rfind("chatcmpl-", 0) == 0);
CHECK(b.rfind("chatcmpl-", 0) == 0);
CHECK(a.size() > std::string("chatcmpl-").size());
CHECK(a != b); /* ids collide in a client's logs, not in the server */
CHECK_EQ(a.size(), b.size()); /* fixed width, so it sorts and pads predictably */
const std::string c = random_id("cmpl-");
CHECK(c.rfind("cmpl-", 0) == 0);
/* The body is drawn from a printable set -- an id lands in a URL and in a log line. */
for (size_t i = std::string("cmpl-").size(); i < c.size(); ++i)
CHECK(c[i] > 0x20 && c[i] < 0x7f);
}
TEST(the_error_envelope_is_the_shape_a_client_parses) {
const ApiError bad = err_bad("temperature", "must be in [0, 2]");
CHECK_EQ(bad.status, 400);
CHECK_EQ(bad.param, std::string("temperature"));
const std::string d = bad.dump();
/* OpenAI's envelope is {"error":{"message":...}} and a client reads message and param by
* name; anything flatter is an error body a library reports as "unknown". */
CHECK(d.find("\"error\"") != std::string::npos);
CHECK(d.find("\"message\"") != std::string::npos);
CHECK(d.find("temperature") != std::string::npos);
CHECK(d.find("must be in") != std::string::npos);
CHECK(json_complete(d));
const ApiError uns = err_unsupported("logprobs", "not implemented");
CHECK_EQ(uns.status, 400);
CHECK_EQ(uns.param, std::string("logprobs"));
CHECK(json_complete(uns.dump()));
/* A CAPABILITY THIS BUILD DOES NOT HAVE IS 501 AND NOT 400, because 400 tells the caller to
* fix their request and there is nothing in it to fix. */
const ApiError ni = err_not_implemented("embeddings");
CHECK_EQ(ni.status, 501);
CHECK(ni.dump().find("embeddings") != std::string::npos);
/* And a full queue is 429, which is what carries a Retry-After: the request is fine and the
* server is momentarily not, so backing off and resending is the correct client behaviour.
* 503 would say the service is down, which a client is entitled to treat as fatal. */
const ApiError ov = err_overloaded("admission queue is full");
CHECK_EQ(ov.status, 429);
CHECK(json_complete(ov.dump()));
/* An error about no particular field carries no param rather than an empty one. */
CHECK(err_overloaded("busy").param.empty());
}
/* ================================================================== server-sent events */
TEST(an_sse_event_is_one_data_line_and_a_blank_line) {
const std::string e = sse_event("{\"a\":1}");
CHECK_EQ(e, std::string("data: {\"a\":1}\n\n"));
/* THE BLANK LINE IS THE FRAME DELIMITER. Without it a client buffers the event forever and
* the stream looks hung rather than broken. */
CHECK(e.size() >= 2 && e.compare(e.size() - 2, 2, "\n\n") == 0);
CHECK_EQ(std::string(SSE_DONE), std::string("data: [DONE]\n\n"));
const std::string err = sse_error(err_bad("n", "too large"));
CHECK(err.rfind("data: ", 0) == 0);
CHECK(err.find("\"error\"") != std::string::npos);
CHECK(err.find("too large") != std::string::npos);
CHECK(err.compare(err.size() - 2, 2, "\n\n") == 0);
/* The payload between the prefix and the delimiter is one complete JSON value, which is what
* a client's per-event parse requires. */
CHECK(json_complete(err.substr(6, err.size() - 8)));
}
/* ================================================================== finish reasons */
TEST(the_finish_reason_matches_vllms_spelling) {
CHECK_EQ(std::string(finish_reason_oai(Finish::Stop)), std::string("stop"));
CHECK_EQ(std::string(finish_reason_oai(Finish::Length)), std::string("length"));
CHECK_EQ(std::string(finish_reason_oai(Finish::ToolCalls)), std::string("tool_calls"));
/* CANCELLED HAS NO OPENAI SPELLING and vLLM reports "abort". Dashboards key off that string,
* so inventing a better one here would make this server's traffic invisible in them. */
CHECK_EQ(std::string(finish_reason_oai(Finish::Cancelled)), std::string("abort"));
/* Every reason resolves to something non-empty: a missing finish_reason is a null in the
* choice object, which clients treat as "still streaming". */
for (Finish f : { Finish::Stop, Finish::Length, Finish::ToolCalls, Finish::Cancelled,
Finish::Error })
CHECK(finish_reason_oai(f) && *finish_reason_oai(f));
}
/* ================================================================== the UTF-8 back-off */
TEST(utf8_trunc_backs_out_of_a_split_code_point_and_nothing_else) {
/* Complete input is returned whole -- the common case, and the one a per-delta call takes. */
CHECK_EQ(utf8_trunc("hello"), (size_t)5);
CHECK_EQ(utf8_trunc(""), (size_t)0);
CHECK_EQ(utf8_trunc("\xC3\xA9"), (size_t)2); /* e-acute, complete */
CHECK_EQ(utf8_trunc("\xE2\x82\xAC"), (size_t)3); /* euro sign, complete */
CHECK_EQ(utf8_trunc("\xF0\x9F\x98\x80"), (size_t)4); /* an emoji, complete */
/* A TRAILING PARTIAL SEQUENCE IS CUT. A delta ending mid-code-point is not decodable, and a
* client that concatenates deltas before decoding sees a replacement character that never
* goes away. */
CHECK_EQ(utf8_trunc("ab\xC3"), (size_t)2);
CHECK_EQ(utf8_trunc("ab\xE2\x82"), (size_t)2);
CHECK_EQ(utf8_trunc("ab\xE2"), (size_t)2);
CHECK_EQ(utf8_trunc("ab\xF0\x9F\x98"), (size_t)2);
CHECK_EQ(utf8_trunc("\xF0"), (size_t)0);
/* A COMPLETE SEQUENCE FOLLOWED BY A PARTIAL ONE keeps the complete one. */
CHECK_EQ(utf8_trunc("\xE2\x82\xAC\xC3"), (size_t)3);
/* AND A PARTIAL SEQUENCE IN THE MIDDLE IS NOT THIS FUNCTION'S BUSINESS. It backs out of a
* truncation rather than validating, so a lone lead byte followed by ASCII is left where it
* is: only the tail is reconsidered, and the tail here is complete. */
CHECK_EQ(utf8_trunc("\xC3 ok"), (size_t)4);
CHECK_EQ(utf8_trunc("\xC3 ok\xE2\x82"), (size_t)4); /* ... and the real tail still cuts */
}
/* ================================================================== histogram ladders */
/* vLLM'S LAYOUTS, VERBATIM. A dashboard computes quantiles by interpolating between bucket
* bounds, so changing one of these silently moves every historical quantile across a version
* boundary -- the graph does not break, it just stops meaning what it meant. */
TEST(the_bucket_ladders_are_sorted_positive_and_the_ones_vllm_publishes) {
struct { const char* name; std::vector<double> b; size_t n; double first, last; } cases[] = {
{ "ttft", buckets_ttft(), 22, 0.001, 2560.0 },
{ "tpot", buckets_tpot(), 19, 0.01, 80.0 },
{ "latency", buckets_latency(), 21, 0.3, 7680.0 },
};
for (auto& c : cases) {
CHECK_EQ(c.b.size(), c.n);
CHECK_NEAR(c.b.front(), c.first, 1e-12);
CHECK_NEAR(c.b.back(), c.last, 1e-9);
for (size_t i = 0; i < c.b.size(); ++i) {
CHECK(c.b[i] > 0.0);
/* STRICTLY INCREASING. A repeated bound gives a bucket of zero width, which every
* quantile interpolation divides by. */
if (i) CHECK(c.b[i] > c.b[i - 1]);
}
}
}
TEST(the_token_ladder_is_mantissas_1_2_5_stopping_past_the_context) {
/* vLLM's build_1_2_5_buckets: a 32K-context model gets 1..20000 and no more. */
const std::vector<double> b = buckets_1_2_5(32768);
CHECK(!b.empty());
CHECK_NEAR(b.front(), 1.0, 1e-12);
CHECK_NEAR(b.back(), 20000.0, 1e-9);
CHECK_EQ(b.size(), 14u);
for (size_t i = 1; i < b.size(); ++i) CHECK(b[i] > b[i - 1]);
/* Every entry is a mantissa of 1, 2 or 5 at some decade. */
for (double v : b) {
double m = v;
while (m >= 10.0) m /= 10.0;
CHECK(std::fabs(m - 1.0) < 1e-9 || std::fabs(m - 2.0) < 1e-9 || std::fabs(m - 5.0) < 1e-9);
}
/* It stops at the first value PAST the bound rather than including it: nothing above the
* context can be observed, so a bucket there would never be reached. */
for (double v : b) CHECK(v <= 32768.0);
const std::vector<double> big = buckets_1_2_5(200000);
CHECK(big.size() > b.size());
CHECK_NEAR(big.back(), 200000.0, 1e-9); /* the bound itself is legal when it is on the
* ladder, because it can be observed */
/* A DEGENERATE BOUND STILL GIVES A USABLE HISTOGRAM. Zero or negative is clamped to one
* rather than producing an empty ladder, which would make every observation fall in the
* overflow bucket and the metric say nothing. */
CHECK_EQ(buckets_1_2_5(1).size(), 1u);
CHECK_EQ(buckets_1_2_5(0).size(), 1u);
CHECK_EQ(buckets_1_2_5(-5).size(), 1u);
}
/* ================================================================== the response bodies
*
* WHAT THESE HAVE TO GET RIGHT is not the content, which the routes already cover end to end, but
* the SHAPE: a client library deserialises into generated types, and a field of the wrong type --
* a null where a string was declared, a missing usage block, a number where an array belongs --
* is a hard parse failure rather than a degraded answer. They are also the only place `usage` is
* assembled, and usage is what a caller bills against.
*/
namespace {
OaiRequest a_request(const char* id, const char* model) {
OaiRequest r;
r.id = id;
r.model = model;
r.created = 1700000000;
return r;
}
/* nlohmann is already a dependency of this translation unit, so the assertions read the body as
* a client would rather than searching it for substrings. */
json parsed(const std::string& body) {
CHECK(json_complete(body));
return json::parse(body, nullptr, false);
}
} /* namespace */
TEST(the_model_list_is_a_list_of_one_with_the_fields_clients_read) {
const json o = parsed(models_body("q38-flashnext", 1700000000));
CHECK_EQ(o.value("object", std::string()), std::string("list"));
CHECK(o["data"].is_array());
CHECK_EQ(o["data"].size(), 1u);
CHECK_EQ(o["data"][0].value("id", std::string()), std::string("q38-flashnext"));
CHECK_EQ(o["data"][0].value("object", std::string()), std::string("model"));
CHECK_EQ(o["data"][0].value("created", (int64_t)0), (int64_t)1700000000);
/* `owned_by` is in the schema and generated clients deserialise it. */
CHECK(o["data"][0].contains("owned_by"));
}
TEST(a_chat_body_carries_usage_and_one_choice_per_completion) {
ChoiceOut a;
a.index = 0;
a.msg.content = "hello";
a.finish = Finish::Stop;
ChoiceOut b;
b.index = 1;
b.msg.content = "world";
b.finish = Finish::Length;
UsageOut u;
u.prompt = 10;
u.completion = 4;
u.cached = 6;
const json o = parsed(chat_completion_body(a_request("chatcmpl-1", "m"), { a, b }, u));
CHECK_EQ(o.value("object", std::string()), std::string("chat.completion"));
CHECK_EQ(o.value("id", std::string()), std::string("chatcmpl-1"));
CHECK_EQ(o["choices"].size(), 2u);
CHECK_EQ(o["choices"][0]["message"].value("role", std::string()), std::string("assistant"));
CHECK_EQ(o["choices"][0]["message"].value("content", std::string()), std::string("hello"));
CHECK_EQ(o["choices"][0].value("finish_reason", std::string()), std::string("stop"));
CHECK_EQ(o["choices"][1].value("finish_reason", std::string()), std::string("length"));
CHECK_EQ(o["choices"][1].value("index", -1), 1);
/* TOTAL IS THE SUM AND NOT A THIRD COUNTER. A caller reconciling a bill against the two
* halves has to get the same answer both ways. */
CHECK_EQ(o["usage"].value("prompt_tokens", (int64_t)0), (int64_t)10);
CHECK_EQ(o["usage"].value("completion_tokens", (int64_t)0), (int64_t)4);
CHECK_EQ(o["usage"].value("total_tokens", (int64_t)0), (int64_t)14);
/* The cached count sits where vLLM puts it and not at the top level. */
CHECK_EQ(o["usage"]["prompt_tokens_details"].value("cached_tokens", (int64_t)0), (int64_t)6);
/* logprobs is PRESENT AND NULL rather than absent, because a generated client deserialising
* into an optional field distinguishes "not asked for" from "the key does not exist". */
CHECK(o["choices"][0].contains("logprobs"));
CHECK(o["choices"][0]["logprobs"].is_null());
}
/* A TOOL CALL MAKES CONTENT NULL RATHER THAN EMPTY. The schema says a message with tool_calls has
* no content, and a client branching on `content == null` -- which several do -- reads an empty
* string as an ordinary text reply and never looks at the calls. */
TEST(a_chat_body_with_a_tool_call_sends_a_null_content) {
ChoiceOut c;
c.msg.tool_calls.push_back(ToolCall{ "call_1", "get_weather", "{\"city\":\"Berlin\"}" });
c.finish = Finish::ToolCalls;
const json o = parsed(chat_completion_body(a_request("chatcmpl-2", "m"), { c }, UsageOut{}));
const json& m = o["choices"][0]["message"];
CHECK(m["content"].is_null());
CHECK(m["tool_calls"].is_array());
CHECK_EQ(m["tool_calls"].size(), 1u);
CHECK_EQ(o["choices"][0].value("finish_reason", std::string()), std::string("tool_calls"));
/* Text beside a call keeps the text: content is only null when there is none. */
ChoiceOut both = c;
both.msg.content = "checking";
const json p = parsed(chat_completion_body(a_request("chatcmpl-3", "m"), { both }, UsageOut{}));
CHECK_EQ(p["choices"][0]["message"].value("content", std::string()), std::string("checking"));
/* Reasoning is carried under the key vLLM publishes, and only when there is some: an empty
* reasoning_content on every reply is noise in a transcript. */
CHECK(!p["choices"][0]["message"].contains("reasoning_content"));
ChoiceOut think;
think.msg.reasoning = "the user wants weather";
think.msg.content = "it is cold";
const json q = parsed(chat_completion_body(a_request("chatcmpl-4", "m"), { think }, UsageOut{}));
CHECK_EQ(q["choices"][0]["message"].value("reasoning_content", std::string()),
std::string("the user wants weather"));
}
TEST(a_text_completion_body_is_the_other_shape_entirely) {
ChoiceOut c;
c.text = "once upon a time";
c.finish = Finish::Stop;
UsageOut u;
u.prompt = 3;
u.completion = 4;
const json o = parsed(text_completion_body(a_request("cmpl-1", "m"), { c }, u));
CHECK_EQ(o.value("object", std::string()), std::string("text_completion"));
/* A completion choice carries `text` and no `message`; mixing the two is what makes one
* endpoint's response undeserialisable by the other endpoint's client. */
CHECK_EQ(o["choices"][0].value("text", std::string()), std::string("once upon a time"));
CHECK(!o["choices"][0].contains("message"));
CHECK_EQ(o["usage"].value("total_tokens", (int64_t)0), (int64_t)7);
}
/* THE LOGPROB SHAPES DIFFER BETWEEN THE TWO ENDPOINTS and both are fixed by the schema: chat
* nests an array of per-token objects under `content`, completions carries four parallel arrays.
* text_offset is cumulative over the token texts, which is what makes it an offset into `text`. */
TEST(logprobs_take_each_endpoints_own_shape) {
ChoiceOut c;
c.text = "abcd";
c.logprobs = { { 1, "ab", -0.5f }, { 2, "cd", -1.5f } };
OaiRequest r = a_request("x", "m");
r.want_logprobs = true;
const json chat = parsed(chat_completion_body(r, { c }, UsageOut{}));
const json& lp = chat["choices"][0]["logprobs"];
CHECK(lp["content"].is_array());
CHECK_EQ(lp["content"].size(), 2u);
CHECK_EQ(lp["content"][0].value("token", std::string()), std::string("ab"));
CHECK_NEAR(lp["content"][0].value("logprob", 0.0), -0.5, 1e-6);
CHECK(lp["content"][0]["bytes"].is_array());
CHECK_EQ(lp["content"][0]["bytes"].size(), 2u);
const json txt = parsed(text_completion_body(r, { c }, UsageOut{}));
const json& tl = txt["choices"][0]["logprobs"];
CHECK_EQ(tl["tokens"].size(), 2u);
CHECK_EQ(tl["token_logprobs"].size(), 2u);
CHECK_EQ(tl["text_offset"].size(), 2u);
CHECK_EQ(tl["text_offset"][0].get<int64_t>(), (int64_t)0);
CHECK_EQ(tl["text_offset"][1].get<int64_t>(), (int64_t)2);
}
/* AN SSE EVENT WITH NO CHOICES AND ONLY USAGE, which is what stream_options.include_usage asks
* for. Accepting the field and not emitting it leaves a client waiting for a chunk that never
* arrives, so the empty choices array has to be present rather than omitted. */
TEST(the_completion_usage_chunk_is_an_event_with_an_empty_choices_array) {
UsageOut u;
u.prompt = 5;
u.completion = 2;
const std::string ev = text_usage_chunk(a_request("cmpl-9", "m"), u);
CHECK(ev.rfind("data: ", 0) == 0);
CHECK(ev.compare(ev.size() - 2, 2, "\n\n") == 0);
const json o = json::parse(ev.substr(6, ev.size() - 8), nullptr, false);
CHECK(!o.is_discarded());
CHECK_EQ(o.value("object", std::string()), std::string("text_completion"));
CHECK(o["choices"].is_array());
CHECK_EQ(o["choices"].size(), 0u);
CHECK_EQ(o["usage"].value("total_tokens", (int64_t)0), (int64_t)7);
CHECK_EQ(o.value("id", std::string()), std::string("cmpl-9"));
}
/* THE BASE64 ENCODING IS PER-REQUEST AND IT IS THE RAW FLOAT BUFFER, which is what every client
* that asks for it unpacks. Sending the JSON array under that flag, or the base64 of a formatted
* array, both deserialise to nonsense rather than failing. */
TEST(an_embeddings_body_honours_the_encoding_the_request_asked_for) {
const std::vector<std::vector<float>> vecs = { { 1.0f, 2.0f }, { -0.5f, 0.25f } };
UsageOut u;
u.prompt = 8;
OaiRequest plain = a_request("emb-1", "m");
const json o = parsed(embeddings_body(plain, vecs, u));
CHECK_EQ(o.value("object", std::string()), std::string("list"));
CHECK_EQ(o["data"].size(), 2u);
CHECK_EQ(o["data"][0].value("object", std::string()), std::string("embedding"));
CHECK_EQ(o["data"][0].value("index", (int64_t)-1), (int64_t)0);
CHECK_EQ(o["data"][1].value("index", (int64_t)-1), (int64_t)1);
CHECK(o["data"][0]["embedding"].is_array());
CHECK_NEAR(o["data"][0]["embedding"][1].get<double>(), 2.0, 1e-6);
/* An embedding has no completion half, so total is the prompt. */
CHECK_EQ(o["usage"].value("prompt_tokens", (int64_t)0), (int64_t)8);
CHECK_EQ(o["usage"].value("total_tokens", (int64_t)0), (int64_t)8);
OaiRequest b64 = a_request("emb-2", "m");
b64.base64_embeddings = true;
const json e = parsed(embeddings_body(b64, vecs, u));
CHECK(e["data"][0]["embedding"].is_string());
std::vector<uint8_t> raw;
CHECK(base64_decode(e["data"][0]["embedding"].get<std::string>(), &raw));
CHECK_EQ(raw.size(), 2 * sizeof(float));
float back[2];
std::memcpy(back, raw.data(), sizeof back);
CHECK_NEAR(back[0], 1.0f, 1e-6);
CHECK_NEAR(back[1], 2.0f, 1e-6);
/* No inputs is an empty list rather than a null or an error: a caller that sent no strings
* gets no vectors, and the envelope is still the one its client deserialises. */
const json z = parsed(embeddings_body(plain, {}, UsageOut{}));
CHECK(z["data"].is_array());
CHECK_EQ(z["data"].size(), 0u);
}
RAD_TEST_MAIN()