radiance 2.1.0

New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an
IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill
attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by
launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash
drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441):
served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block
FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three
(round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r,
muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two
R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried.

Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an
optional delivery direction, by farcryjohn (#436). The published Breeze container needs
converting again with the updated recipe before it can.

Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving
and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by
category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison
against an earlier report (docs/DIAGNOSE.md), by Code000 (#418).

Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by
default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when
the device has advanced nothing for that long, so a restart policy brings a hung server back
(#409, #415, #428).

Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first
request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks
after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache
across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and
arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card
temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the
KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and
takes its toolchain from the tree.

Plugin ABI 40: out-of-tree plugins need to be rebuilt.

Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
This commit is contained in:
Deadcode committed 2026-11-15 16:00:05 +01:00
1 parent ddcb9c69bb
commit 2a2b756371
166 files changed
+20749 -327

No files matched your search

+27 -10
View File
@@ -10,12 +10,12 @@
# fast every test with none of slow, gpu, oot and perf, set at the end of this file: the
# inner loop (`ctest --preset fast`, or `ctest -L fast`)
#
# arch_test, glm5next_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply
# arch_test, bailing_hybrid_arch_test, flint_arch_test, glm5next_test, museglimmer_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply
# their own recording fake of the declare-phase C ABI (arch_fakes.h), so plugins are tested without
# depending on core/build/'s builder. With the archive linked, a new ABI call missing from the fake
# would pull in rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a
# single undefined reference.
set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test spark25_arch_test nemotronh_test)
set(RAD_TESTS_NO_CORE arch_test bailing_hybrid_arch_test breeze_arch_test flint_arch_test glm5next_test museglimmer_test nemotron35_test spark25_arch_test nemotronh_test)
# fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and
# the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and
@@ -137,6 +137,7 @@ set(RAD_TEST_CPU_BUDGET_tokenizer_test 20) # the reference encoder over every c
set(RAD_TEST_CPU_BUDGET_arch_test 15) # every plugin's graph declared; ~10.8 s with the batched-tower case
set(RAD_TEST_CPU_BUDGET_device_test 30) # on a card, the paging and remap cases spin in stream waits: ~10 s; with no card (the image's test stage) they copy, write and compare on the host: 17-19 s
set(RAD_TEST_CPU_BUDGET_glm5next_test 20) # GLM-5.3-Flash's graphs and op schemas: ~4.8 s built by GCC 16, ~10.1 s by GCC 14 (the image's Ubuntu)
set(RAD_TEST_CPU_BUDGET_museglimmer_test 10) # Muse Glimmer's trunk and tower graphs and steps: ~2 s built by GCC 14
# Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a
# team's worth of slots rather than one.
@@ -415,7 +416,7 @@ endif()
# arch_test and nemotronh_test read libref's vocabulary from $RADIANCE_HOME/kernels to check that
# each architecture declares on it, and glm5next_test the loaded libraries' op schemas, so libref is
# built before them.
foreach(t arch_test glm5next_test nemotronh_test)
foreach(t arch_test breeze_arch_test glm5next_test nemotronh_test)
if(TARGET libref AND TARGET ${t})
add_dependencies(${t} libref)
endif()
@@ -565,9 +566,10 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_kda.hip
${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip
${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip)
${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip
${R4D_DIR}/r4d_vit_muse.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc kda mla moefuse kvres
dsa lili)
dsa lili vit)
set(R4D_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
# No fiber switch for this ISA.
@@ -608,7 +610,8 @@ else()
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_mla.cpp
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp)
${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp
${R4D_EMU}/test_vit.cpp)
get_filename_component(stem ${src} NAME_WE)
set(lang "")
if(src MATCHES "\\.hip$")
@@ -645,7 +648,7 @@ else()
endif()
endif()
if(R4D_EMU_BUILT)
foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili)
foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili vit)
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
endforeach()
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
@@ -865,9 +868,23 @@ endif()
# standalone against it with find_package(radiance). The result must match the tree's plugins,
# vocabulary and registration, and serve rad-kbench's fixture through the installed tools
# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler,
# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes.
# targets, build type and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and
# takes minutes.
#
# An installed radiance finds ROCm through ROCM_PATH and HIP_PATH (radiance-config.cmake), so the
# test gets the root of the HIP runtime this tree links, and that root's tools first on PATH: the
# out-of-tree build then uses the tree's ROCm whatever the shell that runs ctest exports. Left to
# the caller's environment, a shell without them failed to find hip_runtime.h, and one naming
# another ROCm build linked the out-of-tree libr4d against that one's runtime.
set(RAD_OOT_COMPILER "")
set(RAD_OOT_TARGETS "")
set(RAD_OOT_ENV "")
if(RAD_HIP_FOUND AND RAD_HIP_RUNTIME)
get_filename_component(RAD_OOT_ROCM "${RAD_HIP_RUNTIME}" DIRECTORY)
get_filename_component(RAD_OOT_ROCM "${RAD_OOT_ROCM}" DIRECTORY)
set(RAD_OOT_ENV "ROCM_PATH=${RAD_OOT_ROCM}" "HIP_PATH=${RAD_OOT_ROCM}"
"PATH=${RAD_OOT_ROCM}/bin:${RAD_OOT_ROCM}/lib/llvm/bin:$ENV{PATH}")
endif()
if(RAD_HIP_FOUND AND TARGET libr4d)
get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES)
string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}")
@@ -877,13 +894,13 @@ endif()
add_test(NAME oot_plugins
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot "${RAD_OOT_COMPILER}" "${RAD_OOT_TARGETS}"
"${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}")
"${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}" "${CMAKE_BUILD_TYPE}")
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
set_tests_properties(oot_plugins PROPERTIES
LABELS "oot"
TIMEOUT 3600
RESOURCE_LOCK kbench_memory
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV}")
ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV};${RAD_OOT_ENV}")
# ================================================================== the kernel library, as a test
#
+8 -4
View File
@@ -1,4 +1,4 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 39 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 40 and
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
* from the test's printout only together with a version bump. */
@@ -142,7 +142,7 @@
{ "RadBuildCtx", "gen_max_refs", 184, 8 },
{ "RadBuildCtx", "expert_file_tier", 192, 4 },
{ "RadBuildCtx", "slot_base", 196, 4 },
{ "RadAudioGenBatch", "", 0, 344 },
{ "RadAudioGenBatch", "", 0, 352 },
{ "RadAudioGenBatch", "n_lane", 0, 8 },
{ "RadAudioGenBatch", "lane", 8, 8 },
{ "RadAudioGenBatch", "lane_h", 16, 8 },
@@ -188,7 +188,8 @@
{ "RadAudioGenBatch", "ref_cu_h", 320, 8 },
{ "RadAudioGenBatch", "ref_frame", 328, 8 },
{ "RadAudioGenBatch", "ref_frame_h", 336, 8 },
{ "RadAudioGenDecl", "", 0, 280 },
{ "RadAudioGenBatch", "prompt_cu_h", 344, 8 },
{ "RadAudioGenDecl", "", 0, 296 },
{ "RadAudioGenDecl", "name", 0, 8 },
{ "RadAudioGenDecl", "tmpl", 8, 8 },
{ "RadAudioGenDecl", "neg_token", 16, 4 },
@@ -228,6 +229,8 @@
{ "RadAudioGenDecl", "ref_hop", 256, 8 },
{ "RadAudioGenDecl", "ref_max_samples", 264, 8 },
{ "RadAudioGenDecl", "ref_max", 272, 4 },
{ "RadAudioGenDecl", "tmpl_ref_instruct", 280, 8 },
{ "RadAudioGenDecl", "neg_tmpl_ref", 288, 8 },
{ "RadControlVector", "", 0, 32 },
{ "RadControlVector", "dir", 0, 8 },
{ "RadControlVector", "scales", 8, 8 },
@@ -243,7 +246,7 @@
{ "RadAudioFormat", "language_lead", 48, 8 },
{ "RadAudioFormat", "languages", 56, 8 },
{ "RadAudioFormat", "n_languages", 64, 4 },
{ "RadChatFormat", "", 0, 208 },
{ "RadChatFormat", "", 0, 216 },
{ "RadChatFormat", "struct_size", 0, 4 },
{ "RadChatFormat", "name", 8, 8 },
{ "RadChatFormat", "reasoning_open", 16, 8 },
@@ -274,6 +277,7 @@
{ "RadChatFormat", "object_bare_keys", 192, 4 },
{ "RadChatFormat", "reasoning_anywhere", 196, 4 },
{ "RadChatFormat", "arg_json_value_prefix", 200, 8 },
{ "RadChatFormat", "content_open", 208, 8 },
{ "RadConstraint", "", 0, 32 },
{ "RadConstraint", "key", 0, 8 },
{ "RadConstraint", "op", 8, 4 },
+2 -2
View File
@@ -58,8 +58,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 39 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 39, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 40 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 40, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
+52
View File
@@ -301,6 +301,58 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) {
CHECK(cut_cases > 100);
}
/* ================================================================== ADV_COMPACT */
/* An accepted path's rows move to their committed positions whole, in every layer and head, and
* nothing else in the cache changes: at 512 bytes a row (bf16 and fp8 at head_dim 256 and 128)
* and at 516 and 260 (the int8 cache's K, V and two f16 scales, which is never whole 16-byte
* chunks). Run as the host backend does (one caller, every chunk) and as the kernel's 64 threads
* split a row; the path crosses a block boundary. A row that sampled nothing keeps its cache. */
TEST(a_trees_accepted_rows_move_whole_at_every_row_size) {
for (int row_bytes : { 512, 516, 260, 1028 }) {
for (int cstep : { 1, 64 }) {
Slab s(ADV_ACCEPT);
const int layers = 2, heads = 3, bs = 16, blocks = Slab::kPitch;
const int64_t stride = (int64_t)blocks * heads * bs * row_bytes + 64;
std::vector<uint32_t> cache((size_t)(layers * stride / 4));
uint32_t rng = 0xc0a9ac7u + (uint32_t)row_bytes;
for (uint32_t& v : cache) v = lcg(rng);
std::vector<uint32_t> want = cache;
s.row(0, true, 0, 8, 0, /*card=*/3, 0, /*rout=*/0, 7);
s.row(1, true, 8, 8, 0, /*card=*/5, 8, /*rout=*/-1, 7);
const int32_t path[3] = { 2, 5, 7 }, base = 28;
for (int card : { 3, 5 }) {
StepSlot& S = s.st[card];
S.acc = 3; S.npath = 3; S.head = base + 3;
std::memcpy(S.path, path, sizeof path);
}
s.a.n_pool = 1;
s.a.pool[0] = { reinterpret_cast<char*>(cache.data()), stride, layers, heads,
row_bytes, 0 };
auto at = [&](std::vector<uint32_t>& c, int l, int h, int pos) {
return reinterpret_cast<char*>(c.data()) + l * stride +
(((int64_t)(pos / bs) * heads + h) * bs + pos % bs) * row_bytes;
};
for (int l = 0; l < layers; ++l)
for (int h = 0; h < heads; ++h)
for (int t = 0; t < 3; ++t)
std::memcpy(at(want, l, h, base + t + 1), at(want, l, h, base + path[t]),
(size_t)row_bytes);
CHECK_EQ(adv_compact_items(s.a), layers * heads);
for (int i = 0; i < s.a.n_seq; ++i)
for (int w = 0; w < adv_compact_items(s.a); ++w) {
int p = 0, l = 0, h = 0;
CHECK(adv_compact_item(s.a, w, &p, &l, &h));
for (int c0 = 0; c0 < cstep; ++c0) adv_compact(s.a, i, p, l, h, c0, cstep);
}
CHECK(cache == want);
}
}
}
/* ================================================================== ADV_TRUNK */
/* A verify step issued ahead takes its rows from the StepSlots: the bonus token and the head's
+60
View File
@@ -209,6 +209,66 @@ TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) {
}
}
TEST(breeze_reference_rows_are_repeated_with_the_guidance_one_prompt) {
for (float cfg : {1.0f, 2.0f}) {
AudioFixture f;
f.build();
f.prog.audio_gen.ref_max = 1;
f.prog.audio_gen.ref_rate = 50;
f.prog.audio_gen.ref_hop = 4;
f.prog.audio_gen.ref_max_samples = 8;
CHECK_OK(f.start());
auto r = f.req(cfg);
r->ref_audio.assign(4, 0.25f);
r->ref_cu = {0, 4};
r->ref_frame = {-1, 0, -1, -1};
std::string why;
if (cfg != 1.0f) {
CHECK_EQ(f.drv.submit(std::move(r), &why), RAD_E_INVAL);
CHECK(has(why, "guidance_scale 1"));
continue;
}
CHECK_OK(f.drv.submit(std::move(r), &why));
const RadBatch* b = f.drv.next(0);
REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT);
const auto* A = b->agen_b;
REQUIRE(A->ref_frame_h != nullptr && A->ref_frame != nullptr);
CHECK_EQ(A->ref_frame_h[1], 0);
CHECK_EQ(A->ref_frame_h[4], -1);
CHECK_EQ(A->ref_frame_h[5], cfg == 1.0f ? 0 : -1);
for (int64_t i = 0; i < b->n_tok; ++i) CHECK_EQ(A->ref_frame[i], A->ref_frame_h[i]);
CHECK_EQ(A->ref_samples, (int64_t)4);
f.answer(b, 0, 0);
CHECK_OK(f.drv.done());
}
}
TEST(reference_direction_keeps_each_guidance_branchs_reference_map) {
for (float cfg : {1.0f, 4.0f}) {
AudioFixture f;
f.build();
f.prog.audio_gen.ref_max = 1;
f.prog.audio_gen.ref_rate = 50;
f.prog.audio_gen.ref_hop = 4;
f.prog.audio_gen.ref_max_samples = 8;
CHECK_OK(f.start());
auto r = f.req(cfg);
r->ref_audio.assign(4, 0.25f); r->ref_cu = {0, 4};
r->ref_frame = {-1, 0, -1, -1}; r->neg_ref_frame = {-1, 0};
std::string why;
CHECK_OK(f.drv.submit(std::move(r), &why));
const RadBatch* b = f.drv.next(0);
REQUIRE(b && b->agen_b && b->agen_b->prompt_cu_h);
CHECK_EQ(b->n_tok, (int64_t)(cfg == 1.0f ? 8 : 6));
CHECK_EQ(b->agen_b->prompt_cu_h[1], 4);
CHECK_EQ(b->agen_b->prompt_cu_h[2], b->n_tok);
CHECK_EQ(b->agen_b->ref_frame_h[5], 0);
for (int64_t i = 0; i < b->n_tok; ++i)
CHECK_EQ(b->agen_b->ref_frame[i], b->agen_b->ref_frame_h[i]);
f.answer(b, 0, 0); CHECK_OK(f.drv.done());
}
}
/* A hybrid language model (paged attention beside a linear-attention state and a convolution
* group, as Qwen3.5's delta-net layers keep) of one branch: every pass stages one sequence a
* request, the state groups' rows are the sequence's slots, and each entry carries its context
+529
View File
@@ -0,0 +1,529 @@
/* Ling-3.0's declaration and step (arch/bailing_hybrid), without a GPU or checkpoint: the IQ8R
* container data/recipes/ling-3.0-tiny-iq8r.recipe makes, at one and two ranks, and the bf16 and
* four-bit containers, tiny and flash (with its MTP layer). */
#define RAD_ARCH_NO_EXPORTS 1
#include "arch_fakes.h"
#include "rad_plugin.h"
#include "../arch/bailing_hybrid/bailing_hybrid.cpp"
using namespace rad_fake;
namespace {
/* Ling-3.0-tiny's configuration as rad-convert records it. */
MetaKV tiny_meta() {
RadModelMeta m{};
m.arch_id = "bailinghybrid";
m.name = "test-ling-tiny";
m.quant = "";
m.n_layers = 24;
m.n_embd = 1536;
m.n_head = 16;
m.n_head_kv = 16;
m.head_dim = 128;
m.n_ff = 4608;
m.n_vocab = 157184;
m.n_ctx_train = 131072;
m.rms_eps = 1e-6f;
m.rope_theta = 6e6f;
m.n_expert = 128;
m.n_expert_used = 8;
MetaKV k(m);
k.set("num_attention_heads", "16").set("head_dim", "128").set("qk_nope_head_dim", "128")
.set("qk_rope_head_dim", "64").set("v_head_dim", "128").set("kv_lora_rank", "512")
.set("num_experts", "128").set("num_experts_per_tok", "8").set("n_group", "8")
.set("topk_group", "4").set("moe_intermediate_size", "512")
.set("moe_shared_expert_intermediate_size", "512").set("num_shared_experts", "1")
.set("intermediate_size", "4608").set("first_k_dense_replace", "1")
.set("layer_group_size", "4").set("short_conv_kernel_size", "4").set("q_lora_rank", "256")
.set("kda_lower_bound", "-5").set("routed_scaling_factor", "2.5").set("no_kda_lora", "1")
.set("kda_safe_gate", "1").set("rope_interleave", "1")
.set("gated_attention_proj_granularity_type", "head_wise").set("score_function", "sigmoid")
.set("num_nextn_predict_layers", "0").set("norm_topk_prob", "1");
return k;
}
/* Ling-3.0-flash's: 42 layers of 2560, MLA every sixth with no query LoRA, two dense layers, 512
* experts of 768, the SwiGLU clamped in the last layers, one MTP layer. */
MetaKV flash_meta() {
MetaKV k = tiny_meta();
k.m.name = "test-ling-flash";
k.m.n_layers = 42;
k.m.n_embd = 2560;
k.m.n_head = 32;
k.m.n_head_kv = 32;
k.m.n_ff = 6144;
k.m.n_expert = 512;
std::string routed, shared;
for (int l = 0; l < 42; ++l) {
routed += std::string(l ? "," : "") + (l >= 35 ? "4" : "0");
shared += std::string(l ? "," : "") + (l >= 40 ? "7" : l >= 34 ? "5" : "0");
}
k.set("num_attention_heads", "32").set("num_experts", "512")
.set("moe_intermediate_size", "768").set("moe_shared_expert_intermediate_size", "768")
.set("intermediate_size", "6144").set("first_k_dense_replace", "2")
.set("layer_group_size", "6").set("q_lora_rank", "0").set("num_nextn_predict_layers", "1")
.set("expert_swiglu_limit_list", routed.c_str())
.set("share_expert_swiglu_limit_list", shared.c_str());
return k;
}
/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under
* a bf16 scale a row. */
RadEncoding iq8r() {
RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256);
rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0);
rad_enc_copy_str(e.transform, "fwht128");
return e;
}
/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */
RadEncoding i8h() {
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
rad_enc_copy_str(e.transform, "fwht128");
return e;
}
const RadEncoding kI4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
/* data/recipes/ling-3.0-tiny-iq8r.recipe's encodings by declared name, every other weight plain
* bf16. `attn_gate.weight` is the KDA output gate; the MLA's head gate is `attn_head_gate`. */
void iq8r_encs(RadBuilder* b) {
b->encs.clear();
for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" })
b->encs.push_back({ t, i8h() });
for (const char* t : { "attn_qkv.weight", "attn_forget.weight", "attn_gate.weight",
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight",
"ffn_gate_up_shexp" })
b->encs.push_back({ t, iq8r() });
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
}
/* data/recipes/ling3-w4a8-rtn.recipe's: four-bit routed experts, everything else bf16. */
void w4_encs(RadBuilder* b) {
b->encs.clear();
b->encs.push_back({ "ffn_gate_up_exps", kI4 });
b->encs.push_back({ "ffn_down_exps", kI4 });
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
}
/* The bf16 checkpoint. */
void bf16_encs(RadBuilder* b) {
b->encs.clear();
b->encs.push_back({ "", rad_enc_plain(RAD_BF16) });
}
bool is_mla(int l) { return (l + 1) % 4 == 0; }
const std::string& wname(const RadBuilder& b, rad_weight w) { return b.weights[w - 1].name; }
/* The buffer a name declared, 0 if none. */
rad_buf buf(const RadBuilder& b, const char* n) {
for (size_t i = 0; i < b.bufs.size(); ++i)
if (b.bufs[i].name == n) return (rad_buf)(i + 1);
return 0;
}
/* graph_hash with the name maps in declared-name order (stable, so maps that extend one name keep
* theirs): where among the other declarations a map is made (the trunk probe maps layer 0's
* q|k|v ahead of the buffers) is not part of what the core builds from it. */
uint64_t graph_hash_maps_by_name(const RadBuilder& b0) {
RadBuilder b = b0;
std::stable_sort(b.maps.begin(), b.maps.end(),
[](const RecMap& x, const RecMap& y) { return x.declared < y.declared; });
return graph_hash(b);
}
/* A decode step, a prefill of two prompts and a mixed step, each pass clean. */
void steps_lint_clean(RadBuilder& b, int rank, int world) {
const auto dc = kit(b, { 1, 1, 1 }, {});
const auto pf = kit(b, {}, { 64, 100 }, 0);
const auto mx = kit(b, { 1, 1 }, { 120 }, 300);
for (const Kit* k : { dc.get(), pf.get(), mx.get() }) {
auto v = run_passes(b, bailing_hybrid::step, { k }, rank, world);
CHECK_PASSES(b, v);
}
}
} /* namespace */
/* The IQ8R container at one rank and both ranks of two: every trunk linear the recipe quantises is
* one gemm_nt_q at i8a8h, its N and K this rank's, reading the codes of the producer that feeds it
* at that producer's group; the linears the recipe keeps bf16 are gemm_nt over the norm's bf16
* output; the grouped GEMMs are the int8 rows. No E4M3 code and no unrotated int8 quantiser
* exist, and no linear quantises its own input. */
TEST(iq8r_container_declares_the_rotated_int8_trunk) {
for (int world : { 1, 2 })
for (int rank = 0; rank < world; ++rank) {
MetaKV mk = tiny_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx(rank, world);
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
const bailing_hybrid::Model& m = bailing_hybrid::g_model[rank];
CHECK(m.trunk_rot);
CHECK(m.norm_fed);
CHECK_EQ(m.trunk_g8, 256);
const int64_t H = 16 / world, W = 128 * H, FF = 4608 / world, SH = 512 / world,
EX = 512 / world;
const rad_buf normed = buf(b, "normed"), nq = buf(b, "normed.q8"),
ns = buf(b, "normed.s8"), kq = buf(b, "kda_out.q8"),
vq = buf(b, "mla_value.q8"), dq = buf(b, "dense_ff.q8"),
sq = buf(b, "shared_ff.q8"), eq = buf(b, "expert_ff.q8"),
qa = buf(b, "mla_q_a");
REQUIRE(normed && nq && ns && kq && vq && dq && sq && eq && qa);
CHECK_EQ(m.act.q8, (uint32_t)nq);
/* ---- each quantised linear: N, K, group, the codes it reads. */
struct Want { int64_t N, K, group; rad_buf in; int n; };
std::map<std::string, Want> want;
for (int l = 0; l < 24; ++l) {
char n[96];
if (is_mla(l)) {
std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l);
want[n] = { 1536, H * 128, 256, vq, 0 };
} else {
std::snprintf(n, sizeof n, "blk.%d.attn_qkv.weight", l);
want[n] = { 3 * W, 1536, 256, nq, 0 };
std::snprintf(n, sizeof n, "blk.%d.attn_forget.weight", l);
want[n] = { W, 1536, 256, nq, 0 };
std::snprintf(n, sizeof n, "blk.%d.attn_gate.weight", l);
want[n] = { W, 1536, 256, nq, 0 };
std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l);
want[n] = { 1536, W, 256, kq, 0 };
}
if (l == 0) {
want["blk.0.ffn_gate_up.weight"] = { 2 * FF, 1536, 256, nq, 0 };
want["blk.0.ffn_down.weight"] = { 1536, FF, 256, dq, 0 };
} else {
std::snprintf(n, sizeof n, "blk.%d.ffn_gate_up_shexp.weight", l);
want[n] = { 2 * SH, 1536, 256, nq, 0 };
std::snprintf(n, sizeof n, "blk.%d.ffn_down_shexp.weight", l);
want[n] = { 1536, SH, 128, sq, 0 };
}
}
int q = 0;
for (const auto& o : b.ops) {
if (o.op != "gemm_nt_q") continue;
++q;
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
REQUIRE(!o.w.empty());
auto it = want.find(wname(b, o.w[0]));
REQUIRE(it != want.end());
Want& x = it->second;
++x.n;
CHECK_EQ(pint(&o, "N"), x.N);
CHECK_EQ(pint(&o, "K"), x.K);
CHECK_EQ(pint(&o, "group"), x.group);
CHECK(in(o.reads, x.in));
}
CHECK_EQ(q, 18 * 4 + 6 + 2 + 23 * 2);
for (const auto& [name, x] : want) CHECK_EQ(x.n, 1);
/* ---- the linears the recipe keeps bf16, over the norm's bf16 output (the query parts
* over the LoRA's normed latent). */
int keep = 0;
for (const auto& o : b.ops) {
if (o.op != "gemm_nt" || o.w.empty()) continue;
const std::string& n = wname(b, o.w[0]);
const bool lora = n.find("attn_q_rope") != std::string::npos ||
n.find("attn_q_nope") != std::string::npos;
if (n.find("attn_beta") == std::string::npos &&
n.find("attn_q_a.") == std::string::npos &&
n.find("attn_kv_a.") == std::string::npos &&
n.find("attn_head_gate") == std::string::npos && !lora)
continue;
++keep;
CHECK_EQ(pstr(&o, "dtype"), std::string("bf16"));
CHECK(in(o.reads, lora ? qa : normed));
CHECK(!in(o.reads, nq));
}
CHECK_EQ(keep, 18 + 6 * 5);
/* ---- the producers and their groups. */
int norms = 0, outq = 0, dense = 0, shared = 0, routed = 0;
for (const auto& o : b.ops) {
if (o.op == "rmsnorm_had_quant_i8g") {
++norms;
CHECK_EQ(pint(&o, "group"), 256);
CHECK_EQ(pint(&o, "n"), 1536);
CHECK(in(o.writes, nq) && in(o.writes, ns) && in(o.writes, normed));
} else if (o.op == "had_quant_act_i8g") {
++outq;
CHECK_EQ(pint(&o, "group"), 256);
const bool kda = in(o.writes, kq);
CHECK(kda || in(o.writes, vq));
CHECK_EQ(pint(&o, "n"), kda ? W : H * 128);
} else if (o.op == "gated_had_quant_i8g") {
if (in(o.writes, dq)) {
++dense;
CHECK_EQ(pint(&o, "group"), 256);
CHECK_EQ(pint(&o, "n"), FF);
} else if (in(o.writes, sq)) {
++shared;
CHECK_EQ(pint(&o, "group"), 128);
CHECK_EQ(pint(&o, "n"), SH);
} else {
CHECK(in(o.writes, eq));
++routed;
CHECK_EQ(pint(&o, "group"), 128);
CHECK_EQ(pint(&o, "n"), EX);
}
}
}
CHECK_EQ(norms, 48);
CHECK_EQ(outq, 18 + 6);
CHECK_EQ(dense, 1);
CHECK_EQ(shared, 23);
CHECK_EQ(routed, 23);
for (const char* op : { "rmsnorm_quant_fp8", "ar_rmsnorm_quant_fp8",
"ar_rmsnorm_had_quant_i8g", "quant_act_fp8", "quant_act_i8g",
"gated_quant_fp8", "had_quant_act_fp8", "gated_had_quant_fp8",
"swiglu_step", "silu_mul" })
CHECK_EQ(count_op(b, op), 0);
for (const char* n : { "normed.q", "kda_out.q", "mla_value.q", "mla_q_a.q",
"dense_ff.q", "shared_ff.q", "expert_ff.q", "normed_rot.q",
"normed_rot.q8" })
CHECK(find_b(b, n) == nullptr);
/* ---- the routed experts: rotated int8 rows, gate_up over the norm's codes at 256,
* down over the gated product's at 128, each rank a slice of every expert. */
int gu = 0, dn = 0;
for (const auto& o : b.ops) {
if (o.op != "moe_gemm_q") continue;
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
const bool token = pstr(&o, "a_order") == "token";
CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128);
CHECK(in(o.reads, token ? nq : eq));
CHECK_EQ(pint(&o, "N"), token ? 2 * EX : 1536);
CHECK_EQ(pint(&o, "K"), token ? 1536 : EX);
CHECK_EQ(pint(&o, "n_expert"), 128);
(token ? gu : dn) += 1;
}
CHECK_EQ(gu, 23);
CHECK_EQ(dn, 23);
const RecWeight* e0 = find_w(b, "blk.1.ffn_gate_up_exps.127.weight");
REQUIRE(e0 != nullptr);
CHECK_EQ(e0->d.dtype, (uint32_t)RAD_I8);
CHECK_EQ((int)e0->d.shard, (int)RAD_SHARD_ROW);
steps_lint_clean(b, rank, world);
}
}
/* The IQ8R container shards as the bf16 one does: every weight both declare outside the routed
* experts is split the same way, and the collectives are the same standalone all-reduces (the plugin's norms take no
* collective, so no `ar_` norm is declared at two ranks). */
TEST(iq8r_container_follows_the_plugins_sharding) {
for (int world : { 1, 2 }) {
MetaKV mk = tiny_meta();
RadBuilder q, f;
iq8r_encs(&q);
bf16_encs(&f);
RadBuildCtx cq = build_ctx(0, world), cf = build_ctx(0, world);
cf.slot_base = 4;
REQUIRE_EQ(bailing_hybrid::declare(&q, mk.meta(), &cq), RAD_OK);
REQUIRE_EQ(bailing_hybrid::declare(&f, mk.meta(), &cf), RAD_OK);
int same = 0;
for (const RecWeight& w : q.weights) {
const RecWeight* o = find_w(f, w.name);
if (!o || w.name.find("_exps.") != std::string::npos) continue;
++same;
CHECK_EQ(w.d.shard, o->d.shard);
CHECK_EQ(w.d.n_row_parts, o->d.n_row_parts);
}
CHECK(same > 300);
CHECK_EQ(count_op(q, "all_reduce"), count_op(f, "all_reduce"));
CHECK_EQ(count_op(q, "all_reduce"), world == 2 ? 1 + 24 + 24 : 0);
/* Rotated int8 experts are a slice of every expert on each rank, where bf16 ones are
* whole on one. */
CHECK(find_w(q, "blk.1.ffn_gate_up_exps.0.weight") != nullptr);
CHECK(find_w(q, "blk.1.ffn_gate_up_exps.127.weight") != nullptr);
}
}
/* Where no loaded library serves the rotating norm (a CPU-only engine), the norms write E4M3
* codes no linear reads, every int8 trunk linear quantises the norm's bf16 output itself at the
* trunk's group, and the routed gate_up reads a rotated int8 copy written once a layer at 128. */
TEST(iq8r_container_without_the_rotating_norm_quantises_each_input) {
for (int world : { 1, 2 }) {
MetaKV mk = tiny_meta();
RadBuilder b;
b.undeclared.insert("rmsnorm_had_quant_i8g");
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx(0, world);
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
CHECK(bailing_hybrid::g_model[0].trunk_rot);
CHECK(!bailing_hybrid::g_model[0].norm_fed);
CHECK_EQ(count_op(b, "rmsnorm_quant_fp8"), 48);
const rad_buf normed = buf(b, "normed"), hr = buf(b, "normed_rot.q8");
REQUIRE(hr != 0);
int own = 0, copy = 0;
for (const auto& o : b.ops) {
if (o.op == "had_quant_act_i8g" && in(o.reads, normed)) {
const bool c = in(o.writes, hr);
(c ? copy : own) += 1;
CHECK_EQ(pint(&o, "group"), c ? 128 : 256);
}
if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") {
CHECK_EQ(pint(&o, "a_group"), 128);
CHECK(in(o.reads, hr));
}
}
/* q|k|v, forget and gate on 18 layers, the dense gate_up, 23 shared gate_ups. */
CHECK_EQ(own, 18 * 3 + 1 + 23);
CHECK_EQ(copy, 23);
steps_lint_clean(b, 0, world);
}
}
/* A shared expert whose down projection is stored IQ8R too takes its input codes at 256. */
TEST(iq8r_shared_down_sets_its_inputs_group) {
MetaKV mk = tiny_meta();
RadBuilder b;
iq8r_encs(&b);
b.encs.insert(b.encs.begin(), { "ffn_down_shexp", iq8r() });
RadBuildCtx ctx = build_ctx();
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
const rad_buf sq = buf(b, "shared_ff.q8");
int n = 0;
for (const auto& o : b.ops)
if (o.op == "gated_had_quant_i8g" && in(o.writes, sq)) {
CHECK_EQ(pint(&o, "group"), 256);
++n;
}
CHECK_EQ(n, 23);
CHECK_EQ(find_b(b, "shared_ff.s8")->d.shape[1], 2);
}
/* The bf16 and four-bit containers at one rank and both ranks of two, tiny and flash (with its
* MTP layer under speculation), pinned by their graphs' fingerprints: no int8 op, E4M3 codes from
* the norms, and the four-bit experts reading the norm's E4M3 pair at w4a8. */
TEST(bf16_and_four_bit_containers_keep_their_graphs) {
struct Case { bool flash, w4; int world, rank; uint64_t hash; };
const Case cases[] = {
{ false, false, 1, 0, 0x86ab7d6c2a6c7d9aull },
{ false, false, 2, 0, 0x08a9d5eac89cbfdcull },
{ false, false, 2, 1, 0x6bbc016892e93dacull },
{ false, true, 1, 0, 0xcdcf0243f2a0c792ull },
{ false, true, 2, 0, 0xda4c82105c0feb47ull },
{ false, true, 2, 1, 0xd94daa2c5c90352bull },
{ true, false, 1, 0, 0x21f7c41f985de35eull },
{ true, false, 2, 0, 0x0420376396574defull },
{ true, false, 2, 1, 0xb7df9b2e13bc4ae6ull },
{ true, true, 1, 0, 0xf9dec754da195628ull },
{ true, true, 2, 0, 0x7da4ef872c9304e9ull },
{ true, true, 2, 1, 0xcc97ada7f98fca85ull },
};
for (const Case& c : cases) {
MetaKV mk = c.flash ? flash_meta() : tiny_meta();
RadBuilder b;
if (c.w4) w4_encs(&b); else bf16_encs(&b);
RadBuildCtx ctx = build_ctx(c.rank, c.world);
if (c.flash) ctx.max_spec = 3;
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
const bailing_hybrid::Model& m = bailing_hybrid::g_model[c.rank];
CHECK(!m.trunk_rot);
CHECK_EQ(m.have_mtp, c.flash);
CHECK_EQ(graph_hash_maps_by_name(b), c.hash);
CHECK(count_op(b, "rmsnorm_quant_fp8") > 0);
for (const char* op : { "rmsnorm_had_quant_i8g", "had_quant_act_i8g",
"gated_had_quant_i8g", "gemm_nt_q" })
CHECK_EQ(count_op(b, op), 0);
if (c.w4) {
const rad_buf nq = buf(b, "normed.q");
int moe = 0;
for (const auto& o : b.ops)
if (o.op == "moe_gemm_q") {
CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8"));
if (pstr(&o, "a_order") == "token") CHECK(in(o.reads, nq));
++moe;
}
CHECK_EQ(moe, 2 * (c.flash ? 41 : 23));
}
if (!c.flash) steps_lint_clean(b, c.rank, c.world);
}
}
/* What the plugin refuses by name: a rotated trunk over unrotated experts, rotated int8 experts
* under an unrotated trunk, an IQ8R trunk over a clamped SwiGLU (flash's last layers), and the
* tiny IQ8R trunk at four ranks, whose 1152-column dense slice cuts a 256-column scale group. */
TEST(refuses_mismatched_forms) {
{
MetaKV mk = tiny_meta();
RadBuilder b;
iq8r_encs(&b);
for (auto& e : b.encs)
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = kI4;
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
{
MetaKV mk = tiny_meta();
RadBuilder b;
w4_encs(&b);
for (auto& e : b.encs)
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h();
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
{
MetaKV mk = flash_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
{
MetaKV mk = tiny_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx(0, 4);
CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
}
/* Flash's IQ8R trunk with the clamp lists cut declares, MTP layer included: the drafter's MLA and
* routed feed-forward read the trunk's codes like any trunk layer. */
TEST(flash_iq8r_without_clamps_declares_its_drafter_on_the_int8_trunk) {
for (int world : { 1, 2 }) {
MetaKV mk = flash_meta();
mk.drop("expert_swiglu_limit_list").drop("share_expert_swiglu_limit_list");
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx(0, world);
ctx.max_spec = 3;
REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK);
const bailing_hybrid::Model& m = bailing_hybrid::g_model[0];
CHECK(m.trunk_rot);
CHECK(m.have_mtp);
const RecWeight* d = find_w(b, "blk.42.attn_output.weight");
REQUIRE(d != nullptr);
CHECK_EQ(d->d.dtype, (uint32_t)RAD_I8);
/* 40 routed layers and the drafter's; two norms a layer. */
CHECK_EQ(count_op(b, "moe_gemm_q"), 2 * 41);
CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 2 * 43);
}
}
/* Per-instance state lives in the declaring instance's slot, so a second engine in the process
* leaves the first one's model alone. */
TEST(declares_into_its_own_slot) {
MetaKV mk = tiny_meta();
RadBuilder b0, b1;
iq8r_encs(&b0);
w4_encs(&b1);
RadBuildCtx c0 = build_ctx();
RadBuildCtx c1 = build_ctx();
c1.slot_base = 4;
REQUIRE_EQ(bailing_hybrid::declare(&b0, mk.meta(), &c0), RAD_OK);
REQUIRE_EQ(bailing_hybrid::declare(&b1, mk.meta(), &c1), RAD_OK);
CHECK(bailing_hybrid::g_model[0].trunk_rot);
CHECK(!bailing_hybrid::g_model[4].trunk_rot);
CHECK_EQ(bailing_hybrid::g_model[4].s.n_layer, 24);
}
RAD_TEST_MAIN()
+150
View File
@@ -0,0 +1,150 @@
/* Recording tests of Breeze's reference encoder and prompt assembly; no weights or GPU. */
#define RAD_ARCH_NO_EXPORTS 1
#include "arch_fakes.h"
#include <dlfcn.h>
#include "../arch/breeze/breeze.cpp"
extern "C" int rad_declare_audio_generator(RadBuilder*, const RadAudioGenDecl*) { return RAD_OK; }
namespace {
struct Fixture {
RadBuilder b;
breeze::Model m;
Fixture() {
m.gl.max_tok = 1024;
m.gl.n_embd = 2048;
m.ge = m.gl;
m.b_x = rad::arch::decl_b(&b, "lm.x", RAD_BF16, {1024, 2048});
m.w_cb = rad::arch::decl_w(&b, "frame.codebooks.weight", RAD_BF16, {16 * 2051, 2048},
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, rad::arch::grp_layer(0));
const char* keys[] = {"text_encoder_config.layer_types", "text_encoder_config.num_hidden_layers",
"audio_tokenizer.encoder_config.hidden_size", "audio_tokenizer.encoder_config.num_hidden_layers",
"audio_tokenizer.encoder_config.num_filters"};
const char* vals[] = {"full_attention", "1", "512", "8", "64"};
RadModelMeta meta{};
meta.n_kv = 5; meta.kv_key = keys; meta.kv_val = vals;
CHECK_OK(breeze::declare_encoder(&b, &meta, m));
CHECK_OK(breeze::declare_reference(&b, &meta, m));
}
};
}
TEST(breeze_clone_encodes_text_segments_independently_and_audio_only_once) {
Fixture f;
/* Three text rows, two reference frames, one audio EOS, three new text rows, twice. */
int32_t tokens[18]{}, positions[18]{}, cu[] = {0, 9, 18}, ref_cu[] = {0, 3840};
int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1,
-1, -1, -1, 0, 1, -1, -1, -1, -1};
int32_t last[] = {0};
float audio = 0;
RadAudioGenBatch A{};
A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840;
A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio; A.ref_frame_h = map;
A.prompt_cu_h = cu;
RadBatch batch{};
batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 18; batch.n_seq = 2;
batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A;
RadCtx c; c.b = &f.b; c.batch = &batch;
breeze::step_prompt(&c, &batch, f.m);
int text_segments = 0, reference_encodes = 0, quantisers = 0, embeddings = 0;
std::vector<int64_t> output_offsets;
for (const auto& issue : c.issues) {
if (issue.op == f.m.op_eembed) {
++text_segments;
CHECK_EQ(issue.n, (int64_t)3);
}
if (issue.op == f.m.enc[0].op_qknr)
CHECK_EQ(issue.opd[1].handle, f.m.ref.text_pos);
if (issue.op == f.m.op_eproj) output_offsets.push_back(issue.opd.back().offset / 2048);
if (issue.op == f.m.ref.first.op) ++reference_encodes;
if (f.b.ops[issue.op - 1].op == "vq_euclidean") {
++quantisers; CHECK_EQ(issue.n, (int64_t)2);
}
if (issue.op == f.m.ref.embed) {
++embeddings;
/* rvq_embed's second table starts at codebook 1, not at codebook 0.
* The same slice is required for the reference frames and their audio EOS. */
CHECK_EQ(issue.opd[1].handle, f.m.w_cb);
CHECK_EQ(issue.opd[1].offset, (int64_t)0);
CHECK_EQ(issue.opd[2].handle, f.m.w_cb);
CHECK_EQ(issue.opd[2].offset, (int64_t)2051 * 2048);
CHECK_EQ(issue.opd[2].rows, (int64_t)15 * 2051);
}
}
CHECK_EQ(text_segments, 4);
CHECK_EQ(reference_encodes, 1);
CHECK_EQ(quantisers, 16);
CHECK_EQ(embeddings, 4); /* a clip and its EOS in each branch */
CHECK(output_offsets == std::vector<int64_t>({0, 6, 9, 15}));
CHECK_LINT(f.b, &c);
}
TEST(breeze_reference_transcripts_cannot_inject_audio_or_template_markers) {
char out[128];
CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, "the reference words", out, sizeof(out)), 19);
for (const char* marker : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>", "<ins_bos>", "<ins_eos>"})
CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, marker, out, sizeof(out)), (int64_t)RAD_E_INVAL);
}
TEST(breeze_reference_direction_uses_actual_unequal_branch_boundaries) {
Fixture f;
int32_t tokens[22]{}, positions[22]{}, cu[] = {0, 13, 22}, ref_cu[] = {0, 3840};
int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 0, 1, -1, -1, -1, -1};
int32_t last[] = {0}; float audio = 0;
RadAudioGenBatch A{};
A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840;
A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio;
A.ref_frame_h = map; A.prompt_cu_h = cu;
RadBatch batch{};
batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 22; batch.n_seq = 2;
batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A;
RadCtx c; c.b = &f.b; c.batch = &batch;
breeze::step_prompt(&c, &batch, f.m);
std::vector<int64_t> lengths, offsets;
int encodes = 0;
for (const auto& issue : c.issues) {
if (issue.op == f.m.op_eembed) lengths.push_back(issue.n);
if (issue.op == f.m.op_eproj) offsets.push_back(issue.opd.back().offset / 2048);
if (issue.op == f.m.ref.first.op) ++encodes;
}
CHECK(lengths == std::vector<int64_t>({3, 7, 3, 3}));
CHECK(offsets == std::vector<int64_t>({0, 6, 13, 19}));
CHECK_EQ(encodes, 1);
CHECK_LINT(f.b, &c);
}
TEST(breeze_reference_declarations_use_the_real_kernel_vocabulary) {
const char* home = std::getenv("RADIANCE_HOME");
REQUIRE(home != nullptr);
void* lib = dlopen((std::string(home) + "/kernels/libref.so").c_str(), RTLD_NOW | RTLD_LOCAL);
REQUIRE(lib != nullptr);
auto count = (int (*)())dlsym(lib, "rad_kernel_schema_count");
auto at = (const RadOpSchema* (*)(int))dlsym(lib, "rad_kernel_schema_at");
REQUIRE(count && at);
std::map<std::string, const RadOpSchema*> schemas;
for (int i = 0; i < count(); ++i) schemas[at(i)->op] = at(i);
Fixture f;
for (const auto& op : f.b.ops) {
REQUIRE(schemas.count(op.op) != 0);
const auto* s = schemas.at(op.op);
for (const auto& p : op.p) {
bool known = false;
for (int i = 0; i < s->n_params; ++i) known |= p.key == s->params[i].key;
CHECK(known);
}
for (int i = 0; i < s->n_params; ++i) {
if (!s->params[i].required) continue;
CHECK(std::any_of(op.p.begin(), op.p.end(), [&](const auto& p) { return p.key == s->params[i].key; }));
}
size_t min_w = 0, max_w = 0;
for (int i = 0; i < s->n_operands; ++i) if (s->operands[i].role == RAD_OPD_WEIGHT) {
++max_w; if (!s->operands[i].optional) ++min_w;
}
CHECK(op.w.size() >= min_w && op.w.size() <= max_w);
for (auto w : op.w) CHECK(w != 0 && w <= f.b.weights.size());
}
dlclose(lib);
}
RAD_TEST_MAIN()
+44
View File
@@ -367,6 +367,50 @@ TEST(replayed_tool_call_arguments_render_as_parameter_xml) {
CHECK(pb.prompt.find("<function=read>") != std::string::npos);
}
/* A tool-call round in the current turn, as a client replays it, with the call's arguments as
* `args` (absent when null). */
static json replayed_round(const json* args) {
json fn = {{"name", "read"}};
if (args) fn["arguments"] = *args;
json msgs = json::array();
msgs.push_back({{"role", "user"}, {"content", "Read /work/a.py."}});
msgs.push_back({{"role", "assistant"}, {"content", ""},
{"tool_calls", json::array({{{"id", "c1"}, {"type", "function"},
{"function", fn}}})}});
msgs.push_back({{"role", "tool"}, {"tool_call_id", "c1"}, {"content", "print(1)\n"}});
return msgs;
}
/* A call without arguments, replayed as "" (a stored stream) or with no `arguments`, is the
* empty object. Refusing it refused every later turn of the conversation. */
TEST(a_replayed_call_with_empty_or_absent_arguments_is_the_empty_object) {
if (!qwen().need()) return;
const json empty = "", spaces = " \n", obj = "{}";
ChatPrompt want;
ChatOptions opt;
CHECK_OK(qwen().t->apply(replayed_round(&obj), tools_json(), opt, &want));
CHECK(want.prompt.find("<function=read>\n</function>") != std::string::npos);
for (const json* a : {&empty, &spaces, (const json*)nullptr}) {
ChatPrompt p;
CHECK_OK(qwen().t->apply(replayed_round(a), tools_json(), opt, &p));
CHECK_EQ(p.prompt, want.prompt);
}
}
/* Arguments that are not JSON are still refused, but as the request's fault and naming the call,
* not as a refusal by the template. */
TEST(replayed_arguments_that_are_not_json_are_refused_naming_the_call) {
if (!qwen().need()) return;
const json bad = "{\"path\": \"/work/a.py\"";
ChatPrompt p;
ChatOptions opt;
opt.quiet = true;
CHECK_EQ(qwen().t->apply(replayed_round(&bad), tools_json(), opt, &p), (int)RAD_E_INVAL);
CHECK(p.error.find("messages[1].tool_calls[0].function.arguments is not JSON") !=
std::string::npos);
CHECK(p.error.find("template") == std::string::npos);
}
/* ------------------------------------------------------------------ golden renders
*
* Every shipped template renders the requests in tests/data/chat/golden/cases.json byte for byte
+126 -1
View File
@@ -32,6 +32,7 @@
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include "../arch/museglimmer/chat.h"
#include <arch/rad_deepseek41_chat.h>
#include "util/json.h"
@@ -2668,5 +2669,129 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) {
}
}
RAD_TEST_MAIN()
/* ================================================================== Muse's channels
*
* The model opens its own channel after `<|start|>assistant`: ` to=self<|message|>` reasoning
* first, or ` to=user<|message|>` straight into the answer when it does not reason
* (arch/museglimmer/chat.h). The header of an answer that follows reasoning is reasoning_close's;
* the header of an answer that does not is content_open's. */
static std::shared_ptr<const ReplyParser> muse_parser(bool tools, bool extract = true) {
static const json t = agent_tools();
ChatFormat f;
std::string why;
CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why));
ReplyOptions ro;
ro.extract_reasoning = extract;
ro.terminators = { "<|eot|>" };
if (tools) ro.tools = &t;
return parser_of(f, ro);
}
/* `reply` read whole, then streamed at every cut: the answer must come out as `content`, with
* `reasoning` split off and no call. */
static void muse_reads(const std::shared_ptr<const ReplyParser>& rp, const std::string& reply,
const std::string& content, const std::string& reasoning = "") {
REQUIRE(rp);
const ReplyMessage m = reply_parse(*rp, reply);
if (m.content != content || m.reasoning != reasoning || !m.calls.empty())
::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + " read as content " +
quote(m.content) + ", reasoning " + quote(m.reasoning) + ", " +
std::to_string(m.calls.size()) + " calls");
const std::string e = stream_all(*rp, reply);
if (!e.empty()) ::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + ": " + e);
++::radtest::checks();
}
/* A reply with no reasoning opens on the user channel, and the header is not content. */
TEST(a_muse_reply_that_opens_on_the_content_channel_drops_its_header) {
for (bool tools : { false, true }) {
const auto rp = muse_parser(tools);
muse_reads(rp, " to=user<|message|>Here are five prime numbers: 2, 3, 5, 7, 11.<|eot|>",
"Here are five prime numbers: 2, 3, 5, 7, 11.");
muse_reads(rp, "to=user<|message|>Hi", "Hi");
muse_reads(rp, "\n to=user<|message|>\nHi there\n", "\nHi there");
muse_reads(rp, " to=user<|message|>", "");
/* The header's words later in the answer are the answer's. */
muse_reads(rp, " to=user<|message|>write to=user<|message|> next", "write to=user<|message|> next");
}
/* Reasoning kept inline (reasoning_format none): the answer's header is still dropped. */
muse_reads(muse_parser(false, false), " to=user<|message|>Hi<|eot|>", "Hi");
}
/* Text that starts like the header but is not it is the reply, unchanged, and nothing of it is
* held back for good. */
TEST(a_muse_reply_that_only_starts_like_the_content_header_is_unchanged) {
for (bool tools : { false, true }) {
const auto rp = muse_parser(tools);
for (const char* r : { "to=users are asked to wait", "to=user", "to=user<|message", "to=",
"to=user<|message|", "to=user <|message|>x", "to=use", "t",
"to=user<|messages|>x", "to=self", "to=sel", "x to=user<|message|>y",
"to=user to=user<|message|>y" })
muse_reads(rp, r, r);
muse_reads(rp, "to=users are asked to wait<|eot|>", "to=users are asked to wait");
muse_reads(rp, "to=user\n<|message|>x", "to=user\n<|message|>x");
}
}
/* Reasoning first, then the user channel: the header after the block is reasoning_close's, and
* a header-shaped string inside the answer stays. */
TEST(a_muse_reply_that_reasons_first_reads_as_before) {
for (bool tools : { false, true }) {
const auto rp = muse_parser(tools);
muse_reads(rp, " to=self<|message|>Five primes.<|eom|><|start|>assistant to=user<|message|>2, 3, 5, 7, 11.<|eot|>",
"2, 3, 5, 7, 11.", "Five primes.");
muse_reads(rp, " to=self<|message|>r<|eom|><|start|>assistant to=user<|message|>to=user<|message|>x",
"to=user<|message|>x", "r");
}
}
/* A tool call after reasoning is handed off exactly as before: the channel header is framing, the
* call is a call, and the content is empty. */
TEST(a_muse_tool_call_after_reasoning_is_unchanged) {
const auto rp = muse_parser(true);
REQUIRE(rp);
const std::string reply =
" to=self<|message|>Look at it.<|eom|><|start|>assistant to=read<|message|>"
"<atem:function_calls>\n<atem:invoke name=\"read\">\n"
"<atem:parameter name=\"path\">a.txt</atem:parameter>\n</atem:invoke>\n"
"</atem:function_calls>";
const ReplyMessage m = reply_parse(*rp, reply);
CHECK_EQ(m.content, std::string());
CHECK_EQ(m.reasoning, std::string("Look at it."));
REQUIRE_EQ(m.calls.size(), (size_t)1);
CHECK_EQ(m.calls[0].name, std::string("read"));
CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"a.txt\"}"));
const std::string e = stream_all(*rp, reply);
CHECK(e.empty());
if (!e.empty()) std::fprintf(stderr, "%s\n", e.c_str());
}
/* The header is a declared literal like any other: it travels in the ABI struct, reads as absent
* from a struct that ends before it, and a format without one reads a reply as it always did. */
TEST(the_content_header_is_declared_through_the_abi_struct) {
ChatFormat f;
std::string why;
CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why));
CHECK_EQ(f.content_open, std::string("to=user<|message|>"));
CHECK_OK(chat_format_check(f, &why));
const std::vector<std::string> mk = chat_format_markers(f);
CHECK(std::find(mk.begin(), mk.end(), "to=user<|message|>") != mk.end());
/* A plugin compiled before the field: struct_size stops short of it. */
RadChatFormat old = *museglimmer::muse_chat_format();
old.struct_size = (uint32_t)offsetof(RadChatFormat, content_open);
ChatFormat g;
CHECK_OK(chat_format_from_abi(&old, &g, &why));
CHECK(g.content_open.empty());
CHECK_EQ(g.reasoning_open, f.reasoning_open);
CHECK(chat_format_describe(g).find("content") == std::string::npos);
/* Without it the header is content, as before. */
std::shared_ptr<const ReplyFormat> rf;
CHECK_OK(ReplyFormat::compile(g, &rf, &why));
ReplyOptions ro;
std::shared_ptr<const ReplyParser> rp;
CHECK_OK(ReplyParser::create(rf, ro, &rp, &why));
CHECK_EQ(reply_parse(*rp, " to=user<|message|>Hi").content, std::string("to=user<|message|>Hi"));
}
RAD_TEST_MAIN()
+51
View File
@@ -150,6 +150,57 @@ TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) {
CHECK_EQ(ck.meta().m.head_dim, (int64_t)0);
}
/* Muse Glimmer: the underscore-stripped model_type is the architecture id, the trunk's config
* lives under text_config (nested() reads it; the alias pass copies it to bare keys), and the
* head_dim 128 is read, not derived (6656/32 would be 208). The free-form keys a plugin reads --
* the layer schedule, the per-layer rotary bases, the family scalars -- flatten to strings under
* their dotted config.json spellings, and vision_config stays unaliased under its full prefix. */
TEST(muse_glimmer_metadata_maps_the_trunk_and_keeps_the_family_keys) {
const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) },
"{\"model_type\":\"muse_glimmer\",\"architectures\":[\"MuseGlimmerForConditionalGeneration\"],"
"\"image_token_id\":200092,\"video_token_id\":200091,"
"\"text_config\":{\"hidden_size\":6656,\"num_hidden_layers\":52,"
"\"num_attention_heads\":32,\"num_key_value_heads\":2,\"head_dim\":128,"
"\"intermediate_size\":19968,\"vocab_size\":202048,\"rms_norm_eps\":1e-5,"
"\"post_norm_eps\":1e-8,\"sliding_window\":2048,\"max_position_embeddings\":131072,"
"\"qk_scale_factor\":3.87,\"output_multiplier\":0.19611613513818404,"
"\"final_logit_softcapping\":20.0,"
"\"rope_parameters\":{\"rope_theta\":500000.0,\"rope_type\":\"default\"},"
"\"layer_types\":[\"sliding_attention\",\"sliding_attention\",\"sliding_attention\","
"\"full_attention\"],\"layer_rope_theta\":[500000.0,500000.0,500000.0,0]},"
"\"vision_config\":{\"model_type\":\"muse_glimmer_vision\",\"hidden_size\":1536,"
"\"num_hidden_layers\":50,\"patch_size\":14}}");
Checkpoint ck;
REQUIRE_EQ(ck.open(dir), RAD_OK);
const MetaOwn& mo = ck.meta();
const RadModelMeta& m = mo.m;
CHECK_EQ(mo.arch, std::string("museglimmer"));
CHECK_EQ(mo.quant, std::string(""));
CHECK_EQ(mo.has("text_config.layer_rope_theta"), true);
CHECK_EQ(m.n_embd, (int64_t)6656);
CHECK_EQ(m.n_layers, (int64_t)52);
CHECK_EQ(m.n_head, (int64_t)32);
CHECK_EQ(m.n_head_kv, (int64_t)2);
CHECK_EQ(m.head_dim, (int64_t)128);
CHECK_EQ(m.n_ff, (int64_t)19968);
CHECK_EQ(m.n_vocab, (int64_t)202048);
CHECK_EQ(m.rms_eps, 1e-5f);
CHECK_EQ(m.n_ctx_train, (int64_t)131072);
CHECK_EQ(m.rope_theta, 500000.0);
/* The plugin's free-form reads: the aliased bare spellings and the dotted originals agree,
* and the layer arrays arrive as one space-separated string each. */
CHECK_EQ(rad_meta_gets(&m, "layer_types", ""), std::string("sliding_attention sliding_attention "
"sliding_attention full_attention"));
CHECK_EQ(rad_meta_gets(&m, "layer_rope_theta", ""), std::string("500000 500000 500000 0"));
CHECK_EQ(rad_meta_geti(&m, "sliding_window", 0), (long long)2048);
CHECK_EQ(rad_meta_getf(&m, "qk_scale_factor", 0.0), 3.87);
CHECK_EQ(rad_meta_getf(&m, "post_norm_eps", 0.0), 1e-8);
/* vision_config is never aliased: only the full prefix carries it. */
CHECK_EQ(rad_meta_geti(&m, "vision_config.num_hidden_layers", -1), (long long)50);
CHECK_EQ(rad_meta_geti(&m, "num_hidden_layers", -1), (long long)52);
CHECK_EQ(rad_meta_gets(&m, "vision_config.model_type", ""), std::string("muse_glimmer_vision"));
}
/* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's
* --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin,
* so the container never names one format and selects another's plugin. transformers' fp8 states
+55
View File
@@ -203,6 +203,42 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) {
CHECK_EQ(parse({ "--kld-record", "/r", "--kld-corpus", "/c", "--kld-top", "-1" }, &f), RAD_E_INVAL);
}
/* The diagnose mode: one mode a run, and its corpus and baseline belong to its workload. A run
* that took one of them without a DIR would measure nothing while looking configured. */
TEST(the_diagnose_mode_takes_its_own_flags_and_nothing_else) {
Config c;
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-tokens", "64", "--diagnose-runs", "1",
"--diagnose-concurrency", "1,2", "--diagnose-prefill", "1024,4096",
"--diagnose-corpus", "/c.jsonl", "--diagnose-baseline", "/b.json" }, &c), RAD_OK);
CHECK(c.diagnose_mode());
CHECK_EQ(c.diagnose, std::string("/d"));
CHECK_EQ(c.diagnose_tokens, 64);
CHECK_EQ(c.diagnose_runs, 1);
CHECK_EQ(c.diagnose_concurrency.size(), (size_t)2);
CHECK_EQ(c.diagnose_prefill.size(), (size_t)2);
CHECK_EQ(c.diagnose_corpus, std::string("/c.jsonl"));
CHECK_EQ(c.diagnose_baseline, std::string("/b.json"));
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(!d.diagnose_mode());
CHECK_EQ(d.diagnose_tokens, 256); /* the defaults the report states */
CHECK_EQ(d.diagnose_runs, 3);
CHECK_EQ(d.diagnose_concurrency.size(), (size_t)4);
CHECK_EQ(d.diagnose_prefill.size(), (size_t)4);
Config f;
CHECK_EQ(parse({ "--diagnose-corpus", "/c.jsonl" }, &f), RAD_E_INVAL); /* no workload */
CHECK_EQ(parse({ "--diagnose-baseline", "/b.json" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--kld-ref", "/r" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--debug-graph" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--calib-corpus", "/c.jsonl", "--calib-dir", "/s" }, &f),
RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-concurrency", "1,,2" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-prefill", "8" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-runs", "0" }, &f), RAD_E_INVAL);
}
/* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a
* combination that would size slots no adapter uses, or name an adapter that is not served, is
* refused by name. A text model's slot count against its adapters, and its targets, are checked
@@ -478,6 +514,17 @@ TEST(prefill_interleave_takes_a_step_count_up_to_64) {
CHECK_EQ(parse({ "--prefill-interleave", "auto:x" }, &c), RAD_E_INVAL);
}
TEST(mixed_step_target_is_an_opt_in_soft_millisecond_target) {
Config d;
REQUIRE_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.mixed_step_target_ms, 0);
Config c;
CHECK_EQ(parse({ "--mixed-step-target-ms", "150" }, &c), RAD_OK);
CHECK_EQ(c.mixed_step_target_ms, 150);
CHECK_EQ(parse({ "--mixed-step-target-ms", "60001" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--mixed-step-target-ms", "-1" }, &c), RAD_E_INVAL);
}
/* ================================================================== the table, the parser and the help agree
*
* One table (g_flags) drives the help text and the startup report, and a separate chain of ifs
@@ -520,6 +567,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--tp-attn-split", { "rows" } }, { "--weight-prefetch", { "off" } },
{ "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } },
{ "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } },
{ "--mixed-step-target-ms", { "150" } },
{ "--preempt-wait-ms", { "5000" } },
{ "--max-num-seqs", { "4" } },
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
@@ -589,6 +637,13 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--kld-lora", { "a", "--lora", "a=/adapters/a", "--kld-ref", "/r" } },
{ "--kld-lora-sources", { "doc/", "--kld-lora", "a", "--lora", "a=/adapters/a",
"--kld-ref", "/r" } },
{ "--diagnose", { "/d" } },
{ "--diagnose-tokens", { "64", "--diagnose", "/d" } },
{ "--diagnose-runs", { "1", "--diagnose", "/d" } },
{ "--diagnose-concurrency", { "1,2", "--diagnose", "/d" } },
{ "--diagnose-prefill", { "1024,4096", "--diagnose", "/d" } },
{ "--diagnose-corpus", { "/c.jsonl", "--diagnose", "/d" } },
{ "--diagnose-baseline", { "/b.json", "--diagnose", "/d" } },
};
return v;
}
+41
View File
@@ -750,4 +750,45 @@ TEST(the_json_carries_every_section) {
CHECK(text.find("WARN link-below-max") != std::string::npos);
}
TEST(a_card_sample_reads_temperatures_by_label_and_the_current_level) {
Root r;
const std::string d = "/sys/bus/pci/devices/0000:03:00.0";
r.put(d + "/power_dpm_force_performance_level", "auto\n");
r.put(d + "/pp_dpm_sclk", "0: 500Mhz\n1: 1800Mhz *\n2: 2350Mhz\n");
r.put(d + "/pp_dpm_mclk", "0: 96Mhz\n1: 1258Mhz *\n");
r.put(d + "/gpu_busy_percent", "0\n");
r.put(d + "/hwmon/hwmon3/temp1_input", "45000\n");
r.put(d + "/hwmon/hwmon3/temp1_label", "edge\n");
r.put(d + "/hwmon/hwmon3/temp2_input", "61000\n");
r.put(d + "/hwmon/hwmon3/temp2_label", "junction\n");
r.put(d + "/hwmon/hwmon3/temp3_input", "52000\n");
r.put(d + "/hwmon/hwmon3/temp3_label", "mem\n");
r.put(d + "/hwmon/hwmon3/power1_input", "31000000\n"); /* no power1_average: the instant reading */
/* A card whose driver labels nothing: its temp1 is the edge sensor. */
const std::string e = "/sys/bus/pci/devices/0000:07:00.0";
r.put(e + "/hwmon/hwmon5/temp1_input", "38000\n");
r.put(e + "/hwmon/hwmon5/power1_average", "12000000\n");
r.put(e + "/hwmon/hwmon5/power1_input", "99000000\n");
const auto s = diag::sample_cards(r.dir, { "0000:03:00.0", "0000:07:00.0", "0000:0b:00.0" });
REQUIRE(s.size() == 3);
CHECK_EQ(s[0].perf_level, std::string("auto"));
CHECK_EQ(s[0].sclk_cur, std::string("1800Mhz"));
CHECK_EQ(s[0].mclk_cur, std::string("1258Mhz"));
CHECK_EQ(s[0].busy_percent, 0);
CHECK_EQ(s[0].edge_mc, (int64_t)45000);
CHECK_EQ(s[0].junction_mc, (int64_t)61000);
CHECK_EQ(s[0].mem_mc, (int64_t)52000);
CHECK_EQ(s[0].power_uw, (int64_t)31000000);
CHECK_EQ(s[1].edge_mc, (int64_t)38000);
CHECK_EQ(s[1].junction_mc, (int64_t)-1);
CHECK_EQ(s[1].power_uw, (int64_t)12000000); /* the average, when there is one */
CHECK(s[1].perf_level.empty());
/* A card with no files at all is all unknown, not an error. */
CHECK_EQ(s[2].bdf, std::string("0000:0b:00.0"));
CHECK_EQ(s[2].edge_mc, (int64_t)-1);
CHECK_EQ(s[2].power_uw, (int64_t)-1);
CHECK(s[2].sclk_cur.empty());
}
RAD_TEST_MAIN()
File diff suppressed because it is too large. Load diff
+122
View File
@@ -714,6 +714,128 @@ TEST(qwen35_preemption_by_recompute_changes_no_logit) {
CHECK(n > 0);
}
/* The diagnose mode end to end: the real binary starts as a serve would, runs its own workload
* through the scheduler, and writes a report whose sections are the ones the report format
* declares. Its arithmetic is tests/diagnose_test.cpp's; this is that the driver runs at all, that
* every prompt was salted and the cache emptied (no request reports a cached token), and that a
* second run on the same build reproduces every request's tokens, which is what --diagnose-baseline
* compares. The numbers themselves are a card's measurement, not this test's.
*
* The model, the corpus and the baseline all live under a directory named after a marker: the
* report is pasted into issues, so no path of the machine may reach it, and a variable whose name
* is an allowed prefix plus a secret suffix must not be reported at all. */
TEST(the_diagnose_mode_measures_itself_and_reproduces_its_tokens) {
World& w = world();
tiny::TempDir d("diagnose");
REQUIRE(d.ok());
const std::string private_dir = d / "MARKER-private-home";
REQUIRE_EQ(mkdir(private_dir.c_str(), 0755), 0);
const std::string model = private_dir + "/model.rad";
REQUIRE_EQ(symlink(w.llama_rad.c_str(), model.c_str()), 0);
const std::string corpus = private_dir + "/corpus.jsonl";
std::string body;
for (int i = 0; i < 3; ++i) {
tiny::Rng r(40 + i);
body += json{ { "category", "prose" }, { "prompt", words(r, 120) }, { "max_tokens", 8 } }
.dump() + "\n";
}
REQUIRE(tiny::write_text(corpus, body));
/* One point of each sweep, one measured run: the driver's whole shape, quickly. */
const std::vector<std::string> shared = {
"--diagnose-corpus", corpus, "--diagnose-tokens", "8", "--diagnose-runs", "1",
"--diagnose-concurrency", "1", "--diagnose-prefill", "512",
"--max-model-len", "1024", "--max-num-seqs", "2", "--max-num-batched-tokens", "256" };
std::vector<std::string> a = { "--diagnose", d / "first" };
a.insert(a.end(), shared.begin(), shared.end());
const Ran r = radiance(model, a, { "RADIANCE_API_KEY_SYNTHETIC_SECRET_IN_NAME=x" }, 600);
REQUIRE_RAN(r);
std::string text;
{
const std::string path = d.path + "/first/diagnose.json";
FILE* f = std::fopen(path.c_str(), "rb");
REQUIRE(f != nullptr);
char buf[4096];
for (size_t n; (n = std::fread(buf, 1, sizeof buf, f)) > 0;) text.append(buf, n);
std::fclose(f);
}
const json rep = json::parse(text, nullptr, false);
REQUIRE(rep.is_object());
for (const char* k : { "engine", "workload", "categories", "concurrency", "prefill",
"interference", "environment", "not_measured", "verdict", "problems",
"warnings" })
CHECK(rep.contains(k));
CHECK_EQ(rep["verdict"].get<std::string>(), std::string("valid"));
CHECK_EQ(rep["problems"].size(), (size_t)0);
/* Every point of the workload ran: three prose prompts once each, one stream, one 512-token
* prefill, and a prompt arriving into a running stream. A point the engine could not run is
* named in the report, never left as a zero. */
REQUIRE_EQ(rep["categories"].size(), (size_t)1);
const json& cat = rep["categories"][0];
CHECK_EQ(cat["prompts"].get<int64_t>(), (int64_t)3);
CHECK_EQ(cat["runs"].size(), (size_t)3);
CHECK_EQ(rep["concurrency"].size(), (size_t)1);
CHECK_EQ(rep["concurrency"][0]["streams"].get<int64_t>(), (int64_t)1);
REQUIRE_EQ(rep["prefill"].size(), (size_t)1);
CHECK_EQ(rep["prefill"][0]["prompt_tokens"].get<int64_t>(), (int64_t)512);
CHECK(rep["interference"]["runs"][0]["arrival_ttft_ms"].get<double>() > 0);
CHECK(rep["interference"]["runs"][0]["interference"]["stall_ratio"].get<double>() > 0);
/* Salted and uncached, and the step ring lost nothing: the workload's own statement of its
* validity, checked afterwards from what each run recorded. */
int64_t cached = 0, lost = 0;
for (const json& run : cat["runs"]) {
cached += run["requests"]["cached_prompt_tokens"].get<int64_t>();
lost += run["steps"]["lost"].get<int64_t>();
CHECK(run["steps"]["recorded"].get<int64_t>() > 0);
CHECK(run["requests"]["outputs"][0].size() > 0);
}
CHECK_EQ(cached, (int64_t)0);
CHECK_EQ(lost, (int64_t)0);
/* What the run was taken under, and whether its runs agree. The verdict itself is not held
* here: these are a CI host's timings. */
REQUIRE(rep.contains("conditions"));
CHECK_EQ(rep["conditions"]["fingerprint"].get<std::string>().size(), (size_t)16);
CHECK(rep["conditions"]["cards"].empty()); /* the host backend serves no card */
CHECK(rep["stability"].contains("verdict"));
CHECK_EQ(cat["prompts_summary"].size(), (size_t)3);
CHECK(rep["thermal"]["cards"].empty());
CHECK(rep["reproducibility"].is_array());
/* Names, not values: the report is pasted into issues. */
for (const json& n : rep["environment"]["variables"])
CHECK(n.get<std::string>().find('=') == std::string::npos);
/* No path and no secret-suffixed name in either artifact of either run. */
for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) {
CHECK(text.find(marker) == std::string::npos);
CHECK(tiny::read_text(d.path + "/first/diagnose.md").find(marker) == std::string::npos);
}
/* The same build, the same workload: identical tokens, which is what the baseline compares. */
const std::string baseline = private_dir + "/baseline.json";
REQUIRE(tiny::write_text(baseline, text));
std::vector<std::string> b = { "--diagnose", d / "second", "--diagnose-baseline", baseline };
b.insert(b.end(), shared.begin(), shared.end());
const Ran r2 = radiance(model, b, {}, 600);
REQUIRE_RAN(r2);
const std::string json2 = tiny::read_text(d.path + "/second/diagnose.json");
const std::string md = tiny::read_text(d.path + "/second/diagnose.md");
CHECK(md.find("# Diagnosis") == 0);
CHECK(md.find("**Verdict: valid**") != std::string::npos);
CHECK(md.find("## Parity") != std::string::npos);
CHECK(md.find("## Reproducibility") != std::string::npos);
{
/* Two runs on one machine, one after the other: the same conditions. */
const json rep2 = json::parse(json2, nullptr, false);
REQUIRE(rep2.is_object());
CHECK(rep2["parity"]["conditions"].is_array());
CHECK(rep2["parity"]["conditions"].empty());
}
for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) {
CHECK(json2.find(marker) == std::string::npos);
CHECK(md.find(marker) == std::string::npos);
}
}
/* A document longer than the whole KV pool could never be admitted: admission takes only a chunk
* the pool can hold, so it would wait at the head of the queue forever. The run is refused before
* anything is scored, naming the document's length and the pool's. Bounded by a timeout, so the
+26
View File
@@ -95,6 +95,25 @@ TEST(structured_values_are_spelled_for_their_flag) {
CHECK(c.sample_temp > 0.69f && c.sample_temp < 0.71f);
}
/* The diagnose mode is a model key like the KL mode's: the entry's Config is what main() tests to
* run it offline, and a sequence spells the sweeps' lists. */
TEST(the_diagnose_keys_are_model_keys) {
fleet::FleetConfig fc;
CHECK_EQ(yload("models:\n qwen:\n model: /m/q.rad\n diagnose: /out\n diagnose-runs: 5\n"
" diagnose-concurrency: [1, 2]\n diagnose-prefill: [1024, 4096]\n", &fc), RAD_OK);
REQUIRE_EQ(fc.models.size(), 1u);
const Config& c = fc.models[0].cfg;
CHECK(c.diagnose_mode());
CHECK_EQ(c.diagnose, "/out");
CHECK_EQ(c.diagnose_runs, 5);
CHECK_EQ(c.diagnose_concurrency.size(), 2u);
CHECK_EQ(c.diagnose_prefill.size(), 2u);
CHECK_EQ(c.given.at("--diagnose"), "models.qwen.diagnose");
CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-runs: 5\n diagnose: /out\n"
" kld-ref: /r\n"));
CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-baseline: /b.json\n"));
}
TEST(model_ids_may_hold_dots) {
fleet::FleetConfig fc;
CHECK_EQ(yload("models:\n qwen3.8-27b:\n model: /m/q.rad\n tp: 2\n", &fc), RAD_OK);
@@ -253,9 +272,16 @@ TEST(scheduler_cards_and_groups) {
CHECK_EQ(fc.load_timeout_ms, 90000);
CHECK_EQ(fc.drain_timeout_ms, 500);
CHECK_EQ(fc.keepalive_ms, 5000);
CHECK_EQ(fc.stuck_exit_ms, 60000); /* a minute unless the file says otherwise */
CHECK(fc.warm_up); /* on unless the file turns it off */
CHECK_EQ(fc.groups.size(), 2u);
CHECK(fc.groups[1].kind == fleet::Group::Kind::Exclusive);
fleet::FleetConfig off;
CHECK_EQ(yload("scheduler: {stuck-exit: 0}\nmodels:\n a: {model: /m/a.rad}\n", &off), RAD_OK);
CHECK_EQ(off.stuck_exit_ms, 0);
fleet::FleetConfig slow;
CHECK_EQ(yload("scheduler: {stuck-exit: 5m}\nmodels:\n a: {model: /m/a.rad}\n", &slow), RAD_OK);
CHECK_EQ(slow.stuck_exit_ms, 300000);
CHECK_EQ(yload("cards: all\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK);
CHECK(fc.cards.empty());
CHECK_EQ(yload("scheduler: {warm-up: false}\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK);
+318
View File
@@ -0,0 +1,318 @@
/* Flint's declaration and step (arch/flint), without a GPU or checkpoint: the containers its
* recipes make, both KV caches, one and two ranks. */
#define RAD_ARCH_NO_EXPORTS 1
#include "arch_fakes.h"
#include "rad_plugin.h"
#include "../arch/flint/flint.cpp"
using namespace rad_fake;
namespace {
/* Recursive Flint's configuration as rad-convert records it. */
MetaKV flint_meta() {
RadModelMeta m{};
m.arch_id = "flint";
m.name = "test-flint";
m.quant = "";
m.n_layers = 49;
m.n_embd = 2048;
m.n_head = 32;
m.n_head_kv = 4;
m.head_dim = 128;
m.n_ff = 6144;
m.n_vocab = 150144;
m.n_ctx_train = 262144;
m.rms_eps = 1e-6f;
m.rope_theta = 10000.0f;
m.n_expert = 256;
m.n_expert_used = 6;
MetaKV k(m);
k.set("sliding_window", "513").set("num_experts", "256").set("num_experts_per_tok", "6")
.set("moe_intermediate_size", "512").set("shared_expert_intermediate_size", "1024")
.set("intermediate_size", "6144");
return k;
}
/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under
* a bf16 scale a row. */
RadEncoding iq8r() {
RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256);
rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0);
rad_enc_copy_str(e.transform, "fwht128");
return e;
}
/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */
RadEncoding i8h() {
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
rad_enc_copy_str(e.transform, "fwht128");
return e;
}
/* data/recipes/flint-iq8r.recipe's encodings by declared name. The head comes last because
* `output.weight` is in `attn_output.weight`. */
void iq8r_encs(RadBuilder* b) {
b->encs.clear();
for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" })
b->encs.push_back({ t, i8h() });
for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight",
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight",
"ffn_gate_up_shexp" })
b->encs.push_back({ t, iq8r() });
b->encs.push_back({ "output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128) });
}
/* data/recipes/flint-bf16-q4.recipe's: u4 attention under an f16 scale and a u8 zero a 128,
* plain int8 dense and shared linears and head, signed int4 experts. */
void q4_encs(RadBuilder* b) {
RadEncoding u4 = rad_enc_affine(RAD_U4, RAD_F16, 1, 128);
rad_enc_add_plane(&u4, "zero", RAD_U8, 1, 128);
const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
b->encs.clear();
b->encs.push_back({ "ffn_gate_up_exps", i4 });
b->encs.push_back({ "ffn_down_exps", i4 });
for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight",
"attn_output.weight" })
b->encs.push_back({ t, u4 });
for (const char* t : { "ffn_gate_up_shexp", "ffn_down_shexp", "ffn_gate_up.weight",
"ffn_down.weight", "output.weight" })
b->encs.push_back({ t, w8 });
}
bool is_full(int l) { return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0); }
/* Decode, a fused-prologue prefill and one past the fused band, each lint clean. */
void steps_lint_clean(RadBuilder& b, int rank, int world) {
RadBatch d = decode_batch();
RadCtx c1{.b = &b, .batch = &d, .rank = rank, .world = world};
flint::step(&c1, &d);
CHECK_LINT(b, &c1);
CHECK(c1.step_fail.empty());
RadBatch p = prefill_batch();
RadCtx c2{.b = &b, .batch = &p, .rank = rank, .world = world};
flint::step(&c2, &p);
CHECK_LINT(b, &c2);
CHECK(c2.step_fail.empty());
RadBatch w = prefill_batch();
w.n_tok = 200;
w.max_q_len = 100;
RadCtx c3{.b = &b, .batch = &w, .rank = rank, .world = world};
flint::step(&c3, &w);
CHECK_LINT(b, &c3);
CHECK(c3.step_fail.empty());
}
} /* namespace */
/* The attention of every layer: the sink op, the 513 window on the sliding layers, and the fused
* prologue with the rotary on the sliding layers and none (`rotary_dim` 0) on the full ones, on
* the bf16 and the int8 cache; the two KV groups take the cache's dtype. */
TEST(attention_takes_the_sink_window_and_nope_prologue_on_both_caches) {
for (const bool i8 : { false, true }) {
MetaKV mk = flint_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx();
if (i8) ctx.kv_dtype = RAD_I8;
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
const char* kvn = i8 ? "i8" : "bf16";
REQUIRE_EQ(b.kv_groups.size(), (size_t)2);
for (const auto& g : b.kv_groups) CHECK_EQ(g.d.dtype, (uint32_t)(i8 ? RAD_I8 : RAD_BF16));
REQUIRE_EQ(count_op(b, "attn_paged_sink"), 49);
REQUIRE_EQ(count_op(b, "qkv_norm_rope_kv_store"), 49);
CHECK_EQ(count_op(b, "attn_paged"), 0);
CHECK_EQ(count_op(b, "rope"), 2 * 35);
for (int l = 0; l < 49; ++l) {
const RecOp* a = find_op(b, "attn_paged_sink", l);
const RecOp* f = find_op(b, "qkv_norm_rope_kv_store", l);
const RecOp* s = find_op(b, "kv_store", l);
REQUIRE(a && f && s);
CHECK_EQ(pint(a, "window"), is_full(l) ? 0 : 513);
CHECK_EQ(pint(a, "gqa"), 8);
CHECK_EQ(pint(a, "causal"), 1);
CHECK_EQ(pstr(a, "kv_dtype"), std::string(kvn));
CHECK_EQ(pint(f, "rotary_dim"), is_full(l) ? 0 : 128);
CHECK_EQ(pstr(f, "kv_dtype"), std::string(kvn));
CHECK_EQ(pstr(s, "kv_dtype"), std::string(kvn));
CHECK(param(s, "k_scale") == nullptr);
}
steps_lint_clean(b, 0, 1);
}
}
/* The IQ8R container: every trunk linear is an i8a8h GEMM, every grouped GEMM the int8 row, gate_up
* reading the block input's own rotated codes at IQ8R's 256 and down the gated product's at a 128;
* the norms, the gated products and the attention output write those codes, so no linear declares
* a quantiser and no E4M3 code is written. One rank and both ranks of two. */
TEST(iq8r_container_reads_the_trunks_rotated_codes_everywhere) {
for (int world : { 1, 2 })
for (int rank = 0; rank < world; ++rank) {
MetaKV mk = flint_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx(rank, world);
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
const flint::Model& m = flint::g_model[rank];
CHECK(m.trunk_rot);
CHECK_EQ(m.trunk_g8, 256);
const rad_buf hq = (rad_buf)m.h.q8, fq = (rad_buf)m.mw.eff.q8;
REQUIRE(hq != 0);
REQUIRE(fq != 0);
int gu = 0, dn = 0;
for (const auto& o : b.ops) {
if (o.op == "gemm_nt_q") CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
if (o.op != "moe_gemm_q") continue;
CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h"));
const bool token = pstr(&o, "a_order") == "token";
CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128);
CHECK(in(o.reads, token ? hq : fq));
(token ? gu : dn) += 1;
}
CHECK_EQ(gu, 47);
CHECK_EQ(dn, 47);
/* q|k|v, o, the dense pair twice, the shared pair 47 times. */
CHECK_EQ(count_op(b, "gemm_nt_q"), 49 * 4 + 2 * 2 + 47 * 2);
CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 2 + 47 + 47);
CHECK_EQ(count_op(b, "had_quant_act_i8g"), 49);
for (const char* op : { "gated_quant_fp8", "quant_act_fp8", "rmsnorm_quant_fp8",
"ar_rmsnorm_quant_fp8", "quant_act_i8g" })
CHECK_EQ(count_op(b, op), 0);
CHECK_EQ(count_op(b, world == 2 ? "ar_rmsnorm_had_quant_i8g" : "rmsnorm_had_quant_i8g") > 0,
true);
for (const char* a : { "h.q", "moe_ffn.q", "moe_hr.q8", "shared_ffn.q", "attn_out.q" })
CHECK(find_b(b, a) == nullptr);
/* Expert parallel: each rank owns 128 whole experts. */
CHECK(find_w(b, rank == 0 ? "blk.2.ffn_gate_up_exps.0.weight"
: "blk.2.ffn_gate_up_exps.128.weight") != nullptr);
steps_lint_clean(b, rank, world);
}
}
/* Where the rotating norm is not served (the CPU kernels), every linear quantises `h` itself and
* the routed experts read a rotated int8 copy that had_quant_act_i8g writes once a layer. */
TEST(iq8r_container_quantises_the_expert_input_without_the_rotating_norm) {
MetaKV mk = flint_meta();
RadBuilder b;
for (const char* op : { "rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g" })
b.undeclared.insert(op);
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx();
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
const RecBuf* hr = find_b(b, "moe_hr.q8");
REQUIRE(hr != nullptr);
const rad_buf hrb = (rad_buf)flint::g_model[0].hr.q8;
int reads = 0;
for (const auto& o : b.ops)
if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") {
CHECK_EQ(pint(&o, "a_group"), 128);
reads += in(o.reads, hrb);
}
CHECK_EQ(reads, 47);
steps_lint_clean(b, 0, 1);
}
/* The four-bit container: u4 attention over the bf16 plane, four-bit experts over the block
* input's E4M3 pair (w4a8), plain int8 dense and shared linears each quantising its own input,
* an int8 head. */
TEST(q4_container_serves_four_bit_experts_and_plain_int8_linears) {
for (int world : { 1, 2 })
for (int rank = 0; rank < world; ++rank) {
MetaKV mk = flint_meta();
RadBuilder b;
q4_encs(&b);
RadBuildCtx ctx = build_ctx(rank, world);
REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK);
CHECK(!flint::g_model[rank].trunk_rot);
int moe = 0, asym = 0, i8 = 0;
for (const auto& o : b.ops) {
if (o.op == "moe_gemm_q") {
CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8"));
++moe;
}
if (o.op == "gemm_nt_q") {
const std::string dt = pstr(&o, "dtype");
asym += dt == "w4a16_asym" || dt == "w4a8i8_asym";
i8 += dt == "i8a8";
}
}
CHECK_EQ(moe, 2 * 47);
CHECK(asym >= 4 * 49);
CHECK_EQ(i8, 2 * 2 + 2 * 47);
CHECK(count_op(b, world == 2 ? "ar_rmsnorm_quant_fp8" : "rmsnorm_quant_fp8") > 0);
/* No attention output quantiser: the u4 out projection reads the bf16 plane. */
CHECK_EQ(count_op(b, "quant_act_fp8"), 0);
const RecWeight* head = find_w(b, "output.weight");
REQUIRE(head != nullptr);
CHECK_EQ(head->d.dtype, (uint32_t)RAD_I8);
steps_lint_clean(b, rank, world);
}
}
/* What the plugin refuses by name: a container whose experts are plain (unrotated) int8, a rotated
* trunk over unrotated four-bit experts, rotated int8 experts under an unrotated trunk, and a
* cache other than bf16 or int8. */
TEST(refuses_mismatched_forms_and_other_caches) {
{
MetaKV mk = flint_meta();
RadBuilder b;
iq8r_encs(&b);
const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
for (auto& e : b.encs) e.second = w8;
RadBuildCtx ctx = build_ctx();
CHECK(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }) < 0);
}
{
MetaKV mk = flint_meta();
RadBuilder b;
iq8r_encs(&b);
const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
for (auto& e : b.encs)
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i4;
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
{
MetaKV mk = flint_meta();
RadBuilder b;
q4_encs(&b);
for (auto& e : b.encs)
if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h();
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
{
MetaKV mk = flint_meta();
RadBuilder b;
iq8r_encs(&b);
RadBuildCtx ctx = build_ctx();
ctx.kv_dtype = RAD_F8E4M3;
CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
}
/* Per-instance state lives in the declaring instance's slot, so a second engine in the process
* leaves the first one's model alone. */
TEST(declares_into_its_own_slot) {
MetaKV mk = flint_meta();
RadBuilder b0, b1;
iq8r_encs(&b0);
q4_encs(&b1);
RadBuildCtx c0 = build_ctx();
RadBuildCtx c1 = build_ctx();
c1.slot_base = 4;
REQUIRE_EQ(flint::declare(&b0, mk.meta(), &c0), RAD_OK);
REQUIRE_EQ(flint::declare(&b1, mk.meta(), &c1), RAD_OK);
RadArchProbe probe{};
CHECK_OK(flint::probe(mk.meta(), &probe));
CHECK_EQ(probe.draft_depth, 0);
CHECK(flint::g_model[0].trunk_rot);
CHECK(!flint::g_model[4].trunk_rot);
CHECK_EQ(flint::g_model[4].g.n_layer, 49);
}
RAD_TEST_MAIN()
+73
View File
@@ -0,0 +1,73 @@
/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers 5.23.0.dev0 (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, torch 2.15.0+cpu, torchvision 0.29.2+cpu); do not edit. */
#pragma once
#include <cstdint>
static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;
static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;
static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;
static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;
static const int32_t kGoldMuseVidSep = 200087;
/* A h x w picture's resize target, in pixels. */
struct GoldMuseResize { int64_t h, w, oh, ow; };
static const GoldMuseResize kGoldMuseResize[] = {
{ 256, 320, 252, 308 },
{ 100, 100, 112, 112 },
{ 84, 84, 84, 84 },
{ 10, 10, 28, 28 },
{ 28, 28, 28, 28 },
{ 27, 27, 28, 28 },
{ 1, 1, 28, 28 },
{ 8000, 8000, 1792, 1792 },
{ 2000, 50, 2016, 56 },
{ 50, 2000, 56, 2016 },
{ 300, 500, 308, 504 },
{ 640, 427, 616, 420 },
{ 1920, 1080, 1932, 1092 },
{ 3, 5000, 28, 5012 },
{ 500, 3, 504, 28 },
{ 1234, 5678, 812, 3836 },
{ 7, 9, 28, 28 },
{ 112, 224, 112, 224 },
{ 224, 112, 224, 112 },
};
/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row (temporal, channel, y, x) as the reference lays it out. */
struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };
static const GoldMuseImage kGoldMuseImage[] = {
{ 100, 100, 8, 8, {0xbebf, 0xbf56, 0xbeaf, 0x3f50, 0x3db9, 0xbf10, 0x3ea7, 0x3f26, 0x3eef, 0xbeff, 0xbe75, 0xbf7e, 0x3f02, 0x3e2d, 0x3f08, 0xbe55}, 2422471396853671097ull },
{ 256, 320, 18, 22, {0xbec7, 0xbf54, 0x3e4d, 0x3f22, 0xbf18, 0x3e7d, 0x3f28, 0x3e45, 0xbeef, 0xbf22, 0xbd71, 0x3ec7, 0xbf1e, 0x3ebb, 0x3f28, 0x3ca1}, 116533246137817081ull },
};
/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid (groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's stamp. */
static const int64_t kGoldMuseVideoTotal = 37;
static const double kGoldMuseVideoFps = 6.0;
static const int32_t kGoldMuseVideoN = 12;
static const int64_t kGoldMuseVideoIndex[] = {
0, 3, 6, 9, 13, 16, 19, 22, 26, 29, 32, 36};
static const int32_t kGoldMuseVideoGrid[] = { 6, 4, 6 };
static const uint16_t kGoldMuseVideoHead[16] = {
0xbebf, 0xbf38, 0x3f08, 0x3d89, 0xbe93, 0x3f02, 0x3ee3, 0xbef3, 0xbf12, 0xbd11, 0x3e83, 0xbedf, 0x3e15, 0xbf08, 0x3f30, 0x3e9b};
static const uint64_t kGoldMuseVideoFnv = 11707344584801435184ull;
static const char* const kGoldMuseVideoStamps[] = {
"Time: 0.0s",
"Time: 1.0s",
"Time: 2.2s",
"Time: 3.2s",
"Time: 4.3s",
"Time: 5.3s",
};
/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */
struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };
static const GoldMuseSample kGoldMuseSample[] = {
{ 37, 6.0, 12, 7586201493087669970ull },
{ 6, 2.0, 6, 505324669386248260ull },
{ 96, 24.0, 8, 5899556429423025984ull },
{ 1, 2.0, 1, 12161962213042174405ull },
{ 2, 2.0, 2, 7576559462502111812ull },
{ 5, 12.0, 2, 879613241599343585ull },
{ 600, 30.0, 40, 14808218070874272101ull },
{ 1000, 24.0, 82, 13092565161413813425ull },
{ 13, 7.0, 2, 291392423630507241ull },
{ 4, 1.0, 4, 7267626464946418085ull },
};
+104
View File
@@ -4725,6 +4725,110 @@ TEST(dropping_a_clean_entry_gives_its_vram_back_and_keeps_it_restorable) {
CHECK_EQ(x.f.pc.drop_clean(), 0); /* nothing left to drop */
}
/* A conversation larger than the host tier keeps its end in VRAM only, with no host copy coming,
* so it never becomes clean. Left high in the pool by sequences that have since gone, a few such
* blocks stop the expert loan below them for as long as the server runs. drop_clean forgets them
* where giving them up lends far more than it loses, inside the loan it is asked about and once
* no sequence reads them. */
struct Stragglers {
Fixture f;
IdleTiers t;
int64_t all = 0;
/* `slots` host entries; a sequence 9 over the bottom `under` blocks. */
int build(int slots, int under) {
int s = f.build(/*with_linear=*/false, 0);
if (s < 0) return s;
IdleTiers::Config c = tier_config(slots * 1024, 1024);
c.block_tokens = 16;
s = t.configure(c);
if (s < 0) return s;
f.pc.set_tiers(&t);
all = f.kv.total_blocks(G_FULL);
if (under <= 0) return RAD_OK;
s = f.kv.add_sequence(9);
return s < 0 ? s : f.kv.ensure(9, 16 * under);
}
/* A sequence that comes and goes: what makes drop_clean look again. */
void pass() {
CHECK_OK(f.kv.add_sequence(77));
CHECK_OK(f.kv.ensure(77, 16));
f.kv.free_sequence(77);
}
};
TEST(stragglers_with_no_host_copy_coming_leave_vram_for_the_loan) {
Stragglers x;
CHECK_OK(x.build(/*slots=*/16, /*under=*/300));
REQUIRE(x.all >= 400);
const auto prompt = tok_run(7700, 336);
publish(x.f, 1, prompt, 320); /* twenty blocks, at 300 and up */
CHECK_EQ(copy_now(x.t).size(), 16u);
CHECK_EQ(x.t.stats().held_back, 4ll);
const int64_t goal = (x.all - 100) * 16; /* a loan down to block 100 */
/* Still read by its sequence: nothing goes, whatever the loan. */
CHECK_EQ(x.f.pc.drop_clean(goal), 0);
x.f.kv.free_sequence(9);
x.f.kv.free_sequence(1);
/* No loan asked for: the copied start leaves VRAM, the four blocks past the tier stay. */
CHECK_EQ(x.f.pc.drop_clean(), 16);
CHECK_EQ(x.f.pc.resident(), 4ll);
CHECK_EQ(x.f.pc.stats().evictions, 0ll);
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 0ll); /* four blocks keep 316 from the loan */
const int64_t pinned = x.f.kv.spare_tokens();
CHECK(pinned <= (x.all - 316) * 16);
/* A loan that stops above them takes nothing. */
x.pass();
CHECK_EQ(x.f.pc.drop_clean((x.all - 330) * 16), 0);
CHECK_EQ(x.f.pc.resident(), 4ll);
/* The loan the slab is short of reaches below them: they are forgotten, the start is not. */
x.pass();
CHECK_EQ(x.f.pc.drop_clean(goal), 4);
CHECK_EQ(x.f.pc.resident(), 0ll);
CHECK_EQ(x.f.pc.size(), 16ll);
CHECK_EQ(x.f.pc.stats().evictions, 4ll);
CHECK_EQ(x.f.kv.pool_bytes_used(G_FULL), 0ll);
CHECK(x.f.kv.spare_tokens() > pinned);
CHECK_OK(x.f.kv.set_loan(x.f.kv.spare_tokens()));
CHECK_EQ(x.f.pc.restorable_from(prompt, {}).size(), 16u);
}
/* Context that fills its part of the pool is not a straggler, with or without a host copy: the
* loan stops at its edge and takes none of it, however large the loan asked about. The end of an
* older conversation left far above it is, and goes alone. */
TEST(cached_context_that_fills_its_part_of_the_pool_stays_and_the_blocks_far_above_it_go) {
Stragglers x;
CHECK_OK(x.build(/*slots=*/8, /*under=*/300));
REQUIRE(x.all >= 400);
const auto older = tok_run(7800, 16 * 12 + 16);
publish(x.f, 1, older, 16 * 12); /* twelve blocks, at 300 and up */
CHECK_EQ(copy_now(x.t).size(), 8u); /* its start fills the tier */
x.f.kv.free_sequence(9);
x.f.kv.free_sequence(1);
const auto dense = tok_run(9100, 16 * 200 + 16);
publish(x.f, 2, dense, 16 * 200); /* two hundred blocks from the bottom */
CHECK_EQ(copy_now(x.t).size(), 0u); /* no room, and none is made here */
x.f.kv.free_sequence(2);
CHECK_EQ(x.f.pc.drop_clean(), 8); /* the older start, to the host */
CHECK_EQ(x.f.pc.resident(), 204ll);
CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 312ll);
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* the edge of the dense part */
x.pass();
const int64_t goal = x.all * 16; /* every block the pool has */
CHECK_EQ(x.f.pc.drop_clean(goal), 4);
CHECK_EQ(x.f.pc.resident(), 200ll);
CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 200ll);
CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* nothing above the dense part now */
x.pass();
CHECK_EQ(x.f.pc.drop_clean(goal), 0); /* which keeps every block */
CHECK_EQ(x.f.pc.resident(), 200ll);
CHECK_EQ(x.f.pc.lookup(dense, {}).n_attn_tokens, 16 * 200);
}
TEST(a_recomputed_shared_prefix_keeps_its_original_host_copy_and_snapshot) {
/* A short request shares less than one checkpoint with an off-device conversation, so it
* recomputes instead of adopting that prefix. Its different prefill shape can round the KV
+213
View File
@@ -0,0 +1,213 @@
"""mkglimmergolden.py OUT.h -- goldens for tests/mm_test.cpp's Muse Glimmer cases, every number
from the reference itself: transformers' own MuseGlimmerImageProcessor and
MuseGlimmerVideoProcessor (transformers 5.23.0.dev0, torch 2.15.0+cpu, torchvision 0.29.2+cpu),
run on synthetic splitmix frames, plus their sample_frames and replace_video_token.
The resize filter is the real reference path, not a reimplementation: the processor is a
TorchvisionBackend whose resize calls tvF.resize on the uint8 pixels with
InterpolationMode.LANCZOS and antialias=True on CPU, which torch serves with its native uint8
kernel (int16 fixed-point weights, horizontal pass first, an 8-bit rounded intermediate). The
test's C++ side has to reproduce that byte for byte.
* the resize table: each picture's grid straight out of image_grid_thw;
* two pictures' patch planes: the processor's f32 pixel_values cast to bfloat16, the patch rows
in the reference's own raster order (patch row by row), each row (temporal, channel, y, x) as
the reference lays it out, and the FNV-1a of the whole plane;
* a twelve-frame clip: the grid, the plane's FNV-1a, the per-group stamps (each
group's first frame's time, the reference's replace_video_token) and the sampled indices
(the reference's sample_frames, torch.linspace(...).long());
* a sampling table: the indices' count, first entry and FNV-1a.
The pixel at (frame f, row y, column x, channel c) is mm_test's pix(f, y, x, c) splitmix hash,
and pix's frame argument is the SOURCE frame's index, so the test's decoded frames match the
processor's sampled ones exactly.
"""
import sys
import numpy as np
import torch
import transformers
import torchvision
from PIL import Image
from transformers.models.muse_glimmer.image_processing_muse_glimmer import MuseGlimmerImageProcessor
from transformers.models.muse_glimmer.video_processing_muse_glimmer import MuseGlimmerVideoProcessor
from transformers.video_utils import VideoMetadata
PATCH, TEMPORAL, MERGE = 14, 2, 2
MAX_IMAGE_TOKENS = 4096
MAX_VIDEO_FRAME_TOKENS = 144
U = np.uint64
def picture(f, h, w):
"""[h, w, 3] uint8, mm_test's pix(f, y, x, c)."""
y = np.arange(h, dtype=np.uint64)[:, None]
x = np.arange(w, dtype=np.uint64)[None, :]
c = np.arange(3, dtype=np.uint64)[None, None, :]
z = (U(f) * U(0x9E3779B97F4A7C15) + y[:, :, None] * U(0xBF58476D1CE4E5B9) +
x[:, :, None] * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345))
z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9)
z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB)
return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8)
def fnv16(bits):
"""FNV-1a over each element's bytes, least significant first (mm_test's fnv)."""
h = 0xcbf29ce484222325
for v in np.asarray(bits, dtype=np.uint16).ravel(order="C"):
for b in (0, 1):
h = ((h ^ U((int(v) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1)
return int(h)
def bf16(a):
t = torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32))
return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16)
def image_processor():
return MuseGlimmerImageProcessor(
patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE,
max_image_tokens=MAX_IMAGE_TOKENS, image_mean=[0.5] * 3, image_std=[0.5] * 3)
def video_processor():
return MuseGlimmerVideoProcessor(
patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE,
max_video_frame_tokens=MAX_VIDEO_FRAME_TOKENS, num_frames=96, fps=2.0,
image_mean=[0.5] * 3, image_std=[0.5] * 3)
def process_image(h, w):
pil = Image.fromarray(picture(0, h, w), mode="RGB")
out = image_processor()(images=[pil], return_tensors="pt")
rows = out["pixel_values"] # [gh*gw, dim] f32, raster order
if rows.dim() == 3:
rows = rows[0]
gt, gh, gw = (int(v) for v in out["image_grid_thw"][0])
assert gt == 1
return bf16(rows.numpy()), gh, gw # raster order, as the reference emits it
def main(out):
print("transformers", transformers.__version__, "torch", torch.__version__,
"torchvision", torchvision.__version__)
resize_cases = [
(256, 320), (100, 100), (84, 84), (10, 10), (28, 28), (27, 27), (1, 1),
(8000, 8000), (2000, 50), (50, 2000), (300, 500), (640, 427), (1920, 1080),
(3, 5000), (500, 3), (1234, 5678), (7, 9), (112, 224), (224, 112),
]
L = [f"/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers "
f"{transformers.__version__} (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, "
f"torch {torch.__version__}, torchvision {torchvision.__version__}); do not edit. */",
"#pragma once", "#include <cstdint>", "",
"static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;",
"static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;",
"static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;",
"static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;",
"static const int32_t kGoldMuseVidSep = 200087;",
"",
"/* A h x w picture's resize target, in pixels. */",
"struct GoldMuseResize { int64_t h, w, oh, ow; };",
"static const GoldMuseResize kGoldMuseResize[] = {"]
print(" resize table + image patch planes")
image_cases = []
for h, w in resize_cases:
pil = Image.fromarray(picture(0, h, w), mode="RGB")
outi = image_processor()(images=[pil], return_tensors="pt")
_, gh, gw = (int(v) for v in outi["image_grid_thw"][0])
L.append(f" {{ {h}, {w}, {gh * PATCH}, {gw * PATCH} }},")
L.append("};")
L.append("")
for h, w in [(100, 100), (256, 320)]:
px, gh, gw = process_image(h, w)
image_cases.append((h, w, gh, gw, px))
L += ["/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the "
"FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row "
"(temporal, channel, y, x) as the reference lays it out. */",
"struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };",
"static const GoldMuseImage kGoldMuseImage[] = {"]
for h, w, gh, gw, px in image_cases:
head = ", ".join("0x%04x" % int(v) for v in px[0][:16])
L.append(f" {{ {h}, {w}, {gh}, {gw}, {{{head}}}, {fnv16(px)}ull }},")
L.append("};")
L.append("")
print(" video patch plane + stamps")
# A 37-frame source at 6 fps: the reference's sample_frames takes 12 frames at 2 fps, the
# indices linspace(0, 36, 12).long(); six temporal groups, one stamp per group, each the
# group's first frame's time.
total, native_fps, fps = 37, 6.0, 2.0
n = min(int(total * fps / native_fps), 96, total)
n = max(TEMPORAL, (n // TEMPORAL) * TEMPORAL)
n = min(n, total)
idx = torch.linspace(0, total - 1, n).long().tolist()
print(" sampled", n, "frames:", idx)
src = np.stack([picture(f, 64, 96) for f in idx]) # [T, H, W, 3]
md = VideoMetadata(total_num_frames=total, fps=native_fps, width=96, height=64,
duration=total / native_fps, video_backend="nil", frames_indices=idx)
outv = video_processor()(videos=[torch.from_numpy(src)], return_tensors="pt",
video_metadata=[md], do_sample_frames=False)
pv = outv["pixel_values_videos"] # [gt*gh*gw, dim] f32
gt, gh, gw = (int(v) for v in outv["video_grid_thw"][0])
print(" grid", gt, gh, gw)
plane = np.empty((gt, gh * gw, pv.shape[1]), dtype=np.uint16)
for g in range(gt):
plane[g] = bf16(pv[(g * gh * gw):(g + 1) * gh * gw].numpy())
flat = plane.reshape(-1)
# The stamps: metadata.timestamps[::temporal][:grid_t], each formatted "Time: {t:.1f}s".
timestamps = [i / native_fps for i in idx]
stamps = [f"Time: {t:.1f}s" for t in timestamps[::TEMPORAL][:gt]]
while len(stamps) < gt:
stamps.append(stamps[-1] if stamps else "Time: 0.0s")
print(" stamps:", stamps)
L += ["/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid "
"(groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's "
"stamp. */",
f"static const int64_t kGoldMuseVideoTotal = {total};",
f"static const double kGoldMuseVideoFps = {native_fps};",
f"static const int32_t kGoldMuseVideoN = {n};",
"static const int64_t kGoldMuseVideoIndex[] = {",
" " + ", ".join(str(i) for i in idx) + "};",
f"static const int32_t kGoldMuseVideoGrid[] = {{ {gt}, {gh}, {gw} }};",
"static const uint16_t kGoldMuseVideoHead[16] = {",
" " + ", ".join("0x%04x" % int(v) for v in flat[:16]) + "};",
f"static const uint64_t kGoldMuseVideoFnv = {fnv16(flat)}ull;",
"static const char* const kGoldMuseVideoStamps[] = {",
"".join(f' "{s}",\n' for s in stamps) + "};",
""]
while L[-1] == "":
L.pop()
print(" sampling table")
sample_cases = [(37, 6.0), (6, 2.0), (96, 24.0), (1, 2.0), (2, 2.0), (5, 12.0),
(600, 30.0), (1000, 24.0), (13, 7.0), (4, 1.0)]
L += ["/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the "
"FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */",
"struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };",
"static const GoldMuseSample kGoldMuseSample[] = {"]
proc = video_processor()
for total, fps in sample_cases:
md = VideoMetadata(total_num_frames=total, fps=fps, width=96, height=64,
duration=total / fps, video_backend="nil", frames_indices=None)
got = proc.sample_frames(md, temporal_patch_size=TEMPORAL, num_frames=96, fps=2.0).tolist()
h = 0xcbf29ce484222325
for i in got:
for b in range(8):
h = ((h ^ U((int(i) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1)
L.append(f" {{ {total}, {fps}, {len(got)}, {h}ull }},")
print(f" {total} @ {fps}: {got[:6]}{'...' if len(got) > 6 else ''} ({len(got)})")
L.append("};")
with open(out, "w") as f:
f.write("\n".join(L) + "\n")
print("wrote", out)
if __name__ == "__main__":
main(sys.argv[1])
+217
View File
@@ -23,6 +23,7 @@
#include "mm/processor.h"
#include "gemma4_golden.h"
#include "gemma4u_golden.h"
#include "glimmer_golden.h"
#include "glm5_golden.h"
#include "radio_golden.h"
#include "imaging_golden.h"
@@ -1126,6 +1127,222 @@ TEST(glm5_reads_its_processor_from_the_container) {
CHECK(why.find("patch_expand_factor") != std::string::npos);
}
/* ================================================================== Muse Glimmer's processor
*
* glimmer_golden.h: transformers' own MuseGlimmerImageProcessor and MuseGlimmerVideoProcessor
* (mkglimmergolden.py ran them on synthetic splitmix frames), which the processor mirrors: the
* token-capped aspect-nearest resize, torchvision's antialiased Lanczos on the uint8 pixels, the
* (temporal, channel, y, x) patch rows in radiance's merge-block order, and the sampled frames'
* per-group "Time: T s" stamps. */
namespace {
VisionConfig muse_cfg() {
VisionConfig c;
c.family = Family::MuseGlimmer;
c.patch = kGoldMusePatch;
c.temporal = kGoldMuseTemporal;
c.merge = kGoldMuseMerge;
c.max_image_tokens = 4096;
c.max_frame_rows = 144;
c.fps = 2.0;
c.min_frames = c.temporal;
c.max_frames = 96;
const int64_t f2 = (int64_t)c.factor() * c.factor();
c.image_min_pixels = c.video_min_pixels = f2;
c.image_max_pixels = (int64_t)c.max_image_tokens * f2;
c.video_max_pixels = (int64_t)c.max_frame_rows * f2;
c.tok_image = kGoldMuseTokImage;
c.tok_video = kGoldMuseTokVideo;
c.tok_start = kGoldMuseTokStart;
c.tok_end = kGoldMuseTokEnd;
c.tok_video_start = kGoldMuseVidStart;
c.tok_video_end = kGoldMuseVidEnd;
c.tok_video_sep = kGoldMuseVidSep;
c.max_patches = 16384;
return c;
}
} /* namespace */
TEST(muse_sizes_are_the_references) {
for (const GoldMuseResize& g : kGoldMuseResize) {
int64_t oh = 0, ow = 0;
std::string why;
CHECK_OK(muse_size(g.h, g.w, kGoldMusePatch * kGoldMuseMerge, 4096, &oh, &ow, &why));
if (oh != g.oh || ow != g.ow)
std::fprintf(stderr, " %lld x %lld: %lld x %lld, reference %lld x %lld\n",
(long long)g.h, (long long)g.w, (long long)oh, (long long)ow,
(long long)g.oh, (long long)g.ow);
CHECK_EQ(oh, g.oh);
CHECK_EQ(ow, g.ow);
}
}
TEST(muse_pictures_patchify_as_the_reference_does) {
Processor p;
int rc = p.init(muse_cfg(), [](const std::string&) { return std::vector<int32_t>{ 1 }; });
REQUIRE(rc >= 0);
for (const GoldMuseImage& g : kGoldMuseImage) {
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.image_from(frame(0, (int)g.h, (int)g.w), &it, &why));
REQUIRE(it != nullptr);
if (it->grid_h != g.gh || it->grid_w != g.gw)
std::fprintf(stderr, " %lld x %lld: grid %d x %d, reference %d x %d\n",
(long long)g.h, (long long)g.w, it->grid_h, it->grid_w, g.gh, g.gw);
CHECK_EQ(it->grid_t, 1);
CHECK_EQ(it->grid_h, g.gh);
CHECK_EQ(it->grid_w, g.gw);
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176);
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]);
CHECK_EQ(fnv(it->pixels), g.fnv);
/* <|image_start|>, one <|patch|> per merged row, <|image_end|>: the reference's
* replace_image_token. */
const int32_t rows = (g.gh / 2) * (g.gw / 2);
REQUIRE_EQ(it->expand.size(), (size_t)rows + 2);
CHECK_EQ(it->expand.front(), kGoldMuseTokStart);
CHECK_EQ(it->expand.back(), kGoldMuseTokEnd);
for (int32_t i = 1; i <= rows; ++i) CHECK_EQ(it->expand[(size_t)i], kGoldMuseTokImage);
REQUIRE_EQ(it->seg_at.size(), (size_t)1);
CHECK_EQ(it->seg_at[0], 1);
CHECK_EQ(it->n_rows(), (int64_t)rows);
}
}
TEST(muse_reads_its_processor_from_the_container) {
const char* keys[] = { "vision_config.model_type", "vision_config.patch_size",
"vision_config.patch_temporal", "vision_config.merge_size",
"image_token_id", "video_token_id",
"processor.image_processor.max_image_tokens",
"processor.video_processor.max_video_frame_tokens",
"processor.video_processor.num_frames",
"processor.video_processor.fps",
"processor.image_mean", "processor.image_std" };
const char* vals[] = { "muse_glimmer_vision", "14", "2", "2", "200092", "200091",
"4096", "144", "96", "2", "", "" };
RadModelMeta m{};
m.n_kv = (int)(sizeof(keys) / sizeof(keys[0]));
m.kv_key = keys;
m.kv_val = vals;
VisionConfig c;
std::string why;
CHECK_OK(c.from_meta(m, &why));
CHECK(c.family == Family::MuseGlimmer);
CHECK_EQ(c.patch, 14);
CHECK_EQ(c.temporal, 2);
CHECK_EQ(c.merge, 2);
CHECK_EQ(c.patch_dim(), (int64_t)1176);
CHECK_EQ(c.factor(), 28);
CHECK_EQ(c.max_image_tokens, 4096);
CHECK_EQ(c.max_frame_rows, 144);
CHECK_EQ(c.max_frames, 96);
CHECK_EQ(c.fps, 2.0);
CHECK_EQ(c.tok_image, 200092);
CHECK_EQ(c.tok_video, 200091);
/* The markers the container does not number stay unresolved for the vocabulary. */
CHECK_EQ(c.tok_start, -1);
CHECK_EQ(c.tok_video_sep, -1);
/* The shipped mean and deviation, over the reference class's IMAGENET_STANDARD defaults. */
for (int i = 0; i < 3; ++i) {
CHECK_EQ(c.mean[i], 0.5f);
CHECK_EQ(c.stdv[i], 0.5f);
}
/* Numbered markers and stated mean/std win. */
vals[4] = "200090";
vals[10] = "0.48 0.46 0.41";
vals[11] = "0.27 0.26 0.28";
vals[11] = "0.27 0.26 0.28";
VisionConfig d;
CHECK_OK(d.from_meta(m, &why));
CHECK_EQ(d.tok_image, 200090);
CHECK_EQ(d.mean[0], 0.48f);
CHECK_EQ(d.stdv[2], 0.28f);
/* No tower geometry: refused, not defaulted. */
vals[1] = "0";
VisionConfig e;
CHECK_EQ(e.from_meta(m, &why), RAD_E_NOTFOUND);
/* A marker the container does not number that the vocabulary cannot spell: refused at init,
* not on the first picture. */
VisionConfig unnumbered = muse_cfg();
unnumbered.tok_start = -1;
Processor p;
CHECK_EQ(p.init(unnumbered, [](const std::string&) { return std::vector<int32_t>{ 1 }; },
[](const std::string&) { return -1; }),
RAD_E_NOTFOUND);
/* A frame budget above one pass: refused. */
VisionConfig big = muse_cfg();
big.max_patches = 100;
Processor q;
CHECK_EQ(q.init(big, [](const std::string&) { return std::vector<int32_t>{ 1 }; }),
RAD_E_INVAL);
}
TEST(muse_frames_are_sampled_as_the_reference_does) {
for (const GoldMuseSample& g : kGoldMuseSample) {
VideoInfo info{};
info.n_frames = g.total;
info.fps = g.fps;
const std::vector<int64_t> idx = sample_frames_muse(info, 2.0, kGoldMuseTemporal, 96);
if ((int32_t)idx.size() != g.n)
std::fprintf(stderr, " %lld frames at %g fps: %zu indices, reference %d\n",
(long long)g.total, g.fps, idx.size(), g.n);
CHECK_EQ((int32_t)idx.size(), g.n);
CHECK_EQ(fnv(idx), g.fnv);
}
}
TEST(a_muse_clip_patchifies_and_is_stamped_as_the_reference_does) {
std::vector<std::string> stamps;
Processor p;
REQUIRE(p.init(muse_cfg(), [&](const std::string& s) {
stamps.push_back(s);
return std::vector<int32_t>((size_t)s.size(), 7); /* a token per byte */
}) >= 0);
Video v;
v.info.n_frames = kGoldMuseVideoTotal;
v.info.fps = kGoldMuseVideoFps;
v.info.w = 96;
v.info.h = 64;
v.index.assign(kGoldMuseVideoIndex,
kGoldMuseVideoIndex + sizeof(kGoldMuseVideoIndex) / sizeof(kGoldMuseVideoIndex[0]));
for (int64_t i : v.index) v.frames.push_back(frame((int)i, 64, 96));
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.video_from(v, &it, &why));
REQUIRE(it != nullptr);
CHECK_EQ(it->grid_t, kGoldMuseVideoGrid[0]);
CHECK_EQ(it->grid_h, kGoldMuseVideoGrid[1]);
CHECK_EQ(it->grid_w, kGoldMuseVideoGrid[2]);
REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176);
for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], kGoldMuseVideoHead[i]);
CHECK_EQ(fnv(it->pixels), kGoldMuseVideoFnv);
/* One stamp per group, the group's first frame's time. */
const size_t n_stamps = sizeof(kGoldMuseVideoStamps) / sizeof(kGoldMuseVideoStamps[0]);
REQUIRE_EQ(stamps.size(), n_stamps);
for (size_t i = 0; i < n_stamps; ++i) CHECK_EQ(stamps[i], std::string(kGoldMuseVideoStamps[i]));
/* <|vid_start|>, then per group: the stamp's tokens, one <|video|> per merged row, and a
* <|vid_frame_separator|> between the groups and <|vid_end|> after the last. */
const int32_t rows = (kGoldMuseVideoGrid[1] / 2) * (kGoldMuseVideoGrid[2] / 2);
size_t at = 0;
REQUIRE_EQ(it->seg_at.size(), (size_t)kGoldMuseVideoGrid[0]);
CHECK_EQ(it->expand[at], kGoldMuseVidStart);
++at;
for (int32_t g = 0; g < kGoldMuseVideoGrid[0]; ++g) {
at += stamps[(size_t)g].size();
REQUIRE(at < it->expand.size());
CHECK_EQ(it->seg_at[(size_t)g], (int32_t)at);
for (int32_t r = 0; r < rows; ++r) CHECK_EQ(it->expand[at + (size_t)r], kGoldMuseTokVideo);
at += (size_t)rows;
CHECK_EQ(it->expand[at], g + 1 == kGoldMuseVideoGrid[0] ? kGoldMuseVidEnd
: kGoldMuseVidSep);
++at;
}
CHECK_EQ(at, it->expand.size());
}
/* ================================================================== Pillow's arithmetic
*
* imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow,
File diff suppressed because it is too large. Load diff
+63 -10
View File
@@ -1,5 +1,6 @@
#!/bin/sh
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER]]]
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER
# [BUILD_TYPE]]]]
#
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
@@ -26,11 +27,15 @@
# has already checked what the out-of-tree build produced.
set -eu
B=$1; S=$2; W=$3
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}; BT=${8:-}
# The tree's own C++ compiler, so the out-of-tree build does not depend on the host's default
# (`c++` may be a different GCC than the one the installed ABI headers require).
CCXX=""
[ -n "$CXXC" ] && CCXX="-DCMAKE_CXX_COMPILER=$CXXC"
# The tree's build type too: a plugin configured without one takes RelWithDebInfo
# (rad_plugin_defaults), and a tree configured as anything else would then be compared with device
# code compiled at other flags.
[ -n "$BT" ] && CCXX="$CCXX -DCMAKE_BUILD_TYPE=$BT"
GEN=${CMAKE_GENERATOR:-Ninja}
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
@@ -49,10 +54,14 @@ run() { # run LOG CMD... -- quiet unless it fails
say "installing $B into $P"
run "$W/logs/install.log" cmake --install "$B" --prefix "$P"
# The libraries have many sources and build one at a time at the build's full width. An
# architecture or a bundled plugin is one or two large translation units, which no -j speeds up, and
# there are dozens of them: those are built several at a time (`small`, below).
dirs="libref libquant"
[ -d "$S/libavx" ] && [ -f "$B/radiance_home/kernels/libavx.so" ] && dirs="$dirs libavx"
small=""
for d in "$S"/arch/*/ "$S"/plugin/*/; do
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")"
[ -f "$d/CMakeLists.txt" ] && small="$small $(basename "$(dirname "$d")")/$(basename "$d")"
done
# The device libraries: built out of tree only with the tree's HIP compiler, and left out of every
# comparison below without it. Each declares the family it serves, so a tree built for one family
@@ -62,30 +71,74 @@ devlibs=""
for d in libr4d libr3d; do
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d"
done
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
devdirs=""
[ -n "$HIPC" ] && devdirs="$devlibs"
is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
# Each plugin installs its plugin file under $H and anything else it ships (libr4d's r4d_selftest)
# under the package's prefix, as a third party installing into that radiance would.
for d in $dirs; do
n=$(basename "$d")
say "building $d against the installed package"
#
# The ROCm the environment names (the test sets ROCM_PATH to the one the tree links) goes on the
# prefix path beside the package: CMake otherwise takes the HIP runtime from wherever the HIP
# compiler sits, and a tree whose compiler comes from another ROCm build than its runtime would
# get a libr4d linked against that build's runtime, which then fails to load.
PP="$P"
[ -n "${ROCM_PATH:-}" ] && PP="$P;$ROCM_PATH"
build_one() { # build_one DIR JOBS -- configure and build one plugin directory
d=$1; n=$(basename "$d")
extra="$CCXX"
is_dev "$n" && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
# A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's
# HIP compiler as a third party would pass theirs.
case "$d" in plugin/*) [ -n "$HIPC" ] && extra="-DCMAKE_HIP_COMPILER=$HIPC" ;; esac
case "$d" in plugin/*) [ -n "$HIPC" ] && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC" ;; esac
# shellcheck disable=SC2086
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
-DCMAKE_PREFIX_PATH="$P" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J"
-DCMAKE_PREFIX_PATH="$PP" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$2"
}
install_one() { # install_one DIR
n=$(basename "$1")
# --prefix for the same reason as the tree install above: a plugin's own CMakeLists may install
# companions (libr4d ships r4d_selftest) to relative destinations under CMAKE_INSTALL_PREFIX, and
# the test must not need root. The plugins themselves ignore the prefix -- rad_add_plugin installs
# them under the absolute RAD_PLUGIN_INSTALL_HOME given at configure time -- so the checks below,
# which look in $H, are unaffected.
run "$W/logs/$n.install.log" cmake --install "$W/b/$n" --prefix "$W/i"
}
for d in $dirs; do
say "building $d against the installed package"
build_one "$d" "$J"
install_one "$d"
done
# OOT_JOBS of the small ones at a time (default half the build's width, at most 16: a plugin's
# compile holds about half a GiB), two compile jobs each; installed one after another, in order.
PJ=${OOT_JOBS:-$((J / 2))}
[ "$PJ" -gt 16 ] && PJ=16
[ "$PJ" -lt 1 ] && PJ=1
# shellcheck disable=SC2086
set -- $small
say "building $# architectures and bundled plugins against the installed package, $PJ at a time"
while [ $# -gt 0 ]; do
batch=""; nb=0
while [ $# -gt 0 ] && [ "$nb" -lt "$PJ" ]; do
batch="$batch $1"; nb=$((nb + 1))
( build_one "$1" 2 && : > "$W/logs/$(basename "$1").built" ) &
shift
done
wait
for d in $batch; do
[ -f "$W/logs/$(basename "$d").built" ] ||
fail "$d did not build out of tree (logs: $W/logs/$(basename "$d").*.log)"
install_one "$d"
done
done
for d in $devdirs; do
say "building $d against the installed package"
build_one "$d" "$J"
install_one "$d"
done
# 1. The same plugins, file for file.
+28 -5
View File
@@ -306,15 +306,16 @@ int main(int argc, char** argv) {
{"wmma h256 gqa2 i8 ahead w20 picture 90 of 300", 256, 2, 2, true, false, false, false, 20, {90}, {300}, -1, 0, 0, 0, 1, true},
/* LiLiCorr's drafter (attn_paged_sink): 32 query heads over 2 KV heads at h128 (16 over 1 at
* TP 2), a block of 8 non-causal rows past the context, a 1024-token window; one sequence
* and a batch, unsplit and split, a bf16 and an int8 cache */
* and a batch, unsplit and split, a bf16 and an int8 cache, and a prefill-shaped launch
* that takes the WMMA kernel (with and without int8 descales) */
{"sink h128 gqa16 kvh2 block8 w1024", 128, 16, 2, false, false, false, false, 1024, {8}, {1500},
-1, 0, 0, 0, -1, false, true},
{"sink h128 gqa16 kvh1 block8 x3 split", 128, 16, 1, false, false, true, false, 1024, {8, 8, 8},
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa16 kvh2 i8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300},
-1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 0, false, true},
{"sink h128 gqa16 prefill-shaped takes WMMA", 128, 16, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa16 missing-block", 128, 16, 1, false, false, false, false, 1024, {8}, {70}, 1,
0, 0, 0, -1, false, true},
/* and at TP 4, 8 query heads over the rank's replicated KV head */
@@ -324,8 +325,30 @@ int main(int argc, char** argv) {
{900, 40, 2100}, -1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa8 kvh1 i8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300},
-1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa8 prefill-shaped stays scalar", 128, 8, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 0, false, true},
{"sink h128 gqa8 prefill-shaped takes WMMA", 128, 8, 1, false, false, false, false, 1024, {96},
{400}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 prefill-shaped WMMA i8+descale", 128, 8, 1, true, false, false, true, 1024,
{96}, {400}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa16 prefill-shaped WMMA i8+descale", 128, 16, 1, true, false, false, true, 1024,
{96}, {400}, -1, 0, 0, 0, 1, false, true},
/* Recursive Flint (arch/flint): 32 query heads over 4 KV heads at h128 (gqa 8 at TP 1 and
* 2), causal, a sink on every layer; the sliding layers' 513-token window and the full
* layers' none. Prefill on the WMMA kernel, ragged with decode rows beside it and with a
* missing block, and decode on the scalar kernel's split, at both caches. */
{"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200", 128, 8, 4, false, true, false, false,
513, {300}, {1200}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200 i8", 128, 8, 4, true, true, false, false,
513, {300}, {1200}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 kvh2 causal full prefill 200 of 900 i8", 128, 8, 2, true, true, false, false,
0, {200}, {900}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 kvh2 causal full ragged + decode rows", 128, 8, 2, false, true, true, false,
0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 kvh2 causal w513 ragged missing-block i8", 128, 8, 2, true, true, true, false,
513, {130, 70}, {700, 70}, 3, 0, 0, 0, 1, false, true},
{"sink h128 gqa8 kvh4 causal w513 decode split i8", 128, 8, 4, true, true, true, false, 513,
{1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true},
{"sink h128 gqa8 kvh4 causal full decode split", 128, 8, 4, false, true, true, false, 0,
{1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true},
/* and what must stay scalar: a verify batch, many sequences, a few rows each */
{"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16},
{40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0},
+229
View File
@@ -0,0 +1,229 @@
/* tests/r4d_emu: Muse Glimmer's vision-tower coordinate ops (r4d_vit_muse.hip) on the host SIMT
* emulator.
*
* grid_embed_pad: held to hand-computed constants -- a side-4 table resampled to an 8 x 8 grid,
* whose last row and column reach taps off the table (zero-weight, grid_sample's zeros padding),
* and an in-range 4 x 4 grid that reads the table whole. window_order: held to an independent host
* reference that sorts the patches by (segment, window row, window column, raster), which shares
* no arithmetic with the kernel's base-plus-rank slot formula; the inverse permutation, the rope
* positions and every cuw boundary follow from that order.
*/
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "ref_host.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
static RadTensor rows(void* p, uint32_t dt, int64_t r0, int64_t r1, int64_t ld) {
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = r0; t.shape[1] = r1;
t.stride[0] = ld; t.stride[1] = 1;
return t;
}
static RadTensor vec(void* p, uint32_t dt, int64_t n) {
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1;
return t;
}
static RadParam pi_(const char* k, long long v) { RadParam p{}; p.key = k; p.kind = RAD_P_INT; p.ival = v; return p; }
static RadParam ps_(const char* k, const char* v) { RadParam p{}; p.key = k; p.kind = RAD_P_STR; p.sval = v; return p; }
// ------------------------------------------------------------------ grid_embed_pad
static int test_pad() {
const int64_t n = 3, side = 4;
/* table[h * 4 + w] = (h * 4 + w + 1) / 4, three channels offset by 0.1 */
std::vector<float> tabf((size_t)(side * side * n));
for (int h = 0; h < side; ++h)
for (int w = 0; w < side; ++w)
for (int c = 0; c < n; ++c) tabf[(size_t)((h * side + w) * n + c)] = (h * side + w + 1) * 0.25f + 0.1f * c;
std::vector<uint16_t> tab((size_t)(side * side * n));
for (size_t i = 0; i < tab.size(); ++i) tab[i] = f2b(tabf[i]);
/* An 8 x 8 grid: src(i) = i / 2 - 0.25 on each axis; per axis the taps are floor(src) and
* floor(src) + 1 with hat weights, the off-table tap's weight zero. Row 0: taps -1 (masked)
* and 0 at 3/4; row 7: tap 3 at 3/4 and 4 (masked); interior rows blend two adjacent taps. */
const int64_t M = 6;
/* Rows (0,0), (7,7), (1,3), (4,2), (7,0), (3,7) of the 8 x 8 grid. */
const int rr[6] = { 0, 7, 1, 4, 7, 3 }, cc[6] = { 0, 7, 3, 2, 0, 7 };
std::vector<int32_t> crd(4 * M);
for (int m = 0; m < 6; ++m) {
crd[m] = rr[m]; crd[M + m] = cc[m]; crd[2 * M + m] = 8; crd[3 * M + m] = 8;
}
std::vector<uint16_t> x((size_t)(M * n));
for (size_t i = 0; i < x.size(); ++i) x[i] = f2b(7.0f);
RadTensor t[3] = { rows(x.data(), RAD_BF16, M, n, n), rows(tab.data(), RAD_BF16, side * side, n, n),
rows(crd.data(), RAD_I32, 4, M, M) };
RadParam p[4] = { pi_("M", M), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") };
RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 4;
if (r4d_rad_grid_embed_pad(&a, nullptr) != RAD_OK) { std::puts("grid_embed_pad: launch failed"); return 1; }
/* Hand-computed: each axis's in-range weight (the off-table tap contributes nothing), the
* joint weight the product h*w, the taps summed in libref's order (top-left, top-right,
* bottom-left, bottom-right). Channel 0; the others sit 0.1 apart, and x starts at 7. */
/* (0,0): both axes tap 0 only, at 3/4 each -> 9/16 * 0.25 = 0.140625. */
/* (7,7): both axes tap 3 only at 3/4 -> 9/16 * 4 = 2.25. */
/* (1,3): rows 0,1 at 3/4, 1/4; cols 1,2 at 3/4, 1/4 -> 0.8125. */
/* (4,2): rows 1,2 at 1/4, 3/4; cols 1,2 at 3/4, 1/4 -> 2.3125. */
/* (7,0): row tap 3 at 3/4 (tap 4 masked), col tap 0 at 3/4 (tap -1 masked) -> 1.828125. */
/* (3,7): rows 1,2 at 3/4, 1/4; col tap 3 at 3/4 (tap 4 masked) -> 1.6875. */
/* Hand-derived per row: the literal taps and weights (channel 0 verified against the printed
* fractions, every channel against this table). Taps summed in libref's order: top-left,
* top-right, bottom-left, bottom-right, each joint weight the product h*w. */
struct Taps { int th0, th1, tw0, tw1; float wh0, wh1, ww0, ww1; };
const Taps taps[6] = {
{ 0, 0, 0, 0, 0.0f, 0.75f, 0.0f, 0.75f }, /* (0,0): taps -1/4 masked, 0 at 3/4 */
{ 3, 3, 3, 3, 0.75f, 0.0f, 0.75f, 0.0f }, /* (7,7): taps 3 at 3/4, 4 masked */
{ 0, 1, 1, 2, 0.75f, 0.25f, 0.75f, 0.25f }, /* (1,3) */
{ 1, 2, 0, 1, 0.25f, 0.75f, 0.25f, 0.75f }, /* (4,2) */
{ 3, 3, 0, 0, 0.75f, 0.0f, 0.0f, 0.75f }, /* (7,0): row 4 and col -1 masked */
{ 1, 2, 3, 3, 0.75f, 0.25f, 0.75f, 0.0f }, /* (3,7): col 4 masked */
};
int bad = 0;
for (int m = 0; m < 6; ++m) {
const Taps& t6 = taps[m];
for (int c = 0; c < n; ++c) {
const float acc =
b2f(tab[(size_t)((t6.th0 * side + t6.tw0) * n + c)]) * (t6.wh0 * t6.ww0) +
b2f(tab[(size_t)((t6.th0 * side + t6.tw1) * n + c)]) * (t6.wh0 * t6.ww1) +
b2f(tab[(size_t)((t6.th1 * side + t6.tw0) * n + c)]) * (t6.wh1 * t6.ww0) +
b2f(tab[(size_t)((t6.th1 * side + t6.tw1) * n + c)]) * (t6.wh1 * t6.ww1);
const float w = rb(7.0f + rb(acc));
const float got = b2f(x[(size_t)(m * n + c)]);
if (got != w) {
++bad;
std::printf("grid_embed_pad: row %d ch %d: got %g want %g\n", m, c, got, w);
}
}
}
/* In range: a 4 x 4 grid on the side-4 table reads each row whole (src = i exactly). */
const int64_t M2 = 2;
std::vector<int32_t> crd2(4 * M2);
crd2[0] = 2; crd2[1] = 3; crd2[4] = 4; crd2[5] = 4; crd2[6] = 4; crd2[7] = 4;
crd2[2] = 1; crd2[3] = 2;
std::vector<uint16_t> x2((size_t)(M2 * n));
for (size_t i = 0; i < x2.size(); ++i) x2[i] = f2b(0.0f);
RadTensor t2[3] = { rows(x2.data(), RAD_BF16, M2, n, n),
rows(tab.data(), RAD_BF16, side * side, n, n),
rows(crd2.data(), RAD_I32, 4, M2, M2) };
RadParam p2[4] = { pi_("M", M2), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") };
RadArgs a2{}; a2.t = t2; a2.n_t = 3; a2.p = p2; a2.n_p = 4;
if (r4d_rad_grid_embed_pad(&a2, nullptr) != RAD_OK) { std::puts("grid_embed_pad in-range: launch failed"); return 1; }
for (int m = 0; m < 2; ++m)
for (int c = 0; c < n; ++c) {
const int h = m == 0 ? 2 : 3, w = m == 0 ? 1 : 2;
const float want = rb(rb(tabf[(size_t)((h * side + w) * n + c)]) + 0.0f);
if (b2f(x2[(size_t)(m * n + c)]) != want) {
++bad;
std::printf("grid_embed_pad in-range: row %d ch %d: got %g want %g\n", m, c,
b2f(x2[(size_t)(m * n + c)]), want);
}
}
return bad ? 1 : 0;
}
// ------------------------------------------------------------------ window_order
/* The independent reference: sort patches by (segment, window row, window column, row, col). */
struct Ord { int seg, wr, wc, r, c, p; };
static int test_window(int window, const std::vector<std::pair<int, int>>& grids) {
/* Pack the grids back to back: segment s covers base .. base + gh*gw. */
int P = 0;
std::vector<int> cu{ 0 };
std::vector<int> gh_(grids.size()), gw_(grids.size());
for (size_t s = 0; s < grids.size(); ++s) {
gh_[s] = grids[s].first; gw_[s] = grids[s].second;
P += gh_[s] * gw_[s];
cu.push_back(P);
}
std::vector<int32_t> crd(4 * (size_t)P, 0);
std::vector<Ord> ord;
for (size_t s = 0; s < grids.size(); ++s) {
const int base = cu[s];
for (int r = 0; r < gh_[s]; ++r)
for (int c = 0; c < gw_[s]; ++c) {
const int p = base + r * gw_[s] + c;
crd[p] = r; crd[(size_t)P + p] = c;
crd[2 * (size_t)P + p] = gh_[s]; crd[3 * (size_t)P + p] = gw_[s];
ord.push_back({ (int)s, window > 0 ? r / window : 0, window > 0 ? c / window : 0,
r, c, p });
}
}
std::stable_sort(ord.begin(), ord.end(), [](const Ord& l, const Ord& r) {
if (l.seg != r.seg) return l.seg < r.seg;
if (l.wr != r.wr) return l.wr < r.wr;
if (l.wc != r.wc) return l.wc < r.wc;
if (l.r != r.r) return l.r < r.r;
return l.c < r.c;
});
std::vector<int32_t> widx((size_t)P), winv((size_t)P), wpos(2 * (size_t)P), wcuw((size_t)P + 1, P);
for (int slot = 0; slot < P; ++slot) {
widx[(size_t)slot] = ord[(size_t)slot].p;
winv[(size_t)ord[(size_t)slot].p] = slot;
wpos[(size_t)slot] = ord[(size_t)slot].c + 1; /* pos[0][slot] = col + 1 */
wpos[(size_t)P + (size_t)slot] = ord[(size_t)slot].r + 1;
}
if (window <= 0) {
for (int i = 0; i <= (int)grids.size() && i <= P; ++i) wcuw[(size_t)i] = cu[(size_t)i];
} else {
/* cuw[k] is the base slot of window k: the patches before it in the permuted order. */
int k = 0, base = 0;
for (size_t s = 0; s < grids.size(); ++s) {
const int nh = (gh_[s] + window - 1) / window, nw = (gw_[s] + window - 1) / window;
for (int wr = 0; wr < nh; ++wr)
for (int wc = 0; wc < nw; ++wc) {
wcuw[(size_t)k] = base;
int cnt = 0;
for (const Ord& o : ord)
if (o.seg == (int)s && o.wr == wr && o.wc == wc) ++cnt;
base += cnt;
++k;
}
}
wcuw[(size_t)k] = P;
}
std::vector<int32_t> idx((size_t)P, -1), inv((size_t)P, -1), pos(2 * (size_t)P, -1),
cuw((size_t)P + 1, -1);
RadTensor t[6] = { rows(crd.data(), RAD_I32, 4, P, P), rows(cu.data(), RAD_I32, 1, (int64_t)cu.size(), (int64_t)cu.size()),
rows(idx.data(), RAD_I32, 1, P, P), rows(inv.data(), RAD_I32, 1, P, P),
rows(pos.data(), RAD_I32, 2, P, P), rows(cuw.data(), RAD_I32, 1, P + 1, P + 1) };
RadParam p[2] = { pi_("M", P), pi_("window", window) };
RadArgs a{}; a.t = t; a.n_t = 6; a.p = p; a.n_p = 2;
if (r4d_rad_window_order(&a, nullptr) != RAD_OK) {
std::printf("window_order w=%d: launch failed\n", window);
return 1;
}
int bad = 0;
for (int i = 0; i < P; ++i) {
if (idx[(size_t)i] != widx[(size_t)i]) { ++bad; std::printf("window_order w=%d: idx[%d] %d want %d\n", window, i, idx[(size_t)i], widx[(size_t)i]); }
if (inv[(size_t)i] != winv[(size_t)i]) { ++bad; std::printf("window_order w=%d: inv[%d] %d want %d\n", window, i, inv[(size_t)i], winv[(size_t)i]); }
if (pos[(size_t)i] != wpos[(size_t)i]) { ++bad; std::printf("window_order w=%d: pos c[%d] %d want %d\n", window, i, pos[(size_t)i], wpos[(size_t)i]); }
if (pos[(size_t)P + (size_t)i] != wpos[(size_t)P + (size_t)i]) { ++bad; std::printf("window_order w=%d: pos r[%d] %d want %d\n", window, i, pos[(size_t)P + (size_t)i], wpos[(size_t)P + (size_t)i]); }
if (idx[(size_t)inv[(size_t)i]] != i) ++bad; /* the inverse property */
}
for (size_t i = 0; i <= (size_t)P; ++i)
if (cuw[i] != wcuw[i]) { ++bad; std::printf("window_order w=%d: cuw[%zu] %d want %d\n", window, i, cuw[i], wcuw[i]); }
return bad ? 1 : 0;
}
int main() {
int rc = 0;
rc |= test_pad();
/* One 48 x 40 segment, window 32: ragged right and bottom, windows 32x32, 32x8, 16x32, 16x8. */
rc |= test_window(32, { { 48, 40 } });
/* Video-style: two segments back to back, window 16. */
rc |= test_window(16, { { 20, 24 }, { 10, 12 } });
/* Window-divisible. */
rc |= test_window(8, { { 16, 24 } });
/* A window larger than the grid: one window holding the whole segment. */
rc |= test_window(64, { { 12, 10 } });
/* window <= 0: the identity, cuw = cu. */
rc |= test_window(0, { { 9, 7 }, { 5, 5 } });
if (!rc) std::puts("r4d_emu_vit: ok");
return rc;
}
+185
View File
@@ -0,0 +1,185 @@
/* radfile_keep_test.cpp -- what the load's page-cache drop keeps, and what it must not.
*
* The bug this guards: a container larger than RAM has its blob dropped from the page cache after
* the load, so the cache is not left full of weight pages nothing reads again. The mapped tier is
* the exception -- an n-gram table is read through its mapping for the engine's whole life -- and
* dropping it means every gather after a restart faults the rows back from disk (measured: 1 519
* vs 1 998 tok/s prefill on a 24k prompt, 103 GiB table). Two things have to be right for the
* exception to work, and neither is visible from the outside:
*
* 1. the drop frees the blob MINUS the kept ranges, page-aligned so a page holding kept bytes is
* never dropped (rad_keep_complement);
* 2. only addresses inside the container become kept ranges: a copy in RAM
* (--ngram-placement ram) or a table read from its own file (disk=DIR) is not the blob, and
* recording one would keep pages that belong to something else (rad_blob_range).
*
* The second is the easier one to get wrong silently: an offset computed from a pointer that is
* not in the mapping is plausible arithmetic.
*/
#include "rad_test.h"
#include "format/radfile.h"
#include <cstdint>
#include <utility>
#include <vector>
using namespace rad;
namespace {
constexpr int64_t kPage = 4096;
constexpr int64_t kTables = 64 * 1024; /* where the blob starts */
constexpr int64_t kBlob = 1 << 20; /* one MiB of blob */
constexpr int64_t kSize = kTables + kBlob; /* the container's size */
using Ranges = std::vector<std::pair<int64_t, int64_t>>; /* (offset, length) */
Ranges complement(Ranges keep) {
return rad_keep_complement(kTables, kSize, std::move(keep));
}
/* Total bytes a set of ranges covers, which is what "freed" or "kept" means to a page cache. */
int64_t covered(const Ranges& r) {
int64_t n = 0;
for (const auto& x : r) n += x.second;
return n;
}
} // namespace
/* ---- the drop's geometry ---------------------------------------------------------------- */
TEST(without_a_keep_list_the_whole_blob_is_dropped) {
const Ranges freed = complement({});
CHECK_EQ(freed.size(), size_t(1));
CHECK_EQ(freed.at(0).first, kTables);
CHECK_EQ(freed.at(0).second, kBlob);
}
TEST(a_kept_range_splits_the_drop_around_it) {
const Ranges freed = complement({{kTables + 256 * 1024, 256 * 1024}});
CHECK_EQ(freed.size(), size_t(2));
CHECK_EQ(freed.at(0).first, kTables);
CHECK_EQ(freed.at(0).second, 256 * 1024);
CHECK_EQ(freed.at(1).first, kTables + 512 * 1024);
CHECK_EQ(freed.at(1).second, kBlob - 512 * 1024);
CHECK_EQ(covered(freed), kBlob - 256 * 1024);
}
TEST(a_kept_range_at_the_start_leaves_one_range_behind_it) {
const Ranges freed = complement({{kTables, 128 * 1024}});
CHECK_EQ(freed.size(), size_t(1));
CHECK_EQ(freed.at(0).first, kTables + 128 * 1024);
CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024);
}
TEST(a_kept_range_at_the_end_leaves_one_range_before_it) {
const Ranges freed = complement({{kSize - 128 * 1024, 128 * 1024}});
CHECK_EQ(freed.size(), size_t(1));
CHECK_EQ(freed.at(0).first, kTables);
CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024);
}
TEST(a_keep_list_covering_the_blob_drops_nothing) {
CHECK(complement({{kTables, kBlob}}).empty());
CHECK(complement({{kTables - kPage, kBlob + 2 * kPage}}).empty());
}
TEST(unsorted_and_overlapping_keep_ranges_are_merged) {
/* 250..310 KiB and 300..400 KiB merge to one 150 KiB keep; both are page-aligned at the ends
* after rounding, and the duplicate is the same range a second rank would send. */
const Ranges freed = complement({
{kTables + 300 * 1024, 100 * 1024}, /* second */
{kTables + 250 * 1024, 60 * 1024}, /* overlaps and precedes it */
{kTables + 250 * 1024, 60 * 1024}, /* the same range again, one per rank */
});
CHECK_EQ(freed.size(), size_t(2));
CHECK_EQ(freed.at(0).first, kTables);
/* The gap ends at the page boundary below the keep's start: 250 KiB is 62.5 pages, so 62
* pages (253 952 bytes) are freed and the half page holding kept bytes stays. */
CHECK_EQ(freed.at(0).second, 253952);
CHECK_EQ(freed.at(1).first, kTables + 400 * 1024); /* merged end: 250 + 150 KiB */
CHECK_EQ(freed.at(1).second, kBlob - 400 * 1024 + 0);
/* Freed plus kept is the blob, less the 2 KiB page the rounding gave back to the keep. */
CHECK_EQ(covered(freed), kBlob - 150 * 1024 - 2048);
}
TEST(keep_ranges_outside_the_blob_are_clamped_not_trusted) {
CHECK_EQ(covered(complement({{0, kTables}})), kBlob); /* entirely in the tables */
CHECK_EQ(covered(complement({{kSize, 4096}})), kBlob); /* past the end */
CHECK_EQ(covered(complement({{-4096, 4096}})), kBlob); /* before the mapping */
CHECK_EQ(covered(complement({{0, 0}})), kBlob); /* empty */
/* Half in, half out: only the part inside the blob is kept. */
CHECK_EQ(covered(complement({{kSize - 8192, 16384}})), kBlob - 8192);
}
TEST(a_gap_never_takes_a_page_that_holds_kept_bytes) {
/* The kept range starts four bytes into a page; the drop before it must stop at that page's
* boundary, not one byte before the kept range, or the kept bytes share a dropped page. */
const Ranges freed = complement({{kTables + 100 * 1024 + 4, 4096}});
CHECK_EQ(freed.size(), size_t(2));
CHECK_EQ(freed.at(0).second % kPage, 0);
CHECK(freed.at(0).first + freed.at(0).second <= kTables + 100 * 1024 + 4);
CHECK_EQ(freed.at(1).first % kPage, 0);
CHECK(freed.at(1).first >= kTables + 100 * 1024 + 4 + 4096);
}
TEST(a_container_with_no_blob_has_nothing_to_drop_or_keep) {
const auto none = rad_keep_complement(8192, 8192, {{8192, 4096}});
CHECK(none.empty());
}
/* ---- which addresses are the blob -------------------------------------------------------- */
TEST(the_container_covers_its_own_bytes_and_nothing_else) {
const std::vector<uint8_t> container(4 * kPage);
const uint8_t* base = container.data();
const int64_t size = (int64_t)container.size();
int64_t off = -1, len = -1;
CHECK(rad_blob_range(base, size, base, 16, &off, &len));
CHECK_EQ(off, int64_t(0));
CHECK_EQ(len, int64_t(16));
CHECK(rad_blob_range(base, size, base + 2 * kPage + 7, 100, &off, &len));
CHECK_EQ(off, 2 * kPage + 7);
CHECK_EQ(len, int64_t(100));
/* Up to and including the last byte. */
CHECK(rad_blob_range(base, size, base + size - 1, 1, &off, &len));
CHECK_EQ(off, size - 1);
/* One byte past the end, or a range that overruns it. */
CHECK(!rad_blob_range(base, size, base + size, 1, &off, &len));
CHECK(!rad_blob_range(base, size, base + size - 1, 2, &off, &len));
/* A copy in RAM (the --ngram-placement ram case) is not the blob. */
const std::vector<uint8_t> copy(4 * kPage);
CHECK(!rad_blob_range(base, size, copy.data(), 16, &off, &len));
/* Degenerate input refuses rather than computing a range from nothing. */
CHECK(!rad_blob_range(nullptr, size, base, 16, &off, &len));
CHECK(!rad_blob_range(base, 0, base, 16, &off, &len));
CHECK(!rad_blob_range(base, size, nullptr, 16, &off, &len));
CHECK(!rad_blob_range(base, size, base, 0, &off, &len));
CHECK(!rad_blob_range(base, size, base, -8, &off, &len));
}
TEST(the_recorded_range_is_what_the_drop_is_asked_to_keep) {
/* End to end on the two helpers alone: map a "table" inside a container, keep it, and check
* that the freed ranges are its complement. */
const std::vector<uint8_t> container(kSize);
const uint8_t* base = container.data();
const void* table = base + kTables + 4096;
const int64_t n = 64 * 1024;
int64_t off = 0, len = 0;
CHECK(rad_blob_range(base, kSize, table, n, &off, &len));
const Ranges freed = rad_keep_complement(kTables, kSize, {{off, len}});
CHECK_EQ(covered(freed), kBlob - n);
for (const auto& r : freed) {
CHECK(!(r.first < off + len && off < r.first + r.second)); /* no overlap with the keep */
}
}
RAD_TEST_MAIN()
+230
View File
@@ -247,4 +247,234 @@ TEST(the_sage_dflash2_recipes_decide_the_trunk_and_the_drafter) {
}
}
/* The Muse Glimmer recipes as they ship. The bf16 one is documentation only -- no rule, so every
* weight keeps the checkpoint's form. The w4a8 one routes every trunk linear to int4 on the
# 128-column grid (the value projection to int8), and nothing else: the layer norms, the
* embedding and the head match no rule. The patterns are the plugin's declared names:
* separate q and gate projections (this family's q_proj/gate_proj are two tensors), the gate|up
* concat, and the sliding/full two-group trunk. */
TEST(the_museglimmer_recipes_decide_the_model_they_were_written_for) {
const std::string dir = std::string(__FILE__).substr(
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
{
std::ifstream in(dir + "/museglimmer-30b-bf16.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-bf16.recipe", &why), RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)0);
CHECK(r.match("blk.3.attn_q.weight") == nullptr);
}
{
std::ifstream in(dir + "/museglimmer-30b-w4a8.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-w4a8.recipe", &why), RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)7);
const char* i4[] = { "blk.0.attn_q.weight", "blk.51.attn_k.weight", "blk.7.attn_gate.weight",
"blk.3.attn_output.weight", "blk.3.ffn_gate_up.weight",
"blk.3.ffn_down.weight" };
for (const char* n : i4) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK_EQ(m->quantizer, std::string("rtn"));
CHECK(has_opt(m, "codes", "i4"));
CHECK(has_opt(m, "group", "128"));
CHECK(has_opt(m, "scale", "f16"));
CHECK(has_opt(m, "rule", "search"));
}
const RecipeRule* v = r.match("blk.3.attn_v.weight");
REQUIRE(v != nullptr);
CHECK(has_opt(v, "codes", "i8"));
const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight",
"blk.3.ffn_norm.weight", "blk.3.ffn_post.weight",
"token_embd.weight", "output_norm.weight", "output.weight",
"model.vision_tower.layers.3.attn.q_proj.weight" };
for (const char* n : kept)
CHECK(r.match(n) == nullptr);
}
}
/* museglimmer-30b-iq8r as it ships: all seven trunk linears of every layer IQ8R, the head plain
* int8 (no rotation), and nothing else: the norms, the embedding, the vision tower and a merged
* drafter's `dspark.*` matrices match no rule. */
TEST(the_museglimmer_iq8r_recipe_decides_the_model_it_was_written_for) {
const std::string dir = std::string(__FILE__).substr(
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
std::ifstream in(dir + "/museglimmer-30b-iq8r.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "museglimmer-30b-iq8r.recipe", &why), RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)8);
const char* iq8r[] = { "blk.0.attn_q.weight", "blk.7.attn_gate.weight", "blk.51.attn_k.weight",
"blk.3.attn_v.weight", "blk.3.attn_output.weight",
"blk.0.ffn_gate_up.weight", "blk.51.ffn_down.weight" };
for (const char* n : iq8r) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK_EQ(m->quantizer, std::string("rtn"));
CHECK(has_opt(m, "codes", "i8"));
CHECK(has_opt(m, "group", "256"));
CHECK(has_opt(m, "scale", "u8"));
CHECK(has_opt(m, "scale2", "bf16"));
CHECK(has_opt(m, "block2", "1x*"));
CHECK(has_opt(m, "transform", "fwht128"));
CHECK(has_opt(m, "clamp", "sym"));
CHECK(has_opt(m, "rule", "search"));
}
const RecipeRule* head = r.match("output.weight");
REQUIRE(head != nullptr);
CHECK(has_opt(head, "codes", "i8"));
CHECK(has_opt(head, "group", "128"));
CHECK(has_opt(head, "scale", "bf16"));
CHECK(!has_opt(head, "transform", "fwht128"));
const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight",
"blk.3.ffn_norm.weight", "blk.3.ffn_post.weight", "token_embd.weight",
"output_norm.weight", "v.blk.0.attn.q_proj.weight", "v.proj.weight",
"dspark.fc.weight", "dspark.blk.0.attn_q.weight",
"dspark.blk.4.ffn_down.weight",
"model.vision_tower.layers.3.attn.q_proj.weight" };
for (const char* n : kept)
CHECK(r.match(n) == nullptr);
}
/* The Flint recipes as they ship, over arch/flint's declared names. flint-iq8r: every trunk linear
* (attention, the two dense layers, the shared expert's gate/up) IQ8R, the routed experts and the
* shared expert's down projection rotated int8 at a bf16 scale a (row, 128 of K), the head plain
* int8. flint-bf16-q4: u4 attention, signed int4 experts, plain int8 dense, shared and head. In
* both the norms, the sinks, the router and its zero correction, and the embedding match no rule. */
TEST(the_flint_recipes_decide_the_model_they_were_written_for) {
const std::string dir = std::string(__FILE__).substr(
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
const char* kept[] = { "blk.0.attn_norm.weight", "blk.0.attn_q_norm.weight",
"blk.7.attn_k_norm.weight", "blk.0.attn_sinks", "blk.3.ffn_norm.weight",
"blk.3.glm_router.weight", "blk.3.glm_router.correction",
"token_embd.weight", "output_norm.weight" };
{
std::ifstream in(dir + "/flint-iq8r.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "flint-iq8r.recipe", &why), RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)13);
const char* iq8r[] = { "blk.0.attn_q.weight", "blk.48.attn_k.weight", "blk.3.attn_v.weight",
"blk.5.attn_output.weight", "blk.0.ffn_gate_up.weight",
"blk.1.ffn_down.weight", "blk.2.ffn_gate_up_shexp.weight" };
for (const char* n : iq8r) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK_EQ(m->quantizer, std::string("rtn"));
CHECK(has_opt(m, "codes", "i8"));
CHECK(has_opt(m, "group", "256"));
CHECK(has_opt(m, "scale", "u8"));
CHECK(has_opt(m, "scale2", "bf16"));
CHECK(has_opt(m, "transform", "fwht128"));
}
const char* i8h[] = { "blk.2.ffn_gate_up_exps.0.weight", "blk.48.ffn_down_exps.255.weight",
"blk.17.ffn_down_shexp.weight" };
for (const char* n : i8h) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK(has_opt(m, "codes", "i8"));
CHECK(has_opt(m, "group", "128"));
CHECK(has_opt(m, "scale", "bf16"));
CHECK(has_opt(m, "transform", "fwht128"));
}
const RecipeRule* head = r.match("output.weight");
REQUIRE(head != nullptr);
CHECK(has_opt(head, "codes", "i8"));
CHECK(!has_opt(head, "transform", "fwht128"));
for (const char* n : kept) CHECK(r.match(n) == nullptr);
}
{
std::ifstream in(dir + "/flint-bf16-q4.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "flint-bf16-q4.recipe", &why), RAD_OK);
const RecipeRule* a = r.match("blk.9.attn_output.weight");
REQUIRE(a != nullptr);
CHECK(has_opt(a, "codes", "u4"));
CHECK(has_opt(a, "zero", "u8"));
const RecipeRule* e = r.match("blk.30.ffn_down_exps.7.weight");
REQUIRE(e != nullptr);
CHECK(has_opt(e, "codes", "i4"));
for (const char* n : { "blk.1.ffn_gate_up.weight", "blk.40.ffn_down_shexp.weight",
"output.weight" }) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK(has_opt(m, "codes", "i8"));
}
for (const char* n : kept) CHECK(r.match(n) == nullptr);
}
}
/* The Ling-3.0-tiny IQ8R recipe as it ships, over arch/bailing_hybrid's declared names: the KDA
* projections (fused q|k|v, forget, output gate, out), the MLA out projection, the dense layer's
* pair and the shared expert's gate/up IQ8R; the routed experts and the shared expert's down
* projection rotated int8 at a bf16 scale a (row, 128 of K). The KDA beta, the MLA's low-rank q
* and kv projections, its query parts and its head gate, the convolution taps, the router, the
* embedding and the head match no rule and keep the checkpoint's bf16; the norms, the KDA
* parameters and the router are cast to the f32 the plugin declares. */
TEST(the_ling_tiny_iq8r_recipe_decides_the_model_it_was_written_for) {
const std::string dir = std::string(__FILE__).substr(
0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes";
std::ifstream in(dir + "/ling-3.0-tiny-iq8r.recipe");
REQUIRE(in.good());
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
Recipe r;
std::string why;
REQUIRE_EQ(r.add_text(text, "ling-3.0-tiny-iq8r.recipe", &why), RAD_OK);
CHECK_EQ(r.rules().size(), (size_t)20);
const char* iq8r[] = { "blk.0.attn_qkv.weight", "blk.22.attn_forget.weight",
"blk.1.attn_gate.weight", "blk.2.attn_output.weight",
"blk.3.attn_output.weight", "blk.0.ffn_gate_up.weight",
"blk.0.ffn_down.weight", "blk.1.ffn_gate_up_shexp.weight",
"blk.23.ffn_gate_up_shexp.weight" };
for (const char* n : iq8r) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK_EQ(m->quantizer, std::string("rtn"));
CHECK(has_opt(m, "codes", "i8"));
CHECK(has_opt(m, "group", "256"));
CHECK(has_opt(m, "scale", "u8"));
CHECK(has_opt(m, "scale2", "bf16"));
CHECK(has_opt(m, "transform", "fwht128"));
}
const char* i8h[] = { "blk.1.ffn_gate_up_exps.0.weight", "blk.23.ffn_down_exps.127.weight",
"blk.7.ffn_down_shexp.weight" };
for (const char* n : i8h) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK(has_opt(m, "codes", "i8"));
CHECK(has_opt(m, "group", "128"));
CHECK(has_opt(m, "scale", "bf16"));
CHECK(has_opt(m, "transform", "fwht128"));
}
const char* f32[] = { "blk.0.attn_norm.weight", "blk.3.attn_q_a_norm.weight",
"blk.3.attn_kv_a_norm.weight", "blk.1.ffn_norm.weight",
"blk.0.ssm_norm.weight", "blk.0.ssm_a", "blk.0.ssm_dt_bias",
"blk.1.glm_router.weight", "blk.1.glm_router.correction",
"output_norm.weight" };
for (const char* n : f32) {
const RecipeRule* m = r.match(n);
REQUIRE(m != nullptr);
CHECK_EQ(m->quantizer, std::string("cast"));
CHECK(has_opt(m, "dtype", "f32"));
}
const char* kept[] = { "blk.0.attn_beta.weight", "blk.3.attn_q_a.weight",
"blk.3.attn_q_rope.weight", "blk.3.attn_q_nope.weight",
"blk.3.attn_kv_a.weight", "blk.3.attn_kv_b.weight",
"blk.3.attn_head_gate.weight", "blk.0.ssm_conv.weight",
"token_embd.weight", "output.weight" };
for (const char* n : kept) CHECK(r.match(n) == nullptr);
}
RAD_TEST_MAIN()
+239 -3
View File
@@ -1052,6 +1052,42 @@ TEST(group_router_selects_only_inside_the_best_groups) {
CHECK_EQ(run("router_sigmoid_group_topk", bad), RAD_E_SHAPE);
}
TEST(group_router_at_the_tiny_geometry_keeps_four_of_eight_sixteen_expert_groups) {
T lg(RAD_F32, { 1, 128 }), bias(RAD_F32, { 128 }), ids(RAD_I32, { 1, 8 }), w(RAD_F32, { 1, 8 });
// One planted expert a group (16 a group): p 0.90, 0.30, 0.85, 0.10, 0.80, 0.05, 0.75, 0.70,
// and a floor of 0.001 everywhere else. The planted sums lead, so topk_group 4 keeps groups
// 0, 2, 4 and 6: the four largest planted experts are in, groups 1, 3, 5 and 7 bring nothing.
const float planted[8] = { 0.90f, 0.30f, 0.85f, 0.10f, 0.80f, 0.05f, 0.75f, 0.70f };
std::vector<float> p(128, 0.001f), lgv;
for (int g = 0; g < 8; ++g) p[g * 16 + 2] = planted[g];
for (size_t i = 0; i < p.size(); ++i) lgv.push_back(std::log(p[i] / (1 - p[i])));
lg.f(lgv);
bias.f(std::vector<float>(128, 0.0f));
A a;
a.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 128).i("top_k", 8).i("n_group", 8)
.i("topk_group", 4).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32");
auto has = [&](int e) {
for (int i = 0; i < 8; ++i)
if (ids.iat(i) == e) return true;
return false;
};
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
CHECK_EQ(ids.iat(0), 2); // the kept groups' planted experts, in score order:
CHECK_EQ(ids.iat(1), 34); // 0.90, 0.85, 0.80, 0.75
CHECK_EQ(ids.iat(2), 66);
CHECK_EQ(ids.iat(3), 98);
for (int g : { 1, 3, 5, 7 }) CHECK(!has(g * 16 + 2)); // the dropped groups stay out
CHECK_NEAR(w.at(0), 2.5f * 0.90f / (0.90f + 0.85f + 0.80f + 0.75f + 0.004f), 1e-5);
// A correction bias ranks group 3's sum past group 6's and seats its expert; the weights
// stay the unbias'd sigmoid.
std::vector<float> bs(128, 0.0f);
bs[3 * 16 + 2] = 0.9f;
bias.f(bs);
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
CHECK(has(50));
CHECK(!has(98));
}
TEST(paged_latent_attention_is_causal_adds_the_rotary_part_and_gates_per_head) {
// One sequence of three tokens, the last two queried (positions 1 and 2). Token 0 and 1 sit
// in page 1, token 2 in page 0; a row is the latent (2) then the rotary part (2).
@@ -1253,7 +1289,7 @@ TEST(op_vocabulary) {
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
"lora_shrink", "lora_expand", "lora_expand_mm",
"grid_embed_aa", "grid_embed_cpe",
"grid_embed_aa", "grid_embed_cpe", "grid_embed_pad", "window_order",
"attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table",
"attn_paged_sink",
"qk_norm_rope", "qsa_block_key",
@@ -1289,7 +1325,7 @@ TEST(op_vocabulary) {
"chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store",
/* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws,
* and its codec encoder's residual quantiser step. */
"ras_pick", "vq_encode",
"ras_pick", "vq_encode", "vq_euclidean", "elu",
/* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its
* decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free
* activation. */
@@ -4502,6 +4538,160 @@ TEST(op_grid_embed) {
CHECK_NEAR(x.at(4), want, 1e-4);
}
/* grid_embed_pad: the half-pixel resample with grid_sample's zeros padding. A side-4 table onto
* rows of an 8 x 8 grid: src(i) = i / 2 - 0.25, so row 0 keeps only the in-range tap 0 (weight
* 3/4, the tap -1 masked), row 7 only tap 3 at 3/4 (tap 4 masked), and interior rows blend two.
* Table row h * 4 + w holds (4h + w + 1) and (4h + w + 1) / 2 in its two channels. */
TEST(op_grid_embed_pad_zeroes_taps_beyond_the_table) {
const int64_t side = 4, n = 2;
std::vector<float> tab((size_t)(side * side * n));
for (int64_t r = 0; r < side * side; ++r)
for (int64_t i = 0; i < n; ++i) tab[(size_t)(r * n + i)] = (float)(r + 1) * (i ? 0.5f : 1.0f);
T table(RAD_F32, { side * side, n }); table.f(tab);
/* Rows (0,0), (7,7), (1,3), (4,2), (7,0), (3,7) of the 8 x 8 grid. */
T x(RAD_F32, { 6, n }); x.f({ 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100 });
T crd(RAD_I32, { 4, 6 });
crd.n({ 0, 7, 1, 4, 7, 3, 0, 7, 3, 2, 0, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 });
A a; a.t(x).t(table).t(crd).i("M", 6).i("n", n).i("side", side).s("dtype", "f32");
CHECK_OK(run("grid_embed_pad", a));
/* Hand-computed: joint weight = the product of the axes' in-range hat weights (the off-table
* tap contributes nothing), v(h,w) = 4h + w + 1; channel 1 holds v / 2, x starts at 100. */
/* (0,0): both axes tap 0 only, at 3/4 each -> 9/16 * 1 = 0.5625. */
/* (7,7): both axes tap 3 only at 3/4 -> 9/16 * 16 = 9. */
/* (1,3): rows 0,1 at 3/4, 1/4; cols 1,2 at 3/4, 1/4 -> 3.25.
(4,2): rows 1,2 at 1/4, 3/4; cols 0,1 at 1/4, 3/4 -> 8.75. */
/* (7,0): row tap 3 at 3/4 (tap 4 masked), col tap 0 at 3/4 (tap -1 masked) -> 9/16 * 13 = 7.3125. */
/* (3,7): rows 1,2; col tap 3 at 3/4 (tap 4 masked) -> 9/16 * 8 + 3/16 * 12 = 6.75. */
const float want[6] = { 0.5625f, 9.0f, 3.25f, 8.75f, 7.3125f, 6.75f };
for (int64_t m = 0; m < 6; ++m) {
CHECK_NEAR(x.at(m * n), 100.0f + want[m], 1e-5);
CHECK_NEAR(x.at(m * n + 1), 100.0f + want[m] * 0.5f, 1e-5);
}
}
/* A grid no larger than the table never masks a tap, and at scale 1 the half-pixel form reads
* each row whole: a 4 x 4 grid on the side-4 table is the table itself. */
TEST(op_grid_embed_pad_in_range_reads_the_table) {
const int64_t side = 4, n = 1;
std::vector<float> tab((size_t)(side * side));
for (int64_t r = 0; r < side * side; ++r) tab[(size_t)r] = (float)(r + 1);
T table(RAD_F32, { side * side, n }); table.f(tab);
T x(RAD_F32, { 2, n }); x.f({ 0, 0 });
T crd(RAD_I32, { 4, 2 }); crd.n({ 2, 3, 1, 2, 4, 4, 4, 4 });
A a; a.t(x).t(table).t(crd).i("M", 2).i("n", n).i("side", side).s("dtype", "f32");
CHECK_OK(run("grid_embed_pad", a));
CHECK_NEAR(x.at(0), 10.0f, 1e-6); /* table row 2 * 4 + 1 = 10 */
CHECK_NEAR(x.at(1), 15.0f, 1e-6); /* table row 3 * 4 + 2 = 15 */
}
/* window_order: the permutation, its inverse, the rope positions and every cuw boundary, checked
* against an in-test reference that sorts the patches by (segment, window row, window column,
* raster) -- no arithmetic shared with the slot formula. The grids are laid out segment by
* segment, each a raster gh x gw block. */
namespace {
struct WinCase {
std::vector<std::pair<int64_t, int64_t>> grids; /* (height, width) per segment */
int64_t window;
};
/* Builds the case, runs the op, checks the outputs against the sort reference and the hand-derived
* cuw boundaries. Returns the number of disagreements. */
int64_t run_window_case(const char* name, const WinCase& c, const std::vector<int64_t>& cuw_want,
std::vector<int64_t>* idx_out = nullptr) {
int64_t P = 0;
std::vector<int64_t> cu{ 0 };
for (const auto& g : c.grids) { P += g.first * g.second; cu.push_back((int64_t)P); }
std::vector<int64_t> crd(4 * (size_t)P, 0);
struct Ord { int64_t seg, wr, wc, r, cc, p; };
std::vector<Ord> ord;
for (size_t s = 0; s < c.grids.size(); ++s) {
const int64_t base = s ? cu[s] : 0;
for (int64_t r = 0; r < c.grids[s].first; ++r)
for (int64_t q = 0; q < c.grids[s].second; ++q) {
const int64_t p = base + r * c.grids[s].second + q;
crd[(size_t)p] = (int32_t)r;
crd[(size_t)P + (size_t)p] = (int32_t)q;
crd[2 * (size_t)P + (size_t)p] = (int32_t)c.grids[s].first;
crd[3 * (size_t)P + (size_t)p] = (int32_t)c.grids[s].second;
ord.push_back({ (int64_t)s, c.window > 0 ? r / c.window : 0,
c.window > 0 ? q / c.window : 0, r, q, p });
}
}
std::stable_sort(ord.begin(), ord.end(), [](const Ord& l, const Ord& r) {
if (l.seg != r.seg) return l.seg < r.seg;
if (l.wr != r.wr) return l.wr < r.wr;
if (l.wc != r.wc) return l.wc < r.wc;
if (l.r != r.r) return l.r < r.r;
return l.cc < r.cc;
});
T crd_t(RAD_I32, { 4, P }); crd_t.n(crd);
T cu_t(RAD_I32, { 1, (int64_t)cu.size() }); cu_t.n(cu);
T idx(RAD_I32, { 1, P }); T inv(RAD_I32, { 1, P });
T pos(RAD_I32, { 2, P }); T cuw(RAD_I32, { 1, P + 1 });
A a; a.t(crd_t).t(cu_t).t(idx).t(inv).t(pos).t(cuw).i("M", P).i("window", c.window);
CHECK_OK(run("window_order", a));
int64_t bad = 0;
for (int64_t slot = 0; slot < P; ++slot) {
const int64_t src = idx.iat(slot), want = ord[(size_t)slot].p;
if (src != want) { ++bad; fprintf(stderr, " %s: idx[%lld] %lld want %lld\n", name,
(long long)slot, (long long)src, (long long)want); }
if (inv.iat(want) != slot) ++bad;
if (idx.iat(inv.iat(slot)) != slot) ++bad; /* idx and inv are inverses */
/* pos: (col + 1, row + 1) of the slot's source patch, read off the reference's order. */
if (pos.iat(slot) != ord[(size_t)slot].cc + 1) ++bad;
if (pos.iat(P + slot) != ord[(size_t)slot].r + 1) ++bad;
}
for (size_t i = 0; i < cuw_want.size(); ++i)
if (cuw.iat((int64_t)i) != cuw_want[i]) {
++bad;
fprintf(stderr, " %s: cuw[%zu] %lld want %lld\n", name, i,
(long long)cuw.iat((int64_t)i), (long long)cuw_want[i]);
}
if (idx_out) for (int64_t i = 0; i < P; ++i) idx_out->push_back(idx.iat(i));
return bad;
}
} /* namespace */
/* One 48 x 40 segment, window 32: windows 32 x 32, 32 x 8, 16 x 32, 16 x 8 -- ragged right and
* bottom. The first patch of the second window is row 0, column 32, patch 256. */
TEST(op_window_order_ragged_segment) {
std::vector<int64_t> gather;
const int64_t bad = run_window_case(
"48x40 w32", { { { 48, 40 } }, 32 }, { 0, 1024, 1280, 1792, 1920, 1920, 1920 }, &gather);
CHECK_EQ(bad, 0LL);
CHECK_EQ(gather[0], 0LL);
CHECK_EQ(gather[1024], 32LL); /* window (0,1) starts at row 0, column 32: patch 32 */
CHECK_EQ(gather[1920 - 1], 48 * 40 - 1LL);
}
/* Video-style: two segments back to back, windows never across the segment boundary. */
TEST(op_window_order_two_segments) {
const int64_t bad = run_window_case(
"two segments w16", { { { 32, 32 }, { 16, 16 } }, 16 },
{ 0, 256, 512, 768, 1024, 1280, 1280, 1280, 1280 });
CHECK_EQ(bad, 0LL);
}
/* Window-divisible: every window exactly window x window. */
TEST(op_window_order_divisible) {
const int64_t bad = run_window_case(
"16x24 w8", { { { 16, 24 } }, 8 }, { 0, 64, 128, 192, 256, 320, 384, 384 });
CHECK_EQ(bad, 0LL);
}
/* window 0: the identity, cuw = cu, the rope positions still swapped and offset by one. */
TEST(op_window_order_window_zero_is_the_identity) {
const int64_t P = 9 * 7 + 5 * 5;
std::vector<int64_t> gather;
const int64_t bad = run_window_case("identity w0", { { { 9, 7 }, { 5, 5 } }, 0 },
{ 0, 63, 88, 88 }, &gather);
CHECK_EQ(bad, 0LL);
for (int64_t i = 0; i < P; ++i) CHECK_EQ(gather[(size_t)i], i);
}
TEST(op_qk_norm_rope) {
/* At position 0 the rotation is the identity, so this isolates the per-head RMS norm. */
T qkv(RAD_F32, {1, 6}); qkv.f({3, 4, 3, 4, 7, 7});
@@ -8505,6 +8695,45 @@ TEST(vq_encode_takes_the_nearest_code_by_cosine_and_leaves_the_residual) {
CHECK_EQ(run("vq_encode", b), RAD_E_SHAPE);
}
TEST(breeze_euclidean_quantisation_preserves_distance_and_tie_order) {
T x(RAD_F32, {3, 2}); x.f({4, 0, 2, 0, 0, 3});
T cb(RAD_F32, {3, 2}); cb.f({1, 0, 3, 0, 0, 2});
T codes(RAD_I32, {3});
A a; a.t(x).t(cb).t(codes).i("M", 3).i("n", 2).i("bins", 3).s("dtype", "f32");
CHECK_OK(run("vq_euclidean", a));
/* Cosine would choose 0 for [4, 0]; Euclidean must choose the longer centroid 1.
* [2, 0] is exactly equidistant from 0 and 1 and chooses the lower index. */
CHECK_EQ(codes.iat(0), 1); CHECK_EQ(codes.iat(1), 0); CHECK_EQ(codes.iat(2), 2);
CHECK_EQ(x.at(0), 1.0f); CHECK_EQ(x.at(1), 0.0f);
CHECK_EQ(x.at(2), 1.0f); CHECK_EQ(x.at(3), 0.0f);
CHECK_EQ(x.at(4), 0.0f); CHECK_EQ(x.at(5), 1.0f);
CHECK_OK(run("vq_euclidean", a)); /* next residual step, not the original vector */
CHECK_EQ(codes.iat(0), 0); CHECK_EQ(codes.iat(1), 0); CHECK_EQ(codes.iat(2), 2);
A bad; bad.t(x).t(cb).t(codes).i("M", 3).i("n", 2).i("bins", 4).s("dtype", "f32");
CHECK_EQ(run("vq_euclidean", bad), RAD_E_SHAPE);
}
TEST(breeze_elu_has_unit_alpha_and_works_in_place) {
T x(RAD_F32, {4, 1}); x.f({-1, 0, 2, -100});
A a; a.t(x).t(x).i("M", 4).i("n", 1).s("dtype", "f32");
CHECK_OK(run("elu", a));
CHECK(std::abs(x.at(0) - (-0.6321205588f)) < 1e-7f);
CHECK_EQ(x.at(1), 0.0f); CHECK_EQ(x.at(2), 2.0f); CHECK_EQ(x.at(3), -1.0f);
}
TEST(breeze_downsample_replication_is_a_prefix_and_crop) {
/* Original [1, 2, 3, 4], replicate left pad of 2 -> [1, 1, 1, 2, 3, 4].
* An ordinary causal conv on the prefixed input gives one extra leading row. */
T x(RAD_F32, {6, 1}); x.f({1, 1, 1, 2, 3, 4});
T w(RAD_F32, {1, 1, 4}); w.f({1, 10, 100, 1000});
T cu(RAD_I32, {2}); cu.n({0, 6});
T y(RAD_F32, {3, 1});
A a; a.t(x).t(w).t(cu).tnull().t(y).i("M", 6).i("cin", 1).i("cout", 1).i("k", 4)
.i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32");
CHECK_OK(run("conv1d", a));
CHECK_EQ(y.at(1), 2111.0f); CHECK_EQ(y.at(2), 4321.0f);
}
/* snake_aa's paddings, with the activation the identity (alpha 0: sin(0 u) = 0). Ratio 2, filters
* of 4: P = 1. Sequence [10, 20, 40] pads to [10, 10, 20, 40, 40]; the transposed f_up [1, 2, 3, 4]
* gives [10, 20, 40, 60, 50, 80, 100, 160, 160, 240, 120, 160], doubled and cropped by 3 a side:
@@ -10065,6 +10294,8 @@ std::vector<Geo> geometries() {
G("hc_project", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("scale", 1.0).s("dtype", "f32")),
G("mtp_enter", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")),
G("grid_embed", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("grid_embed_pad", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("window_order", "M", 12, a.i("M", R).i("window", 4)),
G("grid_embed_aa", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("grid_embed_cpe", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")),
G("lili_cand", "M", 3, a.i("M", R).i("k", 4).i("world", 1).i("steps", 3).i("n", 8)
@@ -10346,6 +10577,8 @@ std::vector<Geo> geometries() {
G("ras_pick", "M", 2, a.i("M", R).i("win", 4).i("lo", 1).i("hi", 9).i("rep", 1)),
G("vq_encode", "M", 3, a.i("M", R).i("n", 16).i("dim", 4).i("bins", 24)
.s("dtype", "f32")),
G("vq_euclidean", "M", 3, a.i("M", R).i("n", 16).i("bins", 24).s("dtype", "f32")),
G("elu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("resample_nearest", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("fourier_embed", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("win_input", "M", 8, a.i("M", R).i("n_lat", 4).i("n_zero", 2).i("n_cond", 3)
@@ -10444,7 +10677,10 @@ bool undrawable(const char* op) {
return !std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") ||
!std::strcmp(op, "pixtral_merge") ||
/* sample_logprobs rows (sorted pairs, positive sums): avx_check_hand.cpp builds them */
!std::strcmp(op, "lili_cand");
!std::strcmp(op, "lili_cand") ||
/* Whole raster grids with segment boundaries: the window_order cases here and in
* avx_check_hand.cpp build them. */
!std::strcmp(op, "window_order");
}
uint32_t lcg(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; }
+371 -1
View File
@@ -17,7 +17,6 @@
#include <cstring>
#include <new>
#include <string>
#include <unistd.h>
using namespace rad;
@@ -296,6 +295,29 @@ TEST(the_device_fakes_are_the_ones_linked) {
rad_dev_free(p, RAD_MEM_DEVICE);
}
/* THE STEP RECORD EXISTS ONLY FOR --diagnose. Sizing the ring at every init put 2.5 MiB and a
* record a step on the serving path for a report nobody asked for. Off: no ring, no record. On:
* the ring and one record each of the three steps. */
TEST(the_step_record_exists_only_with_diagnose) {
for (const bool on : { false, true }) {
Fixture f;
f.build();
if (on) f.cfg.diagnose = "/tmp/radiance-diagnose-not-written"; /* Scheduler only reads it */
CHECK_OK(f.start());
CHECK_EQ(f.sch.step_record_capacity(), on ? (size_t)(1u << 16) : (size_t)0);
f.submit(64, 8);
for (int i = 0; i < 3; ++i) {
CHECK(f.sch.step() != nullptr);
f.commit_plain();
f.sch.step_finished();
}
CHECK_EQ(f.sch.step_record_count(), on ? (uint64_t)3 : (uint64_t)0);
std::vector<rad::diag::StepRecord> out;
CHECK_EQ(f.sch.step_records(0, &out), (uint64_t)0);
CHECK_EQ(out.size(), on ? (size_t)3 : (size_t)0);
}
}
/* ================================================================== geometry + chunking */
TEST(chunk_geometry_is_computed_not_configured) {
Fixture f;
@@ -3250,6 +3272,354 @@ TEST(an_explicit_busy_prefill_chunk_holds_the_chunk_to_it) {
if (e.seq == a) CHECK_EQ(e.n_tokens, 128);
}
TEST(the_mixed_step_target_controller_corrects_misses_and_grows_cautiously) {
MixedStepTarget d;
d.seed(300, 64, 2048);
CHECK_EQ(d.cap(), 256);
d.reset();
/* 1024 rows taking four times the 100 ms target predicts a 256-row cap. */
d.observe(1024, 400000000, 100000000, 64, 2048);
CHECK_EQ(d.cap(), 256);
CHECK_EQ(d.limit(2048, 64), 256);
/* A step in the dead band does not chase noise. */
d.observe(256, 80000000, 100000000, 64, 2048);
CHECK_EQ(d.cap(), 256);
/* Three comfortably fast full-cap steps grow toward the measured 512 rows, one quarter at a
* time and on the model's quantum. */
for (int i = 0; i < 3; ++i) d.observe(256, 50000000, 100000000, 64, 2048);
CHECK_EQ(d.cap(), 320);
/* A short tail cannot make the deployment's cap grow. */
d.observe(64, 10000000, 100000000, 64, 2048, /*representative=*/false);
CHECK_EQ(d.cap(), 320);
/* A later miss corrects immediately. */
d.observe(320, 200000000, 100000000, 64, 2048);
CHECK_EQ(d.cap(), 128);
}
TEST(the_mixed_step_target_recovers_from_fixed_cost_backoff_and_ignores_short_tails) {
MixedStepTarget d;
d.seed(64, 64, 2048);
/* Fixed decode cost makes proportional scaling round back to 64, but sustained 80%-of-target
* steps still earn a one-quantum probe. */
for (int i = 0; i < 3; ++i) d.observe(64, 160000000, 200000000, 64, 2048);
CHECK_EQ(d.cap(), 128);
/* A short tail can miss because of fixed cost; it did not exercise the cap and cannot lower
* the next full chunk. */
d.observe(32, 260000000, 200000000, 64, 2048, /*representative=*/false);
CHECK_EQ(d.cap(), 128);
/* The same short row count is representative when a fixed policy or checkpoint boundary,
* rather than the end of a prompt, limited it. Repeated slow work must be able to lower the
* controller below that other limit. */
d.seed(2048, 64, 8192);
d.observe(512, 400000000, 200000000, 64, 8192, /*representative=*/true);
CHECK_EQ(d.cap(), 256);
/* An impossible target bottoms out at one legal quantum without underflow. */
d.observe(128, 1000000000, 1000000, 64, 2048);
CHECK_EQ(d.cap(), 64);
d.observe(64, 1000000000, 1000000, 64, 2048);
CHECK_EQ(d.cap(), 64);
}
TEST(a_mixed_step_target_does_not_throttle_an_uncontended_prefill) {
Fixture f;
share_fixture(f, /*busy off=*/0);
f.cfg.mixed_step_target_ms = 200;
CHECK_OK(f.start());
f.submit(3500, 64);
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.plan().e.size(), 1);
CHECK_EQ(f.sch.plan().e[0].n_tokens, 512);
CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 0);
}
TEST(a_mixed_step_target_refuses_a_batch_that_cannot_mix_one_prefill_quantum) {
Fixture f;
share_fixture(f, /*busy off=*/0);
f.cfg.mixed_step_target_ms = 200;
f.cfg.max_seqs = 2;
f.cfg.max_tok = 64; /* quantum 64, no room for a decode row beside it */
CHECK_EQ(f.start(), RAD_E_INVAL);
}
TEST(a_mixed_step_target_validates_the_shared_budget_under_a_prefill_span) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/128, /*max_ctx=*/4096);
f.cfg.checkpoint_interval = 64;
f.cfg.prefill_span = 2;
f.cfg.max_seqs = 2;
f.cfg.mixed_step_target_ms = 200;
/* The lone-prefill budget is 128, but a mixed step uses shared_tok=64: too little for the
* 64-row quantum beside even one ordinary decode row. */
CHECK_EQ(f.start(), RAD_E_INVAL);
}
TEST(a_mixed_step_target_refuses_an_explicit_cap_below_the_prefill_quantum) {
Fixture f;
share_fixture(f, /*busy below the 64-row quantum=*/32);
f.cfg.mixed_step_target_ms = 200;
CHECK_EQ(f.start(), RAD_E_INVAL);
}
TEST(a_mixed_step_target_keeps_decode_rows_in_both_priority_orders_and_busy_modes) {
for (int64_t busy : { -1ll, 128ll }) {
for (int prefill_priority : { -1, 1 }) {
Fixture f;
share_fixture(f, busy);
f.cfg.mixed_step_target_ms = 200;
f.cfg.max_seqs = 2;
f.cfg.max_tok = 128;
f.cfg.checkpoint_interval = 128;
CHECK_OK(f.start());
const uint64_t d = f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
const uint64_t p = f.submit(3500, 64, prefill_priority);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
bool saw_d = false, saw_p = false;
for (const StepEntry& e : f.sch.plan().e) {
if (e.seq == d && !e.is_prefill) saw_d = true;
if (e.seq == p && e.is_prefill) saw_p = true;
}
CHECK(saw_d);
CHECK(saw_p);
}
}
}
/* The scheduler feeds completed mixed-step timing into the controller. A deterministic timing
* sample stands in for step_finished's live bracket. The following step must use the learned cap
* even when --busy-prefill-chunk is off. */
TEST(a_mixed_step_target_adapts_the_next_mixed_prefill_step) {
Fixture f;
share_fixture(f, /*busy off: the target controller stands on its own=*/0);
f.cfg.mixed_step_target_ms = 2;
CHECK_OK(f.start());
const uint64_t d = f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
const uint64_t p = f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
/* This fixture's 512-row mixed capacity seeds at one quarter, on its 64-row quantum. */
CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 128);
int64_t first = 0;
for (const StepEntry& e : f.sch.plan().e) if (e.seq == p) first = e.n_tokens;
CHECK(first > 0);
f.commit_plain(12);
f.sch.note_mixed_step_cost(12000000);
const int64_t learned = f.sch.metrics().mixed_step_target_prefill_cap;
CHECK(learned >= 64);
CHECK(learned < first);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
int64_t next = 0;
for (const StepEntry& e : f.sch.plan().e) if (e.seq == p) next = e.n_tokens;
CHECK(next > 0);
CHECK(next <= learned);
CHECK(f.sch.find(d) != nullptr);
}
/* The learned limit is a budget for the whole mixed step, not for each prefill independently.
* Otherwise a burst of N fresh requests can schedule N times the measured safe amount and miss
* the latency target precisely when the server is busiest. */
TEST(a_mixed_step_target_caps_aggregate_mixed_prefill_rows) {
Fixture f;
share_fixture(f, /*busy off: the target controller stands on its own=*/0);
f.cfg.mixed_step_target_ms = 200;
f.cfg.max_seqs = 3;
CHECK_OK(f.start());
const uint64_t d = f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
f.submit(3500, 64, /*priority=*/1);
f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
CHECK(f.sch.find(d) != nullptr);
int64_t prefill_rows = 0;
int prefills = 0;
for (const StepEntry& e : f.sch.plan().e) {
if (!e.is_prefill) continue;
prefill_rows += e.n_tokens;
++prefills;
}
/* The 128-row seed is shared as one 64-row quantum apiece. */
CHECK_EQ(prefills, 2);
CHECK(prefill_rows <= f.sch.metrics().mixed_step_target_prefill_cap);
CHECK_EQ(f.sch.metrics().queue_depth, 0);
}
TEST(a_mixed_step_target_gives_each_burst_prefill_one_quantum_when_the_target_cannot) {
Fixture f;
share_fixture(f, /*busy off=*/0);
f.cfg.mixed_step_target_ms = 200;
f.cfg.max_seqs = 4;
CHECK_OK(f.start());
f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
for (int i = 0; i < 3; ++i) f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
int prefills = 0;
int64_t rows = 0;
for (const StepEntry& e : f.sch.plan().e) {
if (!e.is_prefill) continue;
++prefills;
rows += e.n_tokens;
CHECK_EQ(e.n_tokens, 64);
}
CHECK_EQ(prefills, 3);
CHECK_EQ(rows, 192);
CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 128);
CHECK_EQ(f.sch.metrics().queue_depth, 0);
}
TEST(a_mixed_step_target_keeps_a_decoder_behind_a_bidirectional_text_prefill) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/128, /*max_ctx=*/4096);
f.cfg.checkpoint_interval = 64;
f.cfg.busy_prefill_chunk = 0;
f.cfg.mixed_step_target_ms = 200;
f.cfg.max_seqs = 2;
f.prog.encoder.bidirectional = 1;
CHECK_OK(f.start());
const uint64_t d = f.submit(40, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
const uint64_t p = f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
bool saw_decode = false, saw_prefill = false;
for (const StepEntry& e : f.sch.plan().e) {
if (e.seq == d && !e.is_prefill) saw_decode = true;
if (e.seq == p && e.is_prefill) saw_prefill = true;
}
CHECK(saw_decode);
CHECK(saw_prefill);
}
TEST(a_cancelled_mixed_prefill_still_teaches_from_the_work_that_ran) {
Fixture f;
share_fixture(f, /*busy off=*/0);
f.cfg.mixed_step_target_ms = 2;
CHECK_OK(f.start());
f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
const uint64_t p = f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
const int64_t before = f.sch.metrics().mixed_step_target_prefill_cap;
CHECK_OK(f.sch.cancel(p));
f.commit_plain(12);
f.sch.note_mixed_step_cost(12000000);
CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1);
CHECK_EQ(f.sch.metrics().mixed_step_target_misses, 1);
CHECK(f.sch.metrics().mixed_step_target_prefill_cap < before);
REQUIRE(f.sch.find(p) != nullptr);
CHECK_EQ((int)f.sch.find(p)->state, (int)ReqState::Cancelled);
if (f.sch.has_deferred()) f.sch.release_deferred();
CHECK(!f.kv.has_sequence(p));
CHECK_OK(f.sch.reap(p));
CHECK(f.sch.find(p) == nullptr);
}
TEST(a_mixed_step_target_preserves_speculative_verification_in_a_mixed_step) {
Fixture f;
share_fixture(f, /*busy off=*/0);
f.cfg.mixed_step_target_ms = 200;
f.cfg.n_spec = 4;
CHECK_OK(f.start());
const uint64_t d = f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
int32_t draft[4] = { 21, 22, 23, 24 };
CHECK_OK(f.sch.set_draft(d, draft, 4));
f.submit(3500, 64, /*priority=*/1);
const RadBatch* b = f.sch.step();
REQUIRE(b != nullptr);
CHECK_EQ(b->phase, RAD_PHASE_MIXED);
CHECK_EQ(b->n_spec, 4);
CHECK_EQ(b->n_seq_decode, 1);
CHECK_OK(f.commit(12, 0, [](const StepEntry& e) { return e.is_prefill ? 0 : 2; }));
f.sch.step_finished();
CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1);
const Request* rd = f.sch.find(d);
REQUIRE(rd != nullptr);
CHECK_EQ((int)rd->output.size(), 4);
CHECK_EQ(rd->output[1], 21);
CHECK_EQ(rd->output[2], 22);
CHECK_EQ(rd->output[3], 12);
CHECK_EQ(rd->n_computed, 103);
CHECK_EQ(rd->n_accepted, 2);
}
TEST(a_mixed_step_target_composes_with_auto_interleave_and_burst_prefills) {
Fixture f;
share_fixture(f, /*busy off: the target controller stands on its own=*/0);
f.cfg.mixed_step_target_ms = 2;
f.cfg.prefill_interleave = -1;
f.cfg.prefill_interleave_share = 1.0;
f.cfg.max_seqs = 3;
CHECK_OK(f.start());
/* One decode-only step after each mixed chunk, deterministically. */
f.sch.note_step_cost(true, 0.4);
f.sch.note_step_cost(false, 0.4);
const uint64_t d = f.submit(100, 512, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
const uint64_t p1 = f.submit(3500, 64, /*priority=*/1);
const uint64_t p2 = f.submit(3500, 64, /*priority=*/1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
int first_prefills = 0;
for (const StepEntry& e : f.sch.plan().e)
if (e.is_prefill && (e.seq == p1 || e.seq == p2)) ++first_prefills;
CHECK_EQ(first_prefills, 2);
f.commit_plain(12);
f.sch.note_mixed_step_cost(12000000);
CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1);
CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 64);
CHECK(f.sch.step() != nullptr); /* auto interleave: decoder alone */
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE);
CHECK_EQ((int)f.sch.plan().e.size(), 1);
CHECK_EQ(f.sch.plan().e[0].seq, d);
f.commit_plain(13);
f.sch.note_mixed_step_cost(12000000); /* a held step teaches nothing */
CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1);
CHECK_EQ(f.sch.metrics().steps_held, 1);
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED);
int next_prefills = 0;
for (const StepEntry& e : f.sch.plan().e) {
if (!e.is_prefill || (e.seq != p1 && e.seq != p2)) continue;
CHECK_EQ(e.n_tokens, 64);
++next_prefills;
}
CHECK_EQ(next_prefills, 2); /* neither burst prompt starves */
CHECK(f.sch.find(d) != nullptr);
}
/* ================================================================== decode-only steps between chunks */
/* --prefill-interleave. A sequence decodes while a 2000-token prompt prefills in 256-token chunks
* (the checkpoint interval). Each step's shape is 'C' when it carries a chunk of the prompt and
+18
View File
@@ -2615,6 +2615,24 @@ TEST(the_steps_a_prefill_interleave_held_are_counted) {
CHECK(it != d.samples.end() && it->second == 6.0);
}
TEST(the_mixed_step_target_controller_is_observable) {
Metrics m("m", 1024);
server::SchedMetrics s;
s.mixed_step_target_steps = 9;
s.mixed_step_target_misses = 2;
s.mixed_step_target_prefill_cap = 384;
m.sample(s);
PromDoc d = parse_prom(m.render());
CHECK_EQ((int)d.errors.size(), 0);
CHECK_EQ(d.type["radiance:mixed_step_target_steps_total"], std::string("counter"));
CHECK_EQ(d.type["radiance:mixed_step_target_misses_total"], std::string("counter"));
CHECK_EQ(d.type["radiance:mixed_step_target_prefill_cap"], std::string("gauge"));
const auto cap = d.samples.find(
"radiance:mixed_step_target_prefill_cap{model_name=\"m\",engine=\"0\"}");
CHECK(cap != d.samples.end());
if (cap != d.samples.end()) CHECK_NEAR(cap->second, 384.0, 1e-9);
}
/* Each draft position's acceptances are a counter next to its reach. At a fixed depth position
* j+1's reach is j's acceptances, but an adaptive window can end at j with j taken, so a ratio
* over a window needs both. Here two verifies end at position 1 with it accepted. */
+6 -1
View File
@@ -91,13 +91,18 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
}
const std::set<std::pair<std::string, std::string>> want = {
{ "anima", "" }, { "bailinghybrid", "" }, { "breeze", "" }, { "clef", "" },
{ "bailinghybrid", "gguf_ftype_7" }, { "bailinghybrid", "gguf_ftype_15" },
{ "bailinghybrid", "gguf_ftype_17" }, { "bailinghybrid", "gguf_ftype_18" },
{ "bailinghybrid", "gguf_ftype_25" },
{ "clef", "fp8_e4m3" }, { "embeddinggemma2", "" },
{ "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" },
{ "fishomni", "bsgemm-moe" }, { "flint", "" }, { "flux3", "" }, { "flux3distilled", "" },
{ "gemma3", "" }, { "gemma4", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" },
{ "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" },
{ "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" },
{ "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" },
{ "museglimmer", "" },
{ "museglimmer", "compressed-tensors" },
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
{ "qwen35moe", "w8a8_fwht128" },
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
+54
View File
@@ -311,6 +311,60 @@ TEST(a_cloning_model_takes_references_as_clips_and_transcripts_in_its_prompt) {
}
/* ================================================================== the response */
TEST(breeze_cloning_uses_one_reference_and_direction_is_opt_in) {
if (!mm::decoder_available()) { SKIP("audio decoder unavailable"); return; }
Speech s;
auto& info = s.gen.inf;
info.max_prompt = 512;
info.tmpl_plain = "<bos>[S0]{input}";
info.tmpl = "<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
info.neg_tmpl = info.tmpl_plain;
info.tmpl_ref = "{references}<bos>[S0]{input}";
info.ref_item = "<bos>[S0]{text}{audio}<|audio_eos|>";
info.ref_rate = 24000;
info.ref_hop = 1920;
info.ref_max_samples = 240000;
info.ref_max = 1;
info.branches = 2;
info.default_steps = 0;
const std::string wav = wav_of(std::vector<int16_t>(2000, 1000), 24000);
const std::string audio = base64_encode((const uint8_t*)wav.data(), wav.size());
const json ref = {{"audio", audio}, {"text", "reference words"}};
json body = {{"input", "new words"}, {"references", json::array({ref})}, {"guidance_scale", 1}};
CHECK_EQ(s.post(body).status, 200);
const auto& q = s.last();
CHECK_EQ(q.ref_audio.size(), (size_t)3840);
CHECK_EQ(q.ref_cu.size(), (size_t)2);
CHECK_EQ(std::count_if(q.ref_frame.begin(), q.ref_frame.end(), [](int v) { return v >= 0; }), 2);
CHECK_EQ(q.ref_frame.size(), q.tokens.size());
CHECK_EQ(q.cfg, 1.0f);
body["guidance_scale"] = 4;
CHECK_EQ(s.refused(body), std::string("guidance_scale"));
body["guidance_scale"] = 1;
body["instructions"] = "a different voice";
CHECK_EQ(s.refused(body), std::string("instructions"));
info.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
info.neg_tmpl_ref = info.tmpl_ref;
body["guidance_scale"] = 4;
CHECK_EQ(s.post(body).status, 200);
const auto& directed = s.last();
CHECK_EQ(directed.cfg, 4.0f);
CHECK_EQ(directed.neg_ref_frame.size(), directed.neg_tokens.size());
CHECK_EQ(std::count(directed.ref_frame.begin(), directed.ref_frame.end(), 0), 1);
CHECK_EQ(std::count(directed.neg_ref_frame.begin(), directed.neg_ref_frame.end(), 0), 1);
CHECK(directed.tokens.size() > directed.neg_tokens.size());
const auto text_of = [](const std::vector<int32_t>& ids) {
std::string text; for (int32_t i : ids) if (i) text.push_back((char)i); return text;
};
CHECK(has(text_of(directed.tokens), "<ins_bos>a different voice<ins_eos>new words"));
CHECK(!has(text_of(directed.neg_tokens), "a different voice"));
CHECK(has(text_of(directed.neg_tokens), "reference words"));
body.erase("instructions");
body["references"].push_back(ref);
CHECK_EQ(s.refused(body), std::string("references"));
body["references"] = json::array({{{"audio", audio}, {"text", " "}}});
CHECK_EQ(s.refused(body), std::string("references[0].text"));
}
/* The whole piece: the windows in order whatever order they were played in, as a WAV whose header
* states the rate, channels and length, or as the same samples raw. */