Archived
radiance 1.4.0
- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against 1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20% - deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM (4096-token prefill steps, 4 sequences, a 301K-token cache) - #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the requests decoding beside it and to new arrivals, instead of taking all of it (baKon) - LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50) - a startup report: every option with its value and where it came from, the hardware, and what on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only to the same machine) - #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at once (exit status 70), instead of hanging or writing a core of tens of gigabytes - #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of crashing at the first launch - the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's libLLVM rebuilt so the same source compiles to the same kernels every time; a source build takes ROCm 10.1 or 7.2 - #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container, and hfget.sh runs under its busybox (baKon) - --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an integrated GPU instead of stopping
This commit is contained in:
1 parent
d5b65cddc6
commit
dc339b4cd2
153 files changed
+12956
-1067
No files matched your search
+13
-5
@@ -55,6 +55,14 @@ set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test)
|
||||
set(RAD_CHAT_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/chat)
|
||||
set(RAD_MEDIA_FIXTURES ${CMAKE_CURRENT_SOURCE_DIR}/data/media)
|
||||
|
||||
# libstdc++ AHEAD OF rad_core ON EVERY TEST'S LINK LINE. lld extracts an archive member to resolve
|
||||
# any undefined symbol, a shared library's imports included: ROCm 10.1's libamdhip64 imports
|
||||
# std::string::reserve, g++-14 emits that template weak in rad_graph.cpp.o, and what that object
|
||||
# needs in turn reaches dispatch.cpp.o, whose strong device calls replace the weak fakes sched_test,
|
||||
# ref_test and runtime_test run on -- with no link error, only a test on the wrong backend. With
|
||||
# libstdc++ first, the import resolves to it and no member is extracted for it.
|
||||
set(RAD_TEST_CORE stdc++ rad_core)
|
||||
|
||||
file(GLOB RAD_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*_test.cpp)
|
||||
foreach(t ${RAD_TESTS})
|
||||
get_filename_component(n ${t} NAME_WE)
|
||||
@@ -62,28 +70,28 @@ foreach(t ${RAD_TESTS})
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/core/util/rad_util.cpp)
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_TOKREF)
|
||||
add_executable(${n} ${t})
|
||||
target_link_libraries(${n} PRIVATE rad_tokref rad_core)
|
||||
target_link_libraries(${n} PRIVATE rad_tokref ${RAD_TEST_CORE})
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_TOOLS)
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/tools/kfixture.cpp
|
||||
${CMAKE_SOURCE_DIR}/tools/opshapes.cpp)
|
||||
target_link_libraries(${n} PRIVATE rad_core)
|
||||
target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/tools)
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_R4D_HOST)
|
||||
add_executable(${n} ${t} ${CMAKE_SOURCE_DIR}/libr4d/r4d_layout.cpp
|
||||
${CMAKE_SOURCE_DIR}/libr4d/r4d_fp8_layout.cpp)
|
||||
target_link_libraries(${n} PRIVATE rad_core ${CMAKE_DL_LIBS})
|
||||
target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE} ${CMAKE_DL_LIBS})
|
||||
target_include_directories(${n} PRIVATE ${CMAKE_SOURCE_DIR}/libr4d)
|
||||
target_compile_options(${n} PRIVATE -ffp-contract=off)
|
||||
elseif(n IN_LIST RAD_TESTS_WITH_GBNF_ORACLE)
|
||||
add_executable(${n} ${t} ${CMAKE_CURRENT_SOURCE_DIR}/gbnf_oracle.cpp)
|
||||
target_link_libraries(${n} PRIVATE rad_core)
|
||||
target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
|
||||
# The chat templates whose tool-call grammars the engine is held to the oracle on. Checked
|
||||
# in, because a template is a few kilobytes and the tokenizer beside it is not.
|
||||
target_compile_definitions(${n} PRIVATE
|
||||
RAD_GBNF_TEST_DATA="${CMAKE_CURRENT_SOURCE_DIR}/data/gbnf")
|
||||
else()
|
||||
add_executable(${n} ${t})
|
||||
target_link_libraries(${n} PRIVATE rad_core)
|
||||
target_link_libraries(${n} PRIVATE ${RAD_TEST_CORE})
|
||||
endif()
|
||||
if(n IN_LIST RAD_TESTS_WITH_LEGACY)
|
||||
target_link_libraries(${n} PRIVATE rad_legacy_toolparse)
|
||||
|
||||
@@ -306,6 +306,14 @@ extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) {
|
||||
(void)c; (void)layer; (void)n_expert;
|
||||
return nullptr;
|
||||
}
|
||||
/* No prefetch here: the three calls are the no-ops a core without one makes them. */
|
||||
extern "C" int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0,
|
||||
int64_t rows, int64_t n_embd) {
|
||||
(void)c; (void)next; (void)h; (void)r0; (void)rows; (void)n_embd;
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_expert_prefetch_mark(RadCtx* c) { (void)c; return RAD_OK; }
|
||||
extern "C" int rad_expert_prefetch_step(RadCtx* c, int layer) { (void)c; (void)layer; return RAD_OK; }
|
||||
/* Non-null and distinct per handle: a plugin only passes these through to rad_route_report. */
|
||||
extern "C" void* rad_weight_ptr(RadCtx* c, rad_weight w) { (void)c; return (void*)(uintptr_t)(w * 64 + 8); }
|
||||
extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void*)(uintptr_t)(b * 64 + 16); }
|
||||
@@ -316,6 +324,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void
|
||||
#include "../arch/qwen4exp_fp8/qwen4exp_fp8.cpp"
|
||||
/* And the LLaMA family, for how it reads its rotary scaling. */
|
||||
#include "../arch/llama_fp8/llama_fp8.cpp"
|
||||
/* And LFM2, whose layer schedule and short convolution are its own. */
|
||||
#include "../arch/lfm2_bf16/lfm2_bf16.cpp"
|
||||
/* The PLE block on its own: no architecture in this file declares it, and what its step() hands
|
||||
* the two windowed ops is a contract of its own (rad_block_ple.h). */
|
||||
#include <arch/rad_block_ple.h>
|
||||
@@ -3086,3 +3096,346 @@ TEST(the_per_expert_tap_keeps_each_experts_gram_whole) {
|
||||
}
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* ==================================================================== LFM2 */
|
||||
namespace {
|
||||
|
||||
/* d1-3B's graph cut to four layers: conv, conv, attention, conv -- an irregular schedule the
|
||||
* plugin must read, not derive. A VL checkpoint (it has a text_config), tied head. */
|
||||
const char* k_lfm2_keys[] = { "text_config.num_hidden_layers", "layer_types", "conv_L_cache",
|
||||
"tie_word_embeddings" };
|
||||
const char* k_lfm2_vals[] = { "4", "conv conv full_attention conv", "3", "true" };
|
||||
|
||||
RadModelMeta lfm2_meta(int n_kv = 4) {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "lfm2"; m.name = "test-lfm2"; m.quant = "";
|
||||
m.n_layers = 4; m.n_embd = 64; m.n_head = 4; m.n_head_kv = 1; m.head_dim = 16;
|
||||
m.n_ff = 128; m.n_vocab = 512; m.n_ctx_train = 32768;
|
||||
m.rms_eps = 1e-5f; m.rope_theta = 1e6f; m.rope_scale = 1.0f;
|
||||
m.n_kv = n_kv; m.kv_key = k_lfm2_keys; m.kv_val = k_lfm2_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
std::vector<std::string> lfm2_layer_ops(bool attention) {
|
||||
std::vector<std::string> v = { "rmsnorm" };
|
||||
if (attention) {
|
||||
for (const char* s : { "gemm_nt", "gemm_nt", "gemm_nt", "rmsnorm", "rmsnorm", "rope",
|
||||
"rope", "attn_paged", "kv_store", "gemm_nt" })
|
||||
v.push_back(s);
|
||||
} else {
|
||||
for (const char* s : { "gemm_nt", "mul", "causal_conv1d", "mul", "gemm_nt" })
|
||||
v.push_back(s);
|
||||
}
|
||||
v.push_back("add");
|
||||
append(v, mlp_ops(false));
|
||||
return v;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(lfm2_declares_the_checkpoints_own_schedule) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
std::vector<std::string> want = { "embed_lookup" };
|
||||
for (bool att : { false, false, true, false }) append(want, lfm2_layer_ops(att));
|
||||
for (const char* s : { "gather_rows", "rmsnorm", "logits_gemm" }) want.push_back(s);
|
||||
CHECK_EQ(join(op_names(b)), join(want));
|
||||
|
||||
/* Two state groups: paged KV bound to the one attention layer, and a conv window of
|
||||
* n_embd channels and the checkpoint's width bound to the other three. */
|
||||
REQUIRE(b.kv_groups.size() == 2);
|
||||
CHECK_EQ(b.kv_groups[0].d.kind, (int)RAD_KV_FULL);
|
||||
CHECK_EQ(b.kv_groups[1].d.kind, (int)RAD_KV_CONV);
|
||||
CHECK_EQ(b.kv_groups[1].d.conv_width, (int64_t)3);
|
||||
CHECK_EQ(b.kv_groups[1].d.n_head_kv * b.kv_groups[1].d.head_dim, (int64_t)64);
|
||||
REQUIRE(b.binds.size() == 4);
|
||||
for (const auto& bd : b.binds)
|
||||
CHECK_EQ(bd.second, bd.first == 2 ? (rad_kvgroup)1 : (rad_kvgroup)2);
|
||||
|
||||
/* A plain RMSNorm at the checkpoint's epsilon, NeoX over the whole head. */
|
||||
const RecOp* norm = find_op(b, "rmsnorm");
|
||||
CHECK_NEAR(pflt(norm, "eps"), 1e-5, 1e-9);
|
||||
CHECK_EQ(param(norm, "wadd") ? pflt(norm, "wadd") : 0.0, 0.0);
|
||||
CHECK_EQ(pstr(find_op(b, "rope"), "mode"), "neox");
|
||||
CHECK_EQ(pint(find_op(b, "rope"), "rotary_dim"), 16);
|
||||
CHECK_EQ(pint(find_op(b, "attn_paged"), "gqa"), 4);
|
||||
CHECK_EQ(pint(find_op(b, "causal_conv1d"), "width"), 3);
|
||||
|
||||
/* The VL checkpoint's names, and a tied head read from the embedding when there is no
|
||||
* lm_head of its own. */
|
||||
const RecMap* in = find_map(b, "blk.0.conv_in.weight");
|
||||
REQUIRE(in != nullptr);
|
||||
CHECK_EQ(in->src[0], "model.language_model.layers.0.conv.in_proj.weight");
|
||||
const RecMap* head = find_map(b, "output.weight");
|
||||
REQUIRE(head != nullptr && head->src.size() == 2);
|
||||
CHECK_EQ(head->src[0], "lm_head.weight");
|
||||
CHECK_EQ(head->src[1], "model.language_model.embed_tokens.weight");
|
||||
}
|
||||
|
||||
TEST(lfm2_text_checkpoint_keeps_its_names_under_model) {
|
||||
/* No text_config: a text-only LFM2, whose layers sit under `model.` */
|
||||
static const char* keys[] = { "layer_types", "conv_L_cache" };
|
||||
static const char* vals[] = { "conv conv full_attention conv", "3" };
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta();
|
||||
meta.n_kv = 2; meta.kv_key = keys; meta.kv_val = vals;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
const RecMap* q = find_map(b, "blk.2.attn_q.weight");
|
||||
REQUIRE(q != nullptr);
|
||||
CHECK_EQ(q->src[0], "model.layers.2.self_attn.q_proj.weight");
|
||||
}
|
||||
|
||||
TEST(lfm2_refuses_what_it_does_not_serve) {
|
||||
{
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta(1); /* no layer_types */
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK(lfm2_bf16::declare(&b, &meta, &ctx) < 0);
|
||||
}
|
||||
{
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta();
|
||||
RadBuildCtx ctx = build_ctx(0, 2);
|
||||
CHECK_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED);
|
||||
}
|
||||
{
|
||||
static const char* keys[] = { "layer_types", "conv_L_cache" };
|
||||
static const char* vals[] = { "conv sliding_attention conv conv", "3" };
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta();
|
||||
meta.n_kv = 2; meta.kv_key = keys; meta.kv_val = vals;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_EQ(lfm2_bf16::declare(&b, &meta, &ctx), RAD_E_UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(lfm2_issues_the_convolution_once_per_half_of_a_mixed_step) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
/* Two decode rows (a verify of 3 and a plain decode) and one prefill chunk of 5. */
|
||||
static const int32_t tok[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
static const int32_t pos[9] = { 40, 41, 42, 30, 0, 1, 2, 3, 4 };
|
||||
static const int32_t cu[4] = { 0, 3, 4, 9 };
|
||||
static const int32_t ctxl[3] = { 40, 30, 0 };
|
||||
static const int32_t nacc[3] = { 2, 1, 1 };
|
||||
static const int32_t out[3] = { 2, 3, 8 };
|
||||
static int32_t cv_idx[3] = { 4, 5, 6 };
|
||||
RadKVGroupBatch kv[2]{};
|
||||
kv[0].group = lfm2_bf16::g_model[0].kv_attn;
|
||||
kv[1].group = lfm2_bf16::g_model[0].kv_conv; kv[1].state_index = cv_idx;
|
||||
RadBatch mixed{};
|
||||
mixed.phase = RAD_PHASE_MIXED;
|
||||
mixed.n_tok = 9; mixed.n_seq = 3; mixed.max_q_len = 5;
|
||||
mixed.n_seq_decode = 2; mixed.n_tok_decode = 4;
|
||||
mixed.token_ids = tok; mixed.positions = pos; mixed.cu_seqlens = cu; mixed.ctx_lens = ctxl;
|
||||
mixed.num_accepted = nacc; mixed.n_out = 3; mixed.out_ids = out;
|
||||
mixed.n_kv_groups = 2; mixed.kv = kv;
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1; c.batch = &mixed;
|
||||
lfm2_bf16::step(&c, &mixed);
|
||||
CHECK(c.step_fail.empty());
|
||||
|
||||
int convs = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o) continue;
|
||||
if (o->op == "mul" && i.opd.size() == 3 && i.opd[0].cols > 0) {
|
||||
/* conv(B * x): the B and x thirds of the [B | C | x] row, as column slices. */
|
||||
if (i.opd[1].cols > 0) {
|
||||
CHECK_EQ(i.opd[0].offset, (int64_t)0);
|
||||
CHECK_EQ(i.opd[1].offset, (int64_t)128);
|
||||
} else {
|
||||
CHECK_EQ(i.opd[0].offset, (int64_t)64); /* C * conv(...) */
|
||||
}
|
||||
CHECK_EQ(i.opd[0].cols, (int64_t)64);
|
||||
}
|
||||
if (o->op != "causal_conv1d") continue;
|
||||
REQUIRE(i.opd.size() == 8);
|
||||
if (convs++ % 2 == 0) { /* the decode half */
|
||||
CHECK_EQ(i.n, (int64_t)4);
|
||||
CHECK_EQ(i.opd[0].rows, (int64_t)4);
|
||||
CHECK(i.opd[3].raw == (void*)cu); CHECK_EQ(i.opd[3].rows, (int64_t)3);
|
||||
CHECK(i.opd[4].raw == (void*)cv_idx);
|
||||
CHECK(i.opd[6].raw == (void*)nacc);
|
||||
} else { /* the prefill half: arrays from D, rows from the base */
|
||||
CHECK_EQ(i.n, (int64_t)9);
|
||||
CHECK_EQ(i.opd[0].rows, (int64_t)9);
|
||||
CHECK(i.opd[3].raw == (void*)(cu + 2)); CHECK_EQ(i.opd[3].rows, (int64_t)2);
|
||||
CHECK(i.opd[4].raw == (void*)(cv_idx + 2));
|
||||
CHECK(i.opd[5].raw == (void*)(ctxl + 2));
|
||||
CHECK_EQ(i.opd[6].kind, (uint8_t)RAD_OPK_NONE);
|
||||
}
|
||||
}
|
||||
CHECK_EQ(convs, 6); /* three conv layers, two halves each */
|
||||
}
|
||||
|
||||
/* ==================================================================== LFM2-VL's tower */
|
||||
namespace {
|
||||
|
||||
/* lfm2_meta's text model under a SigLIP2 tower cut to two layers of 64 (four heads of 16), d1's
|
||||
* patch, position table and unshuffle, a 96-wide projector. */
|
||||
const char* k_lfm2vl_keys[] = { "text_config.num_hidden_layers", "layer_types", "conv_L_cache",
|
||||
"tie_word_embeddings", "vision_config.model_type",
|
||||
"vision_config.num_hidden_layers", "vision_config.hidden_size",
|
||||
"vision_config.num_attention_heads", "vision_config.intermediate_size",
|
||||
"vision_config.patch_size", "vision_config.num_patches",
|
||||
"vision_config.hidden_act", "vision_config.vision_use_head",
|
||||
"downsample_factor", "projector_hidden_size",
|
||||
"projector_hidden_act", "projector_bias",
|
||||
"projector_use_layernorm", "max_num_patches" };
|
||||
const char* k_lfm2vl_vals[] = { "4", "conv conv full_attention conv", "3", "true",
|
||||
"siglip2_vision_model", "2", "64", "4", "128", "16", "256",
|
||||
"gelu_pytorch_tanh", "false", "2", "96", "gelu", "true", "false",
|
||||
"1024" };
|
||||
const char* k_lfm2vl_norm_vals[] = { "4", "conv conv full_attention conv", "3", "true",
|
||||
"siglip2_vision_model", "2", "64", "4", "128", "16", "256",
|
||||
"gelu_pytorch_tanh", "false", "2", "96", "gelu", "true", "true",
|
||||
"1024" };
|
||||
|
||||
RadModelMeta lfm2vl_meta(bool proj_norm = false) {
|
||||
RadModelMeta m = lfm2_meta();
|
||||
m.n_kv = (int)(sizeof(k_lfm2vl_keys) / sizeof(k_lfm2vl_keys[0]));
|
||||
m.kv_key = k_lfm2vl_keys;
|
||||
m.kv_val = proj_norm ? k_lfm2vl_norm_vals : k_lfm2vl_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(lfm2_vl_declares_the_siglip2_tower_and_its_projector) {
|
||||
{ /* No encoder budget: text only, whatever the container carries. */
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2vl_meta();
|
||||
RadBuildCtx ctx = vl_ctx(0);
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK(b.encoder_name.empty());
|
||||
CHECK_EQ(count_op(b, "scatter_rows"), 0);
|
||||
}
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2vl_meta();
|
||||
RadBuildCtx ctx = vl_ctx(1024);
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ(b.encoder_name, std::string("vision"));
|
||||
CHECK_EQ(b.encoder.modalities, (uint32_t)RAD_MM_IMAGE);
|
||||
CHECK_EQ(b.encoder.patch_dim, 3 * 16 * 16);
|
||||
CHECK_EQ(b.encoder.merge, 4);
|
||||
CHECK_EQ(b.encoder.max_patches, 1024);
|
||||
CHECK_EQ(b.encoder.n_embd, 64);
|
||||
CHECK_EQ(count_op(b, "scatter_rows"), 1);
|
||||
|
||||
/* 3 stem + 12 a layer + 2 post-norm + 4 projector, each mapped from the checkpoint. */
|
||||
int nv = 0;
|
||||
for (const auto& w : b.weights)
|
||||
if (w.name.rfind("v.", 0) == 0) {
|
||||
++nv;
|
||||
CHECK(find_map(b, w.name) != nullptr);
|
||||
}
|
||||
CHECK_EQ(nv, 3 + 2 * 12 + 2 + 4);
|
||||
/* q, k and v are concatenated at convert into one QKV weight and one bias. */
|
||||
const RecMap* qkv = find_map(b, "v.blk.1.qkv.weight");
|
||||
REQUIRE(qkv != nullptr);
|
||||
REQUIRE_EQ(qkv->src.size(), (size_t)3);
|
||||
CHECK_EQ(qkv->src[0],
|
||||
std::string("model.vision_tower.vision_model.encoder.layers.1.self_attn.q_proj.weight"));
|
||||
CHECK_EQ(qkv->src[2],
|
||||
std::string("model.vision_tower.vision_model.encoder.layers.1.self_attn.v_proj.weight"));
|
||||
const RecMap* l1 = find_map(b, "v.proj.fc1.weight");
|
||||
REQUIRE(l1 != nullptr);
|
||||
CHECK_EQ(l1->src[0], std::string("model.multi_modal_projector.linear_1.weight"));
|
||||
/* The projector reads four patches as one row; its first layer is erf GELU, the tower's tanh. */
|
||||
const RecWeight* w1 = find_w(b, "v.proj.fc1.weight");
|
||||
REQUIRE(w1 != nullptr);
|
||||
CHECK_EQ(w1->d.shape[0], 96);
|
||||
CHECK_EQ(w1->d.shape[1], 4 * 64);
|
||||
int tanh = 0, erf = 0;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.op == "gemm_nt_bias") {
|
||||
tanh += pstr(&o, "act") == "gelu_tanh";
|
||||
erf += pstr(&o, "act") == "gelu";
|
||||
}
|
||||
CHECK_EQ(tanh, 2);
|
||||
CHECK_EQ(erf, 1);
|
||||
/* No rotary in the tower, the position table resampled as torch's antialiased bilinear, and
|
||||
* the attention's block height bounded by the longest segment the processor makes. */
|
||||
CHECK_EQ(count_op(b, "grid_embed_aa"), 1);
|
||||
CHECK_EQ(count_op(b, "grid_embed"), 0);
|
||||
CHECK_EQ(pint(find_op(b, "attn_dense"), "max_seqlen"), 1024);
|
||||
CHECK_EQ(pint(find_op(b, "attn_dense"), "head_dim"), 16);
|
||||
|
||||
/* A projector with its layer norm declares one over the merged rows. */
|
||||
RadBuilder bn;
|
||||
RadModelMeta mn = lfm2vl_meta(true);
|
||||
CHECK_OK(lfm2_bf16::declare(&bn, &mn, &ctx));
|
||||
CHECK(find_w(bn, "v.proj.norm.weight") != nullptr);
|
||||
CHECK_EQ(count_op(bn, "layernorm"), count_op(b, "layernorm") + 1);
|
||||
}
|
||||
|
||||
TEST(lfm2_vl_encoder_pass_and_the_rows_it_scatters) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = lfm2vl_meta();
|
||||
RadBuildCtx ctx = vl_ctx(1024);
|
||||
CHECK_OK(lfm2_bf16::declare(&b, &meta, &ctx));
|
||||
|
||||
/* A tile of 8 x 8 patches and a thumbnail of 4 x 8. */
|
||||
static uint16_t pix[96 * 768];
|
||||
static int32_t coord[4 * 96];
|
||||
static const int32_t cu[] = { 0, 64, 96 };
|
||||
RadBatch batch{};
|
||||
batch.enc = RAD_MM_IMAGE;
|
||||
batch.enc_n_patch = 96;
|
||||
batch.enc_pixels = pix;
|
||||
batch.enc_coord = coord;
|
||||
batch.enc_n_seg = 2;
|
||||
batch.enc_cu = cu;
|
||||
batch.enc_max_seg = 64;
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1; c.batch = &batch;
|
||||
lfm2_bf16::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
std::vector<std::string> want = { "gemm_nt_bias", "grid_embed_aa" };
|
||||
for (int l = 0; l < 2; ++l)
|
||||
for (const char* s : { "layernorm", "gemm_nt_bias", "attn_dense", "gemm_nt_bias",
|
||||
"layernorm", "gemm_nt_bias", "gemm_nt_bias" })
|
||||
want.push_back(s);
|
||||
for (const char* s : { "layernorm", "gemm_nt_bias", "gemm_nt_bias" }) want.push_back(s);
|
||||
CHECK_EQ(join(issued_ops(b, c)), join(want));
|
||||
/* The position resample reads all four coordinate planes; the projector runs on merged rows. */
|
||||
const RecIssue* ge = issue_of(b, c, "grid_embed_aa");
|
||||
REQUIRE(ge != nullptr);
|
||||
CHECK(ge->opd[2].raw == coord);
|
||||
CHECK_EQ(ge->opd[2].rows, 4);
|
||||
CHECK_EQ(c.issues.back().n, 24);
|
||||
const RecIssue* at = issue_of(b, c, "attn_dense");
|
||||
REQUIRE(at != nullptr);
|
||||
CHECK_EQ(at->opd[1].offset, 64);
|
||||
CHECK_EQ(at->opd[2].offset, 128);
|
||||
CHECK(at->opd[3].raw == cu);
|
||||
|
||||
/* A text step with media rows puts them over the lookup, before the first layer. */
|
||||
static const int32_t tok[4] = { 1, 2, 3, 4 }, pos[4] = { 0, 1, 2, 3 }, cus[2] = { 0, 4 };
|
||||
static const int32_t ctxl[1] = { 0 }, out[1] = { 3 }, rows[2] = { 1, 2 };
|
||||
static uint16_t embd[2 * 64];
|
||||
static int32_t cv_idx[1] = { 0 };
|
||||
RadKVGroupBatch kv[2]{};
|
||||
kv[0].group = lfm2_bf16::g_model[0].kv_attn;
|
||||
kv[1].group = lfm2_bf16::g_model[0].kv_conv; kv[1].state_index = cv_idx;
|
||||
RadBatch tb{};
|
||||
tb.phase = RAD_PHASE_PREFILL;
|
||||
tb.n_tok = 4; tb.n_seq = 1; tb.max_q_len = 4;
|
||||
tb.token_ids = tok; tb.positions = pos; tb.cu_seqlens = cus; tb.ctx_lens = ctxl;
|
||||
tb.n_out = 1; tb.out_ids = out; tb.n_kv_groups = 2; tb.kv = kv;
|
||||
tb.n_mm_rows = 2; tb.mm_rows = rows; tb.mm_embd = embd;
|
||||
RadCtx ct; ct.b = &b; ct.rank = 0; ct.world = 1; ct.batch = &tb;
|
||||
lfm2_bf16::step(&ct, &tb);
|
||||
CHECK(ct.step_fail.empty());
|
||||
const std::vector<std::string> ops = issued_ops(b, ct);
|
||||
REQUIRE(ops.size() > 2);
|
||||
CHECK_EQ(ops[0], std::string("embed_lookup"));
|
||||
CHECK_EQ(ops[1], std::string("scatter_rows"));
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unistd.h>
|
||||
|
||||
using rad::DirectFile;
|
||||
@@ -281,6 +282,214 @@ TEST(memcpy_async_then_stream_sync) {
|
||||
rad_dev_free(dst, RAD_MEM_HOST);
|
||||
}
|
||||
|
||||
/* A list copy is many copies handed to the card's DMA engine at once, so what it can get wrong is
|
||||
* at the BOUNDARIES: a copy landing a few bytes off, short by its last bytes, or running into its
|
||||
* neighbour. So: dozens of copies, lengths from one word to a few hundred KiB, sources taken out of
|
||||
* order, destinations with gaps whose sentinel bytes must survive, odd lengths and unaligned
|
||||
* sources -- and the bytes read back through an ordinary copy on the same stream, which must wait
|
||||
* for the list. */
|
||||
TEST(memcpy_list_async_copies_every_segment_and_nothing_else) {
|
||||
const int nseg = 77;
|
||||
const int64_t gap = 48, slab = 16 << 20;
|
||||
Stream st;
|
||||
auto* src = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_HOST_PINNED);
|
||||
auto* dev = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_DEVICE);
|
||||
auto* back = (uint8_t*)rad_dev_alloc(slab, RAD_MEM_HOST_PINNED);
|
||||
CHECK(src && dev && back);
|
||||
if (!src || !dev || !back) return;
|
||||
fill(src, slab, 0x5EC5u);
|
||||
|
||||
std::vector<RadCopySeg> segs;
|
||||
std::vector<int64_t> s_off, d_off, len;
|
||||
int64_t d = 0, s = slab;
|
||||
for (int i = 0; i < nseg; ++i) {
|
||||
int64_t n = 16 * (1 + (int64_t)((i * 2654435761u) % 13000)); /* 16 B .. ~200 KiB */
|
||||
if (i % 19 == 7) n += 5; /* an odd length */
|
||||
s -= n + 64; /* sources backwards */
|
||||
if (i % 23 == 11) s -= 4; /* an unaligned source */
|
||||
s_off.push_back(s);
|
||||
d_off.push_back(d);
|
||||
len.push_back(n);
|
||||
d = (d + n + gap + 15) & ~(int64_t)15;
|
||||
}
|
||||
CHECK(s > 0 && d < slab);
|
||||
CHECK_OK(rad_memset_async(dev, 0xA7, slab, st.s));
|
||||
for (int i = 0; i < nseg; ++i) segs.push_back(RadCopySeg{src + s_off[i], dev + d_off[i], len[i]});
|
||||
segs.push_back(RadCopySeg{src, dev, 0}); /* nothing to copy */
|
||||
CHECK_OK(rad_memcpy_list_async(segs.data(), (int)segs.size(), 0, st.s));
|
||||
CHECK_OK(rad_memcpy_async(back, dev, slab, st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
|
||||
int bad = 0, smashed = 0;
|
||||
for (int i = 0; i < nseg; ++i) {
|
||||
if (std::memcmp(back + d_off[i], src + s_off[i], (size_t)len[i]) != 0) ++bad;
|
||||
const int64_t end = i + 1 < nseg ? d_off[i + 1] : d;
|
||||
for (int64_t j = d_off[i] + len[i]; j < end; ++j)
|
||||
if (back[j] != 0xA7) { ++smashed; break; }
|
||||
}
|
||||
CHECK_EQ(bad, 0);
|
||||
CHECK_EQ(smashed, 0);
|
||||
|
||||
rad_dev_free(src, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(dev, RAD_MEM_DEVICE);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
}
|
||||
|
||||
/* THE DMA QUEUE'S RING IS FINITE AND WRAPS. Thousands of lists of small copies write several times
|
||||
* the ring's packets, so lists land across the wrap and behind a full ring; every copy must still
|
||||
* arrive, at its own place. Every other list yields, so the gate's checks wrap as well. */
|
||||
TEST(memcpy_list_async_survives_its_ring_wrapping) {
|
||||
const int lists = 1500, per = 64;
|
||||
const int64_t each = 256, total = (int64_t)lists * per * each;
|
||||
Stream st;
|
||||
auto* src = (uint8_t*)rad_dev_alloc(total, RAD_MEM_HOST_PINNED);
|
||||
auto* dev = (uint8_t*)rad_dev_alloc(total, RAD_MEM_DEVICE);
|
||||
auto* back = (uint8_t*)rad_dev_alloc(total, RAD_MEM_HOST_PINNED);
|
||||
CHECK(src && dev && back);
|
||||
if (!src || !dev || !back) return;
|
||||
fill(src, total, 0x3A11u);
|
||||
CHECK_OK(rad_memset_async(dev, 0, total, st.s));
|
||||
std::vector<RadCopySeg> segs((size_t)per);
|
||||
for (int k = 0; k < lists; ++k) {
|
||||
for (int i = 0; i < per; ++i) {
|
||||
const int64_t at = ((int64_t)k * per + i) * each;
|
||||
segs[(size_t)i] = RadCopySeg{src + (total - each - at), dev + at, each}; /* mirrored */
|
||||
}
|
||||
CHECK_OK(rad_memcpy_list_async(segs.data(), per, k & 1 ? RAD_COPY_YIELD : 0, st.s));
|
||||
}
|
||||
CHECK_OK(rad_memcpy_async(back, dev, total, st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
int64_t bad = 0;
|
||||
for (int64_t at = 0; at < total; at += each)
|
||||
bad += std::memcmp(back + at, src + (total - each - at), (size_t)each) != 0;
|
||||
CHECK_EQ(bad, (int64_t)0);
|
||||
rad_dev_free(src, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(dev, RAD_MEM_DEVICE);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
}
|
||||
|
||||
/* THE ENGINE WRITES PAST THE L2 AND READS PAST IT. A card buffer small enough to stay in the L2 is
|
||||
* read by a kernel, overwritten by a list and read again by a kernel on the same stream: the second
|
||||
* read must see the list's bytes, not the lines the first left behind. And the other way: bytes a
|
||||
* kernel has just written, still dirty in the L2, are what a list copying them to the host must read.
|
||||
* Twelve rounds, each with new bytes. The inbound list yields, which cuts its one copy into pieces
|
||||
* that must join up exactly. */
|
||||
TEST(memcpy_list_async_is_ordered_against_the_l2_both_ways) {
|
||||
const int64_t n = 4 << 20;
|
||||
Stream st;
|
||||
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
auto* a = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
|
||||
auto* b = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
|
||||
CHECK(src && back && a && b);
|
||||
if (!src || !back || !a || !b) return;
|
||||
int stale = 0, lost = 0;
|
||||
for (int r = 0; r < 12; ++r) {
|
||||
fill(src, n, 0x1000u + (uint32_t)r);
|
||||
CHECK_OK(rad_memset_async(a, 0x40 + r, n, st.s));
|
||||
CHECK_OK(rad_memcpy_async(b, a, n, st.s)); /* a's lines into the L2 */
|
||||
const RadCopySeg in{src, a, n};
|
||||
CHECK_OK(rad_memcpy_list_async(&in, 1, RAD_COPY_YIELD, st.s)); /* in pieces */
|
||||
CHECK_OK(rad_memcpy_async(b, a, n, st.s)); /* must read the list's bytes */
|
||||
CHECK_OK(rad_memcpy_async(back, b, n, st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
stale += std::memcmp(back, src, (size_t)n) != 0;
|
||||
|
||||
CHECK_OK(rad_memset_async(b, 0x80 + r, n, st.s)); /* dirty in the L2 */
|
||||
const RadCopySeg out{b, back, n};
|
||||
CHECK_OK(rad_memcpy_list_async(&out, 1, 0, st.s));
|
||||
CHECK_OK(rad_stream_sync(st.s));
|
||||
for (int64_t i = 0; i < n; i += 4093)
|
||||
if (back[i] != (uint8_t)(0x80 + r)) { ++lost; break; }
|
||||
}
|
||||
CHECK_EQ(stale, 0);
|
||||
CHECK_EQ(lost, 0);
|
||||
rad_dev_free(src, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(a, RAD_MEM_DEVICE);
|
||||
rad_dev_free(b, RAD_MEM_DEVICE);
|
||||
}
|
||||
|
||||
/* A HELD LINK STOPS A YIELDING LIST UNTIL IT IS RELEASED. Stream `c` holds the link, then waits for
|
||||
* a long chain of fills on `slow` before it releases; a yielding list on `t`, ordered behind the
|
||||
* hold, can therefore finish only after the chain has. Without the gate the list -- 64 MiB, a few
|
||||
* milliseconds -- is done long before the chain's tens of milliseconds of fills. A backend without a
|
||||
* DMA engine holds nothing, which it shows by taking a second hold without complaint. */
|
||||
TEST(link_hold_stops_a_yielding_list_until_released) {
|
||||
const int64_t n = 64 << 20, big = 256 << 20;
|
||||
Stream c, t, slow;
|
||||
Event held, chain;
|
||||
CHECK_OK(rad_memcpy_list_async(nullptr, 0, 0, t.s)); /* the card's DMA queue, if it has one */
|
||||
CHECK_OK(rad_link_hold(c.s, 1));
|
||||
if (rad_link_hold(c.s, 1) == RAD_OK) return; /* nothing to hold on this backend */
|
||||
(void)rad_dev_last_error();
|
||||
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
|
||||
auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
auto* fat = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE);
|
||||
CHECK(src && dst && back && fat);
|
||||
if (!src || !dst || !back || !fat) { (void)rad_link_hold(c.s, 0); return; }
|
||||
fill(src, n, 0x6A7Eu);
|
||||
for (int k = 0; k < 40; ++k) CHECK_OK(rad_memset_async(fat, k, big, slow.s));
|
||||
CHECK_OK(rad_event_record(chain.e, slow.s));
|
||||
CHECK_OK(rad_event_record(held.e, c.s));
|
||||
CHECK_OK(rad_event_wait(c.s, chain.e));
|
||||
CHECK_OK(rad_link_hold(c.s, 0));
|
||||
CHECK_EQ(rad_link_hold(c.s, 0), RAD_E_STATE); /* a release must follow a hold */
|
||||
(void)rad_dev_last_error();
|
||||
|
||||
CHECK_OK(rad_event_wait(t.s, held.e));
|
||||
const RadCopySeg seg{src, dst, n};
|
||||
CHECK_OK(rad_memcpy_list_async(&seg, 1, RAD_COPY_YIELD, t.s));
|
||||
CHECK_OK(rad_stream_sync(t.s));
|
||||
CHECK_EQ(rad_event_query(chain.e), 1);
|
||||
CHECK_OK(rad_memcpy_async(back, dst, n, t.s));
|
||||
CHECK_OK(rad_stream_sync(t.s));
|
||||
CHECK(std::memcmp(back, src, (size_t)n) == 0);
|
||||
CHECK_OK(rad_stream_sync(c.s));
|
||||
CHECK_OK(rad_stream_sync(slow.s));
|
||||
rad_dev_free(src, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(dst, RAD_MEM_DEVICE);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(fat, RAD_MEM_DEVICE);
|
||||
}
|
||||
|
||||
/* A HOLD ENDED BY THE WORK IT COVERED. A collective that knows when its peers' bytes have landed
|
||||
* takes one off the word itself (rad_link_gate) and the stream records it with mode 2, so no
|
||||
* barrier follows. Here the host plays the collective: the word is odd once the hold has taken
|
||||
* effect, even once ended, a yielding list behind it runs, and a second end is refused because
|
||||
* nothing is held. */
|
||||
TEST(link_gate_word_ends_a_hold_from_the_work_it_covers) {
|
||||
const int64_t n = 4 << 20;
|
||||
Stream c, t;
|
||||
CHECK_OK(rad_memcpy_list_async(nullptr, 0, 0, t.s)); /* the card's DMA queue, if it has one */
|
||||
volatile long long* g = (volatile long long*)rad_link_gate(c.s);
|
||||
if (!g) return; /* nothing to hold on this backend */
|
||||
CHECK_OK(rad_link_hold(c.s, 1));
|
||||
CHECK_OK(rad_stream_sync(c.s));
|
||||
CHECK_EQ((int)(*g & 1), 1);
|
||||
*g = *g - 1; /* what the launch does once its bytes land */
|
||||
CHECK_OK(rad_link_hold(c.s, 2));
|
||||
CHECK_EQ((int)(*g & 1), 0);
|
||||
CHECK_EQ(rad_link_hold(c.s, 2), RAD_E_STATE);
|
||||
(void)rad_dev_last_error();
|
||||
|
||||
auto* src = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
auto* dst = (uint8_t*)rad_dev_alloc(n, RAD_MEM_DEVICE);
|
||||
auto* back = (uint8_t*)rad_dev_alloc(n, RAD_MEM_HOST_PINNED);
|
||||
CHECK(src && dst && back);
|
||||
if (!src || !dst || !back) return;
|
||||
fill(src, n, 0x9A7Eu);
|
||||
const RadCopySeg seg{src, dst, n};
|
||||
CHECK_OK(rad_memcpy_list_async(&seg, 1, RAD_COPY_YIELD, t.s));
|
||||
CHECK_OK(rad_memcpy_async(back, dst, n, t.s));
|
||||
CHECK_OK(rad_stream_sync(t.s));
|
||||
CHECK(std::memcmp(back, src, (size_t)n) == 0);
|
||||
rad_dev_free(src, RAD_MEM_HOST_PINNED);
|
||||
rad_dev_free(dst, RAD_MEM_DEVICE);
|
||||
rad_dev_free(back, RAD_MEM_HOST_PINNED);
|
||||
}
|
||||
|
||||
TEST(memset_async) {
|
||||
const int64_t n = 1 << 20;
|
||||
Stream st;
|
||||
|
||||
@@ -0,0 +1,710 @@
|
||||
/* diag_test.cpp -- the startup report (core/diag/diag.h).
|
||||
*
|
||||
* THE MACHINE IS A DIRECTORY. The collector reads /proc and /sys under a root, so every case here
|
||||
* builds the root it wants: two R9700s behind on-card switches, one of them on a root port running
|
||||
* at half its speed under load, an integrated GPU beside them, and the host files a real Linux box
|
||||
* has. The layout copies what a gfx1201 host's sysfs actually holds (KFD topology location ids,
|
||||
* pp_dpm_pcie's table, pp_od_clk_voltage's offset block), so a parser that only works on a
|
||||
* simplified fixture fails here.
|
||||
*
|
||||
* What is held down:
|
||||
* COLLECTED each fact reaches its field, every hop of a card's PCIe path included
|
||||
* CHECKED each finding fires on the machine that has the problem and stays quiet on one
|
||||
* that does not -- an idle link parked low is not a finding
|
||||
* REPORTED every option in the command line's table reaches the report, and a secret does not
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_core.h"
|
||||
#include "diag/diag.h"
|
||||
#include "gen_config.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
using namespace rad;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
struct Root {
|
||||
std::string dir;
|
||||
Root() {
|
||||
const char* t = std::getenv("TMPDIR");
|
||||
std::string base = (t && *t) ? t : "/tmp";
|
||||
char tmpl[512];
|
||||
snprintf(tmpl, sizeof tmpl, "%s/diag_test.XXXXXX", base.c_str());
|
||||
dir = mkdtemp(tmpl) ? tmpl : "";
|
||||
}
|
||||
~Root() {
|
||||
std::error_code ec;
|
||||
if (!dir.empty()) fs::remove_all(dir, ec);
|
||||
}
|
||||
void put(const std::string& rel, const std::string& text) const {
|
||||
const fs::path p = fs::path(dir) / rel.substr(1);
|
||||
fs::create_directories(p.parent_path());
|
||||
std::ofstream(p) << text;
|
||||
}
|
||||
void mkdir(const std::string& rel) const { fs::create_directories(fs::path(dir) / rel.substr(1)); }
|
||||
/* A relative symlink, as sysfs's are, so it resolves inside the root. */
|
||||
void link(const std::string& rel, const std::string& target) const {
|
||||
const fs::path p = fs::path(dir) / rel.substr(1);
|
||||
fs::create_directories(p.parent_path());
|
||||
fs::create_symlink(target, p);
|
||||
}
|
||||
};
|
||||
|
||||
/* A PCI device directory under /sys/devices and its /sys/bus/pci/devices link. `path` is the
|
||||
* device's position under the root complex, "pci0000:00/0000:00:01.1/0000:01:00.0". */
|
||||
void pci(const Root& r, const std::string& path, const std::string& cls, const std::string& cur,
|
||||
int curw, const std::string& max, int maxw) {
|
||||
const std::string bdf = path.substr(path.rfind('/') + 1);
|
||||
const std::string d = "/sys/devices/" + path;
|
||||
r.put(d + "/class", cls + "\n");
|
||||
r.put(d + "/current_link_speed", cur + "\n");
|
||||
r.put(d + "/current_link_width", std::to_string(curw) + "\n");
|
||||
r.put(d + "/max_link_speed", max + "\n");
|
||||
r.put(d + "/max_link_width", std::to_string(maxw) + "\n");
|
||||
r.link("/sys/bus/pci/devices/" + bdf, "../../../devices/" + path);
|
||||
}
|
||||
|
||||
/* An R9700 behind its on-card switch, under root port `rp`. */
|
||||
void r9700(const Root& r, const std::string& rp, const std::string& up, const std::string& down,
|
||||
const std::string& bdf, const std::string& rp_cur, int busy, int64_t cap_uw,
|
||||
const char* drm, int dpm_cur, int64_t kfd_loc, int node) {
|
||||
const std::string base = "pci0000:00/0000:00:" + rp;
|
||||
pci(r, base, "0x060400", rp_cur, 8, "32.0 GT/s PCIe", 8);
|
||||
pci(r, base + "/" + up, "0x060400", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16);
|
||||
pci(r, base + "/" + up + "/" + down, "0x060400", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16);
|
||||
const std::string path = base + "/" + up + "/" + down + "/" + bdf;
|
||||
pci(r, path, "0x030000", "32.0 GT/s PCIe", 16, "32.0 GT/s PCIe", 16);
|
||||
const std::string d = "/sys/devices/" + path;
|
||||
r.put(d + "/vendor", "0x1002\n");
|
||||
r.put(d + "/device", "0x7551\n");
|
||||
r.mkdir("/sys/bus/pci/drivers/amdgpu");
|
||||
r.link(d + "/driver", "../../../../../../../bus/pci/drivers/amdgpu");
|
||||
r.put(d + "/numa_node", "-1\n");
|
||||
r.put(d + "/power/runtime_status", "active\n");
|
||||
r.put(d + "/power/control", "auto\n");
|
||||
r.put(d + "/iommu_group/type", "identity\n");
|
||||
r.mkdir(d + "/drm/" + drm);
|
||||
r.put(d + "/mem_info_vram_total", "34208743424\n");
|
||||
r.put(d + "/mem_info_vis_vram_total", "34208743424\n");
|
||||
r.put(d + "/gpu_busy_percent", std::to_string(busy) + "\n");
|
||||
std::string pcie;
|
||||
const char* lv[] = { "0: 2.5GT/s, x8 250Mhz", "1: 16.0GT/s, x8 616Mhz", "2: 32.0GT/s, x8 1143Mhz" };
|
||||
for (int i = 0; i < 3; ++i) pcie += std::string(lv[i]) + (i == dpm_cur ? " *" : "") + "\n";
|
||||
r.put(d + "/pp_dpm_pcie", pcie);
|
||||
r.put(d + "/pp_dpm_sclk", "0: 500Mhz \n1: 1768Mhz *\n2: 2350Mhz \n");
|
||||
r.put(d + "/pp_dpm_mclk", "0: 96Mhz \n1: 456Mhz \n2: 772Mhz \n3: 875Mhz *\n4: 1124Mhz \n5: 1258Mhz \n");
|
||||
r.put(d + "/hwmon/hwmon2/name", "amdgpu\n");
|
||||
r.put(d + "/hwmon/hwmon2/power1_cap", std::to_string(cap_uw) + "\n");
|
||||
r.put(d + "/hwmon/hwmon2/power1_cap_default", "300000000\n");
|
||||
r.put(d + "/hwmon/hwmon2/power1_cap_max", "330000000\n");
|
||||
r.put(d + "/pp_od_clk_voltage",
|
||||
"OD_SCLK_OFFSET:\n0Mhz\nOD_MCLK:\n0: 97Mhz\n1: 1259MHz\nOD_RANGE:\n"
|
||||
"SCLK_OFFSET: -500Mhz 1000Mhz\nVDDGFX_OFFSET: -200mv 0mv\n"
|
||||
"OD_VDDGFX_OFFSET:\n-75mV\n");
|
||||
r.put("/sys/class/kfd/kfd/topology/nodes/" + std::to_string(node) + "/properties",
|
||||
"cpu_cores_count 0\nsimd_count 128\nlocation_id " + std::to_string(kfd_loc) +
|
||||
"\ndomain 0\ngfx_target_version 120001\n");
|
||||
}
|
||||
|
||||
/* The machine the report was written against: a 16-core desktop part, two R9700s (the second on a
|
||||
* root port parked at Gen4 while busy, and with a lower power cap), an integrated GPU. */
|
||||
void machine(const Root& r) {
|
||||
std::string cpu;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
cpu += "processor\t: " + std::to_string(i) + "\nmodel name\t: AMD Ryzen 9 7950X3D 16-Core Processor\n"
|
||||
"physical id\t: 0\ncore id\t\t: " + std::to_string(i / 2) + "\n\n";
|
||||
r.put("/proc/cpuinfo", cpu);
|
||||
r.put("/proc/meminfo", "MemTotal: 64669548 kB\nMemFree: 14000000 kB\n"
|
||||
"MemAvailable: 53000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n");
|
||||
r.put("/proc/sys/kernel/osrelease", "7.2.7-arch1-1\n");
|
||||
r.put("/etc/os-release", "NAME=\"Arch Linux\"\nPRETTY_NAME=\"Arch Linux\"\nID=arch\n");
|
||||
r.put("/proc/cmdline", "initrd=\\initramfs-linux.img root=PARTUUID=x rw iommu=pt amdgpu.ppfeaturemask=0xfff7ffff\n");
|
||||
r.put("/proc/self/cgroup", "0::/user.slice\n");
|
||||
r.put("/sys/fs/cgroup/user.slice/memory.max", "max\n");
|
||||
r.put("/sys/kernel/mm/transparent_hugepage/enabled", "[always] madvise never\n");
|
||||
r.put("/sys/kernel/mm/transparent_hugepage/defrag", "always defer defer+madvise [madvise] never\n");
|
||||
r.put("/sys/kernel/mm/transparent_hugepage/shmem_enabled", "always within_size [advise] never deny force\n");
|
||||
r.put("/sys/module/ttm/parameters/pages_limit", "8083693\n");
|
||||
r.put("/sys/module/amdgpu/parameters/cwsr_enable", "1\n");
|
||||
r.put("/proc/sys/kernel/io_uring_disabled", "0\n");
|
||||
r.put("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", "powersave\n");
|
||||
r.put("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference", "balance_performance\n");
|
||||
r.put("/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver", "amd-pstate-epp\n");
|
||||
r.mkdir("/sys/class/iommu/ivhd0");
|
||||
r.mkdir("/sys/kernel/iommu_groups/0");
|
||||
r9700(r, "01.1", "0000:01:00.0", "0000:02:00.0", "0000:03:00.0", "32.0 GT/s PCIe", 3,
|
||||
300000000, "card0", 2, 768, 1);
|
||||
r9700(r, "01.3", "0000:05:00.0", "0000:06:00.0", "0000:07:00.0", "16.0 GT/s PCIe", 90,
|
||||
280000000, "card1", 1, 1792, 2);
|
||||
/* The integrated GPU: on the root bus, a display device with its own KFD node. */
|
||||
pci(r, "pci0000:00/0000:00:08.1/0000:1b:00.0", "0x030000", "16.0 GT/s PCIe", 16, "16.0 GT/s PCIe", 16);
|
||||
r.put("/sys/devices/pci0000:00/0000:00:08.1/0000:1b:00.0/vendor", "0x1002\n");
|
||||
r.put("/sys/devices/pci0000:00/0000:00:08.1/0000:1b:00.0/device", "0x13c0\n");
|
||||
r.put("/sys/class/kfd/kfd/topology/nodes/3/properties",
|
||||
"simd_count 4\nlocation_id 6912\ndomain 0\ngfx_target_version 100306\n");
|
||||
r.put("/sys/class/kfd/kfd/topology/nodes/0/properties",
|
||||
"cpu_cores_count 32\nsimd_count 0\nlocation_id 0\ndomain 0\ngfx_target_version 0\n");
|
||||
}
|
||||
|
||||
const diag::CardFacts* card(const diag::Facts& f, const char* bdf) {
|
||||
for (const diag::CardFacts& c : f.cards) if (c.bdf == bdf) return &c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* The engine's half: the two cards are ranks 0 and 1. */
|
||||
diag::Facts served_machine(const Root& r) {
|
||||
diag::Facts f = diag::collect(r.dir);
|
||||
for (diag::CardFacts& c : f.cards) {
|
||||
if (c.bdf == "0000:03:00.0") { c.rank = 0; c.device = 0; }
|
||||
if (c.bdf == "0000:07:00.0") { c.rank = 1; c.device = 1; }
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
bool has(const std::vector<diag::Finding>& v, const char* id, diag::Finding::Level lv) {
|
||||
for (const diag::Finding& x : v) if (x.id == id && x.level == lv) return true;
|
||||
return false;
|
||||
}
|
||||
bool has(const std::vector<diag::Finding>& v, const char* id) {
|
||||
for (const diag::Finding& x : v) if (x.id == id) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ collected */
|
||||
|
||||
TEST(host_facts_reach_their_fields) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const diag::Facts f = diag::collect(r.dir);
|
||||
const diag::HostFacts& h = f.host;
|
||||
CHECK_EQ(h.cpu_model, std::string("AMD Ryzen 9 7950X3D 16-Core Processor"));
|
||||
CHECK_EQ(h.threads, 4);
|
||||
CHECK_EQ(h.cores, 2);
|
||||
CHECK_EQ(h.mem_total, (int64_t)64669548 * 1024);
|
||||
CHECK_EQ(h.mem_available, (int64_t)53000000 * 1024);
|
||||
CHECK_EQ(h.swap_total, 0);
|
||||
CHECK_EQ(h.kernel, std::string("7.2.7-arch1-1"));
|
||||
CHECK_EQ(h.distro, std::string("Arch Linux"));
|
||||
CHECK_EQ(h.cgroup_mem_limit, -2);
|
||||
CHECK_EQ(h.thp_enabled, std::string("always"));
|
||||
CHECK_EQ(h.thp_defrag, std::string("madvise"));
|
||||
CHECK_EQ(h.thp_shmem, std::string("advise"));
|
||||
CHECK_EQ(h.iommu, std::string("passthrough"));
|
||||
CHECK_EQ(h.cmdline, std::string("iommu=pt amdgpu.ppfeaturemask=0xfff7ffff"));
|
||||
CHECK_EQ(h.ttm_pages_limit, 8083693);
|
||||
CHECK_EQ(h.cwsr_enable, 1);
|
||||
CHECK_EQ(h.io_uring, std::string("available"));
|
||||
CHECK_EQ(h.cpu_governor, std::string("powersave"));
|
||||
CHECK_EQ(h.cpu_epp, std::string("balance_performance"));
|
||||
}
|
||||
|
||||
TEST(every_display_device_is_listed_with_its_kfd_target) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const diag::Facts f = diag::collect(r.dir);
|
||||
CHECK_EQ((int)f.cards.size(), 3);
|
||||
const diag::CardFacts* a = card(f, "0000:03:00.0");
|
||||
const diag::CardFacts* i = card(f, "0000:1b:00.0");
|
||||
CHECK(a && i);
|
||||
if (!a || !i) return;
|
||||
CHECK_EQ(a->gfx, std::string("gfx1201"));
|
||||
CHECK_EQ(a->simd, 128);
|
||||
CHECK_EQ(i->gfx, std::string("gfx1036"));
|
||||
CHECK_EQ(a->vendor, std::string("0x1002"));
|
||||
CHECK_EQ(a->pci_device, std::string("0x7551"));
|
||||
CHECK_EQ(a->driver, std::string("amdgpu"));
|
||||
CHECK_EQ(a->drm, std::string("card0"));
|
||||
CHECK_EQ(a->iommu_type, std::string("identity"));
|
||||
CHECK_EQ(a->vram_total, (int64_t)34208743424);
|
||||
CHECK_EQ(a->busy_percent, 3);
|
||||
CHECK_EQ(a->sclk, std::string("500-2350 MHz"));
|
||||
CHECK_EQ(a->mclk, std::string("96-1258 MHz"));
|
||||
CHECK_EQ(a->power_cap_uw, (int64_t)300000000);
|
||||
CHECK_EQ(a->power_cap_max_uw, (int64_t)330000000);
|
||||
CHECK_EQ(a->vddgfx_offset, std::string("-75 mV"));
|
||||
CHECK_EQ((int)a->dpm_pcie.size(), 3);
|
||||
CHECK_EQ(a->dpm_pcie_cur, 2);
|
||||
CHECK_EQ(a->dpm_pcie[1], std::string("1: 16.0GT/s, x8 616Mhz"));
|
||||
}
|
||||
|
||||
/* THE ROOT PORT IS ON THE PATH. The card's own link reads Gen5 x16 on both cards; only the second
|
||||
* card's root port says it runs at 16 GT/s. */
|
||||
TEST(the_whole_pcie_path_is_read_root_port_first) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const diag::Facts f = diag::collect(r.dir);
|
||||
const diag::CardFacts* b = card(f, "0000:07:00.0");
|
||||
CHECK(b);
|
||||
if (!b) return;
|
||||
CHECK_EQ((int)b->chain.size(), 4);
|
||||
if (b->chain.size() != 4) return;
|
||||
CHECK_EQ(b->chain[0].bdf, std::string("0000:00:01.3"));
|
||||
CHECK_EQ(b->chain[0].cur_speed, std::string("16.0 GT/s PCIe"));
|
||||
CHECK_EQ(b->chain[0].max_speed, std::string("32.0 GT/s PCIe"));
|
||||
CHECK_EQ(b->chain[0].max_width, 8);
|
||||
CHECK_EQ(b->chain[3].bdf, std::string("0000:07:00.0"));
|
||||
CHECK_EQ(b->chain[3].cur_speed, std::string("32.0 GT/s PCIe"));
|
||||
CHECK_EQ(b->chain[3].cur_width, 16);
|
||||
CHECK(diag::link_gts(b->chain[0].cur_speed) == 16.0);
|
||||
}
|
||||
|
||||
TEST(an_empty_root_is_all_unknown_and_does_not_fail) {
|
||||
Root r;
|
||||
const diag::Facts f = diag::collect(r.dir);
|
||||
CHECK(f.cards.empty());
|
||||
CHECK(f.host.cpu_model.empty());
|
||||
CHECK_EQ(f.host.mem_total, -1);
|
||||
CHECK_EQ(f.host.iommu, std::string("off"));
|
||||
const std::string text = diag::render({}, {}, f, diag::RunFacts{}, {});
|
||||
CHECK(text.find("unknown") != std::string::npos);
|
||||
CHECK(text.find("no display-class PCI device") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A LIMIT ABOVE THE PROCESS'S OWN CGROUP BINDS IT. The leaf says max; the slice above it holds
|
||||
* 8 GiB and the one above that 16 GiB, so the process can have 8. */
|
||||
TEST(the_tightest_cgroup_limit_on_the_way_up_is_reported) {
|
||||
Root r;
|
||||
machine(r);
|
||||
r.put("/proc/self/cgroup", "0::/system.slice/radiance.slice/radiance.service\n");
|
||||
r.put("/sys/fs/cgroup/system.slice/radiance.slice/radiance.service/memory.max", "max\n");
|
||||
r.put("/sys/fs/cgroup/system.slice/radiance.slice/memory.max", "8589934592\n");
|
||||
r.put("/sys/fs/cgroup/system.slice/memory.max", "17179869184\n");
|
||||
CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, (int64_t)8 << 30);
|
||||
/* Every level unlimited is unlimited, not unknown. */
|
||||
r.put("/sys/fs/cgroup/system.slice/radiance.slice/memory.max", "max\n");
|
||||
r.put("/sys/fs/cgroup/system.slice/memory.max", "max\n");
|
||||
CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, -2);
|
||||
/* Inside a cgroup namespace the process is at "/", and the mount's root is its group. */
|
||||
r.put("/proc/self/cgroup", "0::/\n");
|
||||
r.put("/sys/fs/cgroup/memory.max", "4294967296\n");
|
||||
CHECK_EQ(diag::collect(r.dir).host.cgroup_mem_limit, (int64_t)4 << 30);
|
||||
}
|
||||
|
||||
/* unique_id is a full 64-bit hash, which a signed 64-bit read cannot hold. Ahead of the keys the
|
||||
* target is read from, it must not stop the read. */
|
||||
TEST(a_kfd_value_too_large_for_a_signed_read_does_not_hide_the_rest) {
|
||||
Root r;
|
||||
machine(r);
|
||||
r.put("/sys/class/kfd/kfd/topology/nodes/1/properties",
|
||||
"cpu_cores_count 0\nunique_id 17293822569102704640\nsimd_count 128\nlocation_id 768\n"
|
||||
"domain 0\ngfx_target_version 120001\n");
|
||||
const diag::Facts f = diag::collect(r.dir);
|
||||
const diag::CardFacts* a = card(f, "0000:03:00.0");
|
||||
CHECK(a);
|
||||
if (!a) return;
|
||||
CHECK_EQ(a->gfx, std::string("gfx1201"));
|
||||
CHECK_EQ(a->simd, 128);
|
||||
}
|
||||
|
||||
/* A SERVING PROCESS READS THE SMU-BACKED FILES OF ITS OWN CARDS ONLY. The other cards are still
|
||||
* listed, from their PCI and memory files. */
|
||||
TEST(only_the_managed_cards_power_files_are_read) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const std::vector<std::string> mine = { "0000:03:00.0" };
|
||||
const diag::Facts f = diag::collect(r.dir, &mine);
|
||||
CHECK_EQ((int)f.cards.size(), 3);
|
||||
const diag::CardFacts* a = card(f, "0000:03:00.0");
|
||||
const diag::CardFacts* b = card(f, "0000:07:00.0");
|
||||
CHECK(a && b);
|
||||
if (!a || !b) return;
|
||||
CHECK_EQ(a->busy_percent, 3);
|
||||
CHECK_EQ(a->power_cap_uw, (int64_t)300000000);
|
||||
CHECK_EQ(a->vddgfx_offset, std::string("-75 mV"));
|
||||
CHECK_EQ(b->busy_percent, -1);
|
||||
CHECK_EQ(b->power_cap_uw, -1);
|
||||
CHECK(b->dpm_pcie.empty());
|
||||
CHECK(b->sclk.empty());
|
||||
CHECK(b->vddgfx_offset.empty());
|
||||
CHECK_EQ(b->vram_total, (int64_t)34208743424);
|
||||
CHECK_EQ(b->gfx, std::string("gfx1201"));
|
||||
CHECK_EQ((int)b->chain.size(), 4);
|
||||
}
|
||||
|
||||
TEST(environment_names_and_never_their_values) {
|
||||
char a[] = "RADIANCE_TUNE=gemm:tile=128";
|
||||
char b[] = "PATH=/usr/bin";
|
||||
char c[] = "RADIANCE_LOG=debug";
|
||||
char d[] = "RADIANCE_SECRETISH=sk-not-for-the-log";
|
||||
char* env[] = { a, b, c, d, nullptr };
|
||||
const std::vector<std::string> n = diag::env_names(env, "RADIANCE_");
|
||||
CHECK_EQ(n.size(), (size_t)3);
|
||||
if (n.size() != 3) return;
|
||||
CHECK_EQ(n[0], std::string("RADIANCE_LOG"));
|
||||
CHECK_EQ(n[1], std::string("RADIANCE_SECRETISH"));
|
||||
CHECK_EQ(n[2], std::string("RADIANCE_TUNE"));
|
||||
diag::RunFacts run;
|
||||
run.environment = n;
|
||||
const std::string text = diag::render({}, {}, diag::Facts{}, run, {});
|
||||
const std::string json = diag::to_json({}, {}, diag::Facts{}, run, {});
|
||||
CHECK(text.find(" RADIANCE_TUNE\n") != std::string::npos);
|
||||
CHECK(json.find("RADIANCE_SECRETISH") != std::string::npos);
|
||||
CHECK(text.find("sk-not-for-the-log") == std::string::npos);
|
||||
CHECK(json.find("sk-not-for-the-log") == std::string::npos);
|
||||
CHECK(text.find("gemm:tile") == std::string::npos);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ checked */
|
||||
|
||||
TEST(a_link_below_max_under_load_is_a_warning) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const auto found = diag::check(served_machine(r), diag::RunFacts{});
|
||||
CHECK(has(found, "link-below-max", diag::Finding::Warn));
|
||||
CHECK(has(found, "link-dpm-below-top", diag::Finding::Warn));
|
||||
bool names_port = false;
|
||||
for (const diag::Finding& x : found)
|
||||
if (x.id == "link-below-max") names_port = x.what.find("0000:00:01.3") != std::string::npos &&
|
||||
x.what.find("0000:07:00.0") != std::string::npos;
|
||||
CHECK(names_port);
|
||||
}
|
||||
|
||||
/* AT REST A LINK PARKS LOW, and that is not a finding: the same parked root port on an idle card
|
||||
* says nothing. */
|
||||
TEST(an_idle_card_with_a_parked_link_is_not_a_finding) {
|
||||
Root r;
|
||||
machine(r);
|
||||
diag::Facts f = served_machine(r);
|
||||
for (diag::CardFacts& c : f.cards) c.busy_percent = 0;
|
||||
const auto found = diag::check(f, diag::RunFacts{});
|
||||
CHECK(!has(found, "link-below-max"));
|
||||
CHECK(!has(found, "link-dpm-below-top"));
|
||||
}
|
||||
|
||||
TEST(cards_set_up_differently_are_named) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const auto found = diag::check(served_machine(r), diag::RunFacts{});
|
||||
CHECK(has(found, "cards-differ", diag::Finding::Warn));
|
||||
for (const diag::Finding& x : found)
|
||||
if (x.id == "cards-differ") {
|
||||
CHECK(x.what.find("power cap") != std::string::npos);
|
||||
CHECK(x.what.find("280 W") != std::string::npos);
|
||||
}
|
||||
CHECK(has(found, "power-cap-below-default", diag::Finding::Note));
|
||||
CHECK(has(found, "od-runtime-suspend", diag::Finding::Note));
|
||||
CHECK(has(found, "cpu-governor", diag::Finding::Note));
|
||||
}
|
||||
|
||||
/* THE DEFAULT IS THE YARDSTICK, NOT THE MAXIMUM. Both cards allow 330 W and default to 300 W; the
|
||||
* first is at its default and says nothing, the second was lowered to 280 W and is named. */
|
||||
TEST(a_power_cap_is_judged_against_the_cards_default) {
|
||||
Root r;
|
||||
machine(r);
|
||||
diag::Facts f = served_machine(r);
|
||||
auto named = [](const std::vector<diag::Finding>& v, const char* bdf) {
|
||||
for (const diag::Finding& x : v)
|
||||
if (x.id == "power-cap-below-default" && x.what.find(bdf) != std::string::npos)
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
auto found = diag::check(f, diag::RunFacts{});
|
||||
CHECK(!named(found, "0000:03:00.0"));
|
||||
CHECK(named(found, "0000:07:00.0"));
|
||||
/* A card that does not say its default is not judged at all. */
|
||||
for (diag::CardFacts& c : f.cards) c.power_cap_default_uw = -1;
|
||||
CHECK(!has(diag::check(f, diag::RunFacts{}), "power-cap-below-default"));
|
||||
}
|
||||
|
||||
TEST(cards_alike_say_nothing_about_each_other) {
|
||||
Root r;
|
||||
machine(r);
|
||||
diag::Facts f = served_machine(r);
|
||||
for (diag::CardFacts& c : f.cards) {
|
||||
c.power_cap_uw = c.power_cap_max_uw;
|
||||
c.runtime_control = "on";
|
||||
c.busy_percent = 0;
|
||||
if (!c.chain.empty()) c.chain.front().max_width = 8;
|
||||
}
|
||||
const auto found = diag::check(f, diag::RunFacts{});
|
||||
CHECK(!has(found, "cards-differ"));
|
||||
CHECK(!has(found, "power-cap-below-default"));
|
||||
CHECK(!has(found, "od-runtime-suspend"));
|
||||
}
|
||||
|
||||
TEST(the_unserved_igpu_is_not_checked_as_a_rank) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const auto found = diag::check(served_machine(r), diag::RunFacts{});
|
||||
for (const diag::Finding& x : found) CHECK(x.what.find("1b:00.0") == std::string::npos);
|
||||
}
|
||||
|
||||
TEST(host_findings) {
|
||||
Root r;
|
||||
machine(r);
|
||||
diag::Facts f = served_machine(r);
|
||||
diag::RunFacts run;
|
||||
CHECK(!has(diag::check(f, run), "cwsr-off"));
|
||||
f.host.cwsr_enable = 0;
|
||||
f.host.thp_enabled = "never";
|
||||
for (diag::CardFacts& c : f.cards) c.iommu_type = "DMA-FQ";
|
||||
f.host.mem_available = (int64_t)1 << 30;
|
||||
f.host.swap_total = (int64_t)8 << 30;
|
||||
f.host.swap_free = (int64_t)6 << 30;
|
||||
run.host_pool_mib = 12288;
|
||||
run.pinned_bytes = f.host.ttm_pages_limit * f.host.page_size - ((int64_t)1 << 20);
|
||||
const auto found = diag::check(f, run);
|
||||
CHECK(has(found, "cwsr-off", diag::Finding::Warn));
|
||||
CHECK(has(found, "thp-never", diag::Finding::Warn));
|
||||
CHECK(has(found, "iommu-translated", diag::Finding::Note));
|
||||
CHECK(has(found, "memory-low", diag::Finding::Warn));
|
||||
CHECK(has(found, "swap-in-use", diag::Finding::Note));
|
||||
/* Warnings come before notes, so the first lines of the section are the ones to act on. */
|
||||
bool seen_note = false, order_ok = true;
|
||||
for (const diag::Finding& x : found) {
|
||||
if (x.level == diag::Finding::Note) seen_note = true;
|
||||
else if (seen_note) order_ok = false;
|
||||
}
|
||||
CHECK(order_ok);
|
||||
/* Huge pages off on a passthrough IOMMU is a note: the page size has not measured slower. */
|
||||
for (diag::CardFacts& c : f.cards) c.iommu_type = "identity";
|
||||
CHECK(has(diag::check(f, run), "thp-never", diag::Finding::Note));
|
||||
}
|
||||
|
||||
TEST(engine_findings) {
|
||||
Root r;
|
||||
machine(r);
|
||||
diag::Facts f = served_machine(r);
|
||||
diag::RunFacts run;
|
||||
run.tp = 2;
|
||||
run.tp_wire_lossy = true;
|
||||
run.tp_wire_min_kb = 128;
|
||||
run.prefix_cache = false;
|
||||
run.host_weight_bytes = (int64_t)20 << 30;
|
||||
run.p2p = 0;
|
||||
run.p2p_blocked = "0->1";
|
||||
run.ignored.push_back("using 2 of 3 [0:gfx1201 1:gfx1201], ignoring [2:gfx1036]");
|
||||
run.reference_kernels = true;
|
||||
run.profile_ops = true;
|
||||
const auto found = diag::check(f, run);
|
||||
CHECK(has(found, "tp-wire-lossy", diag::Finding::Note));
|
||||
CHECK(has(found, "prefix-cache-off", diag::Finding::Note));
|
||||
/* Passthrough is not advice for peer access: on one Intel VT-d host it removed it. */
|
||||
for (const diag::Finding& x : found)
|
||||
if (x.id == "p2p-off") CHECK(x.fix.find("IOMMU in passthrough") == std::string::npos);
|
||||
CHECK(has(found, "experts-from-host", diag::Finding::Note));
|
||||
CHECK(has(found, "p2p-off", diag::Finding::Note));
|
||||
CHECK(has(found, "device-ignored", diag::Finding::Note));
|
||||
CHECK(has(found, "reference-kernels", diag::Finding::Warn));
|
||||
CHECK(has(found, "profile-ops", diag::Finding::Warn));
|
||||
CHECK(!has(found, "host-backend"));
|
||||
run.p2p_forced_off = true;
|
||||
CHECK(!has(diag::check(f, run), "p2p-off"));
|
||||
/* The cache the engine turned off itself -- the KL mode, an embedding model -- is not a
|
||||
* setting to undo, and its reason is on the option's line instead. */
|
||||
run.prefix_cache_off_why = "an embedding model: an encoder keeps no KV to reuse";
|
||||
CHECK(!has(diag::check(f, run), "prefix-cache-off"));
|
||||
/* #58's shape: a card is in the machine and the engine came up on the host. */
|
||||
for (diag::CardFacts& c : f.cards) { c.rank = -1; }
|
||||
run.host_backend = true;
|
||||
CHECK(has(diag::check(f, run), "host-backend", diag::Finding::Warn));
|
||||
/* An integrated GPU's few hundred MiB of carve-out is not a card the engine would serve on. */
|
||||
for (diag::CardFacts& c : f.cards) c.vram_total = (int64_t)512 << 20;
|
||||
CHECK(!has(diag::check(f, run), "host-backend"));
|
||||
}
|
||||
|
||||
/* THE MODE IS THE CARDS'. An integrated GPU identity-mapped beside a translated discrete card is
|
||||
* a machine whose serving card is translated, whatever the other group says. */
|
||||
TEST(the_iommu_mode_is_read_from_the_serving_cards) {
|
||||
Root r;
|
||||
machine(r);
|
||||
r.put("/proc/cmdline", "root=PARTUUID=x rw\n");
|
||||
r.put("/sys/devices/pci0000:00/0000:00:01.3/0000:05:00.0/0000:06:00.0/0000:07:00.0/iommu_group/type",
|
||||
"DMA-FQ\n");
|
||||
diag::Facts f = served_machine(r);
|
||||
CHECK_EQ(f.host.iommu, std::string("mixed"));
|
||||
CHECK(f.host.iommu_why.find("DMA-FQ for 0000:07:00.0") != std::string::npos);
|
||||
diag::RunFacts run;
|
||||
run.host_pool_mib = 12288;
|
||||
CHECK(has(diag::check(f, run), "iommu-translated", diag::Finding::Note));
|
||||
for (diag::CardFacts& c : f.cards) c.iommu_type = "identity";
|
||||
CHECK(!has(diag::check(f, run), "iommu-translated"));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ reported */
|
||||
|
||||
namespace {
|
||||
|
||||
struct Argv {
|
||||
std::vector<std::string> store;
|
||||
std::vector<char*> argv;
|
||||
explicit Argv(std::initializer_list<const char*> v) {
|
||||
store.emplace_back("radiance");
|
||||
for (const char* s : v) store.emplace_back(s);
|
||||
for (std::string& s : store) argv.push_back(s.data());
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* EVERY OPTION IN THE TABLE REACHES THE REPORT, with a value shown and not the placeholder an
|
||||
* option without a formatter gets. An option added to the table without one fails here by name. */
|
||||
TEST(every_option_in_the_table_is_reported) {
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
const std::vector<diag::ConfigRow> rows = diag::config_rows(c);
|
||||
const std::vector<std::string> names = diag::config_option_names();
|
||||
CHECK_EQ(rows.size(), names.size());
|
||||
CHECK(names.size() > 80);
|
||||
for (size_t i = 0; i < rows.size() && i < names.size(); ++i) {
|
||||
CHECK_EQ(rows[i].flag, names[i]);
|
||||
if (rows[i].value == "(not shown)") {
|
||||
radtest::fail(__FILE__, __LINE__, "no value shown for " + rows[i].flag);
|
||||
}
|
||||
}
|
||||
const std::string text = diag::render(rows, {}, diag::Facts{}, diag::RunFacts{}, {});
|
||||
for (const std::string& n : names)
|
||||
if (text.find(" " + n + " ") == std::string::npos)
|
||||
radtest::fail(__FILE__, __LINE__, "the report has no line for " + n);
|
||||
}
|
||||
|
||||
TEST(sources_and_secrets) {
|
||||
setenv("RADIANCE_KERNELS", "libr4d,libref", 1);
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad", "--tp", "2", "--api-key", "sk-very-secret-value",
|
||||
"--gpu-headroom", "128" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
unsetenv("RADIANCE_KERNELS");
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(c);
|
||||
auto row = [&](const char* f) -> const diag::ConfigRow* {
|
||||
for (const diag::ConfigRow& x : rows) if (x.flag == f) return &x;
|
||||
return nullptr;
|
||||
};
|
||||
CHECK(row("--tp") && row("--tp")->source == "command line" && row("--tp")->value == "2");
|
||||
CHECK(row("--max-num-seqs") && row("--max-num-seqs")->source == "default");
|
||||
/* The alias reports as the option it is. */
|
||||
CHECK(row("--gpu-headroom-mib") && row("--gpu-headroom-mib")->source == "command line" &&
|
||||
row("--gpu-headroom-mib")->value == "128");
|
||||
CHECK(row("--kernels") && row("--kernels")->source == "environment (RADIANCE_KERNELS)" &&
|
||||
row("--kernels")->value == "libr4d,libref");
|
||||
CHECK(row("--api-key") && row("--api-key")->value == "set");
|
||||
|
||||
/* A DECISION SUPPLIES THE VALUE AND THE REASON; a default it resolves becomes `auto`, a given
|
||||
* option keeps its source; a topic no option states is returned as derived. */
|
||||
std::vector<diag::Decision> d;
|
||||
diag::decide(&d, "--num-speculative-tokens", "2", "the drafter's own depth");
|
||||
diag::decide(&d, "--tp", "2", "as given");
|
||||
diag::decide(&d, "vram split", "weights 20 GiB", "the report");
|
||||
diag::decide(&d, "--num-speculative-tokens", "3", "revised");
|
||||
CHECK_EQ(d.size(), (size_t)3);
|
||||
std::vector<diag::Decision> derived;
|
||||
diag::merge(&rows, d, &derived);
|
||||
CHECK(row("--num-speculative-tokens")->value == "3");
|
||||
CHECK(row("--num-speculative-tokens")->source == "auto");
|
||||
CHECK(row("--num-speculative-tokens")->why == "revised");
|
||||
CHECK(row("--tp")->source == "command line");
|
||||
CHECK_EQ(derived.size(), (size_t)1);
|
||||
CHECK(!derived.empty() && derived[0].key == "vram split");
|
||||
|
||||
const std::string text = diag::render(rows, derived, diag::Facts{}, diag::RunFacts{}, {});
|
||||
const std::string json = diag::to_json(rows, derived, diag::Facts{}, diag::RunFacts{}, {});
|
||||
CHECK(text.find("sk-very-secret-value") == std::string::npos);
|
||||
CHECK(json.find("sk-very-secret-value") == std::string::npos);
|
||||
CHECK(text.find("DERIVED") != std::string::npos);
|
||||
}
|
||||
|
||||
/* BYTES THAT ARE NOT UTF-8 ARE REPLACED, NOT THROWN ON. A --model path is the operator's bytes,
|
||||
* and a strict serialiser would turn every /diagnostics request into a 500. */
|
||||
TEST(a_value_that_is_not_utf8_does_not_break_the_json) {
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/caf\xe9.rad" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
c.sample_dry_seq_breakers = std::vector<std::string>{ "\xff\xfe" };
|
||||
std::vector<diag::ConfigRow> rows;
|
||||
bool threw = false;
|
||||
try { rows = diag::config_rows(c); } catch (...) { threw = true; }
|
||||
CHECK(!threw);
|
||||
diag::Facts f;
|
||||
diag::CardFacts card;
|
||||
card.bdf = "0000:03:00.0";
|
||||
card.name = "R9700 \xc3\x28";
|
||||
f.cards.push_back(card);
|
||||
std::string out;
|
||||
try { out = diag::to_json(rows, {}, f, diag::RunFacts{}, {}); } catch (...) { threw = true; }
|
||||
CHECK(!threw);
|
||||
const nlohmann::json j = nlohmann::json::parse(out, nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
if (j.is_discarded()) return;
|
||||
CHECK(j["configuration"][0]["value"].get<std::string>() == "/m/caf\xef\xbf\xbd.rad");
|
||||
}
|
||||
|
||||
/* EACH SAMPLER FIELD NAMES ITS OWN SOURCE. A generation_config.json that states a temperature and
|
||||
* a top_p and nothing else supplied those two; top_k and min_p are SamplingParams' own values,
|
||||
* and a reason that named the file for all four would send a reader to look for them in it. */
|
||||
TEST(sampler_defaults_carry_a_source_per_field) {
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad", "--min-p", "0.05" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
GenSampling g;
|
||||
CHECK(gen_sampling_parse(R"({"temperature": 0.6, "top_p": 0.95})", "test", &g));
|
||||
SamplingParams sp = g.onto(SamplingParams{});
|
||||
sp.min_p = c.sample_min_p;
|
||||
const std::vector<GenFieldSource> s = gen_sampling_sources(g, "/m/gen.json", sp, c);
|
||||
auto find = [&](const char* flag) -> const GenFieldSource* {
|
||||
for (const GenFieldSource& x : s) if (x.flag == flag) return &x;
|
||||
return nullptr;
|
||||
};
|
||||
CHECK(find("--temp") && find("--temp")->why == "from /m/gen.json" &&
|
||||
find("--temp")->value == "0.6");
|
||||
CHECK(find("--top-p") && find("--top-p")->why == "from /m/gen.json");
|
||||
CHECK(find("--top-k") && find("--top-k")->why.find("/m/gen.json states no top_k") == 0);
|
||||
/* --min-p was given: its own row says "command line", and nothing here overrides that. */
|
||||
CHECK(!find("--min-p"));
|
||||
/* No source at all: every field says the model stated nothing. */
|
||||
for (const GenFieldSource& x : gen_sampling_sources(GenSampling{}, "", SamplingParams{}, c))
|
||||
CHECK(x.why.find("the model states no sampling of its own") == 0);
|
||||
}
|
||||
|
||||
/* A VALUE THE SERVER RESOLVES IS RECORDED WHERE IT IS RESOLVED, not worked out again by the
|
||||
* report: unresolved, the option's line says only how it will be. */
|
||||
TEST(auto_server_bounds_are_not_recomputed_by_the_report) {
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
std::vector<diag::ConfigRow> rows = diag::config_rows(c);
|
||||
for (const diag::ConfigRow& x : rows)
|
||||
if (x.flag == "--http-threads" || x.flag == "--max-n" || x.flag == "--max-queued-requests")
|
||||
CHECK(x.value.rfind("auto (", 0) == 0);
|
||||
std::vector<diag::Decision> d, derived;
|
||||
diag::decide(&d, "--http-threads", "32", "one a hardware thread, at least 4");
|
||||
diag::merge(&rows, d, &derived);
|
||||
for (const diag::ConfigRow& x : rows)
|
||||
if (x.flag == "--http-threads") CHECK(x.value == "32" && x.source == "auto");
|
||||
}
|
||||
|
||||
TEST(the_json_carries_every_section) {
|
||||
Root r;
|
||||
machine(r);
|
||||
const diag::Facts f = served_machine(r);
|
||||
const auto found = diag::check(f, diag::RunFacts{});
|
||||
Config c;
|
||||
Argv a({ "--model", "/m/x.rad" });
|
||||
CHECK_EQ(config_parse((int)a.argv.size(), a.argv.data(), &c), 0);
|
||||
const nlohmann::json j = nlohmann::json::parse(
|
||||
diag::to_json(diag::config_rows(c), {}, f, diag::RunFacts{}, found), nullptr, false);
|
||||
CHECK(!j.is_discarded());
|
||||
if (j.is_discarded()) return;
|
||||
CHECK(j["configuration"].is_array() && j["configuration"].size() == diag::config_option_names().size());
|
||||
CHECK(j["hardware"]["cards"].size() == 3);
|
||||
CHECK(j["hardware"]["cards"][1]["link_chain"].size() == 4);
|
||||
CHECK(j["hardware"]["host"]["iommu"]["mode"] == "passthrough");
|
||||
CHECK(j["findings"].size() == found.size());
|
||||
const std::string text = diag::render(diag::config_rows(c), {}, f, diag::RunFacts{}, found);
|
||||
CHECK(text.find("00:01.3 16.0 GT/s x8 (max 32.0 GT/s x8)") != std::string::npos);
|
||||
CHECK(text.find("WARN link-below-max") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -0,0 +1,97 @@
|
||||
/* lfm2_golden.h -- GENERATED by mklfm2golden.py from transformers 5.19.0; do not edit. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
static const int32_t kLfm2Patch = 16, kLfm2Merge = 2, kLfm2MinTok = 64, kLfm2MaxTok = 256;
|
||||
static const int32_t kLfm2MinTiles = 2, kLfm2MaxTiles = 10, kLfm2Tile = 512, kLfm2MaxPatches = 1024;
|
||||
static const double kLfm2Tolerance = 2.0;
|
||||
struct GoldLfm2Size { int64_t h, w, oh, ow; int32_t large, cols, rows; };
|
||||
static const GoldLfm2Size kGoldLfm2Size[] = {
|
||||
{ 1, 1, 256, 256, 0, 2, 2 },
|
||||
{ 40, 30, 320, 224, 0, 2, 3 },
|
||||
{ 300, 500, 288, 512, 0, 3, 2 },
|
||||
{ 700, 700, 512, 512, 0, 2, 2 },
|
||||
{ 900, 1400, 384, 608, 1, 3, 2 },
|
||||
{ 2000, 600, 928, 256, 1, 1, 3 },
|
||||
{ 515, 1031, 352, 704, 0, 2, 1 },
|
||||
{ 512, 1024, 352, 704, 0, 2, 1 },
|
||||
{ 1080, 1920, 384, 672, 1, 4, 2 },
|
||||
{ 4000, 300, 1856, 128, 1, 1, 10 },
|
||||
{ 31, 4000, 32, 4000, 0, 10, 1 },
|
||||
{ 777, 333, 768, 320, 0, 2, 5 },
|
||||
{ 1024, 1024, 512, 512, 1, 2, 2 },
|
||||
{ 1023, 2047, 352, 704, 1, 4, 2 },
|
||||
{ 64, 64, 256, 256, 0, 2, 2 },
|
||||
{ 100, 5000, 64, 3616, 0, 10, 1 },
|
||||
{ 3000, 3000, 512, 512, 1, 3, 3 },
|
||||
{ 720, 1280, 384, 672, 1, 2, 1 },
|
||||
};
|
||||
struct GoldLfm2Marker { const char* name; int32_t id; };
|
||||
static const GoldLfm2Marker kGoldLfm2Markers[] = {
|
||||
{ "<|image_start|>", 125009 },
|
||||
{ "<|image_end|>", 125010 },
|
||||
{ "<|img_thumbnail|>", 125008 },
|
||||
{ "<|img_row_1_col_1|>", 124908 },
|
||||
{ "<|img_row_1_col_2|>", 124909 },
|
||||
{ "<|img_row_1_col_3|>", 124910 },
|
||||
{ "<|img_row_1_col_4|>", 124911 },
|
||||
{ "<|img_row_1_col_5|>", 124912 },
|
||||
{ "<|img_row_1_col_6|>", 124913 },
|
||||
{ "<|img_row_1_col_7|>", 124914 },
|
||||
{ "<|img_row_1_col_8|>", 124915 },
|
||||
{ "<|img_row_1_col_9|>", 124916 },
|
||||
{ "<|img_row_1_col_10|>", 124917 },
|
||||
{ "<|img_row_2_col_1|>", 124918 },
|
||||
{ "<|img_row_2_col_2|>", 124919 },
|
||||
{ "<|img_row_2_col_3|>", 124920 },
|
||||
{ "<|img_row_2_col_4|>", 124921 },
|
||||
{ "<|img_row_2_col_5|>", 124922 },
|
||||
{ "<|img_row_3_col_1|>", 124928 },
|
||||
{ "<|img_row_3_col_2|>", 124929 },
|
||||
{ "<|img_row_3_col_3|>", 124930 },
|
||||
{ "<|img_row_4_col_1|>", 124938 },
|
||||
{ "<|img_row_4_col_2|>", 124939 },
|
||||
{ "<|img_row_5_col_1|>", 124948 },
|
||||
{ "<|img_row_5_col_2|>", 124949 },
|
||||
{ "<|img_row_6_col_1|>", 124958 },
|
||||
{ "<|img_row_7_col_1|>", 124968 },
|
||||
{ "<|img_row_8_col_1|>", 124978 },
|
||||
{ "<|img_row_9_col_1|>", 124988 },
|
||||
{ "<|img_row_10_col_1|>", 124998 },
|
||||
};
|
||||
static const int32_t kLfm2ImageToken = 124907;
|
||||
struct GoldLfm2Pic { int32_t f, h, w; int64_t cap; int32_t cols, rows, n_seg, seg0; int32_t n_ids; uint64_t ids_fnv; };
|
||||
static const GoldLfm2Pic kGoldLfm2Pics[] = {
|
||||
{ 0, 40, 30, 0, 1, 1, 1, 0, 72, 0xf4a13171f5dba0b2ull },
|
||||
{ 1, 300, 500, 0, 1, 1, 1, 1, 146, 0x31e5951b9e177f96ull },
|
||||
{ 2, 700, 700, 0, 1, 1, 1, 2, 258, 0xa3fceabcb4070e76ull },
|
||||
{ 3, 900, 1400, 0, 3, 2, 7, 3, 1773, 0xe878e4810a1f66cdull },
|
||||
{ 4, 2000, 600, 0, 1, 3, 4, 10, 1006, 0xed3837ea6bba64b8ull },
|
||||
{ 5, 1800, 1200, 1048576, 2, 3, 7, 14, 1792, 0x68ef61a1fe0e31ddull },
|
||||
{ 6, 515, 1031, 0, 1, 1, 1, 21, 244, 0x41e3b3c2daa2fccaull },
|
||||
};
|
||||
struct GoldLfm2Seg { int32_t h, w; uint64_t fnv; };
|
||||
static const GoldLfm2Seg kGoldLfm2Segs[] = {
|
||||
{ 20, 14, 0xde350f8ffaae060dull },
|
||||
{ 18, 32, 0x1e897c3d485cf756ull },
|
||||
{ 32, 32, 0x275822a4d8e5c314ull },
|
||||
{ 32, 32, 0xd5c661c14ae1062full },
|
||||
{ 32, 32, 0x1deb651bff0aa1fbull },
|
||||
{ 32, 32, 0x571cdfffc3d7bda4ull },
|
||||
{ 32, 32, 0xc4a9e6d1acc5e8a7ull },
|
||||
{ 32, 32, 0x64bc191eced1db77ull },
|
||||
{ 32, 32, 0x5d9b1cfc1f6748b8ull },
|
||||
{ 24, 38, 0x803957c943657915ull },
|
||||
{ 32, 32, 0xb609a02f3c340c8full },
|
||||
{ 32, 32, 0xed17e14b9740a2c9ull },
|
||||
{ 32, 32, 0x1a6114e52cc829fdull },
|
||||
{ 58, 16, 0x595479cd72f7ff69ull },
|
||||
{ 32, 32, 0xfaaa7e21c05b8325ull },
|
||||
{ 32, 32, 0x851b719d2331a839ull },
|
||||
{ 32, 32, 0xf6e8f07ecad1d04bull },
|
||||
{ 32, 32, 0xb4cc3efd44779290ull },
|
||||
{ 32, 32, 0xd935c251cfcbccf4ull },
|
||||
{ 32, 32, 0x7ca1535ecf888407ull },
|
||||
{ 38, 26, 0xeaf5a49573123b49ull },
|
||||
{ 22, 44, 0x072680b110281b00ull },
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
"""mklfm2golden.py MODELDIR OUT.h -- goldens for the LFM2-VL processor in tests/mm_test.cpp, every
|
||||
number from transformers' own Lfm2VlProcessor as MODELDIR's processor_config.json sets it up:
|
||||
smart_resize, the tile grid and the too-large test, and whole pictures -- each segment's patches
|
||||
and the tokens that replace the picture's <image> -- including one scaled down first by PIL's
|
||||
bicubic to an area cap, as d1's runner does before the processor."""
|
||||
import sys, math, json
|
||||
import numpy as np, torch
|
||||
from PIL import Image
|
||||
from transformers import AutoProcessor
|
||||
|
||||
model_dir, out = sys.argv[1], sys.argv[2]
|
||||
P = AutoProcessor.from_pretrained(model_dir)
|
||||
IP = P.image_processor
|
||||
tok = P.tokenizer
|
||||
L = ["/* lfm2_golden.h -- GENERATED by mklfm2golden.py from transformers %s; do not edit. */"
|
||||
% __import__("transformers").__version__, "#pragma once", "#include <cstdint>", ""]
|
||||
cfg = dict(downsample_factor=IP.downsample_factor, min_image_tokens=IP.min_image_tokens,
|
||||
max_image_tokens=IP.max_image_tokens, encoder_patch_size=IP.encoder_patch_size)
|
||||
L.append(f"static const int32_t kLfm2Patch = {IP.encoder_patch_size}, kLfm2Merge = {IP.downsample_factor}, "
|
||||
f"kLfm2MinTok = {IP.min_image_tokens}, kLfm2MaxTok = {IP.max_image_tokens};")
|
||||
L.append(f"static const int32_t kLfm2MinTiles = {IP.min_tiles}, kLfm2MaxTiles = {IP.max_tiles}, "
|
||||
f"kLfm2Tile = {IP.tile_size}, kLfm2MaxPatches = {IP.max_num_patches};")
|
||||
L.append(f"static const double kLfm2Tolerance = {IP.max_pixels_tolerance!r};")
|
||||
|
||||
# ---- smart_resize (returns width, height) and the tiling decision
|
||||
sizes = [(1, 1), (40, 30), (300, 500), (700, 700), (900, 1400), (2000, 600), (515, 1031), (512, 1024),
|
||||
(1080, 1920), (4000, 300), (31, 4000), (777, 333), (1024, 1024), (1023, 2047), (64, 64),
|
||||
(100, 5000), (3000, 3000), (720, 1280)]
|
||||
L.append("struct GoldLfm2Size { int64_t h, w, oh, ow; int32_t large, cols, rows; };")
|
||||
L.append("static const GoldLfm2Size kGoldLfm2Size[] = {")
|
||||
for h, w in sizes:
|
||||
ow, oh = IP.smart_resize(height=h, width=w, **cfg)
|
||||
large = IP._is_image_too_large(height=h, width=w, max_image_tokens=IP.max_image_tokens,
|
||||
encoder_patch_size=IP.encoder_patch_size,
|
||||
downsample_factor=IP.downsample_factor,
|
||||
max_pixels_tolerance=IP.max_pixels_tolerance)
|
||||
gw, gh, *_ = IP._get_grid_layout(h, w, min_tiles=IP.min_tiles, max_tiles=IP.max_tiles,
|
||||
tile_size=IP.tile_size)
|
||||
L.append(f" {{ {h}, {w}, {oh}, {ow}, {int(large)}, {gw}, {gh} }},")
|
||||
L.append("};")
|
||||
|
||||
# ---- the markers, by name, for a token_id lookup with no tokenizer behind it
|
||||
names = ["<|image_start|>", "<|image_end|>", "<|img_thumbnail|>"]
|
||||
names += [f"<|img_row_{r}_col_{c}|>" for r in range(1, IP.max_tiles + 1) for c in range(1, IP.max_tiles + 1)
|
||||
if r * c <= IP.max_tiles]
|
||||
L.append("struct GoldLfm2Marker { const char* name; int32_t id; };")
|
||||
L.append("static const GoldLfm2Marker kGoldLfm2Markers[] = {")
|
||||
for n in names:
|
||||
L.append(f' {{ "{n}", {tok.convert_tokens_to_ids(n)} }},')
|
||||
L.append("};")
|
||||
L.append(f"static const int32_t kLfm2ImageToken = {P.image_token_id};")
|
||||
|
||||
# ---- whole pictures: splitmix pixels (as mkgolden.py's), optionally area-capped by PIL first
|
||||
def frame(f, h, w):
|
||||
y, x, c = np.meshgrid(np.arange(h, dtype=np.uint64), np.arange(w, dtype=np.uint64),
|
||||
np.arange(3, dtype=np.uint64), indexing="ij")
|
||||
with np.errstate(over="ignore"):
|
||||
z = (np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9) +
|
||||
x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345))
|
||||
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
|
||||
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
|
||||
z = z ^ (z >> np.uint64(31))
|
||||
return (z & np.uint64(255)).astype(np.uint8)
|
||||
def fnv(b):
|
||||
a = np.frombuffer(b, dtype=np.uint8).astype(np.uint64)
|
||||
h = 0xcbf29ce484222325
|
||||
for v in a.tolist():
|
||||
h = ((h ^ v) * 0x100000001b3) & (2**64 - 1)
|
||||
return h
|
||||
def cap(im, max_pixels): # d1's runner, cap_pixels
|
||||
w, h = im.size
|
||||
if not max_pixels or w * h <= max_pixels:
|
||||
return im
|
||||
s = math.sqrt(max_pixels / (w * h))
|
||||
return im.resize((max(1, int(w * s)), max(1, int(h * s))), Image.Resampling.BICUBIC)
|
||||
|
||||
pics = [(0, 40, 30, 0), (1, 300, 500, 0), (2, 700, 700, 0), (3, 900, 1400, 0), (4, 2000, 600, 0),
|
||||
(5, 1800, 1200, 1048576), (6, 515, 1031, 0)]
|
||||
segs, idsall = [], []
|
||||
L.append("struct GoldLfm2Pic { int32_t f, h, w; int64_t cap; int32_t cols, rows, n_seg, seg0; "
|
||||
"int32_t n_ids; uint64_t ids_fnv; };")
|
||||
rows = []
|
||||
for f, h, w, mp in pics:
|
||||
im = cap(Image.fromarray(frame(f, h, w)), mp)
|
||||
o = P(text=["<image>"], images=[[im]], return_tensors="pt", add_special_tokens=False)
|
||||
ids = o["input_ids"][0].to(torch.int32).numpy()
|
||||
mask = o["pixel_attention_mask"]
|
||||
shapes = o["spatial_shapes"].tolist()
|
||||
rc = IP(images=[[im]], return_row_col_info=True)
|
||||
pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16)
|
||||
seg0 = len(segs)
|
||||
for s, (gh, gw) in enumerate(shapes):
|
||||
n = int(mask[s].sum())
|
||||
assert n == gh * gw
|
||||
segs.append((gh, gw, fnv(pv[s, :n].tobytes())))
|
||||
rows.append(f" {{ {f}, {h}, {w}, {mp}, {rc['image_cols'][0]}, {rc['image_rows'][0]}, {len(shapes)}, {seg0}, {len(ids)}, "
|
||||
f"0x{fnv(ids.astype('<i4').tobytes()):016x}ull }},")
|
||||
L.append("static const GoldLfm2Pic kGoldLfm2Pics[] = {")
|
||||
L += rows
|
||||
L.append("};")
|
||||
L.append("struct GoldLfm2Seg { int32_t h, w; uint64_t fnv; };")
|
||||
L.append("static const GoldLfm2Seg kGoldLfm2Segs[] = {")
|
||||
for gh, gw, hv in segs:
|
||||
L.append(f" {{ {gh}, {gw}, 0x{hv:016x}ull }},")
|
||||
L.append("};")
|
||||
open(out, "w").write("\n".join(L) + "\n")
|
||||
print("wrote", out, len(L), "lines")
|
||||
+110
-1
@@ -1,7 +1,8 @@
|
||||
/* mm_test.cpp -- the multimodal processor against the reference, number for number.
|
||||
*
|
||||
* Every expected value in mm_golden.h came out of transformers' own code (tests/mkgolden.py says
|
||||
* which function made which table): smart_resize in both forms, the frames a video keeps, the
|
||||
* which function made which table), and in lfm2_golden.h out of its LFM2-VL processor
|
||||
* (tests/mklfm2golden.py): smart_resize in both forms, the frames a video keeps, the
|
||||
* patches of a picture and of a clip, the timestamps between a clip's groups, and get_rope_index's
|
||||
* positions over a prompt carrying both. A model reads its prompt through all of these at once, so
|
||||
* a mistake in any one is a model that still answers -- about a slightly different picture, or
|
||||
@@ -15,6 +16,7 @@
|
||||
#include "mm/media.h"
|
||||
#include "mm/processor.h"
|
||||
#include "mm_golden.h"
|
||||
#include "lfm2_golden.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -409,4 +411,111 @@ TEST(the_audio_front_end_is_the_references) {
|
||||
CHECK_EQ(it->expand.size(), (size_t)2);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* LiquidAI d1-3B's processor_config.json, as a container converted from it states it. */
|
||||
VisionConfig lfm2_cfg() {
|
||||
VisionConfig c;
|
||||
c.family = Family::Lfm2;
|
||||
c.patch = kLfm2Patch;
|
||||
c.merge = kLfm2Merge;
|
||||
c.temporal = 1;
|
||||
const int64_t f2 = (int64_t)c.factor() * c.factor();
|
||||
c.image_min_pixels = c.video_min_pixels = kLfm2MinTok * f2;
|
||||
c.image_max_pixels = c.video_max_pixels = kLfm2MaxTok * f2;
|
||||
c.min_tiles = kLfm2MinTiles;
|
||||
c.max_tiles = kLfm2MaxTiles;
|
||||
c.tile = kLfm2Tile;
|
||||
c.use_thumbnail = true;
|
||||
c.max_pixels_tolerance = kLfm2Tolerance;
|
||||
c.max_segment_patches = kLfm2MaxPatches;
|
||||
c.tok_image = kLfm2ImageToken;
|
||||
c.max_patches = 4096;
|
||||
return c;
|
||||
}
|
||||
|
||||
int32_t lfm2_marker(const std::string& name) {
|
||||
for (const GoldLfm2Marker& m : kGoldLfm2Markers)
|
||||
if (name == m.name) return m.id;
|
||||
return -1;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(lfm2_sizes_and_tiles_are_the_references) {
|
||||
for (const GoldLfm2Size& g : kGoldLfm2Size) {
|
||||
int64_t oh = 0, ow = 0;
|
||||
lfm2_size(g.h, g.w, kLfm2Patch * kLfm2Merge, (int64_t)kLfm2MinTok * 1024,
|
||||
(int64_t)kLfm2MaxTok * 1024, &oh, &ow);
|
||||
int32_t cols = 0, rows = 0;
|
||||
lfm2_grid(g.h, g.w, kLfm2MinTiles, kLfm2MaxTiles, kLfm2Tile, &cols, &rows);
|
||||
const bool large = lfm2_too_large(g.h, g.w, kLfm2Patch, kLfm2Patch * kLfm2Merge,
|
||||
(int64_t)kLfm2MaxTok * 1024, kLfm2Tolerance);
|
||||
if (oh != g.oh || ow != g.ow || cols != g.cols || rows != g.rows || large != (g.large != 0))
|
||||
std::fprintf(stderr, " %lld x %lld: %lld x %lld, %d x %d tiles, large %d; reference "
|
||||
"%lld x %lld, %d x %d, %d\n", (long long)g.h, (long long)g.w, (long long)oh,
|
||||
(long long)ow, cols, rows, (int)large, (long long)g.oh, (long long)g.ow,
|
||||
g.cols, g.rows, g.large);
|
||||
CHECK_EQ(oh, g.oh);
|
||||
CHECK_EQ(ow, g.ow);
|
||||
CHECK_EQ(cols, g.cols);
|
||||
CHECK_EQ(rows, g.rows);
|
||||
CHECK_EQ(large, g.large != 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Whole pictures, small to tiled, one area-capped first as d1's runner caps it: every segment's
|
||||
* size and patches, and the tokens that replace the picture. The processor keeps a segment's
|
||||
* patches in merge-block order; the reference's are row-major, so they are put back in that order
|
||||
* (Item::coords) before the hash. */
|
||||
TEST(lfm2_pictures_are_the_references) {
|
||||
Processor p;
|
||||
REQUIRE_EQ(p.init(lfm2_cfg(), [](const std::string&) { return std::vector<int32_t>{}; },
|
||||
lfm2_marker), RAD_OK);
|
||||
for (const GoldLfm2Pic& g : kGoldLfm2Pics) {
|
||||
Frame f = frame(g.f, g.h, g.w);
|
||||
if (g.cap > 0) {
|
||||
Frame capped;
|
||||
cap_area(f, g.cap, &capped);
|
||||
f = std::move(capped);
|
||||
}
|
||||
std::shared_ptr<Item> it;
|
||||
std::string why;
|
||||
CHECK_OK(p.image_from(f, &it, &why));
|
||||
REQUIRE(it != nullptr);
|
||||
REQUIRE_EQ(it->n_seg, g.n_seg);
|
||||
const int64_t pd = it->patch_dim;
|
||||
REQUIRE_EQ(pd, (int64_t)3 * kLfm2Patch * kLfm2Patch);
|
||||
for (int32_t s = 0; s < it->n_seg; ++s) {
|
||||
const GoldLfm2Seg& gs = kGoldLfm2Segs[g.seg0 + s];
|
||||
CHECK_EQ(it->seg_h(s), gs.h);
|
||||
CHECK_EQ(it->seg_w(s), gs.w);
|
||||
const int64_t p0 = it->patch_at(s), np = it->patch_at(s + 1) - p0;
|
||||
REQUIRE_EQ(np, (int64_t)gs.h * gs.w);
|
||||
std::vector<int32_t> planes((size_t)(4 * np));
|
||||
it->coords(p0, np, planes.data());
|
||||
std::vector<uint16_t> rowmajor((size_t)(np * pd));
|
||||
for (int64_t k = 0; k < np; ++k) {
|
||||
const int64_t at = (int64_t)planes[(size_t)k] * gs.w + planes[(size_t)(np + k)];
|
||||
std::copy_n(it->pixels.data() + (p0 + k) * pd, pd, rowmajor.data() + at * pd);
|
||||
}
|
||||
if (fnv(rowmajor) != gs.fnv)
|
||||
std::fprintf(stderr, " picture %d x %d, segment %d of %d (%d x %d): patches differ\n",
|
||||
g.h, g.w, s, it->n_seg, gs.h, gs.w);
|
||||
CHECK_EQ(fnv(rowmajor), gs.fnv);
|
||||
}
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
for (int32_t id : it->expand)
|
||||
for (int b = 0; b < 4; ++b) h = (h ^ (uint8_t)((uint32_t)id >> (8 * b))) * 0x100000001b3ull;
|
||||
CHECK_EQ((int32_t)it->expand.size(), g.n_ids);
|
||||
CHECK_EQ(h, g.ids_fnv);
|
||||
/* Each run of placeholders starts where Item::seg_at says, one merged row a token. */
|
||||
REQUIRE_EQ(it->seg_at.size(), (size_t)it->n_seg);
|
||||
for (int32_t s = 0; s < it->n_seg; ++s) {
|
||||
const int64_t at = it->seg_at[(size_t)s], n = it->row_at(s + 1) - it->row_at(s);
|
||||
for (int64_t k = 0; k < n; ++k) CHECK_EQ(it->expand[(size_t)(at + k)], kLfm2ImageToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
+584
-37
@@ -33,6 +33,7 @@
|
||||
#include "place/planner.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
@@ -91,6 +92,13 @@ int rad_memset_async(void* d, int v, int64_t n, RadStream) {
|
||||
if (n > 0) std::memset(d, v, (size_t)n);
|
||||
return RAD_OK;
|
||||
}
|
||||
int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) {
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
int rad_link_hold(RadStream, int) { return RAD_OK; }
|
||||
void* rad_link_gate(RadStream) { return nullptr; }
|
||||
const char* rad_dev_last_error(void) { return ""; }
|
||||
} /* extern "C" */
|
||||
#endif /* RAD_PLACE_TEST_FAKE_DEVICE */
|
||||
@@ -766,11 +774,35 @@ TEST(heat_does_not_thrash_on_an_alternating_pattern) {
|
||||
CHECK(unguarded > 100);
|
||||
}
|
||||
|
||||
/* A PREFILL CHUNK IS CREDITED AS ONE CAPPED HISTOGRAM. Ten times the cap's selections credit a
|
||||
* tenth of each count, so the experts keep their order and one chunk cannot outweigh the decode
|
||||
* steps around it; a histogram under the cap is credited in full. */
|
||||
TEST(heat_caps_what_one_histogram_credits) {
|
||||
HeatFixture hf;
|
||||
HeatEngine h;
|
||||
HeatParams hp;
|
||||
hp.credit_cap = 512.0f;
|
||||
CHECK_OK(h.init(hf.plan, hp));
|
||||
const int32_t a = hf.unit_of_expert(4), b = hf.unit_of_expert(5), c = hf.unit_of_expert(6);
|
||||
|
||||
const int32_t big_ids[2] = {4, 5};
|
||||
const int32_t big[2] = {4000, 1120};
|
||||
h.observe_ids(0, big_ids, big, 2);
|
||||
CHECK(std::fabs(h.heat(a) - 400.0f) < 1e-3f);
|
||||
CHECK(std::fabs(h.heat(b) - 112.0f) < 1e-3f);
|
||||
|
||||
const int32_t small_ids[1] = {6};
|
||||
const int32_t small[1] = {12};
|
||||
h.observe_ids(0, small_ids, small, 1);
|
||||
CHECK_EQ(h.heat(c), 12.0f);
|
||||
CHECK(std::fabs(h.heat(a) - 400.0f * hp.decay) < 1e-3f);
|
||||
}
|
||||
|
||||
TEST(heat_respects_the_move_budget) {
|
||||
HeatFixture hf;
|
||||
HeatEngine h;
|
||||
HeatParams hp;
|
||||
hp.moves_per_dispatch = 3;
|
||||
hp.moves_per_step = 3;
|
||||
hp.min_gain = 0.5f;
|
||||
CHECK_OK(h.init(hf.plan, hp));
|
||||
|
||||
@@ -824,7 +856,7 @@ TEST(heat_step_proposes_exactly_what_repeated_picks_would) {
|
||||
int agreed = 0;
|
||||
for (int trial = 0; trial < 400; ++trial) {
|
||||
HeatParams hp;
|
||||
hp.moves_per_dispatch = 1 + (int)rnd(8);
|
||||
hp.moves_per_step = 1 + (int)rnd(8);
|
||||
hp.min_gain = (float)rnd(3);
|
||||
hp.hysteresis = 1.0f + 0.25f * (float)rnd(3);
|
||||
HeatEngine h;
|
||||
@@ -845,7 +877,7 @@ TEST(heat_step_proposes_exactly_what_repeated_picks_would) {
|
||||
|
||||
HeatEngine ref = h;
|
||||
std::vector<Swap> want;
|
||||
for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) {
|
||||
for (int mv = 0; mv < hp.moves_per_step; ++mv) {
|
||||
Swap sw;
|
||||
if (!ref.pick(&sw)) break;
|
||||
ref.set_busy(sw.promote, true);
|
||||
@@ -896,7 +928,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) {
|
||||
int agreed = 0, crossed = 0, proposed = 0;
|
||||
for (int trial = 0; trial < 400; ++trial) {
|
||||
HeatParams hp;
|
||||
hp.moves_per_dispatch = 1 + (int)rnd(8);
|
||||
hp.moves_per_step = 1 + (int)rnd(8);
|
||||
hp.min_gain = (float)rnd(3);
|
||||
hp.hysteresis = 1.0f + 0.25f * (float)rnd(3);
|
||||
HeatEngine h;
|
||||
@@ -920,7 +952,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) {
|
||||
}
|
||||
for (int k = 0; k < 5; ++k) h.set_busy((int32_t)rnd((uint32_t)n_unit), true);
|
||||
|
||||
/* The reference: repeated picks, each class taking at most `moves_per_dispatch` -- the
|
||||
/* The reference: repeated picks, each class taking at most `moves_per_step` -- the
|
||||
* budget is per class. A pick from a class already at its budget is set aside, busy in
|
||||
* the copy only. */
|
||||
HeatEngine ref = h;
|
||||
@@ -933,7 +965,7 @@ TEST(heat_swaps_stay_inside_a_slab_class) {
|
||||
ref.set_busy(sw.promote, true);
|
||||
ref.set_busy(sw.demote, true);
|
||||
int& n = per[(size_t)plan.units[(size_t)sw.promote].slab_class];
|
||||
if (n >= hp.moves_per_dispatch) {
|
||||
if (n >= hp.moves_per_step) {
|
||||
aside[(size_t)sw.promote] = aside[(size_t)sw.demote] = 1;
|
||||
continue;
|
||||
}
|
||||
@@ -987,7 +1019,7 @@ TEST(heat_step_agrees_with_picks_over_a_run_of_dispatches) {
|
||||
auto rnd = [&](uint32_t n) { x ^= x << 13; x ^= x >> 17; x ^= x << 5; return x % n; };
|
||||
for (int run = 0; run < 20; ++run) {
|
||||
HeatParams hp;
|
||||
hp.moves_per_dispatch = 1 + (int)rnd(3);
|
||||
hp.moves_per_step = 1 + (int)rnd(3);
|
||||
hp.min_gain = 1.0f + (float)rnd(4);
|
||||
hp.hysteresis = 1.0f + 0.25f * (float)rnd(4);
|
||||
HeatEngine h;
|
||||
@@ -1005,7 +1037,7 @@ TEST(heat_step_agrees_with_picks_over_a_run_of_dispatches) {
|
||||
}
|
||||
HeatEngine ref = h;
|
||||
std::vector<Swap> want;
|
||||
for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) {
|
||||
for (int mv = 0; mv < hp.moves_per_step; ++mv) {
|
||||
Swap sw;
|
||||
if (!ref.pick(&sw)) break;
|
||||
ref.set_busy(sw.promote, true);
|
||||
@@ -1075,7 +1107,7 @@ TEST(heat_credits_and_prices_every_layout_the_plan_can_have) {
|
||||
const int32_t n_unit = (int32_t)plan.units.size();
|
||||
|
||||
HeatParams hp;
|
||||
hp.moves_per_dispatch = 3;
|
||||
hp.moves_per_step = 3;
|
||||
HeatEngine h;
|
||||
CHECK_OK(h.init(plan, hp));
|
||||
CHECK(h.enabled());
|
||||
@@ -1118,7 +1150,7 @@ TEST(heat_credits_and_prices_every_layout_the_plan_can_have) {
|
||||
|
||||
HeatEngine ref = h;
|
||||
std::vector<Swap> expect;
|
||||
for (int mv = 0; mv < hp.moves_per_dispatch; ++mv) {
|
||||
for (int mv = 0; mv < hp.moves_per_step; ++mv) {
|
||||
Swap sw;
|
||||
if (!ref.pick(&sw)) break;
|
||||
ref.set_busy(sw.promote, true);
|
||||
@@ -1249,6 +1281,23 @@ TEST(slot_pool_hands_out_and_takes_back) {
|
||||
CHECK(s.empty());
|
||||
}
|
||||
|
||||
/* A TAKE RESTRICTED TO THE SLOTS A CALLER WANTS -- the lowest of them -- leaves every other free
|
||||
* slot free and still handed out lowest first (Mover::pool_slot_for keeps a layer's pool slots
|
||||
* together with it). */
|
||||
TEST(a_slot_pool_takes_the_lowest_slot_a_predicate_wants) {
|
||||
SlotPool s;
|
||||
s.init(8, 64);
|
||||
for (int64_t k : {1, 3, 4, 6, 7}) s.add_free(k);
|
||||
CHECK_EQ(s.take_where([](int64_t k) { return k % 3 == 0; }), (int64_t)3);
|
||||
CHECK_EQ(s.take_where([](int64_t k) { return k == 5; }), (int64_t)-1); /* not free */
|
||||
CHECK_EQ(s.n_free(), (int64_t)4);
|
||||
CHECK_EQ(s.take(), (int64_t)1);
|
||||
CHECK_EQ(s.take_where([](int64_t k) { return k > 4; }), (int64_t)6);
|
||||
CHECK_EQ(s.take(), (int64_t)4);
|
||||
CHECK_EQ(s.take(), (int64_t)7);
|
||||
CHECK(s.empty());
|
||||
}
|
||||
|
||||
TEST(a_slot_pool_grows_only_into_the_capacity_it_was_given) {
|
||||
SlotPool s;
|
||||
s.init(2, 64, 5);
|
||||
@@ -1650,11 +1699,17 @@ struct LoanRig {
|
||||
ComputeWork work;
|
||||
int d = 0;
|
||||
int32_t planned = 0;
|
||||
/* None by default: these tests are about the loan's mechanics, and on a slab this small the
|
||||
* production count would leave most of the loan empty. The turnover test sets its own. */
|
||||
int turnover = 0;
|
||||
|
||||
explicit LoanRig(int n_expert = 8) : hf(n_expert) {}
|
||||
|
||||
int build() {
|
||||
HeatParams hp;
|
||||
RAD_TRY(h.init(hf.plan, hp));
|
||||
MoverConfig mc;
|
||||
mc.turnover_slots = turnover;
|
||||
RAD_TRY(m.init(hf.f.prog, hf.plan, mc));
|
||||
RAD_TRY(rad_stream_create(&compute, 0));
|
||||
RAD_TRY(m.bind_compute_stream(compute));
|
||||
@@ -1711,12 +1766,13 @@ TEST(the_lent_slots_hold_nothing_until_a_loan_covers_them) {
|
||||
}
|
||||
|
||||
/* A LENT SLOT LEFT EMPTY IS VRAM BOUGHT AND WASTED ON EVERY STEP, so a loan is filled in the
|
||||
* dispatch it arrives in -- every slot at once, hottest units first -- and not a few units a step. */
|
||||
* dispatch it arrives in -- every slot past the turnover slots at once, hottest units first -- and
|
||||
* not a few units a step. */
|
||||
TEST(every_lent_slot_is_filled_in_one_dispatch) {
|
||||
LoanRig r;
|
||||
CHECK_OK(r.build());
|
||||
const int64_t slots = r.m.flex_capacity() / r.hf.plan.classes[0].stride;
|
||||
const int64_t expect = std::min<int64_t>(slots, r.pooled());
|
||||
const int64_t expect = std::min<int64_t>(slots - r.m.turnover_slots(), r.pooled());
|
||||
CHECK(expect > 1);
|
||||
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll));
|
||||
@@ -1752,6 +1808,194 @@ TEST(every_lent_slot_is_filled_in_one_dispatch) {
|
||||
CHECK(at[k] - at[k - 1] >= r.hf.plan.classes[0].stride);
|
||||
}
|
||||
|
||||
/* THE TURNOVER SLOTS STAY FREE, AND A SHRINKING LOAN DOES NOT TAKE THEM FOR GOOD. The fill stops
|
||||
* that many slots short of the loan so the engine's swaps have somewhere to land. The free slots
|
||||
* are the loan's top, which is what a cache that wants memory back takes first; the mover then
|
||||
* rebuilds them by dropping the coldest lent units -- each still has its host copy, so nothing
|
||||
* crosses the link -- rather than going without until the loan grows back. */
|
||||
TEST(the_turnover_slots_stay_free_and_are_rebuilt_by_drops) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 2;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_EQ(r.m.turnover_slots(), (int64_t)2);
|
||||
const int64_t slots = r.m.flex_capacity() / r.hf.plan.classes[0].stride;
|
||||
CHECK(r.pooled() > slots); /* more to fill than there is room: only the reserve stops it */
|
||||
|
||||
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());
|
||||
const int32_t full = resident_count(r.h, r.hf.plan);
|
||||
CHECK_EQ(full, r.planned + (int32_t)(slots - 2));
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 2) * r.hf.plan.classes[0].stride);
|
||||
|
||||
/* The fill packs from the bottom, so the free slots are the loan's top: a loan cut to what is
|
||||
* held takes exactly them, and the next dispatch drops two lent units to free two more. */
|
||||
const int64_t held = r.m.loan_held(Mover::kLendKV);
|
||||
CHECK(held < Loan::kAll);
|
||||
const uint64_t d2h = r.m.stats().d2h_bytes;
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, held));
|
||||
for (Deadline dl; (r.m.stats().dropped < 2 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
for (int k = 0; k < 4; ++k) CHECK_OK(r.dispatch());
|
||||
CHECK_EQ(r.m.stats().dropped, (uint64_t)2);
|
||||
CHECK_EQ(r.m.stats().d2h_bytes, d2h); /* nothing crossed the link */
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (slots - 4) * r.hf.plan.classes[0].stride);
|
||||
|
||||
/* A STEP THAT STAGES FILLS THEM: it swaps nothing, and a unit left out is one its stager
|
||||
* copies. The next ordinary step drops the two coldest back out. */
|
||||
CHECK_OK(r.m.begin_dispatch(r.d++, &r.h));
|
||||
r.work.run(r.compute);
|
||||
CHECK_OK(r.m.balance(&r.h, /*turnover=*/false));
|
||||
for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) {
|
||||
CHECK_OK(r.m.begin_dispatch(r.d++, &r.h));
|
||||
r.work.run(r.compute);
|
||||
CHECK_OK(r.m.balance(&r.h, false));
|
||||
}
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), full);
|
||||
for (Deadline dl; (r.m.stats().dropped < 4 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2);
|
||||
CHECK_EQ(r.m.stats().d2h_bytes, d2h);
|
||||
|
||||
/* HELD, AN IDLE TICK FILLS THEM as a staged step does; released, the next one drops them. */
|
||||
r.m.hold_turnover(true);
|
||||
for (Deadline dl; (resident_count(r.h, r.hf.plan) < full || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.m.idle_tick(&r.h));
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), full);
|
||||
r.m.hold_turnover(false);
|
||||
for (Deadline dl; (r.m.stats().dropped < 6 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.m.idle_tick(&r.h));
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), full - 2);
|
||||
CHECK_EQ(r.m.stats().d2h_bytes, d2h);
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* Every weight of every unit stamped with its own bytes, through the device's copies so the same
|
||||
* test runs on a card, and read back from wherever the residency table says it is now. */
|
||||
uint8_t stamp_byte(rad_weight w, size_t i) {
|
||||
uint32_t v = (uint32_t)w * 0x9E3779B1u ^ (uint32_t)i * 0x85EBCA6Bu;
|
||||
v ^= v >> 15; v *= 0x2C1B3C6Du; v ^= v >> 12; v *= 0x297A2D39u; v ^= v >> 15;
|
||||
return (uint8_t)v;
|
||||
}
|
||||
int stamp_units(LoanRig& r, bool check, int* bad) {
|
||||
RadStream s = nullptr;
|
||||
RAD_TRY(rad_stream_create(&s, 0));
|
||||
std::vector<uint8_t> buf;
|
||||
for (const MoveUnit& mu : r.hf.plan.units)
|
||||
for (rad_weight w : mu.weights) {
|
||||
const size_t n = (size_t)r.hf.f.prog.weights[w].logical_bytes;
|
||||
void* at = r.m.residency()->lookup(w)->ptr;
|
||||
buf.resize(n);
|
||||
if (check) {
|
||||
RAD_TRY(rad_memcpy_async(buf.data(), at, (int64_t)n, s));
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
if (buf[i] != stamp_byte(w, i)) { ++*bad; break; }
|
||||
} else {
|
||||
for (size_t i = 0; i < n; ++i) buf[i] = stamp_byte(w, i);
|
||||
RAD_TRY(rad_memcpy_async(at, buf.data(), (int64_t)n, s));
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
}
|
||||
}
|
||||
rad_stream_destroy(s);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A full loan, every unit stamped, then one swap whose budgeted victim finds the pool full: the
|
||||
* promotion lands in a working slot and the victim takes the host copy of a unit in a lent slot. */
|
||||
int donate_once(LoanRig& r, bool held = false) {
|
||||
RAD_TRY(stamp_units(r, false, nullptr));
|
||||
RAD_TRY(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();)
|
||||
RAD_TRY(r.dispatch());
|
||||
int32_t hot = -1, cold = -1;
|
||||
for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u) {
|
||||
if (!r.hf.plan.units[(size_t)u].movable) continue;
|
||||
if (hot < 0 && r.h.tier(u) != Tier::VRAM) hot = u;
|
||||
if (cold < 0 && r.h.tier(u) == Tier::VRAM && !r.loan.inside(r.addr(u))) cold = u;
|
||||
}
|
||||
if (hot < 0 || cold < 0) return RAD_E_STATE;
|
||||
Swap sw;
|
||||
sw.promote = hot;
|
||||
sw.demote = cold;
|
||||
r.h.set_busy(hot, true);
|
||||
r.h.set_busy(cold, true);
|
||||
r.m.hold_turnover(held);
|
||||
RAD_TRY(r.m.issue(sw, &r.h));
|
||||
for (Deadline dl; any_busy(r.h, r.hf.plan) && !dl.passed();) RAD_TRY(r.dispatch());
|
||||
if (held) return r.h.tier(hot) == Tier::VRAM && r.h.tier(cold) == Tier::VRAM ? RAD_OK : RAD_E_STATE;
|
||||
return r.h.tier(hot) == Tier::VRAM && r.h.tier(cold) != Tier::VRAM ? RAD_OK : RAD_E_STATE;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
/* A BUDGETED VICTIM WITH NO POOL SLOT TO GO TO TAKES A LENT UNIT'S HOST COPY (Mover::donor_slot):
|
||||
* the pool is sized to the units that live in it, so it has none free here, and without the
|
||||
* donation the budgeted range would turn over only as fast as its working slots come round. A
|
||||
* recall then moves the donor -- it has no host copy to drop to -- and every unit's bytes are
|
||||
* where its table entry says, throughout. */
|
||||
TEST(a_budgeted_victim_takes_a_lent_units_host_copy_and_a_recall_moves_the_donor) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 2;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_OK(donate_once(r));
|
||||
CHECK_EQ(r.m.stats().donated, (uint64_t)1);
|
||||
CHECK_EQ(r.m.stats().starved_pool, (uint64_t)0);
|
||||
int bad = 0;
|
||||
CHECK_OK(stamp_units(r, true, &bad));
|
||||
CHECK_EQ(bad, 0);
|
||||
|
||||
CHECK_OK(r.m.reclaim(Mover::kLendKV, 0, &r.h));
|
||||
CHECK_EQ(r.m.stats().relocated, (uint64_t)1);
|
||||
CHECK_EQ(r.m.loan_held(Mover::kLendKV), (int64_t)0);
|
||||
for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u)
|
||||
CHECK(!r.loan.inside(r.addr(u)));
|
||||
/* The donor kept its place in VRAM: a working slot was free for it. */
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), r.planned + 1);
|
||||
CHECK_OK(stamp_units(r, true, &bad));
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* NO DONATION WHILE THE TURNOVER SLOTS ARE HELD -- through a prompt and the steps right after it:
|
||||
* the demotion is starved as it was before donation, and the budgeted victim stays. */
|
||||
TEST(a_held_turnover_takes_no_host_copy) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 2;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_OK(donate_once(r, /*held=*/true));
|
||||
CHECK_EQ(r.m.stats().donated, (uint64_t)0);
|
||||
CHECK(r.m.stats().starved_pool >= 1);
|
||||
int bad = 0;
|
||||
CHECK_OK(stamp_units(r, true, &bad));
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* A LOAN THAT SHRINKS UNDER A DONOR moves it out before the slot is given back (balance's sweep):
|
||||
* into the budgeted slot its victim left, a copy inside the card, and the shrink completes once
|
||||
* that lands. The working slot it took is rebuilt the usual way, by demoting the coldest budgeted
|
||||
* unit, and every unit's bytes are where its table entry says throughout. */
|
||||
TEST(a_shrinking_loan_moves_a_donor_out_before_its_slot_is_given_back) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 2;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_OK(donate_once(r));
|
||||
CHECK_EQ(r.m.stats().donated, (uint64_t)1);
|
||||
const uint64_t d2h = r.m.stats().d2h_bytes;
|
||||
|
||||
CHECK_OK(r.m.set_loan(Mover::kLendKV, 0));
|
||||
for (Deadline dl; (r.m.loan_held(Mover::kLendKV) > 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();)
|
||||
CHECK_OK(r.dispatch());
|
||||
CHECK_EQ(r.m.loan_held(Mover::kLendKV), (int64_t)0);
|
||||
CHECK_EQ(r.m.flex_used_bytes(), (int64_t)0);
|
||||
CHECK_EQ(r.m.stats().relocated, (uint64_t)1);
|
||||
CHECK_EQ(r.m.stats().d2h_bytes - d2h, (uint64_t)r.hf.plan.classes[0].stride);
|
||||
CHECK_EQ(resident_count(r.h, r.hf.plan), r.planned);
|
||||
for (int32_t u = 0; u < (int32_t)r.hf.plan.units.size(); ++u)
|
||||
CHECK(!r.loan.inside(r.addr(u)));
|
||||
int bad = 0;
|
||||
CHECK_OK(stamp_units(r, true, &bad));
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* A UNIT IN A LENT SLOT KEEPS ITS HOST COPY, so giving the slot back is a change of address and
|
||||
* not a copy across the link. */
|
||||
TEST(a_shrinking_loan_drops_units_without_copying_them) {
|
||||
@@ -1980,7 +2224,8 @@ TEST(mover_prefetches_staged_units_against_the_declared_order) {
|
||||
/* A ROUTED LAYER'S POOLED UNITS, STAGED FOR ONE PASS (Mover::stage_units). Each copied unit's
|
||||
* weights are published at the copy, settled -- the caller orders their readers with one wait --
|
||||
* and hold the pool slot's bytes; a unit the buffer has no room for keeps its pool address and is
|
||||
* counted; a resident unit is never copied; and unstaging publishes the pool addresses again. */
|
||||
* counted; neighbouring pool slots share a copy; a resident unit is never copied; and unstaging
|
||||
* publishes the pool addresses again. */
|
||||
TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) {
|
||||
HeatFixture hf;
|
||||
Mover m;
|
||||
@@ -2017,6 +2262,19 @@ TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) {
|
||||
CHECK_EQ(m.stats().staged_units, (uint64_t)staged.size());
|
||||
CHECK_EQ(m.stats().stage_layers, (uint64_t)1);
|
||||
|
||||
/* Units on neighbouring pool slots go as one copy, so the copies are the runs of the staged
|
||||
* units' pool addresses -- fewer than the units, since a fresh pool hands slots out in order. */
|
||||
uint64_t runs = 0;
|
||||
const char* run_end = nullptr;
|
||||
for (int32_t u : staged) {
|
||||
const MoveUnit& mu = hf.plan.units[(size_t)u];
|
||||
const char* slot = (const char*)before[mu.weights[0]] - mu.offset[0];
|
||||
if (slot != run_end) ++runs;
|
||||
run_end = slot + each;
|
||||
}
|
||||
CHECK_EQ(m.stats().stage_copies, runs);
|
||||
CHECK(runs < (uint64_t)staged.size());
|
||||
|
||||
/* The copies are on the mover's stream: on the host backend a worker thread runs them. */
|
||||
CHECK_OK(rad_stream_sync(m.transfer_stream()));
|
||||
std::vector<uint8_t> is_staged(hf.plan.units.size(), 0);
|
||||
@@ -2048,15 +2306,16 @@ TEST(a_staged_layer_is_published_at_its_copies_and_unstaged_at_its_pool_slots) {
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
|
||||
/* THE PREFILL STAGER'S ORDER over a pass of two routed layers: the first layer is staged at the
|
||||
* pass's first op, the second at the first layer's first op, each layer is published back at its
|
||||
* pool slots once the next layer starts, and nothing is staged in a pass it did not arm for.
|
||||
/* THE PREFILL STAGER'S ORDER over a pass of two routed layers: at the pass's first op the first
|
||||
* layer goes out and, with room left in the ring, the second behind it; each layer is published
|
||||
* back at its pool slots once the next layer starts; and nothing is staged in a pass it did not
|
||||
* arm for.
|
||||
*
|
||||
* NOT AT ITS OWN LAST OP. A step longer than the MoE block's pass of rows issues a layer's ops once
|
||||
* per pass, so its last op runs again; released at the first run, the second would read copies
|
||||
* the mover is already overwriting with the layer two on, and every token past the first pass of
|
||||
* a step would be garbage. */
|
||||
TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_starts) {
|
||||
* the mover is already overwriting with a layer further on, and every token past the first pass
|
||||
* of a step would be garbage. */
|
||||
TEST(the_stager_stages_ahead_and_releases_each_layer_when_the_next_starts) {
|
||||
Fixture f;
|
||||
const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1);
|
||||
f.op("embed", {emb}, false);
|
||||
@@ -2103,9 +2362,12 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
|
||||
const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT);
|
||||
const int64_t half = each * 8;
|
||||
std::vector<char> region((size_t)(2 * half));
|
||||
auto in_buf = [&](rad_weight w, int b) {
|
||||
const char* p = (const char*)m.residency()->lookup(w)->ptr;
|
||||
return p >= region.data() + b * half && p < region.data() + (b + 1) * half;
|
||||
auto in_ring = [&](const std::vector<rad_weight>& ws) {
|
||||
for (rad_weight w : ws) {
|
||||
const char* p = (const char*)m.residency()->lookup(w)->ptr;
|
||||
if (p < region.data() || p >= region.data() + 2 * half) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
auto at_home = [&](const std::vector<rad_weight>& ws) {
|
||||
for (rad_weight w : ws) if (m.residency()->lookup(w)->ptr != home[w]) return false;
|
||||
@@ -2116,6 +2378,7 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
|
||||
CHECK_OK(st.init(f.prog, plan, &m, region.data(), 2 * half, 64));
|
||||
REQUIRE(st.enabled());
|
||||
CHECK_EQ(st.n_layers(), (size_t)2);
|
||||
CHECK_EQ(st.ring_bytes(), 2 * half);
|
||||
|
||||
RadBatch b{};
|
||||
b.n_tok = 8;
|
||||
@@ -2128,38 +2391,39 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
|
||||
CHECK(st.begin_pass(&b));
|
||||
|
||||
bool resync = false;
|
||||
CHECK_OK(st.before_op(0, compute, &resync)); /* embed: the first layer goes out */
|
||||
CHECK_OK(st.before_op(0, compute, &resync)); /* embed: both layers go out */
|
||||
CHECK(resync);
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK(at_home(p1));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK(in_ring(p1));
|
||||
CHECK_OK(st.after_op(0, compute));
|
||||
CHECK_OK(st.before_op(1, compute, &resync)); /* attn0: nothing */
|
||||
CHECK(!resync);
|
||||
CHECK_OK(st.before_op(2, compute, &resync)); /* moe0: the second layer goes out */
|
||||
CHECK(resync);
|
||||
for (rad_weight w : p1) CHECK(in_buf(w, 1));
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK_OK(st.before_op(2, compute, &resync)); /* moe0: nothing left to stage */
|
||||
CHECK(!resync);
|
||||
CHECK(in_ring(p0));
|
||||
CHECK(in_ring(p1));
|
||||
CHECK_OK(st.after_op(2, compute)); /* moe0 is layer 0's last op... */
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK_OK(st.before_op(2, compute, &resync)); /* ...and runs again for the next rows */
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK_OK(st.after_op(2, compute));
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
for (rad_weight w : p1) CHECK(in_buf(w, 1));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK(in_ring(p1));
|
||||
CHECK_OK(st.before_op(3, compute, &resync)); /* attn1 */
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK_OK(st.before_op(4, compute, &resync)); /* moe1: layer 0 is past every pass */
|
||||
CHECK(at_home(p0));
|
||||
for (rad_weight w : p1) CHECK(in_buf(w, 1));
|
||||
CHECK(in_ring(p1));
|
||||
CHECK_OK(st.after_op(4, compute));
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
CHECK(at_home(p1));
|
||||
CHECK_EQ(m.stats().stage_layers, (uint64_t)2);
|
||||
CHECK_EQ(m.stats().stage_overflow, (uint64_t)0);
|
||||
|
||||
/* A pass that ends after its first layer went out leaves nothing published at a copy. */
|
||||
/* A pass that ends after its first op leaves nothing published at a copy. */
|
||||
CHECK(st.begin_pass(&b));
|
||||
CHECK_OK(st.before_op(0, compute, &resync));
|
||||
for (rad_weight w : p0) CHECK(in_buf(w, 0));
|
||||
CHECK(in_ring(p0));
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
CHECK(at_home(p0));
|
||||
CHECK(at_home(p1));
|
||||
@@ -2168,6 +2432,289 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
|
||||
/* THE RING OVER MANY LAYERS AND PASSES: room for three and a half layers, six layers a pass, three
|
||||
* passes, so places lap the region and wrap past its end. At every op, the layers still published
|
||||
* at copies sit in the ring without overlapping one another; at a layer's first op every one of
|
||||
* its pooled units is published at a copy holding the pool slot's bytes and the layers before it
|
||||
* are home; the copies go out more than one layer ahead whenever the room allows; and nothing
|
||||
* spills to a read in place. */
|
||||
TEST(the_stager_ring_laps_without_overwriting_a_published_layer) {
|
||||
Fixture f;
|
||||
const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1);
|
||||
f.op("embed", {emb}, false);
|
||||
constexpr int kL = 6, kE = 8;
|
||||
std::vector<std::vector<rad_weight>> lw(kL);
|
||||
for (int l = 0; l < kL; ++l)
|
||||
for (int e = 0; e < kE; ++e)
|
||||
lw[(size_t)l].push_back(f.weight("blk." + std::to_string(l) + ".ffn_gate_exps." +
|
||||
std::to_string(e) + ".weight", 1 * MiB,
|
||||
RAD_ACCESS_CONDITIONAL, l, e));
|
||||
for (int l = 0; l < kL; ++l) {
|
||||
f.op("attn" + std::to_string(l), {}, false);
|
||||
f.op("moe" + std::to_string(l), lw[(size_t)l], false);
|
||||
}
|
||||
Config cfg = base_config();
|
||||
cfg.placement = "expert_tiered";
|
||||
cfg.vram_weights_mib = 16;
|
||||
cfg.host_pool_mib = 128;
|
||||
Plan plan;
|
||||
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_OK(Planner(in).plan(&plan));
|
||||
REQUIRE(plan.dynamic);
|
||||
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
CHECK_OK(m.init(f.prog, plan, mc));
|
||||
RadStream compute = nullptr;
|
||||
CHECK_OK(rad_stream_create(&compute, 0));
|
||||
CHECK_OK(m.bind_compute_stream(compute));
|
||||
|
||||
std::vector<std::vector<rad_weight>> pw(kL);
|
||||
int64_t most = 0;
|
||||
const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT);
|
||||
for (int l = 0; l < kL; ++l) {
|
||||
for (rad_weight w : lw[(size_t)l])
|
||||
if (plan.weight[w].tier == Tier::HostPinned) pw[(size_t)l].push_back(w);
|
||||
most = std::max(most, each * (int64_t)pw[(size_t)l].size());
|
||||
}
|
||||
REQUIRE(most > 0);
|
||||
std::vector<void*> home(f.prog.weights.size(), nullptr);
|
||||
for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w)
|
||||
home[w] = m.residency()->lookup(w)->ptr;
|
||||
|
||||
/* Three and a half of the heaviest layer: three go out at the pass's first op, and the fourth
|
||||
* runs past the region's end. */
|
||||
const int64_t ring = most * 7 / 2 / (2 * RAD_ALIGN_UNIT) * (2 * RAD_ALIGN_UNIT);
|
||||
std::vector<char> region((size_t)ring);
|
||||
PrefillStager st;
|
||||
CHECK_OK(st.init(f.prog, plan, &m, region.data(), ring, 64));
|
||||
REQUIRE(st.enabled());
|
||||
CHECK_EQ(st.n_layers(), (size_t)kL);
|
||||
REQUIRE(st.ring_bytes() == ring);
|
||||
|
||||
auto in_ring = [&](rad_weight w) {
|
||||
const char* p = (const char*)m.residency()->lookup(w)->ptr;
|
||||
return p >= region.data() && p < region.data() + ring;
|
||||
};
|
||||
/* The layers published at copies, and whether any two of their units share a byte. */
|
||||
auto published = [&](std::vector<int>* ls) {
|
||||
std::vector<std::pair<const char*, const char*>> spans;
|
||||
ls->clear();
|
||||
for (int l = 0; l < kL; ++l) {
|
||||
bool any = false;
|
||||
for (rad_weight w : pw[(size_t)l])
|
||||
if (in_ring(w)) {
|
||||
const char* p = (const char*)m.residency()->lookup(w)->ptr;
|
||||
spans.emplace_back(p, p + f.prog.weights[w].logical_bytes);
|
||||
any = true;
|
||||
}
|
||||
if (any) ls->push_back(l);
|
||||
}
|
||||
std::sort(spans.begin(), spans.end());
|
||||
for (size_t i = 1; i < spans.size(); ++i)
|
||||
if (spans[i].first < spans[i - 1].second) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
RadBatch b{};
|
||||
b.n_tok = 128;
|
||||
st.set_full_arena(true);
|
||||
bool ran_ahead = false;
|
||||
std::vector<int> ls;
|
||||
for (int pass = 0; pass < 3; ++pass) {
|
||||
CHECK(st.begin_pass(&b));
|
||||
const int n_ops = 1 + 2 * kL;
|
||||
for (int h = 0; h < n_ops; ++h) {
|
||||
bool resync = false;
|
||||
CHECK_OK(st.before_op(h, compute, &resync));
|
||||
CHECK(published(&ls));
|
||||
if (h >= 2 && h % 2 == 0) {
|
||||
const int l = (h - 2) / 2; /* moe_l: the layer's first and last op */
|
||||
for (int k = 0; k < l; ++k)
|
||||
for (rad_weight w : pw[(size_t)k]) CHECK(!in_ring(w));
|
||||
/* Its copies, settled: the wait the stager issued orders the op; here the test
|
||||
* drains the mover's stream to read them. */
|
||||
CHECK_OK(rad_stream_sync(m.transfer_stream()));
|
||||
for (rad_weight w : pw[(size_t)l]) {
|
||||
CHECK(in_ring(w));
|
||||
CHECK(std::memcmp(m.residency()->lookup(w)->ptr, home[w],
|
||||
(size_t)f.prog.weights[w].logical_bytes) == 0);
|
||||
}
|
||||
if (ls.size() > 2) ran_ahead = true;
|
||||
}
|
||||
CHECK_OK(st.after_op(h, compute));
|
||||
}
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
for (int l = 0; l < kL; ++l)
|
||||
for (rad_weight w : pw[(size_t)l]) CHECK(m.residency()->lookup(w)->ptr == home[w]);
|
||||
}
|
||||
CHECK(ran_ahead);
|
||||
CHECK_EQ(m.stats().stage_overflow, (uint64_t)0);
|
||||
CHECK_OK(rad_stream_sync(m.transfer_stream()));
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
|
||||
/* THE NEXT STEP'S FIRST LAYERS AND THE DRAFT HEAD. Six trunk layers and a declared draft head's
|
||||
* seventh. The head's layer is not staged at all. With the next step going on with a prompt, a
|
||||
* pass's end stages the next trunk pass's first PrefillStager::lead() layers; a draft pass in
|
||||
* between neither arms nor touches them; the next armed trunk pass reads them where they are, with
|
||||
* the copies holding the pool's bytes; and a trunk pass that does not arm publishes them at home
|
||||
* again before it resolves anything. */
|
||||
TEST(the_stager_stages_the_next_steps_first_layers_and_never_the_draft_head) {
|
||||
Fixture f;
|
||||
const rad_weight emb = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1);
|
||||
f.op("embed", {emb}, false);
|
||||
constexpr int kL = 7, kE = 8; /* layer 6 is the draft head's */
|
||||
std::vector<std::vector<rad_weight>> lw(kL);
|
||||
for (int l = 0; l < kL; ++l)
|
||||
for (int e = 0; e < kE; ++e)
|
||||
lw[(size_t)l].push_back(f.weight("blk." + std::to_string(l) + ".ffn_gate_exps." +
|
||||
std::to_string(e) + ".weight", 1 * MiB,
|
||||
RAD_ACCESS_CONDITIONAL, l, e));
|
||||
for (int l = 0; l < kL; ++l) {
|
||||
f.op("attn" + std::to_string(l), {}, false);
|
||||
f.op("moe" + std::to_string(l), lw[(size_t)l], false);
|
||||
}
|
||||
f.prog.drafter.kind = RAD_DRAFT_SERIAL;
|
||||
f.prog.meta.n_layers = kL - 1;
|
||||
Config cfg = base_config();
|
||||
cfg.placement = "expert_tiered";
|
||||
cfg.vram_weights_mib = 16;
|
||||
cfg.host_pool_mib = 128;
|
||||
Plan plan;
|
||||
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_OK(Planner(in).plan(&plan));
|
||||
REQUIRE(plan.dynamic);
|
||||
|
||||
Mover m;
|
||||
MoverConfig mc;
|
||||
CHECK_OK(m.init(f.prog, plan, mc));
|
||||
RadStream compute = nullptr;
|
||||
CHECK_OK(rad_stream_create(&compute, 0));
|
||||
CHECK_OK(m.bind_compute_stream(compute));
|
||||
|
||||
std::vector<std::vector<rad_weight>> pw(kL);
|
||||
int64_t most = 0;
|
||||
const int64_t each = align_up(1 * MiB, RAD_ALIGN_UNIT);
|
||||
for (int l = 0; l < kL; ++l) {
|
||||
for (rad_weight w : lw[(size_t)l])
|
||||
if (plan.weight[w].tier == Tier::HostPinned) pw[(size_t)l].push_back(w);
|
||||
most = std::max(most, each * (int64_t)pw[(size_t)l].size());
|
||||
}
|
||||
REQUIRE(most > 0);
|
||||
for (int l = 0; l < kL; ++l) REQUIRE(!pw[(size_t)l].empty());
|
||||
std::vector<void*> home(f.prog.weights.size(), nullptr);
|
||||
for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w)
|
||||
home[w] = m.residency()->lookup(w)->ptr;
|
||||
|
||||
/* Room for every trunk layer at once: what the ring holds is the pace's doing, not its size. */
|
||||
const int64_t ring = most * 8 / (2 * RAD_ALIGN_UNIT) * (2 * RAD_ALIGN_UNIT);
|
||||
std::vector<char> region((size_t)ring);
|
||||
PrefillStager st;
|
||||
CHECK_OK(st.init(f.prog, plan, &m, region.data(), ring, 64));
|
||||
REQUIRE(st.enabled());
|
||||
CHECK_EQ(st.n_layers(), (size_t)(kL - 1));
|
||||
const int lead = (int)PrefillStager::lead();
|
||||
REQUIRE(lead >= 1 && lead < kL - 1);
|
||||
|
||||
auto in_ring = [&](int l) {
|
||||
for (rad_weight w : pw[(size_t)l]) {
|
||||
const char* p = (const char*)m.residency()->lookup(w)->ptr;
|
||||
if (p < region.data() || p >= region.data() + ring) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
auto at_home = [&](int l) {
|
||||
for (rad_weight w : pw[(size_t)l]) if (m.residency()->lookup(w)->ptr != home[w]) return false;
|
||||
return true;
|
||||
};
|
||||
auto copies_hold_the_pool = [&](int l) {
|
||||
CHECK_OK(rad_stream_sync(m.transfer_stream()));
|
||||
for (rad_weight w : pw[(size_t)l])
|
||||
if (std::memcmp(m.residency()->lookup(w)->ptr, home[w],
|
||||
(size_t)f.prog.weights[w].logical_bytes) != 0) return false;
|
||||
return true;
|
||||
};
|
||||
/* A whole trunk pass, checking at each layer's MoE that it reads copies and that the head's
|
||||
* layer is never anywhere but home. */
|
||||
const int n_ops = 1 + 2 * (kL - 1);
|
||||
auto run_pass = [&]() {
|
||||
for (int h = 0; h < n_ops; ++h) {
|
||||
bool resync = false;
|
||||
CHECK_OK(st.before_op(h, compute, &resync));
|
||||
if (h >= 2 && h % 2 == 0) {
|
||||
const int l = (h - 2) / 2;
|
||||
CHECK(in_ring(l));
|
||||
CHECK(copies_hold_the_pool(l));
|
||||
}
|
||||
CHECK(at_home(kL - 1));
|
||||
CHECK_OK(st.after_op(h, compute));
|
||||
}
|
||||
};
|
||||
|
||||
RadBatch b{};
|
||||
b.n_tok = 128;
|
||||
st.set_full_arena(true);
|
||||
|
||||
/* No next step: the end leaves everything home. The engine asks whether the step staged
|
||||
* after the pass has ended, so the answer outlives end_pass. */
|
||||
CHECK(!st.staged());
|
||||
st.set_next_prefill(false);
|
||||
CHECK(st.begin_pass(&b));
|
||||
run_pass();
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
CHECK(st.staged());
|
||||
for (int l = 0; l < kL; ++l) CHECK(at_home(l));
|
||||
|
||||
/* The next step goes on: the first `lead` layers go out at the end. */
|
||||
st.set_next_prefill(true);
|
||||
CHECK(st.begin_pass(&b));
|
||||
run_pass();
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
for (int l = 0; l < kL; ++l) CHECK(l < lead ? in_ring(l) : at_home(l));
|
||||
for (int l = 0; l < lead; ++l) CHECK(copies_hold_the_pool(l));
|
||||
|
||||
/* A draft pass neither arms nor gives them back, and leaves the trunk pass's answer. */
|
||||
RadBatch d = b;
|
||||
d.draft_pass = -1;
|
||||
CHECK(!st.begin_pass(&d));
|
||||
CHECK(st.staged());
|
||||
for (int l = 0; l < lead; ++l) CHECK(in_ring(l));
|
||||
|
||||
/* The next armed trunk pass reads them there, and stages nothing at its first op that is
|
||||
* already out. */
|
||||
const uint64_t layers_before = m.stats().stage_layers;
|
||||
st.set_next_prefill(true);
|
||||
CHECK(st.begin_pass(&b));
|
||||
{
|
||||
bool resync = false;
|
||||
CHECK_OK(st.before_op(0, compute, &resync));
|
||||
CHECK_EQ(m.stats().stage_layers, layers_before);
|
||||
CHECK_OK(st.after_op(0, compute));
|
||||
}
|
||||
for (int h = 1; h < n_ops; ++h) {
|
||||
bool resync = false;
|
||||
CHECK_OK(st.before_op(h, compute, &resync));
|
||||
if (h >= 2 && h % 2 == 0) {
|
||||
const int l = (h - 2) / 2;
|
||||
CHECK(in_ring(l));
|
||||
CHECK(copies_hold_the_pool(l));
|
||||
}
|
||||
CHECK_OK(st.after_op(h, compute));
|
||||
}
|
||||
CHECK_OK(st.end_pass(compute));
|
||||
for (int l = 0; l < kL; ++l) CHECK(l < lead ? in_ring(l) : at_home(l));
|
||||
|
||||
/* A trunk pass too small to arm: everything home before it resolves a table. */
|
||||
b.n_tok = 8;
|
||||
CHECK(!st.begin_pass(&b));
|
||||
CHECK(!st.staged());
|
||||
for (int l = 0; l < kL; ++l) CHECK(at_home(l));
|
||||
CHECK_EQ(m.stats().stage_overflow, (uint64_t)0);
|
||||
CHECK_OK(rad_stream_sync(m.transfer_stream()));
|
||||
rad_stream_destroy(compute);
|
||||
}
|
||||
|
||||
TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) {
|
||||
/* THE PRODUCTION PATH. Pools has already allocated the weights pool as one block; a mover
|
||||
* that called the allocator beside it would spend that budget twice and the overrun would
|
||||
|
||||
@@ -258,6 +258,7 @@ TEST(op_vocabulary) {
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows",
|
||||
"relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu",
|
||||
"sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
|
||||
"causal_conv1d",
|
||||
"embed_lookup_q", "cast",
|
||||
"scale_rows",
|
||||
"softmax",
|
||||
@@ -269,6 +270,7 @@ TEST(op_vocabulary) {
|
||||
"gated_had_quant_i8",
|
||||
"dequant",
|
||||
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
|
||||
"grid_embed_aa",
|
||||
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key",
|
||||
"router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather",
|
||||
"row_topk",
|
||||
@@ -720,6 +722,110 @@ TEST(op_ple_conv) {
|
||||
}
|
||||
}
|
||||
|
||||
/* SigLIP2's position resample, against torch's own F.interpolate(bilinear, align_corners=False,
|
||||
* antialias=True) of the same 4 x 4 x 2 table: shrinking to 2 x 3 (the filter widens), growing to
|
||||
* 6 x 5 (half-pixel taps, edges clamped) and to 1 x 1 (the whole table, averaged). */
|
||||
TEST(op_grid_embed_aa_is_torchs_antialiased_bilinear) {
|
||||
const int side = 4, n = 2;
|
||||
T tab(RAD_F32, {side * side, n});
|
||||
tab.f({ 0.0f, -0.5f, 0.25f, 1.25f, 0.5f, 0.0f, 0.75f, 1.75f, 1.0f, 2.0f, 1.25f, 0.75f, 1.5f, 2.5f,
|
||||
1.75f, 1.25f, 2.0f, 1.5f, 2.25f, 3.25f, 2.5f, 2.0f, 2.75f, 3.75f, 3.0f, 4.0f, 3.25f,
|
||||
2.75f, 3.5f, 4.5f, 3.75f, 3.25f });
|
||||
struct G { int h, w; std::vector<float> want; };
|
||||
const G cases[] = {
|
||||
{ 2, 3, { 0.789286f, 0.996429f, 1.089286f, 1.339286f, 1.389286f, 1.682143f, 2.360714f,
|
||||
2.653571f, 2.660714f, 2.910714f, 2.960714f, 3.167857f } },
|
||||
{ 6, 5, { 0.0f, -0.5f, 0.175f, 0.725f, 0.375f, 0.625f, 0.575f, 0.525f, 0.75f, 1.75f, 0.5f,
|
||||
0.75f, 0.675f, 0.925f, 0.875f, 1.125f, 1.075f, 1.325f, 1.25f, 1.5f, 1.166667f,
|
||||
1.916667f, 1.341667f, 1.391667f, 1.541667f, 1.791667f, 1.741667f, 2.191667f,
|
||||
1.916667f, 1.666667f, 1.833333f, 1.583333f, 2.008333f, 2.458334f, 2.208333f,
|
||||
2.458333f, 2.408334f, 2.458333f, 2.583333f, 3.333334f, 2.5f, 2.75f, 2.675f,
|
||||
2.925f, 2.875f, 3.125f, 3.075f, 3.325f, 3.25f, 3.5f, 3.0f, 4.0f, 3.175f, 3.125f,
|
||||
3.375f, 3.625f, 3.575f, 4.125f, 3.75f, 3.25f } },
|
||||
{ 1, 1, { 1.875f, 2.125f } },
|
||||
};
|
||||
for (const G& g : cases) {
|
||||
const int M = g.h * g.w;
|
||||
T x(RAD_F32, {M, n});
|
||||
std::vector<float> zero((size_t)(M * n), 0.0f);
|
||||
x.f(zero);
|
||||
T crd(RAD_I32, {4, M});
|
||||
std::vector<int64_t> c((size_t)(4 * M));
|
||||
for (int r = 0; r < M; ++r) {
|
||||
c[(size_t)r] = r / g.w;
|
||||
c[(size_t)(M + r)] = r % g.w;
|
||||
c[(size_t)(2 * M + r)] = g.h;
|
||||
c[(size_t)(3 * M + r)] = g.w;
|
||||
}
|
||||
crd.n(c);
|
||||
A a; a.t(x).t(tab).t(crd).i("M", M).i("n", n).i("side", side).s("dtype", "f32");
|
||||
CHECK_OK(run("grid_embed_aa", a));
|
||||
for (int i = 0; i < M * n; ++i) CHECK_NEAR(x.at(i), g.want[(size_t)i], 2e-5);
|
||||
}
|
||||
}
|
||||
|
||||
/* LFM2's short convolution: ple_conv's window at dilation one, with no activation. */
|
||||
TEST(op_causal_conv1d) {
|
||||
const int n = 1, wid = 3;
|
||||
/* COLD: zeros in front of the sequence, and the last width-1 inputs left at offset zero. */
|
||||
{
|
||||
T x(RAD_F32, {4, 1}); x.f({ 1, 2, 3, 4 });
|
||||
T w(RAD_F32, {1, 3}); w.f({ 100, 10, 1 });
|
||||
T cs(RAD_F32, {1, 1, 2}); cs.f({ 7, 7 }); /* a recycled slot's leftovers */
|
||||
T cu(RAD_I32, {2}); cu.n({ 0, 4 });
|
||||
T ci(RAD_I32, {1}); ci.n({ 0 });
|
||||
T hi(RAD_I32, {1}); hi.n({ 0 });
|
||||
T y(RAD_F32, {4, 1});
|
||||
A a; a.t(x).t(w).t(cs).t(cu).t(ci).t(hi).tnull().t(y)
|
||||
.i("M", 4).i("n", n).i("width", wid).s("dtype", "f32");
|
||||
CHECK_OK(run("causal_conv1d", a));
|
||||
CHECK_NEAR(y.at(0), 1.0f, 1e-5); /* 0, 0, 1 -- no silu */
|
||||
CHECK_NEAR(y.at(1), 12.0f, 1e-5); /* 0, 1, 2 */
|
||||
CHECK_NEAR(y.at(3), 234.0f, 1e-5); /* 2, 3, 4 */
|
||||
CHECK_EQ(cs.at(0), 3.0f);
|
||||
CHECK_EQ(cs.at(1), 4.0f);
|
||||
}
|
||||
/* WARM, as two chunks, then a decode step read at num_accepted - 1. */
|
||||
{
|
||||
T w(RAD_F32, {1, 3}); w.f({ 100, 10, 1 });
|
||||
T cs(RAD_F32, {1, 1, 4}); cs.f({ 0, 0, 0, 0 });
|
||||
T ci(RAD_I32, {1}); ci.n({ 0 });
|
||||
T cold(RAD_I32, {1}); cold.n({ 0 });
|
||||
T warm(RAD_I32, {1}); warm.n({ 1 });
|
||||
T x1(RAD_F32, {3, 1}); x1.f({ 1, 2, 3 });
|
||||
T cu1(RAD_I32, {2}); cu1.n({ 0, 3 });
|
||||
T y1(RAD_F32, {3, 1});
|
||||
A a; a.t(x1).t(w).t(cs).t(cu1).t(ci).t(cold).tnull().t(y1)
|
||||
.i("M", 3).i("n", n).i("width", wid).s("dtype", "f32");
|
||||
CHECK_OK(run("causal_conv1d", a));
|
||||
T x2(RAD_F32, {1, 1}); x2.f({ 4 });
|
||||
T cu2(RAD_I32, {2}); cu2.n({ 0, 1 });
|
||||
T y2(RAD_F32, {1, 1});
|
||||
A b; b.t(x2).t(w).t(cs).t(cu2).t(ci).t(warm).tnull().t(y2)
|
||||
.i("M", 1).i("n", n).i("width", wid).s("dtype", "f32");
|
||||
CHECK_OK(run("causal_conv1d", b));
|
||||
CHECK_NEAR(y2.at(0), 234.0f, 1e-5); /* the one-pass t=3 */
|
||||
/* A verify of two drafts (5, 6) behind it, then a step that kept one of them. */
|
||||
T x3(RAD_F32, {2, 1}); x3.f({ 5, 6 });
|
||||
T cu3(RAD_I32, {2}); cu3.n({ 0, 2 });
|
||||
T na1(RAD_I32, {1}); na1.n({ 1 });
|
||||
T y3(RAD_F32, {2, 1});
|
||||
A c; c.t(x3).t(w).t(cs).t(cu3).t(ci).t(warm).t(na1).t(y3)
|
||||
.i("M", 2).i("n", n).i("width", wid).s("dtype", "f32");
|
||||
CHECK_OK(run("causal_conv1d", c));
|
||||
CHECK_NEAR(y3.at(0), 345.0f, 1e-5);
|
||||
CHECK_NEAR(y3.at(1), 456.0f, 1e-5);
|
||||
T x4(RAD_F32, {1, 1}); x4.f({ 9 });
|
||||
T cu4(RAD_I32, {2}); cu4.n({ 0, 1 });
|
||||
T na2(RAD_I32, {1}); na2.n({ 1 }); /* only 5 was kept: history is (4, 5) */
|
||||
T y4(RAD_F32, {1, 1});
|
||||
A d; d.t(x4).t(w).t(cs).t(cu4).t(ci).t(warm).t(na2).t(y4)
|
||||
.i("M", 1).i("n", n).i("width", wid).s("dtype", "f32");
|
||||
CHECK_OK(run("causal_conv1d", d));
|
||||
CHECK_NEAR(y4.at(0), 459.0f, 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
/* PLE's n-gram ids, ON THE REAL CHECKPOINT CONSTANTS.
|
||||
*
|
||||
* The multipliers, vocab sizes and offsets below are the bytes of
|
||||
|
||||
@@ -90,6 +90,13 @@ WEAKDEF int rad_memcpy_2d_async(void* d, int64_t dp, const void* s, int64_t sp,
|
||||
WEAKDEF int rad_memset_async(void* d, int v, int64_t n, RadStream) {
|
||||
std::memset(d, v, (size_t)n); return RAD_OK;
|
||||
}
|
||||
WEAKDEF int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) {
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
WEAKDEF int rad_link_hold(RadStream, int) { return RAD_OK; }
|
||||
WEAKDEF void* rad_link_gate(RadStream) { return nullptr; }
|
||||
WEAKDEF const char* rad_dev_last_error(void) { return "none"; }
|
||||
|
||||
} /* extern "C" */
|
||||
|
||||
@@ -82,6 +82,13 @@ __attribute__((weak)) int rad_memcpy_ranges_async(void* d, const void* s, int64_
|
||||
std::memcpy((char*)d + r[i].dst, (const char*)s + r[i].src, (size_t)r[i].bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
__attribute__((weak)) int rad_memcpy_list_async(const RadCopySeg* g, int n, unsigned, RadStream) {
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (g[i].bytes > 0) std::memcpy(g[i].dst, g[i].src, (size_t)g[i].bytes);
|
||||
return RAD_OK;
|
||||
}
|
||||
__attribute__((weak)) int rad_link_hold(RadStream, int) { return RAD_OK; }
|
||||
__attribute__((weak)) void* rad_link_gate(RadStream) { return nullptr; }
|
||||
|
||||
static int g_fake_event;
|
||||
__attribute__((weak)) int rad_event_create(RadEvent* e) { *e = &g_fake_event; return RAD_OK; }
|
||||
@@ -501,6 +508,7 @@ struct Fixture {
|
||||
g_gdn_row = KernelRow{ &g_gdn_ki, "fake", 0, 0 };
|
||||
|
||||
prog.meta.n_ctx_train = 4096;
|
||||
prog.meta.n_vocab = 512;
|
||||
|
||||
/* index 0 is the sentinel every handle table in Program carries */
|
||||
prog.ops.emplace_back();
|
||||
@@ -698,6 +706,38 @@ TEST(prefill_chunks_split_at_the_checkpoint_interval) {
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 1000, 50, &ck), 0);
|
||||
}
|
||||
|
||||
/* A REQUEST'S OWN CHECKPOINT (Request::checkpoint_at): the end of a head other requests share,
|
||||
* on the quantum below it. It splits a chunk the way the interval does and gives way to nothing. */
|
||||
TEST(prefill_chunks_split_where_the_request_asks_for_a_checkpoint) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
|
||||
int64_t ck = -1;
|
||||
/* Inside the first interval, where nothing else would write one: split at 128, the quantum
|
||||
* under 150, then the rest with none. */
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck, 150), 128);
|
||||
CHECK_EQ(ck, 128);
|
||||
CHECK_EQ(f.sch.plan_chunk(128, 200, 512, &ck, 150), 72);
|
||||
CHECK_EQ(ck, -1);
|
||||
/* Past the interval checkpoint that comes first, and before the next one. */
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 1000, 512, &ck, 600), 256);
|
||||
CHECK_EQ(ck, 256);
|
||||
CHECK_EQ(f.sch.plan_chunk(512, 1000, 512, &ck, 600), 64);
|
||||
CHECK_EQ(ck, 576);
|
||||
/* On a boundary the chunk would end on anyway, it is that boundary's checkpoint. */
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 1000, 512, &ck, 256), 256);
|
||||
CHECK_EQ(ck, 256);
|
||||
/* A head shorter than a quantum has no boundary to keep. */
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck, 40), 200);
|
||||
CHECK_EQ(ck, -1);
|
||||
/* And a budget short of it still ends on a quantum, the checkpoint left for a later chunk. */
|
||||
CHECK_EQ(f.sch.plan_chunk(0, 1000, 100, &ck, 150), 64);
|
||||
CHECK_EQ(ck, -1);
|
||||
CHECK_EQ(f.sch.plan_chunk(64, 1000, 512, &ck, 150), 64);
|
||||
CHECK_EQ(ck, 128);
|
||||
}
|
||||
|
||||
TEST(a_chunk_ending_on_a_checkpoint_carries_it_into_the_batch) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
@@ -802,6 +842,33 @@ TEST(add_all_queues_a_set_under_one_lock_and_refuses_members_singly) {
|
||||
CHECK_EQ(f.sch.metrics().admitted, 2);
|
||||
}
|
||||
|
||||
/* A scored prompt (Request::token_scores) names real vocabulary rows, and drafts nothing. */
|
||||
TEST(a_scored_request_names_real_vocabulary_rows) {
|
||||
Fixture f;
|
||||
f.build(/*blocks=*/20, /*states=*/64);
|
||||
CHECK_OK(f.start());
|
||||
const int32_t n_vocab = (int32_t)f.prog.meta.n_vocab;
|
||||
REQUIRE(n_vocab > 2);
|
||||
std::unique_ptr<Request> rs[4];
|
||||
const std::vector<std::vector<int32_t>> ids = { { 1, 2 }, {}, { n_vocab }, { -1 } };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
rs[i] = std::make_unique<Request>();
|
||||
rs[i]->id = f.next_id++;
|
||||
rs[i]->max_tokens = 1;
|
||||
rs[i]->prompt.assign(16, 7);
|
||||
rs[i]->token_scores = std::make_shared<TokenScores>();
|
||||
rs[i]->token_scores->tokens = ids[(size_t)i];
|
||||
}
|
||||
Request* kept = rs[0].get();
|
||||
int rc[4] = { -1, -1, -1, -1 };
|
||||
f.sch.add_all(rs, 4, rc);
|
||||
CHECK_EQ(rc[0], RAD_OK);
|
||||
CHECK_EQ(rc[1], RAD_E_INVAL);
|
||||
CHECK_EQ(rc[2], RAD_E_INVAL);
|
||||
CHECK_EQ(rc[3], RAD_E_INVAL);
|
||||
CHECK(!kept->may_speculate);
|
||||
}
|
||||
|
||||
TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
|
||||
@@ -2888,6 +2888,41 @@ TEST(server_info_drops_an_engine_blob_that_is_not_an_object) {
|
||||
CHECK(has(r2.body, "\"arch\":\"testarch\""));
|
||||
}
|
||||
|
||||
/* /diagnostics DESCRIBES THE HOST, so without a key it answers this machine only. With a key the
|
||||
* transport's gate has already checked the caller, and any address may ask. */
|
||||
TEST(diagnostics_without_a_key_answers_loopback_only) {
|
||||
FakeScheduler sched;
|
||||
FakeTokenizer tok;
|
||||
Deps d;
|
||||
d.sched = &sched;
|
||||
d.tok = &tok;
|
||||
ServerOptions o;
|
||||
o.model_id = "test-model";
|
||||
o.diagnostics_json = [] { return std::string(R"({"findings":[]})"); };
|
||||
Server srv(d, o);
|
||||
auto from = [](Server& s, const char* peer) {
|
||||
HttpRequest q;
|
||||
q.path = "/diagnostics";
|
||||
q.peer = peer;
|
||||
return s.router().dispatch(q).status;
|
||||
};
|
||||
CHECK_EQ(from(srv, "127.0.0.1:50122"), 200);
|
||||
CHECK_EQ(from(srv, "127.8.9.10:50122"), 200);
|
||||
CHECK_EQ(from(srv, "::1:50122"), 200);
|
||||
CHECK_EQ(from(srv, "[::1]:50122"), 200);
|
||||
CHECK_EQ(from(srv, "::ffff:127.0.0.1:50122"), 200);
|
||||
CHECK_EQ(from(srv, ""), 200); /* in-process */
|
||||
CHECK_EQ(from(srv, "192.168.1.20:50122"), 403);
|
||||
CHECK_EQ(from(srv, "::ffff:10.0.0.7:50122"), 403);
|
||||
CHECK_EQ(from(srv, "fe80::1:50122"), 403);
|
||||
CHECK_EQ(from(srv, "128.0.0.1:50122"), 403);
|
||||
|
||||
ServerOptions ok = o;
|
||||
ok.api_key = "k";
|
||||
Server keyed(d, ok);
|
||||
CHECK_EQ(from(keyed, "192.168.1.20:50122"), 200);
|
||||
}
|
||||
|
||||
TEST(tokenize_takes_a_prompt_or_messages_and_never_both) {
|
||||
Fixture f;
|
||||
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
/* systemone_test.cpp -- /v1/systemone's adapter (core/server/systemone.h) and its handler.
|
||||
*
|
||||
* What d1 reads is exact text: a reworded instruction or a different option code is a different
|
||||
* question to a model trained on its own prompts. So the rendering is checked as text, against
|
||||
* strings written out from d1's prompt.py, and the readout against hand-computed softmaxes. The
|
||||
* end-to-end parity with d1 itself is a serve against the model (docs/SYSTEMONE.md).
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "server/server.h"
|
||||
#include "server/sink.h"
|
||||
#include "server/systemone.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
using namespace rad;
|
||||
using namespace rad::server;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A vocabulary in which d1's answer spellings are single tokens -- yes/no in three cases, the
|
||||
* letters, " A".." Z", the digits -- and everything else is one id a byte, 1000 up, so a prompt
|
||||
* decodes back to its exact text. "Q" and "07" are NOT single tokens, which drives the fallback
|
||||
* codebook. Every string handed to encode is logged, which is how the tokenisation split is seen. */
|
||||
struct DictTokenizer : ITokenizer {
|
||||
std::map<std::string, int32_t> whole;
|
||||
mutable std::vector<std::string> log;
|
||||
mutable std::mutex mu;
|
||||
DictTokenizer() {
|
||||
int32_t id = 1;
|
||||
for (const char* s : { "yes", "Yes", "YES", "no", "No", "NO", "<|startoftext|>" })
|
||||
whole[s] = id++;
|
||||
for (char c = 'A'; c <= 'Z'; ++c) {
|
||||
if (c == 'Q') continue;
|
||||
whole[std::string(1, c)] = id++;
|
||||
whole[" " + std::string(1, c)] = id++;
|
||||
}
|
||||
for (char c = '0'; c <= '9'; ++c) whole[std::string(1, c)] = id++;
|
||||
whole["00"] = id++;
|
||||
}
|
||||
std::vector<int32_t> encode(const std::string& s, bool, bool) const override {
|
||||
{ std::lock_guard<std::mutex> lk(mu); log.push_back(s); }
|
||||
auto it = whole.find(s);
|
||||
if (it != whole.end()) return { it->second };
|
||||
if (s == "Q") return { 1000 + 'Q', 3000 }; /* two ids, the second spelled "" */
|
||||
std::vector<int32_t> v;
|
||||
for (unsigned char c : s) v.push_back(1000 + c);
|
||||
return v;
|
||||
}
|
||||
std::string token_bytes(int32_t id) const override {
|
||||
if (id == 3000) return "";
|
||||
if (id >= 1000) return std::string(1, (char)(id - 1000));
|
||||
for (const auto& kv : whole) if (kv.second == id) return kv.first;
|
||||
return "";
|
||||
}
|
||||
std::string decode(const std::vector<int32_t>& t) const override {
|
||||
std::string s;
|
||||
for (int32_t x : t) s += token_bytes(x);
|
||||
return s;
|
||||
}
|
||||
int32_t eos() const override { return 0; }
|
||||
int32_t bos() const override { return whole.at("<|startoftext|>"); }
|
||||
std::unique_ptr<IDetokenizer> detokenizer(const std::vector<std::string>&,
|
||||
const std::vector<std::string>&) const override {
|
||||
return nullptr;
|
||||
}
|
||||
int32_t id(const std::string& s) const { return whole.at(s); }
|
||||
};
|
||||
|
||||
OaiLimits limits(int64_t max_ctx = 0) {
|
||||
OaiLimits l;
|
||||
l.model_id = "d1";
|
||||
l.max_ctx = max_ctx;
|
||||
return l;
|
||||
}
|
||||
|
||||
int parse(DictTokenizer& tok, const std::string& body, DecisionRequest* r, ApiError* e,
|
||||
int64_t max_ctx = 0) {
|
||||
OaiDeps d;
|
||||
d.tok = &tok;
|
||||
return parse_decision_request(body, d, limits(max_ctx), "d1", r, e);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(a_single_question_is_d1s_prompt_as_one_text) {
|
||||
DictTokenizer tok;
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK_OK(parse(tok, R"({"state": "I was charged twice.",
|
||||
"questions": {"refund": {"type": "noul", "instructions": "Is a refund requested?"}}})",
|
||||
&r, &e));
|
||||
REQUIRE(r.questions.size() == 1);
|
||||
CHECK_EQ(tok.decode(r.questions[0].tokens),
|
||||
"<|startoftext|><|im_start|>user\nI was charged twice.\n\n\nQUESTION:\n"
|
||||
"Is a refund requested?\n\nReply with yes or no only.<|im_end|>\n"
|
||||
"<|im_start|>assistant\n");
|
||||
CHECK_EQ(r.trunk, 0);
|
||||
CHECK_EQ(r.input_tokens, (int64_t)r.questions[0].tokens.size());
|
||||
/* One encode of the whole prompt, after the candidates' single-token probes. */
|
||||
CHECK_EQ(tok.log.back(), tok.decode(r.questions[0].tokens));
|
||||
/* yes/Yes/YES then no/No/NO, max-pooled per answer. */
|
||||
CHECK(r.questions[0].labels == (std::vector<std::string>{ "true", "false" }));
|
||||
CHECK_EQ(r.questions[0].candidates.size(), (size_t)6);
|
||||
REQUIRE(r.questions[0].groups.size() == 2);
|
||||
CHECK_EQ(r.questions[0].groups[0].size(), (size_t)3);
|
||||
}
|
||||
|
||||
TEST(several_questions_share_a_head_tokenised_on_its_own) {
|
||||
DictTokenizer tok;
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK_OK(parse(tok, R"({"state": {"b": 1, "a": [true, null]},
|
||||
"questions": {
|
||||
"z": {"type": "score", "instructions": "How urgent?", "criteria": ["Low", "High"]},
|
||||
"a": {"type": "noul", "instructions": "Late?",
|
||||
"criteria": {"true": "Not on time", "false": null}}}})", &r, &e));
|
||||
REQUIRE(r.questions.size() == 2);
|
||||
/* Insertion order, for the questions and for the state's keys (indented JSON). */
|
||||
CHECK_EQ(r.questions[0].name, "z");
|
||||
const std::string head = "<|startoftext|><|im_start|>user\n{\n \"b\": 1,\n \"a\": [\n true,\n"
|
||||
" null\n ]\n}\n\n\nQUESTION:\n";
|
||||
CHECK_EQ(r.trunk, (int32_t)head.size()); /* one id a byte in this vocabulary */
|
||||
CHECK_EQ(tok.decode(r.questions[0].tokens),
|
||||
head + "How urgent?\n\n0 Low\n1 High\n\nReply with a single digit 0-1 only."
|
||||
"<|im_end|>\n<|im_start|>assistant\n");
|
||||
CHECK_EQ(tok.decode(r.questions[1].tokens),
|
||||
head + "Late?\nYes: Not on time\nNo: None\n\nReply with yes or no only."
|
||||
"<|im_end|>\n<|im_start|>assistant\n");
|
||||
/* The head was encoded once, as itself; usage counts it once. */
|
||||
int heads = 0;
|
||||
for (const std::string& s : tok.log) heads += s == head;
|
||||
CHECK_EQ(heads, 1);
|
||||
CHECK_EQ(r.input_tokens, (int64_t)(r.questions[0].tokens.size() + r.questions[1].tokens.size()) -
|
||||
r.trunk);
|
||||
}
|
||||
|
||||
TEST(choice_codes_follow_d1s_codebook) {
|
||||
DictTokenizer tok;
|
||||
{ /* Names that are not letters: A, B, C, and a description falling back to the name. */
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK_OK(parse(tok, R"({"state": null, "questions": {"team": {"instructions": "Who?",
|
||||
"criteria": {"billing": "Charges", "tech_support": null, "fraud": ""}}}})", &r, &e));
|
||||
const DecisionQuestion& q = r.questions[0];
|
||||
CHECK_EQ(q.type, "choice"); /* d1's default type */
|
||||
CHECK_EQ(tok.decode(q.tokens), "<|startoftext|><|im_start|>user\nWho?\n\nOptions:\nA Charges\n"
|
||||
"B tech support\nC fraud\n\nReply with the option code only.<|im_end|>\n"
|
||||
"<|im_start|>assistant\n");
|
||||
REQUIRE(q.groups.size() == 3);
|
||||
/* Each option reads its code and " code". */
|
||||
CHECK_EQ(q.candidates[q.groups[1][0]], tok.id("B"));
|
||||
CHECK_EQ(q.candidates[q.groups[1][1]], tok.id(" B"));
|
||||
}
|
||||
{ /* Letters are their own codes, except one that is not a token: Q takes the first free
|
||||
* fallback, which is A -- not yet used, because the codes are taken in option order. */
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK_OK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "choice",
|
||||
"instructions": "Pick.", "criteria": {"Q": "first", " B ": "second"}}}})", &r, &e));
|
||||
const std::string text = tok.decode(r.questions[0].tokens);
|
||||
CHECK(text.find("Options:\nA first\nB second\n") != std::string::npos);
|
||||
CHECK(r.questions[0].labels == (std::vector<std::string>{ "Q", " B " }));
|
||||
}
|
||||
{ /* Over 26 options: 00, 01, ... and every two-digit code but 00 falls back. */
|
||||
std::string crit;
|
||||
for (int i = 0; i < 27; ++i) crit += (i ? "," : "") + std::string("\"o") + std::to_string(i) + "\": null";
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK_OK(parse(tok, R"({"state": "s", "questions": {"q": {"type": "choice",
|
||||
"instructions": "Pick.", "criteria": {)" + crit + "}}}}", &r, &e));
|
||||
const std::string text = tok.decode(r.questions[0].tokens);
|
||||
CHECK(text.find("Options:\n00 o0\nA o1\nB o2\n") != std::string::npos);
|
||||
CHECK_EQ(r.questions[0].groups.size(), (size_t)27);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(the_readout_is_a_softmax_over_each_answers_best_spelling) {
|
||||
DecisionQuestion q;
|
||||
q.name = "n"; q.type = "noul"; q.labels = { "true", "false" };
|
||||
q.candidates = { 10, 11, 20, 21 };
|
||||
q.groups = { { 0, 1 }, { 2, 3 } };
|
||||
json a;
|
||||
ApiError e;
|
||||
CHECK_OK(decision_answer(q, { 1.0f, 3.0f, 2.0f, -5.0f }, &a, &e));
|
||||
CHECK_NEAR(a["noul"].get<double>(), 1.0 / (1.0 + std::exp(-1.0)), 1e-12); /* 3 vs 2 */
|
||||
|
||||
DecisionQuestion s;
|
||||
s.name = "s"; s.type = "score"; s.labels = { "0", "1", "2" }; s.legend = { "a", "b", "c" };
|
||||
s.candidates = { 1, 2, 3 };
|
||||
s.groups = { { 0 }, { 1 }, { 2 } };
|
||||
CHECK_OK(decision_answer(s, { 0.0f, 0.0f, std::log(2.0f) }, &a, &e));
|
||||
CHECK_NEAR(a["score"].get<double>(), (0.25 + 2 * 0.5), 1e-6);
|
||||
CHECK_NEAR(a["confidence"].get<double>(), 0.5, 1e-6);
|
||||
CHECK_EQ(a["legend"]["2"].get<std::string>(), "c");
|
||||
CHECK_EQ(a.dump().substr(0, 26), "{\"type\":\"score\",\"score\":1.");
|
||||
|
||||
CHECK(decision_answer(s, { 0.0f, NAN, 1.0f }, &a, &e) < 0);
|
||||
CHECK_EQ(e.status, 500);
|
||||
CHECK(decision_answer(s, { 0.0f }, &a, &e) < 0);
|
||||
}
|
||||
|
||||
TEST(requests_d1_cannot_answer_are_refused_by_field) {
|
||||
DictTokenizer tok;
|
||||
struct Case { const char* body; const char* param; };
|
||||
const Case cases[] = {
|
||||
{ R"({"questions": {"a": {"type": "noul", "instructions": "x"}}})", "state" },
|
||||
{ R"({"state": "s", "questions": {}})", "questions" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x"}}, "stream": true})",
|
||||
"stream" },
|
||||
{ R"({"state": "s", "model": "other", "questions": {"a": {"type": "noul", "instructions": "x"}}})",
|
||||
"model" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "vote", "instructions": "x"}}})", "questions.a.type" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "score", "instructions": "x", "criteria": ["one"]}}})",
|
||||
"questions.a.criteria" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "choice", "instructions": "x", "criteria": {}}}})",
|
||||
"questions.a.criteria" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x", "criteria": {"maybe": "?"}}}})",
|
||||
"questions.a.criteria.maybe" },
|
||||
{ R"({"state": "s", "questions": {"a": {"type": "noul"}}})", "questions.a.instructions" },
|
||||
};
|
||||
for (const Case& c : cases) {
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK(parse(tok, c.body, &r, &e) < 0);
|
||||
CHECK_EQ(e.param, c.param);
|
||||
}
|
||||
/* Pictures without an encoder are the deployment's refusal, not the request's. */
|
||||
DecisionRequest r;
|
||||
ApiError e;
|
||||
CHECK(parse(tok, R"({"state": null, "images": ["data:image/png;base64,AAAA"],
|
||||
"questions": {"a": {"type": "noul", "instructions": "x"}}})", &r, &e) < 0);
|
||||
CHECK_EQ(e.status, 501);
|
||||
/* A prompt must leave one position for the token the request samples. */
|
||||
CHECK(parse(tok, R"({"state": "s", "questions": {"a": {"type": "noul", "instructions": "x"}}})",
|
||||
&r, &e, 40) < 0);
|
||||
CHECK_EQ(e.code, "context_length_exceeded");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the handler */
|
||||
namespace {
|
||||
|
||||
/* Answers every scored request with logits that make the first spelling of the first answer
|
||||
* win by ln 3 -- P = 0.75 at two answers -- and records what it was handed. */
|
||||
struct ScoringScheduler : IScheduler {
|
||||
std::mutex mu;
|
||||
std::vector<Request> seen;
|
||||
std::vector<std::thread> workers;
|
||||
std::atomic<uint64_t> next{ 1 };
|
||||
~ScoringScheduler() override { for (auto& t : workers) if (t.joinable()) t.join(); }
|
||||
uint64_t submit(Request&& r) override {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
auto ts = r.token_scores;
|
||||
void* sink = r.sink;
|
||||
seen.push_back(std::move(r));
|
||||
workers.emplace_back([ts, sink] {
|
||||
sink_admitted(sink);
|
||||
if (ts) {
|
||||
ts->logits.assign(ts->tokens.size(), 0.0f);
|
||||
ts->logits[0] = std::log(3.0f);
|
||||
}
|
||||
sink_push(sink, 'x', nullptr);
|
||||
sink_finish(sink, Finish::Length);
|
||||
});
|
||||
return next++;
|
||||
}
|
||||
void cancel(uint64_t) override {}
|
||||
SchedMetrics metrics() const override { return {}; }
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(the_endpoint_answers_only_for_a_declared_d1) {
|
||||
for (const char* type : { "", "d1" }) {
|
||||
ScoringScheduler sched;
|
||||
DictTokenizer tok;
|
||||
Deps d;
|
||||
d.sched = &sched;
|
||||
d.tok = &tok;
|
||||
ServerOptions o;
|
||||
o.model_id = "d1";
|
||||
o.decision_type = type;
|
||||
Server srv(d, o);
|
||||
HttpResponse res = srv.router().call("POST", "/v1/systemone",
|
||||
R"({"state": "s", "questions": {"q": {"type": "noul", "instructions": "x"},
|
||||
"c": {"type": "choice", "instructions": "y",
|
||||
"criteria": {"one": null, "two": null}}}})");
|
||||
if (!*type) { CHECK_EQ(res.status, 501); continue; }
|
||||
REQUIRE(res.status == 200);
|
||||
const json j = json::parse(res.body);
|
||||
CHECK_NEAR(j["answers"]["q"]["noul"].get<double>(), 0.75, 1e-6);
|
||||
CHECK_EQ(j["answers"]["c"]["choice"].get<std::string>(), "one");
|
||||
CHECK_EQ(j["usage"]["output_tokens"].get<int>(), 0);
|
||||
/* One request a question, scored, one token long, greedy. */
|
||||
std::lock_guard<std::mutex> lk(sched.mu);
|
||||
REQUIRE(sched.seen.size() == 2);
|
||||
for (const Request& rq : sched.seen) {
|
||||
CHECK(rq.token_scores != nullptr);
|
||||
CHECK_EQ(rq.max_tokens, 1);
|
||||
CHECK_EQ(rq.sp.temp, 0.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
@@ -706,6 +706,7 @@ TEST(vocab_section_round_trip) {
|
||||
in.bos = -1; in.eos = 2; in.eot = 2; in.unk = 0; in.pad = -1; in.sep = -1;
|
||||
in.add_bos = false;
|
||||
in.add_eos = true;
|
||||
in.ignore_merges = true;
|
||||
in.chat_template = "{{ messages }}";
|
||||
VocabStep s0; s0.kind = RAD_NORM_NFC; in.steps.push_back(s0);
|
||||
VocabStep s1; s1.kind = RAD_PRE_SPLIT; s1.arg0 = "\\p{N}"; s1.iarg = 1; in.steps.push_back(s1);
|
||||
@@ -749,6 +750,7 @@ TEST(vocab_section_round_trip) {
|
||||
CHECK_EQ(out.eos, in.eos);
|
||||
CHECK_EQ(out.unk, in.unk);
|
||||
CHECK_EQ(out.add_eos, in.add_eos);
|
||||
CHECK_EQ(out.ignore_merges, in.ignore_merges);
|
||||
CHECK_EQ(out.chat_template, in.chat_template);
|
||||
CHECK_EQ(out.steps.size(), in.steps.size());
|
||||
for (size_t i = 0; i < out.steps.size(); ++i) {
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "llama/src/unicode.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
@@ -348,6 +349,58 @@ TEST(bpe_merges_as_worked_out_by_hand) {
|
||||
}
|
||||
}
|
||||
|
||||
/* `ignore_merges`: "abc" is a vocabulary entry the one merge cannot reach, so the flag is the only
|
||||
* way to get it. It applies to each pre-token after the declared chain (the Lowercase normalizer
|
||||
* and the whitespace split run first), and on both ByteLevel paths: the deferred one that merges
|
||||
* raw bytes, and the materialised one a later Split forces. */
|
||||
TEST(bpe_ignore_merges_takes_a_whole_pretoken) {
|
||||
const char* chains[] = {
|
||||
R"({"type":"WhitespaceSplit"})",
|
||||
R"({"type":"Sequence","pretokenizers":[{"type":"WhitespaceSplit"},)"
|
||||
R"({"type":"ByteLevel","add_prefix_space":false,"use_regex":false}]})",
|
||||
R"({"type":"Sequence","pretokenizers":[{"type":"WhitespaceSplit"},)"
|
||||
R"({"type":"ByteLevel","add_prefix_space":false,"use_regex":false},)"
|
||||
R"({"type":"Split","pattern":{"String":" "},"behavior":"Removed"}]})",
|
||||
};
|
||||
for (const char* chain : chains)
|
||||
for (const char* flag : { "", "\"ignore_merges\":false,", "\"ignore_merges\":true," }) {
|
||||
const bool ignore = std::strstr(flag, "true") != nullptr;
|
||||
const std::string js = std::string(R"({"normalizer":{"type":"Lowercase"},"pre_tokenizer":)") +
|
||||
chain + R"(,"model":{"type":"BPE",)" + flag +
|
||||
R"("vocab":{"a":0,"b":1,"c":2,"ab":3,"abc":4,"abc abc":5},"merges":["a b"]}})";
|
||||
auto v = from_json(js.c_str());
|
||||
REQUIRE(v != nullptr);
|
||||
CHECK_EQ(v->build().ignore_merges, ignore);
|
||||
Tokenizer t;
|
||||
CHECK_OK(t.init(v));
|
||||
const std::vector<int32_t> whole{ 4 }, merged{ 3, 2 };
|
||||
for (int repeat = 0; repeat < 2; ++repeat) { /* the second pass reads the caches */
|
||||
CHECK(encode_new(t, "ABC") == (ignore ? whole : merged));
|
||||
CHECK(encode_new(t, "ABCABC") == (std::vector<int32_t>{ 3, 2, 3, 2 }));
|
||||
CHECK(encode_new(t, "ABC ABC") == (ignore ? std::vector<int32_t>{ 4, 4 }
|
||||
: std::vector<int32_t>{ 3, 2, 3, 2 }));
|
||||
}
|
||||
CHECK(encode_ref(*v, "ABC ABC") == encode_new(t, "ABC ABC"));
|
||||
}
|
||||
}
|
||||
|
||||
/* A control token read as text stays text: the flag must not turn its spelling back into the
|
||||
* marker when the caller asked for specials not to be parsed. */
|
||||
TEST(bpe_ignore_merges_leaves_unparsed_control_tokens_as_text) {
|
||||
auto v = from_json(R"JSON({
|
||||
"added_tokens":[{"id":4,"content":"abc","special":true}],
|
||||
"pre_tokenizer":{"type":"WhitespaceSplit"},
|
||||
"model":{"type":"BPE","ignore_merges":true,
|
||||
"vocab":{"a":0,"b":1,"c":2,"ab":3},"merges":["a b"]}
|
||||
})JSON");
|
||||
REQUIRE(v != nullptr);
|
||||
Tokenizer t;
|
||||
CHECK_OK(t.init(v));
|
||||
CHECK(encode_new(t, "abc", true) == (std::vector<int32_t>{ 4 }));
|
||||
CHECK(encode_new(t, "abc", false) == (std::vector<int32_t>{ 3, 2 }));
|
||||
CHECK(encode_ref(*v, "abc", false) == (std::vector<int32_t>{ 3, 2 }));
|
||||
}
|
||||
|
||||
TEST(byte_fallback_and_unk_follow_the_declared_chain) {
|
||||
auto v = from_json(k_spm);
|
||||
REQUIRE(v != nullptr);
|
||||
|
||||
Reference in new issue
Block a user