Archived
radiance 1.5.0
- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a prefix hit on a sliding-window model resumes instead of prefilling again. deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards - ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations, as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made with the PR builds is refused: convert it again with --reuse <old container> - Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16 checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe), and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9 - a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD request by name), the library that made it, and its stack, which addr2line resolves against the binary - the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and startup refuses all three with what replaced them. The compose files no longer mount /data, and .env no longer needs RADIANCE_STATE - --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A full host tier now drops its least recently used conversations - --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and gives its VRAM to the KV cache, read over the link once an image - timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival to the first and the last token, queueing and tokenisation included - a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the slots it had already freed: after it every recall failed, the cache stayed short until a restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and always finishes - a tool result or tool-call arguments that are not JSON are no longer refused as nesting past 1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the bound, since nothing else is parsed into a tree - the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and 1.5 GiB), not ttm.pages_limit - --embedding-placement auto, removed in 1.3.0, is refused with what replaced it - for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary without declaring it
This commit is contained in:
commit
b93b531f63
127 files changed
+9609
-4796
No files matched your search
+52
-2
@@ -189,6 +189,56 @@ if(TARGET libavx AND TARGET rad-avx-check)
|
||||
set_tests_properties(avx_check PROPERTIES TIMEOUT 600)
|
||||
endif()
|
||||
|
||||
# ================================================================== libr4d's kernels, on the host
|
||||
#
|
||||
# libr4d builds for gfx12 only, and some of its ops (the sandwich-norm joins, expert_scale) have no
|
||||
# libref oracle by design (docs/OPS.md), so neither rad-kbench nor a no-card machine would ever run
|
||||
# those kernels. r4d_emu runs the SOURCE of four of libr4d's units on the host instead -- the
|
||||
# windowed paged attention, pair_argmax, the joins and expert_scale, the units written against
|
||||
# r4d_launch.h: emu/hip/hip_runtime.h supplies the HIP names, every GPU thread is a fiber,
|
||||
# __syncthreads and every cross-lane op a barrier (one not reached uniformly is reported as a
|
||||
# deadlock), and the units' launch macro is pointed at the emulator. Checked against a port of
|
||||
# libref's ref_attn_paged, against the host arithmetic in ref_host.cpp, and -- for the joins --
|
||||
# against the unfused chain, bit for bit.
|
||||
#
|
||||
# CLANG AND x86-64: the kernels use clang's ext_vector_type, and the fiber switch is x86-64 SysV
|
||||
# inline assembly. Under a clang C++ compiler they are ordinary targets here, the .hip files
|
||||
# compiled as C++ (`-x c++`, which is what makes them host code; the property is per directory, so
|
||||
# libr4d's own HIP build is untouched). Under g++ -- the docker image's -- a build with a card
|
||||
# still has a clang: its HIP compiler, ROCm's own clang++, and r4d_emu/run.sh builds and runs the
|
||||
# same tests with that. So wherever libr4d is built, this runs.
|
||||
set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d)
|
||||
set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# no fiber switch for this ISA: nothing to register
|
||||
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip
|
||||
${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip)
|
||||
set_source_files_properties(${R4D_EMU_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++")
|
||||
add_library(r4d_emu_kernels OBJECT ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp)
|
||||
target_include_directories(r4d_emu_kernels PUBLIC ${R4D_EMU}/emu ${R4D_EMU} ${R4D_DIR})
|
||||
target_link_libraries(r4d_emu_kernels PUBLIC rad_abi)
|
||||
# As libr4d compiles every unit: the joins are held to the chain bit for bit, and a contracted
|
||||
# multiply-add is a different rounding.
|
||||
target_compile_options(r4d_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi)
|
||||
foreach(t attn pick norm escale)
|
||||
add_executable(r4d_emu_${t} ${R4D_EMU}/test_${t}.cpp)
|
||||
target_link_libraries(r4d_emu_${t} PRIVATE r4d_emu_kernels)
|
||||
target_compile_options(r4d_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi)
|
||||
set_target_properties(r4d_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
|
||||
add_test(NAME r4d_emu_${t} COMMAND r4d_emu_${t})
|
||||
endforeach()
|
||||
# The random sweep at a size the inner loop can afford; `r4d_emu_attn sweep 200` is the long one.
|
||||
add_test(NAME r4d_emu_attn_sweep COMMAND r4d_emu_attn sweep 40)
|
||||
set_tests_properties(r4d_emu_attn r4d_emu_pick r4d_emu_norm r4d_emu_escale r4d_emu_attn_sweep
|
||||
PROPERTIES LABELS "r4d_emu" TIMEOUT 600)
|
||||
elseif(RAD_HIP_FOUND AND CMAKE_HIP_COMPILER_ID MATCHES "Clang")
|
||||
add_test(NAME r4d_emu
|
||||
COMMAND sh ${R4D_EMU}/run.sh ${CMAKE_HIP_COMPILER} ${CMAKE_SOURCE_DIR}/abi ${R4D_DIR}
|
||||
${CMAKE_CURRENT_BINARY_DIR}/r4d_emu 40)
|
||||
set_tests_properties(r4d_emu PROPERTIES LABELS "r4d_emu" TIMEOUT 900)
|
||||
endif()
|
||||
|
||||
# ================================================================== the document as a test
|
||||
#
|
||||
# docs/OPS.md calls its resolved table "THE AUTHORITY FOR THE OPS IN IT" and says of itself that
|
||||
@@ -224,8 +274,8 @@ set_tests_properties(ops_doc PROPERTIES SKIP_RETURN_CODE 77)
|
||||
# (tests/oot_plugins.sh). A first-party plugin that quietly depended on being built in the tree
|
||||
# fails here; so does an installed package a third party could not build against.
|
||||
#
|
||||
# libr4d is included where the tree built it: the same HIP compiler, its own targets. Labelled
|
||||
# `oot` because it rebuilds every plugin, which is minutes, not seconds.
|
||||
# The device library (libr4d) is included where the tree built it: the same HIP compiler, libr4d's
|
||||
# targets. Labelled `oot` because it rebuilds every plugin, which is minutes, not seconds.
|
||||
set(RAD_OOT_HIP "")
|
||||
if(RAD_HIP_FOUND AND TARGET libr4d)
|
||||
get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES)
|
||||
|
||||
+838
-3
@@ -20,6 +20,7 @@
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -71,7 +72,10 @@ struct RecIssue {
|
||||
rad_op op = 0;
|
||||
std::vector<RadOperand> opd;
|
||||
int64_t n = 0;
|
||||
int lane = 0; /* the lane it was issued on (rad_lane) */
|
||||
};
|
||||
/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */
|
||||
struct RecJoin { size_t at = 0; int from = 0, to = 0; };
|
||||
|
||||
} /* namespace */
|
||||
|
||||
@@ -84,8 +88,11 @@ struct RadBuilder {
|
||||
std::vector<std::pair<int, rad_kvgroup>> binds;
|
||||
std::vector<std::string> notes;
|
||||
|
||||
/* Ops the fake kernel hierarchy refuses, so the fused-op fallback can be driven. */
|
||||
/* Ops the fake kernel hierarchy refuses, so the fused-op fallback can be driven; and ops no
|
||||
* loaded library declares at all (rad_op_declared), as without an optional library. */
|
||||
std::set<std::string> refuse;
|
||||
std::set<std::string> undeclared;
|
||||
std::vector<std::string> asked_undeclared; /* what a real engine would have refused */
|
||||
int64_t kv_block = 16;
|
||||
|
||||
/* The buffer the plugin named as this step's logits (rad_declare_logits). */
|
||||
@@ -98,6 +105,9 @@ struct RadBuilder {
|
||||
bool drafter_shared = false;
|
||||
int drafter_pos = -1;
|
||||
|
||||
/* The buffers named to rad_buf_concurrent: the ones a second lane touches. */
|
||||
std::vector<rad_buf> concurrent;
|
||||
|
||||
/* The vision tower's declaration (rad_declare_encoder), when the plugin made one, and the
|
||||
* audio encoder's. */
|
||||
RadEncoderDecl encoder{};
|
||||
@@ -120,6 +130,8 @@ struct RadCtx {
|
||||
std::vector<RecIssue> issues;
|
||||
std::vector<int> routed_layers;
|
||||
std::string step_fail;
|
||||
int lane = 0; /* where the next issue goes */
|
||||
std::vector<RecJoin> joins;
|
||||
};
|
||||
|
||||
/* -------------------------------------------------------------------- the declare-side ABI */
|
||||
@@ -141,6 +153,10 @@ extern "C" rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBuf
|
||||
|
||||
extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params,
|
||||
const rad_weight* weights, int n_weights) {
|
||||
if (b->undeclared.count(op)) {
|
||||
b->asked_undeclared.push_back(op);
|
||||
return RAD_NULL_HANDLE;
|
||||
}
|
||||
RecOp r;
|
||||
r.op = op;
|
||||
for (int i = 0; i < n_params; ++i) {
|
||||
@@ -181,6 +197,10 @@ extern "C" int rad_op_resolved(RadBuilder* b, rad_op h) {
|
||||
return h != RAD_NULL_HANDLE && b->ops[h - 1].resolved;
|
||||
}
|
||||
|
||||
extern "C" int rad_op_declared(RadBuilder* b, const char* op) {
|
||||
return op && b->undeclared.count(op) == 0;
|
||||
}
|
||||
|
||||
extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name,
|
||||
const RadKVGroupDecl* d) {
|
||||
b->kv_groups.push_back({name, *d, false});
|
||||
@@ -219,8 +239,12 @@ extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Recorded as calls and nothing else: no test here reads a lane or a drafter declaration. */
|
||||
extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { (void)b; (void)buf; return RAD_OK; }
|
||||
/* Recorded: the gemma4 prefill overlap names the buffers its second lane reduces in place. */
|
||||
extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) {
|
||||
if (!b || !buf) return RAD_E_INVAL;
|
||||
b->concurrent.push_back(buf);
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) {
|
||||
if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL;
|
||||
if (lo < 0 || hi <= lo) return RAD_E_INVAL;
|
||||
@@ -301,9 +325,21 @@ extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd,
|
||||
r.op = op;
|
||||
r.n = n;
|
||||
for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]);
|
||||
r.lane = c->lane;
|
||||
c->issues.push_back(r);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The second lane, recorded: the lane each issue went to, and where each join sits among them. */
|
||||
extern "C" int rad_lane(RadCtx* c, int lane) {
|
||||
if (lane != 0 && lane != 1) return RAD_E_INVAL;
|
||||
c->lane = lane;
|
||||
return RAD_OK;
|
||||
}
|
||||
extern "C" int rad_lane_join(RadCtx* c, int from, int to) {
|
||||
if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL;
|
||||
c->joins.push_back({ c->issues.size(), from, to });
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A block that refuses the batch records the reason; the recorder is what the tests read. */
|
||||
extern "C" int rad_step_fail(RadCtx* c, const char* what) {
|
||||
c->step_fail = what ? what : "";
|
||||
@@ -346,6 +382,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void
|
||||
#include "../arch/lfm2_bf16/lfm2_bf16.cpp"
|
||||
/* Gemma 4 dense: two attention classes (sliding-window + proportional-RoPE global) on one stream. */
|
||||
#include "../arch/gemma4_bf16/gemma4_bf16.cpp"
|
||||
/* And the bf16 / fp8-expert Gemma 4 plugin: the 26B-A4B's dense and routed arms side by side. */
|
||||
#include "../arch/gemma4/gemma4.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>
|
||||
@@ -4132,3 +4170,800 @@ TEST(gemma4_probe_names_the_heads_operating_depth) {
|
||||
CHECK_OK(gemma4_bf16::probe(&without, &q));
|
||||
CHECK_EQ(q.draft_depth, 0);
|
||||
}
|
||||
|
||||
/* ===================== gemma4: the 26B-A4B, a dense and a routed arm side by side ===================== */
|
||||
|
||||
namespace {
|
||||
|
||||
/* gemma-4-26B-A4B-it's text geometry cut to SIX layers -- five sliding then one full, the model's
|
||||
* own 5:1 -- with the routed arm on. The keys are the checkpoint's (text_config flattened), which
|
||||
* is what arch/gemma4 reads, and quant is empty: the container this plugin claims. */
|
||||
const char* k_g4moe_keys[] = {
|
||||
"hidden_size", "num_attention_heads", "num_key_value_heads", "head_dim", "global_head_dim",
|
||||
"num_global_key_value_heads", "attention_k_eq_v", "vocab_size", "intermediate_size",
|
||||
"rms_norm_eps", "sliding_window", "final_logit_softcapping", "hidden_activation", "layer_types",
|
||||
"rope_parameters.sliding_attention.rope_theta", "rope_parameters.sliding_attention.rope_type",
|
||||
"rope_parameters.full_attention.rope_theta", "rope_parameters.full_attention.rope_type",
|
||||
"rope_parameters.full_attention.partial_rotary_factor", "enable_moe_block", "num_experts",
|
||||
"top_k_experts", "moe_intermediate_size",
|
||||
};
|
||||
const char* k_g4moe_vals[] = {
|
||||
"2816", "16", "8", "256", "512",
|
||||
"2", "true", "262144", "2112",
|
||||
"1e-06", "1024", "30.0", "gelu_pytorch_tanh",
|
||||
"[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", \"sliding_attention\", "
|
||||
"\"sliding_attention\", \"full_attention\"]",
|
||||
"10000.0", "default",
|
||||
"1000000.0", "proportional",
|
||||
"0.25", "true", "128",
|
||||
"8", "704",
|
||||
};
|
||||
static_assert(sizeof(k_g4moe_keys) == sizeof(k_g4moe_vals), "one value a key");
|
||||
|
||||
RadModelMeta gemma4_moe_meta() {
|
||||
RadModelMeta m{};
|
||||
m.arch_id = "gemma4";
|
||||
m.name = "test-gemma4-26b-a4b";
|
||||
m.quant = "";
|
||||
m.n_layers = 6;
|
||||
m.n_embd = 2816;
|
||||
m.n_head = 16;
|
||||
m.n_head_kv = 8;
|
||||
m.head_dim = 256;
|
||||
m.n_ff = 2112;
|
||||
m.n_vocab = 262144;
|
||||
m.n_ctx_train = 262144;
|
||||
m.rms_eps = 1e-6f;
|
||||
m.n_kv = (int)(sizeof(k_g4moe_keys) / sizeof(k_g4moe_keys[0]));
|
||||
m.kv_key = k_g4moe_keys;
|
||||
m.kv_val = k_g4moe_vals;
|
||||
return m;
|
||||
}
|
||||
|
||||
int count_resolved(const RadBuilder& b, const std::string& name) {
|
||||
int n = 0;
|
||||
for (const auto& o : b.ops) if (o.op == name && o.resolved) ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
int count_issued(const std::vector<std::string>& v, const std::string& name) {
|
||||
return (int)std::count(v.begin(), v.end(), name);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(a_gemma4_moe_trunk_declares_both_arms_and_the_joins) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
/* five sliding layers read q in the fused row (attn_paged_qrow), the full one attn_paged */
|
||||
CHECK_EQ(count_op(b, "attn_paged_qrow"), 5);
|
||||
CHECK_EQ(count_op(b, "attn_paged"), 1);
|
||||
CHECK_EQ(count_op(b, "kv_store"), 6);
|
||||
/* One join after attention and one after the two feed-forward arms, a layer. */
|
||||
CHECK_EQ(count_resolved(b, "norm_add_norm"), 6);
|
||||
CHECK_EQ(count_resolved(b, "join_add_scale"), 6);
|
||||
/* The routed arm: experts served bf16 where the container holds no encoding for them. */
|
||||
CHECK(count_op(b, "moe_gemm") > 0);
|
||||
CHECK_EQ(count_op(b, "moe_gemm_q"), 0);
|
||||
CHECK_EQ(count_op(b, "logit_softcap"), 1);
|
||||
CHECK_EQ(count_op(b, "all_reduce"), 0); /* world 1 */
|
||||
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved) CHECK(o.uses_declared);
|
||||
for (const auto& w : b.weights)
|
||||
CHECK(find_map(b, w.name) != nullptr);
|
||||
}
|
||||
|
||||
/* THE SLIDING GROUP IS FULL, with the window on the attention op: a WINDOW group is not
|
||||
* prefix-cached, and FULL keeps a hit (arch/gemma4/gemma4.cpp, the KV groups). */
|
||||
TEST(gemma4_moe_kv_groups_are_both_full_and_the_window_rides_the_op) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
REQUIRE((int)b.kv_groups.size() == 2);
|
||||
for (const auto& g : b.kv_groups) {
|
||||
CHECK_EQ((int)g.d.kind, RAD_KV_FULL);
|
||||
CHECK_EQ(g.d.window, 0);
|
||||
}
|
||||
const RecOp* sl = find_op(b, "attn_paged_qrow", 0);
|
||||
REQUIRE(sl != nullptr);
|
||||
CHECK_EQ(pint(sl, "head_dim"), 256);
|
||||
CHECK_EQ(pint(sl, "window"), 1024);
|
||||
const RecOp* fu = find_op(b, "attn_paged", 0);
|
||||
REQUIRE(fu != nullptr);
|
||||
CHECK_EQ(pint(fu, "head_dim"), 512);
|
||||
CHECK_EQ(pint(fu, "gqa"), 8);
|
||||
CHECK_EQ(pint(fu, "window"), 0);
|
||||
}
|
||||
|
||||
/* PROPORTIONAL ROPE IS NOT A PARTIAL ROTARY: the full layers rotate the whole 512-wide head as a
|
||||
* NeoX pair (j, j + 256), with every frequency past pair 63 divided away by the YaRN ramp. A
|
||||
* rotary_dim of 128 would pair (j, j + 64) -- fluent, and wrong. */
|
||||
TEST(gemma4_full_rope_is_the_whole_head_with_the_frequencies_past_64_pairs_cut) {
|
||||
RadBuilder b;
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
int full = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (o.op != "rope" || pint(&o, "head_dim") != 512) continue;
|
||||
++full;
|
||||
CHECK_EQ(pint(&o, "rotary_dim"), 512);
|
||||
CHECK_EQ(pstr(&o, "mode"), std::string("neox"));
|
||||
CHECK_NEAR(pflt(&o, "theta"), 1e6, 1.0);
|
||||
CHECK_NEAR(pflt(&o, "yarn_low"), 63.5, 1e-9);
|
||||
CHECK_NEAR(pflt(&o, "yarn_high"), 64.0, 1e-9);
|
||||
CHECK(pflt(&o, "yarn_factor") >= 1e30);
|
||||
}
|
||||
CHECK(full > 0);
|
||||
}
|
||||
|
||||
/* Where no kernel library serves a join, the plugin declares the rmsnorm / add chain instead and
|
||||
* issues that -- and libref has no row for the joins precisely so that this path stays reachable
|
||||
* (docs/OPS.md). */
|
||||
TEST(gemma4_falls_back_to_the_chain_where_no_join_resolves) {
|
||||
std::vector<std::string> fused, chain;
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadBuilder b;
|
||||
if (refuse) { b.refuse.insert("norm_add_norm"); b.refuse.insert("join_add_scale"); }
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
(refuse ? chain : fused) = issued_ops(b, c);
|
||||
}
|
||||
CHECK_EQ(count_issued(fused, "norm_add_norm"), 6);
|
||||
CHECK_EQ(count_issued(fused, "join_add_scale"), 6);
|
||||
CHECK_EQ(count_issued(chain, "norm_add_norm"), 0);
|
||||
CHECK_EQ(count_issued(chain, "join_add_scale"), 0);
|
||||
for (const auto* v : { &fused, &chain }) {
|
||||
CHECK_EQ(count_issued(*v, "attn_paged_qrow"), 5);
|
||||
CHECK_EQ(count_issued(*v, "attn_paged"), 1);
|
||||
}
|
||||
/* The chain is longer, by the norms and adds the joins fold in. */
|
||||
CHECK(count_issued(chain, "rmsnorm") > count_issued(fused, "rmsnorm"));
|
||||
CHECK(count_issued(chain, "add") > count_issued(fused, "add"));
|
||||
}
|
||||
|
||||
/* Both Gemma 4 plugins state the model's reply format, and it is one declaration. */
|
||||
TEST(both_gemma4_plugins_export_one_reply_format) {
|
||||
RadModelMeta moe = gemma4_moe_meta(), dense = gemma4_meta();
|
||||
CHECK(gemma4::chat_format(&moe) == rad::arch::gemma4_chat_format());
|
||||
CHECK(gemma4_bf16::chat_format(&dense) == rad::arch::gemma4_chat_format());
|
||||
}
|
||||
|
||||
/* ================== gemma4 + DFlash: the drafter's taps, live where they are written ================== */
|
||||
|
||||
namespace {
|
||||
|
||||
/* The MoE trunk above with z-lab's DFlash drafter merged: five layers, four sliding and one full,
|
||||
* reading the trunk at layers 1, 3 and 5. */
|
||||
std::vector<const char*> g4df_keys() {
|
||||
std::vector<const char*> k(std::begin(k_g4moe_keys), std::end(k_g4moe_keys));
|
||||
for (const char* s : { "draft.architectures", "draft.num_hidden_layers", "draft.head_dim",
|
||||
"draft.num_attention_heads", "draft.num_key_value_heads",
|
||||
"draft.intermediate_size", "draft.rms_norm_eps", "draft.rope_theta",
|
||||
"draft.hidden_size", "draft.vocab_size", "draft.block_size",
|
||||
"draft.dflash_config.target_layer_ids",
|
||||
"draft.dflash_config.mask_token_id", "draft.layer_types",
|
||||
"draft.sliding_window" })
|
||||
k.push_back(s);
|
||||
return k;
|
||||
}
|
||||
std::vector<const char*> g4df_vals() {
|
||||
std::vector<const char*> v(std::begin(k_g4moe_vals), std::end(k_g4moe_vals));
|
||||
for (const char* s : { "[\"DFlashDraftModel\"]", "5", "128", "32", "8", "5632", "1e-06",
|
||||
"1000000.0", "2816", "262144", "16", "[1, 3, 5]", "4",
|
||||
"[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", "
|
||||
"\"sliding_attention\", \"full_attention\"]",
|
||||
"2048" })
|
||||
v.push_back(s);
|
||||
return v;
|
||||
}
|
||||
|
||||
int buf_named(const RadBuilder& b, const char* name) {
|
||||
for (size_t i = 0; i < b.bufs.size(); ++i)
|
||||
if (b.bufs[i].name == name) return (int)i + 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* DFlash proposes its block in one pass, so the depth the probe names is the block it was trained
|
||||
* at less the anchor, and fixed; a container without the drafter, or with a DFlash2 one, which
|
||||
* this plugin does not serve, names none. */
|
||||
TEST(gemma4_probe_names_the_dflash_blocks_depth) {
|
||||
std::vector<const char*> keys = g4df_keys(), vals = g4df_vals();
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
meta.n_kv = (int)keys.size();
|
||||
meta.kv_key = keys.data();
|
||||
meta.kv_val = vals.data();
|
||||
RadArchProbe p{};
|
||||
CHECK_OK(gemma4::probe(&meta, &p));
|
||||
CHECK_EQ(p.draft_depth, 15);
|
||||
CHECK_EQ(p.draft_depth_fixed, 1);
|
||||
|
||||
for (size_t i = 0; i < keys.size(); ++i)
|
||||
if (!std::strcmp(keys[i], "draft.architectures")) vals[i] = "[\"DFlash2DraftModel\"]";
|
||||
meta.kv_val = vals.data();
|
||||
RadArchProbe q{};
|
||||
CHECK_OK(gemma4::probe(&meta, &q));
|
||||
CHECK_EQ(q.draft_depth, 0);
|
||||
|
||||
RadModelMeta plain = gemma4_moe_meta();
|
||||
RadArchProbe r{};
|
||||
CHECK_OK(gemma4::probe(&plain, &r));
|
||||
CHECK_EQ(r.draft_depth, 0);
|
||||
}
|
||||
|
||||
/* THE TAP IS DECLARED WHERE IT IS ISSUED. The buffer planner takes liveness from declaration order,
|
||||
* so `dflash_src` is live from its first DECLARED write. A tap op declared once after the whole
|
||||
* trunk -- and issued inside it, at each tap layer -- made the buffer look born at the end, and the
|
||||
* plan was free to put it on top of `moe_edn`, which every MoE layer writes. At --max-num-seqs 16
|
||||
* it did: every layer after a tap overwrote what the drafter reads, and acceptance fell to 2% with
|
||||
* the reply still fluent. The two ranges must overlap, so no plan can share them. */
|
||||
TEST(gemma4_dflash_taps_are_live_from_the_layer_that_writes_them) {
|
||||
const std::vector<const char*> keys = g4df_keys(), vals = g4df_vals();
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
meta.n_kv = (int)keys.size();
|
||||
meta.kv_key = keys.data();
|
||||
meta.kv_val = vals.data();
|
||||
RadBuilder b;
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 15;
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
const int src = buf_named(b, "dflash_src"), edn = buf_named(b, "moe_edn");
|
||||
REQUIRE(src > 0 && edn > 0);
|
||||
int first_src = -1, last_edn = -1;
|
||||
for (size_t i = 0; i < b.ops.size(); ++i)
|
||||
for (rad_buf w : b.ops[i].writes) {
|
||||
if ((int)w == src && first_src < 0) first_src = (int)i;
|
||||
if ((int)w == edn) last_edn = (int)i;
|
||||
}
|
||||
REQUIRE(first_src >= 0 && last_edn >= 0);
|
||||
CHECK(first_src < last_edn);
|
||||
|
||||
/* And a trunk step writes each tap once: three taps, three copies into `dflash_src`. */
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
int taps = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (o && std::find(o->writes.begin(), o->writes.end(), (rad_buf)src) != o->writes.end())
|
||||
++taps;
|
||||
}
|
||||
CHECK_EQ(taps, 3);
|
||||
}
|
||||
|
||||
/* The sliding layers' attention reads q where the fused projection left it -- no copy between the
|
||||
* qkv projection and the attention -- where attn_paged_qrow is served, and lifts q for attn_paged
|
||||
* where it is not. */
|
||||
TEST(gemma4_sliding_attention_reads_q_in_the_fused_row) {
|
||||
/* Served, attn_paged_qrow reads the slice and nothing is lifted; refused -- a hierarchy where
|
||||
* nothing serves it -- q is lifted into q_s for attn_paged, and the slice reaches no attn_paged
|
||||
* either way, since that op may resolve to a kernel that reads q only dense. */
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadBuilder b;
|
||||
if (refuse) b.refuse.insert("attn_paged_qrow");
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
const int qkv = buf_named(b, "qkv_s"), qs = buf_named(b, "q_s");
|
||||
REQUIRE(qkv > 0);
|
||||
CHECK_EQ(qs > 0, refuse == 1);
|
||||
auto reads = [](const RecOp& o, int buf) {
|
||||
return buf > 0 && std::find(o.reads.begin(), o.reads.end(), (rad_buf)buf) != o.reads.end();
|
||||
};
|
||||
int qrow = 0, paged_slice = 0, paged_lifted = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (!o.resolved) continue;
|
||||
if (o.op == "attn_paged_qrow" && reads(o, qkv)) ++qrow;
|
||||
if (o.op == "attn_paged" && reads(o, qkv)) ++paged_slice;
|
||||
if (o.op == "attn_paged" && reads(o, qs)) ++paged_lifted;
|
||||
}
|
||||
const int sliding = refuse ? paged_lifted : qrow;
|
||||
CHECK(sliding > 0);
|
||||
CHECK_EQ(refuse ? qrow : paged_lifted, 0);
|
||||
CHECK_EQ(paged_slice, 0);
|
||||
CHECK_EQ(count_op(b, "cast"), refuse ? sliding : 0); /* the lifts; no drafter, no taps */
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> issued = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(issued, "attn_paged_qrow"), refuse ? 0 : sliding);
|
||||
CHECK_EQ(count_issued(issued, "cast"), refuse ? sliding : 0);
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved) CHECK(o.uses_declared);
|
||||
}
|
||||
}
|
||||
|
||||
/* The feed-forward join writes the next layer's input norm: with the joins served, the only
|
||||
* rmsnorm from the residual `x` into `h` is layer 0's (nothing precedes it), the final norm is the
|
||||
* last join's, and every join writes `h`. Refused, the chain declares all of them again. */
|
||||
TEST(gemma4_feed_forward_join_writes_the_next_input_norm) {
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadBuilder b;
|
||||
if (refuse) { b.refuse.insert("norm_add_norm"); b.refuse.insert("join_add_scale"); }
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
const int x = buf_named(b, "x"), h = buf_named(b, "h");
|
||||
REQUIRE(x > 0 && h > 0);
|
||||
int x_to_h = 0, joins_to_h = 0;
|
||||
for (const auto& o : b.ops) {
|
||||
if (!o.resolved) continue;
|
||||
const bool rx = std::find(o.reads.begin(), o.reads.end(), (rad_buf)x) != o.reads.end();
|
||||
const bool wh = std::find(o.writes.begin(), o.writes.end(), (rad_buf)h) != o.writes.end();
|
||||
if (o.op == "rmsnorm" && rx && wh) ++x_to_h;
|
||||
if (o.op == "join_add_scale" && wh) ++joins_to_h;
|
||||
}
|
||||
/* fused: layer 0's input norm. Chained: six input norms, six pre-feedforward norms, the
|
||||
* final norm. */
|
||||
CHECK_EQ(x_to_h, refuse ? 13 : 1);
|
||||
CHECK_EQ(joins_to_h, refuse ? 0 : 6);
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> issued = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(issued, "join_add_scale"), refuse ? 0 : 6);
|
||||
CHECK_EQ(count_issued(issued, "logits_gemm"), 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* At decode heights the router, its top-k and the sort are one launch (libr4d's
|
||||
* router_gemm_topk_scatter); refused, the pair (router_topk_scatter) behind the router GEMM; both
|
||||
* refused, the three separate ops as before. The routing's buffers are the same either way. */
|
||||
TEST(gemma4_routes_a_decode_step_in_one_launch) {
|
||||
for (int refuse = 0; refuse < 3; ++refuse) {
|
||||
RadBuilder b;
|
||||
if (refuse >= 1) b.refuse.insert("router_gemm_topk_scatter");
|
||||
if (refuse >= 2) b.refuse.insert("router_topk_scatter");
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> issued = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(issued, "router_gemm_topk_scatter"), refuse == 0 ? 6 : 0);
|
||||
CHECK_EQ(count_issued(issued, "router_topk_scatter"), refuse == 1 ? 6 : 0);
|
||||
CHECK_EQ(count_issued(issued, "router_topk"), refuse == 2 ? 6 : 0);
|
||||
CHECK_EQ(count_issued(issued, "moe_scatter"), refuse == 2 ? 6 : 0);
|
||||
/* the per-expert scale and the experts' gather run whichever form routed */
|
||||
CHECK_EQ(count_issued(issued, "expert_scale"), 6);
|
||||
CHECK_EQ(count_issued(issued, "moe_gather"), 6);
|
||||
}
|
||||
}
|
||||
|
||||
/* The per-expert scale is one launch where `expert_scale` is served, and the table lookup and the
|
||||
* multiply where it is not -- the same buffers read and written either way. */
|
||||
TEST(gemma4_scales_the_routing_weights_in_one_launch) {
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadBuilder b;
|
||||
if (refuse) b.refuse.insert("expert_scale");
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> issued = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(issued, "expert_scale"), refuse ? 0 : 6);
|
||||
CHECK_EQ(count_issued(issued, "embed_lookup"), refuse ? 1 + 6 : 1); /* + the token embedding */
|
||||
CHECK_EQ(count_issued(issued, "mul"), refuse ? 6 : 0);
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved) CHECK(o.uses_declared);
|
||||
}
|
||||
}
|
||||
|
||||
/* The drafter's head reads the container's block-fp8 copy of the target's table where it holds one
|
||||
* -- `dflash.draft_head.weight` -- through quant_act_fp8 and gemm_nt_q, and the bf16 table through
|
||||
* gemm_nt where it does not. The copy is declared only in the first case, so a container converted
|
||||
* without the recipe line is served exactly as before. */
|
||||
TEST(gemma4_dflash_head_reads_the_fp8_copy_where_the_container_holds_one) {
|
||||
const std::vector<const char*> keys = g4df_keys(), vals = g4df_vals();
|
||||
for (int fp8 = 0; fp8 < 2; ++fp8) {
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
meta.n_kv = (int)keys.size();
|
||||
meta.kv_key = keys.data();
|
||||
meta.kv_val = vals.data();
|
||||
RadBuilder b;
|
||||
if (fp8)
|
||||
b.encs = { { "dflash.draft_head", rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128) } };
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 15;
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ(find_w(b, "dflash.draft_head.weight") != nullptr, fp8 == 1);
|
||||
|
||||
const int dlog = buf_named(b, "df_dlog"), selh = buf_named(b, "df_selh");
|
||||
REQUIRE(dlog > 0 && selh > 0);
|
||||
const RecOp* head = nullptr;
|
||||
for (const auto& o : b.ops)
|
||||
if (o.resolved &&
|
||||
std::find(o.writes.begin(), o.writes.end(), (rad_buf)dlog) != o.writes.end())
|
||||
head = &o;
|
||||
REQUIRE(head != nullptr);
|
||||
CHECK_EQ(head->op, std::string(fp8 ? "gemm_nt_q" : "gemm_nt"));
|
||||
const bool reads_selh =
|
||||
std::find(head->reads.begin(), head->reads.end(), (rad_buf)selh) != head->reads.end();
|
||||
CHECK_EQ(reads_selh, fp8 == 0);
|
||||
|
||||
/* and a draft pass issues it */
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
batch.draft_pass = 1;
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
int head_issues = 0;
|
||||
for (const auto& i : c.issues)
|
||||
if (b.op_of(i.op) == head) ++head_issues;
|
||||
CHECK_EQ(head_issues, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* THE DRAFTER'S RESIDUAL ADD, NORM AND QUANTISER IN ONE LAUNCH (`rmsnorm_quant_fp8`): ten a draft
|
||||
* pass over five layers, each layer's two inputs, layer 0's attention input taking x as the
|
||||
* embedding left it -- and one `add` left, the last layer's, ahead of the final norm. Refused, the
|
||||
* chain: two adds and two quantisers of x a layer. */
|
||||
TEST(gemma4_dflash_folds_the_residual_add_norm_and_quantiser_into_one_launch) {
|
||||
const std::vector<const char*> keys = g4df_keys(), vals = g4df_vals();
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
meta.n_kv = (int)keys.size();
|
||||
meta.kv_key = keys.data();
|
||||
meta.kv_val = vals.data();
|
||||
RadBuilder b;
|
||||
if (refuse) b.refuse.insert("rmsnorm_quant_fp8");
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
ctx.max_spec = 15;
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
batch.draft_pass = 1;
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> ops = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(ops, "rmsnorm_quant_fp8"), refuse ? 0 : 10);
|
||||
CHECK_EQ(count_issued(ops, "add"), refuse ? 10 : 1);
|
||||
/* x's quantiser twice a layer in the chain; the attention output's once a layer always */
|
||||
CHECK_EQ(count_issued(ops, "quant_act_fp8"), refuse ? 15 : 5);
|
||||
if (refuse) continue;
|
||||
|
||||
/* the delta then the residual x past layer 0; layer 0 reads x and adds nothing */
|
||||
const uint32_t x = (uint32_t)buf_named(b, "df_x"), h = (uint32_t)buf_named(b, "df_h");
|
||||
int k = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (!o || o->op != "rmsnorm_quant_fp8") continue;
|
||||
REQUIRE(i.opd.size() == 6);
|
||||
if (k++ == 0) {
|
||||
CHECK_EQ(i.opd[0].handle, x);
|
||||
CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_NONE);
|
||||
} else {
|
||||
CHECK_EQ(i.opd[0].handle, h);
|
||||
CHECK_EQ(i.opd[1].handle, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ============ gemma4: the prefill overlap -- two slices, the reductions on lane 1 ============ */
|
||||
|
||||
namespace {
|
||||
|
||||
/* The elements [lo, hi) of its buffer an operand can reach, whole rows at the declared width. False
|
||||
* for an operand that is not a buffer. */
|
||||
bool reach(const RadBuilder& b, const RadOperand& o, rad_buf* buf, int64_t* lo, int64_t* hi) {
|
||||
if (o.kind != RAD_OPK_BUF || o.handle == 0 || o.handle > b.bufs.size()) return false;
|
||||
const RadBufDecl& d = b.bufs[o.handle - 1].d;
|
||||
int64_t pitch = 1;
|
||||
for (uint32_t i = 1; i < d.rank; ++i) pitch *= d.shape[i];
|
||||
*buf = o.handle;
|
||||
*lo = o.offset - o.offset % pitch;
|
||||
*hi = *lo + (o.rows > 0 ? o.rows : d.shape[0]) * pitch;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Whether issue a runs before issue b (a < b): on one lane by issue order, across the two only
|
||||
* through a join from a's lane to b's issued between them. */
|
||||
bool ordered(const RadCtx& c, size_t a, size_t b) {
|
||||
const int la = c.issues[a].lane, lb = c.issues[b].lane;
|
||||
if (la == lb) return true;
|
||||
for (const RecJoin& j : c.joins)
|
||||
if (j.from == la && j.to == lb && j.at > a && j.at <= b) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Pairs of issues on different lanes that reach a common element with nothing ordering them.
|
||||
* Every operand is taken as read and written, which can only over-count. */
|
||||
int races(const RadBuilder& b, const RadCtx& c) {
|
||||
int n = 0;
|
||||
for (size_t i = 0; i < c.issues.size(); ++i)
|
||||
for (size_t j = i + 1; j < c.issues.size(); ++j) {
|
||||
if (ordered(c, i, j)) continue;
|
||||
bool meet = false;
|
||||
for (const RadOperand& p : c.issues[i].opd)
|
||||
for (const RadOperand& q : c.issues[j].opd) {
|
||||
rad_buf bp = 0, bq = 0;
|
||||
int64_t pl = 0, ph = 0, ql = 0, qh = 0;
|
||||
if (reach(b, p, &bp, &pl, &ph) && reach(b, q, &bq, &ql, &qh) && bp == bq &&
|
||||
pl < qh && ql < ph)
|
||||
meet = true;
|
||||
}
|
||||
n += meet ? 1 : 0;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* One prompt of T tokens, its last sampled. */
|
||||
RadBatch one_prompt(int64_t T, const int32_t* out) {
|
||||
RadBatch b{};
|
||||
b.phase = RAD_PHASE_PREFILL;
|
||||
b.n_tok = T;
|
||||
b.n_seq = 1;
|
||||
b.max_q_len = T;
|
||||
b.max_ctx_len = T;
|
||||
b.n_out = 1;
|
||||
b.out_ids = out;
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Rows issued, summed by op: a slice's n is its rows, a whole step's RAD_N_BATCH is T. */
|
||||
std::map<std::string, int64_t> rows_by_op(const RadBuilder& b, const RadCtx& c, int64_t T) {
|
||||
std::map<std::string, int64_t> w;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
w[o ? o->op : "<null>"] += i.n < 0 ? T : i.n;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
/* The n of each issue of one op, in issue order. */
|
||||
std::vector<int64_t> ns_of(const RadBuilder& b, const RadCtx& c, const char* op) {
|
||||
std::vector<int64_t> v;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
if (o && o->op == op) v.push_back(i.n);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
bool noted(const RadBuilder& b, const char* text) {
|
||||
for (const auto& n : b.notes)
|
||||
if (n.find(text) != std::string::npos) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* A PREFILL CHUNK IN TWO SLICES (arch/gemma4, trunk_overlap). What a recorder can check is the
|
||||
* order and the work: every reduction rides lane 1 behind its producer and ahead of its consumer,
|
||||
* nothing else does, the cut is a whole number of routed passes, and the slices issue exactly the
|
||||
* rows the whole step issues -- the same routed passes, the drafter's taps -- which is what makes
|
||||
* the output the whole step's. A chunk under two passes, and a decode step, run whole: their
|
||||
* reductions on lane 0 and the dense arm on lane 1 beside the routed arm (trunk), with nothing
|
||||
* unordered either. */
|
||||
TEST(a_gemma4_prefill_chunk_runs_as_two_slices_with_its_reductions_on_the_second_lane) {
|
||||
const std::vector<const char*> keys = g4df_keys(), vals = g4df_vals();
|
||||
const int64_t E = 2816, L = 6;
|
||||
auto model = [&](RadBuilder& b, bool whole) {
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
meta.n_kv = (int)keys.size();
|
||||
meta.kv_key = keys.data();
|
||||
meta.kv_val = vals.data();
|
||||
RadBuildCtx ctx = build_ctx(0, 4);
|
||||
ctx.max_tok = 8192;
|
||||
ctx.max_spec = 15;
|
||||
/* The lossy wire runs every chunk whole: nothing shows a slice gets the bits the whole
|
||||
* step gets on it. */
|
||||
if (whole) ctx.tp_wire_lossy = 1;
|
||||
return gemma4::declare(&b, &meta, &ctx);
|
||||
};
|
||||
auto run = [&](RadBuilder& b, RadCtx& c, RadBatch& batch) {
|
||||
c.b = &b; c.rank = 0; c.world = 4; c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
};
|
||||
|
||||
struct Case { int64_t T, cut; };
|
||||
for (const Case k : { Case{8192, 4096}, Case{6144, 4096}, Case{6143, 2048}, Case{4096, 2048},
|
||||
Case{4095, 0} }) {
|
||||
const int32_t out[1] = { (int32_t)(k.T - 1) };
|
||||
RadBuilder b;
|
||||
CHECK_OK(model(b, false));
|
||||
CHECK(noted(b, "prefill overlap: a chunk of two routed passes"));
|
||||
CHECK_EQ((int)b.concurrent.size(), 5);
|
||||
for (const char* name : { "o", "ff2", "h", "gate_up", "ffn" })
|
||||
CHECK(std::count(b.concurrent.begin(), b.concurrent.end(),
|
||||
(rad_buf)buf_named(b, name)) == 1);
|
||||
RadBatch batch = one_prompt(k.T, out);
|
||||
RadCtx c;
|
||||
run(b, c, batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK_EQ(c.lane, 0);
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
|
||||
std::vector<int64_t> lane1; /* the reductions on lane 1 */
|
||||
int dense1 = 0; /* and the dense arm's launches */
|
||||
for (const auto& i : c.issues) {
|
||||
if (i.lane != 1) continue;
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
REQUIRE(o != nullptr);
|
||||
if (o->op == "all_reduce") lane1.push_back(i.n);
|
||||
else ++dense1;
|
||||
}
|
||||
if (k.cut == 0) {
|
||||
CHECK(lane1.empty());
|
||||
CHECK_EQ(dense1, 3 * (int)L); /* gate_up, act_mul, down: beside the routed arm */
|
||||
} else {
|
||||
CHECK_EQ(dense1, 0);
|
||||
REQUIRE(lane1.size() == (size_t)(4 * L));
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
CHECK_EQ(lane1[4 * l + 0], k.cut * E); /* attention, slice A */
|
||||
CHECK_EQ(lane1[4 * l + 1], (k.T - k.cut) * E); /* attention, slice B */
|
||||
CHECK_EQ(lane1[4 * l + 2], 2 * k.cut * E); /* both arms, slice A */
|
||||
CHECK_EQ(lane1[4 * l + 3], 2 * (k.T - k.cut) * E); /* both arms, slice B */
|
||||
}
|
||||
}
|
||||
|
||||
/* The whole step, on the lossy wire: the same rows by op, the same routed passes. Its
|
||||
* reductions stay on lane 0 and only the dense arm takes the second. */
|
||||
RadBuilder w;
|
||||
CHECK_OK(model(w, true));
|
||||
CHECK(noted(w, "prefill overlap: off (the lossy all-reduce wire)"));
|
||||
CHECK(std::count(w.concurrent.begin(), w.concurrent.end(), (rad_buf)buf_named(w, "o")) == 0);
|
||||
RadBatch wbatch = one_prompt(k.T, out);
|
||||
RadCtx wc;
|
||||
run(w, wc, wbatch);
|
||||
CHECK(wc.step_fail.empty());
|
||||
CHECK_EQ(races(w, wc), 0);
|
||||
for (const auto& i : wc.issues) {
|
||||
const RecOp* o = w.op_of(i.op);
|
||||
if (i.lane == 1) CHECK(o == nullptr || o->op != "all_reduce");
|
||||
}
|
||||
CHECK(rows_by_op(b, c, k.T) == rows_by_op(w, wc, k.T));
|
||||
CHECK(ns_of(b, c, "moe_gather") == ns_of(w, wc, "moe_gather"));
|
||||
CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */
|
||||
}
|
||||
|
||||
/* A decode step: the reductions on lane 0, the dense arm on lane 1 joined in before the
|
||||
* feed-forward's, nothing unordered. */
|
||||
RadBuilder b;
|
||||
CHECK_OK(model(b, false));
|
||||
CHECK(noted(b, "the two arms: in a step that runs whole"));
|
||||
RadBatch d = decode_batch();
|
||||
RadCtx c;
|
||||
run(b, c, d);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK_EQ(c.lane, 0);
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
int dense1 = 0;
|
||||
for (const auto& i : c.issues) {
|
||||
const RecOp* o = b.op_of(i.op);
|
||||
REQUIRE(o != nullptr);
|
||||
if (o->op == "all_reduce") CHECK_EQ(i.lane, 0);
|
||||
if (i.lane == 1) {
|
||||
++dense1;
|
||||
CHECK(o->op == "gemm_nt" || o->op == "act_mul");
|
||||
}
|
||||
}
|
||||
CHECK_EQ(dense1, 3 * (int)L);
|
||||
CHECK_EQ((int)c.joins.size(), 2 * (int)L);
|
||||
}
|
||||
|
||||
/* WHERE NO LOADED LIBRARY DECLARES THE FUSED OPS -- a CPU-only build, a hierarchy without libr4d --
|
||||
* asking for one would stop the engine, so the plugin asks first (rad_op_declared) and declares
|
||||
* the chains: the rmsnorm / add joins, embed_lookup and mul for the expert scale, and q lifted for
|
||||
* attn_paged. It never asks for an undeclared op. */
|
||||
TEST(gemma4_without_the_fused_ops_declares_the_chains_and_asks_for_no_undeclared_op) {
|
||||
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
|
||||
RadBuilder b;
|
||||
b.encs = { { "ffn_gate_up_exps", fp8 } };
|
||||
for (const char* op : { "norm_add_norm", "norm_add_norm_route", "join_add_scale",
|
||||
"expert_scale", "attn_paged_qrow" })
|
||||
b.undeclared.insert(op);
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
CHECK(b.asked_undeclared.empty());
|
||||
CHECK(noted(b, "sandwich joins: 0 of 12 fused"));
|
||||
CHECK(noted(b, "routed inputs: 0 of 6"));
|
||||
CHECK(noted(b, "sliding attention: q lifted"));
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
const std::vector<std::string> ops = issued_ops(b, c);
|
||||
CHECK_EQ(count_issued(ops, "rmsnorm_quant_fp8"), 6);
|
||||
CHECK_EQ(count_issued(ops, "cast"), 5);
|
||||
CHECK(count_issued(ops, "add") > 0);
|
||||
}
|
||||
|
||||
/* THE ATTENTION JOIN WRITES THE ROUTED ARM'S INPUTS on a layer whose gate_up is block fp8
|
||||
* (norm_add_norm_route): the router's norm into moe_rn and the experts' codes into
|
||||
* moe_hq / moe_hqs, so a step issues neither the router's rmsnorm nor rmsnorm_quant_fp8. Refused,
|
||||
* norm_add_norm and the two launches. A tp-4 prefill through the overlap keeps every reduction
|
||||
* ordered with the route form too. */
|
||||
TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) {
|
||||
const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128);
|
||||
std::map<std::string, int> issued[2];
|
||||
for (int refuse = 0; refuse < 2; ++refuse) {
|
||||
RadBuilder b;
|
||||
b.encs = { { "ffn_gate_up_exps", fp8 } };
|
||||
if (refuse) b.refuse.insert("norm_add_norm_route");
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx();
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
CHECK_EQ(count_resolved(b, "norm_add_norm_route"), refuse ? 0 : 6);
|
||||
CHECK_EQ(count_resolved(b, "norm_add_norm"), refuse ? 6 : 0);
|
||||
CHECK(noted(b, refuse ? "routed inputs: 0 of 6" : "routed inputs: 6 of 6"));
|
||||
if (!refuse) {
|
||||
const RecOp* r = find_op(b, "norm_add_norm_route");
|
||||
REQUIRE(r != nullptr);
|
||||
for (const char* name : { "moe_rn", "moe_hq", "moe_hqs", "x", "h" })
|
||||
CHECK(std::count(r->writes.begin(), r->writes.end(),
|
||||
(rad_buf)buf_named(b, name)) == 1);
|
||||
}
|
||||
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 1;
|
||||
RadBatch batch = decode_batch();
|
||||
c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
for (const auto& n : issued_ops(b, c)) ++issued[refuse][n];
|
||||
}
|
||||
CHECK_EQ(issued[0]["norm_add_norm_route"], 6);
|
||||
CHECK_EQ(issued[0]["norm_add_norm"], 0);
|
||||
CHECK_EQ(issued[0]["rmsnorm_quant_fp8"], 0);
|
||||
CHECK_EQ(issued[1]["norm_add_norm_route"], 0);
|
||||
CHECK_EQ(issued[1]["norm_add_norm"], 6);
|
||||
CHECK_EQ(issued[1]["rmsnorm_quant_fp8"], 6);
|
||||
CHECK_EQ(issued[1]["rmsnorm"] - issued[0]["rmsnorm"], 6); /* the router's input norm */
|
||||
CHECK_EQ(issued[0]["moe_gemm_q"], 6);
|
||||
|
||||
/* tp 4, an 8192-token chunk in two slices */
|
||||
RadBuilder b;
|
||||
b.encs = { { "ffn_gate_up_exps", fp8 } };
|
||||
RadModelMeta meta = gemma4_moe_meta();
|
||||
RadBuildCtx ctx = build_ctx(0, 4);
|
||||
ctx.max_tok = 8192;
|
||||
CHECK_OK(gemma4::declare(&b, &meta, &ctx));
|
||||
CHECK(noted(b, "prefill overlap: a chunk of two routed passes"));
|
||||
const int32_t out[1] = { 8191 };
|
||||
RadBatch batch = one_prompt(8192, out);
|
||||
RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &batch;
|
||||
gemma4::step(&c, &batch);
|
||||
CHECK(c.step_fail.empty());
|
||||
CHECK_EQ(races(b, c), 0);
|
||||
CHECK_EQ(count_issued(issued_ops(b, c), "norm_add_norm_route"), 12);
|
||||
CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0);
|
||||
}
|
||||
@@ -1006,6 +1006,11 @@ TEST(the_c_surface_drives_the_builder) {
|
||||
CHECK(op != RAD_NULL_HANDLE);
|
||||
CHECK_EQ(rad_op_resolved(h, op), 1);
|
||||
CHECK_EQ(rad_op_resolved(h, 99), 0);
|
||||
/* Whether an op is in the vocabulary at all, asked without declaring it: no error either way. */
|
||||
CHECK_EQ(rad_op_declared(h, "t_gemm"), 1);
|
||||
CHECK_EQ(rad_op_declared(h, "t_no_such_op"), 0);
|
||||
CHECK_EQ(rad_op_declared(h, nullptr), 0);
|
||||
CHECK_EQ(b.status(), RAD_OK);
|
||||
|
||||
/* A weight declared twice cannot be diagnosed later: the container has one entry for it. */
|
||||
CHECK_EQ(rad_decl_weight(h, "blk.0.ffn_gate.weight", &wd), RAD_NULL_HANDLE);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* name and ONE object in a dialect of JSON.
|
||||
*
|
||||
* Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis
|
||||
* finds no format in it and the plugin declares one (arch/gemma4_bf16/gemma4_chat_format.h):
|
||||
* finds no format in it and the plugins declare one (arch/common/rad_gemma4_chat.h):
|
||||
*
|
||||
* <|channel>thought\n ... <channel|> reasoning
|
||||
* <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3}<tool_call|> a call, repeated for more
|
||||
@@ -28,7 +28,7 @@
|
||||
#include "text/chatparse.h"
|
||||
#include "text/tokenizer.h"
|
||||
|
||||
#include "../arch/gemma4_bf16/gemma4_chat_format.h"
|
||||
#include <arch/rad_gemma4_chat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -60,7 +60,7 @@ static std::string fixture() {
|
||||
static const Model& gemma() {
|
||||
static const Model m = { "gemma4", "gemma4", "<bos>", "<eos>",
|
||||
{ "<eos>", "<turn|>", "<|tool_response>" },
|
||||
gemma4_bf16::chat_format_decl() };
|
||||
rad::arch::gemma4_chat_format() };
|
||||
return m;
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ static std::shared_ptr<const ReplyParser> parser(const std::string& gp, bool too
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
std::shared_ptr<const ReplyFormat> r;
|
||||
if (chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why) < 0 ||
|
||||
if (chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why) < 0 ||
|
||||
ReplyFormat::compile(f, &r, &why) < 0)
|
||||
::radtest::fail(__FILE__, __LINE__, "gemma4 format: " + why);
|
||||
return r;
|
||||
@@ -167,7 +167,7 @@ static const std::string kAfter = "<|channel>thought\n";
|
||||
TEST(the_declaration_is_a_format_the_parser_runs) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why));
|
||||
CHECK_OK(chat_format_check(f, &why));
|
||||
CHECK(f.object_args());
|
||||
CHECK(f.reasoning_anywhere);
|
||||
@@ -189,7 +189,7 @@ TEST(the_declaration_is_a_format_the_parser_runs) {
|
||||
* the tagged family, no dialect, reasoning at the start only -- and Gemma's declaration read that
|
||||
* way is refused by name rather than run wrongly. */
|
||||
TEST(an_older_struct_reads_the_object_fields_as_zero) {
|
||||
RadChatFormat c = *gemma4_bf16::chat_format_decl();
|
||||
RadChatFormat c = *rad::arch::gemma4_chat_format();
|
||||
c.struct_size = (uint32_t)offsetof(RadChatFormat, args_form);
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
@@ -204,7 +204,7 @@ TEST(an_older_struct_reads_the_object_fields_as_zero) {
|
||||
|
||||
TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) {
|
||||
auto refused = [](void (*edit)(RadChatFormat&), const char* word) {
|
||||
RadChatFormat c = *gemma4_bf16::chat_format_decl();
|
||||
RadChatFormat c = *rad::arch::gemma4_chat_format();
|
||||
edit(c);
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
@@ -707,7 +707,7 @@ static int admits(const std::string& gbnf, const std::string& prefix, const std:
|
||||
static std::string grammar_for(const ChatGrammarRequest& gq) {
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why));
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
return g.text;
|
||||
@@ -723,7 +723,7 @@ TEST(the_call_grammar_admits_what_the_model_writes_and_refuses_the_rest) {
|
||||
gq.generation_prompt = b->prompt().generation_prompt;
|
||||
ChatFormat f;
|
||||
std::string why;
|
||||
CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why));
|
||||
CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why));
|
||||
ChatGrammar g;
|
||||
CHECK_OK(chat_format_grammar(f, gq, &g, &why));
|
||||
CHECK(g.lazy);
|
||||
@@ -839,7 +839,7 @@ TEST(the_chat_bridge_serves_gemma_from_its_declaration) {
|
||||
REQUIRE(v != nullptr);
|
||||
CHECK(v->is_eog(6)); /* <|tool_response>: after its calls the model stops there */
|
||||
server::ChatTemplateBridge br;
|
||||
CHECK_OK(br.init(*v, gemma4_bf16::chat_format_decl(), "gemma4_bf16"));
|
||||
CHECK_OK(br.init(*v, rad::arch::gemma4_chat_format(), "gemma4_bf16"));
|
||||
CHECK(br.supports_tools());
|
||||
CHECK(br.tool_refusal().empty());
|
||||
|
||||
|
||||
+26
-7
@@ -170,6 +170,26 @@ TEST(the_pool_size_flags_are_gone_and_say_what_replaced_them) {
|
||||
CHECK_EQ(parse({ "--vram-kv-mib", "6144" }, &k), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_prefix_cache_disk_flags_are_gone_and_the_host_size_was_renamed) {
|
||||
/* The prefix cache keeps nothing on a drive. A launch line still naming the disk tier, or the
|
||||
* host tier's old name, is refused rather than served without what it asked for. */
|
||||
for (const char* f : { "--prefix-cache-host-mib", "--prefix-cache-disk-mib", "--prefix-cache-dir" }) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ f, "4096" }, &c), RAD_E_INVAL);
|
||||
}
|
||||
Config d;
|
||||
CHECK_EQ(parse({}, &d), RAD_OK);
|
||||
CHECK_EQ(d.prefix_cache_mib, 0ll);
|
||||
CHECK_EQ(d.prefix_cache_ttl, 3600ll); /* an hour */
|
||||
Config z;
|
||||
CHECK_EQ(parse({ "--prefix-cache-ttl", "0" }, &z), RAD_OK);
|
||||
CHECK_EQ(z.prefix_cache_ttl, 0ll); /* never */
|
||||
Config n;
|
||||
CHECK_EQ(parse({ "--prefix-cache-ttl", "-1" }, &n), RAD_E_INVAL);
|
||||
Config h;
|
||||
CHECK_EQ(parse({ "--prefix-cache-ttl", "1h" }, &h), RAD_E_INVAL);
|
||||
}
|
||||
|
||||
TEST(the_sizes_and_counts_reach_the_fields_they_name) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--tp", "2",
|
||||
@@ -177,8 +197,8 @@ TEST(the_sizes_and_counts_reach_the_fields_they_name) {
|
||||
"--max-num-seqs", "8",
|
||||
"--max-model-len", "200000",
|
||||
"--host-pool-mib", "12288",
|
||||
"--prefix-cache-host-mib", "4096",
|
||||
"--prefix-cache-disk-mib", "65536",
|
||||
"--prefix-cache-mib", "4096",
|
||||
"--prefix-cache-ttl", "600",
|
||||
"--checkpoint-interval", "2048",
|
||||
"--checkpoint-slots", "8",
|
||||
"--tp-wire-min-kb", "64",
|
||||
@@ -188,8 +208,8 @@ TEST(the_sizes_and_counts_reach_the_fields_they_name) {
|
||||
CHECK_EQ(c.max_seqs, 8ll);
|
||||
CHECK_EQ(c.max_ctx, 200000ll);
|
||||
CHECK_EQ(c.host_pool_mib, 12288ll);
|
||||
CHECK_EQ(c.prefix_cache_host_mib, 4096ll);
|
||||
CHECK_EQ(c.prefix_cache_disk_mib, 65536ll);
|
||||
CHECK_EQ(c.prefix_cache_mib, 4096ll);
|
||||
CHECK_EQ(c.prefix_cache_ttl, 600ll);
|
||||
CHECK_EQ(c.checkpoint_interval, 2048ll);
|
||||
CHECK_EQ(c.checkpoint_slots, 8ll);
|
||||
CHECK_EQ(c.tp_wire_min_kb, 64ll);
|
||||
@@ -206,7 +226,6 @@ TEST(the_paths_and_names_reach_their_fields) {
|
||||
Config c;
|
||||
CHECK_EQ(parse({ "--radiance-home", "/rh",
|
||||
"--weights-disk-tier",
|
||||
"--prefix-cache-dir", "/kvdir",
|
||||
"--placement", "expert_tiered",
|
||||
"--host", "0.0.0.0",
|
||||
"--generation-config", "/g.json",
|
||||
@@ -215,7 +234,6 @@ TEST(the_paths_and_names_reach_their_fields) {
|
||||
"--override-chat-template", "/t.jinja" }, &c), RAD_OK);
|
||||
CHECK_EQ(c.radiance_home, std::string("/rh"));
|
||||
CHECK(c.weights_disk_tier);
|
||||
CHECK_EQ(c.prefix_cache_dir, std::string("/kvdir"));
|
||||
CHECK_EQ(c.placement, std::string("expert_tiered"));
|
||||
CHECK_EQ(c.host, std::string("0.0.0.0"));
|
||||
CHECK_EQ(c.generation_config, std::string("/g.json"));
|
||||
@@ -860,7 +878,8 @@ TEST(usage_names_every_flag_it_documents) {
|
||||
CHECK(text.find(std::string("Default ") + draft_window_name(kDraftWindowDefault)) !=
|
||||
std::string::npos);
|
||||
CHECK(text.find("--checkpoint-policy") != std::string::npos);
|
||||
CHECK(text.find("--prefix-cache-host-mib") != std::string::npos);
|
||||
CHECK(text.find("--prefix-cache-mib") != std::string::npos);
|
||||
CHECK(text.find("--prefix-cache-ttl") != std::string::npos);
|
||||
CHECK(text.find("--tp-wire") != std::string::npos);
|
||||
CHECK(text.find("--embedding-placement") != std::string::npos);
|
||||
CHECK(text.find("--ngram-placement") != std::string::npos);
|
||||
|
||||
+213
-1313
File diff suppressed because it is too large.
Load diff
+42
-28
@@ -15,10 +15,11 @@
|
||||
# (rad-info --plugins), from the out-of-tree home alone;
|
||||
# 4. the installed rad-kbench replays the recorded fixture through the host libraries from that
|
||||
# home, and every check passes;
|
||||
# 5. with HIP_COMPILER given, libr4d is built out of tree too, for HIP_TARGETS, and compiles to
|
||||
# the tree's device code. A replay of a device library needs a card, and this test must not
|
||||
# touch one a server is using; the same instructions mean the tree's own GPU suite
|
||||
# (ctest -L gpu) has already checked what the out-of-tree build produced.
|
||||
# 5. with HIP_COMPILER given, the device library the tree built (libr4d) is built out of tree
|
||||
# too, for HIP_TARGETS, and compiles to the tree's device code. A replay of a device library
|
||||
# needs a card, and this test must not touch one a server is using; the same instructions mean
|
||||
# the tree's own GPU suite (ctest -L gpu) has already checked what the out-of-tree build
|
||||
# produced.
|
||||
set -eu
|
||||
B=$1; S=$2; W=$3
|
||||
HIPC=${4:-}; HIPT=${5:-}
|
||||
@@ -45,13 +46,20 @@ dirs="libref libquant"
|
||||
for d in "$S"/arch/*/; do
|
||||
[ -f "$d/CMakeLists.txt" ] && dirs="$dirs arch/$(basename "$d")"
|
||||
done
|
||||
[ -n "$HIPC" ] && dirs="$dirs libr4d"
|
||||
# The device libraries: built out of tree only with the tree's HIP compiler, and left out of every
|
||||
# comparison below without it.
|
||||
devlibs=""
|
||||
for d in libr4d; do
|
||||
[ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d"
|
||||
done
|
||||
[ -n "$HIPC" ] && dirs="$dirs $devlibs"
|
||||
is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
|
||||
|
||||
for d in $dirs; do
|
||||
n=$(basename "$d")
|
||||
say "building $d against the installed package"
|
||||
extra=""
|
||||
[ "$n" = libr4d ] && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT"
|
||||
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT"
|
||||
# shellcheck disable=SC2086
|
||||
run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \
|
||||
-DCMAKE_PREFIX_PATH="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra
|
||||
@@ -66,7 +74,9 @@ sets() {
|
||||
done | sort
|
||||
}
|
||||
want=$(sets "$B/radiance_home")
|
||||
[ -n "$HIPC" ] || want=$(printf '%s\n' "$want" | grep -v '^kernels/libr4d\.so$' || true)
|
||||
if [ -z "$HIPC" ]; then
|
||||
for d in $devlibs; do want=$(printf '%s\n' "$want" | grep -v "^kernels/$d\.so\$" || true); done
|
||||
fi
|
||||
have=$(sets "$H")
|
||||
if [ "$want" != "$have" ]; then
|
||||
say "in-tree:"; say "$want"; say "out of tree:"; say "$have"
|
||||
@@ -91,9 +101,11 @@ listing() {
|
||||
grep -v '^plugins on' | grep -v '^ /'
|
||||
}
|
||||
tree_list=$(listing "$B/radiance_home")
|
||||
[ -n "$HIPC" ] || tree_list=$(printf '%s\n' "$tree_list" | grep -v ' libr4d ' || true)
|
||||
if [ -z "$HIPC" ]; then
|
||||
for d in $devlibs; do tree_list=$(printf '%s\n' "$tree_list" | grep -v " $d " || true); done
|
||||
fi
|
||||
oot_list=$(listing "$H")
|
||||
# The in-tree list numbers libr4d's position when it is left out above; compare without the order
|
||||
# The in-tree list numbers a device library's position when it is left out above; compare without the order
|
||||
# column and check the order separately by name.
|
||||
strip() { printf '%s\n' "$1" | sed 's/^ *[0-9]* //'; }
|
||||
if [ "$(strip "$tree_list")" != "$(strip "$oot_list")" ]; then
|
||||
@@ -104,12 +116,12 @@ say "3. same registration:"
|
||||
say "$oot_list"
|
||||
|
||||
# 4. The installed tools serve from the out-of-tree home. The replay runs every library its home
|
||||
# holds, so it is given the out-of-tree home less its device library, which has no card here.
|
||||
# holds, so it is given the out-of-tree home less its device libraries, which have no card here.
|
||||
HH="$W/hosthome"
|
||||
mkdir -p "$HH/kernels"
|
||||
for k in architectures quantizers; do [ -d "$H/$k" ] && ln -s "$H/$k" "$HH/$k"; done
|
||||
for so in "$H"/kernels/*.so; do
|
||||
[ "$(basename "$so")" = libr4d.so ] || ln -s "$so" "$HH/kernels/"
|
||||
is_dev "$(basename "$so" .so)" || ln -s "$so" "$HH/kernels/"
|
||||
done
|
||||
run "$W/logs/kbench.log" env HIP_VISIBLE_DEVICES=-1 RADIANCE_HOME="$HH" \
|
||||
"$P/bin/rad-kbench" --fixture "$P/share/radiance/kernels.rkb" --max-cases 1
|
||||
@@ -134,8 +146,6 @@ if [ -n "$HIPC" ]; then
|
||||
for t in llvm-objcopy llvm-readelf clang-offload-bundler; do
|
||||
[ -x "$L/$t" ] || fail "no $t beside $HIPC"
|
||||
done
|
||||
td="$B/libr4d/CMakeFiles/libr4d.dir"
|
||||
od="$W/b/libr4d/CMakeFiles/libr4d.dir"
|
||||
mkdir -p "$W/co"
|
||||
fatbin() { # fatbin OBJ -- its fat binary into $W/co/fb; false for a source with no kernels
|
||||
"$L/llvm-objcopy" --dump-section .hip_fatbin="$W/co/fb" "$1" /dev/null 2>/dev/null
|
||||
@@ -169,22 +179,26 @@ if [ -n "$HIPC" ]; then
|
||||
descriptors "$W/co/co" "$W/co/.rodata" | cksum
|
||||
cksum < "$W/co/.rodata"
|
||||
}
|
||||
[ "$(ls "$td"/*.hip.o | wc -l)" = "$(ls "$od"/*.hip.o | wc -l)" ] ||
|
||||
fail "libr4d compiles a different set of HIP sources out of tree"
|
||||
n=0
|
||||
for o in "$td"/*.hip.o; do
|
||||
f=$(basename "$o")
|
||||
[ -f "$od/$f" ] || fail "libr4d's $f has no out-of-tree twin"
|
||||
if ! fatbin "$o"; then
|
||||
if fatbin "$od/$f"; then fail "libr4d's $f has device code out of tree only"; fi
|
||||
continue
|
||||
fi
|
||||
for t in $("$L/clang-offload-bundler" --type=o --input="$W/co/fb" --list | grep -v '^host-'); do
|
||||
[ "$(code "$o" "$t")" = "$(code "$od/$f" "$t")" ] ||
|
||||
fail "libr4d's $f compiles to different device code for $t out of tree"
|
||||
n=$((n + 1))
|
||||
for lib in $devlibs; do
|
||||
td="$B/$lib/CMakeFiles/$lib.dir"
|
||||
od="$W/b/$lib/CMakeFiles/$lib.dir"
|
||||
[ "$(ls "$td"/*.hip.o | wc -l)" = "$(ls "$od"/*.hip.o | wc -l)" ] ||
|
||||
fail "$lib compiles a different set of HIP sources out of tree"
|
||||
n=0
|
||||
for o in "$td"/*.hip.o; do
|
||||
f=$(basename "$o")
|
||||
[ -f "$od/$f" ] || fail "$lib's $f has no out-of-tree twin"
|
||||
if ! fatbin "$o"; then
|
||||
if fatbin "$od/$f"; then fail "$lib's $f has device code out of tree only"; fi
|
||||
continue
|
||||
fi
|
||||
for t in $("$L/clang-offload-bundler" --type=o --input="$W/co/fb" --list | grep -v '^host-'); do
|
||||
[ "$(code "$o" "$t")" = "$(code "$od/$f" "$t")" ] ||
|
||||
fail "$lib's $f compiles to different device code for $t out of tree"
|
||||
n=$((n + 1))
|
||||
done
|
||||
done
|
||||
say "5. $lib's device code is the tree's: $n code objects, the same instructions and descriptors"
|
||||
done
|
||||
say "5. libr4d's device code is the tree's: $n code objects, the same instructions and descriptors"
|
||||
fi
|
||||
say "PASS"
|
||||
+176
-2
@@ -1955,6 +1955,81 @@ TEST(a_budgeted_victim_takes_a_lent_units_host_copy_and_a_recall_moves_the_donor
|
||||
CHECK_EQ(bad, 0);
|
||||
}
|
||||
|
||||
/* THE CARD BEHIND THE HOST: the compute stream held behind a long copy on a stream of its own, so
|
||||
* anything recorded on it from here -- a quarantine barrier -- stays pending until the copy is
|
||||
* done. */
|
||||
struct ComputeHold {
|
||||
static constexpr int64_t kBytes = 64ll << 20;
|
||||
void* a = nullptr;
|
||||
void* b = nullptr;
|
||||
RadStream s = nullptr;
|
||||
RadEvent e = nullptr;
|
||||
|
||||
int hold(RadStream compute, int rounds) {
|
||||
a = rad_dev_alloc(kBytes, RAD_MEM_DEVICE);
|
||||
b = rad_dev_alloc(kBytes, RAD_MEM_DEVICE);
|
||||
if (!a || !b) return RAD_E_NOMEM;
|
||||
RAD_TRY(rad_stream_create(&s, 0));
|
||||
RAD_TRY(rad_event_create(&e));
|
||||
for (int i = 0; i < rounds; ++i) RAD_TRY(rad_memcpy_async(a, b, kBytes, s));
|
||||
RAD_TRY(rad_event_record(e, s));
|
||||
return rad_event_wait(compute, e);
|
||||
}
|
||||
~ComputeHold() {
|
||||
if (s) { rad_stream_sync(s); rad_stream_destroy(s); }
|
||||
if (e) rad_event_destroy(e);
|
||||
if (a) rad_dev_free(a, RAD_MEM_DEVICE);
|
||||
if (b) rad_dev_free(b, RAD_MEM_DEVICE);
|
||||
}
|
||||
};
|
||||
|
||||
/* A RECALL RIGHT AFTER A DONATION, with the card behind: the swap's copies have landed but the slots
|
||||
* they gave up -- the victim's budgeted slot, the promoted unit's pool slot -- are still in
|
||||
* quarantine behind the compute stream. Those are the slots the donor is owed (donor_slot), so the
|
||||
* recall drains the stream before it looks for one, and the donor moves; looked for first, it
|
||||
* found none, the recall stopped, and the slots it had already taken from other units were held by
|
||||
* nothing for good (a KV cache stuck at 39% until restart, Qwen3.8-Flash-Next at one card). */
|
||||
TEST(a_recall_moves_a_donor_whose_slots_are_still_in_quarantine) {
|
||||
LoanRig r(24);
|
||||
r.turnover = 2;
|
||||
CHECK_OK(r.build());
|
||||
CHECK_OK(stamp_units(r, false, nullptr));
|
||||
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());
|
||||
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;
|
||||
}
|
||||
CHECK(hot >= 0 && cold >= 0);
|
||||
if (hot < 0 || cold < 0) return;
|
||||
|
||||
CHECK_OK(r.m.begin_dispatch(r.d++, &r.h));
|
||||
r.work.run(r.compute);
|
||||
Swap sw;
|
||||
sw.promote = hot;
|
||||
sw.demote = cold;
|
||||
r.h.set_busy(hot, true);
|
||||
r.h.set_busy(cold, true);
|
||||
CHECK_OK(r.m.issue(sw, &r.h));
|
||||
CHECK_EQ(r.m.stats().donated, (uint64_t)1);
|
||||
ComputeHold hold;
|
||||
CHECK_OK(hold.hold(r.compute, 48));
|
||||
CHECK_EQ(rad_event_query(hold.e), 0); /* the card is still behind at the recall */
|
||||
|
||||
CHECK_OK(r.m.reclaim(Mover::kLendKV, 0, &r.h));
|
||||
CHECK_EQ(r.m.stats().relocated, (uint64_t)1);
|
||||
CHECK_EQ(r.m.stats().stranded, (uint64_t)0);
|
||||
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)));
|
||||
int bad = 0;
|
||||
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) {
|
||||
@@ -3128,6 +3203,105 @@ TEST(embedding_ram_brings_its_own_room_beside_the_host_pool) {
|
||||
CHECK_EQ(plan2.host_budget, 3 * MiB); /* --host-pool-mib, whole */
|
||||
}
|
||||
|
||||
/* An encoder tower as the architectures declare one: a stem and a merger at model level and a
|
||||
* layer unit a block, numbered past the text layers, every weight read once per request. */
|
||||
void add_tower(Fixture& f, int first_layer, int blocks, int64_t per_block) {
|
||||
const rad_weight s = f.weight("v.patch_embd.weight", 1 * MiB, RAD_ACCESS_PER_REQUEST, -1, -1);
|
||||
f.op("vit_gemm", {s}, false);
|
||||
for (int b = 0; b < blocks; ++b) {
|
||||
const rad_weight w = f.weight("v.blk." + std::to_string(b) + ".attn_qkv.weight", per_block,
|
||||
RAD_ACCESS_PER_REQUEST, first_layer + b, -1);
|
||||
f.op("vit_gemm", {w}, false);
|
||||
}
|
||||
const rad_weight m = f.weight("v.merger.weight", 1 * MiB, RAD_ACCESS_PER_REQUEST, -1, -1);
|
||||
f.op("vit_gemm", {m}, false);
|
||||
}
|
||||
|
||||
/* THE TOWER IS FOUND BY ITS ACCESS CLASS, at every level it spans: the footprint counts every unit
|
||||
* whose weights are all read once per request, model-level and per-block alike, inside the
|
||||
* statics the resolver takes it back out of. */
|
||||
TEST(the_footprint_counts_an_encoder_tower_at_every_level) {
|
||||
Fixture f;
|
||||
build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB);
|
||||
add_tower(f, /*first_layer=*/2, /*blocks=*/3, /*per_block=*/2 * MiB);
|
||||
WeightFootprint fp;
|
||||
weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
|
||||
CHECK_EQ(fp.tower, 1 * MiB + 3 * 2 * MiB + 1 * MiB);
|
||||
CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB + fp.tower);
|
||||
|
||||
Fixture t;
|
||||
build_dense_lookup(t, /*layers=*/2, /*per_layer=*/4 * MiB);
|
||||
weight_footprint(t.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
|
||||
CHECK_EQ(fp.tower, 0ll);
|
||||
}
|
||||
|
||||
/* --vision-tower-placement ram: EVERY TOWER UNIT goes to the pinned pool, read in place, before
|
||||
* any strategy ran -- so a weights budget that holds only the text model plans, and the text model
|
||||
* stays on the card. Vram leaves the tower with the other weights. */
|
||||
TEST(tower_ram_pins_every_tower_unit_in_the_pool_and_costs_no_vram) {
|
||||
Fixture f;
|
||||
build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB);
|
||||
const size_t first_tower = f.prog.weights.size();
|
||||
add_tower(f, /*first_layer=*/2, /*blocks=*/3, /*per_block=*/2 * MiB);
|
||||
Config cfg = base_config();
|
||||
cfg.placement = "all_vram";
|
||||
cfg.vram_weights_mib = 10; /* the text model exactly: layers, embedding and head */
|
||||
cfg.host_pool_mib = 0;
|
||||
cfg.tower_resolved = TablePlacement::Ram;
|
||||
cfg.tower_host_mib = 8; /* the resolver's room beside the pool */
|
||||
Plan plan;
|
||||
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_OK(Planner(in).plan(&plan));
|
||||
for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w) {
|
||||
if ((size_t)w < first_tower) {
|
||||
CHECK(plan.weight[w].tier == Tier::VRAM);
|
||||
continue;
|
||||
}
|
||||
CHECK(plan.weight[w].tier == Tier::HostPinned);
|
||||
CHECK(plan.weight[w].site == Site::DeviceZeroCopy);
|
||||
const MoveUnit& mu = plan.units[(size_t)plan.weight[w].unit];
|
||||
CHECK(!mu.movable);
|
||||
CHECK(mu.preplaced());
|
||||
}
|
||||
CHECK_EQ(plan.tower_host_bytes, 8 * MiB);
|
||||
CHECK_EQ(plan.forced_host_used, 8 * MiB);
|
||||
CHECK_EQ(plan.host_budget, 0ll);
|
||||
CHECK(plan.report(f.prog).find("--vision-tower-placement ram") != std::string::npos);
|
||||
|
||||
cfg.tower_resolved = TablePlacement::Vram;
|
||||
cfg.tower_host_mib = 0;
|
||||
cfg.vram_weights_mib = 18;
|
||||
Plan plan2;
|
||||
CHECK_OK(Planner(in).plan(&plan2));
|
||||
for (rad_weight w = 1; (size_t)w < f.prog.weights.size(); ++w)
|
||||
CHECK(plan2.weight[w].tier == Tier::VRAM);
|
||||
CHECK_EQ(plan2.tower_host_bytes, 0ll);
|
||||
}
|
||||
|
||||
/* A tower the pool cannot hold is refused by name, and so is ram where the program has no tower:
|
||||
* the resolver only resolves Ram where the footprint found one, so that is a wiring fault. */
|
||||
TEST(tower_ram_refuses_a_pool_too_small_and_a_program_with_no_tower) {
|
||||
Fixture f;
|
||||
build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB);
|
||||
add_tower(f, /*first_layer=*/2, /*blocks=*/3, /*per_block=*/2 * MiB);
|
||||
Config cfg = base_config();
|
||||
cfg.placement = "all_vram";
|
||||
cfg.vram_weights_mib = 10;
|
||||
cfg.host_pool_mib = 0;
|
||||
cfg.tower_resolved = TablePlacement::Ram;
|
||||
cfg.tower_host_mib = 7;
|
||||
Plan plan;
|
||||
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_EQ(Planner(in).plan(&plan), RAD_E_NOMEM);
|
||||
|
||||
Fixture t;
|
||||
build_dense_lookup(t, /*layers=*/2, /*per_layer=*/4 * MiB);
|
||||
cfg.tower_host_mib = 8;
|
||||
Plan plan2;
|
||||
PlannerInput tin{&t.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_EQ(Planner(tin).plan(&plan2), RAD_E_STATE);
|
||||
}
|
||||
|
||||
/* A TABLE THAT IS NOT A WHOLE NUMBER OF PAGES still leaves the report's pinned total at what the
|
||||
* pooled units use: the pool slot is charged rounded up and the tier total counts weight bytes, so
|
||||
* the report subtracts the same weight bytes it added. */
|
||||
@@ -3141,8 +3315,8 @@ TEST(the_report_counts_a_hosted_embedding_once_in_one_unit) {
|
||||
Plan plan;
|
||||
PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
|
||||
CHECK_OK(Planner(in).plan(&plan));
|
||||
CHECK_EQ(plan.embedding_host_used, 3 * MiB + 100);
|
||||
CHECK(plan.embedding_host_bytes >= plan.embedding_host_used);
|
||||
CHECK_EQ(plan.forced_host_used, 3 * MiB + 100);
|
||||
CHECK(plan.embedding_host_bytes >= plan.forced_host_used);
|
||||
const std::string r = plan.report(f.prog);
|
||||
const size_t at = r.find("host pinned");
|
||||
CHECK(at != std::string::npos);
|
||||
|
||||
+10
-5
@@ -901,13 +901,18 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
|
||||
CHECK_EQ(names(bands(2, 1, chunk)),
|
||||
"524288:ar_oneshot_2rank_exact 5242880:ar_oneshot_2rank_exact ");
|
||||
|
||||
/* Above the two-shot's cap the one-shot takes the message back. */
|
||||
/* A 16384-token chunk is two-shot to its end: the two-shot's bound is a guard on its word
|
||||
* offsets, not a prefill size, and a chunk past the old 20971520 went back to the one-shot's
|
||||
* twice-as-heavy send. */
|
||||
CHECK_EQ(names(bands(4, 1, 16384)),
|
||||
"524288:ar_oneshot_4rank_exact 20971520:ar_twoshot_4rank_exact "
|
||||
"41943040:ar_oneshot_4rank_exact ");
|
||||
"524288:ar_oneshot_4rank_exact 41943040:ar_twoshot_4rank_exact ");
|
||||
CHECK_EQ(names(bands(3, 1, 16384)),
|
||||
"524288:ar_oneshot_3rank_exact 20971520:ar_twoshot_3rank_exact "
|
||||
"41943040:ar_oneshot_3rank_exact ");
|
||||
"524288:ar_oneshot_3rank_exact 41943040:ar_twoshot_3rank_exact ");
|
||||
|
||||
/* Above the two-shot's bound the one-shot takes the message back. */
|
||||
CHECK_EQ(names(bands(4, 1, 131072)),
|
||||
"524288:ar_oneshot_4rank_exact 268435456:ar_twoshot_4rank_exact "
|
||||
"335544320:ar_oneshot_4rank_exact ");
|
||||
|
||||
/* A step that never exceeds the bound has one band, and it is the one-shot's. */
|
||||
CHECK_EQ(names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact ");
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
#include "hip/hip_runtime.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
/* ---- the context switch: callee-saved registers and the stack pointer (x86-64 SysV) */
|
||||
extern "C" void emu_switch(void** save_sp, void* new_sp);
|
||||
asm(R"(
|
||||
.text
|
||||
.globl emu_switch
|
||||
.type emu_switch,@function
|
||||
emu_switch:
|
||||
pushq %rbp
|
||||
pushq %rbx
|
||||
pushq %r12
|
||||
pushq %r13
|
||||
pushq %r14
|
||||
pushq %r15
|
||||
movq %rsp, (%rdi)
|
||||
movq %rsi, %rsp
|
||||
popq %r15
|
||||
popq %r14
|
||||
popq %r13
|
||||
popq %r12
|
||||
popq %rbx
|
||||
popq %rbp
|
||||
ret
|
||||
)");
|
||||
|
||||
namespace {
|
||||
constexpr size_t kStack = 512 * 1024;
|
||||
struct Fiber {
|
||||
void* sp = nullptr;
|
||||
std::vector<char> stack;
|
||||
EmuIdx tid{};
|
||||
bool done = false;
|
||||
unsigned bar_gen = 0; /* block barrier generation this fiber waits on */
|
||||
unsigned wbar_gen = 0;
|
||||
int waiting = 0; /* 0 run, 1 block barrier, 2 wave barrier */
|
||||
};
|
||||
struct Sched {
|
||||
std::vector<Fiber> f;
|
||||
void* main_sp = nullptr;
|
||||
int cur = -1, nthreads = 0;
|
||||
EmuIdx bid{};
|
||||
void (*body)(void*) = nullptr;
|
||||
void* ctx = nullptr;
|
||||
/* block barrier */
|
||||
int arrive = 0; unsigned gen = 0;
|
||||
/* wave barriers and exchange slots, double-buffered by parity */
|
||||
int warrive[64] = {}; unsigned wgen[64] = {};
|
||||
int slot[64][2][32] = {};
|
||||
unsigned xparity[1024] = {};
|
||||
} S;
|
||||
|
||||
void yield() { Fiber& me = S.f[S.cur]; emu_switch(&me.sp, S.main_sp); }
|
||||
|
||||
extern "C" void emu_trampoline() {
|
||||
S.body(S.ctx);
|
||||
S.f[S.cur].done = true;
|
||||
yield();
|
||||
std::abort();
|
||||
}
|
||||
/* the entry a fresh stack "returns" into, keeping the SysV alignment at call boundaries */
|
||||
asm(R"(
|
||||
.text
|
||||
.globl emu_entry
|
||||
.type emu_entry,@function
|
||||
emu_entry:
|
||||
andq $-16, %rsp
|
||||
call emu_trampoline
|
||||
ud2
|
||||
)");
|
||||
extern "C" void emu_entry();
|
||||
} // namespace
|
||||
|
||||
EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; }
|
||||
EmuIdx& emu_block_idx() { return S.bid; }
|
||||
|
||||
void __syncthreads() {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.gen;
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; }
|
||||
me.waiting = 1;
|
||||
while (S.gen == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
|
||||
static void wave_barrier(int w) {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.wgen[w];
|
||||
if (++S.warrive[w] == 32) { S.warrive[w] = 0; ++S.wgen[w]; return; }
|
||||
me.waiting = 2;
|
||||
while (S.wgen[w] == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
|
||||
int emu_bpermute(int addr, int v) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
S.slot[w][par][l] = v;
|
||||
wave_barrier(w);
|
||||
return S.slot[w][par][(addr >> 2) & 31];
|
||||
}
|
||||
int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); }
|
||||
int emu_cvt_pk_fp8(float a, float b, int old, bool hi) {
|
||||
const unsigned pk = (unsigned)rad_f32_to_fp8e4m3(a) | ((unsigned)rad_f32_to_fp8e4m3(b) << 8);
|
||||
const unsigned o = (unsigned)old;
|
||||
return (int)(hi ? ((o & 0xffffu) | (pk << 16)) : ((o & 0xffff0000u) | pk));
|
||||
}
|
||||
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
for (int e = 0; e < 8; ++e) { g_wa[w][par][l][e] = a[e]; g_wb[w][par][l][e] = b[e]; }
|
||||
wave_barrier(w);
|
||||
auto bf = [](short v) { unsigned u = (unsigned)(unsigned short)v << 16; float f; std::memcpy(&f, &u, 4); return f; };
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 8 * h + e;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += bf(g_wa[w][par][M + 16 * (k >> 3)][k & 7]) * bf(g_wb[w][par][N + 16 * (k >> 3)][k & 7]);
|
||||
d[e] = acc;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
for (int e = 0; e < 8; ++e) { g_ha[w][par][l][e] = a[e]; g_hb[w][par][l][e] = b[e]; }
|
||||
wave_barrier(w);
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 8 * h + e;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += (float)g_ha[w][par][M + 16 * (k >> 3)][k & 7] * (float)g_hb[w][par][N + 16 * (k >> 3)][k & 7];
|
||||
d[e] = acc;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
unsigned emu_ballot(bool p) {
|
||||
unsigned m = 0;
|
||||
for (int l = 0; l < 32; ++l) m |= (unsigned)(emu_readlane(p ? 1 : 0, l) & 1) << l;
|
||||
return m;
|
||||
}
|
||||
|
||||
int emu_grids = 0;
|
||||
int emu_last_block = 0;
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) {
|
||||
++emu_grids;
|
||||
const int n = (int)(block.x * block.y * block.z);
|
||||
emu_last_block = n;
|
||||
if (block.y != 1 || block.z != 1 || n % 32 || n > 1024) { std::fprintf(stderr, "emu: block shape\n"); std::abort(); }
|
||||
S.body = body; S.ctx = ctx; S.nthreads = n;
|
||||
S.f.resize(n);
|
||||
for (auto& f : S.f) if (f.stack.size() != kStack) f.stack.assign(kStack, 0);
|
||||
for (unsigned bz = 0; bz < grid.z; ++bz)
|
||||
for (unsigned by = 0; by < grid.y; ++by)
|
||||
for (unsigned bx = 0; bx < grid.x; ++bx) {
|
||||
S.bid = EmuIdx{bx, by, bz};
|
||||
S.arrive = 0; S.gen = 0;
|
||||
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; }
|
||||
for (int t = 0; t < n; ++t) {
|
||||
Fiber& f = S.f[t];
|
||||
f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0};
|
||||
S.xparity[t] = 0;
|
||||
/* a fresh stack: six callee-saved slots, then the entry as the return address */
|
||||
void** top = (void**)(f.stack.data() + kStack - 64);
|
||||
*--top = (void*)&emu_entry;
|
||||
for (int r = 0; r < 6; ++r) *--top = nullptr;
|
||||
f.sp = top;
|
||||
}
|
||||
int live = n;
|
||||
while (live > 0) {
|
||||
int progressed = 0;
|
||||
const int live_before = live;
|
||||
const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w];
|
||||
int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w];
|
||||
live = 0;
|
||||
for (int t = 0; t < n; ++t) {
|
||||
if (S.f[t].done) continue;
|
||||
S.cur = t;
|
||||
emu_switch(&S.main_sp, S.f[t].sp);
|
||||
S.cur = -1;
|
||||
if (!S.f[t].done) ++live;
|
||||
}
|
||||
progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
|
||||
for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]);
|
||||
if (live > 0 && !progressed) {
|
||||
int done = 0, wb = 0, bb = 0;
|
||||
for (auto& f : S.f) { done += f.done; wb += f.waiting == 2; bb += f.waiting == 1; }
|
||||
std::fprintf(stderr, "emu: DEADLOCK in block (%u,%u,%u): %d threads done, %d at a block "
|
||||
"barrier, %d at a wave barrier -- a barrier not reached uniformly\n",
|
||||
bx, by, bz, done, bb, wb);
|
||||
std::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/* tests/r4d_emu: SIMT EMULATOR SHIM -- runs libr4d kernel source on the host. Every GPU thread is a fiber on
|
||||
* one OS thread; __syncthreads and every cross-lane op are barriers the scheduler enforces, and a
|
||||
* barrier some threads never reach is reported as a deadlock rather than hung. Test-only. */
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#define __global__
|
||||
#define __device__
|
||||
#define __host__
|
||||
#define __shared__ static
|
||||
#define __forceinline__ inline
|
||||
#define __launch_bounds__(n)
|
||||
|
||||
struct dim3 {
|
||||
unsigned x, y, z;
|
||||
constexpr dim3(unsigned a = 1, unsigned b = 1, unsigned c = 1) : x(a), y(b), z(c) {}
|
||||
};
|
||||
typedef void* hipStream_t;
|
||||
typedef int hipError_t;
|
||||
enum { hipSuccess = 0 };
|
||||
inline hipError_t hipGetLastError() { return 0; }
|
||||
|
||||
struct EmuIdx { unsigned x, y, z; };
|
||||
EmuIdx& emu_thread_idx();
|
||||
EmuIdx& emu_block_idx();
|
||||
#define threadIdx (emu_thread_idx())
|
||||
#define blockIdx (emu_block_idx())
|
||||
void __syncthreads();
|
||||
int emu_bpermute(int addr, int v);
|
||||
int emu_readlane(int v, int lane);
|
||||
#define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v))
|
||||
#define __builtin_amdgcn_readlane(v, l) emu_readlane((v), (l))
|
||||
unsigned emu_ballot(bool p);
|
||||
#define __builtin_amdgcn_ballot_w32(p) emu_ballot((p))
|
||||
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
|
||||
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
|
||||
typedef short emu_v8s __attribute__((ext_vector_type(8)));
|
||||
typedef float emu_v8f __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c))
|
||||
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
|
||||
/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): a and b as two codes into the low half of `old` (hi false)
|
||||
* or its high half, the other half kept; round to nearest even. The project's saturating encoder,
|
||||
* rad_f32_to_fp8e4m3, is the same function on the +-448 a kernel clamps to first. */
|
||||
int emu_cvt_pk_fp8(float a, float b, int old, bool hi);
|
||||
#define __builtin_amdgcn_cvt_pk_fp8_f32(a, b, old, hi) emu_cvt_pk_fp8((a), (b), (old), (hi))
|
||||
extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */
|
||||
|
||||
struct alignas(8) uint2 { unsigned x, y; };
|
||||
struct alignas(16) uint4 { unsigned x, y, z, w; };
|
||||
struct alignas(16) float4 { float x, y, z, w; };
|
||||
inline uint4 make_uint4(unsigned a, unsigned b, unsigned c, unsigned d) { return uint4{a, b, c, d}; }
|
||||
inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; }
|
||||
inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; }
|
||||
inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */
|
||||
inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; }
|
||||
inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; }
|
||||
|
||||
/* one block at a time, every thread a fiber */
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx);
|
||||
template <typename K, typename A>
|
||||
struct EmuCall { K k; A a; static void run(void* p) { auto* c = (EmuCall*)p; c->k(c->a); } };
|
||||
template <typename A>
|
||||
void emu_launch(void (*k)(A), dim3 g, dim3 b, A a) {
|
||||
EmuCall<void (*)(A), A> c{k, a};
|
||||
emu_run_grid(g, b, &EmuCall<void (*)(A), A>::run, &c);
|
||||
}
|
||||
#define R4D_KLAUNCH(kernel, grid, block, stream, ...) emu_launch(&kernel, grid, block, __VA_ARGS__)
|
||||
@@ -0,0 +1,213 @@
|
||||
/* ref_host.cpp -- ref_host.h's functions: the rules and roundings of r4d_pair_argmax_f32.hip,
|
||||
* r4d_norm_join_bf16.hip and r4d_expert_scale_bf16.hip, one element at a time. */
|
||||
#include "ref_host.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
/* pair_argmax: the device kernel's rules in plain C++. */
|
||||
int host_pair_argmax(const RadArgs* a) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor* p = rad_arg_in(a, 0);
|
||||
const RadTensor* t = rad_arg_in(a, 1);
|
||||
const RadTensor* v = rad_arg_in(a, 2);
|
||||
if (!p || !t) return RAD_E_INVAL;
|
||||
if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
const long long n = rad_args_geti_or(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
if (p->rank == 3) {
|
||||
if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE;
|
||||
} else if (p->rank == 2) {
|
||||
if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE;
|
||||
} else {
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
const int64_t rows = p->shape[0];
|
||||
if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE;
|
||||
const int64_t prs = p->stride[0], trs = t->rank >= 2 ? t->stride[0] : 1;
|
||||
const int64_t vrs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const float* row = (const float*)p->data + r * prs;
|
||||
int32_t bid = -1;
|
||||
float bv = -INFINITY;
|
||||
for (long long j = 0; j < n; ++j) {
|
||||
int32_t id;
|
||||
std::memcpy(&id, &row[2 * j], 4);
|
||||
const float val = row[2 * j + 1];
|
||||
if (id < 0) continue;
|
||||
if (bid < 0 || val > bv || (val == bv && id < bid)) { bid = id; bv = val; }
|
||||
}
|
||||
((int32_t*)t->data)[r * trs] = bid;
|
||||
if (v) ((float*)v->data)[r * vrs] = bv;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The joins: each value the unfused chain stores is rounded to bf16 where it stores it. Summed in
|
||||
* index order, so a ULP from the device's block order. */
|
||||
static float hb2f(uint16_t h) { const uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t hf2b(float f) {
|
||||
uint32_t u; std::memcpy(&u, &f, 4);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
static float hrbf(float f) { return hb2f(hf2b(f)); }
|
||||
static float hnorm(const float* v, int64_t n, double eps) {
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) ss += v[i] * v[i];
|
||||
return 1.0f / std::sqrt(ss / (float)n + (float)eps);
|
||||
}
|
||||
static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) {
|
||||
if (!t || t->dtype != RAD_BF16 || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
|
||||
if (t->stride[t->rank - 1] != 1) return false;
|
||||
*rows = rad_tensor_rows(t);
|
||||
*ld = rad_tensor_row_pitch(t);
|
||||
return true;
|
||||
}
|
||||
static bool hgain(const RadTensor* w, int64_t n) {
|
||||
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
|
||||
}
|
||||
|
||||
/* [rows..., n] of `dt`, dense last axis, for the route form's fp8 codes and f32 scales */
|
||||
static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) {
|
||||
if (!t || t->dtype != dt || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
|
||||
if (t->stride[t->rank - 1] != 1) return false;
|
||||
*rows = rad_tensor_rows(t);
|
||||
*ld = rad_tensor_row_pitch(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */
|
||||
static int nan_host(const RadArgs* a, bool route) {
|
||||
if (!a || a->n_t < (route ? 10 : 5)) return RAD_E_INVAL;
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
const double eps = rad_args_getf_or(a, "eps", 1e-6);
|
||||
const float mult = (float)rad_args_getf_or(a, "mult", 1.0);
|
||||
const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2),
|
||||
*Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4);
|
||||
const RadTensor *Wr = route ? rad_arg_in(a, 5) : nullptr, *R = route ? rad_arg_in(a, 6) : nullptr;
|
||||
const RadTensor *We = route ? rad_arg_in(a, 7) : nullptr, *Q = route ? rad_arg_in(a, 8) : nullptr;
|
||||
const RadTensor *S = route ? rad_arg_in(a, 9) : nullptr;
|
||||
if (n <= 0 || !A_ || !X || !Y || (route && (!R || !Q || !S))) return RAD_E_INVAL;
|
||||
if (route && (n % 128 || rad_args_geti_or(a, "group", 0) != 128)) return RAD_E_SHAPE;
|
||||
if (!hgain(Wa, n) || !hgain(Wy, n) || (route && (!hgain(Wr, n) || !hgain(We, n))))
|
||||
return RAD_E_DTYPE;
|
||||
int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0;
|
||||
if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
|
||||
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
|
||||
!hrows_as(S, RAD_F32, n / 128, &rs, &ls)))
|
||||
return RAD_E_SHAPE;
|
||||
if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE;
|
||||
const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data;
|
||||
std::vector<float> v((size_t)n), xv((size_t)n);
|
||||
for (int64_t m = 0; m < rx; ++m) {
|
||||
const uint16_t* ar = (const uint16_t*)A_->data + m * la;
|
||||
uint16_t* xr = (uint16_t*)X->data + m * lx;
|
||||
uint16_t* yr = (uint16_t*)Y->data + m * ly;
|
||||
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = hb2f(ar[i]);
|
||||
const float sa = hnorm(v.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float t = hrbf((v[(size_t)i] * sa) * wa[i]);
|
||||
xv[(size_t)i] = hrbf(hb2f(xr[i]) + t);
|
||||
xr[i] = hf2b(xv[(size_t)i]);
|
||||
}
|
||||
const float sx = hnorm(xv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]);
|
||||
if (!route) continue;
|
||||
/* the router's row, and the experts' as rmsnorm_quant_fp8 writes it (v holds it) */
|
||||
const float *wr = (const float*)Wr->data, *we = (const float*)We->data;
|
||||
uint16_t* rrow = (uint16_t*)R->data + m * lr;
|
||||
uint8_t* qrow = (uint8_t*)Q->data + m * lq;
|
||||
float* srow = (float*)S->data + m * ls;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
rrow[i] = hf2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
|
||||
v[(size_t)i] = hrbf((xv[(size_t)i] * sx) * we[i]);
|
||||
}
|
||||
for (int64_t g = 0; g < n / 128; ++g) {
|
||||
float am = 0.0f;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
|
||||
am = std::fmax(am, std::fabs(v[(size_t)i]));
|
||||
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
srow[g] = sc;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i) {
|
||||
const float c = std::fmin(std::fmax(v[(size_t)i] * inv, -448.0f), 448.0f);
|
||||
qrow[i] = rad_f32_to_fp8e4m3(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
int host_norm_add_norm(const RadArgs* a) { return nan_host(a, false); }
|
||||
int host_norm_add_norm_route(const RadArgs* a) { return nan_host(a, true); }
|
||||
|
||||
int host_join_add_scale(const RadArgs* a) {
|
||||
if (!a || a->n_t < 7) return RAD_E_INVAL;
|
||||
const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr,
|
||||
*Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
|
||||
if (!Wn != !Y) return RAD_E_INVAL;
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
const double eps = rad_args_getf_or(a, "eps", 1e-6);
|
||||
const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2),
|
||||
*Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5),
|
||||
*Sc = rad_arg_in(a, 6);
|
||||
if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL;
|
||||
if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE;
|
||||
if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE;
|
||||
if (Wn && !hgain(Wn, n)) return RAD_E_DTYPE;
|
||||
int64_t rd, ld, rr, lr, rx, lx, ry = 0, ly = 0;
|
||||
if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE;
|
||||
if (Y && !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
|
||||
if (rd < rx || rr < rx || (Y && ry < rx)) return RAD_E_SHAPE;
|
||||
const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data;
|
||||
const float sc = hb2f(*(const uint16_t*)Sc->data);
|
||||
std::vector<float> dv((size_t)n), rv((size_t)n);
|
||||
for (int64_t m = 0; m < rx; ++m) {
|
||||
const uint16_t* dr = (const uint16_t*)D->data + m * ld;
|
||||
const uint16_t* rrw = (const uint16_t*)R->data + m * lr;
|
||||
uint16_t* xr = (uint16_t*)X->data + m * lx;
|
||||
for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = hb2f(dr[i]); rv[(size_t)i] = hb2f(rrw[i]); }
|
||||
const float sd = hnorm(dv.data(), n, eps), sr = hnorm(rv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
dv[(size_t)i] = hrbf(hrbf((dv[(size_t)i] * sd) * wd[i]) + hrbf((rv[(size_t)i] * sr) * wr[i]));
|
||||
const float sj = hnorm(dv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i]));
|
||||
xr[i] = hf2b(x1 * sc);
|
||||
rv[(size_t)i] = hb2f(xr[i]);
|
||||
}
|
||||
if (Y) {
|
||||
const float* wn = (const float*)Wn->data;
|
||||
uint16_t* yr = (uint16_t*)Y->data + m * ly;
|
||||
const float sn = hnorm(rv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((rv[(size_t)i] * sn) * wn[i]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* expert_scale: the device kernel's one product. */
|
||||
int host_expert_scale(const RadArgs* a) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0);
|
||||
if (k <= 0 || ne <= 0) return RAD_E_SHAPE;
|
||||
const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2);
|
||||
if (!I || !S || !W) return RAD_E_INVAL;
|
||||
if (I->dtype != RAD_I32 || S->dtype != RAD_BF16 || W->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (rad_tensor_numel(S) < ne || rad_tensor_lastdim(I) != k || rad_tensor_lastdim(W) != k)
|
||||
return RAD_E_SHAPE;
|
||||
if (I->stride[I->rank - 1] != 1 || W->stride[W->rank - 1] != 1) return RAD_E_STRIDE;
|
||||
const int64_t rows = rad_tensor_rows(W);
|
||||
if (rad_tensor_rows(I) < rows) return RAD_E_SHAPE;
|
||||
const int64_t li = rad_tensor_row_pitch(I), lw = rad_tensor_row_pitch(W);
|
||||
const uint16_t* sc = (const uint16_t*)S->data;
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < k; ++c) {
|
||||
const int32_t id = ((const int32_t*)I->data)[r * li + c];
|
||||
const float s = (id >= 0 && id < ne) ? hb2f(sc[id]) : 0.0f;
|
||||
uint16_t* w = (uint16_t*)W->data + r * lw + c;
|
||||
*w = hf2b(hb2f(*w) * s);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/* ref_host.h -- what the four libr4d units r4d_emu runs compute, in plain C++ on the host.
|
||||
*
|
||||
* The device kernels' arithmetic restated, each a RadArgs in and RAD_OK or an error out: the
|
||||
* reference the emulated kernels are held to beside the unfused chain each test builds itself
|
||||
* (the joins, expert_scale) or a brute force (pair_argmax). No HIP, no libr4d header. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
int host_pair_argmax(const RadArgs* a);
|
||||
int host_norm_add_norm(const RadArgs* a);
|
||||
int host_norm_add_norm_route(const RadArgs* a);
|
||||
int host_join_add_scale(const RadArgs* a);
|
||||
int host_expert_scale(const RadArgs* a);
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# tests/r4d_emu/run.sh -- build and run r4d_emu with a clang that is not the build's C++ compiler.
|
||||
#
|
||||
# A build whose C++ compiler is clang builds these as ordinary targets (tests/CMakeLists.txt). The
|
||||
# docker image compiles host C++ with g++, which has no ext_vector_type; its HIP compiler is ROCm's
|
||||
# own clang++, and with `-x c++` that compiles the kernel sources as the host code this test needs.
|
||||
#
|
||||
# run.sh <clang++> <abi dir> <libr4d dir> <work dir> [sweep cases]
|
||||
set -e
|
||||
CXX=${1:?usage: run.sh <clang++> <abi dir> <libr4d dir> <work dir> [sweep cases]}
|
||||
ABI=$2; G=$3; B=$4; N=${5:-40}
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
mkdir -p "$B"
|
||||
F="-std=c++20 -O2 -ffp-contract=off -Wno-psabi -I$HERE/emu -I$HERE -I$ABI -I$G"
|
||||
$CXX $F -x c++ -c "$G/r4d_attn_paged_window.hip" -o "$B/k_attn.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_pair_argmax_f32.hip" -o "$B/k_pick.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_norm_join_bf16.hip" -o "$B/k_norm.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_expert_scale_bf16.hip" -o "$B/k_escale.o"
|
||||
$CXX $F -c "$HERE/ref_host.cpp" -o "$B/ref.o"
|
||||
$CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o"
|
||||
for t in attn pick norm escale; do
|
||||
$CXX $F -c "$HERE/test_$t.cpp" -o "$B/test_$t.o"
|
||||
$CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/k_escale.o" "$B/ref.o" \
|
||||
"$B/emu.o" -o "$B/test_$t"
|
||||
done
|
||||
"$B/test_attn"
|
||||
"$B/test_attn" sweep "$N"
|
||||
"$B/test_pick"
|
||||
"$B/test_norm"
|
||||
"$B/test_escale"
|
||||
@@ -0,0 +1,250 @@
|
||||
/* Drives libr4d's windowed attn_paged entry points (r4d_attn_paged_window.hip) through the SIMT
|
||||
* emulator and checks every output element against a port of libref's ref_attn_paged (same mask
|
||||
* predicates, f64 accumulation). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::mt19937 rng(1234);
|
||||
extern int emu_grids;
|
||||
extern int emu_last_block; /* threads a block of the last grid: 512 is the WMMA kernel */
|
||||
static float nrm() { static std::normal_distribution<float> d(0.f, 1.f); return d(rng); }
|
||||
|
||||
static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) { t.shape[i] = shape[i]; t.stride[i] = st; st *= shape[i]; }
|
||||
return t;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
int hd, gqa, kvh;
|
||||
bool fp8, causal, ragged, descale;
|
||||
int window;
|
||||
std::vector<int> qlen, ctx; /* per sequence */
|
||||
int missing_block = -1; /* sequence 0's block index to mark -1, or -1 */
|
||||
long long max_ctx = 0; /* 0: not passed */
|
||||
int64_t scratch = 0; /* 0: no scratch */
|
||||
int qpitch_extra = 0; /* q as a column slice of a wider buffer */
|
||||
int expect_wmma = -1; /* 1: must take the WMMA kernel, 0: must not, -1: either */
|
||||
};
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static Fn pick(int hd, int gqa, bool fp8) {
|
||||
#define P(H, G) if (hd == H && gqa == G) return fp8 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
#undef P
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static int run(const Case& c) {
|
||||
const int n_seq = (int)c.qlen.size(), HD = c.hd, kvh = c.kvh, qh = kvh * c.gqa;
|
||||
int rows = 0; for (int q : c.qlen) rows += q;
|
||||
/* blocks: each sequence gets ceil(ctx/16) blocks at shuffled ids */
|
||||
int maxb = 0; for (int x : c.ctx) maxb = std::max(maxb, (x + 15) / 16);
|
||||
maxb += 1; /* a spare column: the table is wider than any sequence needs */
|
||||
const int nblocks = n_seq * maxb + 3;
|
||||
std::vector<int> ids(nblocks); for (int i = 0; i < nblocks; ++i) ids[i] = i;
|
||||
std::shuffle(ids.begin(), ids.end(), rng);
|
||||
std::vector<int> bt(n_seq * maxb, -1);
|
||||
int nx = 0;
|
||||
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < (c.ctx[s] + 15) / 16; ++b) bt[s * maxb + b] = ids[nx++];
|
||||
if (c.missing_block >= 0) bt[c.missing_block] = -1;
|
||||
/* the cache, filled everywhere -- including slots past each context, with NaN in some, so a
|
||||
* kernel that reads a masked key's V without guarding is caught */
|
||||
const int64_t slot = 2 * HD, nel = (int64_t)nblocks * kvh * 16 * slot;
|
||||
std::vector<float> kvf(nel);
|
||||
std::vector<uint16_t> kvb(nel); std::vector<uint8_t> kv8(nel);
|
||||
for (int64_t i = 0; i < nel; ++i) {
|
||||
float v = nrm();
|
||||
if (c.fp8) { kv8[i] = rad_f32_to_fp8e4m3(v * 4.f); kvf[i] = rad_fp8e4m3_to_f32(kv8[i]); }
|
||||
else { kvb[i] = rad_f32_to_bf16(v); kvf[i] = rad_bf16_to_f32(kvb[i]); }
|
||||
}
|
||||
/* poison: every slot at or past a sequence's context in its last block, and every block no
|
||||
* table names */
|
||||
std::vector<char> named(nblocks, 0);
|
||||
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < maxb; ++b) if (bt[s * maxb + b] >= 0) named[bt[s * maxb + b]] = 1;
|
||||
auto poison = [&](int64_t i) { if (c.fp8) { kv8[i] = 0x7f; } else { kvb[i] = 0x7fc0; } kvf[i] = NAN; };
|
||||
for (int blk = 0; blk < nblocks; ++blk) if (!named[blk]) for (int64_t i = 0; i < kvh * 16 * slot; ++i) poison((int64_t)blk * kvh * 16 * slot + i);
|
||||
for (int s = 0; s < n_seq; ++s) {
|
||||
const int last = (c.ctx[s] - 1) / 16, blk = bt[s * maxb + last];
|
||||
if (blk < 0) continue;
|
||||
for (int o = c.ctx[s] % 16 ? c.ctx[s] % 16 : 16; o < 16; ++o)
|
||||
for (int h = 0; h < kvh; ++h) for (int d = 0; d < slot; ++d) poison((((int64_t)blk * kvh + h) * 16 + o) * slot + d);
|
||||
}
|
||||
const int qcols = qh * HD + c.qpitch_extra;
|
||||
std::vector<uint16_t> qb((size_t)rows * qcols); std::vector<float> qf(qb.size());
|
||||
for (size_t i = 0; i < qb.size(); ++i) { qb[i] = rad_f32_to_bf16(nrm()); qf[i] = rad_bf16_to_f32(qb[i]); }
|
||||
std::vector<int> su(c.ctx), cu(n_seq + 1, 0);
|
||||
for (int s = 0; s < n_seq; ++s) cu[s + 1] = cu[s] + c.qlen[s];
|
||||
std::vector<float> kd(n_seq * kvh, 1.f), vd(n_seq * kvh, 1.f);
|
||||
if (c.descale) for (auto* v : {&kd, &vd}) for (auto& x : *v) x = 0.5f + (float)(rng() % 100) / 100.f;
|
||||
std::vector<uint16_t> out((size_t)rows * qh * HD, 0xffff);
|
||||
std::vector<char> scratch(c.scratch + 64);
|
||||
char* sp = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
|
||||
RadTensor t[8];
|
||||
t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols;
|
||||
t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot});
|
||||
t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb});
|
||||
t[3] = tens(su.data(), RAD_I32, {n_seq});
|
||||
t[4] = c.descale ? tens(kd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
t[5] = c.descale ? tens(vd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
t[6] = c.ragged ? tens(cu.data(), RAD_I32, {n_seq + 1}) : RadTensor{};
|
||||
t[7] = tens(out.data(), RAD_BF16, {rows, qh, HD});
|
||||
int qmax = 0; for (int q : c.qlen) qmax = std::max(qmax, q);
|
||||
std::vector<RadParam> p;
|
||||
auto pi = [&](const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); };
|
||||
auto ps = [&](const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = v; p.push_back(x); };
|
||||
auto pf = [&](const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); };
|
||||
pi("q_len", qmax + 3); /* the band bound, above the step's max */
|
||||
pi("head_dim", HD); pi("gqa", c.gqa); pi("block_size", 16); pi("causal", c.causal); pi("window", c.window);
|
||||
ps("q_dtype", "bf16"); ps("kv_dtype", c.fp8 ? "fp8_e4m3" : "bf16");
|
||||
const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */
|
||||
pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq);
|
||||
if (c.max_ctx) pi("max_ctx", c.max_ctx);
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p.data(); a.n_p = (int)p.size();
|
||||
a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch;
|
||||
Fn fn = pick(HD, c.gqa, c.fp8);
|
||||
const int g0 = emu_grids;
|
||||
const int rc = fn(&a, nullptr);
|
||||
const int launches = emu_grids - g0;
|
||||
if (rc != RAD_OK) { std::printf("%-44s launch returned %d\n", c.name.c_str(), rc); return 1; }
|
||||
|
||||
/* the reference */
|
||||
double max_err = 0, max_ref = 0, se = 0, sr = 0; long bad = 0, nan_out = 0;
|
||||
for (int s = 0; s < n_seq; ++s) for (int i = 0; i < c.qlen[s]; ++i) for (int h = 0; h < qh; ++h) {
|
||||
const int tok = cu[s] + i, kh = h / c.gqa, pos = c.ctx[s] - c.qlen[s] + i;
|
||||
auto visible = [&](int j) {
|
||||
if (c.causal ? j > pos : j >= c.ctx[s]) return false;
|
||||
if (c.window > 0) { const int d = pos - j; if (c.causal ? d >= c.window : (d >= c.window || d <= -c.window)) return false; }
|
||||
return bt[s * maxb + j / 16] >= 0;
|
||||
};
|
||||
std::vector<double> sc(c.ctx[s], -INFINITY); double mx = -INFINITY;
|
||||
for (int j = 0; j < c.ctx[s]; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot;
|
||||
double dot = 0; for (int d = 0; d < HD; ++d) dot += (double)qf[(size_t)tok * qcols + h * HD + d] * kvf[kb + d] * kd[s * kvh + kh];
|
||||
sc[j] = dot * scale; mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(HD, 0.0); double sum = 0;
|
||||
if (mx > -INFINITY)
|
||||
for (int j = 0; j < c.ctx[s]; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx); sum += w;
|
||||
const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot;
|
||||
for (int d = 0; d < HD; ++d) acc[d] += w * kvf[kb + HD + d] * vd[s * kvh + kh];
|
||||
}
|
||||
for (int d = 0; d < HD; ++d) {
|
||||
const double ref = sum > 0 ? acc[d] / sum : 0.0;
|
||||
const float got = rad_bf16_to_f32(out[((size_t)tok * qh + h) * HD + d]);
|
||||
if (std::isnan(got)) { ++nan_out; continue; }
|
||||
const double e = std::fabs(got - ref);
|
||||
max_err = std::max(max_err, e); max_ref = std::max(max_ref, std::fabs(ref));
|
||||
se += e * e; sr += ref * ref;
|
||||
if (e > 1e-2 * std::max(1.0, std::fabs(ref)) + 4e-3 * std::fabs(ref)) ++bad;
|
||||
}
|
||||
}
|
||||
const double rel = std::sqrt(se / std::max(sr, 1e-30));
|
||||
const bool ok = bad == 0 && nan_out == 0 && rel < 5e-3;
|
||||
std::printf("%-44s rows %4d %s rel_l2 %.2e max_abs %.2e bad %ld nan %ld %s\n", c.name.c_str(), rows,
|
||||
launches > 1 ? "split" : emu_last_block == 512 ? "wmma " : " ", rel, max_err, bad, nan_out,
|
||||
ok ? "PASS" : "FAIL");
|
||||
if (c.expect_wmma >= 0 && (emu_last_block == 512) != (c.expect_wmma == 1)) {
|
||||
std::printf("%-44s took the %s kernel, expected the %s one\n", c.name.c_str(),
|
||||
emu_last_block == 512 ? "WMMA" : "scalar", c.expect_wmma ? "WMMA" : "scalar");
|
||||
return 1;
|
||||
}
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const int64_t s256 = r4d_rad_attn_window_h256_scratch(nullptr), s512 = r4d_rad_attn_window_h512_scratch(nullptr);
|
||||
std::vector<Case> cases = {
|
||||
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
|
||||
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
/* the real window, a context past it, a verify-sized query */
|
||||
{"h256 gqa2 swa w1024 verify16", 256, 2, 1, false, true, false, false, 1024, {16}, {1100}},
|
||||
/* split-KV decode: one row a sequence, long context, scratch present */
|
||||
{"h256 gqa2 swa w1024 decode split", 256, 2, 2, false, true, true, false, 1024, {1, 1}, {1300, 40}, -1, 0, s256},
|
||||
/* Gemma 4 full: h512, causal, no window, at the three TP ratios */
|
||||
{"h512 gqa8 full ragged bf16", 512, 8, 1, false, true, true, false, 0, {2, 7}, {90, 33}},
|
||||
{"h512 gqa8 full decode split fp8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa4 full verify16 split", 512, 4, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
|
||||
/* the serving case: max_ctx 262144 gives a decode step 64 splits, most of them empty */
|
||||
{"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512},
|
||||
{"h256 gqa2 swa w1024 verify, ragged, splits", 256, 2, 2, true, true, true, true, 1024, {3, 5}, {20, 900}, -1, 262144, s256},
|
||||
{"h512 gqa2 full ragged", 512, 2, 2, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}},
|
||||
/* the coverage the rows claim beyond Gemma: non-causal, two-sided window, a missing block */
|
||||
{"h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {6, 2}, {70, 30}, 2},
|
||||
{"h512 gqa1 noncausal full", 512, 1, 1, false, false, false, false, 0, {4}, {37}},
|
||||
{"h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {5}, {21}, -1, 0, 0, 512},
|
||||
/* no scratch where a split was wanted: falls back to the unsplit kernel */
|
||||
{"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}},
|
||||
/* PREFILL-SHAPED: the WMMA kernel (a 64-row query, or longer) */
|
||||
{"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
|
||||
{"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa1 noncausal", 512, 1, 1, false, false, false, false, 0, {64}, {100}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w1024 prefill 300 of 1500", 256, 2, 2, false, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {80, 70}, {200, 70}, 3, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {64}, {64}, -1, 0, 0, 512, 1},
|
||||
{"wmma h256 gqa1 causal w5 fp8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
|
||||
/* and what must stay scalar: a verify batch, many sequences, a few rows each */
|
||||
{"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16},
|
||||
{40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0},
|
||||
};
|
||||
if (argc > 1 && std::string(argv[1]) == "sweep") {
|
||||
const int n = argc > 2 ? std::atoi(argv[2]) : 200;
|
||||
int fails = 0, splits = 0, wmmas = 0;
|
||||
const int hds[2] = {256, 512}, gqas[4] = {1, 2, 4, 8};
|
||||
for (int it = 0; it < n; ++it) {
|
||||
Case c;
|
||||
c.hd = hds[rng() % 2]; c.gqa = gqas[rng() % 4]; c.kvh = 1 + rng() % 3;
|
||||
c.fp8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
|
||||
c.window = rng() % 3 == 0 ? 0 : 1 + rng() % 200;
|
||||
const int ns = 1 + rng() % 4;
|
||||
const bool pre = rng() % 3 == 0; /* prefill-shaped: the WMMA kernel */
|
||||
const int qspan = pre ? 160 : 40, qmin = pre ? 64 : 1;
|
||||
const int ql = qmin + rng() % qspan;
|
||||
for (int s = 0; s < ns; ++s) {
|
||||
int q = c.ragged ? (int)(rng() % 3 == 0 ? 0 : qmin + rng() % qspan) : ql;
|
||||
if (c.ragged && s == 0 && q == 0) q = 1;
|
||||
c.qlen.push_back(q);
|
||||
c.ctx.push_back(q + (int)(rng() % 400));
|
||||
}
|
||||
if (rng() % 2) c.scratch = c.hd == 256 ? s256 : s512;
|
||||
if (rng() % 2) c.max_ctx = 512;
|
||||
if (rng() % 5 == 0) c.missing_block = (int)(rng() % ((c.ctx[0] + 15) / 16));
|
||||
c.name = "sweep " + std::to_string(it) + " h" + std::to_string(c.hd) + " g" + std::to_string(c.gqa) +
|
||||
" kvh" + std::to_string(c.kvh) + (c.fp8 ? " fp8" : " bf16") + (c.causal ? " c" : " nc") +
|
||||
" w" + std::to_string(c.window) + (c.ragged ? " rag" : "");
|
||||
const int g0 = emu_grids;
|
||||
fails += run(c);
|
||||
splits += emu_grids - g0 > 1;
|
||||
wmmas += emu_last_block == 512;
|
||||
}
|
||||
std::printf("sweep: %d cases, %d took the split path, %d the WMMA kernel, %d failure(s)\n", n, splits,
|
||||
wmmas, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
int fails = 0;
|
||||
for (auto& c : cases) {
|
||||
if (argc > 1 && c.name.find(argv[1]) == std::string::npos) continue;
|
||||
fails += run(c);
|
||||
}
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/* tests/r4d_emu: expert_scale (r4d_expert_scale_bf16.hip) on the host SIMT emulator, against the chain it
|
||||
* replaces -- embed_lookup of the [n_expert, 1] scale table by the ids, then mul into the weights --
|
||||
* and against ref_host.cpp, bit for bit: one product rounded once has no other answer. Ids outside
|
||||
* the table (a negative pad, one past the end) read a zero scale; rows past M and the pitch's
|
||||
* padding stay untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(5);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
int fails = 0, cases = 0;
|
||||
for (int ne : {32, 128}) for (int k : {1, 8}) for (int M : {1, 4, 16, 37}) for (int pad : {0, 3}) {
|
||||
const int ld = k + pad, R = M + 2;
|
||||
std::vector<int32_t> ids((size_t)R * ld);
|
||||
for (auto& v : ids) {
|
||||
const int u = (int)(rng() % 40);
|
||||
v = u == 0 ? -1 : u == 1 ? ne : (int)(rng() % (unsigned)ne); /* pads, one past */
|
||||
}
|
||||
std::vector<uint16_t> table((size_t)ne), ew0((size_t)R * ld);
|
||||
for (auto& v : table) v = f2b(0.5f + 0.25f * nd(rng));
|
||||
for (auto& v : ew0) v = f2b(nd(rng));
|
||||
auto dev = ew0, hst = ew0;
|
||||
RadTensor t[3]{};
|
||||
t[0].data = ids.data(); t[0].dtype = RAD_I32; t[0].rank = 2; t[0].shape[0] = M; t[0].shape[1] = k; t[0].stride[0] = ld; t[0].stride[1] = 1;
|
||||
t[1].data = table.data(); t[1].dtype = RAD_BF16; t[1].rank = 1; t[1].shape[0] = ne; t[1].stride[0] = 1;
|
||||
t[2].dtype = RAD_BF16; t[2].rank = 2; t[2].shape[0] = M; t[2].shape[1] = k; t[2].stride[0] = ld; t[2].stride[1] = 1;
|
||||
RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n_expert", RAD_P_INT, ne}; p[2] = {"top_k", RAD_P_INT, k};
|
||||
p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 4;
|
||||
t[2].data = dev.data();
|
||||
const int rd = r4d_rad_expert_scale_bf16(&a, nullptr);
|
||||
t[2].data = hst.data();
|
||||
const int rh = host_expert_scale(&a);
|
||||
bool ok = rd == RAD_OK && rh == RAD_OK;
|
||||
for (int r = 0; r < R && ok; ++r)
|
||||
for (int c = 0; c < ld && ok; ++c) {
|
||||
const size_t o = (size_t)r * ld + c;
|
||||
uint16_t want = ew0[o];
|
||||
if (r < M && c < k) {
|
||||
const int id = ids[o];
|
||||
const uint16_t es = (id >= 0 && id < ne) ? table[(size_t)id] : f2b(0.0f); /* embed_lookup */
|
||||
want = f2b(b2f(ew0[o]) * b2f(es)); /* mul */
|
||||
}
|
||||
ok = dev[o] == want && hst[o] == want;
|
||||
}
|
||||
++cases;
|
||||
if (!ok) { ++fails; std::printf("FAIL n_expert %d top_k %d M %d pitch %d\n", ne, k, M, ld); }
|
||||
}
|
||||
std::printf("expert_scale: %d cases, %d failure(s)\n", cases, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
/* tests/r4d_emu: the sandwich-norm joins (r4d_norm_join_bf16.hip) on the host SIMT emulator.
|
||||
*
|
||||
* Two references. The CHAIN is the unfused sequence the arch plugin would otherwise issue -- rmsnorm,
|
||||
* add, rmsnorm (or rmsnorm x2, add, rmsnorm, add, mul_weight) -- in libr4d's per-element arithmetic,
|
||||
* its sums of squares added in this kernel's block order: the fused kernel must match it BIT FOR
|
||||
* BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in
|
||||
* index order -- what a different libr4d block width does too -- and may differ by a flipped
|
||||
* rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be
|
||||
* left alone. The route form's chain adds the router's rmsnorm (with its mult) and libr4d's
|
||||
* rmsnorm_quant_fp8 of the experts' norm -- amax * (1 / 448) a group, the clamped value encoded by
|
||||
* the emulator's v_cvt_pk_fp8_f32, the saturating encoder every fp8 cast here uses. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::mt19937 rng(11);
|
||||
static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
|
||||
static float rb(float f) { return b2f(f2b(f)); }
|
||||
|
||||
/* the kernel's sum of squares: 256 threads strided over the row, a butterfly a wave, waves in order */
|
||||
static float block_factor(const std::vector<float>& v, int n, float eps) {
|
||||
float part[256];
|
||||
for (int t = 0; t < 256; ++t) {
|
||||
float s = 0.0f;
|
||||
for (int k = 0; k < 24; ++k) { const int i = t + 256 * k; const float x = i < n ? v[(size_t)i] : 0.0f; s += x * x; }
|
||||
part[t] = s;
|
||||
}
|
||||
float total = 0.0f;
|
||||
for (int w = 0; w < 8; ++w) {
|
||||
float l[32];
|
||||
for (int i = 0; i < 32; ++i) l[i] = part[w * 32 + i];
|
||||
for (int d = 16; d >= 1; d >>= 1) {
|
||||
float nl[32];
|
||||
for (int i = 0; i < 32; ++i) nl[i] = l[i] + l[i ^ d];
|
||||
std::memcpy(l, nl, sizeof l);
|
||||
}
|
||||
total += l[0];
|
||||
}
|
||||
return 1.0f / std::sqrt(total / (float)n + eps);
|
||||
}
|
||||
static std::vector<float> chain_norm(const std::vector<float>& v, const float* g, int n, float eps) {
|
||||
const float f = block_factor(v, n, eps);
|
||||
std::vector<float> y((size_t)n);
|
||||
for (int i = 0; i < n; ++i) y[(size_t)i] = rb((v[(size_t)i] * f) * g[i]);
|
||||
return y;
|
||||
}
|
||||
|
||||
static RadTensor rows(void* p, uint32_t dt, int64_t M, int64_t n, int64_t ld) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = M; t.shape[1] = n; t.stride[0] = ld; t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, uint32_t dt, int64_t n) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
static std::vector<uint16_t> randb(size_t k, float sd) {
|
||||
std::normal_distribution<float> d(0.f, sd);
|
||||
std::vector<uint16_t> v(k);
|
||||
for (auto& x : v) x = f2b(d(rng));
|
||||
return v;
|
||||
}
|
||||
static std::vector<float> gains(int n) {
|
||||
std::normal_distribution<float> d(1.f, 0.4f);
|
||||
std::vector<float> g((size_t)n);
|
||||
for (auto& x : g) x = d(rng);
|
||||
return g;
|
||||
}
|
||||
/* vs the host arm, the difference in units of the row's RMS: a different summation order moves the
|
||||
* norm factor by an f32 ulp, which flips a bf16 rounding here and there -- and where the residual
|
||||
* add cancels, a flipped ulp of the addend is many ulps of a small sum, so ulps of the OUTPUT are
|
||||
* the wrong yardstick and the row's scale is the right one. */
|
||||
struct Tally { long chain_bad = 0, host_diff = 0, host_bad = 0, pad = 0; double worst = 0.0; };
|
||||
static void cmp(const uint16_t* got, const uint16_t* chain, const uint16_t* host, int n, Tally& t) {
|
||||
double ss = 0.0;
|
||||
for (int i = 0; i < n; ++i) ss += (double)b2f(host[i]) * b2f(host[i]);
|
||||
const double rms = std::sqrt(ss / n) + 1e-30;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (got[i] != chain[i]) ++t.chain_bad;
|
||||
if (got[i] == host[i]) continue;
|
||||
++t.host_diff;
|
||||
const double e = std::fabs((double)b2f(got[i]) - b2f(host[i])) / rms;
|
||||
if (e > t.worst) t.worst = e;
|
||||
/* one bf16 ulp of an element at 4x the row's rms is up to 3% of it: 1/16 passes a flipped
|
||||
* rounding of a large element and fails anything a real bug produces */
|
||||
if (e > 1.0 / 16) ++t.host_bad;
|
||||
}
|
||||
}
|
||||
|
||||
static int case_nan(int M, int n, int pad, int extra_rows) {
|
||||
const int ld = n + pad, R = M + extra_rows;
|
||||
const float eps = 1e-6f;
|
||||
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
|
||||
auto wa = gains(n), wy = gains(n);
|
||||
auto xd = x, yd = y0, xh = x, yh = y0;
|
||||
RadTensor t[5] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n),
|
||||
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
|
||||
rows(yd.data(), RAD_BF16, M, n, ld) };
|
||||
RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 5; ar.p = p; ar.n_p = 4;
|
||||
if (r4d_rad_norm_add_norm_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm: device launch failed"); return 1; }
|
||||
t[2].data = xh.data(); t[4].data = yh.data();
|
||||
if (host_norm_add_norm(&ar) != RAD_OK) { std::puts("norm_add_norm: host launch failed"); return 1; }
|
||||
Tally tx, ty;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld;
|
||||
if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; }
|
||||
for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]);
|
||||
std::vector<float> av((size_t)n), xv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]);
|
||||
const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */
|
||||
std::vector<uint16_t> cx((size_t)n), cy((size_t)n);
|
||||
for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */
|
||||
const auto t2 = chain_norm(xv, wy.data(), n, eps); /* rmsnorm */
|
||||
for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(t2[(size_t)i]);
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
cmp(&yd[o], cy.data(), &yh[o], n, ty);
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0;
|
||||
std::printf("norm_add_norm M %3d n %4d pitch %4d: vs chain x %ld y %ld differ; vs host arm %ld/%ld differ, worst "
|
||||
"%.1e of the row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, ty.chain_bad, tx.host_diff,
|
||||
ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad, ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts'
|
||||
* E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns,
|
||||
* so that group's amax is 0 and its scale the quantiser's 1. */
|
||||
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) {
|
||||
const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3;
|
||||
const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n);
|
||||
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
|
||||
auto r0 = randb((size_t)R * ld, 1.f);
|
||||
auto wa = gains(n), wy = gains(n), wr = gains(n), we = gains(n);
|
||||
if (zero_group && n >= 256) for (int i = 128; i < 256; ++i) we[(size_t)i] = 0.0f;
|
||||
std::vector<uint8_t> q0((size_t)R * ldq);
|
||||
std::vector<float> s0((size_t)R * lds);
|
||||
for (auto& v : q0) v = (uint8_t)(rng() & 0xff);
|
||||
for (auto& v : s0) v = -7.0f;
|
||||
auto xd = x, yd = y0, rd = r0, xh = x, yh = y0, rh = r0;
|
||||
auto qd = q0, qh = q0;
|
||||
auto sd = s0, sh = s0;
|
||||
RadTensor t[10] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n),
|
||||
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
|
||||
rows(yd.data(), RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
|
||||
rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n),
|
||||
rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
|
||||
RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128};
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6;
|
||||
if (r4d_rad_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
|
||||
t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data();
|
||||
if (host_norm_add_norm_route(&ar) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; }
|
||||
Tally tx, ty, tr;
|
||||
long q_chain = 0, s_chain = 0, q_host_bad = 0, touched = 0;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld, oq = (size_t)m * ldq, os = (size_t)m * lds;
|
||||
if (m >= M) {
|
||||
for (int i = 0; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
|
||||
for (int i = 0; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
|
||||
for (int i = 0; i < lds; ++i) touched += sd[os + i] != s0[os + i];
|
||||
continue;
|
||||
}
|
||||
for (int i = n; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
|
||||
for (int i = n; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
|
||||
for (int i = G; i < lds; ++i) touched += sd[os + i] != s0[os + i];
|
||||
std::vector<float> av((size_t)n), xv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]);
|
||||
const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */
|
||||
std::vector<uint16_t> cx((size_t)n), cy((size_t)n), cr((size_t)n);
|
||||
for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */
|
||||
const float f = block_factor(xv, n, eps);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
cy[(size_t)i] = f2b((xv[(size_t)i] * f) * wy[(size_t)i]); /* rmsnorm */
|
||||
cr[(size_t)i] = f2b(((xv[(size_t)i] * f) * wr[(size_t)i]) * mult); /* the router's */
|
||||
}
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
cmp(&yd[o], cy.data(), &yh[o], n, ty);
|
||||
cmp(&rd[o], cr.data(), &rh[o], n, tr);
|
||||
for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */
|
||||
float h[128], am = 0.0f;
|
||||
for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); }
|
||||
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc;
|
||||
s_chain += sd[os + g] != sc;
|
||||
if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain;
|
||||
for (int j = 0; j < 128; ++j) {
|
||||
const int i = g * 128 + j;
|
||||
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
|
||||
/* vs the host arm: one code step is an eighth of its value at most, which is no
|
||||
* more than an eighth of the group's amax; a scale an ulp off moves less */
|
||||
const double dv = std::fabs((double)rad_fp8e4m3_to_f32(qd[oq + i]) * sd[os + g] -
|
||||
(double)rad_fp8e4m3_to_f32(qh[oq + i]) * sh[os + g]);
|
||||
if (dv > (double)am / 8 + 1e-30) ++q_host_bad;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 &&
|
||||
tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0;
|
||||
std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
|
||||
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld,
|
||||
zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain,
|
||||
tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
/* `next`: also the next layer's input norm, y = norm(x) * w_n over the x the join writes */
|
||||
static int case_jas(int M, int n, int pad, int extra_rows, bool next = false) {
|
||||
const int ld = n + pad, R = M + extra_rows;
|
||||
const float eps = 1e-6f;
|
||||
/* the two arms as one [2M, n] buffer, as the plugin holds them: dense rows, then routed */
|
||||
auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f), y0 = randb((size_t)R * ld, 1.f);
|
||||
auto wd = gains(n), wr = gains(n), wj = gains(n), wn = gains(n);
|
||||
uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f);
|
||||
auto xd = x, xh = x, yd = y0, yh = y0;
|
||||
RadTensor t[9] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n),
|
||||
rows(ff.data() + (size_t)M * ld, RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
|
||||
vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1),
|
||||
vec(wn.data(), RAD_F32, n), rows(yd.data(), RAD_BF16, M, n, ld) };
|
||||
RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = next ? 9 : 7; ar.p = p; ar.n_p = 4;
|
||||
if (r4d_rad_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; }
|
||||
t[5].data = xh.data(); t[8].data = yh.data();
|
||||
if (host_join_add_scale(&ar) != RAD_OK) { std::puts("join_add_scale: host launch failed"); return 1; }
|
||||
Tally tx, ty;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld;
|
||||
if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; }
|
||||
for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]);
|
||||
std::vector<float> dv((size_t)n), rv((size_t)n), sv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) { dv[(size_t)i] = b2f(ff[o + i]); rv[(size_t)i] = b2f(ff[(size_t)M * ld + o + i]); }
|
||||
const auto d1 = chain_norm(dv, wd.data(), n, eps); /* rmsnorm (arm 1) */
|
||||
const auto r1 = chain_norm(rv, wr.data(), n, eps); /* rmsnorm (arm 2) */
|
||||
for (int i = 0; i < n; ++i) sv[(size_t)i] = rb(d1[(size_t)i] + r1[(size_t)i]); /* add */
|
||||
const auto j = chain_norm(sv, wj.data(), n, eps); /* rmsnorm */
|
||||
std::vector<uint16_t> cx((size_t)n);
|
||||
for (int i = 0; i < n; ++i) cx[(size_t)i] = f2b(rb(b2f(x[o + i]) + j[(size_t)i]) * b2f(sc)); /* add, mul_weight */
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
if (next) { /* the next rmsnorm */
|
||||
std::vector<float> xv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) xv[(size_t)i] = b2f(cx[(size_t)i]);
|
||||
const auto yn = chain_norm(xv, wn.data(), n, eps);
|
||||
std::vector<uint16_t> cy((size_t)n);
|
||||
for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(yn[(size_t)i]);
|
||||
cmp(&yd[o], cy.data(), &yh[o], n, ty);
|
||||
}
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0;
|
||||
std::printf("join_add_scale%s M %3d n %4d pitch %4d: vs chain %ld/%ld differ; vs host arm %ld/%ld differ, worst %.1e "
|
||||
"of the row rms; padding touched %ld -> %s\n", next ? "+next" : " ", M, n, ld, tx.chain_bad,
|
||||
ty.chain_bad, tx.host_diff, ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad,
|
||||
ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = 0;
|
||||
/* Gemma 4 26B's 2816 at decode and verify heights, a prefill height, odd widths, the limit */
|
||||
const int Ms[] = {1, 4, 16, 37};
|
||||
for (int M : Ms) fails += case_nan(M, 2816, M % 2 ? 64 : 0, 2);
|
||||
for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 0 : 128, 2);
|
||||
fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1);
|
||||
fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0);
|
||||
fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1);
|
||||
/* the edge between the 12-a-thread kernels and the 24: 3072 the last of the first */
|
||||
fails += case_nan(2, 3072, 0, 1) + case_nan(2, 3073, 8, 1);
|
||||
fails += case_jas(2, 3072, 0, 1, true) + case_jas(2, 3073, 8, 1, true) + case_jas(3, 3073, 0, 1);
|
||||
/* and with the next layer's input norm folded in */
|
||||
for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true);
|
||||
fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true);
|
||||
/* the route form: the 26B-A4B's width at decode, verify and prefill heights, the edge between the
|
||||
* 12- and 24-a-thread kernels, one group, the limit, and a group whose norm is all zero */
|
||||
for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2);
|
||||
fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1);
|
||||
fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true);
|
||||
std::printf("norm joins: %d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/* pair_argmax: device kernel (emulated) vs ref_host.cpp vs brute force, over the row-interleaved
|
||||
* [rows][world][R][2] layout the all_gather produces -- ties, negative (unfilled) ids, -inf, empty rows. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
int main() {
|
||||
std::mt19937 rng(11);
|
||||
int fails = 0, cases = 0;
|
||||
for (int world : {1, 2, 4, 8}) for (int R : {2, 4}) for (int rows : {1, 7, 16, 33, 240}) for (int rank3 = 0; rank3 < 2; ++rank3) {
|
||||
const int n = world * R;
|
||||
std::vector<float> pairs((size_t)rows * n * 2);
|
||||
std::vector<int32_t> ref(rows), dev(rows, 12345), hst(rows, 12345), pitched(rows * 3, 777);
|
||||
std::vector<float> dval(rows), hval(rows);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
int32_t bid = -1; float bv = -INFINITY;
|
||||
const int mode = rng() % 5; /* 0: ties, 1: some unfilled, 2: all unfilled, else random */
|
||||
for (int j = 0; j < n; ++j) {
|
||||
int32_t id = (int32_t)(rng() % 262144);
|
||||
float v = mode == 0 ? 3.5f : std::ldexp((float)(int)(rng() % 2000) - 1000.f, -4);
|
||||
if ((mode == 1 && rng() % 3 == 0) || mode == 2) { id = -1; v = -INFINITY; }
|
||||
std::memcpy(&pairs[((size_t)r * n + j) * 2], &id, 4);
|
||||
pairs[((size_t)r * n + j) * 2 + 1] = v;
|
||||
if (id >= 0 && (bid < 0 || v > bv || (v == bv && id < bid))) { bid = id; bv = v; }
|
||||
}
|
||||
ref[r] = bid;
|
||||
}
|
||||
RadTensor t[3]{};
|
||||
t[0].data = pairs.data(); t[0].dtype = RAD_F32;
|
||||
if (rank3) { t[0].rank = 3; t[0].shape[0] = rows; t[0].shape[1] = n; t[0].shape[2] = 2; t[0].stride[0] = n * 2; t[0].stride[1] = 2; t[0].stride[2] = 1; }
|
||||
else { t[0].rank = 2; t[0].shape[0] = rows; t[0].shape[1] = 2 * n; t[0].stride[0] = 2 * n; t[0].stride[1] = 1; }
|
||||
t[1].dtype = RAD_I32; t[1].rank = 2; t[1].shape[0] = rows; t[1].shape[1] = 1; t[1].stride[0] = 1; t[1].stride[1] = 1;
|
||||
t[2].dtype = RAD_F32; t[2].rank = 2; t[2].shape[0] = rows; t[2].shape[1] = 1; t[2].stride[0] = 1; t[2].stride[1] = 1;
|
||||
RadParam p[3]{}; p[0] = {"M", RAD_P_INT, rows}; p[1] = {"n", RAD_P_INT, n}; p[2].key = "dtype"; p[2].kind = RAD_P_STR; p[2].sval = "f32";
|
||||
RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 3;
|
||||
t[1].data = dev.data(); t[2].data = dval.data();
|
||||
int rc = r4d_rad_pair_argmax_f32(&a, nullptr);
|
||||
t[1].data = hst.data(); t[2].data = hval.data();
|
||||
int rh = host_pair_argmax(&a);
|
||||
/* a pitched output: every third element, the rest must stay untouched */
|
||||
RadTensor tp = t[1]; tp.data = pitched.data(); tp.stride[0] = 3; RadTensor t3[3] = {t[0], tp, RadTensor{}};
|
||||
RadArgs ap = a; ap.t = t3;
|
||||
int rp = r4d_rad_pair_argmax_f32(&ap, nullptr);
|
||||
bool ok = rc == 0 && rh == 0 && rp == 0;
|
||||
for (int r = 0; r < rows && ok; ++r) {
|
||||
ok = dev[r] == ref[r] && hst[r] == ref[r] && pitched[3 * r] == ref[r] && pitched[3 * r + 1] == 777 && pitched[3 * r + 2] == 777;
|
||||
if (ok && ref[r] < 0) ok = std::isinf(dval[r]) && dval[r] < 0;
|
||||
}
|
||||
++cases; if (!ok) { ++fails; std::printf("FAIL world %d R %d rows %d rank%d\n", world, R, rows, rank3 ? 3 : 2); }
|
||||
}
|
||||
std::printf("pair_argmax: %d cases, %d failure(s)\n", cases, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
+38
-1
@@ -275,7 +275,7 @@ TEST(op_vocabulary) {
|
||||
"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",
|
||||
"row_topk_merge", "logit_rerank",
|
||||
"row_topk_merge", "pair_argmax", "logit_rerank",
|
||||
"gdn_conv_prep", "gdn_conv_update", "gdn_kkt_solve", "gdn_chunk_scan",
|
||||
"gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm",
|
||||
"all_reduce", "all_gather",
|
||||
@@ -606,6 +606,43 @@ TEST(op_scale) {
|
||||
CHECK(run("scale", b) != RAD_OK);
|
||||
}
|
||||
|
||||
/* The sharded draft head's merge at R = 1, on paper: three rows of four gathered pairs, each case
|
||||
* one rule. Row 0 ties on 2.0 between ids 9 and 3 (the lower id wins, whatever slot it sits in)
|
||||
* beside a pad carrying the row's largest value (dropped: a pad is a negative id, not a value);
|
||||
* row 1 is all pads (-1 and -inf, nothing invented); row 2 is all negative values (the largest is
|
||||
* still the answer). `idx` is written at a pitch of two, as a proposal lands in a token buffer laid
|
||||
* out for something else, and the slots between are left alone. */
|
||||
TEST(op_pair_argmax) {
|
||||
struct P { int32_t id; float v; };
|
||||
const P rows[3][4] = {
|
||||
{ { 5, 1.0f }, { 9, 2.0f }, { 3, 2.0f }, { -1, 7.0f } },
|
||||
{ { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f }, { -1, 9.0f } },
|
||||
{ { 7, -3.0f }, { 2, -4.0f }, { 11, -1.0f }, { 4, -1.5f } },
|
||||
};
|
||||
T pairs(RAD_F32, {3, 4, 2});
|
||||
float* pf = (float*)pairs.t.data;
|
||||
for (int m = 0; m < 3; ++m)
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
std::memcpy(&pf[(m * 4 + j) * 2], &rows[m][j].id, 4);
|
||||
pf[(m * 4 + j) * 2 + 1] = rows[m][j].v;
|
||||
}
|
||||
T idx(RAD_I32, {3, 2}); idx.n({ 100, 100, 100, 100, 100, 100 });
|
||||
idx.t.shape[1] = 1; /* [3, 1] at a row pitch of 2 */
|
||||
T val(RAD_F32, {3});
|
||||
A a; a.t(pairs).t(idx).t(val).i("M", 3).i("n", 4).s("dtype", "f32");
|
||||
CHECK_OK(run("pair_argmax", a));
|
||||
CHECK_EQ(idx.iat(0), 3); CHECK_EQ(val.at(0), 2.0f);
|
||||
CHECK_EQ(idx.iat(2), -1); CHECK(std::isinf(val.at(1)) && val.at(1) < 0);
|
||||
CHECK_EQ(idx.iat(4), 11); CHECK_EQ(val.at(2), -1.0f);
|
||||
CHECK_EQ(idx.iat(1), 100); CHECK_EQ(idx.iat(3), 100);
|
||||
|
||||
/* `val` is optional, and the ids do not depend on it. */
|
||||
T idx2(RAD_I32, {3});
|
||||
A b; b.t(pairs).t(idx2).tnull().i("M", 3).i("n", 4).s("dtype", "f32");
|
||||
CHECK_OK(run("pair_argmax", b));
|
||||
CHECK_EQ(idx2.iat(0), 3); CHECK_EQ(idx2.iat(1), -1); CHECK_EQ(idx2.iat(2), 11);
|
||||
}
|
||||
|
||||
/* The quantised gather. Three things, and the scale is the least interesting of them.
|
||||
*
|
||||
* The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0,
|
||||
|
||||
+74
-55
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "mm/processor.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sched/advance_impl.h"
|
||||
#include "sched/derive.h"
|
||||
@@ -365,14 +366,8 @@ struct FakePC : IPrefixCache {
|
||||
}
|
||||
}
|
||||
|
||||
/* The requests whose context is still being read off disk. */
|
||||
std::vector<uint64_t> reading;
|
||||
std::vector<uint64_t> restores;
|
||||
Restore restore(const Request& r) override {
|
||||
restores.push_back(r.id);
|
||||
return std::find(reading.begin(), reading.end(), r.id) != reading.end() ? Restore::Wait
|
||||
: Restore::Done;
|
||||
}
|
||||
void restore(const Request& r) override { restores.push_back(r.id); }
|
||||
|
||||
mutable int64_t lookups = 0;
|
||||
/* A cap (HitCap) as prefix.cpp applies one: attention ends at a block at or below it, the
|
||||
@@ -459,11 +454,7 @@ struct FakePC : IPrefixCache {
|
||||
return ((pos / interval) + 1) * interval;
|
||||
}
|
||||
std::vector<int64_t> committed;
|
||||
std::vector<int64_t> resumed; /* the commits marked as resume points */
|
||||
void commit_checkpoint(const Request&, int64_t pos, bool resume) override {
|
||||
committed.push_back(pos);
|
||||
if (resume) resumed.push_back(pos);
|
||||
}
|
||||
void commit_checkpoint(const Request&, int64_t pos) override { committed.push_back(pos); }
|
||||
int reserve_checkpoint(const Request&, int64_t, int32_t* slot_out) override {
|
||||
++reserved;
|
||||
*slot_out = next_slot++;
|
||||
@@ -629,6 +620,22 @@ struct Fixture {
|
||||
return id;
|
||||
}
|
||||
|
||||
/* One whose prompt carries a picture the encoder has not run yet: it waits in the queue until
|
||||
* `*item` says it is encoded. */
|
||||
uint64_t submit_unencoded(int n_prompt, int max_tokens, std::shared_ptr<mm::Item>* item) {
|
||||
auto r = std::make_unique<Request>();
|
||||
r->id = next_id++;
|
||||
r->max_tokens = max_tokens;
|
||||
r->prompt.resize((size_t)n_prompt);
|
||||
for (int i = 0; i < n_prompt; ++i) r->prompt[(size_t)i] = 1000 + i;
|
||||
*item = std::make_shared<mm::Item>();
|
||||
r->media = std::make_shared<mm::PromptMedia>();
|
||||
r->media->items.push_back(mm::Placed{*item, 0});
|
||||
uint64_t id = r->id;
|
||||
if (sch.add(std::move(r)) < 0) return 0;
|
||||
return id;
|
||||
}
|
||||
|
||||
/* The same, with the server's sink attached, for what a request tells its client. */
|
||||
uint64_t submit_to(server::Sink* sink, int n_prompt, int max_tokens) {
|
||||
auto r = std::make_unique<Request>();
|
||||
@@ -971,23 +978,6 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
|
||||
CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */
|
||||
}
|
||||
|
||||
/* THE DEEPEST CHECKPOINT A PROMPT GETS IS ITS RESUME POINT, and it alone is committed as one: it is
|
||||
* the state the next turn resumes from, and the tiers copy it off the card at once rather than
|
||||
* with the rest of the conversation at its publish. */
|
||||
TEST(only_a_prompt_s_deepest_checkpoint_is_its_resume_point) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
const uint64_t a = f.submit(1000, 8);
|
||||
for (int i = 0; i < 64 && f.sch.find(a)->n_computed < 1000; ++i) {
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
}
|
||||
REQUIRE(f.pc.committed.size() >= 2u);
|
||||
REQUIRE_EQ(f.pc.resumed.size(), 1u);
|
||||
CHECK_EQ(f.pc.resumed[0], f.pc.committed.back());
|
||||
}
|
||||
|
||||
/* A hit that skipped tokens with no snapshot to resume from is the corruption this whole mechanism
|
||||
* exists to prevent, so it is refused outright rather than served with a zeroed state. */
|
||||
TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) {
|
||||
@@ -1091,17 +1081,17 @@ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) {
|
||||
}
|
||||
|
||||
/* ================================================================== preemption */
|
||||
/* A REQUEST WHOSE CONTEXT IS STILL BEING READ OFF DISK WAITS, AND ONLY IT DOES. It is not admitted
|
||||
* short -- the hit length is what its prefill is shaped by -- and it does not hold up the queue:
|
||||
* the request behind it is asked and runs. Once the read is in, it is admitted where it stood. */
|
||||
TEST(a_request_waiting_on_a_disk_read_lets_the_queue_past_it) {
|
||||
/* A REQUEST WHOSE MEDIA IS NOT ENCODED YET WAITS, AND ONLY IT DOES. It is not admitted without
|
||||
* its rows, and it does not hold up the queue: the request behind it is asked and runs. Once its
|
||||
* items are encoded, it is admitted where it stood. */
|
||||
TEST(a_request_waiting_on_its_encoder_lets_the_queue_past_it) {
|
||||
Fixture f;
|
||||
f.build();
|
||||
CHECK_OK(f.start());
|
||||
const uint64_t a = f.submit(160, 8);
|
||||
std::shared_ptr<mm::Item> ia, ic;
|
||||
const uint64_t a = f.submit_unencoded(160, 8, &ia);
|
||||
const uint64_t b = f.submit(160, 8);
|
||||
const uint64_t c = f.submit(160, 8);
|
||||
f.pc.reading = {a, c};
|
||||
const uint64_t c = f.submit_unencoded(160, 8, &ic);
|
||||
|
||||
const RadBatch* s1 = f.sch.step();
|
||||
CHECK(s1 != nullptr);
|
||||
@@ -1117,18 +1107,16 @@ TEST(a_request_waiting_on_a_disk_read_lets_the_queue_past_it) {
|
||||
CHECK_EQ(q[1], c);
|
||||
f.commit_plain();
|
||||
|
||||
/* Asked again every step, and admitted the step its read is in. */
|
||||
f.pc.reading = {c};
|
||||
f.pc.restores.clear();
|
||||
/* Asked again every step, and admitted the step its items are in. */
|
||||
ia->encoded = true;
|
||||
const RadBatch* s2 = f.sch.step();
|
||||
CHECK(s2 != nullptr);
|
||||
CHECK_EQ(s2->n_seq, 2);
|
||||
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
|
||||
CHECK_EQ((int)f.sch.find(c)->state, (int)ReqState::Waiting);
|
||||
CHECK(std::find(f.pc.restores.begin(), f.pc.restores.end(), c) != f.pc.restores.end());
|
||||
f.commit_plain();
|
||||
|
||||
f.pc.reading.clear();
|
||||
ic->encoded = true;
|
||||
const RadBatch* s3 = f.sch.step();
|
||||
CHECK(s3 != nullptr);
|
||||
CHECK_EQ(s3->n_seq, 3);
|
||||
@@ -1885,9 +1873,8 @@ TEST(busy_cap_keeps_the_stager_floor_and_never_leaves_a_runt) {
|
||||
CHECK_EQ(f.sch.busy_cap(0, 100000, 2048, 8 + 256, false, false), 1024);
|
||||
}
|
||||
|
||||
/* The share left for a request that then does not start (here its context is still being read
|
||||
* back from the host tier) goes back to the chunk that made room for it: the step is planned as
|
||||
* if nothing had waited. */
|
||||
/* The share left for a request that then does not start (here its media is not encoded yet) goes
|
||||
* back to the chunk that made room for it: the step is planned as if nothing had waited. */
|
||||
TEST(auto_a_share_nobody_takes_goes_back_to_the_prefill) {
|
||||
Fixture f;
|
||||
share_fixture(f, -1);
|
||||
@@ -1895,8 +1882,8 @@ TEST(auto_a_share_nobody_takes_goes_back_to_the_prefill) {
|
||||
uint64_t a = f.submit(3500, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain();
|
||||
uint64_t b = f.submit(100, 64);
|
||||
f.pc.reading.push_back(b);
|
||||
std::shared_ptr<mm::Item> ib;
|
||||
REQUIRE(f.submit_unencoded(100, 64, &ib) != 0);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
REQUIRE_EQ((int)f.sch.plan().e.size(), 1);
|
||||
CHECK_EQ(f.sch.plan().e[0].seq, a);
|
||||
@@ -2271,10 +2258,10 @@ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) {
|
||||
CHECK_EQ(h.plan_step(hone, 0, 3), 2);
|
||||
}
|
||||
|
||||
/* THE FLAG, AND ONLY FOR A SERIAL HEAD. --draft-window adaptive with a block drafter, with prompt
|
||||
* lookup alone, or with no speculation keeps the configured depth and says so at startup; the
|
||||
* proposal then reaches the step uncut. The default is the fixed window. */
|
||||
TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not) {
|
||||
/* THE FLAG, FOR A DRAFTING HEAD -- SERIAL OR BLOCK. --draft-window adaptive with prompt lookup
|
||||
* alone, or with no speculation, keeps the configured depth and says so at startup; the proposal
|
||||
* then reaches the step uncut. The default is the fixed window. */
|
||||
TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_none) {
|
||||
{
|
||||
Fixture f;
|
||||
adaptive_fixture(f, 4);
|
||||
@@ -2293,18 +2280,50 @@ TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not)
|
||||
Config d;
|
||||
CHECK(d.draft_window == kDraftWindowDefault); /* the default */
|
||||
}
|
||||
for (int kind : { (int)RAD_DRAFT_BLOCK, (int)RAD_DRAFT_NONE }) {
|
||||
/* A BLOCK DRAFTER TAKES THE POLICY WITH ITS ROUNDS FIXED. It proposes its whole block in one
|
||||
* pass, and each sequence verifies the first of it up to its own window: the whole block while
|
||||
* its estimate is the prior, one draft once its drafts stop being taken. Startup says so. */
|
||||
{
|
||||
Fixture f;
|
||||
adaptive_fixture(f, 4);
|
||||
f.prog.drafter.kind = (decltype(f.prog.drafter.kind))kind;
|
||||
if (kind == RAD_DRAFT_NONE) f.prog.drafter.depth = 0;
|
||||
f.prog.drafter.kind = RAD_DRAFT_BLOCK;
|
||||
int st = RAD_E_STATE;
|
||||
const std::string log = stderr_of([&] { st = f.start(); });
|
||||
CHECK_OK(st);
|
||||
CHECK(f.sch.draft().adaptive());
|
||||
CHECK(log.find("ADAPTIVE") != std::string::npos);
|
||||
CHECK(log.find("with a block drafter") != std::string::npos);
|
||||
CHECK(log.find("the window is fixed") == std::string::npos);
|
||||
|
||||
const uint64_t a = f.submit(160, 2000);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
f.commit_plain(11);
|
||||
int32_t draft[4] = { 21, 22, 23, 24 };
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 4));
|
||||
CHECK_EQ(f.sch.find(a)->n_draft, 4);
|
||||
for (int t = 0; t < 64; ++t) { /* no draft is ever taken */
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
f.commit_plain(9);
|
||||
CHECK_OK(f.sch.set_draft(a, draft, 4));
|
||||
}
|
||||
CHECK_EQ(f.sch.find(a)->n_draft, 1);
|
||||
REQUIRE(f.sch.step() != nullptr);
|
||||
for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, 1);
|
||||
CHECK(f.sch.metrics().draft_adaptive);
|
||||
CHECK(f.sch.metrics().draft_verify_depth[4] > 0);
|
||||
CHECK(f.sch.metrics().draft_verify_depth[1] > 0);
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
adaptive_fixture(f, 4);
|
||||
f.prog.drafter.kind = RAD_DRAFT_NONE;
|
||||
f.prog.drafter.depth = 0;
|
||||
int st = RAD_E_STATE;
|
||||
const std::string log = stderr_of([&] { st = f.start(); });
|
||||
CHECK_OK(st);
|
||||
CHECK(!f.sch.draft().adaptive());
|
||||
CHECK(log.find("--draft-window adaptive: the window is fixed at 4") != std::string::npos);
|
||||
CHECK(log.find(kind == RAD_DRAFT_BLOCK ? "a block drafter" : "prompt lookup only") !=
|
||||
std::string::npos);
|
||||
CHECK(log.find("prompt lookup only") != std::string::npos);
|
||||
|
||||
const uint64_t a = f.submit(160, 64);
|
||||
CHECK(f.sch.step() != nullptr);
|
||||
|
||||
@@ -854,6 +854,14 @@ TEST(a_body_or_template_json_nested_past_the_bound_is_refused) {
|
||||
CHECK_OK(parse_chat_request(call(nest(fine)), f.odeps(), lim, &r, &e));
|
||||
CHECK_OK(parse_chat_request(result(nest(fine)), f.odeps(), lim, &r, &e));
|
||||
}
|
||||
/* A tool result that is not JSON is never parsed into a tree, so brackets in it are text:
|
||||
* openers that never close, and nesting with text before or after it. */
|
||||
{
|
||||
OaiRequest r; ApiError e;
|
||||
CHECK_OK(parse_chat_request(result(std::string(5000, '[')), f.odeps(), lim, &r, &e));
|
||||
CHECK_OK(parse_chat_request(result("got: " + nest(deep)), f.odeps(), lim, &r, &e));
|
||||
CHECK_OK(parse_chat_request(result(nest(deep) + ","), f.odeps(), lim, &r, &e));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the 400 path */
|
||||
@@ -2216,6 +2224,62 @@ TEST(timings_rates_divide_the_tokens_by_the_time_that_produced_them) {
|
||||
CHECK(j["prompt_per_second"].is_null());
|
||||
}
|
||||
|
||||
/* THE SERVER'S OWN TIME, from the moment the body had arrived: ttft_ms is everything up to the
|
||||
* first token, total_ms everything up to the last, on the buffered body and on a stream's final
|
||||
* chunk. A request made in-process has no arrival to count from and reports neither. */
|
||||
TEST(timings_count_ttft_and_total_from_the_bodys_arrival) {
|
||||
auto arrived = [](const char* path, const std::string& body) {
|
||||
HttpRequest q;
|
||||
q.method = "POST";
|
||||
q.path = path;
|
||||
q.body = body;
|
||||
/* Five milliseconds before now, on the steady clock the sinks count on. */
|
||||
q.t_received_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count() - 5000000;
|
||||
return q;
|
||||
};
|
||||
auto check = [](const json& t) {
|
||||
REQUIRE(t["ttft_ms"].is_number());
|
||||
REQUIRE(t["total_ms"].is_number());
|
||||
CHECK(t["ttft_ms"].get<double>() >= 5.0);
|
||||
CHECK(t["ttft_ms"].get<double>() >= t["prompt_ms"].get<double>());
|
||||
CHECK_NEAR(t["total_ms"].get<double>(),
|
||||
t["ttft_ms"].get<double>() + t["predicted_ms"].get<double>(), 1e-6);
|
||||
};
|
||||
{
|
||||
Fixture f;
|
||||
HttpResponse r = f.srv->router().dispatch(
|
||||
arrived("/v1/chat/completions", R"({"messages":[{"role":"user","content":"hi"}]})"));
|
||||
CHECK_EQ(r.status, 200);
|
||||
check(json::parse(r.body)["timings"]);
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
HttpResponse r = f.srv->router().dispatch(
|
||||
arrived("/v1/completions", R"({"prompt":"hi","stream":true})"));
|
||||
CHECK_EQ(r.status, 200);
|
||||
int bad = 0, finals = 0;
|
||||
auto p = sse_payloads(drain(r), &bad);
|
||||
CHECK_EQ(bad, 0);
|
||||
for (size_t i = 0; i + 1 < p.size(); ++i) {
|
||||
const json j = json::parse(p[i]);
|
||||
if (j["choices"][0]["finish_reason"].is_null()) continue;
|
||||
++finals;
|
||||
check(j["timings"]);
|
||||
}
|
||||
CHECK_EQ(finals, 1);
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
HttpResponse r = f.post("/v1/chat/completions",
|
||||
R"({"messages":[{"role":"user","content":"hi"}]})");
|
||||
CHECK_EQ(r.status, 200);
|
||||
const json t = json::parse(r.body)["timings"];
|
||||
CHECK(t["ttft_ms"].is_null());
|
||||
CHECK(t["total_ms"].is_null());
|
||||
}
|
||||
}
|
||||
|
||||
/* The sink keeps the first admission across a preemption and sums the drafts it is told of. */
|
||||
TEST(a_sink_keeps_its_first_admission_and_sums_its_drafts) {
|
||||
Sink s;
|
||||
|
||||
@@ -977,6 +977,32 @@ TEST(vocab_ends_a_generation_on_every_id_the_checkpoint_names) {
|
||||
CHECK_EQ(v->eog().size(), (size_t)2);
|
||||
}
|
||||
|
||||
/* The names the loader completes the set from, for a container that declares one eos and no list:
|
||||
* Gemma 4's turn end and its tool-response opener end a generation; `</s>` does not where the
|
||||
* vocabulary has a turn marker of its own, and does where it has none. */
|
||||
TEST(vocab_completes_the_end_set_from_known_control_names_and_keeps_a_turn_vocabularys_s_tag_as_text) {
|
||||
VocabBuild vb;
|
||||
vb.kind = RAD_TOK_BPE;
|
||||
vb.tokens = { "a", "<eos>", "<turn|>", "<|tool_response>", "</s>" };
|
||||
vb.types = { RAD_TT_NORMAL, RAD_TT_CONTROL, RAD_TT_CONTROL, RAD_TT_CONTROL, RAD_TT_CONTROL };
|
||||
vb.eos = 1;
|
||||
auto v = std::make_shared<Vocab>();
|
||||
CHECK_OK(v->load(std::move(vb)));
|
||||
CHECK(v->is_eog(1));
|
||||
CHECK(v->is_eog(2));
|
||||
CHECK(v->is_eog(3));
|
||||
CHECK(!v->is_eog(4));
|
||||
|
||||
VocabBuild plain;
|
||||
plain.kind = RAD_TOK_BPE;
|
||||
plain.tokens = { "a", "<eos>", "</s>" };
|
||||
plain.types = { RAD_TT_NORMAL, RAD_TT_CONTROL, RAD_TT_CONTROL };
|
||||
plain.eos = 1;
|
||||
auto w = std::make_shared<Vocab>();
|
||||
CHECK_OK(w->load(std::move(plain)));
|
||||
CHECK(w->is_eog(2));
|
||||
}
|
||||
|
||||
/* ================================================================== chain steps */
|
||||
|
||||
TEST(step_chain_units) {
|
||||
|
||||
+94
-1
@@ -1,4 +1,5 @@
|
||||
/* util_test.cpp -- core/util/rad_util.cpp: the bedrock every other translation unit links against.
|
||||
/* util_test.cpp -- core/util/rad_util.cpp, the bedrock every other translation unit links against, and
|
||||
* core/util/stallwatch.cpp, which reports where a phase that has gone quiet waits.
|
||||
*
|
||||
* WHY THIS FILE EXISTS. Nothing here is interesting on its own, and every one of these is small
|
||||
* enough to read and believe -- which is what leaves such code untested. The two that are not
|
||||
@@ -13,8 +14,15 @@
|
||||
#include "rad_test.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "util/stallwatch.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <mutex>
|
||||
#include <unistd.h>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
@@ -437,4 +445,89 @@ TEST(constraint_why_names_the_key_the_bound_and_what_was_there) {
|
||||
CHECK(miss.find("<absent>") != std::string::npos);
|
||||
}
|
||||
|
||||
/* ================================================================== StallWatch */
|
||||
|
||||
namespace {
|
||||
/* Everything written to stderr while `f` runs. */
|
||||
template <class F> std::string capture_stderr(F f) {
|
||||
std::fflush(stderr);
|
||||
char path[] = "/tmp/rad_util_test_XXXXXX";
|
||||
const int fd = mkstemp(path);
|
||||
const int saved = dup(2);
|
||||
dup2(fd, 2);
|
||||
f();
|
||||
std::fflush(stderr);
|
||||
dup2(saved, 2);
|
||||
close(saved);
|
||||
std::string out;
|
||||
if (FILE* r = std::fopen(path, "r")) {
|
||||
char buf[4096];
|
||||
size_t n;
|
||||
while ((n = std::fread(buf, 1, sizeof buf, r)) > 0) out.append(buf, n);
|
||||
std::fclose(r);
|
||||
}
|
||||
close(fd);
|
||||
unlink(path);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(a_syscall_line_names_the_call_and_a_kfd_ioctl_by_its_name) {
|
||||
CHECK_EQ(stall_decode_syscall("running"), std::string("running"));
|
||||
CHECK_EQ(stall_decode_syscall("-1 0x7ffd1000 0x7f0012345678"), std::string("not in a system call"));
|
||||
CHECK(stall_decode_syscall("202 0x1 0x80 0x0 0x0 0x0 0x0 0x7ffd1000 0x0").rfind("futex", 0) == 0);
|
||||
/* A file that will not open -- a FIFO with no writer, a hung network mount -- is named too. */
|
||||
CHECK(stall_decode_syscall("257 0xffffff9c 0x5600 0x0 0x0 0x0 0x0 0x7ffd1000 0x0").rfind("openat", 0) == 0);
|
||||
/* An ioctl names the file its descriptor is open on and, for the KFD, the request by name:
|
||||
* _IOWR('K', 0x16, 40 bytes) is ALLOC_MEMORY_OF_GPU. */
|
||||
const int fd = open("/dev/null", O_RDONLY);
|
||||
CHECK(fd >= 0);
|
||||
const unsigned long req = (3ul << 30) | (40ul << 16) | ((unsigned long)'K' << 8) | 0x16;
|
||||
const std::string k = stall_decode_syscall(fmt("16 0x%x 0x%lx 0x0 0x0 0x0 0x0 0x0 0x0", fd, req));
|
||||
CHECK(k.find("ioctl(/dev/null, AMDKFD_IOC_ALLOC_MEMORY_OF_GPU)") != std::string::npos);
|
||||
/* Another driver's request is spelt out rather than guessed at. */
|
||||
const unsigned long drm = (3ul << 30) | (32ul << 16) | ((unsigned long)'d' << 8) | 0x40;
|
||||
const std::string d = stall_decode_syscall(fmt("16 0x%x 0x%lx 0x0 0x0 0x0 0x0 0x0 0x0", fd, drm));
|
||||
CHECK(d.find("type 'd' number 0x40") != std::string::npos);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
/* Relative to the module's load base, the number addr2line takes, which is not the file offset
|
||||
* where the linker placed a segment elsewhere than its file position. */
|
||||
TEST(an_address_is_named_by_its_module_and_its_offset_from_the_load_base) {
|
||||
const uintptr_t a = (uintptr_t)&capture_stderr<void (*)()>;
|
||||
Dl_info di{};
|
||||
CHECK(dladdr((void*)a, &di) != 0);
|
||||
CHECK_EQ(stall_module_offset(a), fmt("util_test+0x%lx", (unsigned long)(a - (uintptr_t)di.dli_fbase)));
|
||||
}
|
||||
|
||||
/* A thread that waits on a lock with nothing logged is reported once the quiet has passed: what
|
||||
* it is in, and its stack through this binary's frames. */
|
||||
TEST(a_quiet_phase_names_the_wait_and_the_stack_of_the_thread_in_it) {
|
||||
const std::string out = capture_stderr([] {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
std::unique_lock<std::mutex> lk(mu);
|
||||
StallWatch w("probe", 300);
|
||||
cv.wait_for(lk, std::chrono::milliseconds(1600));
|
||||
});
|
||||
CHECK(out.find("probe: nothing has been logged for") != std::string::npos);
|
||||
CHECK(out.find("futex") != std::string::npos);
|
||||
CHECK(out.find("stack: ") != std::string::npos);
|
||||
CHECK(out.find("util_test+0x") != std::string::npos);
|
||||
}
|
||||
|
||||
/* A phase that keeps logging is not quiet, however long it runs. */
|
||||
TEST(a_phase_that_logs_is_never_reported) {
|
||||
const std::string out = capture_stderr([] {
|
||||
StallWatch w("probe", 400);
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
RAD_INFO("probe: step %d", i);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||
}
|
||||
});
|
||||
CHECK(out.find("nothing has been logged") == std::string::npos);
|
||||
CHECK(out.find("probe: step 11") != std::string::npos);
|
||||
}
|
||||
|
||||
RAD_TEST_MAIN()
|
||||
Reference in new issue
Block a user