radiance 1.9.0

New models:
- LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first
  frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2
  latent upsampler
- Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up
  to ten reference pictures, on one card
- GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze)
- Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81)

Engine:
- --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81)
- the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168)
- eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes)
- the dashboard shows the single-stream decode floor and its most recent window (Memoria)

Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses
namespaces (#119), system messages merged when a template refuses several (#137), a prefill
continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns
read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state.
Plugin ABI 24.
This commit is contained in:
Deadcode committed 2026-10-19 21:58:07 +02:00
1 parent 778cbf315e
commit 685ec5bd85
136 files changed
+18917 -3821

No files matched your search

+5 -4
View File
@@ -366,7 +366,7 @@ endif()
# HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not
# reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and
# ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit,
# and for the LoRA pair libref itself when the test can load it.
# for the LoRA pair libref itself when the test can load it, and for KDA libref itself.
#
# Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang
# C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so
@@ -437,7 +437,7 @@ else()
list(APPEND objs ${dir}/${stem}.o)
endif()
endforeach()
# test_lora opens libref with dlopen to hold the emulated kernels to it.
# test_lora and test_kda open libref with dlopen to hold the emulated kernels to it.
set(dl "")
foreach(l ${CMAKE_DL_LIBS})
list(APPEND dl -l${l})
@@ -470,8 +470,9 @@ if(R4D_EMU_BUILT)
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
# The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can
# load one -- expand bit for bit, shrink to its bound.
set_tests_properties(r4d_emu_lora PROPERTIES
# load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within
# rounding, and that test needs it.
set_tests_properties(r4d_emu_lora r4d_emu_kda PROPERTIES
ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home")
# A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at
# about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it.
+51
View File
@@ -349,6 +349,19 @@ ABI_FIELD(RadGenBatch, dec_lane)
ABI_FIELD(RadGenBatch, dec_height)
ABI_FIELD(RadGenBatch, dec_width)
ABI_FIELD(RadGenBatch, dec_preview)
ABI_FIELD(RadGenBatch, branch)
ABI_FIELD(RadGenBatch, n_pad)
ABI_FIELD(RadGenBatch, valid_cu)
ABI_FIELD(RadGenBatch, n_img)
ABI_FIELD(RadGenBatch, img_cu)
ABI_FIELD(RadGenBatch, img_rows)
ABI_FIELD(RadGenBatch, mode_cu)
ABI_FIELD(RadGenBatch, rope_f)
ABI_FIELD(RadGenBatch, mode_rows)
ABI_FIELD(RadGenBatch, mode_src)
ABI_FIELD(RadGenBatch, mode_ccu)
ABI_FIELD(RadGenBatch, n_mode_h)
ABI_FIELD(RadGenBatch, mode_rope_f)
ABI_STRUCT(RadGeneratorDecl)
ABI_FIELD(RadGeneratorDecl, name)
ABI_FIELD(RadGeneratorDecl, layout)
@@ -382,6 +395,14 @@ ABI_FIELD(RadGeneratorDecl, shift_terminal)
ABI_FIELD(RadGeneratorDecl, default_cfg)
ABI_FIELD(RadGeneratorDecl, max_lanes)
ABI_FIELD(RadGeneratorDecl, image_out)
ABI_FIELD(RadGeneratorDecl, cond_rows)
ABI_FIELD(RadGeneratorDecl, rope_hw_scale)
ABI_FIELD(RadGeneratorDecl, rope_text_l)
ABI_FIELD(RadGeneratorDecl, pad_multiple)
ABI_FIELD(RadGeneratorDecl, pad_token)
ABI_FIELD(RadGeneratorDecl, cfg_original)
ABI_FIELD(RadGeneratorDecl, default_negative)
ABI_FIELD(RadGeneratorDecl, ref_shrink_only)
ABI_STRUCT(RadKVGroupBatch)
ABI_FIELD(RadKVGroupBatch, group)
ABI_FIELD(RadKVGroupBatch, slot_mapping)
@@ -615,6 +636,12 @@ ABI_FIELD(RadVideoGenBatch, n_frames_out)
ABI_FIELD(RadVideoGenBatch, n_samples)
ABI_FIELD(RadVideoGenBatch, geom_from)
ABI_FIELD(RadVideoGenBatch, upscale)
ABI_FIELD(RadVideoGenBatch, n_neg)
ABI_FIELD(RadVideoGenBatch, guidance_h)
ABI_FIELD(RadVideoGenBatch, image)
ABI_FIELD(RadVideoGenBatch, has_image)
ABI_FIELD(RadVideoGenBatch, guidance)
ABI_FIELD(RadVideoGenBatch, decoder)
ABI_STRUCT(RadVideoGenDecl)
ABI_FIELD(RadVideoGenDecl, name)
ABI_FIELD(RadVideoGenDecl, tmpl)
@@ -653,6 +680,30 @@ ABI_FIELD(RadVideoGenDecl, n_rungs)
ABI_FIELD(RadVideoGenDecl, rungs)
ABI_FIELD(RadVideoGenDecl, upscale_max)
ABI_FIELD(RadVideoGenDecl, upscale_refine)
ABI_FIELD(RadVideoGenDecl, sched_kind)
ABI_FIELD(RadVideoGenDecl, dyn_shift)
ABI_FIELD(RadVideoGenDecl, base_shift)
ABI_FIELD(RadVideoGenDecl, max_shift)
ABI_FIELD(RadVideoGenDecl, base_seq)
ABI_FIELD(RadVideoGenDecl, max_seq)
ABI_FIELD(RadVideoGenDecl, shift_terminal)
ABI_FIELD(RadVideoGenDecl, n_refine_rungs)
ABI_FIELD(RadVideoGenDecl, refine_rungs)
ABI_FIELD(RadVideoGenDecl, step_text_rows)
ABI_FIELD(RadVideoGenDecl, guidance)
ABI_FIELD(RadVideoGenDecl, guidance_default)
ABI_FIELD(RadVideoGenDecl, default_negative)
ABI_FIELD(RadVideoGenDecl, image_cond)
ABI_FIELD(RadVideoGenDecl, image_crf)
ABI_FIELD(RadVideoGenDecl, text_left_pad)
ABI_FIELD(RadVideoGenDecl, audio_streams)
ABI_FIELD(RadVideoGenDecl, upscale_exact)
ABI_FIELD(RadVideoGenDecl, duration_out)
ABI_FIELD(RadVideoGenDecl, duration_min)
ABI_FIELD(RadVideoGenDecl, duration_max)
ABI_FIELD(RadVideoGenDecl, duration_dtype)
ABI_FIELD(RadVideoGenDecl, decoders)
ABI_FIELD(RadVideoGenDecl, decoder_max_area)
ABI_STRUCT(RadVideoGeom)
ABI_FIELD(RadVideoGeom, n_text)
ABI_FIELD(RadVideoGeom, frames)
+56 -5
View File
@@ -1,4 +1,4 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 23 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 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. */
@@ -315,7 +315,7 @@
{ "RadFuseStep", "n_p", 584, 4 },
{ "RadFuseStep", "from", 588, 32 },
{ "RadFuseStep", "n_from", 620, 4 },
{ "RadGenBatch", "", 0, 224 },
{ "RadGenBatch", "", 0, 320 },
{ "RadGenBatch", "rows", 0, 8 },
{ "RadGenBatch", "src", 8, 8 },
{ "RadGenBatch", "rope", 16, 8 },
@@ -346,7 +346,20 @@
{ "RadGenBatch", "dec_height", 212, 4 },
{ "RadGenBatch", "dec_width", 216, 4 },
{ "RadGenBatch", "dec_preview", 220, 4 },
{ "RadGeneratorDecl", "", 0, 248 },
{ "RadGenBatch", "branch", 224, 4 },
{ "RadGenBatch", "n_pad", 228, 4 },
{ "RadGenBatch", "valid_cu", 232, 8 },
{ "RadGenBatch", "n_img", 240, 8 },
{ "RadGenBatch", "img_cu", 248, 8 },
{ "RadGenBatch", "img_rows", 256, 8 },
{ "RadGenBatch", "mode_cu", 264, 8 },
{ "RadGenBatch", "rope_f", 272, 8 },
{ "RadGenBatch", "mode_rows", 280, 8 },
{ "RadGenBatch", "mode_src", 288, 8 },
{ "RadGenBatch", "mode_ccu", 296, 8 },
{ "RadGenBatch", "n_mode_h", 304, 8 },
{ "RadGenBatch", "mode_rope_f", 312, 8 },
{ "RadGeneratorDecl", "", 0, 296 },
{ "RadGeneratorDecl", "name", 0, 8 },
{ "RadGeneratorDecl", "layout", 8, 4 },
{ "RadGeneratorDecl", "tmpl_text", 16, 8 },
@@ -379,6 +392,14 @@
{ "RadGeneratorDecl", "default_cfg", 224, 8 },
{ "RadGeneratorDecl", "max_lanes", 232, 8 },
{ "RadGeneratorDecl", "image_out", 240, 4 },
{ "RadGeneratorDecl", "cond_rows", 248, 8 },
{ "RadGeneratorDecl", "rope_hw_scale", 256, 8 },
{ "RadGeneratorDecl", "rope_text_l", 264, 4 },
{ "RadGeneratorDecl", "pad_multiple", 268, 4 },
{ "RadGeneratorDecl", "pad_token", 272, 4 },
{ "RadGeneratorDecl", "cfg_original", 276, 4 },
{ "RadGeneratorDecl", "default_negative", 280, 8 },
{ "RadGeneratorDecl", "ref_shrink_only", 288, 4 },
{ "RadKVGroupBatch", "", 0, 72 },
{ "RadKVGroupBatch", "group", 0, 4 },
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
@@ -590,7 +611,7 @@
{ "RadTunable", "n_values", 16, 4 },
{ "RadTunable", "deflt", 24, 8 },
{ "RadTunable", "doc", 32, 8 },
{ "RadVideoGenBatch", "", 0, 192 },
{ "RadVideoGenBatch", "", 0, 240 },
{ "RadVideoGenBatch", "lane", 0, 4 },
{ "RadVideoGenBatch", "geom", 4, 24 },
{ "RadVideoGenBatch", "geom_d", 32, 8 },
@@ -612,7 +633,13 @@
{ "RadVideoGenBatch", "n_samples", 152, 8 },
{ "RadVideoGenBatch", "geom_from", 160, 24 },
{ "RadVideoGenBatch", "upscale", 184, 8 },
{ "RadVideoGenDecl", "", 0, 288 },
{ "RadVideoGenBatch", "n_neg", 192, 4 },
{ "RadVideoGenBatch", "guidance_h", 200, 8 },
{ "RadVideoGenBatch", "image", 208, 8 },
{ "RadVideoGenBatch", "has_image", 216, 4 },
{ "RadVideoGenBatch", "guidance", 224, 8 },
{ "RadVideoGenBatch", "decoder", 232, 4 },
{ "RadVideoGenDecl", "", 0, 512 },
{ "RadVideoGenDecl", "name", 0, 8 },
{ "RadVideoGenDecl", "tmpl", 8, 8 },
{ "RadVideoGenDecl", "max_text", 16, 8 },
@@ -650,6 +677,30 @@
{ "RadVideoGenDecl", "rungs", 264, 8 },
{ "RadVideoGenDecl", "upscale_max", 272, 8 },
{ "RadVideoGenDecl", "upscale_refine", 280, 4 },
{ "RadVideoGenDecl", "sched_kind", 284, 4 },
{ "RadVideoGenDecl", "dyn_shift", 288, 4 },
{ "RadVideoGenDecl", "base_shift", 296, 8 },
{ "RadVideoGenDecl", "max_shift", 304, 8 },
{ "RadVideoGenDecl", "base_seq", 312, 8 },
{ "RadVideoGenDecl", "max_seq", 320, 8 },
{ "RadVideoGenDecl", "shift_terminal", 328, 8 },
{ "RadVideoGenDecl", "n_refine_rungs", 336, 4 },
{ "RadVideoGenDecl", "refine_rungs", 344, 8 },
{ "RadVideoGenDecl", "step_text_rows", 352, 8 },
{ "RadVideoGenDecl", "guidance", 360, 4 },
{ "RadVideoGenDecl", "guidance_default", 368, 64 },
{ "RadVideoGenDecl", "default_negative", 432, 8 },
{ "RadVideoGenDecl", "image_cond", 440, 4 },
{ "RadVideoGenDecl", "image_crf", 444, 4 },
{ "RadVideoGenDecl", "text_left_pad", 448, 8 },
{ "RadVideoGenDecl", "audio_streams", 456, 4 },
{ "RadVideoGenDecl", "upscale_exact", 460, 4 },
{ "RadVideoGenDecl", "duration_out", 464, 4 },
{ "RadVideoGenDecl", "duration_min", 472, 8 },
{ "RadVideoGenDecl", "duration_max", 480, 8 },
{ "RadVideoGenDecl", "duration_dtype", 488, 4 },
{ "RadVideoGenDecl", "decoders", 496, 8 },
{ "RadVideoGenDecl", "decoder_max_area", 504, 8 },
{ "RadVideoGeom", "", 0, 24 },
{ "RadVideoGeom", "n_text", 0, 4 },
{ "RadVideoGeom", "frames", 4, 4 },
+3 -3
View File
@@ -8,7 +8,7 @@
*
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
* the layout agrees with the table below, taken at RAD_ABI_VERSION 23 and RAD_FORMAT_VER 2. Under
* the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
* headers: nothing else states the layout. When it disagrees the test prints the live table.
@@ -57,8 +57,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 23 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 23, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 24, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
+171 -278
View File
@@ -2375,7 +2375,6 @@ TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residua
TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) {
using namespace rad::arch;
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
for (int world : { 1, 2, 4, 8 })
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
@@ -2501,7 +2500,6 @@ TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) {
TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) {
using namespace rad::arch;
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
for (int world : { 1, 2, 4, 8 })
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
@@ -2578,44 +2576,6 @@ TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold)
REQUIRE_EQ(ctx.issues.size(), (size_t)2);
CHECK_EQ(ctx.issues[0].op, router.op_project);
}
{
setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "64", 1);
RadBuilder b;
Names nm("");
Geom g{};
g.n_embd = 4096;
g.max_tok = 128;
g.world = 8;
g.rank = 5;
GlmRouter::Config cfg;
cfg.rows = 128;
GlmRouter::Wire w;
w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 });
w.logits = decl_b(&b, "logits", RAD_F32, { 128, 288 });
w.ids = decl_b(&b, "ids", RAD_I32, { 128, 8 });
w.weights = decl_b(&b, "weights", RAD_F32, { 128, 8 });
GlmRouter::Src src{ "model.layers.3.mlp.gate.weight",
"model.layers.3.mlp.gate.e_score_correction_bias" };
GlmRouter router;
REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK);
RadCtx ctx;
router.step(&ctx, 0, 64);
router.step(&ctx, 0, 63);
REQUIRE_EQ(ctx.issues.size(), (size_t)5);
CHECK_EQ(ctx.issues[0].op, router.split.op_part);
CHECK_EQ(ctx.issues[3].op, router.op_project);
setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "0", 1);
RadBuilder off;
GlmRouter whole;
auto w2 = w;
w2.input = decl_b(&off, "hidden", RAD_BF16, { 128, 4096 });
w2.logits = decl_b(&off, "logits", RAD_F32, { 128, 288 });
w2.ids = decl_b(&off, "ids", RAD_I32, { 128, 8 });
w2.weights = decl_b(&off, "weights", RAD_F32, { 128, 8 });
REQUIRE_EQ(whole.declare(&off, nm, g, 3, "blk.3.router", cfg, w2, src), RAD_OK);
CHECK_EQ(count_op(off, "all_gather"), 0);
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
}
}
TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) {
@@ -2681,7 +2641,6 @@ TEST(
meta.kv_val = vals;
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
for (int world : { 1, 4, 8 })
for (int rank = 0; rank < world; ++rank) {
RadBuilder b;
@@ -2900,77 +2859,72 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) {
meta.kv_val = vals;
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
// 256 is the default threshold; at 2048 the 256- and 1024-row levels lie below it.
const int world = 8, rank = 3;
for (const char* split : { "256", "2048" })
for (int64_t R : { 256, 3072 }) {
setenv("RADIANCE_GLM_TP_SPLIT_ROWS", split, 1);
auto encs = [&](RadBuilder& b) {
b.kv_block = 4;
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
{ "mtp.blk.45.ffn_down_exps", fp8 },
{ "ffn_gate_up_exps", mx },
{ "ffn_down_exps", mx },
{ "ffn_gate_up_shexp", mx },
{ "ffn_down_shexp", mx },
{ "ffn_gate_up.weight", fp8 },
{ "ffn_down.weight", fp8 } };
};
RadBuildCtx c{};
c.rank = rank;
c.world_size = world;
c.max_tok = 4096;
c.max_seqs = 8;
c.max_ctx = 32768;
c.max_spec = 3;
RadBuilder full;
encs(full);
REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK);
RadBuildCtx p = c;
p.max_tok = R;
p.shape_probe = 1;
RadBuilder small;
encs(small);
REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK);
REQUIRE_EQ(small.ops.size(), full.ops.size());
int differ = 0;
for (size_t i = 0; i < full.ops.size(); ++i) {
if (small.ops[i].op != full.ops[i].op) {
++differ;
for (int64_t R : { 256, 3072 }) {
auto encs = [&](RadBuilder& b) {
b.kv_block = 4;
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
{ "mtp.blk.45.ffn_down_exps", fp8 },
{ "ffn_gate_up_exps", mx },
{ "ffn_down_exps", mx },
{ "ffn_gate_up_shexp", mx },
{ "ffn_down_shexp", mx },
{ "ffn_gate_up.weight", fp8 },
{ "ffn_down.weight", fp8 } };
};
RadBuildCtx c{};
c.rank = rank;
c.world_size = world;
c.max_tok = 4096;
c.max_seqs = 8;
c.max_ctx = 32768;
c.max_spec = 3;
RadBuilder full;
encs(full);
REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK);
RadBuildCtx p = c;
p.max_tok = R;
p.shape_probe = 1;
RadBuilder small;
encs(small);
REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK);
REQUIRE_EQ(small.ops.size(), full.ops.size());
int differ = 0;
for (size_t i = 0; i < full.ops.size(); ++i) {
if (small.ops[i].op != full.ops[i].op) {
++differ;
continue;
}
REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size());
for (size_t k = 0; k < full.ops[i].p.size(); ++k) {
const RecParam& a = full.ops[i].p[k];
const RecParam& q = small.ops[i].p[k];
if (a.kind == RAD_P_RANGE) continue;
// A capacity may shrink: its kernel writes by its operands' extents.
if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival)
continue;
}
REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size());
for (size_t k = 0; k < full.ops[i].p.size(); ++k) {
const RecParam& a = full.ops[i].p[k];
const RecParam& q = small.ops[i].p[k];
if (a.kind == RAD_P_RANGE) continue;
// A capacity may shrink: its kernel writes by its operands' extents.
if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival)
continue;
if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) {
fprintf(stderr,
" split %s R %lld: op %zu '%s' param '%s': "
"%lld real, %lld small\n",
split, (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(),
a.ival, q.ival);
++differ;
}
if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) {
fprintf(stderr,
" R %lld: op %zu '%s' param '%s': "
"%lld real, %lld small\n",
(long long)R, i, full.ops[i].op.c_str(), a.key.c_str(),
a.ival, q.ival);
++differ;
}
}
CHECK_EQ(differ, 0);
REQUIRE_EQ(small.bufs.size(), full.bufs.size());
for (size_t i = 0; i < full.bufs.size(); ++i)
for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d)
CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]);
}
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
CHECK_EQ(differ, 0);
REQUIRE_EQ(small.bufs.size(), full.bufs.size());
for (size_t i = 0; i < full.bufs.size(); ++i)
for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d)
CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]);
}
}
/* The MoE block's decode fusions (RADIANCE_GLM_*): each switch, alone and with the others, changes
* exactly its launches against the step without switches, over a two-row trunk step, its draft
* pass and a 512-row prefill (past the router fusion's one-workgroup sort), with the step lint
* clean throughout. A switch value other than 0 or 1 is refused. */
/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill
* (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the
* launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's
* row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */
TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) {
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
"index_topk" };
@@ -2985,175 +2939,122 @@ TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) {
meta.kv_val = vals;
const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128);
const char* const env[] = { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT",
"RADIANCE_GLM_GATHER_INVERSE" };
const int n_env = (int)(sizeof env / sizeof env[0]);
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
auto clear = [&]() {
for (const char* e : env) unsetenv(e);
};
using Counts = std::map<std::string, int>;
/* Launches the first two switches remove (negative) and add, per step: trunk, draft pass,
* prefill. The trunk has 42 MoE layers, each a routed and a shared clamped SwiGLU, and three
* dense ones. The third turns every remaining sort and gather into its inverse form. */
struct Delta {
/* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed
* and a shared clamped SwiGLU, and three dense ones. */
struct Want {
const char* op;
int trunk, draft, prefill;
};
const std::vector<Delta> deltas[] = {
{ { "router_sigmoid_topk_scatter", 42, 1, 0 },
{ "router_sigmoid_topk", -42, -1, 0 },
{ "moe_scatter", -42, -1, 0 },
{ "fill", -42, -1, 0 } },
{ { "swiglu_clamped_quant_fp8", 87, 2, 87 },
{ "swiglu_clamped", -87, -2, -87 },
{ "quant_act_fp8", -87, -2, -87 } },
const Want wants[] = {
{ "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 },
{ "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 },
{ "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 },
};
for (int world : { 1, 8 }) {
Counts base[3];
for (int mask = 0; mask < (1 << n_env); ++mask) {
// At one rank only the extremes: no switch reads the world.
if (world == 1 && mask && mask != (1 << n_env) - 1) continue;
for (int e = 0; e < n_env; ++e) setenv(env[e], mask >> e & 1 ? "1" : "0", 1);
RadBuilder b;
b.kv_block = 4;
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
{ "mtp.blk.45.ffn_down_exps", fp8 },
{ "ffn_gate_up_exps", mx },
{ "ffn_down_exps", mx },
{ "ffn_gate_up_shexp", mx },
{ "ffn_down_shexp", mx },
{ "ffn_gate_up.weight", fp8 },
{ "ffn_down.weight", fp8 } };
RadBuildCtx build{};
build.rank = 0;
build.world_size = world;
build.max_tok = 512;
build.max_seqs = 4;
build.max_ctx = 4096;
build.max_spec = 3;
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 },
slots[] = { 0, 1 }, out[] = { 1 };
int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{};
std::vector<RadKVGroupBatch> kv(b.kv_groups.size());
for (size_t i = 0; i < kv.size(); ++i) {
kv[i].group = (rad_kvgroup)i + 1;
kv[i].slot_mapping = slots;
kv[i].block_table = tables;
kv[i].block_table_pitch = 32;
kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx;
kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6;
}
RadBatch batch{};
batch.phase = RAD_PHASE_PREFILL;
batch.n_tok = 2;
batch.n_seq = 1;
batch.token_ids = ids;
batch.positions = positions;
batch.cu_seqlens = cu;
batch.ctx_lens = ctxlens;
batch.kv = kv.data();
batch.n_kv_groups = (int)kv.size();
batch.n_out = 1;
batch.out_ids = out;
RadCtx ctx;
ctx.b = &b;
ctx.rank = 0;
ctx.world = world;
ctx.batch = &batch;
Counts got[3];
/* With the inverse, the fused selection writes it as its ninth operand and the gather
* reads it as its third. */
const rad_buf inv = find_b(b, "expert_inverse")
? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1)
: 0;
CHECK_EQ(inv != 0, (mask & 4) != 0);
auto run = [&](int k) {
ctx.issues.clear();
glm5next::step(&ctx, &batch);
CHECK(ctx.step_fail.empty());
CHECK_LINT(b, &ctx);
for (const auto& op : issued_ops(b, ctx)) ++got[k][op];
for (const auto& is : ctx.issues) {
const RecOp* o = b.op_of(is.op);
if (!o || !inv) continue;
if (o->op == "router_sigmoid_topk_scatter")
CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF &&
is.opd[8].handle == inv);
if (o->op == "moe_gather_inv")
CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF &&
is.opd[2].handle == inv);
}
};
run(0);
batch.draft_pass = -1;
batch.n_draft_out = 1;
batch.draft_out_ids = out;
run(1);
std::vector<int32_t> long_ids(512, 7), long_positions(512), long_slots(512),
long_tables(1024);
for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i;
int32_t long_cu[] = { 0, 512 }, last = 511;
for (auto& group : kv) {
group.slot_mapping = long_slots.data();
group.block_table = long_tables.data();
group.block_table_pitch = 1024;
}
batch.n_tok = 512;
batch.token_ids = long_ids.data();
batch.positions = long_positions.data();
batch.cu_seqlens = long_cu;
batch.out_ids = &last;
batch.draft_pass = 0;
batch.n_draft_out = 0;
batch.max_q_len = 512;
run(2);
if (mask == 0) {
for (int k = 0; k < 3; ++k) base[k] = got[k];
continue;
}
for (int k = 0; k < 3; ++k) {
Counts want = base[k];
for (int e = 0; e < 2; ++e)
if (mask >> e & 1)
for (const Delta& d : deltas[e])
want[d.op] += k == 0 ? d.trunk : k == 1 ? d.draft : d.prefill;
if (mask & 4) {
want["moe_scatter_inv"] += want["moe_scatter"];
want["moe_scatter"] = 0;
want["moe_gather_inv"] += want["moe_gather"];
want["moe_gather"] = 0;
}
for (auto it = want.begin(); it != want.end();)
it = it->second == 0 ? want.erase(it) : std::next(it);
if (got[k] != want) {
fprintf(stderr, " world %d switches %d step %d:", world, mask, k);
for (const auto& [op, n] : want)
if (got[k][op] != n)
fprintf(stderr, " %s %d (want %d)", op.c_str(), got[k][op], n);
for (const auto& [op, n] : got[k])
if (!want.count(op)) fprintf(stderr, " %s %d (want 0)", op.c_str(), n);
fprintf(stderr, "\n");
}
CHECK(got[k] == want);
}
}
}
for (const char* e : env) {
clear();
setenv(e, "2", 1);
RadBuilder b;
b.kv_block = 4;
b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 },
{ "mtp.blk.45.ffn_down_exps", fp8 },
{ "ffn_gate_up_exps", mx },
{ "ffn_down_exps", mx },
{ "ffn_gate_up_shexp", mx },
{ "ffn_down_shexp", mx },
{ "ffn_gate_up.weight", fp8 },
{ "ffn_down.weight", fp8 } };
RadBuildCtx build{};
build.rank = 0;
build.world_size = 8;
build.max_tok = 64;
build.world_size = world;
build.max_tok = 512;
build.max_seqs = 4;
build.max_ctx = 4096;
build.max_spec = 3;
CHECK_EQ(glm5next::declare(&b, &meta, &build), RAD_E_INVAL);
REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK);
int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 },
slots[] = { 0, 1 }, out[] = { 1 };
int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{};
std::vector<RadKVGroupBatch> kv(b.kv_groups.size());
for (size_t i = 0; i < kv.size(); ++i) {
kv[i].group = (rad_kvgroup)i + 1;
kv[i].slot_mapping = slots;
kv[i].block_table = tables;
kv[i].block_table_pitch = 32;
kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx;
kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6;
}
RadBatch batch{};
batch.phase = RAD_PHASE_PREFILL;
batch.n_tok = 2;
batch.n_seq = 1;
batch.token_ids = ids;
batch.positions = positions;
batch.cu_seqlens = cu;
batch.ctx_lens = ctxlens;
batch.kv = kv.data();
batch.n_kv_groups = (int)kv.size();
batch.n_out = 1;
batch.out_ids = out;
RadCtx ctx;
ctx.b = &b;
ctx.rank = 0;
ctx.world = world;
ctx.batch = &batch;
Counts got[3];
/* With the inverse, the fused selection writes it as its ninth operand and the gather
* reads it as its third. */
const rad_buf inv = find_b(b, "expert_inverse")
? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1)
: 0;
REQUIRE(inv != 0);
auto run = [&](int k) {
ctx.issues.clear();
glm5next::step(&ctx, &batch);
CHECK(ctx.step_fail.empty());
CHECK_LINT(b, &ctx);
for (const auto& op : issued_ops(b, ctx)) ++got[k][op];
for (const auto& is : ctx.issues) {
const RecOp* o = b.op_of(is.op);
if (!o) continue;
if (o->op == "router_sigmoid_topk_scatter")
CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF &&
is.opd[8].handle == inv);
if (o->op == "moe_gather_inv")
CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF &&
is.opd[2].handle == inv);
}
};
run(0);
batch.draft_pass = -1;
batch.n_draft_out = 1;
batch.draft_out_ids = out;
run(1);
std::vector<int32_t> long_ids(512, 7), long_positions(512), long_slots(512),
long_tables(1024);
for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i;
int32_t long_cu[] = { 0, 512 }, last = 511;
for (auto& group : kv) {
group.slot_mapping = long_slots.data();
group.block_table = long_tables.data();
group.block_table_pitch = 1024;
}
batch.n_tok = 512;
batch.token_ids = long_ids.data();
batch.positions = long_positions.data();
batch.cu_seqlens = long_cu;
batch.out_ids = &last;
batch.draft_pass = 0;
batch.n_draft_out = 0;
batch.max_q_len = 512;
run(2);
for (int k = 0; k < 3; ++k)
for (const Want& w : wants) {
const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill;
if (got[k][w.op] != want)
fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op,
got[k][w.op], want);
CHECK_EQ(got[k][w.op], want);
}
}
clear();
}
TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) {
@@ -3296,7 +3197,7 @@ TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) {
MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight",
"mlp.up_proj.weight", "mlp.down_proj.weight" };
REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK);
CHECK_EQ(block.op_gated, 0);
CHECK_EQ(block.op_gated, 0u);
CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped"));
RadCtx ctx;
ctx.b = &b;
@@ -3619,12 +3520,12 @@ TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_
if (glm) {
CHECK_EQ(b.weights[moe.w_router - 1].d.dtype, RAD_F32);
CHECK_EQ(b.ops[moe.op_topk - 1].op, std::string("router_sigmoid_topk"));
CHECK_EQ(moe.op_topk_scatter, 0);
CHECK_EQ(moe.op_router_fused, 0);
CHECK_EQ(moe.op_topk_scatter, 0u);
CHECK_EQ(moe.op_router_fused, 0u);
CHECK_EQ(b.ops[moe.gq_exp.op - 1].op, std::string("swiglu_clamped"));
CHECK_EQ(b.ops[moe.gq_sh.op - 1].op, std::string("swiglu_clamped"));
CHECK_EQ(b.ops[moe.op_sgate - 1].op, std::string("fill"));
CHECK_EQ(moe.w_sgate, 0);
CHECK_EQ(moe.w_sgate, 0u);
bool plain_shared = false;
for (const auto& p : b.ops[moe.op_gather - 1].p)
if (p.key == "act") plain_shared = p.sval == "none";
@@ -9475,10 +9376,9 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) {
}
}
/* With the decode fusions switched off, GLM declares and steps the graph and launches it had
* before them, at one and eight ranks: a 4096-row prefill after history, a mixed step, a decode
* step, a verify and its draft passes. */
TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) {
/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill
* after history, a mixed step, a decode step, a verify and its draft passes. */
TEST(glm53_is_the_pinned_graph_and_steps) {
const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts",
"index_topk" };
const char* vals[] = { "1", "4", "288", "2048" };
@@ -9496,12 +9396,8 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) {
int world;
uint64_t graph, steps;
};
const Case cases[] = { { 1, 0xd48139cb64abf0b1ull, 0x6982726c635df529ull },
{ 8, 0x90fc5bc69f1cfb10ull, 0x197c95726131b817ull } };
for (const char* e :
{ "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" })
setenv(e, "0", 1);
unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS");
const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull },
{ 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } };
for (const Case& cs : cases) {
RadBuilder b;
b.kv_block = 4;
@@ -9525,9 +9421,6 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) {
CHECK_EQ(g, cs.graph);
CHECK_EQ(s, cs.steps);
}
for (const char* e :
{ "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" })
unsetenv(e);
}
/* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its
+30
View File
@@ -1043,6 +1043,36 @@ TEST(a_dotted_integer_is_an_index_as_in_jinja2) {
CHECK_EQ(p.prompt, std::string("hi|assistant"));
}
/* A template that takes one system message, first, as many do, against conversations the Chat
* Completions API allows: a system message after a user turn, and two at the head. They are
* rendered with the system messages merged, in order, into one at the head (#137). Any other
* refusal comes back in the template's own words, without the parser-generation wrapper. */
TEST(system_messages_a_template_takes_only_first_are_merged_at_the_head) {
ChatTemplate t;
CHECK_OK(t.load(
"{%- for m in messages %}"
"{%- if m.role == 'system' and not loop.first %}"
"{{- raise_exception('System message must be at the beginning.') }}{%- endif %}"
"{%- if m.role == 'user' and m.content == 'boom' %}{{- raise_exception('no boom') }}{%- endif %}"
"<{{ m.role }}>{{ m.content }}</{{ m.role }}>"
"{%- endfor %}{%- if add_generation_prompt %}<assistant>{% endif %}", "", ""));
ChatOptions opt;
opt.quiet = true;
auto render = [&](const json& msgs, ChatPrompt* p) { return t.apply(msgs, json(), opt, p); };
ChatPrompt a, b, c, d;
CHECK_OK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"hi"}])"), &a));
CHECK_EQ(a.prompt, std::string("<system>s</system><user>hi</user><assistant>"));
CHECK_OK(render(json::parse(R"([{"role":"user","content":"hi"},{"role":"system","content":"s"}])"), &b));
CHECK_EQ(b.prompt, std::string("<system>s</system><user>hi</user><assistant>"));
CHECK_OK(render(json::parse(R"([{"role":"system","content":"s1"},{"role":"system",
"content":[{"type":"text","text":"s2"}]},{"role":"user","content":"hi"}])"), &c));
CHECK_EQ(c.prompt, std::string("<system>s1\n\ns2</system><user>hi</user><assistant>"));
CHECK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"boom"}])"),
&d) < 0);
CHECK(d.error.find("no boom") != std::string::npos);
CHECK(d.error.find("Unable to generate parser") == std::string::npos);
}
/* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value;
* a throw would cross the bringup path. */
TEST(a_template_that_does_not_parse_is_a_value_and_not_a_throw) {
+95
View File
@@ -327,4 +327,99 @@ TEST(the_generator_admits_in_order_and_shutdown_answers_every_ticket) {
CHECK(f.drv.next(1) == nullptr);
}
/* The joint layout (RAD_GEN_LAYOUT_JOINT_STEP): no KV group; the conditioning's prompt padded to
* the declared multiple (padding at position 1, valid_cu bounding the prompt), the reference
* picture's tokens after it with its own l and scaled positions, and stored for every lane of the
* request. A denoising entry is that conditioning, read from its lane and branch's store rows,
* then the image, both in the pass order and mode by mode. */
TEST(the_joint_layout_carries_the_conditioning_in_every_step) {
Program prog;
prog.generator = decl_base();
RadGeneratorDecl& d = prog.generator;
d.layout = RAD_GEN_LAYOUT_JOINT_STEP;
d.cond_rows = 64;
d.pad_multiple = 8;
d.pad_token = 99;
d.rope_hw_scale = 0.5;
d.rope_text_l = 1;
d.ref_area = 32 * 32;
prog.ctx.max_tok = 2048;
prog.ctx.max_seqs = 8;
prog.kv_groups.emplace_back();
gen::Driver drv;
REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK);
auto r = std::make_unique<gen::Request>();
r->width = 64;
r->height = 32;
r->n = 2;
r->pos.tokens = { 1, 2, 3, 4, 5 };
r->pos.n_drop = 1;
r->has_neg = true;
r->neg.tokens = { 1, 6 };
r->neg.n_drop = 1;
r->cfg = 3.0f;
gen::Pixels px;
px.w = 32;
px.h = 32;
px.ch = 4;
px.bf16.assign(32 * 32 * 4, 0);
r->refs.push_back(px);
r->ticket = std::make_shared<gen::Ticket>();
std::string why;
REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK);
/* The positive conditioning: 4 text rows padded to 8, then the picture's 2 x 2 tokens. */
const RadBatch* b = drv.next(0);
REQUIRE(b != nullptr);
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND);
const RadGenBatch* G = b->gen_b;
CHECK_EQ(b->n_kv_groups, (int32_t)0);
CHECK_EQ(b->n_tok, (int64_t)9); /* five tokens and four padding */
CHECK_EQ(G->rows, (int64_t)12); /* 8 text rows and 4 picture tokens */
CHECK_EQ(G->n_pad, (int32_t)4);
CHECK_EQ(G->branch, (int32_t)0);
CHECK_EQ(G->valid_cu[1], (int32_t)5);
CHECK_EQ(b->token_ids[8], (int32_t)99);
CHECK_EQ(b->positions[8], (int32_t)1);
CHECK_EQ(G->n_lane, (int64_t)2);
CHECK_EQ(G->src[0], (int32_t)1); /* the prompt row after the drop */
CHECK_EQ(G->src[8], (int32_t)-1); /* the picture's first latent row */
CHECK_EQ(G->rope_f[3 * 12 + 2], 2.0f); /* text row 2: l = 2 */
CHECK_EQ(G->rope_f[3 * 12 + 9], -1.0f); /* the picture: l = -1 */
CHECK_EQ(G->rope_f[2 * 12 + 9], 0.5f); /* its token (0, 1): w = 0.5 */
CHECK_OK(drv.done());
b = drv.next(1);
REQUIRE(b != nullptr);
CHECK_EQ(b->gen_b->branch, (int32_t)1);
CHECK_EQ(b->gen_b->rows, (int64_t)12); /* one token padded to 8, the picture */
CHECK_OK(drv.done());
/* A step: four entries (two images, each with its negative), 12 + 8 rows each. */
b = drv.next(2);
REQUIRE(b != nullptr);
REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE);
G = b->gen_b;
REQUIRE_EQ(b->n_seq, (int64_t)4);
CHECK_EQ(b->n_tok, (int64_t)80);
CHECK_EQ(G->n_img, (int64_t)32);
CHECK_EQ(b->cu_seqlens[1], (int32_t)20);
const int32_t lane0 = G->lane_dh[0];
CHECK_EQ(G->src[0], (int32_t)(2 * lane0 * 64)); /* lane 0's positive row 0 */
CHECK_EQ(G->src[20], (int32_t)((2 * lane0 + 1) * 64)); /* its negative row 0 */
CHECK_EQ(G->src[12], (int32_t)-1); /* the first image row */
CHECK_EQ(G->img_rows[0], (int32_t)12);
CHECK_EQ(G->img_cu[1], (int32_t)8);
CHECK_EQ(G->mode_cu[1], (int32_t)8); /* entry 0: text 0..8 */
CHECK_EQ(G->mode_cu[2], (int32_t)12); /* pictures 8..12 */
CHECK_EQ(G->mode_cu[3], (int32_t)20); /* image to 20 */
CHECK_EQ(G->n_mode_h[0], (int64_t)32);
CHECK_EQ(G->n_mode_h[1], (int64_t)16);
CHECK_EQ(G->n_mode_h[2], (int64_t)32);
CHECK_EQ(G->mode_rows[32], (int32_t)8); /* the first picture row */
CHECK_EQ(G->mode_ccu[1 * 5 + 1], (int32_t)4); /* pictures: entry 1 from 4 */
CHECK_EQ(G->mode_rope_f[4 * 32 + 3 * 16 + 0], -1.0f); /* the pictures' l plane */
CHECK_EQ(G->rope_f[1 * 80 + 12 + 4], 0.5f); /* image token (1, 0): h = 0.5 */
CHECK_OK(drv.done());
}
RAD_TEST_MAIN()
+27
View File
@@ -171,6 +171,33 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) {
/* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must
* be the first picture's size. */
/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2):
* a request naming nothing is guided at the card's scale with the model's own empty negative
* prompt, handed on as s + 1; `guidance_scale` is the same field as `true_cfg_scale`, 0 turns it
* off, and naming both is refused. An RGB model refuses a transparent background. */
TEST(guidance_follows_the_model_cards_terms_and_its_default_negative) {
Images s;
s.img.inf.cfg_original = true;
s.img.inf.default_cfg = 4.5;
s.img.inf.has_default_negative = true;
s.img.inf.default_negative = "";
s.img.inf.pixel_channels = 3;
s.gen({ { "prompt", "a fox" } });
REQUIRE(!s.img.got.empty());
CHECK(s.last().has_neg);
CHECK_EQ(s.last().cfg, 5.5f);
s.gen({ { "prompt", "a fox" }, { "guidance_scale", 2.0 } });
CHECK(s.last().has_neg);
CHECK_EQ(s.last().cfg, 3.0f);
s.gen({ { "prompt", "a fox" }, { "guidance_scale", 0.0 } });
CHECK(!s.last().has_neg);
const json both = s.gen({ { "prompt", "x" }, { "guidance_scale", 2.0 }, { "true_cfg_scale", 2.0 } },
400);
CHECK_EQ(str_at(both["error"], "param"), std::string("guidance_scale"));
const json alpha = s.gen({ { "prompt", "x" }, { "background", "transparent" } }, 400);
CHECK_EQ(str_at(alpha["error"], "param"), std::string("background"));
}
TEST(an_auto_background_follows_the_pictures_alpha) {
if (!mm::decoder_available()) return;
Images s;
+47 -38
View File
@@ -3834,48 +3834,57 @@ int process_vram(int64_t* out) {
/* Tools and tests build and tear down movers repeatedly, and on a card every event or stream is
* a hardware queue and VRAM. A mover that staged, promoted and filled a loan gives back every
* event and every byte of device memory it took. */
/* The runtime and the driver keep some memory for the life of the process once a path is first
* used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory), and
* on some hosts about 30 MiB the first copy sets up (#124: 2 MiB, 2 MiB + 4 KiB and 31 MiB + 348
* KiB across runs on one host). So the work runs once before the count is taken, and the count
* after a second run may differ by a page and a directory, never by a buffer. */
TEST(a_mover_gives_back_every_event_and_device_byte) {
const int64_t events0 = rad_dev_live_events();
auto run = [&]() {
const int64_t events0 = rad_dev_live_events();
{
Fixture f;
build_dense(f, 8, 1 * MiB, /*host_kernel=*/false);
Config c = base_config();
c.placement = "layer_offload";
c.vram_weights_mib = 5;
c.host_pool_mib = 64;
PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0};
Plan p;
REQUIRE_EQ(Planner(in).plan(&p), RAD_OK);
Mover m;
MoverConfig mc;
REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK);
RadStream compute = nullptr;
REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK);
CHECK_OK(m.bind_compute_stream(compute));
CHECK(rad_dev_live_events() > events0);
ComputeWork work;
for (int d = 0; d < 20; ++d) {
CHECK_OK(m.begin_dispatch(d, nullptr));
work.run(compute);
CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op));
}
CHECK(m.stats().prefetched > 0);
CHECK_OK(rad_stream_sync(compute));
rad_stream_destroy(compute);
}
{
LoanRig r;
REQUIRE_EQ(r.build(), RAD_OK);
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
CHECK_OK(r.dispatch());
CHECK(r.m.stats().promotions > 0);
}
CHECK_EQ(rad_dev_live_events(), events0);
};
run();
int64_t vram0 = 0, vram1 = 0;
CHECK_OK(process_vram(&vram0));
{
Fixture f;
build_dense(f, 8, 1 * MiB, /*host_kernel=*/false);
Config c = base_config();
c.placement = "layer_offload";
c.vram_weights_mib = 5;
c.host_pool_mib = 64;
PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0};
Plan p;
REQUIRE_EQ(Planner(in).plan(&p), RAD_OK);
Mover m;
MoverConfig mc;
REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK);
RadStream compute = nullptr;
REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK);
CHECK_OK(m.bind_compute_stream(compute));
CHECK(rad_dev_live_events() > events0);
ComputeWork work;
for (int d = 0; d < 20; ++d) {
CHECK_OK(m.begin_dispatch(d, nullptr));
work.run(compute);
CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op));
}
CHECK(m.stats().prefetched > 0);
CHECK_OK(rad_stream_sync(compute));
rad_stream_destroy(compute);
}
{
LoanRig r;
REQUIRE_EQ(r.build(), RAD_OK);
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
CHECK_OK(r.dispatch());
CHECK(r.m.stats().promotions > 0);
}
CHECK_EQ(rad_dev_live_events(), events0);
run();
CHECK_OK(process_vram(&vram1));
CHECK_EQ(vram1, vram0);
CHECK(vram1 - vram0 <= 2 * MiB + 4096);
}
RAD_TEST_MAIN()
+1 -3
View File
@@ -996,12 +996,10 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) {
}
/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves
* every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M
* lowers that bound, which this case does not cover. */
* every M up to its bound, a decode step's rows and a prefill chunk alike. */
TEST(libr4d_resolves_the_mla_attention_by_rows) {
const std::string so = libr4d();
if (so.empty()) return;
if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return;
Registry r;
CHECK(r.load_plugin(so, 0) >= 0);
Geometry g;
+38 -84
View File
@@ -1,24 +1,24 @@
/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form
* (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the
* legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with
* fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding
* stay untouched.
/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. The form the launcher picks
* at each shape (one wave an output at one row, else a tile of rows x columns a wave, by M; the
* shapes reach every one) must match the arithmetic written out here bit for bit: lane l folds
* k = l, l+32, ... with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns
* and the pitch's padding stay untouched.
*
* router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan
* (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on
* random and on tied ranks, with the outputs' pitch padding untouched. */
* router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written
* out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "ref_host.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
static float legacy_model(const uint16_t* x, const float* w, int k) {
extern const char* emu_last_kernel;
static float gemm_model(const uint16_t* x, const float* w, int k) {
float lane[32];
for (int l = 0; l < 32; ++l) {
float s = 0;
@@ -115,62 +115,41 @@ static void router_cases(std::mt19937& rng, int& cases, int& fails) {
a.n_t = 4;
a.p = p;
a.n_p = 6;
auto run = [&](const char* form, std::vector<int>& ids, std::vector<float>& w) {
ids.assign((size_t)M * ip, -77);
w.assign((size_t)M * wp, -7.25f);
t[2].data = ids.data();
t[3].data = w.data();
if (form)
setenv("RADIANCE_ROUTER_SELECT", form, 1);
else
unsetenv("RADIANCE_ROUTER_SELECT");
return r4d_rad_router_sigmoid_topk(&a, nullptr);
};
std::vector<int> ids_old, ids_new;
std::vector<float> w_old, w_new;
std::vector<int> ids((size_t)M * ip, -77);
std::vector<float> w((size_t)M * wp, -7.25f);
t[2].data = ids.data();
t[3].data = w.data();
++cases;
if (run("old", ids_old, w_old) != RAD_OK) {
std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne);
++fails;
continue;
}
const int rc = r4d_rad_router_sigmoid_topk(&a, nullptr);
int bad = 0;
for (int r = 0; r < M; ++r) {
for (int r = 0; r < M && rc == RAD_OK; ++r) {
int mi[32];
float mw[32];
router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw);
bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0;
bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0;
for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77;
for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f;
bad += std::memcmp(mi, &ids[(size_t)r * ip], (size_t)k * 4) != 0;
bad += std::memcmp(mw, &w[(size_t)r * wp], (size_t)k * 4) != 0;
for (int c = k; c < ip; ++c) bad += ids[(size_t)r * ip + c] != -77;
for (int c = k; c < wp; ++c) bad += w[(size_t)r * wp + c] != -7.25f;
}
if (bad) {
std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k,
bad);
++fails;
}
++cases;
const int rc = run(nullptr, ids_new, w_new);
if (rc != RAD_OK || ids_new != ids_old ||
std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) {
std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k,
sh.ties ? " tied" : "", rc);
if (rc != RAD_OK || bad) {
std::printf("FAIL router wave select against the scan at M=%d ne=%d k=%d%s (rc %d): "
"%d\n",
M, ne, k, sh.ties ? " tied" : "", rc, bad);
++fails;
}
}
unsetenv("RADIANCE_ROUTER_SELECT");
}
int main() {
std::mt19937 rng(17);
std::normal_distribution<float> nd(0.f, 1.f);
const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2",
"4x4", "8x4", "16x2", "16x4", nullptr };
struct Shape {
int M, N, K;
};
const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 },
{ 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } };
// One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles.
const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 },
{ 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 },
{ 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } };
int fails = 0, cases = 0;
for (const Shape& sh : shapes) {
const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3;
@@ -211,49 +190,24 @@ int main() {
a.n_t = 3;
a.p = p;
a.n_p = 4;
auto run = [&](const char* form, std::vector<float>& y) {
y.assign((size_t)M * yp, -7.25f);
t[2].data = y.data();
if (form)
setenv("RADIANCE_F32_GEMM_TILE", form, 1);
else
unsetenv("RADIANCE_F32_GEMM_TILE");
return r4d_rad_gemm_nt_f32(&a, nullptr);
};
std::vector<float> legacy, got;
std::vector<float> y((size_t)M * yp, -7.25f);
t[2].data = y.data();
++cases;
if (run("legacy", legacy) != RAD_OK) {
std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K);
++fails;
continue;
}
const int rc = r4d_rad_gemm_nt_f32(&a, nullptr);
int bad = 0;
for (int r = 0; r < M; ++r) {
for (int r = 0; r < M && rc == RAD_OK; ++r) {
for (int c = 0; c < N; ++c) {
const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K);
bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0;
const float e = gemm_model(&x[(size_t)r * xp], &w[(size_t)c * K], K);
bad += std::memcmp(&e, &y[(size_t)r * yp + c], 4) != 0;
}
for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f;
for (int c = N; c < yp; ++c) bad += y[(size_t)r * yp + c] != -7.25f;
}
if (bad) {
std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N,
K, bad);
if (rc != RAD_OK || bad) {
std::printf("FAIL %s at M=%d N=%d K=%d against its model (rc %d): %d words\n",
emu_last_kernel, M, N, K, rc, bad);
++fails;
}
for (const char* const* f = forms;; ++f) {
++cases;
const int rc = run(*f, got);
const bool same =
rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0;
if (!same) {
std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N,
K, rc);
++fails;
}
if (!*f) break;
}
}
unsetenv("RADIANCE_F32_GEMM_TILE");
router_cases(rng, cases, fails);
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
+38 -30
View File
@@ -1,20 +1,22 @@
/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT
* emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must
* match the legacy 16x64 tile
* bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order.
* Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly
* idle are covered; the output's pitch padding stays untouched. */
* emulator. The form the rule picks at each shape (the decode form at one and two column tiles a
* wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile,
* which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma
* chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that
* leaves the decode form's last wave group partly idle are covered; the output's pitch padding
* stays untouched. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "ref_host.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <vector>
extern const char* emu_last_kernel;
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
RadTensor t{};
t.data = p;
@@ -32,19 +34,26 @@ int main() {
std::normal_distribution<float> nd(0.f, 1.f);
struct Shape {
int M, N, K;
const char* kernel;
};
const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 },
{ 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 },
{ 3, 128, 4096 } };
const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8",
"decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2",
"decode3x4x2", "decode2x4x4", "rows1", "rows2",
"rows4", nullptr };
const char* const dec1 = "(fp8_f32scale_decode<1, 1>)";
const char* const dec2 = "(fp8_f32scale_decode<1, 2>)";
const char* const rows = "fp8_f32scale_rows<R>";
// Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column
// tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096.
const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 },
{ 17, 256, 512, dec1 }, { 48, 128, 512, dec1 },
{ 2, 128, 256, dec1 }, { 5, 256, 128, dec1 },
{ 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 },
{ 20, 640, 256, dec2 }, { 70, 128, 384, rows },
{ 130, 128, 256, rows }, { 33, 4096, 512, rows },
{ 70, 4096, 128, rows } };
int fails = 0, cases = 0;
for (const Shape& sh : shapes) {
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8;
std::vector<uint8_t> a((size_t)M * ap), w((size_t)N * K);
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8;
std::vector<uint8_t> a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K);
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K);
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
@@ -67,10 +76,12 @@ int main() {
p[4].key = "dtype";
p[4].kind = RAD_P_STR;
p[4].sval = "fp8a8f32";
auto run = [&](const char* form, std::vector<uint16_t>& y) {
// The pitch off 16 bytes takes the legacy tile.
auto run = [&](bool legacy, std::vector<uint16_t>& y) {
y.assign((size_t)M * yp, 0x7777);
t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp)
: mat(a.data(), RAD_F8E4M3, M, K, ap);
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
setenv("RADIANCE_FP8F32_FORM", form, 1);
RadArgs ar{};
ar.t = t;
ar.n_t = 7;
@@ -80,8 +91,8 @@ int main() {
};
std::vector<uint16_t> legacy, got;
++cases;
if (run("legacy", legacy) != RAD_OK) {
std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K);
if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) {
std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel);
++fails;
continue;
}
@@ -92,19 +103,16 @@ int main() {
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
++fails;
}
for (const char* const* f = forms; *f; ++f) {
++cases;
const int rc = run(*f, got);
if (rc != RAD_OK || got != legacy) {
size_t i = 0;
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K,
rc, i);
++fails;
}
++cases;
const int rc = run(false, got);
if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) {
size_t i = 0;
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n",
emu_last_kernel, sh.kernel, M, N, K, rc, i);
++fails;
}
}
unsetenv("RADIANCE_FP8F32_FORM");
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
}
+65 -35
View File
@@ -1,15 +1,19 @@
/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form
* must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes:
* prefill per candidate and anchored, verify per candidate and anchored (after the replay of the
* accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot
* are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */
/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator, held to libref's kda_update
* (from $RADIANCE_HOME, which ctest sets) over the output and the whole state buffer, in all four
* modes: prefill per candidate and anchored, verify per candidate and anchored (after the replay
* of the accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten
* slot are mixed in, so a byte the reference leaves alone must stay as it was. The kernel's lane
* reductions sum in another order than libref's loops: f32 state within 2e-5 + 2e-5 |x|, bf16
* output within one rounding step. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <random>
#include <string>
#include <vector>
@@ -33,6 +37,32 @@ static uint16_t f2b(float f) {
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
/* libref's kda_update, through the plugin's own exports, or null. */
static RadLaunchFn load_libref() {
const char* home = std::getenv("RADIANCE_HOME");
if (!home || !*home) return nullptr;
const std::string p = std::string(home) + "/kernels/libref.so";
void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!h) return nullptr;
auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */
if (open && open() < 0) return nullptr;
auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count");
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
if (!cnt || !at) return nullptr;
for (int i = 0; i < cnt(); ++i) {
const RadKernelInfo* k = at(i);
if (k && k->op && !std::strcmp(k->op, "kda_update")) return k->launch;
}
return nullptr;
}
static float bf16_value(uint16_t b) {
const uint32_t u = (uint32_t)b << 16;
float f;
std::memcpy(&f, &u, 4);
return f;
}
struct Case {
const char* name;
const char* mode;
@@ -43,6 +73,11 @@ struct Case {
};
int main() {
const RadLaunchFn reference = load_libref();
if (!reference) {
std::printf("FAIL libref's kda_update not loadable (set RADIANCE_HOME)\n");
return 1;
}
std::mt19937 rng(41);
std::uniform_real_distribution<float> u(-1.f, 1.f);
const int64_t H = 2, D = 128, slots = 16, tokens = 9;
@@ -93,12 +128,6 @@ int main() {
{ 1, 1, 0 },
{ { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } },
};
struct Form {
const char* rows;
const char* prefetch;
};
const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" },
{ "1", "0" }, { "2", "0" }, { "4", "0" } };
int fails = 0, checks = 0;
for (const Case& c : cases) {
std::vector<float> start = state0;
@@ -106,7 +135,7 @@ int main() {
for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second;
const int64_t seqs = (int64_t)c.cu.size() - 1;
std::vector<int> idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init;
auto run = [&](std::vector<uint16_t>& out, std::vector<float>& state) {
auto run = [&](RadLaunchFn launch, std::vector<uint16_t>& out, std::vector<float>& state) {
out.assign((size_t)(tokens * H * D), 0x7777);
state = start;
RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }),
@@ -149,39 +178,40 @@ int main() {
a.n_t = 13;
a.p = p;
a.n_p = 9;
return r4d_rad_kda_update(&a, nullptr);
return launch(&a, nullptr);
};
std::vector<uint16_t> ref_out, out;
std::vector<float> ref_state, state;
setenv("RADIANCE_KDA_FORM", "old", 1);
if (run(ref_out, ref_state) != RAD_OK) {
std::printf("FAIL %s: old form refused\n", c.name);
++checks;
if (run(reference, ref_out, ref_state) != RAD_OK ||
run(r4d_rad_kda_update, out, state) != RAD_OK) {
std::printf("FAIL %s: refused\n", c.name);
++fails;
continue;
}
unsetenv("RADIANCE_KDA_FORM");
bool written = false;
for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777;
if (!written) {
std::printf("FAIL %s: the old form wrote no output\n", c.name);
++fails;
size_t bad = 0;
double out_err = 0, state_err = 0;
for (size_t i = 0; i < out.size(); ++i) {
if (out[i] == ref_out[i]) continue;
const float x = bf16_value(out[i]), y = bf16_value(ref_out[i]);
const double e = std::fabs((double)x - y);
out_err = std::max(out_err, e);
if (!std::isfinite(x) || ref_out[i] == 0x7777 || out[i] == 0x7777 ||
e > 1e-6 + 0.008 * std::fabs(y))
++bad;
}
for (const Form& f : forms) {
setenv("RADIANCE_KDA_ROWS", f.rows, 1);
setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1);
++checks;
const bool same = run(out, state) == RAD_OK && out == ref_out &&
std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0;
if (!same) {
++fails;
std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n",
c.name, f.rows, f.prefetch);
}
for (size_t i = 0; i < state.size(); ++i) {
if (state[i] == ref_state[i]) continue;
const double e = std::fabs((double)state[i] - ref_state[i]);
state_err = std::max(state_err, e);
if (!std::isfinite(state[i]) || e > 2e-5 + 2e-5 * std::fabs(ref_state[i])) ++bad;
}
unsetenv("RADIANCE_KDA_ROWS");
unsetenv("RADIANCE_KDA_PREFETCH");
std::printf("%-24s output max %.3g, state max %.3g%s\n", c.name, out_err, state_err,
!written ? " NO OUTPUT" : bad ? " FAIL" : "");
if (!written || bad) ++fails;
}
std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails,
checks);
std::printf("kda_update against libref: %d of %d within bounds\n", checks - fails, checks);
return fails ? 1 : 0;
}
+123 -160
View File
@@ -1,8 +1,9 @@
/* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator.
* Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the
* row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and
* comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots
* are zero. Every form is also held to the old dispatch, bit for bit. */
* comb bit for bit; the partial matrix's padding slots are zero. On 16-byte rows the vector forms
* run, and they are held bit for bit to the same operands on pitched rows, where the scalar forms
* run. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -42,148 +43,123 @@ int main() {
std::vector<float> fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix);
for (auto& v : fn) v = nd(rng) * 0.01f;
for (auto& v : base) v = nd(rng) * 0.5f;
struct Form {
const char* env;
const char* value;
};
const Form forms[] = { { nullptr, nullptr },
{ "RADIANCE_MHC_PREFILL_COEFF4", "0" },
{ "RADIANCE_MHC_PREFILL_ROWS4", "0" },
{ "RADIANCE_MHC_PREFILL_WARP", "0" } };
int fails = 0, cases = 0;
for (int64_t rows : { 1, 5, 37 }) {
const int64_t hp = W + 6, xp = n + 2;
std::vector<uint16_t> h((size_t)(rows * hp));
for (auto& v : h) v = f2b(nd(rng));
for (const Form& f : forms) {
if (f.env) setenv(f.env, f.value, 1);
RadParam coef[8]{};
coef[0] = { "M", RAD_P_INT, rows };
coef[1] = { "n", RAD_P_INT, n };
coef[2] = { "hc", RAD_P_INT, hc };
coef[3] = { "iterations", RAD_P_INT, 20 };
coef[4].key = "eps";
coef[4].kind = RAD_P_F64;
coef[4].dval = 1e-5;
coef[5].key = "hc_eps";
coef[5].kind = RAD_P_F64;
coef[5].dval = 1e-6;
coef[6].key = "dtype";
coef[6].kind = RAD_P_STR;
coef[6].sval = "bf16";
std::vector<uint16_t> x((size_t)(rows * xp), 0x7777);
std::vector<float> post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc));
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp),
mat(fn.data(), RAD_F32, mix, W, W),
vec(scale.data(), 3),
vec(base.data(), mix),
mat(x.data(), RAD_BF16, rows, n, xp),
mat(post.data(), RAD_F32, rows, hc, hc),
mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) };
RadArgs a{};
a.t = t;
a.n_t = 7;
a.p = coef;
a.n_p = 7;
if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) {
std::printf("FAIL mhc_pre M=%lld\n", (long long)rows);
RadParam coef[8]{};
coef[0] = { "M", RAD_P_INT, rows };
coef[1] = { "n", RAD_P_INT, n };
coef[2] = { "hc", RAD_P_INT, hc };
coef[3] = { "iterations", RAD_P_INT, 20 };
coef[4].key = "eps";
coef[4].kind = RAD_P_F64;
coef[4].dval = 1e-5;
coef[5].key = "hc_eps";
coef[5].kind = RAD_P_F64;
coef[5].dval = 1e-6;
coef[6].key = "dtype";
coef[6].kind = RAD_P_STR;
coef[6].sval = "bf16";
std::vector<uint16_t> x((size_t)(rows * xp), 0x7777);
std::vector<float> post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc));
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp),
mat(fn.data(), RAD_F32, mix, W, W),
vec(scale.data(), 3),
vec(base.data(), mix),
mat(x.data(), RAD_BF16, rows, n, xp),
mat(post.data(), RAD_F32, rows, hc, hc),
mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) };
RadArgs a{};
a.t = t;
a.n_t = 7;
a.p = coef;
a.n_p = 7;
if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) {
std::printf("FAIL mhc_pre M=%lld\n", (long long)rows);
++fails;
continue;
}
for (int world : { 2, 4, 8 }) {
++cases;
const int64_t mine = total / world;
std::vector<float> gathered((size_t)(rows * total * S));
bool padded = true, launched = true;
for (int rank = 0; rank < world; ++rank) {
std::vector<float> part((size_t)(rows * mine * S), 7.0f);
RadTensor pt[3] = { t[0], t[1],
mat(part.data(), RAD_F32, rows, mine * S, mine * S) };
RadParam pp[7]{};
pp[0] = { "M", RAD_P_INT, rows };
pp[1] = { "n", RAD_P_INT, n };
pp[2] = { "hc", RAD_P_INT, hc };
pp[3] = { "chunk", RAD_P_INT, 2048 };
pp[4] = { "first", RAD_P_INT, rank * mine };
pp[5] = { "chunks", RAD_P_INT, mine };
pp[6].key = "dtype";
pp[6].kind = RAD_P_STR;
pp[6].sval = "bf16";
RadArgs pa{};
pa.t = pt;
pa.n_t = 3;
pa.p = pp;
pa.n_p = 7;
launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
for (int64_t r = 0; r < rows; ++r) {
for (int64_t c = 0; c < mine; ++c)
for (int64_t j = mix + 1; j < S; ++j)
padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f;
std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)],
&part[(size_t)(r * mine * S)], (size_t)(mine * S * 4));
}
}
std::vector<uint16_t> x2((size_t)(rows * xp), 0x7777);
std::vector<float> post2(post.size()), comb2(comb.size());
RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S),
t[0],
t[2],
t[3],
mat(x2.data(), RAD_BF16, rows, n, xp),
mat(post2.data(), RAD_F32, rows, hc, hc),
mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) };
RadParam fp[8];
std::memcpy(fp, coef, sizeof coef);
fp[6] = { "chunk", RAD_P_INT, 2048 };
fp[7].key = "dtype";
fp[7].kind = RAD_P_STR;
fp[7].sval = "bf16";
RadArgs fa{};
fa.t = ft;
fa.n_t = 7;
fa.p = fp;
fa.n_p = 8;
launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK;
const bool same = launched && x2 == x &&
std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 &&
std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0;
if (!same || !padded) {
std::printf("FAIL M=%lld world %d: %s\n", (long long)rows, world,
!launched ? "launch"
: !padded ? "padding"
: "differs");
++fails;
continue;
}
for (int world : { 2, 4, 8 }) {
++cases;
const int64_t mine = total / world;
std::vector<float> gathered((size_t)(rows * total * S));
bool padded = true, launched = true;
for (int rank = 0; rank < world; ++rank) {
std::vector<float> part((size_t)(rows * mine * S), 7.0f);
RadTensor pt[3] = { t[0], t[1],
mat(part.data(), RAD_F32, rows, mine * S, mine * S) };
RadParam pp[7]{};
pp[0] = { "M", RAD_P_INT, rows };
pp[1] = { "n", RAD_P_INT, n };
pp[2] = { "hc", RAD_P_INT, hc };
pp[3] = { "chunk", RAD_P_INT, 2048 };
pp[4] = { "first", RAD_P_INT, rank * mine };
pp[5] = { "chunks", RAD_P_INT, mine };
pp[6].key = "dtype";
pp[6].kind = RAD_P_STR;
pp[6].sval = "bf16";
RadArgs pa{};
pa.t = pt;
pa.n_t = 3;
pa.p = pp;
pa.n_p = 7;
launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
for (int64_t r = 0; r < rows; ++r) {
for (int64_t c = 0; c < mine; ++c)
for (int64_t j = mix + 1; j < S; ++j)
padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f;
std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)],
&part[(size_t)(r * mine * S)], (size_t)(mine * S * 4));
}
}
std::vector<uint16_t> x2((size_t)(rows * xp), 0x7777);
std::vector<float> post2(post.size()), comb2(comb.size());
RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S),
t[0],
t[2],
t[3],
mat(x2.data(), RAD_BF16, rows, n, xp),
mat(post2.data(), RAD_F32, rows, hc, hc),
mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) };
RadParam fp[8];
std::memcpy(fp, coef, sizeof coef);
fp[6] = { "chunk", RAD_P_INT, 2048 };
fp[7].key = "dtype";
fp[7].kind = RAD_P_STR;
fp[7].sval = "bf16";
RadArgs fa{};
fa.t = ft;
fa.n_t = 7;
fa.p = fp;
fa.n_p = 8;
launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK;
const bool same = launched && x2 == x &&
std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 &&
std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0;
if (!same || !padded) {
std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world,
f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "",
!launched ? "launch"
: !padded ? "padding"
: "differs");
++fails;
}
}
if (f.env) unsetenv(f.env);
}
}
/* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read
* below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the
* vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's
* output, bit for bit. */
struct Pin {
const char* what;
const char* finish;
const char* vec;
const char* prow;
};
const Pin pins[] = { { "rule", nullptr, nullptr, nullptr },
{ "finish scalar", "scalar", nullptr, nullptr },
{ "partials four-slot, 1 row a wave", nullptr, "1", "1" },
{ "partials four-slot, 2 rows a wave", nullptr, "1", "2" },
{ "partials four-slot, 4 rows a wave", nullptr, "1", "4" } };
auto pin = [](const char* k, const char* v) {
if (v)
setenv(k, v, 1);
else
unsetenv(k);
};
/* The vector forms (four-slot partials, the finish's 16-byte collapse, the eight-column
* mhc_post) on 16-byte rows against the scalar forms (one slot a thread, four rows and four
* coefficients a block from 32 rows, the per-output mhc_post) on the same operands with the
* residual pitched by two elements: mhc_pre's x, post and comb, mhc_pre_partial's matrix and
* mhc_post's output, bit for bit. */
for (int64_t rows : { 1, 5, 16, 37, 64 }) {
std::vector<uint16_t> h((size_t)(rows * W)), y((size_t)(rows * n));
for (auto& v : h) v = f2b(nd(rng));
for (auto& v : y) v = f2b(nd(rng));
const int64_t pitched = W + 2;
std::vector<uint16_t> hp((size_t)(rows * pitched), 0x7777);
for (int64_t r = 0; r < rows; ++r)
std::memcpy(&hp[(size_t)(r * pitched)], &h[(size_t)(r * W)], (size_t)W * 2);
RadParam coef[7]{};
coef[0] = { "M", RAD_P_INT, rows };
coef[1] = { "n", RAD_P_INT, n };
@@ -202,13 +178,13 @@ int main() {
std::vector<uint16_t> x, o;
std::vector<float> p, c, part;
};
auto run = [&](Out* r) {
auto run = [&](Out* r, const uint16_t* hd, int64_t ld) {
r->x.assign((size_t)(rows * n), 0x7777);
r->o.assign((size_t)(rows * W), 0x7777);
r->p.assign((size_t)(rows * hc), 0);
r->c.assign((size_t)(rows * hc * hc), 0);
r->part.assign((size_t)(rows * total * S), 7.0f);
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W),
RadTensor t[7] = { mat((void*)hd, RAD_BF16, rows, W, ld),
mat(fn.data(), RAD_F32, mix, W, W),
vec(scale.data(), 3),
vec(base.data(), mix),
@@ -249,34 +225,21 @@ int main() {
return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK;
};
Out ref, got;
pin("RADIANCE_MHC_FINISH", "old");
pin("RADIANCE_MHC_PARTIAL_VEC", "0");
pin("RADIANCE_MHC_POST_VEC", "0");
const bool ref_ok = run(&ref);
pin("RADIANCE_MHC_POST_VEC", nullptr);
for (const Pin& f : pins) {
++cases;
pin("RADIANCE_MHC_FINISH", f.finish);
pin("RADIANCE_MHC_PARTIAL_VEC", f.vec);
pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow);
const bool launched = ref_ok && run(&got);
const char* bad = !launched ? "launch"
: got.x != ref.x ? "x"
: std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post"
: std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb"
: std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4)
? "partials"
: got.o != ref.o ? "mhc_post"
: nullptr;
if (bad) {
std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n",
(long long)rows, f.what, bad);
++fails;
}
++cases;
const bool launched = run(&ref, hp.data(), pitched) && run(&got, h.data(), W);
const char* bad = !launched ? "launch"
: got.x != ref.x ? "x"
: std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post"
: std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb"
: std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4)
? "partials"
: got.o != ref.o ? "mhc_post"
: nullptr;
if (bad) {
std::printf("FAIL M=%lld 16-byte rows against pitched rows: %s differs\n",
(long long)rows, bad);
++fails;
}
for (const char* k :
{ "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" })
unsetenv(k);
}
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
+21 -10
View File
@@ -3,7 +3,9 @@
* tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk
* whose rows share one table, and rows past the DSA budget, where each row selects its own top
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the
* same operands: the union at the case's table width, the positional pairing on the table
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -22,7 +24,7 @@ extern "C" void r4d_mla_matrix_stats(unsigned long long* out);
namespace {
constexpr int D = 512, BS = 4;
constexpr int D = 512, BS = 4, kUnionBlocks = 520;
enum class Fill { prefill, topk, ragged, repeat };
@@ -35,6 +37,7 @@ struct Case {
bool scratch = false; /* lets the launcher split the history */
int form = 0; /* r4d_mla_matrix_pin_form */
int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */
/* Unsplit only: with scratch the widened table gives the positional run more splits. */
bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */
bool bitwise_all = false; /* both requests do (the tables agree position by position) */
bool union_falls_back = false; /* the table is wider than the union's lists */
@@ -234,14 +237,24 @@ int run(const Case& c, std::mt19937& rng) {
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
}
/* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the
* union, which must never take a second pass. */
/* Both pairings on the same operands: the positional one, on the table widened past the
* union's lists, and at the case's own width the launcher's choice, the union, which must
* never take a second pass. A tile of 16 heads has no pairing and runs once. */
const bool paired = H % 16 == 8;
const int wide = std::max(B, kUnionBlocks + 1);
std::vector<int> bt_wide((size_t)M * wide, -1);
for (int r = 0; r < M; ++r)
std::copy(bt.begin() + (size_t)r * B, bt.begin() + (size_t)(r + 1) * B,
bt_wide.begin() + (size_t)r * wide);
std::vector<uint16_t> by_pos;
int fails = 0;
for (const char* pairing : { "pos", "union" }) {
if (!paired && !std::strcmp(pairing, "union")) break;
setenv("RADIANCE_MLA_PAIR", pairing, 1);
const bool by_page = !std::strcmp(pairing, "union");
if (!paired && by_page) break;
const bool widened = paired && !by_page;
t[2] = widened ? tens(bt_wide.data(), RAD_I32, { M, wide })
: tens(bt.data(), RAD_I32, { M, B });
p[3].ival = widened ? wide : B;
std::fill(out.begin(), out.end(), 0xffff);
unsigned long long stats[3];
r4d_mla_matrix_stats(stats);
@@ -249,7 +262,6 @@ int run(const Case& c, std::mt19937& rng) {
const int rc = r4d_rad_mla_attn_matrix(&a, nullptr);
r4d_mla_matrix_pin_form(0);
r4d_mla_matrix_stats(stats);
unsetenv("RADIANCE_MLA_PAIR");
if (rc != RAD_OK) {
std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc);
++fails;
@@ -265,7 +277,6 @@ int run(const Case& c, std::mt19937& rng) {
}
bool ok = bad == 0;
std::string note;
const bool by_page = !std::strcmp(pairing, "union");
if (!by_page) {
by_pos = out;
if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) {
@@ -297,11 +308,11 @@ int run(const Case& c, std::mt19937& rng) {
std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e",
first_diff_a, diff_b, max_ab);
note += buf;
if (c.bitwise_a && first_diff_a) {
if (c.bitwise_a && !c.scratch && first_diff_a) {
note += " (request r differs)";
ok = false;
}
if (c.bitwise_all && diff_b) {
if (c.bitwise_all && !c.scratch && diff_b) {
note += " (request r+1 differs)";
ok = false;
}
+129 -229
View File
@@ -1,30 +1,28 @@
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form
* the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit,
* and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group
* a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale *
* E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows,
* dropped slots inside runs and past the routed rows, columns an odd expert does not have, a
* shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes
* and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and
* column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column
* blocks past N and the output through LDS at aligned and odd pitches. The table decode is also
* held to the arithmetic one over every code. */
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the
* rule picks at each case (named per case, so a moved bound shows) must match a host restatement
* of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh
* 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0
* scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a
* longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up
* slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped
* slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for
* odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer
* tables. The table decode is also held to the arithmetic one over every code. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include "r4d_mxfp4.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <random>
#include <string>
#include <vector>
extern const char* emu_last_kernel;
/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its
* byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */
/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes
* from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high
* nibbles' bytes interleave in k order. */
static uint32_t fp4x4_ref(uint32_t n) {
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
const uint32_t mask = (flag << 5) - (flag >> 3);
@@ -76,6 +74,7 @@ struct Case {
bool sorted_a, tables, exceptional;
std::vector<int> runs;
int tail; // dropped slots past the routed rows
const char* kernel; // the form the rule picks
};
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
@@ -87,9 +86,6 @@ static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint1
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
}
static bool same16(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
return a.size() == b.size() && first_diff(a, b) == a.size();
}
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
std::vector<int64_t> stride) {
@@ -104,18 +100,30 @@ static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
return t;
}
/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */
static std::vector<int> glm_runs(std::vector<int> live) {
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
std::vector<int> runs(288, 0);
for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i];
return runs;
}
int main() {
int fails = check_decode(), cases = 1;
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)";
const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)";
const char* const groups = "moe_mxfp4_fp8_kernel";
const Case all[] = {
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 },
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6,
groups },
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
2 },
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 },
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 },
{ "decode band, row groups of 4",
2, groups },
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups },
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups },
{ "expert-major, K 384",
64,
384,
64,
@@ -126,8 +134,9 @@ int main() {
true,
false,
{ 0, 1, 15, 16, 17, 30 },
3 },
{ "decode band, row groups of 1",
3,
expert },
{ "expert-major, K 256, exceptional codes",
64,
256,
32,
@@ -138,8 +147,9 @@ int main() {
false,
true,
{ 1, 0, 3, 15, 1 },
2 },
{ "P64 jobs at 32 and 64 rows, N under a block",
2,
staged },
{ "expert-major, K 512:384, runs past 64 rows, N under a block",
96,
512,
96,
@@ -150,8 +160,9 @@ int main() {
false,
false,
{ 32, 33, 31, 96, 128, 129, 0, 2 },
9 },
{ "P64 resident A, column tiles cut",
9,
expert },
{ "expert-major, K 256:128, column tiles cut",
192,
256,
128,
@@ -162,83 +173,47 @@ int main() {
true,
true,
{ 64, 63, 65, 1, 0, 127, 17 },
5 },
};
struct Form {
const char* env;
int stage, tiles, lut;
const char* kernel;
bool prefill;
bool pipe = false;
};
/* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */
const Form forms[] = {
{ "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false },
{ "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false },
{ "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false },
{ "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false },
{ "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false },
{ "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false },
{ "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false },
{ "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false },
{ "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false },
{ "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true },
{ "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true },
{ "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true },
{ "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true },
{ "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true },
{ "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true },
{ "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true },
{ "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel<false>", true, true },
{ "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel<true>", true, true },
};
/* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS
* output at the default; the K of a case picks streamed or resident A. */
struct P64 {
int bm, bn, sk, ct, out, db = 0;
};
std::vector<P64> p64s;
for (int bm : { 32, 64 })
for (int bn : { 64, 128 })
for (int sk : { 128, 256 })
for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 });
p64s.push_back({ 64, 128, 128, 4, 1 });
p64s.push_back({ 32, 64, 256, 1, 1 });
/* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with
* resident A, the single-buffer form runs. */
for (int bm : { 32, 64 })
for (int bn : { 64, 128 })
for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 });
p64s.push_back({ 64, 128, 128, 4, 1, 1 });
static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64",
"RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP",
"RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN",
"RADIANCE_MXFP4_PREFILL_P64_BM",
"RADIANCE_MXFP4_PREFILL_P64_BN",
"RADIANCE_MXFP4_PREFILL_P64_STAGE_K",
"RADIANCE_MXFP4_PREFILL_P64_COLTILES",
"RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT",
"RADIANCE_MXFP4_PREFILL_P64_T_BM64",
"RADIANCE_MXFP4_PREFILL_P64_T_BN128",
"RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE",
"RADIANCE_MXFP4_PREFILL_P64_DB" };
/* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are
* under all of them); the widest tiles take the LDS output. */
struct Rule {
const char* t_bm64;
const char* t_bn128;
const char* t_down;
const char* streamed;
const char* resident;
};
const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>",
"<32, 64, 128, 4, true>" },
{ "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" },
{ "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } };
static const char* const kEnv[] = {
"RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS",
"RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32",
"RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS"
5,
staged },
{ "GLM TP4 down, the GLM prefill form",
4096,
512,
4096,
512,
1,
8,
true,
true,
true,
glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }),
13,
"moe_mxfp4_prefill_kernel" },
{ "GLM TP8 gate_up, P64 BM32 BN64 K256",
512,
4096,
512,
4096,
2,
8,
false,
true,
false,
glm_runs({ 200, 33, 300, 31, 200 }),
20,
"(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" },
{ "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident",
4096,
256,
4096,
256,
1,
8,
true,
true,
true,
glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }),
40,
"(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" },
};
for (const Case& c : all) {
@@ -264,21 +239,37 @@ int main() {
// A dropped slot about every eleventh row, the first rows of some runs included.
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
}
/* Stacked planes hold every expert; a pointer table names one of at most three slices a
* class, so GLM's 288 experts stay small. */
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
nexp[2] = { (E + 1) / 2, E / 2 };
std::vector<uint8_t> w[2], s[2];
std::vector<const void*> wt[2], st[2];
std::vector<std::vector<float>> wf[2];
int slices[2];
for (int q = 0; q < 2; ++q) {
w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2);
s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32);
slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q];
w[q].resize((size_t)slices[q] * n[q] * k[q] / 2);
s[q].resize((size_t)slices[q] * n[q] * k[q] / 32);
for (auto& v : w[q]) v = (uint8_t)rng();
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
for (size_t i = 0; i < s[q].size(); ++i)
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
: (uint8_t)(118 + rng() % 16);
for (int x = 0; x < nexp[q]; ++x) {
wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2);
st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32);
wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2);
st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32);
}
/* each slice's codes as the E4M3 values the table decode gives */
for (int x = 0; x < slices[q]; ++x) {
std::vector<float> f((size_t)n[q] * k[q]);
const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2;
for (size_t i = 0; i < f.size(); ++i) {
uint32_t lo, hi;
r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi);
f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
}
wf[q].push_back(std::move(f));
}
}
auto plane = [&](int q, bool scale) {
@@ -291,6 +282,8 @@ int main() {
};
/* the per-element sequence, on the host */
std::vector<float> af(a.size());
for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]);
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
for (int r = 0; r < T; ++r)
for (int col = 0; col < OUT; ++col) {
@@ -301,21 +294,15 @@ int main() {
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
const bool valid = within < cw;
const int wn = (col / pw) * cw + within;
const uint8_t* wr =
w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2;
const uint8_t* sr =
s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32;
const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q];
const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32;
const float* arow = af.data() + (size_t)ar * ap;
float total = 0.f;
for (int kb = 0; kb < k[q]; kb += 128)
for (int g = 0; g < 4; ++g) {
float raw = 0.f;
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) {
const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u;
uint32_t lo, hi;
r4d_mxfp4_unpack8_exact(code, &lo, &hi);
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) *
rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
}
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk)
raw += arow[kk] * (valid ? wr[kk] : 0.f);
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
float scale;
@@ -329,6 +316,12 @@ int main() {
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
16); // f32_to_bf16, r4d_common.h
}
int live = 0;
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
if (live < T * OUT / 3) {
std::printf("FAIL %s: output mostly zero\n", c.name);
++fails;
}
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
@@ -365,118 +358,25 @@ int main() {
p[8] = pi("group", 128);
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
p[10] = ps("dtype", "mxfp4a8");
auto run = [&](const Form& f, std::vector<uint16_t>& y) {
y.assign((size_t)T * yp, 0x7777);
t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 });
for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1);
if (f.stage) {
setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1);
setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1);
}
setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1);
setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1);
RadArgs ar{};
ar.t = t;
ar.n_t = 9;
ar.p = p;
ar.n_p = 11;
emu_last_kernel = "";
return r4d_rad_moe_mxfp4(&ar, nullptr);
};
auto run_p64 = [&](const P64& f, std::vector<uint16_t>& y) {
const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out };
for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1);
setenv(kP64[11], f.db ? "1" : "0", 1);
const Form base = { "000000", 0, 0, 1, "", false };
const int rc = run(base, y);
setenv(kP64[0], "0", 1);
return rc;
};
const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false };
std::vector<uint16_t> legacy, got;
std::vector<uint16_t> got((size_t)T * yp, 0x7777);
t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 });
RadArgs ar{};
ar.t = t;
ar.n_t = 9;
ar.p = p;
ar.n_p = 11;
emu_last_kernel = "";
++cases;
int rc = run(alt, legacy);
if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) {
std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel);
const int rc = r4d_rad_moe_mxfp4(&ar, nullptr);
const size_t i = first_diff(got, ref);
if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) {
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: "
"%04x, want %04x)\n",
c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp,
i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0);
++fails;
continue;
}
if (!same16(legacy, ref)) {
const size_t i = first_diff(legacy, ref);
std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: "
"%04x, want %04x\n",
c.name, i / yp, i % yp, legacy[i], ref[i]);
++fails;
}
int live = 0;
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
if (live < T * OUT / 3) {
std::printf("FAIL %s: output mostly zero\n", c.name);
++fails;
}
for (const Form& f : forms) {
if (f.prefill && T < 512) continue;
++cases;
rc = run(f, got);
const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr;
if (rc != RAD_OK || !reached || !same16(got, legacy)) {
const size_t i = first_diff(got, legacy);
std::printf(
"FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first "
"word %zu\n",
c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i);
++fails;
}
}
const bool resident = NK <= 256;
for (const Rule& u : rules) {
++cases;
for (const char* v : kP64) unsetenv(v);
setenv(kP64[0], "1", 1);
setenv(kP64[1], "0", 1);
setenv(kP64[2], "0", 1);
if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1);
if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1);
if (u.t_down) setenv(kP64[10], u.t_down, 1);
const Form base = { "000000", 0, 0, 1, "", false };
rc = run(base, got);
for (const char* v : kP64) unsetenv(v);
const std::string want =
std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed);
if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) ||
!same16(got, legacy)) {
std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name,
emu_last_kernel, want.c_str(), rc, first_diff(got, legacy));
++fails;
}
}
for (const P64& f : p64s) {
++cases;
rc = run_p64(f, got);
const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64));
const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " +
std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " +
(resident ? std::to_string(f.ct) : "1") + ", " +
(resident ? "true" : "false") + (db ? ", true>" : ">");
const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr;
if (rc != RAD_OK || !reached || !same16(got, legacy)) {
const size_t i = first_diff(got, legacy);
std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want "
"%s), rc %d, "
"first word %zu (row %zu col %zu: %04x, want %04x)\n",
c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel,
want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0,
i < legacy.size() ? legacy[i] : 0);
++fails;
}
}
}
for (const char* v : kEnv) unsetenv(v);
for (const char* v : kP64) unsetenv(v);
unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K");
unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES");
unsetenv("RADIANCE_MXFP4_LUT");
unsetenv("RADIANCE_MXFP4_PREFILL_PIPE");
std::printf("%d case(s), %d failure(s)\n", cases, fails);
return fails ? 1 : 0;
}
+227 -1
View File
@@ -966,7 +966,7 @@ TEST(op_vocabulary) {
* denoiser, and the index helpers that feed them. */
"conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store",
"end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish",
"chan_split", "interleave2", "iota", "cu_repeat", "frame_store",
"chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store",
/* 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. */
@@ -979,6 +979,20 @@ TEST(op_vocabulary) {
* the fold back into patch rows and the re-noising. */
"conv3d_ndhwc", "group_norm", "tconv_dw", "resize_bilinear", "patch_fold",
"flow_renoise",
/* The joint image generators' (Krea 2, FLUX.3): attention over separate key bounds, a
* per-layer table added to every row, a learned mix of consecutive rows, and the VAE's
* channel statistics. */
"attn_cross", "table_add", "mix_rows", "chan_stats",
/* LTX-2's: its rotary over fractional coordinates, the per-head gate and the guided
* sampler step. */
"rope_split", "head_gate", "ltx_guide",
/* Its VAE's norm, resampling and patches; its vocoder's spectrogram and resampler. */
"pixel_norm", "d2s3d", "s2d3d", "pix_patch", "patch_pix8", "stft_logmel", "bwe_up",
/* Its VAE decoded in tiles: the boxes, a tile's latent, the blended stitch. */
"tile_grid", "tile_crop", "tile_stitch",
/* LTX-2.5's diffusion decoder: its rotary's voxel coordinates and its neighborhood
* attention. */
"vol_index", "attn_na3d",
};
for (const char* op : kOps) {
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
@@ -7063,6 +7077,188 @@ TEST(scale_rows_gates_each_row_by_its_scalar) {
CHECK_EQ(y2.at(2), 36.0f); CHECK_EQ(y2.at(3), 48.0f);
}
/* tile_grid: diffusers' tiled_decode boxes -- a tile every `stride` latents while it starts inside
* the axis, `tile` long or to the edge -- one row (t, h, w, t0, y0, x0, k, count) a tile, rows past
* the count zero. 29 rows at stride 14 are bands of 16, 15 and 1; 16 columns are bands of 16 and
* 2. Under `intervals` (the diffusion decoder's _tile_intervals) an axis of `tile` cells or fewer
* is one band and a last band shorter than `min` joins the one before: 61 frames at 40 / 28 are
* [0, 40) and [28, 61); 68 rows at 96 / 88 one band; 100 columns at 96 / 88, min 13, one band
* of 96 and then [88, 100) is 12 < 13, merged: [0, 100). The last time band carries `tail` more. */
TEST(tile_grid_cuts_where_tiled_decode_does) {
T g(RAD_I32, {3}); g.n({3, 29, 16});
T y(RAD_I32, {7, 8});
A a; a.t(g).t(y).i("M", 7).i("tile", 16).i("stride", 14);
CHECK_OK(run("tile_grid", a));
const int32_t want[7][8] = { { 3, 16, 16, 0, 0, 0, 0, 6 }, { 3, 16, 2, 0, 0, 14, 1, 6 },
{ 3, 15, 16, 0, 14, 0, 2, 6 }, { 3, 15, 2, 0, 14, 14, 3, 6 },
{ 3, 1, 16, 0, 28, 0, 4, 6 }, { 3, 1, 2, 0, 28, 14, 5, 6 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
for (int k = 0; k < 7; ++k)
for (int e = 0; e < 8; ++e) CHECK_EQ(y.iat(k * 8 + e), want[k][e]);
T g2(RAD_I32, {3}); g2.n({61, 68, 100});
T y2(RAD_I32, {3, 8});
A b; b.t(g2).t(y2).i("M", 3).i("tile", 96).i("stride", 88).s("rule", "intervals").i("min", 13)
.i("tile_t", 40).i("stride_t", 28).i("min_t", 6).i("tail", 8);
CHECK_OK(run("tile_grid", b));
const int32_t want2[3][8] = { { 40, 68, 100, 0, 0, 0, 0, 2 }, { 41, 68, 100, 28, 0, 0, 1, 2 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
for (int k = 0; k < 3; ++k)
for (int e = 0; e < 8; ++e) CHECK_EQ(y2.iat(k * 8 + e), want2[k][e]);
}
/* attn_na3d is attention over each query's window: on a 2 x 4 x 5 volume with a 3 x 3 x 3 window
* (2 in time, the axis's length), the window of the corner voxel (0, 0, 0) is shifted inward to
* start at (0, 0, 0), and of (1, 3, 4) to start at (0, 1, 2); against attention over exactly those
* keys. */
TEST(attn_na3d_attends_the_inward_shifted_window) {
const int64_t Tn = 2, Hn = 4, Wn = 5, V = Tn * Hn * Wn, hd = 4;
auto val = [](int64_t i) { return (float)((i * 29) % 23 - 11) / 8.0f; };
std::vector<float> qv((size_t)(V * hd)), kv((size_t)(V * hd)), vv((size_t)(V * hd));
for (int64_t i = 0; i < V * hd; ++i) { qv[(size_t)i] = val(i); kv[(size_t)i] = val(i + 7); vv[(size_t)i] = val(i + 13); }
T q(RAD_F32, {V, hd}); q.f(qv);
T k(RAD_F32, {V, hd}); k.f(kv);
T v(RAD_F32, {V, hd}); v.f(vv);
T g(RAD_I32, {3}); g.n({Tn, Hn, Wn});
T o(RAD_F32, {V, hd});
A a; a.t(q).t(k).t(v).t(g).t(o).i("M", V).i("head_dim", hd).i("kt", 3).i("kh", 3).i("kw", 3)
.s("dtype", "f32");
CHECK_OK(run("attn_na3d", a));
struct Q { int64_t t, i, j, t0, i0, j0; };
for (const Q c : { Q{ 0, 0, 0, 0, 0, 0 }, Q{ 1, 3, 4, 0, 1, 2 }, Q{ 0, 2, 2, 0, 1, 1 } }) {
const int64_t r = (c.t * Hn + c.i) * Wn + c.j;
std::vector<double> sc;
std::vector<int64_t> keys;
for (int64_t a1 = c.t0; a1 < c.t0 + 2; ++a1)
for (int64_t b1 = c.i0; b1 < c.i0 + 3; ++b1)
for (int64_t c1 = c.j0; c1 < c.j0 + 3; ++c1) {
const int64_t key = (a1 * Hn + b1) * Wn + c1;
double d = 0;
for (int64_t e = 0; e < hd; ++e) d += (double)qv[(size_t)(r * hd + e)] * kv[(size_t)(key * hd + e)];
sc.push_back(d / 2.0);
keys.push_back(key);
}
double mx = -1e30, sum = 0;
for (double x : sc) mx = std::max(mx, x);
for (double& x : sc) { x = std::exp(x - mx); sum += x; }
for (int64_t e = 0; e < hd; ++e) {
double want = 0;
for (size_t n = 0; n < keys.size(); ++n) want += sc[n] / sum * vv[(size_t)(keys[n] * hd + e)];
CHECK_NEAR(o.at(r * hd + e), want, 1e-5);
}
}
}
/* vol_index: a 2 x 2 x 3 volume's coordinates, component-major; voxel 7 is (1, 0, 1). */
TEST(vol_index_writes_each_voxels_coordinates) {
T g(RAD_I32, {3}); g.n({2, 2, 3});
T y(RAD_I32, {3, 12});
A a; a.t(g).t(y).i("M", 12);
CHECK_OK(run("vol_index", a));
CHECK_EQ(y.iat(7), 1); CHECK_EQ(y.iat(12 + 7), 0); CHECK_EQ(y.iat(24 + 7), 1);
CHECK_EQ(y.iat(11), 1); CHECK_EQ(y.iat(12 + 11), 1); CHECK_EQ(y.iat(24 + 11), 2);
}
/* tile_crop copies a box out of the volume: a 2 x 3 x 4 volume of its row indices, the 1 x 2 x 2
* box at (1, 1, 1). */
TEST(tile_crop_copies_the_box) {
T x(RAD_F32, {24, 1});
std::vector<float> v(24);
for (int i = 0; i < 24; ++i) v[(size_t)i] = (float)i;
x.f(v);
T g(RAD_I32, {3}); g.n({2, 3, 4});
T b(RAD_I32, {6}); b.n({1, 2, 2, 1, 1, 1});
T y(RAD_F32, {4, 1});
A a; a.t(x).t(g).t(b).t(y).i("M", 4).i("C", 1).s("dtype", "f32");
CHECK_OK(run("tile_crop", a));
CHECK_EQ(y.at(0), 17.0f); CHECK_EQ(y.at(1), 18.0f);
CHECK_EQ(y.at(2), 21.0f); CHECK_EQ(y.at(3), 22.0f);
}
/* tile_stitch: tiles cut from one picture stitch back to that picture's bytes (every blend mixes
* equal values; with an extent of 2 the weights are 0, 0.5 and 1, so exactly); and across a seam
* between a tile of zeros and one of ones, the first column of the right tile is the left tile's
* margin and the second their mean. A 5 x 5 latent grid at tile 4, stride 3, a latent 1 x 1 patch
* of 2 x 2 pixels: bands of 4 and 2 latents, 8 and 4 pixels, kept to 6. */
TEST(tile_stitch_blends_as_tiled_decode_and_keeps_a_cut_picture) {
const int64_t H = 5, W = 5, tile = 4, stride = 3, p = 2, Hp = H * p, Wp = W * p;
auto band = [&](int64_t L, int64_t k) { return std::min(tile, L - k * stride); };
auto band_of = [](int64_t L, int64_t k, int64_t t, int64_t s) { return std::min(t, L - k * s); };
std::vector<float> img((size_t)(Hp * Wp));
for (int64_t i = 0; i < Hp * Wp; ++i) img[(size_t)i] = (float)((i * 37) % 63 - 31) / 32.0f;
auto store = [&](auto value) {
std::vector<float> v;
for (int64_t i = 0; i < 2; ++i)
for (int64_t j = 0; j < 2; ++j)
for (int64_t py = 0; py < band(H, i); ++py) /* patch rows of the tile */
for (int64_t px = 0; px < band(W, j); ++px)
for (int64_t dx = 0; dx < p; ++dx) /* order wh: column offset outer */
for (int64_t dy = 0; dy < p; ++dy)
v.push_back(value(i, j, py * p + dy, px * p + dx));
return v;
};
auto run_stitch = [&](const std::vector<float>& tiles, std::vector<uint8_t>* out) {
T x(RAD_F32, {(int64_t)tiles.size() / (p * p), p * p}); x.f(tiles);
T g(RAD_I32, {3}); g.n({1, H, W});
T f(RAD_I32, {1}); f.n({0});
T y(RAD_U8, {Hp, Wp});
A a; a.t(x).t(g).t(f).t(y).i("M", Hp).i("tile", tile).i("stride", stride).i("scale", 1)
.i("p", p).i("C", 1).s("dtype", "f32");
CHECK_OK(run("tile_stitch", a));
out->resize((size_t)(Hp * Wp));
for (int64_t i = 0; i < Hp * Wp; ++i) (*out)[(size_t)i] = y.mem[(size_t)i];
};
std::vector<uint8_t> got;
run_stitch(store([&](int64_t i, int64_t j, int64_t yy, int64_t xx) {
return img[(size_t)((i * stride * p + yy) * Wp + j * stride * p + xx)];
}), &got);
for (int64_t i = 0; i < Hp * Wp; ++i) {
const float u = std::min(std::max(img[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f);
CHECK_EQ((int)got[(size_t)i], (int)std::nearbyint(u * 255.0f));
}
/* Left tiles zeros, right tiles ones: row 0 is 0 to column 6, the margin (0) at 6, the mean at
* 7, then 1 (bytes 128, 128, 191, 255). */
run_stitch(store([](int64_t, int64_t j, int64_t, int64_t) { return j ? 1.0f : 0.0f; }), &got);
CHECK_EQ((int)got[5], 128); CHECK_EQ((int)got[6], 128);
CHECK_EQ((int)got[7], 191); CHECK_EQ((int)got[8], 255);
/* In time too: 4 cells of 2 frames, the first one frame (7 frames), cut at tile_t 3, stride_t 2
* into cells [0, 3) (frames 0..4) and [2, 4) (frames 3..6); each tile is its box of a 7-frame
* clip, and every frame stitches back to the clip's bytes. */
const int64_t nfr = 7;
std::vector<float> clip((size_t)(nfr * Hp * Wp));
for (int64_t i = 0; i < (int64_t)clip.size(); ++i) clip[(size_t)i] = (float)((i * 53) % 61 - 30) / 32.0f;
std::vector<float> tiles3;
for (int64_t kt = 0; kt < 2; ++kt) {
const int64_t P = kt == 0 ? 0 : 3, F = kt == 0 ? 5 : 4;
for (int64_t i = 0; i < 2; ++i)
for (int64_t j = 0; j < 2; ++j)
for (int64_t f = 0; f < F; ++f)
for (int64_t py = 0; py < band_of(H, i, tile, stride); ++py)
for (int64_t px = 0; px < band_of(W, j, tile, stride); ++px)
for (int64_t dx = 0; dx < p; ++dx)
for (int64_t dy = 0; dy < p; ++dy)
tiles3.push_back(clip[(size_t)(((P + f) * Hp + i * stride * p +
py * p + dy) * Wp +
j * stride * p + px * p + dx)]);
}
{
T x(RAD_F32, {(int64_t)tiles3.size() / (p * p), p * p}); x.f(tiles3);
T g(RAD_I32, {3}); g.n({4, H, W});
T f(RAD_I32, {1}); f.n({0});
T y(RAD_U8, {nfr * Hp, Wp});
A a; a.t(x).t(g).t(f).t(y).i("M", nfr * Hp).i("tile", tile).i("stride", stride)
.i("tile_t", 3).i("stride_t", 2).i("scale", 1).i("scale_t", 2).i("p", p).i("C", 1)
.s("dtype", "f32");
CHECK_OK(run("tile_stitch", a));
int64_t bad = 0;
for (int64_t i = 0; i < nfr * Hp * Wp; ++i) {
const float u = std::min(std::max(clip[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f);
bad += (int)y.mem[(size_t)i] != (int)std::nearbyint(u * 255.0f);
}
CHECK_EQ(bad, (int64_t)0);
}
}
TEST(sigmoid_is_the_logistic_function) {
T x(RAD_F32, {1, 4}); x.f({0, 100, -100, 1});
T y(RAD_F32, {1, 4});
@@ -7749,6 +7945,7 @@ std::vector<Geo> geometries() {
G("interleave2", "M", 4, a.i("M", R).s("dtype", "f32")),
G("iota", "M", 4, a.i("M", R).i("start", 0).i("step", 1)),
G("cu_repeat", "M", 3, a.i("M", R).i("mult", 2)),
G("int_affine", "M", 3, a.i("M", R).s("src", "0 -1 2").s("mul", "2 0 4").s("add", "-1 5 -3")),
G("frame_store", "M", 2, a.i("M", R).i("n_codes", 4).i("stride", 6).i("rep", 2)
.i("skip", 0)),
G("rms_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).i("gated", 1).s("dtype", "bf16")),
@@ -7784,6 +7981,35 @@ std::vector<Geo> geometries() {
G("patch_fold", "M", 8, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2)
.s("mul", "1 2 3").s("add", "0 1 2").s("dtype", "f32")),
G("flow_renoise", "M", 3, a.i("M", R).i("n", 8).i("stream", 1).s("dtype", "f32")),
G("attn_cross", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 0)
.s("dtype", "f32").i("n_head", 2)),
G("table_add", "M", 3, a.i("M", R).i("n", 8).i("L", 3).s("dtype", "f32")),
G("mix_rows", "M", 3, a.i("M", R).i("n", 8).i("k", 4).s("dtype", "f32")),
G("chan_stats", "M", 3, a.i("M", R).i("n", 8).s("mode", "norm").s("dtype", "f32")),
G("rope_split", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).i("dim", 16)
.i("n_dims", 3).d("theta", 10000.0).s("max", "20 2048 2048")
.s("dtype", "f32")),
G("head_gate", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).s("dtype", "f32")),
G("ltx_guide", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")),
G("pixel_norm", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).s("form", "rsqrt")
.i("ileave", 2).d("mult", 2.5).s("dtype", "f32")),
/* M 7 is a cube of side 1 and 14 one of side 2, so the zero-row call sees the volume
* change. */
G("d2s3d", "M", 7, a.i("M", R).i("C", 3).i("st", 2).i("sh", 2).i("sw", 2).s("dtype", "f32")),
G("s2d3d", "M", 7, a.i("M", R).i("C", 6).i("st", 1).i("sh", 1).i("sw", 1)
.i("group", 2).s("mode", "mean").s("dtype", "f32")),
G("pix_patch", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")),
G("patch_pix8", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")),
G("stft_logmel", "M", 3, a.i("M", R).i("hop", 4).i("nfft", 8).i("n_mel", 3).i("ch", 2)
.s("dtype", "f32")),
G("bwe_up", "M", 6, a.i("M", R).i("ratio", 3).i("ch", 2).s("dtype", "f32")),
G("tile_grid", "M", 4, a.i("M", R).i("tile", 4).i("stride", 3)),
G("vol_index", "M", 7, a.i("M", R)),
G("attn_na3d", "M", 7, a.i("M", R).i("head_dim", 8).i("kt", 3).i("kh", 3).i("kw", 3)
.s("dtype", "f32")),
G("tile_crop", "M", 7, a.i("M", R).i("C", 3).s("dtype", "f32")),
G("tile_stitch", "M", 100, a.i("M", R).i("tile", 4).i("stride", 3).i("scale", 2).i("p", 2)
.i("C", 3).s("dtype", "f32")),
};
}
#undef G
+22 -3
View File
@@ -229,7 +229,7 @@ struct Fixture {
return (rad_op)(P.ops.size() - 1);
}
int start(rad::ResidencyTable* res = nullptr, bool profile = false) {
int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false) {
CtxDesc d;
d.program = &P;
d.rank = 1;
@@ -241,8 +241,8 @@ struct Fixture {
d.registry = registry;
/* The arch bodies here issue whatever a case asks, which the batch does not describe, so
* no pass may be recorded and replayed under the batch's key (a card records passes; the
* host backend cannot). */
d.record_passes = false;
* host backend cannot). A case about the recording decision itself asks for it. */
d.record_passes = record;
return ctx.init(d);
}
@@ -1869,6 +1869,25 @@ TEST(a_lane_built_mid_step_starts_behind_lane_zero) {
CHECK_EQ(dev_get(f, f.ctx.buf_ptr(y)), 4242);
}
/* A calibration tap's gram_accum sums across passes while its plugin counts the summed rows in
* step; a played pass reissues the sum without calling step (#122). A program holding one records
* no passes; one without records them wherever the backend can. */
TEST(a_program_with_a_calibration_tap_records_no_passes) {
{
Fixture f;
f.add_buffer("x", RAD_BF16, 64, 4, 0);
loose_op(f);
CHECK_OK(f.start(nullptr, false, /*record=*/true));
CHECK_EQ(f.ctx.records_passes(), rad::tape_supported());
}
Fixture f;
f.add_buffer("x", RAD_BF16, 64, 4, 0);
loose_op(f);
loose_op(f, "gram_accum");
CHECK_OK(f.start(nullptr, false, /*record=*/true));
CHECK(!f.ctx.records_passes());
}
/* ================================================================== the pass key */
/* A recorded pass is replayed while its key holds, so the key must change with every batch field
* and runtime state a pass's shape or arguments read, and must not change with the step number
+34 -19
View File
@@ -1746,6 +1746,23 @@ static Interleaved interleave_run(int64_t n, bool decoder, int steps) {
return out;
}
/* Between a commit and the next step (where an encoder pass is prepared) the committed step's
* plan names a request the scheduler may already have released: a client cancelled it and the
* server reaped it. prefill_continues() reads only an open step's plan (#127). */
TEST(prefill_continues_reads_no_committed_plan) {
Fixture f;
f.build();
CHECK_OK(f.start());
f.sch.set_stage_rows(64);
const uint64_t p = f.submit(2000, 4);
CHECK(f.sch.step() != nullptr);
CHECK(f.sch.prefill_continues());
f.commit_plain(12);
CHECK_OK(f.sch.cancel(p));
CHECK_OK(f.sch.reap(p));
CHECK(!f.sch.prefill_continues());
}
TEST(interleave_off_puts_a_chunk_in_every_step) {
const Interleaved r = interleave_run(0, /*decoder=*/true, 8);
CHECK_EQ(r.shape, std::string("CCCCCCCC"));
@@ -2717,9 +2734,9 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) {
f.build(/*blocks=*/4096, /*states=*/64);
CHECK_OK(f.start());
/* A prefill step samples nothing. Budget 128 tokens: this test walks 1 prefill +
* (kWindow-1) + 1 + kWindow = 65 steps, so 64 would run dry one step short. */
uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true);
/* A prefill step samples nothing. Budget 320 tokens: this test walks 1 prefill + one window,
* at most six windows until the floor is set and one more, 257 steps. */
uint64_t a = f.submit(160, 320, /*priority=*/0, /*ignore_eos=*/true);
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(11);
f.sch.step_finished();
@@ -2745,9 +2762,11 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) {
f.sch.step_finished();
CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0);
/* The SECOND window is the first gated one and sets the floor: positive, and no larger than
* the cumulative decode time it was drawn from. */
for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) {
/* The first gated window sets the floor: positive, and no larger than the cumulative decode
* time it was drawn from. The fixture's steps take microseconds and vary widely, so the gate
* may reject some and the window take more than kWindow steps to fill. */
for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best;
++i) {
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(14);
f.sch.step_finished();
@@ -2769,27 +2788,23 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) {
}
TEST(the_decode_floor_ignores_a_decode_step_issued_behind_a_prefill) {
/* The live defect was a raw min latching the first decode step, which is issued ahead behind
* the prefill's host-side staging and whose bracket holds no GPU work. The fix does NOT
* exclude that step -- it is a real single-sequence decode step and belongs in the floor. It
* is made harmless by averaging: the floor is a min over window means, so the one degenerate
* bracket is diluted by the honest steps sharing its window. This pins that the
* prefill-following decode step IS eligible: a full window of decode steps that BEGINS with it
* produces a floor. Under the old predecessor-phase gate the first step was dropped, so a
* window of exactly kWindow decode steps fed only kWindow-1 samples and left the floor unset
* -- this test would have failed on that design. */
/* The decode step issued behind the prefill's host-side staging is a real single-sequence
* decode step: it is eligible, and the window mean dilutes its short bracket. Decode steps
* that begin with it produce a floor. The fixture's steps take microseconds and vary widely,
* so the gate may reject some and a window take more than kWindow steps to fill. */
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64);
CHECK_OK(f.start());
uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true);
uint64_t a = f.submit(160, 256, /*priority=*/0, /*ignore_eos=*/true);
REQUIRE(f.sch.step() != nullptr); /* prefill */
f.commit_plain(21);
f.sch.step_finished();
/* Two windows: window 1 (holding the prefill-following step) is the un-gated warmup, so the
* floor only appears once a second, gated window completes. */
for (int i = 0; i < 2 * rad::DecodeFloor::kWindow; ++i) {
/* Window 1 (holding the prefill-following step) is the un-gated warmup, so the floor only
* appears once a gated window completes. */
for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best;
++i) {
REQUIRE(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE);
CHECK_EQ(f.sch.plan().n_seq_decode, 1);
+4
View File
@@ -144,6 +144,8 @@ struct FakeChatTemplate : IChatTemplate {
if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]";
if (!opt.enable_thinking) s += "[nothink]";
for (const auto& kv : opt.template_kwargs) s += "[" + kv.first + "=" + kv.second + "]";
if (!default_effort.empty() && !opt.template_kwargs.count("reasoning_effort"))
s += "[reasoning_effort=" + default_effort + "]";
size_t n_msg = 0;
int tool_msgs = 0;
for (const auto& m : messages) {
@@ -203,6 +205,8 @@ struct FakeChatTemplate : IChatTemplate {
std::string refusal;
std::string refuse_kwarg;
std::vector<std::string> efforts; /* JSON text, as the template context carries them */
/* The effort a render naming none is written as, as Qwen3.8's template writes xhigh. */
std::string default_effort;
/* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */
std::string think_open, think_close;
bool think_starts_open = false;
+58
View File
@@ -946,6 +946,14 @@ TEST(an_effort_the_template_refuses_is_answered_with_the_set_it_takes) {
CHECK_EQ(set[0], std::string("low"));
CHECK_EQ(set[1], std::string("medium"));
CHECK_EQ(set[2], std::string("xhigh"));
CHECK(f.srv->template_default_effort().empty()); /* no level renders as no level */
/* A template that writes one level when a request names none, as Qwen3.8's writes xhigh
* (#113): the probe names it. */
f.tmpl.default_effort = "\"xhigh\"";
f.srv->probe_reasoning_efforts();
CHECK_EQ(f.srv->template_default_effort(), std::string("xhigh"));
f.tmpl.default_effort.clear();
f.srv->probe_reasoning_efforts();
OaiLimits lim = f.limits();
lim.reasoning_efforts = set;
@@ -4016,6 +4024,56 @@ TEST(a_responses_request_becomes_the_chat_request_it_means) {
&echo, &e) < 0);
}
/* A namespace groups function tools (Codex sends every MCP server's tools that way). They reach
* the model flattened to <namespace>__<name>, the reply's function_call item reports the two apart,
* streamed and not, and the next turn's call and tool_choice come back joined (#119). */
TEST(a_namespaces_tools_are_offered_flat_and_answered_apart) {
OaiLimits lim;
std::string chat, echo;
ApiError e;
std::map<std::string, std::pair<std::string, std::string>> ns;
CHECK_OK(responses_to_chat(R"({
"tools":[{"type":"function","name":"plain","parameters":{"type":"object"}},
{"type":"namespace","name":"crm","description":"d","tools":[
{"type":"function","name":"find","parameters":{"type":"object"}},
{"type":"custom","name":"raw"}]}],
"tool_choice":{"type":"function","namespace":"crm","name":"find"},
"input":[{"role":"user","content":"x"},
{"type":"function_call","call_id":"c1","namespace":"crm","name":"find","arguments":"{}"},
{"type":"function_call_output","call_id":"c1","output":"y"}]})",
lim, &chat, &echo, &e, &ns));
const json c = json::parse(chat);
CHECK_EQ(c["tools"].size(), (size_t)2); /* the custom tool left out */
CHECK_EQ(c["tools"][1]["function"].value("name", ""), std::string("crm__find"));
CHECK_EQ(c["messages"][1]["tool_calls"][0]["function"].value("name", ""), std::string("crm__find"));
CHECK_EQ(c["tool_choice"]["function"].value("name", ""), std::string("crm__find"));
CHECK_EQ(ns.size(), (size_t)1);
CHECK_EQ(ns["crm__find"].first, std::string("crm"));
CHECK_EQ(json::parse(echo)["tools"].size(), (size_t)2); /* echoed as sent */
/* A flattened name may not shadow a top-level tool's. */
CHECK(responses_to_chat(R"({"input":"x","tools":[{"type":"function","name":"crm__find"},
{"type":"namespace","name":"crm","tools":[{"type":"function","name":"find"}]}]})",
lim, &chat, &echo, &e, &ns) < 0);
Fixture f;
f.sched.reply = R"(TOOL:crm__find:{"q":"P"})";
const std::string tools = R"("tools":[{"type":"namespace","name":"crm","tools":[)"
R"({"type":"function","name":"find","parameters":{"type":"object"}}]}],)";
HttpResponse r = f.post("/v1/responses", "{" + tools + R"("input":"find P"})");
CHECK_EQ(r.status, 200);
const json o = json::parse(r.body);
CHECK_EQ(o["output"][0].value("type", ""), std::string("function_call"));
CHECK_EQ(o["output"][0].value("namespace", ""), std::string("crm"));
CHECK_EQ(o["output"][0].value("name", ""), std::string("find"));
f.sched.join_all();
HttpResponse st = f.post("/v1/responses", "{" + tools + R"("stream":true,"input":"find P"})");
const std::string body = drain(st);
CHECK(has(body, R"("namespace":"crm")"));
CHECK(!has(body, "crm__find"));
f.sched.join_all();
}
TEST(the_responses_api_answers_with_a_response_object_and_its_events) {
Fixture f;
HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})");
+4 -3
View File
@@ -88,12 +88,13 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second);
}
const std::set<std::pair<std::string, std::string>> want = {
{ "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" },
{ "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" },
{ "gemma3", "" }, { "gemma4", "" },
{ "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" },
{ "llama", "fp8_e4m3" }, { "qwen35", "" },
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
{ "qwen3asr", "" },
{ "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } };
std::set<std::pair<std::string, std::string>> got;
for (const auto& [k, name] : keys) got.insert(k);
if (got != want)
+395 -3
View File
@@ -8,8 +8,10 @@
using namespace sched_fake;
#include "gen/video_driver.h"
#include "rad_plugin.h"
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
@@ -55,9 +57,13 @@ RadVideoGenDecl decl_small() {
return d;
}
/* The soundtrack's rows a latent in fake_positions' layout: the declaration's audio_streams, or its
* two channels. */
int g_audio_streams = 2;
/* The packed layout's rows, each position the row's index; a decode pass, ten rows a frame. */
int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) {
const int64_t rows = g->n_text + 2 * (int64_t)g->n_audio +
const int64_t rows = g->n_text + g_audio_streams * (int64_t)g->n_audio +
(int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2);
if (which == RAD_VPOS_DECODE) return 10 * (int64_t)g->frames;
if (pos) {
@@ -409,7 +415,7 @@ TEST(an_upscale_that_cannot_run_is_refused_at_submit) {
/* What can never run is refused at submit: an empty or long prompt, a size off the multiple,
* below the least side, over the area or the aspect, a length outside the chunks, steps outside
* 2..max. */
* 2..max. A length of 0 chunks is none named. */
TEST(a_request_that_cannot_run_is_refused_at_submit) {
VideoFixture f;
f.build();
@@ -438,9 +444,395 @@ TEST(a_request_that_cannot_run_is_refused_at_submit) {
r->height = 96;
refused(std::move(r), "size");
refused(f.req(4), "chunks");
refused(f.req(0), "chunks");
refused(f.req(1, 6), "num_inference_steps");
refused(f.req(1, 1), "num_inference_steps");
/* No length named is the model's default. */
auto none = f.req(0);
gen::VideoTicket* t = none->ticket.get();
CHECK_OK(f.drv.submit(std::move(none), &why));
CHECK_EQ(t->frames, 3);
}
/* Decoders (RadVideoGenDecl::decoders): a request's index reaches every VDECODE pass; an index past
* the list, or a frame over the decoder's area, is refused at submit. */
TEST(the_decoder_a_request_names_reaches_its_decode_passes) {
VideoFixture f;
f.build();
f.prog.vgen_str.decoders = { "vae", "diffusion" };
f.prog.vgen_str.decoder_max_area = { 64 * 64, 32 * 32 };
CHECK_OK(f.start());
std::string why;
auto r = f.req(1);
r->decoder = 1;
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); /* 64 x 32 over 32 x 32 */
CHECK(why.find("diffusion") != std::string::npos);
r = f.req(1);
r->decoder = 2;
CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL);
r = f.req(1);
r->decoder = 1;
r->width = 32;
r->height = 32;
CHECK_OK(f.drv.submit(std::move(r), &why));
int decodes = 0;
for (int i = 0; i < 20; ++i) {
const RadBatch* b = f.drv.next(i);
if (!b) break;
if (b->gen == RAD_GEN_PASS_VDECODE) {
CHECK_EQ(b->vgen_b->decoder, 1);
++decodes;
}
f.answer(0);
CHECK_OK(f.drv.done());
}
CHECK(decodes > 0);
}
/* A length head (RadVideoGenDecl::duration_out): a request that names no length is shaped at the
* default until its VCOND pass, whose prediction (ln seconds, read back) the driver turns into
* chunks -- clamped to the declared seconds, rounded half to even to frames, floored to the chunk
* grid and lifted a chunk under the minimum -- then held to the chunks the model makes. */
TEST(a_length_head_sets_the_length_after_the_prompt_pass) {
struct Case { double sec; int32_t frames; };
/* 4 fps, 2 frames a chunk + 1, 1..3 chunks, 0.5..2 s (2..8 frames): 1.3 s is 5.2 frames, 5;
* 1.125 s is 4.5, which rounds to 4 (half to even) and floors to 3; 0.1 s is held to 2
* frames, which floor to 1 and are lifted to 3; 9 s is held to 8 frames, 7 on the grid. */
const Case cases[] = { { 1.3, 5 }, { 1.125, 3 }, { 0.1, 3 }, { 9.0, 7 } };
for (const Case& k : cases) {
VideoFixture f;
f.build();
f.prog.video_gen.duration_out = 3;
f.prog.video_gen.duration_min = 0.5;
f.prog.video_gen.duration_max = 2.0;
f.prog.video_gen.duration_dtype = RAD_F32;
CHECK_OK(f.start());
std::string why;
auto r = f.req(0);
std::shared_ptr<gen::VideoTicket> t = r->ticket;
CHECK_OK(f.drv.submit(std::move(r), &why));
CHECK_EQ(t->frames, 3); /* the default, one chunk */
const RadBatch* b = f.drv.next(0);
REQUIRE(b != nullptr);
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VCOND);
REQUIRE_EQ(f.drv.readbacks().size(), (size_t)1);
CHECK_EQ(f.drv.readbacks()[0].buf, (rad_buf)3);
*static_cast<float*>(f.drv.readbacks()[0].host) = (float)std::log(k.sec);
CHECK_OK(f.drv.done());
CHECK_EQ(t->frames, k.frames);
gen::VideoEvent e;
bool to = false;
REQUIRE(t->next(&e, 0, &to));
CHECK_EQ(e.kind, (int)gen::VideoEvent::LENGTH);
CHECK_EQ(e.n, k.frames);
/* The steps run at that length. */
b = f.drv.next(1);
REQUIRE(b != nullptr);
CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VSTEP);
CHECK_EQ(b->vgen_b->geom.frames, k.frames);
}
}
/* ---- form 1 (LTX-2's FlowMatchEulerDiscrete): evaluations, not grid points */
static uint32_t bits(float v) {
uint32_t u;
std::memcpy(&u, &v, 4);
return u;
}
/* The dev schedule bit for bit against diffusers' scheduler (numpy 2.5): 30 evaluations of a
* 6144-token video shift by mu 2.7833 and stretch to end at 0.1; and 7 of a 1500-token one. */
TEST(form_one_is_ltx2s_dynamically_shifted_schedule_bit_for_bit) {
RadVideoGenDecl d = decl_small();
d.sched_kind = 1;
d.dyn_shift = 1;
d.base_shift = 0.95;
d.max_shift = 2.05;
d.base_seq = 1024;
d.max_seq = 4096;
d.shift_terminal = 0.1;
const gen::VideoSchedule s = gen::video_schedule(d, 30, 6144);
REQUIRE_EQ(s.sig_v.size(), (size_t)31);
CHECK_EQ(s.steps, 30);
const std::pair<int, uint32_t> want[] = {
{ 0, 0x3f800000u }, { 1, 0x3f7f3c87u }, { 2, 0x3f7e6c02u }, { 15, 0x3f6b19eeu },
{ 27, 0x3eff5f82u }, { 28, 0x3eb2f452u }, { 29, 0x3dccccd0u }, { 30, 0u },
};
for (const auto& w : want) CHECK_EQ(bits(s.sig_v[(size_t)w.first]), w.second);
CHECK(s.sig_a == s.sig_v);
const gen::VideoSchedule s7 = gen::video_schedule(d, 7, 1500);
const uint32_t want7[] = { 0x3f800000u, 0x3f6e0d50u, 0x3f57d30eu, 0x3f3b945eu, 0x3f167dc8u,
0x3ec74586u, 0x3dccccd0u, 0u };
REQUIRE_EQ(s7.sig_v.size(), (size_t)8);
for (int i = 0; i < 8; ++i) CHECK_EQ(bits(s7.sig_v[(size_t)i]), want7[i]);
/* One evaluation is a schedule of form 1. */
CHECK_EQ(gen::video_schedule(d, 1, 6144).steps, 1);
}
static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725,
0.421875 };
static const double kStage2[] = { 0.909375, 0.725, 0.421875 };
RadVideoGenDecl decl_distilled() {
RadVideoGenDecl d = decl_small();
d.sched_kind = 1;
d.n_rungs = 8;
d.rungs = kDistilled;
d.default_steps = d.max_steps = 8;
d.upscale_max = 2.0;
d.n_refine_rungs = 3;
d.refine_rungs = kStage2;
d.upscale_refine = 3;
return d;
}
/* A trained schedule of form 1 is its rungs as given, and with refinement the second stage's rungs
* follow the first's in place of the 0. */
TEST(form_one_rungs_are_used_as_given_and_the_refinement_follows_them) {
const RadVideoGenDecl d = decl_distilled();
const gen::VideoSchedule s = gen::video_schedule(d, 8);
REQUIRE_EQ(s.sig_v.size(), (size_t)9);
CHECK_EQ(s.steps, 8);
for (int i = 0; i < 8; ++i) CHECK_EQ(s.sig_v[(size_t)i], (float)kDistilled[i]);
CHECK_EQ(s.sig_v[8], 0.0f);
CHECK_EQ(gen::video_schedule(d, 9).steps, 0);
const gen::VideoSchedule r = gen::video_schedule(d, 8, 0, true);
REQUIRE_EQ(r.sig_v.size(), (size_t)12);
CHECK_EQ(r.steps, 11);
CHECK_EQ(r.sig_v[8], (float)kStage2[0]);
CHECK_EQ(r.sig_v[10], (float)kStage2[2]);
CHECK_EQ(r.sig_v[11], 0.0f);
}
/* Two stages: every first-stage rung at the small size, the last to the clean estimate; the
* upscale re-noises to the second stage's first sigma; the second stage's rungs at the full size.
* The request's refinement is the second stage's length or nothing. */
TEST(a_two_stage_request_runs_the_second_stages_own_rungs_after_the_upscale) {
VideoFixture f;
f.build();
f.prog.video_gen = decl_distilled();
f.prog.video_gen.rungs = nullptr;
f.prog.video_gen.refine_rungs = nullptr;
f.prog.vgen_str.rungs.assign(kDistilled, kDistilled + 8);
f.prog.vgen_str.refine_rungs.assign(kStage2, kStage2 + 3);
CHECK_OK(f.start());
std::string why;
auto bad = f.req(1, 0);
bad->width = bad->height = 64;
bad->upscale = 2.0;
bad->refine = 2;
CHECK_EQ(f.drv.submit(std::move(bad), &why), (int)RAD_E_INVAL);
CHECK(has(why, "upscale_refine_steps must be 3"));
auto r = f.req(1, 0);
r->width = r->height = 64;
r->upscale = 2.0;
auto t = r->ticket;
CHECK_OK(f.drv.submit(std::move(r), &why));
CHECK_EQ(t->steps, 11);
CHECK_EQ(t->refine, 3);
std::string kinds;
int n = 0;
for (int i = 0; i < 40; ++i) {
const RadBatch* b = f.drv.next(i);
if (!b) break;
const RadVideoGenBatch* V = b->vgen_b;
kinds += kind_of(b->gen);
if (b->gen == RAD_GEN_PASS_VSTEP) {
const float cur = n < 8 ? (float)kDistilled[n] : (float)kStage2[n - 8];
const float nxt = n == 7 || n == 10 ? 0.0f
: n < 7 ? (float)kDistilled[n + 1] : (float)kStage2[n - 7];
CHECK_EQ(V->sched[1], cur);
CHECK_EQ(V->sched[2], nxt);
CHECK_EQ(V->geom.lat_h, n < 8 ? 2 : 4);
++n;
} else if (b->gen == RAD_GEN_PASS_VUPSCALE) {
CHECK_EQ(V->sched[1], (float)kStage2[0]);
CHECK_EQ(V->sched[4], (float)kStage2[0]);
}
f.answer(0);
CHECK_OK(f.drv.done());
}
CHECK_EQ(kinds, std::string("CSSSSSSSSUSSSAD"));
CHECK_EQ(t->status(), (int)RAD_OK);
}
/* A guided model: the request's terms over the model's defaults reach every pass; the negative
* prompt rides in the VCOND pass after the prompt, each from position 0, only while a scale asks
* for the unconditional branch; the text rows of a step are the model's fixed count. */
TEST(guidance_and_the_negative_prompt_reach_the_passes) {
VideoFixture f;
f.build();
RadVideoGenDecl& d = f.prog.video_gen;
d.guidance = 1;
const double defaults[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 };
std::memcpy(d.guidance_default, defaults, sizeof defaults);
d.step_text_rows = 6;
CHECK_OK(f.start());
std::string why;
auto r = f.req(1, 3);
r->neg_tokens = { 9, 8 };
r->guidance[1] = 0.0;
CHECK_OK(f.drv.submit(std::move(r), &why));
const RadBatch* b = f.drv.next(0);
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
const RadVideoGenBatch* V = b->vgen_b;
CHECK_EQ(b->n_tok, (int64_t)5);
CHECK_EQ(b->n_seq, 2);
CHECK_EQ(V->n_neg, 2);
CHECK(std::vector<int32_t>(b->cu_seqlens, b->cu_seqlens + 3) == std::vector<int32_t>({ 0, 3, 5 }));
CHECK(std::vector<int32_t>(b->token_ids, b->token_ids + 5) ==
std::vector<int32_t>({ 1, 2, 3, 9, 8 }));
CHECK(std::vector<int32_t>(b->positions, b->positions + 5) ==
std::vector<int32_t>({ 0, 1, 2, 0, 1 }));
CHECK_EQ(V->geom.n_text, 6);
REQUIRE(V->guidance_h != nullptr);
CHECK_EQ(V->guidance_h[0], 3.0f);
CHECK_EQ(V->guidance_h[1], 0.0f);
CHECK_EQ(V->guidance_h[3], 0.7f);
CHECK_OK(f.drv.done());
b = f.drv.next(1);
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
CHECK_EQ(b->n_tok, (int64_t)(6 + 60 + 2 * 2));
CHECK_EQ(b->vgen_b->guidance_h[4], 7.0f);
/* The device copy the ops read. */
REQUIRE(b->vgen_b->guidance != nullptr);
CHECK_EQ(b->vgen_b->guidance[0], 3.0f);
CHECK_EQ(b->vgen_b->guidance[4], 7.0f);
CHECK_OK(f.drv.done());
/* Both scales 1: no unconditional branch, so no negative prompt. */
VideoFixture g;
g.build();
g.prog.video_gen = d;
CHECK_OK(g.start());
auto u = g.req(1, 3);
u->neg_tokens = { 9 };
u->guidance[0] = 1.0;
u->guidance[4] = 1.0;
CHECK_OK(g.drv.submit(std::move(u), &why));
b = g.drv.next(0);
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
CHECK_EQ(b->n_tok, (int64_t)3);
CHECK_EQ(b->n_seq, 1);
CHECK_EQ(b->vgen_b->n_neg, 0);
/* A guided request with no negative prompt cannot run; an unguided model takes no terms. */
auto m = g.req(1, 3);
why.clear();
CHECK_EQ(g.drv.submit(std::move(m), &why), (int)RAD_E_INVAL);
CHECK(has(why, "negative prompt"));
VideoFixture h;
h.build();
CHECK_OK(h.start());
auto q = h.req(1, 3);
q->guidance[2] = 2.0;
why.clear();
CHECK_EQ(h.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
CHECK(has(why, "no guidance"));
}
/* A first frame reaches the VCOND pass as bf16 x / 255 * 2 - 1 at the size the first steps run
* at, and every pass of the request says it has one; a model without image conditioning, or a
* frame of another size, is refused. */
TEST(a_first_frame_reaches_the_prompt_pass_at_the_first_steps_size) {
VideoFixture f;
f.build();
f.prog.video_gen.image_cond = 1;
f.prog.video_gen.upscale_max = 2.0;
f.prog.video_gen.upscale_refine = 1;
CHECK_OK(f.start());
std::string why;
auto r = f.req(1, 3);
r->width = r->height = 64;
r->upscale = 2.0;
r->image.assign(32 * 32 * 3, 0);
r->image[0] = 255;
r->image[1] = 128;
auto wrong = f.req(1, 3);
wrong->image.assign(64 * 32 * 3, 0);
wrong->width = wrong->height = 64;
wrong->upscale = 2.0;
CHECK_EQ(f.drv.submit(std::move(wrong), &why), (int)RAD_E_INVAL);
CHECK(has(why, "32x32"));
CHECK_OK(f.drv.submit(std::move(r), &why));
const RadBatch* b = f.drv.next(0);
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
const RadVideoGenBatch* V = b->vgen_b;
REQUIRE(V->image != nullptr);
CHECK_EQ(V->has_image, 1);
CHECK_EQ(V->image[0], rad_f32_to_bf16(1.0f));
CHECK_EQ(V->image[1], rad_f32_to_bf16(2.0f * (128.0f / 255.0f) - 1.0f));
CHECK_EQ(V->image[2], rad_f32_to_bf16(-1.0f));
CHECK_OK(f.drv.done());
b = f.drv.next(1);
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
CHECK(b->vgen_b->image == nullptr);
CHECK_EQ(b->vgen_b->has_image, 1);
VideoFixture g;
g.build();
CHECK_OK(g.start());
auto q = g.req(1, 3);
q->image.assign(64 * 32 * 3, 0);
why.clear();
CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL);
CHECK(has(why, "picture"));
}
/* A left-padded encoder's prompt ends at text_left_pad - 1, the negative prompt too; one stream of
* soundtrack rows a latent; an exact upscaler takes its factor only, over sides it divides. */
TEST(left_padded_prompts_one_audio_stream_and_an_exact_upscaler) {
VideoFixture f;
f.build();
RadVideoGenDecl& d = f.prog.video_gen;
d.guidance = 1;
d.guidance_default[0] = 3.0;
d.guidance_default[4] = 1.0;
d.text_left_pad = 8;
d.audio_streams = 1;
d.upscale_max = 2.0;
d.upscale_refine = 1;
d.upscale_exact = 1;
g_audio_streams = 1;
CHECK_OK(f.start());
std::string why;
auto r = f.req(1, 3);
r->neg_tokens = { 9, 8 };
CHECK_OK(f.drv.submit(std::move(r), &why));
const RadBatch* b = f.drv.next(0);
REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND);
CHECK(std::vector<int32_t>(b->positions, b->positions + 5) ==
std::vector<int32_t>({ 5, 6, 7, 6, 7 }));
CHECK_OK(f.drv.done());
b = f.drv.next(1);
REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP);
/* 3 text rows, 30 soundtrack latents in one stream, 2 x 2 video patches. */
CHECK_EQ(b->n_tok, (int64_t)(3 + 30 + 2 * 2));
/* The soundtrack as a (30, 1, 1) volume; the video's rows cut at its first latent frame. */
const int32_t* gd = b->vgen_b->geom_d;
CHECK(std::vector<int32_t>(gd + RAD_VGEOM_AUDIO_VOL, gd + RAD_VGEOM_AUDIO_VOL + 3) ==
std::vector<int32_t>({ 30, 1, 1 }));
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU], 0);
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 2], 4);
CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 1] * gd[RAD_VGEOM_LAT_FRAMES], 4);
CHECK_OK(f.drv.done());
auto u = f.req(1, 3);
u->width = 64;
u->height = 32;
u->upscale = 2.0;
u->neg_tokens = { 9 };
why.clear();
CHECK_EQ(f.drv.submit(std::move(u), &why), (int)RAD_E_INVAL);
CHECK(has(why, "multiples of 64"));
auto v = f.req(1, 3);
v->width = v->height = 64;
v->upscale = 1.5;
v->neg_tokens = { 9 };
why.clear();
CHECK_EQ(f.drv.submit(std::move(v), &why), (int)RAD_E_INVAL);
CHECK(has(why, "exactly 2"));
g_audio_streams = 2;
}
RAD_TEST_MAIN()
+218
View File
@@ -10,6 +10,7 @@
#include "server_fakes.h"
#include "gen/video.h"
#include "mm/media.h"
#include <chrono>
#include <thread>
@@ -65,6 +66,13 @@ struct FakeVideoGen : IVideoGen {
t.refine = r->refine > 0 ? r->refine : (int32_t)inf.upscale_refine;
}
if (finish_status == RAD_OK) {
/* A request that named no length learns the one the model chose first. */
if (r->chunks == 0) {
gen::VideoEvent l;
l.kind = gen::VideoEvent::LENGTH;
l.n = 3;
t.push(std::move(l));
}
for (int s = 1; s <= 2; ++s) {
gen::VideoEvent e;
e.kind = gen::VideoEvent::STEP;
@@ -209,6 +217,57 @@ TEST(the_generator_gets_the_size_the_chunks_and_the_steps) {
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
}
/* A model with a length head chooses the length of a request that names none or says "auto": the
* generator gets 0 chunks, the video object says "auto" until the model has chosen and then the
* length chosen. A length named is as for any model; without a head, none named is the default. */
TEST(a_length_head_chooses_the_length_of_a_request_that_names_none) {
Videos v;
HttpResponse r = v.create(Videos::body());
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().chunks, 7);
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
v.gen.inf.length_head = true;
for (const json& b : { Videos::body(), Videos::body({ { "seconds", "auto" } }) }) {
r = v.create(b);
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().chunks, 0);
json o = json::parse(r.body, nullptr, false);
CHECK_EQ(str_at(o, "seconds"), std::string("auto"));
o = v.wait(str_at(o, "id"));
CHECK_EQ(str_at(o, "status"), std::string("completed"));
CHECK_EQ(str_at(o, "seconds"), std::string("0.12")); /* 3 frames at 24 a second */
}
r = v.create(Videos::body({ { "seconds", "8" } }));
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().chunks, 11);
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
}
/* A model with more than one decoder takes `decoder` by name, the default first: the generator gets
* its index, the video object names a decoder other than the default, an unknown name or a frame
* over the decoder's area is a 400 naming the field. A model with one decoder takes no name. */
TEST(a_decoder_is_named_and_held_to_its_area) {
Videos v;
CHECK_EQ(v.refused(Videos::body({ { "decoder", "vae" } })), std::string("decoder"));
v.gen.inf.decoders = { "vae", "diffusion" };
v.gen.inf.decoder_max_area = { 1344 * 768, 512 * 256 };
HttpResponse r = v.create(Videos::body({ { "decoder", "diffusion" }, { "size", "512x256" } }));
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().decoder, 1);
json o = json::parse(r.body, nullptr, false);
CHECK_EQ(str_at(o, "decoder"), std::string("diffusion"));
v.wait(str_at(o, "id"));
r = v.create(Videos::body({ { "decoder", "vae" } }));
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().decoder, 0);
CHECK(!json::parse(r.body, nullptr, false).contains("decoder"));
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
CHECK_EQ(v.refused(Videos::body({ { "decoder", "magic" } })), std::string("decoder"));
CHECK_EQ(v.refused(Videos::body({ { "decoder", "diffusion" }, { "size", "768x512" } })),
std::string("decoder"));
}
/* Latent upscaling: refused by a model without an upscaler; with one, the factor and the refine
* steps reach the generator, a factor of 1 is none, and the refine steps need a factor. */
TEST(latent_upscale_reaches_the_generator_where_the_model_has_an_upscaler) {
@@ -340,4 +399,163 @@ TEST(the_video_routes_are_501_without_a_video_model) {
CHECK_EQ(f.get("/v1/videos").status, 501);
}
namespace {
/* A PNG of w x h, every pixel (r, g, b). */
std::string png_rgb(int32_t w, int32_t h, uint8_t r, uint8_t g, uint8_t b) {
std::vector<uint8_t> px;
for (int64_t i = 0; i < (int64_t)w * h; ++i) px.insert(px.end(), { r, g, b });
std::vector<uint8_t> file;
std::string why;
if (mm::encode_image(px.data(), w, h, 3, "png", 0, &file, &why) < 0) return std::string();
return std::string(file.begin(), file.end());
}
std::string png_url(const std::string& bytes) {
return "data:image/png;base64," + base64_encode(bytes.data(), bytes.size());
}
/* A guided model that starts from a picture, as LTX-2.5's dev weights. */
void guided(Videos& v, int32_t crf) {
VideoGenInfo& in = v.gen.inf;
in.guidance = true;
const double d[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 };
std::copy(d, d + 8, in.guidance_default);
in.default_negative = "ugly";
in.image_cond = true;
in.image_crf = crf;
in.step_evals = true;
in.upscale_max = 2.0;
in.upscale_refine = 3;
}
std::string text_of(const std::vector<int32_t>& ids) {
std::string s;
for (int32_t c : ids) s += (char)c;
return s;
}
} /* namespace */
/* Guidance terms and the negative prompt: refused by a model without guidance; on a guided one the
* named terms reach the generator (the rest NaN, the model's default), the negative prompt is
* rendered in the template (the model's own when none is named), and the video object reports the
* resolved terms. Steps count evaluations there, from 1. */
TEST(guidance_and_the_negative_prompt_reach_a_guided_model) {
{
Videos v;
CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", "x" } })),
std::string("negative_prompt"));
CHECK_EQ(v.refused(Videos::body({ { "stg_scale", 1 } })), std::string("stg_scale"));
}
Videos v;
guided(v, 0);
CHECK_EQ(v.refused(Videos::body({ { "guidance_rescale", 1.5 } })),
std::string("guidance_rescale"));
CHECK_EQ(v.refused(Videos::body({ { "audio_guidance_scale", -1 } })),
std::string("audio_guidance_scale"));
CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", 3 } })), std::string("negative_prompt"));
HttpResponse r = v.create(Videos::body({ { "guidance_scale", 5 }, { "audio_stg_scale", "0" },
{ "negative_prompt", "blurry" },
{ "num_inference_steps", 1 } }));
REQUIRE_EQ(r.status, 200);
const gen::VideoRequest& q = v.gen.last();
CHECK_EQ(q.guidance[0], 5.0);
CHECK_EQ(q.guidance[5], 0.0);
CHECK(std::isnan(q.guidance[1]) && std::isnan(q.guidance[4]));
CHECK(q.has_neg);
CHECK_EQ(text_of(q.neg_tokens), std::string("<v>blurry"));
CHECK_EQ(q.steps, 1);
json o = json::parse(r.body, nullptr, false);
CHECK_EQ(o["guidance_scale"].get<double>(), 5.0);
CHECK_EQ(o["guidance_rescale"].get<double>(), 0.7);
CHECK_EQ(o["audio_guidance_scale"].get<double>(), 7.0);
CHECK_EQ(str_at(o, "negative_prompt"), std::string("blurry"));
v.wait(str_at(o, "id"));
r = v.create(Videos::body());
REQUIRE_EQ(r.status, 200);
CHECK(!v.gen.last().has_neg);
CHECK_EQ(text_of(v.gen.last().neg_tokens), std::string("<v>ugly"));
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
/* Both scales 1: unguided, so the object names no negative prompt. */
r = v.create(Videos::body({ { "guidance_scale", 1 }, { "audio_guidance_scale", 1 } }));
REQUIRE_EQ(r.status, 200);
o = json::parse(r.body, nullptr, false);
CHECK(!o.contains("negative_prompt"));
v.wait(str_at(o, "id"));
}
/* input_reference: refused by a text-only model; on a model that starts from a picture, a data URL
* in JSON or a file in a form becomes the first frame at the size the first steps run at (the
* small size under latent upscaling), an even colour staying that colour; task i2va goes with it. */
TEST(input_reference_becomes_the_first_frame_at_the_first_steps_size) {
const std::string pic = png_rgb(300, 170, 200, 40, 90);
{
Videos v;
CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) } })),
std::string("input_reference"));
}
Videos v;
guided(v, 0);
CHECK_EQ(v.refused(Videos::body({ { "input_reference", "data:image/png;base64,AAAA" } })),
std::string("input_reference"));
CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) }, { "task", "t2va" } })),
std::string("task"));
HttpResponse r = v.create(Videos::body({ { "input_reference", { { "image_url", png_url(pic) } } },
{ "task", "i2va" } }));
REQUIRE_EQ(r.status, 200);
const gen::VideoRequest& q = v.gen.last();
REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3);
CHECK_EQ((int)q.image[0], 200);
CHECK_EQ((int)q.image[1], 40);
CHECK_EQ((int)q.image[q.image.size() - 1], 90);
json o = json::parse(r.body, nullptr, false);
CHECK(o.value("input_reference", false));
v.wait(str_at(o, "id"));
r = v.create(Videos::body({ { "input_reference", png_url(pic) }, { "size", "512x512" },
{ "latent_upscale", 2 } }));
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().image.size(), (size_t)256 * 256 * 3);
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
HttpRequest f;
f.method = "POST";
f.path = "/v1/videos";
f.form = { FormPart{ "prompt", "", "", "a boat" }, FormPart{ "size", "", "", "512x256" },
FormPart{ "input_reference", "boat.png", "image/png", pic } };
r = v.f->srv->router().dispatch(f);
REQUIRE_EQ(r.status, 200);
CHECK_EQ(v.gen.last().image.size(), (size_t)512 * 256 * 3);
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
}
/* With the model's H.264 quality the picture goes through the round trip first: an even colour
* comes back within a few levels (yuv420p's rounding), an odd size losing its last column. */
TEST(input_reference_takes_the_models_h264_round_trip) {
Videos v;
guided(v, 18);
const std::string pic = png_rgb(301, 171, 200, 40, 90);
HttpResponse r = v.create(Videos::body({ { "input_reference", png_url(pic) } }));
if (r.status == 503) return; /* a build without libx264 refuses it, as it should */
REQUIRE_EQ(r.status, 200);
const gen::VideoRequest& q = v.gen.last();
REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3);
const int want[3] = { 200, 40, 90 };
for (size_t i = 0; i < q.image.size(); i += 997)
CHECK(std::abs((int)q.image[i] - want[i % 3]) <= 3);
v.wait(str_at(json::parse(r.body, nullptr, false), "id"));
mm::Frame in, out;
in.w = 7;
in.h = 5;
in.rgb.assign(7 * 5 * 3, 128);
std::string why;
REQUIRE_EQ(mm::h264_roundtrip(in, 18, &out, &why), (int)RAD_OK);
CHECK_EQ(out.w, 6);
CHECK_EQ(out.h, 4);
}
RAD_TEST_MAIN()