Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+13 -4
View File
@@ -88,9 +88,18 @@ install(TARGETS rad-info rad-convert rad-kbench rad-tune rad-schemas rad-tokchec
# template, compared with the legacy parser in tests/legacy/. It shares that parser and the
# differential harness with tests/chatparse_test, so it is built only with the tests.
if(RAD_BUILD_TESTS)
add_executable(rad-chatparse rad_chatparse.cpp ${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp)
target_link_libraries(rad-chatparse PRIVATE rad_legacy_toolparse)
# Its --request mode loads the architecture plugin for the model's declared reply format, so it
# is a plugin host like rad_add_tool's tools: the whole of rad_core, with its symbols exported.
# The legacy parser's sources are compiled in rather than linked as rad_legacy_toolparse, which
# links rad_core without that feature.
add_executable(rad-chatparse rad_chatparse.cpp chatparse_serve.cpp
${CMAKE_CURRENT_SOURCE_DIR}/iface.cpp
${CMAKE_SOURCE_DIR}/tests/legacy/toolparse_legacy.cpp
${CMAKE_SOURCE_DIR}/tests/legacy/chatdiff.cpp)
target_link_libraries(rad-chatparse PRIVATE "$<LINK_LIBRARY:WHOLE_ARCHIVE,rad_core>")
target_include_directories(rad-chatparse PRIVATE ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/abi
${CMAKE_CURRENT_SOURCE_DIR})
set_target_properties(rad-chatparse PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tests/legacy)
set_target_properties(rad-chatparse PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin
ENABLE_EXPORTS ON)
endif()
+447
View File
@@ -0,0 +1,447 @@
/* chatparse_serve.cpp -- rad-chatparse's request mode: one chat request rendered and its replies
* parsed exactly as the server does it, offline, against a container's own vocabulary and the
* architecture plugin's declared reply format.
*
* rad-chatparse --request REQ.json --rad MODEL.rad [--override-chat-template T.jinja]
* [--chat-template-kwargs JSON] [--reasoning-format auto|none] [--home DIRS]
* [--no-plugin] [--reply FILE ...]
* rad-chatparse --render-raw T.jinja --context CTX.json
*
* --request goes through parse_chat_request with the server's own adapters (TokenizerBridge,
* ChatTemplateBridge, GrammarBridge), so the prompt is the one the server would tokenise, the
* grammar the one it would compile and the parser the one it would read the reply with. The
* template is the container's, or --override-chat-template's (trailing newlines stripped, as the
* engine does). The reply format is the architecture plugin's declaration when it makes one
* (rad_arch_chat_format, loaded from $RADIANCE_HOME / --home as the engine does), else the
* template's analysis; --no-plugin forces the latter.
*
* Each --reply is a file holding text the model generates after the prompt. It is tokenised with
* the container's tokenizer (control tokens as themselves), stopped at the first end-of-generation
* token, decoded token by token through the server's Detokenizer with the request's preserved
* tokens, and then read twice: whole, as the non-streaming answer (chat_completion_body), and
* piece by piece through ChatDeltaStream, as the SSE stream, whose chunks are reassembled the way
* an OpenAI client does. Both messages, both finish reasons and whether they agree are printed,
* and the request's tool-call grammar is run over the reply's tokens as the sampler masks them
* (lazy until its trigger; a whole-turn grammar first takes the generation prompt).
*
* --render-raw renders a template with an arbitrary JSON context (messages, tools, any variable)
* through the vendored jinja engine alone, for message shapes the OpenAI API cannot carry.
*
* Output is one JSON object on stdout. Exit status: 0, or 1 when the request is refused, a reply
* cannot be read, the streamed and non-streamed answers disagree, or the grammar refuses a token. */
#include "build/startup.h"
#include "format/radfile.h"
#include "iface.h"
#include "sample/gbnf.h"
#include "sample/grammar.h"
#include "server/adapters.h"
#include "server/oai.h"
#include "text/chatfmt.h"
#include "text/token_view.h"
#include "text/tokenizer.h"
#include "llama/common/chat.h"
#include "llama/common/jinja/runtime.h"
#include <nlohmann/json.hpp>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
using namespace rad;
using ojson = nlohmann::ordered_json;
namespace {
bool read_file(const std::string& p, std::string* out) {
std::ifstream f(p, std::ios::binary);
if (!f) return false;
std::ostringstream ss;
ss << f.rdbuf();
*out = ss.str();
return true;
}
int usage() {
std::fprintf(stderr,
"usage: rad-chatparse --request REQ.json --rad MODEL.rad [--override-chat-template T]\n"
" [--chat-template-kwargs JSON] [--reasoning-format auto|none]\n"
" [--home DIRS] [--no-plugin] [--reply FILE ...]\n"
" rad-chatparse --render-raw T.jinja --context CTX.json\n");
return 2;
}
/* The SSE chunks of one choice, reassembled as an OpenAI client does: content and reasoning
* concatenated, each tool call's name and arguments joined by its index. */
ojson reassemble(const std::string& sse, std::string* finish, int* chunks) {
ojson msg = { { "role", "assistant" }, { "content", "" } };
std::string reasoning;
std::vector<ojson> calls;
bool any_content = false;
size_t at = 0;
while (at < sse.size()) {
size_t nl = sse.find('\n', at);
if (nl == std::string::npos) nl = sse.size();
const std::string line = sse.substr(at, nl - at);
at = nl + 1;
if (line.rfind("data: ", 0) != 0) continue;
const std::string body = line.substr(6);
if (body == "[DONE]") continue;
const ojson j = ojson::parse(body, nullptr, false);
if (!j.is_object() || !j.contains("choices")) continue;
++*chunks;
for (const ojson& c : j.at("choices")) {
if (c.contains("finish_reason") && c.at("finish_reason").is_string())
*finish = c.at("finish_reason").get<std::string>();
if (!c.contains("delta")) continue;
const ojson& d = c.at("delta");
if (d.contains("content") && d.at("content").is_string()) {
msg["content"] = msg["content"].get<std::string>() + d.at("content").get<std::string>();
any_content = true;
}
if (d.contains("reasoning_content") && d.at("reasoning_content").is_string())
reasoning += d.at("reasoning_content").get<std::string>();
if (d.contains("tool_calls"))
for (const ojson& tc : d.at("tool_calls")) {
const size_t i = tc.value("index", (size_t)0);
while (calls.size() <= i)
calls.push_back({ { "type", "function" },
{ "function", { { "name", "" }, { "arguments", "" } } } });
if (tc.contains("id")) calls[i]["id"] = tc.at("id");
if (tc.contains("function")) {
const ojson& f = tc.at("function");
if (f.contains("name") && f.at("name").is_string())
calls[i]["function"]["name"] = calls[i]["function"]["name"].get<std::string>() +
f.at("name").get<std::string>();
if (f.contains("arguments") && f.at("arguments").is_string())
calls[i]["function"]["arguments"] =
calls[i]["function"]["arguments"].get<std::string>() +
f.at("arguments").get<std::string>();
}
}
}
}
if (!any_content) msg["content"] = nullptr;
if (!reasoning.empty()) msg["reasoning_content"] = reasoning;
if (!calls.empty()) msg["tool_calls"] = calls;
return msg;
}
/* What the two answers must agree on: content (null and "" alike), reasoning, and each call's
* name and arguments. Call ids are random per answer. */
ojson comparable(const ojson& m) {
ojson o;
o["content"] = m.contains("content") && m.at("content").is_string() ? m.at("content") : ojson("");
o["reasoning_content"] = m.value("reasoning_content", std::string());
ojson calls = ojson::array();
if (m.contains("tool_calls"))
for (const ojson& tc : m.at("tool_calls"))
calls.push_back({ tc.at("function").at("name"), tc.at("function").at("arguments") });
o["tool_calls"] = calls;
return o;
}
int render_raw(const std::string& tpath, const std::string& cpath) {
std::string src, ctxs;
if (!read_file(tpath, &src) || !read_file(cpath, &ctxs)) {
std::fprintf(stderr, "rad-chatparse: cannot read %s or %s\n", tpath.c_str(), cpath.c_str());
return 2;
}
while (!src.empty() && (src.back() == '\n' || src.back() == '\r')) src.pop_back();
const ojson ctx = ojson::parse(ctxs, nullptr, false);
if (!ctx.is_object()) {
std::fprintf(stderr, "rad-chatparse: %s is not a JSON object\n", cpath.c_str());
return 2;
}
ojson out;
try {
common_chat_template tmpl(src, ctx.value("bos_token", std::string()),
ctx.value("eos_token", std::string()));
jinja::context jc(tmpl.source());
jinja::global_from_json(jc, ctx, false);
jinja::runtime rt(jc);
const jinja::value res = rt.execute(tmpl.prog);
out["prompt"] = jinja::runtime::gather_string_parts(res)->as_string().str();
} catch (const std::exception& e) {
out["error"] = e.what();
}
std::printf("%s\n", out.dump(-1, ' ', false, ojson::error_handler_t::replace).c_str());
return out.contains("error") ? 1 : 0;
}
} /* namespace */
int serve_main(int argc, char** argv) {
std::string req_path, rad_path, tmpl_path, kwargs, rfmt = "auto", home, raw_tmpl, raw_ctx;
std::vector<std::string> replies;
bool plugin = true;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto val = [&](std::string* dst) {
if (i + 1 >= argc) return false;
*dst = argv[++i];
return true;
};
bool ok = true;
if (a == "--request") ok = val(&req_path);
else if (a == "--rad") ok = val(&rad_path);
else if (a == "--override-chat-template") ok = val(&tmpl_path);
else if (a == "--chat-template-kwargs") ok = val(&kwargs);
else if (a == "--reasoning-format") ok = val(&rfmt);
else if (a == "--home") ok = val(&home);
else if (a == "--no-plugin") plugin = false;
else if (a == "--reply") { std::string r; ok = val(&r); replies.push_back(r); }
else if (a == "--render-raw") ok = val(&raw_tmpl);
else if (a == "--context") ok = val(&raw_ctx);
else ok = false;
if (!ok) return usage();
}
if (!raw_tmpl.empty()) return raw_ctx.empty() ? usage() : render_raw(raw_tmpl, raw_ctx);
if (req_path.empty() || rad_path.empty()) return usage();
/* ---------------------------------------------------------------- the vocabulary, as
* Engine::load_vocab reads it out of a container */
RadFile f;
if (f.open(rad_path.c_str()) < 0) return 1;
VocabSection vs = f.vocab();
if (!vs) { std::fprintf(stderr, "rad-chatparse: %s has no vocabulary\n", rad_path.c_str()); return 1; }
VocabBuild vb;
if (vocab_deserialize(f.base(), (uint64_t)f.size(), vs.h, vb) < 0) return 1;
if (!tmpl_path.empty()) {
std::string t;
if (!read_file(tmpl_path, &t)) {
std::fprintf(stderr, "rad-chatparse: cannot read %s\n", tmpl_path.c_str());
return 1;
}
while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back();
vb.chat_template = t;
}
if (const char* ids = f.get_s("generation.eos_token_id", nullptr)) {
const char* q = ids;
while (*q) {
char* end = nullptr;
const long v = std::strtol(q, &end, 10);
if (end == q) break;
if (v >= 0 && v <= INT32_MAX) vb.eos_ids.push_back((int32_t)v);
q = end;
}
}
auto vocab = std::make_shared<Vocab>();
if (vocab->load(std::move(vb)) < 0) return 1;
/* ---------------------------------------------------------------- the reply format */
const RadChatFormat* declared = nullptr;
LoadedPlugins lp;
if (plugin) {
const RadFileHeader& h = f.header();
if (rad_tools_load_plugins(home.empty() ? rad_home() : home, rad_hierarchy_from_env(),
f.str(h.arch_id), f.str(h.quant), &lp) < 0) {
std::fprintf(stderr, "rad-chatparse: the architecture plugin did not load\n");
return 1;
}
RadModelMeta meta{};
meta.arch_id = f.str(h.arch_id);
declared = rad_tools_chat_format(lp, meta);
}
server::TokenizerBridge tok(vocab);
server::ChatTemplateBridge chat;
if (chat.init(*vocab, declared, lp.arch_plugin) < 0) return 1;
TokenView view;
if (view.init(vocab) < 0) return 1;
server::GrammarBridge grammar(&view);
server::OaiDeps d;
d.tok = &tok;
d.chat = &chat;
d.grammar = &grammar;
server::OaiLimits lim;
lim.reasoning_format = rfmt;
if (!kwargs.empty()) {
const ojson kw = ojson::parse(kwargs, nullptr, false);
if (!kw.is_object()) {
std::fprintf(stderr, "rad-chatparse: --chat-template-kwargs is not a JSON object\n");
return 2;
}
for (const auto& [k, v] : kw.items()) lim.default_template_kwargs[k] = v.dump();
}
/* What the template's analysis alone reads, beside whatever the plugin declares. */
ojson derived;
{
ChatFormat tf;
std::string refused, why;
const std::string bos = vocab->bos() >= 0 ? vocab->text(vocab->bos()) : std::string();
const std::string eos = vocab->eos() >= 0 ? vocab->text(vocab->eos()) : std::string();
if (chat_format_from_template(vocab->chat_template(), bos, eos, &tf, &refused, &why) < 0) {
derived["error"] = why;
} else {
derived["describe"] = chat_format_describe(tf);
derived["tools_refused"] = refused;
derived["fields"] = { { "section_open", tf.section_open }, { "section_close", tf.section_close },
{ "call_open", tf.call_open }, { "call_close", tf.call_close },
{ "name_prefix", tf.name_prefix }, { "name_suffix", tf.name_suffix },
{ "call_end", tf.call_end }, { "arg_prefix", tf.arg_prefix },
{ "arg_name_suffix", tf.arg_name_suffix },
{ "arg_value_prefix", tf.arg_value_prefix },
{ "arg_value_suffix", tf.arg_value_suffix },
{ "reasoning_open", tf.reasoning_open },
{ "reasoning_close", tf.reasoning_close } };
}
}
std::string body;
if (!read_file(req_path, &body)) {
std::fprintf(stderr, "rad-chatparse: cannot read %s\n", req_path.c_str());
return 1;
}
server::OaiRequest r;
server::ApiError err;
ojson out;
out["plugin"] = lp.arch_plugin;
out["declared_format"] = declared != nullptr;
out["tool_refusal"] = chat.tool_refusal();
out["template_analysis"] = derived;
if (server::parse_chat_request(body, d, lim, &r, &err) < 0) {
out["error"] = { { "status", err.status }, { "message", err.message }, { "param", err.param } };
std::printf("%s\n", out.dump(-1, ' ', false, ojson::error_handler_t::replace).c_str());
return 1;
}
r.id = "chatcmpl-check";
r.created = 1761500000;
out["prompt"] = r.prompts.empty() ? std::string() : r.prompts[0].text;
out["prompt_tokens"] = r.prompts.empty() ? 0 : r.prompts[0].tokens.size();
out["parse_tools"] = r.parse_tools;
out["preserved_tokens"] = r.preserved_tokens;
out["grammar_lazy"] = r.sp.grammar_lazy;
out["grammar_bytes"] = r.sp.grammar.size();
ojson trig = ojson::array();
for (const auto& t : r.sp.grammar_triggers) trig.push_back(t.value);
out["grammar_triggers"] = trig;
/* ---------------------------------------------------------------- the replies */
int bad = 0;
out["replies"] = ojson::array();
for (const std::string& rp : replies) {
ojson one;
one["file"] = rp;
std::string text;
if (!read_file(rp, &text)) {
one["error"] = "cannot read the file";
out["replies"].push_back(one);
++bad;
continue;
}
/* The model's tokens, up to the first end-of-generation one, which stops the request and
* is not decoded. */
std::vector<int32_t> ids = tok.encode(text, false, true);
size_t n = 0;
while (n < ids.size() && !vocab->is_eog(ids[n])) ++n;
one["tokens"] = n;
one["stopped_at_eog"] = n < ids.size();
/* The request's grammar, as the sampler runs it: every token of the reply must be in the
* mask when it is sampled, and the end of the turn admissible after the last. */
if (!r.sp.grammar.empty()) {
std::vector<std::string> words;
std::vector<int32_t> trig_tokens;
for (const auto& t : r.sp.grammar_triggers) {
std::vector<int32_t> tt;
view.tokenize_special(t.value, &tt);
if (tt.size() == 1) trig_tokens.push_back(tt[0]);
else words.push_back(t.value);
}
std::unique_ptr<GbnfGrammar> g;
std::string gerr;
ojson gj;
if (GbnfGrammar::create(r.sp.grammar, "root", &view, r.sp.grammar_lazy, words,
trig_tokens, &g, &gerr) < 0) {
gj["error"] = gerr;
++bad;
} else if (!r.sp.grammar_lazy && !r.sp.grammar_prefix.empty() &&
g->accept_str(r.sp.grammar_prefix) < 0) {
/* A grammar that is the whole turn starts at the generation prompt, which the
* sampler replays into it first (grammar.cpp, GrammarSpec::prefix). */
gj["error"] = "the generation prompt is not admitted";
++bad;
} else {
std::vector<uint32_t> mask((size_t)grammar_mask_words(view.n_tokens()));
int64_t refused = -1;
for (size_t i = 0; i < n && refused < 0; ++i) {
if (g->fill_mask(mask.data(), (int64_t)mask.size()) < 0 ||
!(mask[(size_t)ids[i] / 32] >> ((size_t)ids[i] % 32) & 1u) ||
g->accept_token(ids[i]) < 0)
refused = (int64_t)i;
}
gj["admitted"] = refused < 0;
if (refused >= 0) {
gj["refused_token"] = refused;
gj["refused_piece"] = vocab->text(ids[(size_t)refused]);
++bad;
}
/* A lazy grammar that never triggered constrains nothing, the end included. */
gj["triggered"] = !g->awaiting_trigger();
gj["end_admissible"] = refused < 0 && (g->awaiting_trigger() || g->complete());
}
one["grammar"] = gj;
}
Detokenizer dt(vocab, {}, /*render_special=*/false, r.preserved_tokens);
std::vector<std::string> pieces;
std::string all;
for (size_t i = 0; i < n; ++i) {
std::string p = dt.push(ids[i]);
if (!p.empty()) { all += p; pieces.push_back(std::move(p)); }
}
std::string tail = dt.flush();
if (!tail.empty()) { all += tail; pieces.push_back(std::move(tail)); }
one["decoded"] = all;
/* Non-streaming: the server's assembly (server.cpp, the chat branch). */
server::ChoiceOut c;
c.finish = server::Finish::Stop;
if (r.reply_parser) {
std::unique_ptr<server::IReplyReader> rd = r.reply_parser->open();
rd->feed(all, nullptr);
rd->finish(nullptr);
c.msg = rd->message();
const bool complete = r.parse_tools && server::calls_complete(c.msg);
if (complete) c.finish = server::Finish::ToolCalls;
if (c.msg.open_call) {
c.msg.content = rd->content_with_open_call(all);
c.msg.tool_calls.pop_back();
c.msg.open_call = false;
}
} else {
c.msg.content = all;
}
int k = 0;
for (auto& tc : c.msg.tool_calls) tc.id = "call_" + std::to_string(k++);
const ojson resp = ojson::parse(server::chat_completion_body(r, { c }, server::UsageOut()),
nullptr, false);
const ojson& ch = resp.at("choices").at(0);
one["message"] = ch.at("message");
one["finish_reason"] = ch.at("finish_reason");
/* Streaming: one push per decoded piece, as the server pushes per read. */
server::ChatDeltaStream st(r, 0, r.reply_parser.get());
std::string sse = st.first_chunk() + st.started();
for (const std::string& p : pieces) sse += st.push(p, false);
sse += st.final_chunk(server::Finish::Stop, server::TimingsOut(), server::UsageOut());
std::string sfin;
int chunks = 0;
const ojson smsg = reassemble(sse, &sfin, &chunks);
one["stream"] = { { "message", smsg }, { "finish_reason", sfin }, { "chunks", chunks },
{ "pieces", pieces.size() } };
const bool agree = comparable(smsg) == comparable(one["message"]) &&
sfin == one["finish_reason"].get<std::string>();
one["stream_agrees"] = agree;
if (!agree) ++bad;
out["replies"].push_back(one);
}
std::printf("%s\n", out.dump(-1, ' ', false, ojson::error_handler_t::replace).c_str());
return bad ? 1 : 0;
}
+2 -2
View File
@@ -61,8 +61,8 @@ const std::vector<TolRow> g_tol = {
* moves by whole code steps (see g_opd_tol). */
{ "gemm_nt_q_gated", "*", 3e-2 },
/* The m2xfp4 fold's k = 3 multipliers round the odd-mantissa magnitudes as r4d_m2xfp4.h
* documents, up to 2^-4.4 relative on a quarter of the weights (the selftest's own margin
* over the mxfp4 tolerance below). */
* documents, up to 2^-4.4 relative on a quarter of the weights; r4d_selftest holds these rows
* to the same 4e-2. */
{ "gemm_nt_q", "m2xfp4", 4e-2 },
{ "gemm_nt", "bf16", 8e-3 },
{ "gemm_nt", "f16", 4e-3 },
+25 -7
View File
@@ -154,13 +154,13 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6
add((uint32_t)RAD_F32, {M, (n + group - 1) / group});
}
else if (op == "gemm_nt_q") {
/* Block-scaled fp8 and mxfp4 only. `gemm_nt_q` covers six weight formats whose scale grids
* (per row, per row-group, per output-row-block, e8m0 exponents, zero points, reference
* exponents) belong to the reading kernel, not the schema. The fp8 grid is fixed by the
* checkpoint: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] scale plane, `group`
* being the 128. Other formats are skipped and counted.
*
* `a_sum` and `b_ref` belong to the asymmetric-integer and mxfp4 grids. */
/* Block-scaled fp8, mxfp4 and the 2-bit asymmetric grid, sized from each kernel's stored layout.
* `gemm_nt_q`'s scale grids belong to the reading kernel, not the schema. The fp8 grid is the
* checkpoint's: E4M3 [N][K] with a bf16 [ceil(N/128)][ceil(K/128)] scale plane, `group` 128.
* libref describes the symmetric integer grids, so a tool takes those from its hook; a grid
* with a zero point is declined there (ref_planes.h joins scale and zero into one operand).
* Anything else is skipped and counted. `a_sum` and `b_ref` belong to the asymmetric-integer
* and mxfp4 grids. */
const char* q = g.get_s("dtype");
/* OCP-MXFP4: e2m1 codes with one E8M0 exponent per 32 of K (`group` 32), against the fp8
* activation pair (E4M3 plus an f32 scale per row and 128 of K, as LinearFP8 feeds it).
@@ -175,6 +175,24 @@ int rad_operand_shapes(const std::string& op, const Geometry& g, int n_opd, int6
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
add((uint32_t)RAD_U8, {N}); /* b_ref -- the per-row reference */
} else if (q && std::strcmp(q, "w2a8") == 0) {
/* The DFlash2 draft head's grid (libr4d/r4d_gemm_w2a8_nt.hip): unsigned 2-bit codes in
* the kernel's fragment order, N*K/4 bytes (`r4d.w2a8.frag.g128`), and one dword per
* row and `group` of K holding that group's f16 scale and integer zero, tile-major,
* N*K/group of them (`r4d.w2a8.sz.g128`) -- both extents owned by
* libr4d/r4d_layout.cpp's r4d_rad_layout_w2a8, which is what sizes the real weight.
* The activation pair and the group sums are quant_act_i8's own outputs above, and the
* grid is asymmetric, so the kernel refuses the case without `a_sum`. `b_ref` is
* mxfp4's. Sizes are the stored bytes; random bytes suffice for timing. */
if (N <= 0 || K <= 0 || group != 128 || (K % 128) || (N % 16))
return RAD_E_UNSUPPORTED;
add((uint32_t)RAD_I8, {M, K}); /* a -- int8 codes */
add((uint32_t)RAD_F32, {M, 1}); /* a_scale -- one f32 per row */
add((uint32_t)RAD_U8, {N, K / 4}); /* b -- u2 codes, fragment order */
add((uint32_t)RAD_U32, {N, K / group}); /* b_scale -- scale+zero dwords */
add((uint32_t)RAD_BF16, {M, N}); /* y */
add((uint32_t)RAD_F32, {K / group, (M + 15) / 16 * 16}); /* a_sum, group-major */
skip_opd(); /* b_ref */
} else {
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
+10 -1
View File
@@ -30,7 +30,11 @@
* chunk JSON, and the tool-call grammar's accept_token / fill_mask), with every SSE event checked
* against nlohmann's serialisation.
*
* Exit status is non-zero when any reply breaks the contract or a verdict is not allowed. */
* Exit status is non-zero when any reply breaks the contract or a verdict is not allowed.
*
* With --request or --render-raw it instead renders one request and reads its replies the way the
* server does, against a container's vocabulary and its plugin's reply format
* (chatparse_serve.cpp). */
#include "chatdiff.h"
#include "iface.h"
#include "sample/grammar.h"
@@ -525,7 +529,12 @@ int breakdown(const Bench& b, const Tok& tk, const TokenView& view, int reps) {
} /* namespace */
int serve_main(int argc, char** argv); /* chatparse_serve.cpp */
int main(int argc, char** argv) {
for (int i = 1; i < argc; ++i)
if (!std::strcmp(argv[i], "--request") || !std::strcmp(argv[i], "--render-raw"))
return serve_main(argc, argv);
std::vector<std::pair<std::string, std::string>> want; /* model name, folder */
int fuzz = 300;
int reps = 5;
+398 -19
View File
@@ -25,6 +25,9 @@
#include "rad_plugin.h"
#include "rad_quant.h"
#include <dlfcn.h>
#include <nlohmann/json.hpp>
#include <sys/stat.h>
#ifdef _OPENMP
@@ -34,6 +37,7 @@
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <cstring>
@@ -41,6 +45,7 @@
#include <fstream>
#include <map>
#include <sstream>
#include <thread>
#include <unordered_set>
using namespace rad;
@@ -49,6 +54,203 @@ namespace {
bool file_exists(const std::string& p) { std::ifstream f(p); return (bool)f; }
/* clef (decision.type=clef): the head's geometry from joint_head_config.json beside the
* checkpoint, and its three learned scalars from the head's own tensors (joint_head.safetensors,
* merged with --add), into the header. The plugin declares the head from the geometry
* (arch/common/rad_block_clef.h) and the server applies the scalars (core/server/clef.h). */
int clef_metadata(const std::string& in, const std::string& config_dir, const Checkpoint& ck,
MetaOwn& meta) {
/* The head lives in the clef plugins, selected by the architecture id. A container that
* says decision.type=clef but keeps its qwen35 id would load the trunk alone and answer
* /v1/systemone from a head that never ran. */
if (meta.arch != "clef") {
RAD_ERR("%s: decision.type=clef needs the clef plugins: convert with --arch clef (the "
"container's architecture is '%s')", in.c_str(), meta.arch.c_str());
return -1;
}
std::string dir = config_dir;
if (dir.empty()) {
struct stat st{};
if (stat(in.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) dir = in;
else {
const size_t slash = in.find_last_of('/');
dir = slash == std::string::npos ? "." : in.substr(0, slash);
}
}
const std::string path = dir + "/joint_head_config.json";
std::ifstream f(path);
if (!f) {
RAD_ERR("%s: decision.type=clef needs the head's joint_head_config.json beside the "
"checkpoint (or under --config)", path.c_str());
return -1;
}
nlohmann::json c;
try { f >> c; } catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return -1;
}
for (const char* k : { "hidden_size", "width", "routing_layers", "layers", "heads", "feedforward" }) {
if (!c.contains(k) || !c[k].is_number_integer() || c[k].get<long long>() <= 0) {
RAD_ERR("%s: `%s` is missing or not a positive integer", path.c_str(), k);
return -1;
}
meta.set(std::string("decision.clef.") + k, std::to_string(c[k].get<long long>()));
}
for (const char* k : { "prior_logit_scale", "joint_logit_scale", "residual_gate" }) {
const SrcTensor* t = ck.find(k);
if (!t || !t->data || t->bytes < 2) {
RAD_ERR("the head's `%s` is not in the checkpoint: add joint_head.safetensors with "
"--add", k);
return -1;
}
float v = 0.0f;
if (t->rad_dtype == RAD_BF16) {
uint16_t h = 0;
std::memcpy(&h, t->data, 2);
const uint32_t u = (uint32_t)h << 16;
std::memcpy(&v, &u, 4);
} else if (t->rad_dtype == RAD_F32 && t->bytes >= 4) {
std::memcpy(&v, t->data, 4);
} else {
RAD_ERR("the head's `%s` is %s; bf16 or f32 is read", k, rad_dtype_name(t->rad_dtype));
return -1;
}
char s[32];
std::snprintf(s, sizeof s, "%.9g", (double)v);
meta.set(std::string("decision.clef.") + k, s);
}
RAD_INFO("clef head %s x %s, %s routing + %s decoder layers; scalars from the checkpoint",
meta.get("decision.clef.width"), meta.get("decision.clef.heads"),
meta.get("decision.clef.routing_layers"), meta.get("decision.clef.layers"));
return 0;
}
/* The rounding every Laya checkpoint needs: the release ships f16 (laya.train saves .half()), and
* the laya plugin reads its linears and tables in bf16, as the release computes them on a card.
* Norms and biases are declared f32, an exact widening of f16, so no rule names them. */
const char* const kLayaBf16 =
"token_embd.weight cast dtype=bf16\n"
"type_emb.weight cast dtype=bf16\n"
"scorer.fc1.weight cast dtype=bf16\n"
"scorer.fc2.weight cast dtype=bf16\n"
"blk.*.attn_qkv.weight cast dtype=bf16\n"
"blk.*.attn_out.weight cast dtype=bf16\n"
"blk.*.ffn_in_gate.weight cast dtype=bf16\n"
"blk.*.ffn_down.weight cast dtype=bf16\n"
"head.*.attn_qkv.weight cast dtype=bf16\n"
"head.*.attn_out.weight cast dtype=bf16\n"
"head.*.ffn_up.weight cast dtype=bf16\n"
"head.*.ffn_down.weight cast dtype=bf16\n";
/* Laya (a checkpoint whose config.json says model_type laya, or --set decision.type=laya): the
* release keeps its parts in folders, so the encoder's geometry comes from encoder/config.json,
* the head's settings from rl_agent_config.json and the vocabulary from tokenizer/. The plugin
* declares from the geometry (arch/laya); the server builds each question's sequence from the
* special tokens and lengths and applies the fitted temperatures (core/server/laya.h). */
int laya_metadata(const std::string& in, const std::string& config_dir, MetaOwn& meta,
std::string* tokjson) {
if (meta.arch != "laya") {
RAD_ERR("%s: decision.type=laya needs a Laya checkpoint directory, whose config.json says "
"model_type laya (this one's architecture is '%s')", in.c_str(), meta.arch.c_str());
return -1;
}
std::string dir = config_dir;
if (dir.empty()) {
struct stat st{};
if (stat(in.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) dir = in;
else {
const size_t slash = in.find_last_of('/');
dir = slash == std::string::npos ? "." : in.substr(0, slash);
}
}
auto read_json = [](const std::string& path, nlohmann::json* j) {
std::ifstream f(path);
if (!f) { RAD_ERR("%s: a Laya checkpoint carries it; cannot read it", path.c_str()); return -1; }
try { f >> *j; } catch (const std::exception& e) {
RAD_ERR("%s: %s", path.c_str(), e.what());
return -1;
}
return j->is_object() ? 0 : -1;
};
/* The encoder's own config: its geometry and free-form keys (layer_types, local_attention,
* the rotary thetas), keeping the checkpoint's model_type, which named the plugin. */
MetaOwn enc;
if (meta_from_config_json(dir + "/encoder", &enc) != RAD_OK) return -1;
for (size_t i = 0; i < enc.keys.size(); ++i)
if (enc.keys[i] != "model_type" && enc.keys[i] != "architectures") meta.set(enc.keys[i], enc.vals[i]);
meta.m = enc.m;
nlohmann::json rl;
if (read_json(dir + "/rl_agent_config.json", &rl) < 0) return -1;
const std::pair<const char*, long long> counts[] = { { "max_len", 1 }, { "head_max_len", 1 },
{ "head_layers", 0 } };
for (const auto& [k, least] : counts) {
if (!rl.contains(k) || !rl[k].is_number_integer() || rl[k].get<long long>() < least) {
RAD_ERR("%s/rl_agent_config.json: `%s` is missing or not a count", dir.c_str(), k);
return -1;
}
meta.set(std::string("decision.laya.") + k, std::to_string(rl[k].get<long long>()));
}
if (rl.contains("option_layout") && rl["option_layout"] != "sequential") {
RAD_ERR("%s/rl_agent_config.json: option_layout '%s'; the sequential layout every "
"published checkpoint uses is served", dir.c_str(), rl["option_layout"].dump().c_str());
return -1;
}
auto num = [](double v) { char s[32]; std::snprintf(s, sizeof s, "%.9g", v); return std::string(s); };
std::string temps = "1 1 1";
if (rl.contains("temperature")) {
const nlohmann::json& t = rl["temperature"];
if (!t.is_array() || t.size() != 3 || !t[0].is_number() || !t[1].is_number() || !t[2].is_number()) {
RAD_ERR("%s/rl_agent_config.json: `temperature` is not three numbers (choice, score, "
"noul)", dir.c_str());
return -1;
}
temps = num(t[0].get<double>()) + " " + num(t[1].get<double>()) + " " + num(t[2].get<double>());
}
meta.set("decision.laya.temperature", temps);
if (rl.contains("temperature_by_options") && rl["temperature_by_options"].is_object())
for (const auto& kv : rl["temperature_by_options"].items())
if (kv.value().is_number())
meta.set("decision.laya.temperature_by_options." + kv.key(), num(kv.value().get<double>()));
/* The special tokens by name (tokenizer_config.json), their ids from tokenizer.json. */
const std::string tdir = dir + "/tokenizer";
if (tokjson->empty()) *tokjson = tdir + "/tokenizer.json";
nlohmann::json tc, tj;
if (read_json(tdir + "/tokenizer_config.json", &tc) < 0 || read_json(*tokjson, &tj) < 0) return -1;
for (const char* which : { "cls_token", "sep_token", "mask_token" }) {
const nlohmann::json* v = tc.contains(which) ? &tc[which] : nullptr;
if (v && v->is_object() && v->contains("content")) v = &(*v)["content"];
if (!v || !v->is_string()) {
RAD_ERR("%s/tokenizer_config.json: no `%s`", tdir.c_str(), which);
return -1;
}
const std::string tok = v->get<std::string>();
long long id = -1;
if (tj.contains("added_tokens"))
for (const auto& a : tj["added_tokens"])
if (a.contains("content") && a["content"] == tok && a.contains("id")) id = a["id"].get<long long>();
if (id < 0 && tj.contains("model") && tj["model"].contains("vocab") && tj["model"]["vocab"].is_object() &&
tj["model"]["vocab"].contains(tok))
id = tj["model"]["vocab"][tok].get<long long>();
if (id < 0) {
RAD_ERR("%s: the %s '%s' is not in the vocabulary", tokjson->c_str(), which, tok.c_str());
return -1;
}
const std::string base = std::string(which).substr(0, std::strlen(which) - 6);
meta.set("decision.laya." + base, std::to_string(id));
if (base == "mask") meta.set("decision.laya.mask_token", tok);
}
meta.set("decision.type", "laya");
meta.finish();
RAD_INFO("laya %s: encoder %lld x %lld, head %s layers, max_len %s, head_max_len %s",
dir.c_str(), (long long)meta.m.n_layers, (long long)meta.m.n_embd,
meta.get("decision.laya.head_layers"), meta.get("decision.laya.max_len"),
meta.get("decision.laya.head_max_len"));
return 0;
}
/* `blk.12.attn_q.weight` -> 12; -1 for a model-level name (GGUF naming, as in an imatrix). */
int32_t layer_from_name(const std::string& n) {
if (n.rfind("blk.", 0) != 0) return -1;
@@ -131,6 +333,10 @@ void usage() {
" --imatrix F llama.cpp imatrix: the expert-popularity profile, the column\n"
" importances handed to each quantiser, and the weighting of the\n"
" error report\n"
" --chat-template F a jinja template baked as the container's chat template,\n"
" overriding the checkpoint's own (or its absence). A release that\n"
" ships none (DeepSeek's) needs one, or /v1/chat/completions answers\n"
" 501. Trailing newlines are stripped\n"
" --set K=V a metadata key, seen by declare AND written into the container,\n"
" so a convert-time choice that must also hold at serve time is\n"
" stated once. Repeatable\n"
@@ -146,17 +352,36 @@ void usage() {
" --max-spec N the max_spec declare is run at (default 4, or the block a\n"
" drafter states; a number given here is used as given); 0\n"
" leaves a draft head out\n"
" --reuse FILE a container converted earlier from the SAME checkpoint. A weight\n"
" --reuse FILE a container converted earlier from the SAME checkpoint (repeatable;\n"
" the first is searched first). A weight\n"
" it holds with the same encoding, quantiser, options and shape is\n"
" copied from it instead of quantised again\n"
" --changed FILE with --reuse: checkpoint tensors (one name a line) that differ from\n"
" the checkpoint the --reuse container was converted from. Every\n"
" weight that reads one is converted; the rest are copied\n"
" --lora FILE|DIR a PEFT adapter (.safetensors file or directory of them) merged\n"
" into the checkpoint tensors it names before they are converted:\n"
" W + strength * (alpha/r where the adapter states one) * B @ A.\n"
" Repeatable, merged in the order given; each merged tensor joins\n"
" the --changed set, so --reuse never copies an unmerged weight\n"
" --lora-strength F\n"
" the strength of every --lora (default 1)\n"
" --lora-map FILE with --lora: a JSON map for adapters trained on module names this\n"
" checkpoint does not use. {\"strip\": [\"prefix\", ...], \"modules\":\n"
" {\"<pat>\": [\"<target>\", ...]}}: a pattern holds at most one '*',\n"
" which matches one run (the block index) and is substituted into\n"
" every target; several targets mean the module is their concate-\n"
" nation (a fused qkv), and the adapter's rows split along them\n"
" in the order listed\n"
" --in-place with --reuse: EXTEND that container instead of writing a new one.\n"
" Its weights stay where they are; new ones are written past its\n"
" end and the header last. Refused when a weight it holds would\n"
" change or a new weight is an expert. <file>.pre-append keeps the\n"
" old header and length\n"
" --gpus LIST the cards (HIP device numbers, comma separated) the quantisers\n"
" may run on, and large weights then run two at a time. A\n"
" quantiser writes the same bytes on a card as on the host; with\n"
" no quantiser plugin that has a device path, refused\n"
" --plan-only declare, plan every weight's encoding, print the plan, and stop\n"
" before writing anything\n"
" --report N the worst N quantisation errors to print (default 20)\n"
@@ -186,7 +411,7 @@ int for_row_pieces(int64_t n, bool parallel, std::string* why, F fn) {
} /* namespace */
int main(int argc, char** argv) {
std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir;
std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir, chat_tmpl;
std::string tokjson2, config_dir;
std::vector<std::string> add_files;
std::vector<std::string> hierarchy = rad_hierarchy_from_env();
@@ -200,9 +425,14 @@ int main(int argc, char** argv) {
int report_n = 20;
bool verbose = false, plan_only = false, list_quant = false;
std::string reuse_path, changed_path;
std::vector<std::string> reuse_more; /* --reuse given again: more containers to copy from */
std::vector<std::string> lora_paths;
double lora_strength = 1.0;
std::string lora_map;
bool in_place = false;
int kv_dtype = RAD_DT_INVALID;
std::vector<std::pair<std::string, std::string>> set_kv;
std::vector<int> gpus; /* --gpus: the cards the quantisers may run on */
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
@@ -227,6 +457,7 @@ int main(int argc, char** argv) {
else if (a == "--add") add_files.push_back(next("--add"));
else if (a == "--config") config_dir = next("--config");
else if (a == "--imatrix") imat_path = next("--imatrix");
else if (a == "--chat-template") chat_tmpl = next("--chat-template");
else if (a == "--set") {
const std::string kv = next("--set");
const size_t eq = kv.find('=');
@@ -243,9 +474,29 @@ int main(int argc, char** argv) {
else if (a == "--draft-model") draft_dir = next("--draft-model");
else if (a == "--plan-only") plan_only = true;
else if (a == "--report") report_n = (int)num("--report", 0, INT32_MAX);
else if (a == "--reuse") reuse_path = next("--reuse");
else if (a == "--reuse") {
const std::string r = next("--reuse");
if (reuse_path.empty()) reuse_path = r;
else reuse_more.push_back(r);
}
else if (a == "--changed") changed_path = next("--changed");
else if (a == "--lora") lora_paths.push_back(next("--lora"));
else if (a == "--lora-strength") {
const char* v = next("--lora-strength");
char* end = nullptr;
lora_strength = std::strtod(v, &end);
if (!end || *end || end == v) {
std::fprintf(stderr, "rad-convert: --lora-strength wants a number, got '%s'\n",
v);
return 2;
}
}
else if (a == "--lora-map") lora_map = next("--lora-map");
else if (a == "--in-place") in_place = true;
else if (a == "--gpus") {
for (const std::string& d : rad_split_list(next("--gpus")))
gpus.push_back((int)rad_flag_int("rad-convert", "--gpus", d.c_str(), 0, 1023));
}
else if (a == "--kv-cache-dtype") {
const std::string v = next("--kv-cache-dtype");
if (v == "fp8") kv_dtype = RAD_F8E4M3;
@@ -303,6 +554,16 @@ int main(int argc, char** argv) {
"weight cannot be replaced in place)\n");
return 2;
}
if (!lora_paths.empty() && in_place) {
std::fprintf(stderr, "rad-convert: --lora merges into the source, whose weights "
"--in-place copies from --reuse unchanged; convert to a new file\n");
return 2;
}
if (!lora_map.empty() && lora_paths.empty()) {
std::fprintf(stderr, "rad-convert: --lora-map renames the modules --lora merges; give "
"a --lora to go with it\n");
return 2;
}
if (in_place) {
if (reuse_path.empty()) {
std::fprintf(stderr, "rad-convert: --in-place extends the container --reuse names\n");
@@ -344,7 +605,16 @@ int main(int argc, char** argv) {
/* ---------------------------------------------------------------- source */
Checkpoint ck;
if (!config_dir.empty()) ck.set_meta_dir(config_dir);
/* A Laya checkpoint as laya's own loader downloads it carries no config.json of its own, only
* encoder/config.json beside rl_agent_config.json: the geometry is the encoder's, the
* architecture laya (laya_metadata reads the rest). */
struct stat in_st{};
const bool laya_dir = config_dir.empty() && stat(in.c_str(), &in_st) == 0 && S_ISDIR(in_st.st_mode) &&
!file_exists(in + "/config.json") && file_exists(in + "/rl_agent_config.json") &&
file_exists(in + "/encoder/config.json");
if (laya_dir) ck.set_meta_dir(in + "/encoder");
if (ck.open(in) < 0) return 1;
if (laya_dir) ck.meta().arch = "laya";
for (const std::string& f : add_files) {
if (ck.add_file(f) < 0) return 1;
RAD_INFO("added %s", f.c_str());
@@ -362,6 +632,22 @@ int main(int argc, char** argv) {
* and in the engine both read RadModelMeta from the container header, so the value holds for
* both. */
for (const auto& kv : set_kv) meta.set(kv.first, kv.second);
if (const char* dt = meta.get("decision.type"); dt && !std::strcmp(dt, "clef") &&
clef_metadata(in, config_dir, ck, meta) < 0)
return 1;
if (const char* dt = meta.get("decision.type");
(meta.arch == "laya" || (dt && !std::strcmp(dt, "laya"))) &&
laya_metadata(in, config_dir, meta, &tokjson) < 0)
return 1;
/* f16 to bf16 rounds, so it is a recipe's rule (spec §4.4). Every Laya checkpoint needs the same
* rules, so they follow any the caller gave, and the container records them with the rest. */
if (meta.arch == "laya") {
std::string why;
if (recipe.add_text(kLayaBf16, "laya's f16 to bf16 (built in)", &why) < 0) {
RAD_ERR("%s", why.c_str());
return 1;
}
}
/* The quantisation descriptor (which selects the plugin pair) is derived from
* quantization_config, so a --set of it re-derives the descriptor. E.g. a bf16 checkpoint
* whose recipe writes Qwen's block fp8 targets qwen35_fp8 by setting what that release
@@ -376,6 +662,17 @@ int main(int argc, char** argv) {
/* The --reuse container, read with pread, never through its mapping. */
RadFile reuse;
if (!reuse_path.empty() && reuse.open(reuse_path.c_str()) != RAD_OK) return 1;
/* Further --reuse containers supply only weights the first lacks or holds converted otherwise:
* a container assembled from several converts (a mixed-precision recipe). */
std::deque<RadFile> reuse_extra;
if (!reuse_more.empty() && in_place) {
std::fprintf(stderr, "rad-convert: --in-place extends one container; give --reuse once\n");
return 2;
}
for (const std::string& r : reuse_more) {
reuse_extra.emplace_back();
if (reuse_extra.back().open(r.c_str()) != RAD_OK) return 1;
}
/* --changed lists the checkpoint tensors that differ from the --reuse container's source
* (e.g. a partial fine-tune). --reuse matches on how a weight was converted, not on its
* source bytes, so without the list it would copy the stale weights. */
@@ -395,6 +692,15 @@ int main(int argc, char** argv) {
return 1;
}
}
/* Adapters merge before anything reads the source, and a merged tensor joins the changed set:
* --reuse matches a weight by how it was converted, not by its source bytes. */
for (const std::string& lp : lora_paths) {
std::vector<std::string> merged;
if (ck.add_lora(lp, lora_strength, &merged,
lora_map.empty() ? nullptr : &lora_map) < 0)
return 1;
for (std::string& m : merged) changed.insert(std::move(m));
}
/* --in-place inherits the container's radiance.* keys (the convert-time choices its weights
* were made under), except `radiance.encoder`, which this run derives. */
int inherited = 0;
@@ -438,13 +744,37 @@ int main(int argc, char** argv) {
"recipe is checked against");
return 1;
}
/* An imported quantisation is recorded as the descriptor of the plugin serving it; the engine
* selects by exact match, and each weight states its own encoding. */
if (imported) {
/* An imported quantisation, or block fp8 served by a family that claims no descriptor for it,
* is recorded as the descriptor of the plugin serving it; the engine selects by exact match,
* and each weight states its own encoding. */
if (!plugins.arch_plugin.empty() && plugins.arch_quant != meta.quant) {
meta.quant = plugins.arch_quant;
meta.finish();
}
Registry& reg = rad_tools_registry();
if (!gpus.empty()) {
/* Every quantiser plugin that runs on a card is handed the list (rad_quant.h,
* RadQuantDevicesFn); a plugin without the hook stays on the host. */
int taken = 0;
for (const Plugin& p : reg.plugins()) {
if (p.kind != RAD_PLUGIN_QUANT || !p.handle) continue;
const auto fn = (RadQuantDevicesFn)dlsym(p.handle, "rad_quant_devices");
if (!fn) continue;
const int st = fn(gpus.data(), (int)gpus.size());
if (st == RAD_E_UNSUPPORTED) continue;
if (st < 0) {
RAD_ERR("--gpus: quantiser plugin '%s' refuses the list: %s", p.name.c_str(),
rad_strerror(st));
return 2;
}
++taken;
}
if (!taken) {
RAD_ERR("--gpus: no quantiser plugin loaded here has a device path (a build without "
"ROCm has none)");
return 2;
}
}
std::deque<CompiledRule> compiled;
std::map<const RecipeRule*, const CompiledRule*> by_rule;
std::map<const RecipeRule*, ImportForm> import_forms;
@@ -540,8 +870,10 @@ int main(int argc, char** argv) {
const RadQuantWeight qw = quant_weight(L, nullptr);
const int st = L.rule->q->encoding(L.rule->params.data(), (int)L.rule->params.size(),
&qw, &L.enc);
if (st == RAD_E_UNSUPPORTED && (L.src.trivial || L.src.imported)) {
/* declined (e.g. a norm under a matrix pattern): keep as is */
if (st == RAD_E_UNSUPPORTED &&
(L.src.trivial || (L.src.imported && !L.src.ggml_blocks))) {
/* declined (e.g. a norm under a matrix pattern): keep as is. Not a GGUF block
* tensor: keeping its planes would hide that the rule did not apply. */
L.rule = nullptr;
L.enc = L.src.enc;
} else if (st != RAD_OK) {
@@ -788,8 +1120,8 @@ int main(int argc, char** argv) {
*
* Small weights run one per thread, in plan order (roughly file order); nested parallelism is
* off, so a quantiser's OpenMP region stays on its calling thread. Large weights (n-gram
* table, lm_head, attention linears) run afterwards one at a time, with decode, quantise and
* error each parallel over rows. */
* table, lm_head, attention linears) run afterwards one at a time (two with --gpus), with
* decode, quantise and error each parallel over rows. */
#ifdef _OPENMP
omp_set_max_active_levels(1);
#endif
@@ -799,7 +1131,8 @@ int main(int argc, char** argv) {
struct Job {
Logical* L = nullptr;
int64_t idx = -1;
const RadFileEntry* re = nullptr; /* copied from the --reuse container */
const RadFileEntry* re = nullptr; /* copied from a --reuse container */
RadFile* rf = nullptr; /* that container */
int64_t bytes = 0; /* its planes */
};
std::vector<Job> jobs;
@@ -863,9 +1196,23 @@ int main(int argc, char** argv) {
}
if (!same) re = nullptr;
}
RadFile* rf = re ? &reuse : nullptr;
for (size_t x = 0; !re && !reads_changed && x < reuse_extra.size(); ++x) {
RadFile& R = reuse_extra[x];
const RadFileEntry* e = R.find(ww.name);
if (!e) continue;
const bool expert = ww.expert >= 0 || e->expert >= 0;
bool same = rad_enc_equal(&R.encoding(*e), &ww.enc) && ww.quantizer == R.str(e->quantizer) &&
ww.options == R.str(e->options) && e->rank == ww.rank &&
(!expert || (e->layer == ww.layer && e->expert == ww.expert &&
e->slot == ww.slot));
for (uint32_t i = 0; same && i < RAD_MAX_RANK; ++i)
if (e->shape[i] != ww.shape[i]) same = false;
if (same) { re = e; rf = &R; }
}
const int64_t idx = w.add_weight(ww);
if (idx < 0) { w.abort(); return 1; }
jobs.push_back(Job{ Lp, idx, re, plane_total });
jobs.push_back(Job{ Lp, idx, re, rf, plane_total });
}
/* A --changed name no weight reads is a typo or an unconverted tensor; refuse it. */
if (!changed.empty()) {
@@ -874,7 +1221,8 @@ int main(int argc, char** argv) {
if (!changed_read.count(n)) unread.push_back(n);
if (!unread.empty()) {
std::sort(unread.begin(), unread.end());
RAD_ERR("--changed names %zu tensor(s) no weight of this conversion reads, e.g. '%s'",
RAD_ERR("the changed set (--changed and merged adapters) names %zu tensor(s) no "
"weight of this conversion reads, e.g. '%s'",
unread.size(), unread[0].c_str());
w.abort();
return 1;
@@ -915,6 +1263,12 @@ int main(int argc, char** argv) {
w.abort();
return 1;
}
/* The operator's template replaces whatever the checkpoint carried (or lacked), so a release
* that ships none still bakes a container that serves /v1/chat/completions. */
if (!chat_tmpl.empty() && read_chat_template_path(chat_tmpl.c_str(), vb) < 0) {
w.abort();
return 1;
}
/* Serialised at section offset 0; finish() rebases once the string blob is sized. */
std::vector<uint8_t> vocab_blob;
if (vocab_serialize(vb, sink, 0, vocab_blob) < 0) { w.abort(); return 1; }
@@ -988,15 +1342,15 @@ int main(int argc, char** argv) {
if (j.re) {
for (int k = 0; k < L.enc.n_planes; ++k) {
const RadFilePlane& fp = reuse.plane(*j.re, k);
const RadFilePlane& fp = j.rf->plane(*j.re, k);
for (int64_t off = 0; off < (int64_t)fp.bytes; off += kChunk) {
const int64_t n = std::min<int64_t>(kChunk, (int64_t)fp.bytes - off);
stage.resize((size_t)n);
if (reuse.read_at(stage.data(), n, (int64_t)fp.offset + off) != RAD_OK ||
if (j.rf->read_at(stage.data(), n, (int64_t)fp.offset + off) != RAD_OK ||
w.write_plane(idx, k, off, stage.data(), n) != RAD_OK)
return RAD_E_IO;
}
reuse.drop_range((int64_t)fp.offset, (int64_t)fp.bytes);
j.rf->drop_range((int64_t)fp.offset, (int64_t)fp.bytes);
}
written += j.bytes;
reused += j.bytes;
@@ -1017,11 +1371,18 @@ int main(int argc, char** argv) {
/* An imported weight is re-laid row by row (ckpt_plane_rows); its bytes are not
* the plane's. */
if (!L.src.imported && (L.src.concat_dim == 0 || src.size() == 1)) {
/* Pieces that share one scale tensor (shards under `X.weight_scale`) have
* that one plane, written once. */
const bool shared = k > 0 && std::all_of(src.begin(), src.end(),
[&](const SrcTensor* s) {
return s == src[0];
});
int64_t off = 0;
for (const SrcTensor* s : src) {
if (w.write_plane(idx, k, off, s->data, s->bytes) != RAD_OK)
return RAD_E_IO;
off += s->bytes;
if (shared) break;
}
if (off != pb) {
RAD_ERR("'%s': its sources hold %lld bytes of plane '%s' and the "
@@ -1141,9 +1502,27 @@ int main(int argc, char** argv) {
failed.compare_exchange_strong(ok, st);
}
}
for (size_t i = 0; i < large.size() && failed.load() == RAD_OK; ++i) {
const int st = run_job(jobs[large[i]]);
if (st < 0) failed = st;
{
/* With the quantisers on cards (--gpus), large weights run two at a time, so one's host
* work (its rows read, its Hessian factored, its error measured) overlaps the other's on
* the card. Each runs on a thread of its own, whose OpenMP regions get a full team. */
std::atomic<size_t> next{0};
auto worker = [&] {
for (size_t i; failed.load() == RAD_OK && (i = next.fetch_add(1)) < large.size();) {
const int st = run_job(jobs[large[i]]);
if (st < 0) {
int ok = RAD_OK;
failed.compare_exchange_strong(ok, st);
}
}
};
if (gpus.empty()) {
worker();
} else {
std::thread side(worker);
worker();
side.join();
}
}
if (failed.load() != RAD_OK) { w.abort(); return 1; }
RAD_INFO("weights %zu written in %.0f s: %zu a thread each, %zu across every thread",
+34 -116
View File
@@ -358,12 +358,25 @@ int write_report(const std::string& path, const std::vector<Row>& rows,
std::string s;
s += "# radiance kernel libraries\n\n";
s += "Generated by `rad-kbench`. Every kernel of every loaded library ran on the same "
"inputs" + (benched ? std::string(" and each\ncase that passed was timed in the same "
"run, so correctness, completeness and speed come from "
"one run\n(the Speed section says how the times were "
"taken).\n\n")
: std::string(";\nnothing was timed (`--bench` was not given).\n\n"));
/* The header claims only what this pass measured: its counts are the ones the *Rows nothing
* ran* section prints below, and "every kernel ran" only when no declared row went
* unreached. */
size_t declared_rows = 0, reached_rows = 0;
for (const LibRow& l : libs) { declared_rows += l.rows.size(); reached_rows += l.ran.size(); }
const bool all_ran = reached_rows == declared_rows;
s += "Generated by `rad-kbench`. " +
(all_ran
? std::string("Every kernel of every loaded library ran on the same inputs")
: fmt("%zu of %zu declared kernel rows ran on the same inputs", reached_rows,
declared_rows)) +
(benched ? std::string(" and each\ncase that passed was timed in the same "
"run, so correctness, completeness and speed come from "
"one run\n(the Speed section says how the times were "
"taken).\n\n")
: std::string(";\nnothing was timed (`--bench` was not given).\n\n"));
if (!all_ran)
s += "Rows no case in this pass reached are listed under *Rows nothing ran*; a row "
"there is a gap in\ncoverage, not a failing kernel.\n\n";
s += "- " + provenance + "\n";
if (!arch_plugin.empty()) s += "- architecture plugin: `" + arch_plugin + "`\n";
s += "- libraries: `" + libraries + "`\n";
@@ -1907,104 +1920,15 @@ int Replay::rerecord() {
return 0;
}
/* The gemm_nt_q mx/m2 family, re-encoded for a row the recording's container never fed: the
* m2xfp4 rows sit at the m2xfp4 encoding, which no in-tree container carries, and the OCP rows'
* mxfp4a8 cases exist only at containers this fixture was not recorded from. Moving a case
* between the two families keeps the codes and exponent planes -- the same planes at both -- and
* draws the meta plane beside them, whose every byte is a valid multiplier, so the reference
* records at the row's own encoding. `d` already carries the reference's description of the
* operand at the target dtype (`sh`); this fills its encoding and selection. False when the row
* is not after one of the two families, the base encoding is the same family or neither, or the
* planes do not line up: the caller's strict shape check then governs. */
static bool reencode_gemmx_weight(const KfOperand& b, const char* row_dtype, const OpdShape& sh,
KfOperand* d, std::string* why) {
if (!b.has_enc || !row_dtype) return false;
const bool to_m2 = std::strcmp(row_dtype, "m2xfp4") == 0;
const bool to_mx = std::strcmp(row_dtype, "mxfp4a8") == 0;
if (!to_m2 && !to_mx) return false;
auto bad = [&](const char* w) { if (why) *why = w; return false; };
/* The base family: the m2xfp4 quantiser's own scheme, or affine MXFP4 (codes plus one E8M0
* exponent a group of 32). */
const RadEncoding& e = b.enc;
const bool base_m2 = rad_enc_is(&e, "m2xfp4") && e.n_planes == 3;
const bool base_mx = rad_enc_is(&e, "affine") && e.n_planes >= 2;
if (base_m2 == base_mx) return bad("its weight is neither the mxfp4a8 nor the m2xfp4 grid");
if (to_m2 && base_m2) return false; /* same family: the plain copy serves */
if (to_mx && base_mx) return false;
const int ic = 0;
const int is = rad_enc_find(&e, "scale");
const int im = base_m2 ? rad_enc_find(&e, "meta") : -1;
if (is < 0 || (base_m2 && im < 0)) return bad("its encoding has no exponent (or meta) plane");
if (e.transform[0]) return bad("its weight carries a transform the target family does not");
if (e.plane[ic].dtype != RAD_FP4E2M1 || e.plane[ic].block[0] != 1 ||
e.plane[is].block[0] != 1 || e.plane[is].block[1] != 32 ||
std::strncmp(e.plane[ic].role, "codes", RAD_ENC_STR) != 0)
return bad("its codes and exponent planes are not the MXFP4 grid's");
/* The target encoding: the same codes and exponents, the meta plane beside them. */
RadEncoding t{};
rad_enc_copy_str(t.scheme, to_m2 ? "m2xfp4" : "affine");
rad_enc_add_plane(&t, "codes", RAD_FP4E2M1, 1, 1);
rad_enc_add_plane(&t, "scale", RAD_E8M0, 1, 32);
if (to_m2) rad_enc_add_plane(&t, "meta", RAD_U8, 1, 32);
if (!rad_enc_valid(&t)) return bad("the re-encoded weight is not well formed");
/* What this operand reads, by the planes it selected: the weight (the codes, and the meta at
* m2) or a scale stream (b_scale and b_ref select the exponent plane). Its extents come from
* the plane it selected, in that plane's own elements. */
const bool codes_opd = std::find(b.sel.begin(), b.sel.end(), ic) != b.sel.end();
int64_t N = 0, kb = 0;
for (size_t k = 0; k < b.sel.size(); ++k) {
if (b.sel[k] == ic) { N = b.sel_rows[k]; kb = b.sel_cols[k] / 32; }
if (b.sel[k] == is) { N = b.sel_rows[k]; kb = b.sel_cols[k]; }
}
if (N <= 0 || kb <= 0) return bad("its planes are not a whole number of exponent groups");
const int64_t K = kb * 32;
auto fits = [&](const char* what, uint32_t dt, std::initializer_list<int64_t> shape) {
if (sh.dtype != dt || sh.shape != std::vector<int64_t>(shape)) {
if (why)
*why = std::string("the reference describes ") + what + " differently than the " +
(to_m2 ? "m2xfp4" : "mxfp4a8") + " grid implies";
return false;
}
return true;
};
std::vector<int> sel;
std::vector<int64_t> sel_rows, sel_cols;
if (codes_opd) {
if (to_m2) {
if (!fits("the weight", RAD_U8, { N * (K / 2 + kb) })) return false;
sel = { 0, 2 }; sel_rows = { N, N }; sel_cols = { K, kb };
} else {
if (!fits("the weight", RAD_FP4E2M1, { N, K })) return false;
sel = { 0 }; sel_rows = { N }; sel_cols = { K };
}
} else {
if (!fits("the scale stream", RAD_E8M0, { N, kb })) return false;
sel = { 1 }; sel_rows = { N }; sel_cols = { kb };
}
d->has_enc = true;
d->enc = t;
d->sel = std::move(sel);
d->sel_rows = std::move(sel_rows);
d->sel_cols = std::move(sel_cols);
return true;
}
/* ================================================================== the row-driven fixture
*
* A recording reaches only the rows its container's geometry selects; a row behind another band,
* tuned point or dtype never runs. For every row of every library under test, this moves the
* fixtures' cases into the row's constraints (kb::satisfy_constraints) and records the reference's
* answer at every distinct geometry that lands there -- one case serves every row sharing it, and
* a row keeps sweeping instead of stopping at the first base case, so a band's whole M ladder is
* covered. Only cases whose operand shapes the reference can describe from the parameters alone,
* and whose weights keep their shapes (or re-encode, above), are moved: a weight of another shape
* would need an encoding the base case does not carry. Replay the result with --all-rows, since a
* row a higher-priority row shadows is reached only that way. No container and no card are
* needed. */
* tuned point or dtype never runs. For every row of every library under test, this moves an
* existing case of the row's op into the row's constraints (kb::satisfy_constraints) and records
* the reference's answer there. Only cases whose operand shapes the reference can describe from the
* parameters alone, and whose weights keep their shapes, are moved: a weight of another shape would
* need an encoding the base case does not carry. Replay the result with --all-rows, since a row
* a higher-priority row shadows is reached only that way. No container and no card are needed. */
int Replay::record_rows() {
Kfixture out;
out.oracle = ref_name_;
@@ -2012,7 +1936,7 @@ int Replay::record_rows() {
for (size_t fi = 0; fi < fx_.size(); ++fi)
out.source += (out.source.empty() ? "rows from " : " + ") + fx_[fi].source;
std::set<std::string> seen;
int rows_total = 0, rows_served = 0, rows_recorded = 0;
int rows_total = 0, rows_recorded = 0;
std::map<std::string, int> why_not;
for (const KernelRow& r : reg_->rows()) {
if (!r.info || !r.info->launch || !r.info->op) continue;
@@ -2028,9 +1952,10 @@ int Replay::record_rows() {
if (!schema) continue;
++rows_total;
std::string last = "no recorded case of its op";
bool any = false;
for (size_t fi = 0; fi < fx_.size(); ++fi) {
bool done = false;
for (size_t fi = 0; fi < fx_.size() && !done; ++fi) {
for (const KfCase& base : fx_[fi].cases) {
if (done) break;
if (base.op != r.info->op || (int)base.opd.size() != schema->n_operands) continue;
Geometry g = case_geometry(base);
if (!kb::satisfy_constraints(r.info, &g)) {
@@ -2074,12 +1999,6 @@ int Replay::record_rows() {
d.idx_const = sh[k].idx_const;
d.fill_chunk = sh[k].fill_chunk;
if (d.role == RAD_OPD_WEIGHT || d.role == RAD_OPD_WTAB) {
/* The mx/m2 pair re-encodes between families; everything else must keep
* the weight the base case recorded. */
std::string rwhy;
if (!d.absent && b.has_enc &&
reencode_gemmx_weight(b, g.get_s("dtype"), sh[k], &d, &rwhy))
continue;
if (d.absent != b.absent || d.dtype != b.dtype || d.shape != b.shape) {
weights_kept = false;
break;
@@ -2109,18 +2028,17 @@ int Replay::record_rows() {
}
c.seed = rad_case_seed(base.seed, r.info->name, 0, r.info->domain, 0);
const std::string key = kb::cap_key(c, "", "", 0, g);
if (seen.count(key)) { any = true; continue; }
if (seen.count(key)) { done = true; ++rows_recorded; break; }
KfCase rc;
std::string why;
if (record_case(c, &rc, &why) != RAD_OK) { last = why; continue; }
seen.insert(key);
out.cases.push_back(std::move(rc));
++rows_recorded;
any = true;
done = true;
}
}
if (any) ++rows_served;
else why_not[std::string(r.plugin) + "/" + r.info->name + " (" + last + ")"]++;
if (!done) why_not[std::string(r.plugin) + "/" + r.info->name + " (" + last + ")"]++;
}
if (!why_not.empty()) {
std::printf("rows without a case\n");
@@ -2131,8 +2049,8 @@ int Replay::record_rows() {
RAD_ERR("--record-rows %s: %s", o_.record_rows_path.c_str(), rad_strerror(rc));
return 1;
}
std::printf("recorded %zu case(s) reaching %d of %d row(s) to %s; replay it with --all-rows\n",
out.cases.size(), rows_served, rows_total, o_.record_rows_path.c_str());
std::printf("recorded %zu case(s) for %d of %d row(s) to %s; replay it with --all-rows\n",
out.cases.size(), rows_recorded, rows_total, o_.record_rows_path.c_str());
return 0;
}
+308 -102
View File
@@ -45,8 +45,14 @@ void usage() {
" --iters N launches per rep (default 32). One launch is short enough that\n"
" launch overhead and clock ramp would otherwise dominate.\n"
" --max-tok N the max_tok declare is run at (default 8192)\n"
" --max-seqs N the max_seqs declare is run at (default 256)\n"
" --tp N tensor-parallel width to declare at (default 1). The shapes a\n"
" sharded deployment runs are not the shapes tp=1 runs.\n"
" --kv-cache-dtype T bf16 (default) or fp8 -- attention bands are gated on it.\n"
" Declare what the served engine runs, or the tune rows will not\n"
" match the bands it selects.\n"
" --tp-wire MODE exact (default) or wht6 -- selects the all-reduce family.\n"
" --tp-wire-min-kb N the message size from which the lossy wire is used.\n"
" --num-speculative-tokens N|auto\n"
" draft depth to declare at (default auto: the container's own). It puts\n"
" the drafter's kernels in the measured graph.\n"
@@ -55,9 +61,16 @@ void usage() {
" -h, --help\n");
}
/* A device allocation that frees itself, because the timing path has several ways out. */
/* A device allocation that frees itself, because the timing path has several ways out. Neither
* copyable nor movable: a rank holds a vector of these, and a second handle to the same
* allocation would free the buffer out from under a launch still reading it. */
struct DevBuf {
void* p = nullptr;
DevBuf() = default;
DevBuf(const DevBuf&) = delete;
DevBuf& operator=(const DevBuf&) = delete;
DevBuf(DevBuf&&) = delete;
DevBuf& operator=(DevBuf&&) = delete;
~DevBuf() { if (p) rad_dev_free(p, RAD_MEM_DEVICE); }
};
@@ -121,37 +134,110 @@ tune_candidates(const RadKernelInfo* k, const Geometry& g, int64_t* space_size,
return out;
}
/* Every OUT and INOUT operand's bytes after one launch at `g`, which carries the candidate point as
* ordinary parameters. Used to compare a candidate with the defaults. */
int capture_outputs(const KernelRow& row, std::vector<RadTensor>& t,
const Geometry& g, const RadOpSchema* schema,
const std::vector<OpdShape>& sh, RadStream stream,
std::vector<uint8_t>* out) {
RadArgs a{};
a.t = t.data(); a.n_t = (int)t.size();
a.p = g.params(); a.n_p = g.n_params();
a.rank = 0; a.world_size = 1;
DevBuf scratch;
if (row.info->scratch) {
const int64_t need = row.info->scratch(&a);
if (need > 0) {
scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE);
if (!scratch.p) return RAD_E_NOMEM;
rad_memset_async(scratch.p, 0, need, stream);
a.scratch = scratch.p;
a.scratch_bytes = need;
}
}
if (row.info->launch(&a, stream) < 0) return RAD_E_SHAPE;
if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE;
/* One rank's side of one candidate's launch: the instance its declare made, its operands on its
* card, its scratch and its stream. A plain row has one; a collective has one per rank, fired
* together, since a rank launching alone waits for a peer flag nobody raises. The instance is the
* only route to the peer bundle (scratch, flags, sequence counters) init() builds, so a
* collective cannot launch without it. */
struct Rank {
int rank = 0, world = 1;
void* instance = nullptr;
RadStream stream = nullptr; /* owned by the request's StreamSet */
std::vector<RadTensor> t; /* the operands, as the kernel sees them */
std::vector<DevBuf> buf; /* ...and the allocations behind them */
std::vector<std::vector<uint8_t>> host; /* the draw, only ever a copy source */
DevBuf scratch;
int64_t scratch_bytes = 0;
};
/* Streams die with the request, every way out of it, skips included. */
struct StreamSet {
std::vector<RadStream> s;
~StreamSet() { for (RadStream x : s) if (x) rad_stream_destroy(x); }
};
/* The RadArgs a rank's launch takes. The candidate's axes ride in `g` exactly as at issue, so the
* kernel reads `sk` with rad_args_geti() like `M`. */
void fill_args(const KernelRow& row, Rank& r, const Geometry& g, RadArgs* a) {
std::memset(a, 0, sizeof(*a));
a->t = r.t.data(); a->n_t = (int)r.t.size();
a->p = g.params(); a->n_p = g.n_params();
a->instance = r.instance;
a->rank = r.rank;
a->world_size = r.world;
if (r.scratch.p) { a->scratch = r.scratch.p; a->scratch_bytes = r.scratch_bytes; }
}
/* Every rank's stream drained. A stream's device has to be current to sync it. */
int sync_all(std::vector<Rank>& rs) {
int st = RAD_OK;
for (Rank& r : rs) {
if (!r.stream) continue;
if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE;
if (rad_stream_sync(r.stream) < 0) st = RAD_E_STATE;
}
return st;
}
/* Scratch zeroed before a candidate starts, outside the timed region: a candidate must not be
* timed -- or judged -- on the leftovers of the one before it. */
int zero_scratch(std::vector<Rank>& rs) {
for (Rank& r : rs) {
if (!r.scratch.p) continue;
if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE;
if (rad_memset_async(r.scratch.p, 0, (uint64_t)r.scratch_bytes, r.stream) < 0)
return RAD_E_STATE;
}
return RAD_OK;
}
/* `iters` launches on every rank. A collective's ranks launch from one thread each: the exchange
* pipelines only once every card has work queued. A single rank launches inline, so the timed
* region holds no thread start.
*
* A refusal is symmetric (every rank resolved the same kernel for the same geometry, and a launch
* checks only the geometry and the instance), so no rank has queued work to drain; the caller
* treats it as fatal for the candidate. */
int launch_all(const KernelRow& row, std::vector<Rank>& rs, const Geometry& g, int iters) {
auto run = [&](Rank& r) {
if (rad_dev_set(r.rank) < 0) return (int)RAD_E_DEVICE;
RadArgs a;
fill_args(row, r, g, &a);
for (int k = 0; k < iters; ++k)
if (const int s = row.info->launch(&a, r.stream); s < 0) return s;
return (int)RAD_OK;
};
if (rs.size() == 1) return run(rs[0]);
std::vector<int> st(rs.size(), (int)RAD_E_STATE);
std::vector<std::thread> th;
th.reserve(rs.size());
for (size_t i = 0; i < rs.size(); ++i) th.emplace_back([&, i] { st[i] = run(rs[i]); });
for (std::thread& t : th) t.join();
for (int s : st) if (s < 0) return s;
return RAD_OK;
}
/* Rank 0's OUT and INOUT bytes after one launch at `g`, which carries the candidate point as
* ordinary parameters. Every candidate saw the same bytes on every rank, so a variant that
* reorders a reduction, drops a peer's term, or writes the wrong slice differs from the defaults
* here. */
int capture_outputs(const KernelRow& row, std::vector<Rank>& rs, const Geometry& g,
const RadOpSchema* schema, const std::vector<OpdShape>& sh,
std::vector<uint8_t>* out) {
if (const int z = zero_scratch(rs)) return z;
const int w = launch_all(row, rs, g, 1);
if (w < 0) return w;
if (const int s = sync_all(rs)) return s;
Rank& r = rs[0];
if (rad_dev_set(r.rank) < 0) return RAD_E_DEVICE;
/* Size the destination before copying: growing it between async copies would reallocate it
* under copies still in flight. */
size_t total = 0;
for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) {
const int role = schema->operands[k].role;
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
if (!t[k].data) continue;
if (!r.t[k].data) continue;
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape));
if (bytes > 0) total += (size_t)bytes;
}
@@ -160,13 +246,14 @@ int capture_outputs(const KernelRow& row, std::vector<RadTensor>& t,
for (size_t k = 0; k < sh.size() && k < (size_t)schema->n_operands; ++k) {
const int role = schema->operands[k].role;
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
if (!t[k].data) continue;
if (!r.t[k].data) continue;
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape));
if (bytes <= 0) continue;
if (rad_memcpy_async(out->data() + at, t[k].data, bytes, stream) < 0) return RAD_E_STATE;
if (rad_memcpy_async(out->data() + at, r.t[k].data, bytes, r.stream) < 0)
return RAD_E_STATE;
at += (size_t)bytes;
}
if (stream && rad_stream_sync(stream) < 0) return RAD_E_STATE;
if (rad_stream_sync(r.stream) < 0) return RAD_E_STATE;
return RAD_OK;
}
@@ -203,43 +290,30 @@ double max_rel_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b
return worst;
}
/* Median microseconds per launch at `g` (which carries the candidate point). Negative means the
* kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid prunes only
* what the geometry alone can rule out. */
double time_point(const KernelRow& row, std::vector<RadTensor>& t,
const Geometry& g, int reps, int iters,
RadStream stream, double* spread_pct) {
RadArgs a{};
a.t = t.data(); a.n_t = (int)t.size();
a.p = g.params(); a.n_p = g.n_params();
a.rank = 0; a.world_size = 1;
/* Scratch must be device memory: e.g. a split-K GEMM writes its partial planes there. */
DevBuf scratch;
if (row.info->scratch) {
const int64_t need = row.info->scratch(&a);
if (need > 0) {
scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE);
if (!scratch.p) return (double)RAD_E_NOMEM;
rad_memset_async(scratch.p, 0, need, stream);
a.scratch = scratch.p;
a.scratch_bytes = need;
}
}
/* Median microseconds per iteration at `g` (which carries the candidate point): the wall time of
* `iters` launches on every rank, from the first launch to the last stream drained. Negative
* means the kernel refused the shape at its entry point (spec 2.1), which is allowed: tune_valid
* prunes only what the geometry alone can rule out.
*
* The clock stops only after the devices finish: launches are asynchronous, so without the sync
* this would time host submission. For a collective that is doubly true -- the exchange's cost is
* the wait for the peer, and the wait happens on the card, so a rank timed alone would report a
* local copy. */
double time_point(const KernelRow& row, std::vector<Rank>& rs, const Geometry& g,
int reps, int iters, double* spread_pct) {
if (const int z = zero_scratch(rs)) return (double)z;
/* A warm-up launch; its status decides whether this candidate serves the shape at all. */
const int s = row.info->launch(&a, stream);
if (s < 0) return (double)s;
if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE;
const int w = launch_all(row, rs, g, 1);
if (w < 0) return (double)w;
if (const int s = sync_all(rs)) return (double)s;
/* Stop the clock only after the device finishes: launches are asynchronous, so without the
* sync this would time host submission only. */
std::vector<double> us;
us.reserve((size_t)reps);
for (int r = 0; r < reps; ++r) {
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < iters; ++i)
if (row.info->launch(&a, stream) < 0) return (double)RAD_E_SHAPE;
if (stream && rad_stream_sync(stream) < 0) return (double)RAD_E_STATE;
if (const int s = launch_all(row, rs, g, iters)) return (double)s;
if (const int s = sync_all(rs)) return (double)s;
const auto t1 = std::chrono::steady_clock::now();
us.push_back(std::chrono::duration<double, std::micro>(t1 - t0).count() / iters);
}
@@ -257,7 +331,11 @@ int main(int argc, char** argv) {
std::vector<std::string> hierarchy = rad_hierarchy_from_env();
int reps = 5, iters = 32;
int64_t max_tok = 8192;
int64_t max_seqs = 256;
int tp = 1, spec = -1; /* -1 = the container's own drafter depth */
int kv_dtype = RAD_DT_INVALID; /* RAD_F8E4M3 = the engine's --kv-cache-dtype fp8 */
int wire_lossy = 0; /* the engine's --tp-wire wht6 */
int64_t wire_min_kb = 128; /* the engine's --tp-wire-min-kb */
bool dry = false, verbose = false;
for (int i = 1; i < argc; ++i) {
@@ -279,7 +357,24 @@ int main(int argc, char** argv) {
else if (a == "--reps") reps = (int)num("--reps", 1, INT32_MAX);
else if (a == "--iters") iters = (int)num("--iters", 1, INT32_MAX);
else if (a == "--max-tok") max_tok = num("--max-tok", 1, INT64_MAX);
else if (a == "--max-seqs") max_seqs = num("--max-seqs", 1, INT64_MAX);
else if (a == "--tp") tp = (int)num("--tp", 1, INT32_MAX);
else if (a == "--kv-cache-dtype") {
const char* v = next("--kv-cache-dtype");
if (!std::strcmp(v, "fp8")) kv_dtype = RAD_F8E4M3;
else if (!std::strcmp(v, "bf16")) kv_dtype = RAD_DT_INVALID;
else { std::fprintf(stderr, "rad-tune: --kv-cache-dtype: '%s' is not one of "
"bf16, fp8 (the tuner tunes the bands it declares; other "
"encodings are the engine's)\n", v); return 2; }
}
else if (a == "--tp-wire") {
const char* v = next("--tp-wire");
if (!std::strcmp(v, "wht6")) wire_lossy = 1;
else if (!std::strcmp(v, "exact")) wire_lossy = 0;
else { std::fprintf(stderr, "rad-tune: --tp-wire: '%s' is not one of exact, wht6\n",
v); return 2; }
}
else if (a == "--tp-wire-min-kb") wire_min_kb = num("--tp-wire-min-kb", 0, INT64_MAX);
else if (a == "--num-speculative-tokens") {
/* `auto` is the container's own depth, as the engine's flag of this name reads it. */
const char* v = next("--num-speculative-tokens");
@@ -332,17 +427,44 @@ int main(int argc, char** argv) {
* the speculative depth decides whether the drafter (and its shapes) is in the graph. */
RadBuildCtx ctx{};
ctx.rank = 0; ctx.world_size = tp; ctx.max_tok = max_tok;
ctx.max_seqs = max_seqs;
ctx.tp_wire_lossy = wire_lossy;
ctx.tp_wire_min_bytes = wire_min_kb * 1024;
ctx.kv_dtype = kv_dtype;
RadArchProbe probe{};
(void)rad_tools_probe(plugins, meta, &probe);
ctx.max_spec = spec >= 0 ? spec : probe.draft_depth;
ctx.max_seqs = 256; ctx.max_ctx = meta.n_ctx_train; ctx.scope = "";
ctx.max_seqs = max_seqs; ctx.max_ctx = meta.n_ctx_train; ctx.scope = "";
/* Peer access, measured before selection, as Engine does: collectives constrain device.p2p
* (abi/rad_types.h), and with the fact unset neither the peer-to-peer row nor its host-memory
* twin can match, so every collective resolves to nothing -- silently, with no tune request
* for it ever reaching the loop below. Every ordered pair is asked, since access is granted
* one way at a time. */
long long p2p = 1;
for (int i = 0; i < tp; ++i)
for (int j = 0; j < tp; ++j) {
if (i == j) continue;
const int a = rad_dev_peer_access(i, j);
if (a < 0) {
std::fprintf(stderr, "rad-tune: could not ask whether card %d can reach card %d's "
"memory: %s\n", i, j, rad_dev_last_error());
return 1;
}
if (a == 0) p2p = 0;
}
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
const char* p2p_note = p2p ? "peer to peer" : "the collectives run through pinned host memory";
/* Every rank declares concurrently on its own thread and device, as Engine does: kernel init()
* runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for
* its peers), so declaring rank 0 alone would hang. Only rank 0's program is measured. */
Program prog;
* runs from declare, and a collective's init is a rendezvous (libr4d's all-reduce waits for its
* peers), so declaring rank 0 alone would hang.
*
* All the programs stay alive, not only rank 0's. A collective's launch needs the instance each
* rank's own declare made, and an instance is reachable only through the program that declared
* it, so rank 0's program is the one measured while the others supply the peers. */
std::vector<Program> progs((size_t)tp);
{
std::vector<Program> progs((size_t)tp);
std::vector<int> st((size_t)tp, 0);
std::vector<std::thread> th;
for (int ri = 0; ri < tp; ++ri) {
@@ -362,7 +484,16 @@ int main(int argc, char** argv) {
for (auto& t : th) t.join();
if (tp > 1) rad_dev_set(0);
for (int ri = 0; ri < tp; ++ri) if (st[(size_t)ri] < 0) return 1;
prog = std::move(progs[0]);
}
Program& prog = progs[0];
/* Name what resolved to nothing, so a hole is a printed line instead of a tune request that
* never appears: the engine's declare counts the misses, and this is the count's detail. */
if (!prog.misses.empty()) {
RadDeviceProps dp{};
const bool host_backend = rad_dev_props(0, &dp) >= 0 && dp.is_host_backend;
for (const Program::Miss* m : prog.device_holes(host_backend))
std::printf(" unresolved %s\n", m->line().c_str());
}
if (machine.empty()) machine = rad_machine_key();
@@ -378,6 +509,7 @@ int main(int argc, char** argv) {
std::printf("rad-tune %s\n", model.c_str());
std::printf(" machine %s\n", machine.c_str());
if (tp > 1) std::printf(" p2p %s\n", p2p_note);
std::printf(" cache %s (%zu existing row(s))\n", src.c_str(), before);
std::printf(" requests %zu (kernel, shape) pair(s) the declared graph reaches\n\n",
prog.tune_requests.size());
@@ -393,14 +525,6 @@ int main(int argc, char** argv) {
int measured = 0, skipped = 0, single = 0;
std::map<std::string, int> skip_why;
/* One explicit stream for the run; timing on the null stream would measure host submission.
* Without ROCm the device layer is a synchronous host stub, so the same path works. */
RadStream stream = nullptr;
if (rad_stream_create(&stream, 0) < 0) {
std::fprintf(stderr, "rad-tune: could not create a stream: %s\n", rad_dev_last_error());
return 1;
}
for (const Program::TuneRequest& tr : prog.tune_requests) {
const KernelRow* row = row_for(tr.plugin, tr.kernel);
if (!row || !row->info || !row->info->launch) {
@@ -480,31 +604,114 @@ int main(int argc, char** argv) {
}
const int64_t vocab_rows = kf_vocab_rows(kop);
/* One set of device buffers shared by all candidates, so they all see the same bytes.
* `store` is the host-side draw, only ever a copy source; RadTensor::data must be the
* device allocation (a host address would fail silently). */
std::vector<std::vector<uint8_t>> store(sh.size());
std::vector<DevBuf> dev(sh.size());
std::vector<RadTensor> t(sh.size());
/* One set of operands per rank: a collective's ranks contribute their own bytes on their own
* card, with the instance their own declare made. Each rank draws different bytes, so a
* kernel that read its own contribution twice cannot pass. `rs` is sized once and never
* grown: a moved DevBuf would leave its old handle to free the buffer too. */
const int world = row->collective && tp > 1 ? tp : 1;
std::string scale;
if (world > 1) scale = ", " + std::to_string(world) + " ranks";
std::vector<Rank> rs((size_t)world);
StreamSet streams;
bool ok = true;
for (size_t k = 0; k < sh.size() && ok; ++k) {
const int64_t n = rad_numel(sh[k].shape);
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, n);
if (bytes <= 0) { ok = false; break; }
kf_draw(kop, k, M, vocab_rows, rad_case_seed(1, op, 0, row->info->domain, (int)k),
&store[k]);
dev[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE);
if (!dev[k].p) { ok = false; break; }
if (rad_memcpy_async(dev[k].p, store[k].data(), bytes, stream) < 0) { ok = false; break; }
t[k].data = dev[k].p;
t[k].dtype = sh[k].dtype;
t[k].rank = (uint32_t)sh[k].shape.size();
for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d)
t[k].shape[d] = sh[k].shape[d];
rad_tensor_pack(&t[k]);
for (int ri = 0; ri < world && ok; ++ri) {
Rank& r = rs[(size_t)ri];
r.rank = ri; r.world = world;
/* The instance is found by the key the cache uses, not by position: a rank that
* resolved a different kernel for this band has no peer to exchange with. A
* collective cannot launch without it; a plain kernel has none, and null is exactly
* what its launch expects. */
const Program::TuneRequest* q = &tr;
if (ri > 0) {
q = nullptr;
for (const auto& p : progs[(size_t)ri].tune_requests)
if (p.kernel == tr.kernel && p.plugin == tr.plugin &&
p.geom_key == tr.geom_key) { q = &p; break; }
}
if (world > 1 && (!q || !q->instance)) {
skip_why[op + " (rank " + std::to_string(ri) + " declared no instance for this "
"instantiation: no exchange to launch)"]++;
++skipped; ok = false; break;
}
r.instance = q ? q->instance : nullptr;
if (rad_dev_set(ri) < 0) {
skip_why[op + " (no device to put rank " + std::to_string(ri) + " on)"]++;
++skipped; ok = false; break;
}
/* An explicit stream per rank; timing on the null stream would measure host
* submission. Without ROCm the device layer is a synchronous host stub, and the
* same path still works. */
RadStream s = nullptr;
if (rad_stream_create(&s, 0) < 0) {
std::fprintf(stderr, "rad-tune: could not create a stream for rank %d: %s\n", ri,
rad_dev_last_error());
return 1;
}
streams.s.push_back(s);
r.stream = s;
/* Inputs come from kf_draw, the same draw rad-kbench checks with, so each operand
* stays in the domain its recipe states (constant `seqused`, cumulative lengths,
* distinct scatter destinations, in-range block tables). */
r.host.resize(sh.size());
r.buf = std::vector<DevBuf>(sh.size());
r.t = std::vector<RadTensor>(sh.size());
for (size_t k = 0; k < sh.size(); ++k) {
/* An absent operand (attn's descales and cu_seqlens) is a zeroed tensor: no
* draw, no allocation, data null -- what kbench passes and the kernel checks. */
if (sh[k].absent) continue;
const int64_t bytes = rad_dtype_bytes(sh[k].dtype, rad_numel(sh[k].shape));
if (bytes <= 0) {
skip_why[op + " (an operand has a plugin-private dtype the core cannot "
"size)"]++;
++skipped; ok = false; break;
}
kf_draw(kop, k, M, vocab_rows,
rad_case_seed(1, op, ri, row->info->domain, (int)k), &r.host[k]);
r.buf[k].p = rad_dev_alloc(bytes, RAD_MEM_DEVICE);
if (!r.buf[k].p) {
skip_why[op + " (no device memory for an operand on rank " +
std::to_string(ri) + ")"]++;
++skipped; ok = false; break;
}
if (rad_memcpy_async(r.buf[k].p, r.host[k].data(), bytes, r.stream) < 0) {
skip_why[op + " (the operands would not copy onto rank " +
std::to_string(ri) + ")"]++;
++skipped; ok = false; break;
}
/* RadTensor::data must be the device allocation; a host address fails silently. */
RadTensor& t = r.t[k];
t = RadTensor{};
t.data = r.buf[k].p;
t.dtype = sh[k].dtype;
t.rank = (uint32_t)sh[k].shape.size();
for (size_t d = 0; d < sh[k].shape.size() && d < RAD_MAX_RANK; ++d)
t.shape[d] = sh[k].shape[d];
rad_tensor_pack(&t);
}
}
if (!ok) { skip_why[op + " (an operand has a plugin-private dtype the core cannot "
"size)"]++; ++skipped; continue; }
/* Scratch sized from each rank's own arguments: a split kernel writes its partials to
* device memory, and every card needs its own. */
if (ok && row->info->scratch) {
for (Rank& r : rs) {
if (rad_dev_set(r.rank) < 0) {
skip_why[op + " (no device to size scratch on for rank " +
std::to_string(r.rank) + ")"]++;
++skipped; ok = false; break;
}
RadArgs a;
fill_args(*row, r, tr.geom, &a);
const int64_t need = row->info->scratch(&a);
if (need <= 0) continue;
r.scratch.p = rad_dev_alloc(need, RAD_MEM_DEVICE);
if (!r.scratch.p) {
skip_why[op + " (no device memory for the scratch it asks for)"]++;
++skipped; ok = false; break;
}
r.scratch_bytes = need;
}
}
if (!ok) continue; /* the reason is already counted */
if (world > 1) rad_dev_set(0);
/* One geometry per candidate, built up front. As at issue, the chosen values are appended
* to the resolved geometry, so a launch reads `sk` via rad_args_geti() like `M`. */
@@ -518,7 +725,7 @@ int main(int argc, char** argv) {
std::vector<double> best_us((size_t)n_var, -1.0), spread((size_t)n_var, 0.0);
for (int v = 0; v < n_var; ++v) {
double sp = 0;
best_us[(size_t)v] = time_point(*row, t, gv[(size_t)v], reps, iters, stream, &sp);
best_us[(size_t)v] = time_point(*row, rs, gv[(size_t)v], reps, iters, &sp);
spread[(size_t)v] = sp;
}
@@ -530,7 +737,7 @@ int main(int argc, char** argv) {
* kVariantTol allows the last-bit changes of a reordered reduction. */
std::vector<uint8_t> ref;
std::vector<double> verr((size_t)n_var, 0.0);
if (best_us[0] <= 0 || capture_outputs(*row, t, gv[0], schema, sh, stream, &ref) < 0) {
if (best_us[0] <= 0 || capture_outputs(*row, rs, gv[0], schema, sh, &ref) < 0) {
skip_why[tr.plugin + "/" + tr.kernel + " (the defaults refused the shape: no "
"reference to check candidates against)"]++;
++skipped;
@@ -539,7 +746,7 @@ int main(int argc, char** argv) {
for (int v = 1; v < n_var; ++v) {
if (best_us[(size_t)v] <= 0) continue;
std::vector<uint8_t> got;
if (capture_outputs(*row, t, gv[(size_t)v], schema, sh, stream, &got) < 0) {
if (capture_outputs(*row, rs, gv[(size_t)v], schema, sh, &got) < 0) {
best_us[(size_t)v] = (double)RAD_E_STATE;
continue;
}
@@ -589,8 +796,9 @@ int main(int argc, char** argv) {
cache.put(tr_out);
++measured;
std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld)\n", op.c_str(),
tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space);
std::printf(" %-22s %-46s %-28s %9.3f us (%d of %lld%s)\n", op.c_str(),
tr.geom.str().c_str(), wname.c_str(), tr_out.us, n_var, (long long)space,
scale.c_str());
}
if (dry) {
@@ -607,8 +815,6 @@ int main(int argc, char** argv) {
std::printf("\n%d request(s) had one point or none: nothing to choose, and the kernel's\n"
"own axis defaults are already what it runs.\n", single);
rad_stream_destroy(stream);
cache.set_machine(machine);
if (cache.save(save_home) < 0) return 1;